Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3d6ef5c7b4 | ||
|
|
78a4ce009c | ||
|
|
7ccab6fbc4 |
No files matched your search
@@ -0,0 +1,18 @@
|
|||||||
|
---
|
||||||
|
description: Keep led-driver and led-tool git submodules in sync when updating led-controller
|
||||||
|
alwaysApply: true
|
||||||
|
---
|
||||||
|
|
||||||
|
# Submodule pointers (`led-driver`, `led-tool`)
|
||||||
|
|
||||||
|
This repo tracks **`led-driver`** and **`led-tool`** as git submodules (see `.gitmodules`).
|
||||||
|
|
||||||
|
When you **update led-controller** work that should ship with matching firmware or CLI behaviour—or when you finish changes **inside** those submodule directories—**record the new submodule commits in the parent repo**:
|
||||||
|
|
||||||
|
1. In each submodule, commit and push on its remote if there are local commits (or ensure the checkout is the intended revision).
|
||||||
|
2. From the **led-controller** root: `git add led-driver led-tool` after their HEADs point at the right commits.
|
||||||
|
3. Include the parent-repo commit that bumps the gitlinks (so CI and clones get consistent trees).
|
||||||
|
|
||||||
|
**Do not** leave submodule directories dirty or forgotten while presenting the parent repo as “done”: either commit the submodule pointer update in led-controller, or leave an explicit note if the user must push submodule remotes first.
|
||||||
|
|
||||||
|
If the user only asked for a submodule bump with no code edits, a single `chore(submodules): bump led-driver and led-tool` style commit is appropriate (see commit rule).
|
||||||
@@ -28,6 +28,7 @@ Thumbs.db
|
|||||||
scripts/.led-controller-venv
|
scripts/.led-controller-venv
|
||||||
docs/.help-print.html
|
docs/.help-print.html
|
||||||
settings.json
|
settings.json
|
||||||
|
db/
|
||||||
*.log
|
*.log
|
||||||
*.db
|
*.db
|
||||||
*.sqlite
|
*.sqlite
|
||||||
|
|||||||
@@ -22,9 +22,11 @@ pytest = "*"
|
|||||||
python_version = "3.11"
|
python_version = "3.11"
|
||||||
|
|
||||||
[scripts]
|
[scripts]
|
||||||
web = "python /home/pi/led-controller/tests/web.py"
|
web = "python tests/web.py"
|
||||||
watch = "python -m watchfiles 'python tests/web.py' src tests"
|
watch = "python -m watchfiles \"python tests/web.py\" src tests"
|
||||||
install = "pipenv install"
|
|
||||||
run = "sh -c 'cd src && python main.py'"
|
run = "sh -c 'cd src && python main.py'"
|
||||||
dev = "watchfiles \"sh -c 'cd src && python main.py'\" src"
|
dev = "python -m watchfiles \"sh -c 'cd src && python main.py'\" src"
|
||||||
help-pdf = "sh scripts/build_help_pdf.sh"
|
test = "python -m pytest"
|
||||||
|
test-browser = "sh -c 'python tests/web.py > /tmp/led-controller-web.log 2>&1 & pid=$!; trap \"kill $pid\" EXIT; sleep 2; LED_CONTROLLER_RUN_BROWSER_TESTS=1 LED_CONTROLLER_DEVICE_IP=http://127.0.0.1:5000 python -m pytest tests/test_browser.py'"
|
||||||
|
test-browser-device = "sh -c 'LED_CONTROLLER_RUN_BROWSER_TESTS=1 python -m pytest tests/test_browser.py'"
|
||||||
|
|
||||||
@@ -41,21 +41,3 @@ LED controller web app for managing profiles, **zones**, presets, and colour pal
|
|||||||
## Driver pattern modules
|
## Driver pattern modules
|
||||||
|
|
||||||
Pattern **`.py`** sources live under **`led-driver/src/patterns`**. The Pi app resolves that path via `util.driver_patterns.driver_patterns_dir()`. If you deploy without that tree next to the app, set **`LED_CONTROLLER_PATTERNS_DIR`** to the directory that contains those files.
|
Pattern **`.py`** sources live under **`led-driver/src/patterns`**. The Pi app resolves that path via `util.driver_patterns.driver_patterns_dir()`. If you deploy without that tree next to the app, set **`LED_CONTROLLER_PATTERNS_DIR`** to the directory that contains those files.
|
||||||
|
|
||||||
## Animation engine (Pi-side)
|
|
||||||
|
|
||||||
`src/engine/` lets the Pi drive LEDs itself, in addition to the ESP32 drivers:
|
|
||||||
|
|
||||||
- **Pixel generator**: runs the **unchanged** `led-driver/src/patterns/*.py` under CPython (a `utime` shim plus a NeoPixel-like buffer) with the same preset JSON the drivers get, and streams each frame to **pixel outputs**: DDP, Art-Net, sACN (E1.31), or USB-DMX (Enttec Pro / Open DMX). Configure outputs in **Outputs** (edit mode) and add an output's name to a zone's devices.
|
|
||||||
- **Preset sequencer**: **Sequences** play timed chains of presets on a zone, switching both the pixel outputs and the zone's ESP32 drivers. Sequences resume after a restart.
|
|
||||||
- ESP32 firmware is unchanged; drivers still get presets + `select`.
|
|
||||||
|
|
||||||
CLI (run from `src/`):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python -m engine.cli --output "ddp://192.168.1.60?pixels=300" --test
|
|
||||||
python -m engine.cli --output "artnet://192.168.1.61?universe=0&pixels=170" --preset 16
|
|
||||||
python -m engine.cli --pattern rainbow --n1 2 --leds 60 # terminal preview
|
|
||||||
```
|
|
||||||
|
|
||||||
Tests: `pipenv run pytest tests/engine_tests`.
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
{"188b0e1560a8": {"id": "188b0e1560a8", "name": "led-188b0e1560a8", "type": "led", "transport": "wifi", "address": "10.1.1.192", "default_pattern": null, "zones": []}, "f0f5bdfb9d30": {"id": "f0f5bdfb9d30", "name": "led-f0f5bdfb9d30", "type": "led", "transport": "wifi", "address": "10.1.1.232", "default_pattern": null, "zones": []}}
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
{}
|
|
||||||
+1
-1
@@ -1 +1 @@
|
|||||||
{"on": {"min_delay": 10, "max_delay": 10000, "max_colors": 1}, "off": {"min_delay": 10, "max_delay": 10000, "max_colors": 0}, "rainbow": {"n1": "Step Rate", "min_delay": 10, "max_delay": 10000, "max_colors": 0}, "colour_cycle": {"n1": "Step Rate", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "transition": {"min_delay": 10, "max_delay": 10000, "max_colors": 10}, "chase": {"n1": "Colour 1 Length", "n2": "Colour 2 Length", "n3": "Step 1", "n4": "Step 2", "min_delay": 10, "max_delay": 10000, "max_colors": 2}, "pulse": {"n1": "Attack", "n2": "Hold", "n3": "Decay", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "circle": {"n1": "Head Rate", "n2": "Max Length", "n3": "Tail Rate", "n4": "Min Length", "min_delay": 10, "max_delay": 10000, "max_colors": 2}, "blink": {"min_delay": 10, "max_delay": 10000, "max_colors": 10}, "flicker": {"n1": "Min brightness", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "flame": {"n1": "Min brightness", "n2": "Breath period (ms)", "n3": "Spark gap min (ms, 0=default 10\u201330 s, -1=off)", "n4": "Spark gap max (ms)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "twinkle": {"n1": "Twinkle activity (1\u2013255, higher = more changes)", "n2": "Density (0\u2013255, higher = more of the strip lit)", "n3": "Min adjacent LEDs per twinkle (same as max for fixed length)", "n4": "Max adjacent LEDs per twinkle (same as min for fixed length)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "radiate": {"n1": "Node spacing (LEDs)", "n2": "Out time (ms)", "n3": "In time (ms)", "min_delay": 10, "max_delay": 10000, "max_colors": 2}, "meteor_rain": {"n1": "Tail length", "n2": "Speed (LEDs per frame)", "n3": "Fade amount (1-255)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "scanner": {"n1": "Eye width", "n2": "End pause (frames)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "gradient_scroll": {"n1": "Scroll step rate", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "comet_dual": {"n1": "Tail length", "n2": "Speed", "n3": "Gap", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "sparkle_trail": {"n1": "Spark density", "n2": "Decay", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "wave": {"n1": "Wavelength", "n2": "Amplitude", "n3": "Drift speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "plasma": {"n1": "Scale", "n2": "Speed", "n3": "Contrast", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "segment_chase": {"n1": "Segment size", "n2": "Phase step", "n3": "Segment phase offset", "n4": "Gap per segment", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "bar_graph": {"n1": "Level percent", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "breathing_dual": {"n1": "Phase offset", "n2": "Ease", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "strobe_burst": {"n1": "Burst count", "n2": "Burst gap", "n3": "Cooldown", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "rain_drops": {"n1": "Drop rate", "n2": "Ripple width", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "fireflies": {"n1": "Count", "n2": "Twinkle speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "clock_sweep": {"n1": "Hand width", "n2": "Marker interval", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "marquee": {"n1": "On length", "n2": "Off length", "n3": "Step", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "aurora": {"n1": "Band count", "n2": "Shimmer", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "snowfall": {"n1": "Flake density", "n2": "Fall speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "heartbeat": {"n1": "Pulse 1 ms", "n2": "Pulse 2 ms", "n3": "Pause ms", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "orbit": {"n1": "Orbit count", "n2": "Base speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "palette_morph": {"n1": "Morph ms", "n2": "Warp rate", "n3": "Turbulence", "max_colors": 10, "min_delay": 10, "max_delay": 10000}}
|
{"on": {"min_delay": 10, "max_delay": 10000, "max_colors": 1}, "off": {"min_delay": 10, "max_delay": 10000, "max_colors": 0}, "rainbow": {"n1": "Step Rate", "min_delay": 10, "max_delay": 10000, "max_colors": 0}, "colour_cycle": {"n1": "Step Rate", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "transition": {"min_delay": 10, "max_delay": 10000, "max_colors": 10}, "chase": {"n1": "Colour 1 Length", "n2": "Colour 2 Length", "n3": "Step 1", "n4": "Step 2", "min_delay": 10, "max_delay": 10000, "max_colors": 2, "has_background": true}, "pulse": {"n1": "Attack", "n2": "Hold", "n3": "Decay", "min_delay": 10, "max_delay": 10000, "max_colors": 10, "has_background": true}, "circle": {"n1": "Head Rate", "n2": "Max Length", "n3": "Tail Rate", "n4": "Min Length", "min_delay": 10, "max_delay": 10000, "max_colors": 2, "has_background": true}, "blink": {"min_delay": 10, "max_delay": 10000, "max_colors": 10, "has_background": true}, "flicker": {"n1": "Min brightness", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "flame": {"n1": "Min brightness", "n2": "Breath period (ms)", "n3": "Spark gap min (ms, 0=default 10–30 s, -1=off)", "n4": "Spark gap max (ms)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "twinkle": {"n1": "Twinkle activity (1–255, higher = more changes)", "n2": "Density (0–255, higher = more of the strip lit)", "n3": "Min adjacent LEDs per twinkle (same as max for fixed length)", "n4": "Max adjacent LEDs per twinkle (same as min for fixed length)", "min_delay": 10, "max_delay": 10000, "max_colors": 10, "has_background": true}, "radiate": {"n1": "Node spacing (LEDs)", "n2": "Out time (ms)", "n3": "In time (ms)", "min_delay": 10, "max_delay": 10000, "max_colors": 2, "has_background": true}, "meteor_rain": {"n1": "Tail length", "n2": "Speed (LEDs per frame)", "n3": "Fade amount (1-255)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "scanner": {"n1": "Eye width", "n2": "End pause (frames)", "min_delay": 10, "max_delay": 10000, "max_colors": 10, "has_background": true}, "gradient_scroll": {"n1": "Scroll step rate", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "comet_dual": {"n1": "Tail length", "n2": "Speed", "n3": "Gap", "max_colors": 10, "min_delay": 10, "max_delay": 10000, "has_background": true}, "sparkle_trail": {"n1": "Spark density", "n2": "Decay", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "wave": {"n1": "Wavelength", "n2": "Amplitude", "n3": "Drift speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "plasma": {"n1": "Scale", "n2": "Speed", "n3": "Contrast", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "segment_chase": {"n1": "Segment size", "n2": "Phase step", "n3": "Segment phase offset", "n4": "Gap per segment", "max_colors": 10, "min_delay": 10, "max_delay": 10000, "has_background": true}, "bar_graph": {"n1": "Level percent", "max_colors": 10, "min_delay": 10, "max_delay": 10000, "has_background": true}, "breathing_dual": {"n1": "Phase offset", "n2": "Ease", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "strobe_burst": {"n1": "Burst count", "n2": "Burst gap", "n3": "Cooldown", "max_colors": 10, "min_delay": 10, "max_delay": 10000, "has_background": true}, "rain_drops": {"n1": "Drop rate", "n2": "Ripple width", "max_colors": 10, "min_delay": 10, "max_delay": 10000, "has_background": true}, "fireflies": {"n1": "Count", "n2": "Twinkle speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000, "has_background": true}, "clock_sweep": {"n1": "Hand width", "n2": "Marker interval", "max_colors": 10, "min_delay": 10, "max_delay": 10000, "has_background": true}, "marquee": {"n1": "On length", "n2": "Off length", "n3": "Step", "max_colors": 10, "min_delay": 10, "max_delay": 10000, "has_background": true}, "aurora": {"n1": "Band count", "n2": "Shimmer", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "snowfall": {"n1": "Flake density", "n2": "Fall speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000, "has_background": true}, "heartbeat": {"n1": "Pulse 1 ms", "n2": "Pulse 2 ms", "n3": "Pause ms", "max_colors": 10, "min_delay": 10, "max_delay": 10000, "has_background": true}, "orbit": {"n1": "Orbit count", "n2": "Base speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000, "has_background": true}, "palette_morph": {"n1": "Morph ms", "n2": "Warp rate", "n3": "Turbulence", "max_colors": 10, "min_delay": 10, "max_delay": 10000}}
|
||||||
+1
-1
@@ -1 +1 @@
|
|||||||
{"1": {"name": "on", "pattern": "on", "colors": ["#FFFFFF"], "brightness": 255, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "2": {"name": "off", "pattern": "off", "colors": [], "brightness": 0, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "3": {"name": "rainbow", "pattern": "rainbow", "colors": [], "brightness": 255, "delay": 100, "auto": true, "n1": 2, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "4": {"name": "transition", "pattern": "transition", "colors": ["#FF0000", "#00FF00", "#0000FF", "#FFFFFF", "#0000FF", "#FFFF00"], "brightness": 255, "delay": 5000, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null, null, 6, 2, 3]}, "5": {"name": "chase", "pattern": "chase", "colors": ["#FF0000", "#0000FF"], "brightness": 255, "delay": 200, "auto": true, "n1": 5, "n2": 5, "n3": 1, "n4": 1, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "6": {"name": "pulse", "pattern": "pulse", "colors": ["#00FF00"], "brightness": 255, "delay": 500, "auto": true, "n1": 1000, "n2": 500, "n3": 1000, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "7": {"name": "circle", "pattern": "circle", "colors": ["#FFA500", "#800080"], "brightness": 255, "delay": 200, "auto": true, "n1": 2, "n2": 10, "n3": 2, "n4": 5, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "8": {"name": "blink", "pattern": "blink", "colors": ["#FF0000", "#00FF00", "#0000FF", "#FFFF00"], "brightness": 255, "delay": 1000, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "9": {"name": "warm white", "pattern": "on", "colors": ["#FFF5E6"], "brightness": 200, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "10": {"name": "cool white", "pattern": "on", "colors": ["#E6F2FF"], "brightness": 200, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "11": {"name": "red", "pattern": "on", "colors": ["#FF0000"], "brightness": 255, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "12": {"name": "blue", "pattern": "on", "colors": ["#0000FF"], "brightness": 255, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "13": {"name": "rainbow slow", "pattern": "rainbow", "colors": [], "brightness": 255, "delay": 150, "auto": true, "n1": 1, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "14": {"name": "pulse slow", "pattern": "pulse", "colors": ["#FF6600"], "brightness": 255, "delay": 800, "auto": true, "n1": 2000, "n2": 1000, "n3": 2000, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "15": {"name": "blink red green", "pattern": "blink", "colors": ["#FF0000", "#00FF00"], "brightness": 255, "delay": 500, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "30": {"name": "rainbow slow", "pattern": "rainbow", "colors": [], "brightness": 255, "delay": 150, "auto": true, "n1": 1, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "31": {"name": "DJ Rainbow", "pattern": "rainbow", "colors": [], "brightness": 220, "delay": 60, "n1": 12, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "32": {"name": "DJ Single Color", "pattern": "on", "colors": ["#ff00ff"], "brightness": 220, "delay": 100, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "33": {"name": "DJ Transition", "pattern": "transition", "colors": ["#ff0000", "#00ff00", "#0000ff"], "brightness": 220, "delay": 250, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "34": {"name": "DJ Rainbow", "pattern": "rainbow", "colors": [], "brightness": 220, "delay": 60, "n1": 12, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "35": {"name": "DJ Single Color", "pattern": "on", "colors": ["#ff00ff"], "brightness": 220, "delay": 100, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "36": {"name": "DJ Transition", "pattern": "transition", "colors": ["#ff0000", "#00ff00", "#0000ff"], "brightness": 220, "delay": 250, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "37": {"name": "tranistion2", "pattern": "transition", "colors": ["#FF0000", "#FFFF00", "#FF00FF"], "brightness": 128, "delay": 1000, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [0, 3, 4]}, "38": {"name": "Colour Cycle", "pattern": "cLine truncated
|
{"1": {"name": "on", "pattern": "on", "colors": ["#FFFFFF"], "brightness": 255, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "2": {"name": "off", "pattern": "off", "colors": [], "brightness": 0, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "3": {"name": "rainbow", "pattern": "rainbow", "colors": [], "brightness": 255, "delay": 100, "auto": true, "n1": 2, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "4": {"name": "transition", "pattern": "transition", "colors": ["#FF0000", "#00FF00", "#0000FF", "#FFFFFF", "#0000FF", "#FFFF00"], "brightness": 255, "delay": 5000, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null, null, 6, 2, 3]}, "5": {"name": "chase", "pattern": "chase", "colors": ["#FF0000", "#0000FF"], "brightness": 255, "delay": 200, "auto": true, "n1": 5, "n2": 5, "n3": 1, "n4": 1, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "6": {"name": "pulse", "pattern": "pulse", "colors": ["#00FF00"], "brightness": 255, "delay": 500, "auto": true, "n1": 1000, "n2": 500, "n3": 1000, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "7": {"name": "circle", "pattern": "circle", "colors": ["#FFA500", "#800080"], "brightness": 255, "delay": 200, "auto": true, "n1": 2, "n2": 10, "n3": 2, "n4": 5, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "8": {"name": "blink", "pattern": "blink", "colors": ["#FF0000", "#00FF00", "#0000FF", "#FFFF00"], "brightness": 255, "delay": 1000, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "9": {"name": "warm white", "pattern": "on", "colors": ["#FFF5E6"], "brightness": 200, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "10": {"name": "cool white", "pattern": "on", "colors": ["#E6F2FF"], "brightness": 200, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "11": {"name": "red", "pattern": "on", "colors": ["#FF0000"], "brightness": 255, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "12": {"name": "blue", "pattern": "on", "colors": ["#0000FF"], "brightness": 255, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "13": {"name": "rainbow slow", "pattern": "rainbow", "colors": [], "brightness": 255, "delay": 150, "auto": true, "n1": 1, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "14": {"name": "pulse slow", "pattern": "pulse", "colors": ["#FF6600"], "brightness": 255, "delay": 800, "auto": true, "n1": 2000, "n2": 1000, "n3": 2000, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "15": {"name": "blink red green", "pattern": "blink", "colors": ["#FF0000", "#00FF00"], "brightness": 255, "delay": 500, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "30": {"name": "rainbow slow", "pattern": "rainbow", "colors": [], "brightness": 255, "delay": 150, "auto": true, "n1": 1, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "31": {"name": "DJ Rainbow", "pattern": "rainbow", "colors": [], "brightness": 220, "delay": 60, "n1": 12, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "32": {"name": "DJ Single Color", "pattern": "on", "colors": ["#ff00ff"], "brightness": 220, "delay": 100, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "33": {"name": "DJ Transition", "pattern": "transition", "colors": ["#ff0000", "#00ff00", "#0000ff"], "brightness": 220, "delay": 250, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "34": {"name": "DJ Rainbow", "pattern": "rainbow", "colors": [], "brightness": 220, "delay": 60, "n1": 12, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "35": {"name": "DJ Single Color", "pattern": "on", "colors": ["#ff00ff"], "brightness": 220, "delay": 100, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "36": {"name": "DJ Transition", "pattern": "transition", "colors": ["#ff0000", "#00ff00", "#0000ff"], "brightness": 220, "delay": 250, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "37": {"name": "tranistion2", "pattern": "transition", "colors": ["#FF0000", "#FFFF00", "#FF00FF"], "brightness": 128, "delay": 1000, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [0, 3, 4]}, "38": {"name": "Colour Cycle", "pattern": "cLine truncated
|
||||||
+1
-1
@@ -1 +1 @@
|
|||||||
{"1": {"name": "Main Group", "zone_id": null, "loop": true, "repeat_count": 0, "steps": [{"preset_id": "1", "duration_s": 3.0}, {"preset_id": "2", "duration_s": 3.0}], "active": false}, "2": {"name": "Accent Group", "zone_id": null, "loop": true, "repeat_count": 0, "steps": [{"preset_id": "2", "duration_s": 2.0}, {"preset_id": "3", "duration_s": 2.0}], "active": false}}
|
{"1": {"group_name": "Main Group", "presets": ["1", "2"], "sequence_duration": 3000, "sequence_transition": 500, "sequence_loop": true, "sequence_repeat_count": 0, "sequence_active": false, "sequence_index": 0, "sequence_start_time": 0}, "2": {"group_name": "Accent Group", "presets": ["2", "3"], "sequence_duration": 2000, "sequence_transition": 300, "sequence_loop": true, "sequence_repeat_count": 0, "sequence_active": false, "sequence_index": 0, "sequence_start_time": 0}}
|
||||||
@@ -1 +0,0 @@
|
|||||||
{"1": {"name": "default", "names": ["led-188b0e1560a8", "led-f0f5bdfb9d30"], "presets": [["4", "2", "7"], ["3", "14", "5"], ["8", "9", "1"], ["6", "38", "42"], ["39", "40", "41"], ["43", "44", "45"], ["46", "47", "48"], ["49", "50", "51"], ["52", "53", "54"], ["55", "56", "57"], ["58", "59", "60"], ["61", "62"]], "presets_flat": ["4", "2", "7", "3", "14", "5", "8", "9", "1", "6", "38", "42", "39", "40", "41", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62"], "default_preset": "41"}, "2": {"name": "default", "names": ["1", "2", "3", "4", "5", "6", "7", "8", "0", "a"], "presets": [["16", "17", "18"], ["19", "20", "21"], ["22", "23", "24"], ["25", "26", "27"], ["28", "29", "30"]], "presets_flat": ["16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30"]}, "3": {"name": "default", "names": ["1"], "presets": [], "default_preset": null}, "4": {"name": "default", "names": ["1"], "presets": [], "default_preset": null}, "5": {"name": "dj", "names": ["dj"], "presets": [["31", "32", "33"]], "default_preset": "31", "presets_flat": ["31", "32", "33"]}, "6": {"name": "default", "names": ["1"], "presets": [], "default_preset": null, "presets_flat": []}, "7": {"name": "dj", "names": ["dj"], "presets": [["34", "35", "36"]], "default_preset": "34", "presets_flat": ["34", "35", "36"]}, "8": {"name": "test", "names": ["led-188b0e1560a8"], "presets": [["1", "2", "3"], ["4", "5"]], "default_preset": "1", "presets_flat": ["1", "2", "3", "4", "5"]}}
|
|
||||||
+3
-51
@@ -159,9 +159,6 @@ Stored preset records can include:
|
|||||||
| DELETE | `/zones/<id>` | Delete zone; can delete `current` to remove the active zone; updates profile zone list. |
|
| DELETE | `/zones/<id>` | Delete zone; can delete `current` to remove the active zone; updates profile zone list. |
|
||||||
| POST | `/zones/<id>/set-current` | Sets `current_zone` cookie. |
|
| POST | `/zones/<id>/set-current` | Sets `current_zone` cookie. |
|
||||||
| POST | `/zones/<id>/clone` | Clone zone into current profile. |
|
| POST | `/zones/<id>/clone` | Clone zone into current profile. |
|
||||||
| POST | `/zones/<id>/play` | Body **`{"preset_id": "16", "drivers": true}`**. Runs the preset on every target in the zone through the Pi engine: pixel **outputs** are rendered on the Pi, ESP32 drivers get the preset + `select` (skipped when **`drivers`** is `false`; the UI sends to drivers itself and passes `false`). Stops any sequence on the zone. Returns the zone's player status. |
|
|
||||||
| POST | `/zones/<id>/stop` | Stops the zone's sequence and Pi rendering (pixel outputs go black). ESP32 drivers keep their current preset. |
|
|
||||||
| GET | `/zones/engine/status` | Engine state: `zones` (per-zone player: preset, pattern, error, per-output frame/packet/error counters) and `sequences`. |
|
|
||||||
|
|
||||||
### Palettes — `/palettes`
|
### Palettes — `/palettes`
|
||||||
|
|
||||||
@@ -193,60 +190,15 @@ Stored preset records can include:
|
|||||||
| PUT | `/scenes/<id>` | Update. |
|
| PUT | `/scenes/<id>` | Update. |
|
||||||
| DELETE | `/scenes/<id>` | Delete. |
|
| DELETE | `/scenes/<id>` | Delete. |
|
||||||
|
|
||||||
### Scene playback
|
|
||||||
|
|
||||||
| Method | Path | Description |
|
|
||||||
|--------|------|-------------|
|
|
||||||
| POST | `/scenes/<id>/play` | Starts every sequence listed in the scene's `sequences`. Returns `started` ids and per-sequence `errors`. |
|
|
||||||
| POST | `/scenes/<id>/stop` | Stops the scene's sequences. |
|
|
||||||
|
|
||||||
### Sequences — `/sequences`
|
### Sequences — `/sequences`
|
||||||
|
|
||||||
Timed preset chains for one zone, run by the Pi engine (hard cuts). Stored in **`db/sequence.json`**:
|
|
||||||
|
|
||||||
```json
|
|
||||||
{"name": "Showcase", "zone_id": "2", "loop": true, "repeat_count": 0,
|
|
||||||
"steps": [{"preset_id": "16", "duration_s": 8}, {"preset_id": "17", "duration_s": 8}],
|
|
||||||
"active": false}
|
|
||||||
```
|
|
||||||
|
|
||||||
`duration_s` is clamped to 0.5–600 (default 5). `repeat_count` counts passes when `loop` is true (0 = forever). `active` is maintained by the engine; active sequences resume after a restart. Legacy records (`group_name`, `presets`, `sequence_duration` in ms) are migrated on load.
|
|
||||||
|
|
||||||
| Method | Path | Description |
|
| Method | Path | Description |
|
||||||
|--------|------|-------------|
|
|--------|------|-------------|
|
||||||
| GET | `/sequences` | All sequences. |
|
| GET | `/sequences` | All sequences. |
|
||||||
| GET | `/sequences/status` | Runtime state per sequence: `zone_id`, `step_index`, `preset_id`, `pass`, `next_at`, `running`, optional `error`. |
|
|
||||||
| GET | `/sequences/<id>` | One sequence. |
|
| GET | `/sequences/<id>` | One sequence. |
|
||||||
| POST | `/sequences` | Create (body as above). 400 on invalid steps. |
|
| POST | `/sequences` | Create; may use `group_name`, `presets` in body. |
|
||||||
| PUT | `/sequences/<id>` | Update (merged, then re-validated). |
|
| PUT | `/sequences/<id>` | Update. |
|
||||||
| DELETE | `/sequences/<id>` | Stop if running, then delete. |
|
| DELETE | `/sequences/<id>` | Delete. |
|
||||||
| POST | `/sequences/<id>/play` | Start on its zone; replaces a sequence already running there. 400 without `zone_id`/steps. |
|
|
||||||
| POST | `/sequences/<id>/stop` | Stop; the zone keeps its current preset. |
|
|
||||||
|
|
||||||
Picking a preset manually on a zone (`/zones/<id>/play`) stops that zone's sequence.
|
|
||||||
|
|
||||||
### Outputs — `/outputs`
|
|
||||||
|
|
||||||
Pixel outputs the Pi renders frames for, stored in **`db/output.json`**. A zone drives an output when the output's **`name`** appears in the zone's `names` (the same list that holds ESP32 device names).
|
|
||||||
|
|
||||||
| Field | Notes |
|
|
||||||
|-------|-------|
|
|
||||||
| `name` | Matched against zone `names`. |
|
|
||||||
| `protocol` | `ddp` (UDP 4048), `artnet` (ArtDMX, UDP 6454), `sacn` (E1.31, UDP 5568), `dmx_serial` (USB-DMX). |
|
|
||||||
| `host`, `port` | Network outputs. `ddp` needs a host; Art-Net without host broadcasts; sACN without host uses multicast `239.255.<hi>.<lo>`. Blank port = protocol default. |
|
|
||||||
| `universe` | Art-Net/sACN start universe (sACN 1–63999). 170 RGB pixels per universe; consecutive universes are used for longer strips. |
|
|
||||||
| `serial_port`, `dmx_mode`, `channel` | USB-DMX: `enttec_pro` (Enttec DMX USB Pro) or `open_dmx` (FTDI); start channel 1–512; one universe max. |
|
|
||||||
| `pixel_count`, `pixel_offset` | Pixels this output takes from the zone frame, starting at `pixel_offset`. Outputs at offset 0 mirror the frame start. |
|
|
||||||
| `color_order`, `reverse`, `brightness`, `fps`, `enabled` | Per-output wiring order, direction, 0–255 brightness (× global brightness), frame-rate cap (default 40). |
|
|
||||||
|
|
||||||
| Method | Path | Description |
|
|
||||||
|--------|------|-------------|
|
|
||||||
| GET | `/outputs` | All outputs. |
|
|
||||||
| GET | `/outputs/<id>` | One output. |
|
|
||||||
| POST | `/outputs` | Create; 400 with `error` on validation failure. |
|
|
||||||
| PUT | `/outputs/<id>` | Update. |
|
|
||||||
| DELETE | `/outputs/<id>` | Delete. |
|
|
||||||
| POST | `/outputs/<id>/test` | Sends red, green, blue, white (optional body `step_s`, default 1 s each) then black. Returns per-output counters. |
|
|
||||||
|
|
||||||
### Patterns — `/patterns`
|
### Patterns — `/patterns`
|
||||||
|
|
||||||
|
|||||||
+1
-1
Submodule led-driver updated: 2fcaf2f064...fbebe9f4f9.
+1
-1
Submodule led-simulator updated: 7ce56b64df...42c14361e8.
+1
-1
Submodule led-tool updated: d6331a105c...580fd11aca.
+1
-1
@@ -1,3 +1,3 @@
|
|||||||
[tool.pytest.ini_options]
|
[tool.pytest.ini_options]
|
||||||
testpaths = ["tests"]
|
testpaths = ["tests"]
|
||||||
python_files = ["test_endpoints_pytest.py", "engine_tests/test_*.py"]
|
python_files = ["test_endpoints_pytest.py"]
|
||||||
Executable
+253
@@ -0,0 +1,253 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Configure Raspberry Pi OS: Wi-Fi client on IF_WAN (default wlan0), Ethernet IF_LAN
|
||||||
|
# (default eth0) toward an external AP. Static LAN IP, DHCP via dnsmasq, NAT masquerade.
|
||||||
|
#
|
||||||
|
# Usage:
|
||||||
|
# sudo ./pi-eth-lan-router.sh install
|
||||||
|
# sudo ./pi-eth-lan-router.sh remove
|
||||||
|
#
|
||||||
|
# Environment overrides (optional):
|
||||||
|
# IF_WAN=wlan0 IF_LAN=eth0 LAN_IP=192.168.4.1 LAN_PREFIX=24 \
|
||||||
|
# DHCP_START=192.168.4.100 DHCP_END=192.168.4.200 \
|
||||||
|
# DNSMASQ_DNS=1.1.1.1,8.8.8.8 \
|
||||||
|
# sudo ./pi-eth-lan-router.sh install
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
IF_WAN="${IF_WAN:-wlan0}"
|
||||||
|
IF_LAN="${IF_LAN:-eth0}"
|
||||||
|
LAN_IP="${LAN_IP:-192.168.4.1}"
|
||||||
|
LAN_PREFIX="${LAN_PREFIX:-24}"
|
||||||
|
DHCP_START="${DHCP_START:-192.168.4.100}"
|
||||||
|
DHCP_END="${DHCP_END:-192.168.4.200}"
|
||||||
|
# Comma-separated DNS for DHCP clients (Pi does not need to run a resolver).
|
||||||
|
DNSMASQ_DNS="${DNSMASQ_DNS:-1.1.1.1,8.8.8.8}"
|
||||||
|
|
||||||
|
NM_CON_NAME="pi-eth-lan-router"
|
||||||
|
MARK_BEGIN="# BEGIN pi-eth-lan-router (scripts/pi-eth-lan-router.sh)"
|
||||||
|
MARK_END="# END pi-eth-lan-router"
|
||||||
|
SYSCTL_FILE="/etc/sysctl.d/99-pi-eth-lan-router.conf"
|
||||||
|
DNSMASQ_SNIPPET="/etc/dnsmasq.d/pi-eth-lan-router.conf"
|
||||||
|
NFT_SNIPPET="/etc/nftables.d/50-pi-eth-lan-router.nft"
|
||||||
|
NFT_INCLUDE='include "/etc/nftables.d/50-pi-eth-lan-router.nft"'
|
||||||
|
NFTABLES_CONF="/etc/nftables.conf"
|
||||||
|
DHCPCD_CONF="/etc/dhcpcd.conf"
|
||||||
|
|
||||||
|
die() { echo "error: $*" >&2; exit 1; }
|
||||||
|
log() { echo "$*"; }
|
||||||
|
|
||||||
|
need_root() {
|
||||||
|
[[ "${EUID:-0}" -eq 0 ]] || die "run as root (sudo)"
|
||||||
|
}
|
||||||
|
|
||||||
|
have_cmd() { command -v "$1" >/dev/null 2>&1; }
|
||||||
|
|
||||||
|
apt_install() {
|
||||||
|
export DEBIAN_FRONTEND=noninteractive
|
||||||
|
apt-get update -qq
|
||||||
|
apt-get install -y -qq dnsmasq nftables
|
||||||
|
}
|
||||||
|
|
||||||
|
write_sysctl() {
|
||||||
|
cat >"$SYSCTL_FILE" <<EOF
|
||||||
|
# Managed by scripts/pi-eth-lan-router.sh
|
||||||
|
net.ipv4.ip_forward=1
|
||||||
|
EOF
|
||||||
|
sysctl --system -q 2>/dev/null || sysctl -p "$SYSCTL_FILE" || true
|
||||||
|
}
|
||||||
|
|
||||||
|
remove_sysctl() {
|
||||||
|
rm -f "$SYSCTL_FILE"
|
||||||
|
sysctl --system -q 2>/dev/null || true
|
||||||
|
}
|
||||||
|
|
||||||
|
write_dnsmasq() {
|
||||||
|
local mask="255.255.255.0"
|
||||||
|
if [[ "$LAN_PREFIX" != "24" ]]; then
|
||||||
|
die "only LAN_PREFIX=24 is supported by this script (extend dnsmasq netmask manually)"
|
||||||
|
fi
|
||||||
|
cat >"$DNSMASQ_SNIPPET" <<EOF
|
||||||
|
# Managed by scripts/pi-eth-lan-router.sh
|
||||||
|
interface=$IF_LAN
|
||||||
|
bind-interfaces
|
||||||
|
dhcp-range=$DHCP_START,$DHCP_END,$mask,24h
|
||||||
|
dhcp-option=option:router,$LAN_IP
|
||||||
|
dhcp-option=option:dns-server,$DNSMASQ_DNS
|
||||||
|
EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
remove_dnsmasq() {
|
||||||
|
rm -f "$DNSMASQ_SNIPPET"
|
||||||
|
}
|
||||||
|
|
||||||
|
write_nft() {
|
||||||
|
mkdir -p /etc/nftables.d
|
||||||
|
cat >"$NFT_SNIPPET" <<EOF
|
||||||
|
# Managed by scripts/pi-eth-lan-router.sh
|
||||||
|
table ip pi_eth_wlan_nat {
|
||||||
|
chain postrouting {
|
||||||
|
type nat hook postrouting priority 100; policy accept;
|
||||||
|
oifname "$IF_WAN" masquerade
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
if [[ -f "$NFTABLES_CONF" ]] && ! grep -qF '50-pi-eth-lan-router.nft' "$NFTABLES_CONF" 2>/dev/null; then
|
||||||
|
printf '\n# pi-eth-lan-router\n%s\n' "$NFT_INCLUDE" >>"$NFTABLES_CONF"
|
||||||
|
elif [[ ! -f "$NFTABLES_CONF" ]]; then
|
||||||
|
log "warning: $NFTABLES_CONF missing; NAT was not added for boot persistence. Install/configure nftables, or add: $NFT_INCLUDE"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
remove_nft() {
|
||||||
|
rm -f "$NFT_SNIPPET"
|
||||||
|
if [[ -f "$NFTABLES_CONF" ]]; then
|
||||||
|
sed -i '/# pi-eth-lan-router/d;/50-pi-eth-lan-router\.nft/d' "$NFTABLES_CONF" || true
|
||||||
|
fi
|
||||||
|
nft delete table ip pi_eth_wlan_nat 2>/dev/null || true
|
||||||
|
}
|
||||||
|
|
||||||
|
apply_nft() {
|
||||||
|
if have_cmd nft; then
|
||||||
|
nft delete table ip pi_eth_wlan_nat 2>/dev/null || true
|
||||||
|
nft -f "$NFT_SNIPPET"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
configure_nm_eth() {
|
||||||
|
have_cmd nmcli || return 1
|
||||||
|
systemctl is-active --quiet NetworkManager 2>/dev/null || return 1
|
||||||
|
|
||||||
|
if nmcli -t -f NAME con show --active 2>/dev/null | grep -qxF "$NM_CON_NAME"; then
|
||||||
|
nmcli con down "$NM_CON_NAME" || true
|
||||||
|
fi
|
||||||
|
if nmcli -t -f NAME con show 2>/dev/null | grep -qxF "$NM_CON_NAME"; then
|
||||||
|
nmcli con mod "$NM_CON_NAME" \
|
||||||
|
connection.interface-name "$IF_LAN" \
|
||||||
|
ipv4.method manual \
|
||||||
|
ipv4.addresses "${LAN_IP}/${LAN_PREFIX}" \
|
||||||
|
ipv4.gateway "" \
|
||||||
|
ipv4.dns "" \
|
||||||
|
ipv4.never-default yes \
|
||||||
|
ipv6.method ignore
|
||||||
|
else
|
||||||
|
nmcli con add type ethernet con-name "$NM_CON_NAME" ifname "$IF_LAN" \
|
||||||
|
ipv4.method manual \
|
||||||
|
ipv4.addresses "${LAN_IP}/${LAN_PREFIX}" \
|
||||||
|
ipv4.gateway "" \
|
||||||
|
ipv4.dns "" \
|
||||||
|
ipv4.never-default yes \
|
||||||
|
ipv6.method ignore
|
||||||
|
fi
|
||||||
|
if ! nmcli con up "$NM_CON_NAME"; then
|
||||||
|
log "warning: could not activate '$NM_CON_NAME' (is $IF_LAN connected?); profile saved for next boot."
|
||||||
|
fi
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
remove_nm_eth() {
|
||||||
|
have_cmd nmcli || return 0
|
||||||
|
if nmcli -t -f NAME con show 2>/dev/null | grep -qxF "$NM_CON_NAME"; then
|
||||||
|
nmcli con delete "$NM_CON_NAME" || true
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
configure_dhcpcd_eth() {
|
||||||
|
[[ -f "$DHCPCD_CONF" ]] || return 1
|
||||||
|
if grep -qF "$MARK_BEGIN" "$DHCPCD_CONF" 2>/dev/null; then
|
||||||
|
sed -i "/$MARK_BEGIN/,/$MARK_END/d" "$DHCPCD_CONF" || true
|
||||||
|
fi
|
||||||
|
{
|
||||||
|
echo "$MARK_BEGIN"
|
||||||
|
echo "interface $IF_LAN"
|
||||||
|
echo "static ip_address=${LAN_IP}/${LAN_PREFIX}"
|
||||||
|
echo "nohook wpa_supplicant"
|
||||||
|
echo "$MARK_END"
|
||||||
|
} >>"$DHCPCD_CONF"
|
||||||
|
systemctl restart dhcpcd 2>/dev/null || true
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
remove_dhcpcd_block() {
|
||||||
|
[[ -f "$DHCPCD_CONF" ]] || return 0
|
||||||
|
if grep -qF "$MARK_BEGIN" "$DHCPCD_CONF" 2>/dev/null; then
|
||||||
|
sed -i "/$MARK_BEGIN/,/$MARK_END/d" "$DHCPCD_CONF" || true
|
||||||
|
systemctl restart dhcpcd 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
configure_eth_static() {
|
||||||
|
if configure_nm_eth; then
|
||||||
|
log "configured $IF_LAN via NetworkManager profile '$NM_CON_NAME'"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
if configure_dhcpcd_eth; then
|
||||||
|
log "configured $IF_LAN via dhcpcd ($DHCPCD_CONF)"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
die "neither NetworkManager (active) nor $DHCPCD_CONF found; set $IF_LAN to ${LAN_IP}/${LAN_PREFIX} manually"
|
||||||
|
}
|
||||||
|
|
||||||
|
remove_eth_static() {
|
||||||
|
remove_nm_eth
|
||||||
|
remove_dhcpcd_block
|
||||||
|
}
|
||||||
|
|
||||||
|
do_install() {
|
||||||
|
need_root
|
||||||
|
log "installing packages (dnsmasq, nftables)…"
|
||||||
|
apt_install
|
||||||
|
|
||||||
|
log "writing sysctl, dnsmasq, nftables snippets…"
|
||||||
|
write_sysctl
|
||||||
|
write_dnsmasq
|
||||||
|
write_nft
|
||||||
|
|
||||||
|
log "setting static IP on $IF_LAN…"
|
||||||
|
configure_eth_static
|
||||||
|
|
||||||
|
log "restarting dnsmasq…"
|
||||||
|
systemctl enable dnsmasq
|
||||||
|
systemctl restart dnsmasq
|
||||||
|
|
||||||
|
log "loading NAT rules and enabling nftables…"
|
||||||
|
apply_nft
|
||||||
|
systemctl enable nftables 2>/dev/null || true
|
||||||
|
systemctl restart nftables 2>/dev/null || true
|
||||||
|
|
||||||
|
log "done. Connect $IF_LAN to the external AP (DHCP off on the AP)."
|
||||||
|
log "Join Wi-Fi on $IF_WAN to the uplink network and complete any captive portal on the Pi."
|
||||||
|
}
|
||||||
|
|
||||||
|
do_remove() {
|
||||||
|
need_root
|
||||||
|
remove_eth_static
|
||||||
|
remove_dnsmasq
|
||||||
|
systemctl restart dnsmasq 2>/dev/null || true
|
||||||
|
|
||||||
|
remove_nft
|
||||||
|
systemctl restart nftables 2>/dev/null || true
|
||||||
|
|
||||||
|
remove_sysctl
|
||||||
|
sysctl -w net.ipv4.ip_forward=0 2>/dev/null || true
|
||||||
|
|
||||||
|
log "removed pi-eth-lan-router configuration snippets and NM profile '$NM_CON_NAME' (if present)."
|
||||||
|
}
|
||||||
|
|
||||||
|
usage() {
|
||||||
|
cat <<EOF
|
||||||
|
Usage: sudo $0 install|remove
|
||||||
|
|
||||||
|
WAN (Wi-Fi client): $IF_WAN
|
||||||
|
LAN (Ethernet to AP): $IF_LAN
|
||||||
|
LAN address: ${LAN_IP}/${LAN_PREFIX}
|
||||||
|
DHCP range: $DHCP_START – $DHCP_END
|
||||||
|
|
||||||
|
Override with environment variables (see script header).
|
||||||
|
EOF
|
||||||
|
}
|
||||||
|
|
||||||
|
case "${1:-}" in
|
||||||
|
install) do_install ;;
|
||||||
|
remove) do_remove ;;
|
||||||
|
*) usage; exit 1 ;;
|
||||||
|
esac
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
from microdot import Microdot
|
|
||||||
from models.output import Output
|
|
||||||
from engine.outputs import open_output
|
|
||||||
import asyncio
|
|
||||||
import json
|
|
||||||
|
|
||||||
controller = Microdot()
|
|
||||||
outputs = Output()
|
|
||||||
|
|
||||||
_JSON = {'Content-Type': 'application/json'}
|
|
||||||
|
|
||||||
TEST_COLORS = ((255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255))
|
|
||||||
|
|
||||||
|
|
||||||
async def run_output_test(out, step_s=1.0):
|
|
||||||
"""Red, green, blue, white for ``step_s`` each, then black."""
|
|
||||||
await out.open()
|
|
||||||
try:
|
|
||||||
for color in TEST_COLORS:
|
|
||||||
frame = bytes(color) * out.pixel_count
|
|
||||||
end = asyncio.get_running_loop().time() + step_s
|
|
||||||
while asyncio.get_running_loop().time() < end:
|
|
||||||
await out.send(frame)
|
|
||||||
await asyncio.sleep(1.0 / out.fps)
|
|
||||||
finally:
|
|
||||||
await out.close()
|
|
||||||
return out.status()
|
|
||||||
|
|
||||||
|
|
||||||
@controller.get('')
|
|
||||||
async def list_outputs(request):
|
|
||||||
"""List all pixel outputs."""
|
|
||||||
return json.dumps(outputs), 200, _JSON
|
|
||||||
|
|
||||||
|
|
||||||
@controller.get('/<id>')
|
|
||||||
async def get_output(request, id):
|
|
||||||
doc = outputs.read(id)
|
|
||||||
if doc:
|
|
||||||
return json.dumps(doc), 200, _JSON
|
|
||||||
return json.dumps({"error": "Output not found"}), 404, _JSON
|
|
||||||
|
|
||||||
|
|
||||||
@controller.post('')
|
|
||||||
async def create_output(request):
|
|
||||||
try:
|
|
||||||
output_id = outputs.create(request.json or {})
|
|
||||||
return json.dumps(outputs.read(output_id)), 201, _JSON
|
|
||||||
except ValueError as e:
|
|
||||||
return json.dumps({"error": str(e)}), 400, _JSON
|
|
||||||
|
|
||||||
|
|
||||||
@controller.put('/<id>')
|
|
||||||
async def update_output(request, id):
|
|
||||||
try:
|
|
||||||
if outputs.update(id, request.json or {}):
|
|
||||||
return json.dumps(outputs.read(id)), 200, _JSON
|
|
||||||
return json.dumps({"error": "Output not found"}), 404, _JSON
|
|
||||||
except ValueError as e:
|
|
||||||
return json.dumps({"error": str(e)}), 400, _JSON
|
|
||||||
|
|
||||||
|
|
||||||
@controller.delete('/<id>')
|
|
||||||
async def delete_output(request, id):
|
|
||||||
if outputs.delete(id):
|
|
||||||
return json.dumps({"message": "Output deleted successfully"}), 200, _JSON
|
|
||||||
return json.dumps({"error": "Output not found"}), 404, _JSON
|
|
||||||
|
|
||||||
|
|
||||||
@controller.post('/<id>/test')
|
|
||||||
async def test_output(request, id):
|
|
||||||
"""Send a short red/green/blue/white test sequence, then black."""
|
|
||||||
doc = outputs.read(id)
|
|
||||||
if not doc:
|
|
||||||
return json.dumps({"error": "Output not found"}), 404, _JSON
|
|
||||||
data = request.json or {}
|
|
||||||
try:
|
|
||||||
step_s = max(0.1, min(5.0, float(data.get("step_s", 1.0))))
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
step_s = 1.0
|
|
||||||
try:
|
|
||||||
status = await run_output_test(open_output(doc), step_s=step_s)
|
|
||||||
except Exception as e:
|
|
||||||
return json.dumps({"error": f"Test failed: {e}"}), 503, _JSON
|
|
||||||
return json.dumps({"message": "Test sent", "status": status}), 200, _JSON
|
|
||||||
@@ -367,6 +367,7 @@ async def create_driver_pattern(request):
|
|||||||
Body JSON:
|
Body JSON:
|
||||||
name, code (required),
|
name, code (required),
|
||||||
min_delay, max_delay, max_colors (optional numbers),
|
min_delay, max_delay, max_colors (optional numbers),
|
||||||
|
has_background (optional bool),
|
||||||
n1..n8 (optional string labels),
|
n1..n8 (optional string labels),
|
||||||
overwrite (optional, default true).
|
overwrite (optional, default true).
|
||||||
"""
|
"""
|
||||||
@@ -409,6 +410,9 @@ async def create_driver_pattern(request):
|
|||||||
"Content-Type": "application/json"
|
"Content-Type": "application/json"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if "has_background" in data:
|
||||||
|
meta["has_background"] = bool(data.get("has_background"))
|
||||||
|
|
||||||
for i in range(1, 9):
|
for i in range(1, 9):
|
||||||
nk = "n%d" % i
|
nk = "n%d" % i
|
||||||
if nk not in data:
|
if nk not in data:
|
||||||
|
|||||||
@@ -47,37 +47,3 @@ async def delete_scene(request, id):
|
|||||||
if scenes.delete(id):
|
if scenes.delete(id):
|
||||||
return json.dumps({"message": "Scene deleted successfully"}), 200
|
return json.dumps({"message": "Scene deleted successfully"}), 200
|
||||||
return json.dumps({"error": "Scene not found"}), 404
|
return json.dumps({"error": "Scene not found"}), 404
|
||||||
|
|
||||||
|
|
||||||
@controller.post('/<id>/play')
|
|
||||||
async def play_scene(request, id):
|
|
||||||
"""Start every sequence in the scene (one per zone; later ones win a shared zone)."""
|
|
||||||
from engine import get_engine
|
|
||||||
from engine.core import EngineError
|
|
||||||
|
|
||||||
scene = scenes.read(id)
|
|
||||||
if not scene:
|
|
||||||
return json.dumps({"error": "Scene not found"}), 404, {'Content-Type': 'application/json'}
|
|
||||||
started, errors = [], {}
|
|
||||||
for sid in scene.get("sequences") or []:
|
|
||||||
try:
|
|
||||||
await get_engine().sequences.play(sid)
|
|
||||||
started.append(str(sid))
|
|
||||||
except EngineError as e:
|
|
||||||
errors[str(sid)] = str(e)
|
|
||||||
return json.dumps({"started": started, "errors": errors}), 200, {'Content-Type': 'application/json'}
|
|
||||||
|
|
||||||
|
|
||||||
@controller.post('/<id>/stop')
|
|
||||||
async def stop_scene(request, id):
|
|
||||||
"""Stop every sequence in the scene."""
|
|
||||||
from engine import get_engine
|
|
||||||
|
|
||||||
scene = scenes.read(id)
|
|
||||||
if not scene:
|
|
||||||
return json.dumps({"error": "Scene not found"}), 404, {'Content-Type': 'application/json'}
|
|
||||||
stopped = []
|
|
||||||
for sid in scene.get("sequences") or []:
|
|
||||||
if await get_engine().sequences.stop(sid):
|
|
||||||
stopped.append(str(sid))
|
|
||||||
return json.dumps({"stopped": stopped}), 200, {'Content-Type': 'application/json'}
|
|
||||||
+22
-49
@@ -1,78 +1,51 @@
|
|||||||
from microdot import Microdot
|
from microdot import Microdot
|
||||||
from models.squence import Sequence
|
from models.squence import Sequence
|
||||||
from engine import get_engine
|
|
||||||
from engine.core import EngineError
|
|
||||||
import json
|
import json
|
||||||
|
|
||||||
controller = Microdot()
|
controller = Microdot()
|
||||||
sequences = Sequence()
|
sequences = Sequence()
|
||||||
|
|
||||||
_JSON = {'Content-Type': 'application/json'}
|
|
||||||
|
|
||||||
|
|
||||||
@controller.get('')
|
@controller.get('')
|
||||||
async def list_sequences(request):
|
async def list_sequences(request):
|
||||||
"""List all sequences."""
|
"""List all sequences."""
|
||||||
return json.dumps(sequences), 200, _JSON
|
return json.dumps(sequences), 200, {'Content-Type': 'application/json'}
|
||||||
|
|
||||||
|
|
||||||
@controller.get('/status')
|
|
||||||
async def sequences_status(request):
|
|
||||||
"""Running state of every sequence started since boot."""
|
|
||||||
return json.dumps(get_engine().sequences.status()), 200, _JSON
|
|
||||||
|
|
||||||
|
|
||||||
@controller.get('/<id>')
|
@controller.get('/<id>')
|
||||||
async def get_sequence(request, id):
|
async def get_sequence(request, id):
|
||||||
"""Get a specific sequence by ID."""
|
"""Get a specific sequence by ID."""
|
||||||
sequence = sequences.read(id)
|
sequence = sequences.read(id)
|
||||||
if sequence:
|
if sequence:
|
||||||
return json.dumps(sequence), 200, _JSON
|
return json.dumps(sequence), 200, {'Content-Type': 'application/json'}
|
||||||
return json.dumps({"error": "Sequence not found"}), 404, _JSON
|
return json.dumps({"error": "Sequence not found"}), 404
|
||||||
|
|
||||||
|
|
||||||
@controller.post('')
|
@controller.post('')
|
||||||
async def create_sequence(request):
|
async def create_sequence(request):
|
||||||
"""Create a sequence: {name, zone_id, loop, repeat_count, steps: [{preset_id, duration_s}]}."""
|
"""Create a new sequence."""
|
||||||
try:
|
try:
|
||||||
sequence_id = sequences.create(request.json or {})
|
data = request.json or {}
|
||||||
return json.dumps(sequences.read(sequence_id)), 201, _JSON
|
group_name = data.get("group_name", "")
|
||||||
except ValueError as e:
|
preset_names = data.get("presets", None)
|
||||||
return json.dumps({"error": str(e)}), 400, _JSON
|
sequence_id = sequences.create(group_name, preset_names)
|
||||||
|
if data:
|
||||||
|
sequences.update(sequence_id, data)
|
||||||
|
return json.dumps(sequences.read(sequence_id)), 201, {'Content-Type': 'application/json'}
|
||||||
|
except Exception as e:
|
||||||
|
return json.dumps({"error": str(e)}), 400
|
||||||
|
|
||||||
@controller.put('/<id>')
|
@controller.put('/<id>')
|
||||||
async def update_sequence(request, id):
|
async def update_sequence(request, id):
|
||||||
"""Update an existing sequence."""
|
"""Update an existing sequence."""
|
||||||
try:
|
try:
|
||||||
if sequences.update(id, request.json or {}):
|
data = request.json
|
||||||
return json.dumps(sequences.read(id)), 200, _JSON
|
if sequences.update(id, data):
|
||||||
return json.dumps({"error": "Sequence not found"}), 404, _JSON
|
return json.dumps(sequences.read(id)), 200, {'Content-Type': 'application/json'}
|
||||||
except ValueError as e:
|
return json.dumps({"error": "Sequence not found"}), 404
|
||||||
return json.dumps({"error": str(e)}), 400, _JSON
|
except Exception as e:
|
||||||
|
return json.dumps({"error": str(e)}), 400
|
||||||
|
|
||||||
@controller.delete('/<id>')
|
@controller.delete('/<id>')
|
||||||
async def delete_sequence(request, id):
|
async def delete_sequence(request, id):
|
||||||
"""Delete a sequence (stops it first if running)."""
|
"""Delete a sequence."""
|
||||||
await get_engine().sequences.stop(id)
|
|
||||||
if sequences.delete(id):
|
if sequences.delete(id):
|
||||||
return json.dumps({"message": "Sequence deleted successfully"}), 200, _JSON
|
return json.dumps({"message": "Sequence deleted successfully"}), 200
|
||||||
return json.dumps({"error": "Sequence not found"}), 404, _JSON
|
return json.dumps({"error": "Sequence not found"}), 404
|
||||||
|
|
||||||
|
|
||||||
@controller.post('/<id>/play')
|
|
||||||
async def play_sequence(request, id):
|
|
||||||
"""Start the sequence on its zone (replaces any sequence already running there)."""
|
|
||||||
try:
|
|
||||||
state = await get_engine().sequences.play(id)
|
|
||||||
return json.dumps(state), 200, _JSON
|
|
||||||
except EngineError as e:
|
|
||||||
return json.dumps({"error": str(e)}), e.status, _JSON
|
|
||||||
|
|
||||||
|
|
||||||
@controller.post('/<id>/stop')
|
|
||||||
async def stop_sequence(request, id):
|
|
||||||
"""Stop the sequence; the zone keeps showing its current preset."""
|
|
||||||
stopped = await get_engine().sequences.stop(id)
|
|
||||||
return json.dumps({"stopped": stopped}), 200, _JSON
|
|
||||||
@@ -211,45 +211,6 @@ async def set_current_zone(request, id):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@controller.get("/engine/status")
|
|
||||||
async def engine_status(request):
|
|
||||||
"""Pi-side engine state: rendering zones and running sequences."""
|
|
||||||
from engine import get_engine
|
|
||||||
|
|
||||||
return json.dumps(get_engine().status()), 200, {"Content-Type": "application/json"}
|
|
||||||
|
|
||||||
|
|
||||||
@controller.post("/<id>/play")
|
|
||||||
async def play_zone(request, id):
|
|
||||||
"""Run a preset on every target in the zone.
|
|
||||||
|
|
||||||
Body: {"preset_id": "16", "drivers": true}. Pixel outputs (DDP/Art-Net/sACN/DMX)
|
|
||||||
are rendered on the Pi; ESP32 led-drivers get the preset + select as before
|
|
||||||
unless ``drivers`` is false. Stops any sequence running on the zone.
|
|
||||||
"""
|
|
||||||
from engine import get_engine
|
|
||||||
from engine.core import EngineError
|
|
||||||
|
|
||||||
data = request.json or {}
|
|
||||||
preset_id = data.get("preset_id")
|
|
||||||
if preset_id in (None, ""):
|
|
||||||
return json.dumps({"error": "preset_id is required"}), 400, {"Content-Type": "application/json"}
|
|
||||||
try:
|
|
||||||
status = await get_engine().play(id, str(preset_id), drivers=data.get("drivers", True) is not False)
|
|
||||||
except EngineError as e:
|
|
||||||
return json.dumps({"error": str(e)}), e.status, {"Content-Type": "application/json"}
|
|
||||||
return json.dumps(status), 200, {"Content-Type": "application/json"}
|
|
||||||
|
|
||||||
|
|
||||||
@controller.post("/<id>/stop")
|
|
||||||
async def stop_zone(request, id):
|
|
||||||
"""Stop the zone's sequence and Pi rendering (pixel outputs go black)."""
|
|
||||||
from engine import get_engine
|
|
||||||
|
|
||||||
stopped = await get_engine().stop(id)
|
|
||||||
return json.dumps({"stopped": stopped}), 200, {"Content-Type": "application/json"}
|
|
||||||
|
|
||||||
|
|
||||||
@controller.get("/<id>")
|
@controller.get("/<id>")
|
||||||
async def get_zone(request, id):
|
async def get_zone(request, id):
|
||||||
z = zones.read(id)
|
z = zones.read(id)
|
||||||
|
|||||||
@@ -1,25 +0,0 @@
|
|||||||
"""Pi-side animation engine.
|
|
||||||
|
|
||||||
* ``engine.outputs`` — protocol drivers (DDP, Art-Net, sACN, USB-DMX, ESP32 presets)
|
|
||||||
* ``engine.renderer`` — runs unchanged led-driver patterns under CPython
|
|
||||||
* ``engine.player`` — per-zone frame streaming
|
|
||||||
* ``engine.sequence_runner`` — timed preset chains
|
|
||||||
|
|
||||||
``get_engine()`` returns the process-wide Engine (created on first use).
|
|
||||||
"""
|
|
||||||
|
|
||||||
_engine = None
|
|
||||||
|
|
||||||
|
|
||||||
def get_engine():
|
|
||||||
global _engine
|
|
||||||
if _engine is None:
|
|
||||||
from engine.core import Engine
|
|
||||||
_engine = Engine()
|
|
||||||
return _engine
|
|
||||||
|
|
||||||
|
|
||||||
def set_engine(engine):
|
|
||||||
global _engine
|
|
||||||
_engine = engine
|
|
||||||
return engine
|
|
||||||
@@ -1,148 +0,0 @@
|
|||||||
"""Engine CLI (run from ``src/``) — portal's ``run_cli`` equivalent.
|
|
||||||
|
|
||||||
python -m engine.cli --output ddp://10.0.0.5?pixels=300 --test
|
|
||||||
python -m engine.cli --output artnet://10.0.0.6?universe=0&pixels=170 --color ff0000
|
|
||||||
python -m engine.cli --output sacn://?universe=1&pixels=170 --preset 16
|
|
||||||
python -m engine.cli --pattern rainbow --n1 2 --leds 60 # stdout preview
|
|
||||||
python -m engine.cli --output dmx_serial:///dev/ttyUSB0?pixels=10 --pattern pulse \\
|
|
||||||
--colors ff0000,0000ff --n1 300 --n2 200 --n3 300
|
|
||||||
"""
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import asyncio
|
|
||||||
import sys
|
|
||||||
|
|
||||||
from engine.outputs import parse_output_url
|
|
||||||
from engine.outputs.base import FrameOutput
|
|
||||||
from engine.player import ZonePlayer
|
|
||||||
from engine.zone_targets import ZoneTargets
|
|
||||||
|
|
||||||
|
|
||||||
class StdoutOutput(FrameOutput):
|
|
||||||
"""Truecolour terminal strip, one line redrawn per frame."""
|
|
||||||
|
|
||||||
protocol = "stdout"
|
|
||||||
|
|
||||||
async def _send_prepared(self, payload):
|
|
||||||
cells = []
|
|
||||||
for i in range(0, len(payload), 3):
|
|
||||||
r, g, b = payload[i], payload[i + 1], payload[i + 2]
|
|
||||||
cells.append(f"\x1b[48;2;{r};{g};{b}m ")
|
|
||||||
sys.stdout.write("\r" + "".join(cells) + "\x1b[0m")
|
|
||||||
sys.stdout.flush()
|
|
||||||
self.stats.packets += 1
|
|
||||||
|
|
||||||
|
|
||||||
def _output_factory(cfg):
|
|
||||||
if cfg.get("protocol") == "stdout":
|
|
||||||
return StdoutOutput(cfg)
|
|
||||||
from engine.outputs import open_output
|
|
||||||
return open_output(cfg)
|
|
||||||
|
|
||||||
|
|
||||||
def build_parser():
|
|
||||||
p = argparse.ArgumentParser(prog="python -m engine.cli", description=__doc__,
|
|
||||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
||||||
p.add_argument("--output", action="append", default=[],
|
|
||||||
help="ddp://, artnet://, sacn://, dmx_serial:// URL (repeatable); default stdout")
|
|
||||||
p.add_argument("--leds", type=int, default=None, help="pixel count (default: from output URL, else 60)")
|
|
||||||
p.add_argument("--fps", type=int, default=None, help="output fps cap")
|
|
||||||
p.add_argument("--global-brightness", type=int, default=255, help="0-255, applied at send")
|
|
||||||
p.add_argument("--duration", type=float, default=None, help="seconds to run (default: until Ctrl-C)")
|
|
||||||
what = p.add_mutually_exclusive_group()
|
|
||||||
what.add_argument("--test", action="store_true", help="red, green, blue, white, then black")
|
|
||||||
what.add_argument("--color", help="solid colour hex, e.g. ff0000")
|
|
||||||
what.add_argument("--preset", help="preset id from db/preset.json")
|
|
||||||
what.add_argument("--pattern", help="driver pattern name, e.g. rainbow")
|
|
||||||
p.add_argument("--colors", default="ffffff", help="comma-separated hex colours for --pattern")
|
|
||||||
p.add_argument("--delay", type=int, default=100)
|
|
||||||
p.add_argument("--brightness", type=int, default=255, help="preset brightness 0-255")
|
|
||||||
p.add_argument("--no-auto", action="store_true", help="manual (beat) mode: auto=false")
|
|
||||||
for i in range(1, 7):
|
|
||||||
p.add_argument(f"--n{i}", type=int, default=0)
|
|
||||||
return p
|
|
||||||
|
|
||||||
|
|
||||||
def _frame_cfgs(args):
|
|
||||||
urls = args.output or ["stdout://"]
|
|
||||||
cfgs = []
|
|
||||||
for url in urls:
|
|
||||||
cfg = {"protocol": "stdout", "name": "stdout"} if url.startswith("stdout") else parse_output_url(url)
|
|
||||||
if args.leds is not None:
|
|
||||||
cfg["pixel_count"] = args.leds
|
|
||||||
cfg.setdefault("pixel_count", 60)
|
|
||||||
if args.fps is not None:
|
|
||||||
cfg["fps"] = args.fps
|
|
||||||
elif cfg["protocol"] == "stdout":
|
|
||||||
cfg.setdefault("fps", 20)
|
|
||||||
cfgs.append(cfg)
|
|
||||||
return cfgs
|
|
||||||
|
|
||||||
|
|
||||||
def _payload_from_args(args):
|
|
||||||
if args.preset:
|
|
||||||
from engine.presets import preset_payload
|
|
||||||
payload = preset_payload(args.preset)
|
|
||||||
if payload is None:
|
|
||||||
raise SystemExit(f"preset {args.preset!r} not found")
|
|
||||||
return args.preset, payload
|
|
||||||
if args.color:
|
|
||||||
return "cli", {"p": "on", "c": ["#" + args.color.lstrip("#")], "b": args.brightness}
|
|
||||||
payload = {
|
|
||||||
"p": args.pattern or "rainbow",
|
|
||||||
"c": ["#" + c.strip().lstrip("#") for c in args.colors.split(",") if c.strip()],
|
|
||||||
"d": args.delay,
|
|
||||||
"b": args.brightness,
|
|
||||||
"a": not args.no_auto,
|
|
||||||
}
|
|
||||||
for i in range(1, 7):
|
|
||||||
payload[f"n{i}"] = getattr(args, f"n{i}")
|
|
||||||
return "cli", payload
|
|
||||||
|
|
||||||
|
|
||||||
async def _run_test(player, step_s=1.0):
|
|
||||||
for color in ((255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255)):
|
|
||||||
await player.apply("cli", {"p": "on", "c": [color], "b": 255})
|
|
||||||
await asyncio.sleep(step_s)
|
|
||||||
|
|
||||||
|
|
||||||
async def run(args):
|
|
||||||
from engine.pattern_loader import get_library
|
|
||||||
|
|
||||||
library = get_library()
|
|
||||||
if library.errors:
|
|
||||||
print(f"pattern load errors: {library.errors}", file=sys.stderr)
|
|
||||||
targets = ZoneTargets("cli", _frame_cfgs(args), [])
|
|
||||||
player = ZonePlayer(targets, library, lambda: args.global_brightness, output_factory=_output_factory)
|
|
||||||
await player.start()
|
|
||||||
try:
|
|
||||||
if args.test:
|
|
||||||
await _run_test(player)
|
|
||||||
return
|
|
||||||
preset_id, payload = _payload_from_args(args)
|
|
||||||
if payload.get("p") not in library.ids():
|
|
||||||
raise SystemExit(f"unknown pattern {payload.get('p')!r}; available: {', '.join(library.ids())}")
|
|
||||||
await player.apply(preset_id, payload)
|
|
||||||
if args.duration:
|
|
||||||
await asyncio.sleep(args.duration)
|
|
||||||
else:
|
|
||||||
while True:
|
|
||||||
await asyncio.sleep(3600)
|
|
||||||
finally:
|
|
||||||
await player.stop()
|
|
||||||
print()
|
|
||||||
for st in player.status()["outputs"]:
|
|
||||||
print(f"{st['name']}: frames={st['frames']} packets={st['packets']} errors={st['errors']}"
|
|
||||||
+ (f" last_error={st['last_error']}" if st["last_error"] else ""))
|
|
||||||
|
|
||||||
|
|
||||||
def main(argv=None):
|
|
||||||
args = build_parser().parse_args(argv)
|
|
||||||
try:
|
|
||||||
asyncio.run(run(args))
|
|
||||||
except KeyboardInterrupt:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
"""Engine: one ZonePlayer per zone + the preset sequencer on top."""
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
|
|
||||||
from engine.pattern_loader import get_library
|
|
||||||
from engine.player import ZonePlayer
|
|
||||||
from engine.presets import preset_payload
|
|
||||||
from engine.sequence_runner import SequenceRunner
|
|
||||||
from engine.zone_targets import resolve_zone
|
|
||||||
|
|
||||||
|
|
||||||
class EngineError(Exception):
|
|
||||||
def __init__(self, message, status=400):
|
|
||||||
super().__init__(message)
|
|
||||||
self.status = status
|
|
||||||
|
|
||||||
|
|
||||||
class Engine:
|
|
||||||
def __init__(self, library=None, brightness_getter=None, zone_resolver=None,
|
|
||||||
payload_resolver=None, player_factory=None, sequences_model=None):
|
|
||||||
self._library = library
|
|
||||||
self.brightness_getter = brightness_getter or (lambda: 255)
|
|
||||||
self._resolve_zone = zone_resolver or resolve_zone
|
|
||||||
self._payload = payload_resolver or preset_payload
|
|
||||||
self._player_factory = player_factory or ZonePlayer
|
|
||||||
self.players = {}
|
|
||||||
self._lock = None
|
|
||||||
self.sequences = SequenceRunner(self, sequences_model=sequences_model)
|
|
||||||
|
|
||||||
@property
|
|
||||||
def library(self):
|
|
||||||
if self._library is None:
|
|
||||||
self._library = get_library()
|
|
||||||
return self._library
|
|
||||||
|
|
||||||
def _get_lock(self):
|
|
||||||
if self._lock is None:
|
|
||||||
self._lock = asyncio.Lock()
|
|
||||||
return self._lock
|
|
||||||
|
|
||||||
async def play(self, zone_id, preset_id, source="manual", drivers=True):
|
|
||||||
"""Run ``preset_id`` on every target of ``zone_id`` (pixel outputs + ESP32s).
|
|
||||||
|
|
||||||
``source="manual"`` (UI pick) stops any sequence running on the zone.
|
|
||||||
``drivers=False`` leaves the ESP32s alone (the UI already sent to them).
|
|
||||||
"""
|
|
||||||
zone_id = str(zone_id)
|
|
||||||
if source == "manual":
|
|
||||||
await self.sequences.stop_zone(zone_id)
|
|
||||||
targets = self._resolve_zone(zone_id)
|
|
||||||
if targets is None:
|
|
||||||
raise EngineError("Zone not found", 404)
|
|
||||||
payload = self._payload(str(preset_id))
|
|
||||||
if payload is None:
|
|
||||||
raise EngineError("Preset not found", 404)
|
|
||||||
async with self._get_lock():
|
|
||||||
player = self.players.get(zone_id)
|
|
||||||
if player is not None and player.targets.signature() != targets.signature():
|
|
||||||
await player.stop()
|
|
||||||
player = None
|
|
||||||
if player is None:
|
|
||||||
player = self._player_factory(targets, self.library, self.brightness_getter)
|
|
||||||
await player.start()
|
|
||||||
self.players[zone_id] = player
|
|
||||||
await player.apply(str(preset_id), payload, drivers=drivers)
|
|
||||||
return player.status()
|
|
||||||
|
|
||||||
async def stop(self, zone_id):
|
|
||||||
"""Stop the zone's sequence and Pi rendering (pixel outputs go black)."""
|
|
||||||
zone_id = str(zone_id)
|
|
||||||
await self.sequences.stop_zone(zone_id)
|
|
||||||
async with self._get_lock():
|
|
||||||
player = self.players.pop(zone_id, None)
|
|
||||||
if player is not None:
|
|
||||||
await player.stop()
|
|
||||||
return player is not None
|
|
||||||
|
|
||||||
async def stop_all(self, persist=False):
|
|
||||||
await self.sequences.stop_all(persist=persist)
|
|
||||||
async with self._get_lock():
|
|
||||||
players, self.players = list(self.players.values()), {}
|
|
||||||
for player in players:
|
|
||||||
await player.stop()
|
|
||||||
|
|
||||||
def status(self):
|
|
||||||
return {
|
|
||||||
"zones": {zid: p.status() for zid, p in self.players.items()},
|
|
||||||
"sequences": self.sequences.status(),
|
|
||||||
}
|
|
||||||
@@ -1,68 +0,0 @@
|
|||||||
"""Stand-in for the led-driver ``Presets`` object that patterns draw into.
|
|
||||||
|
|
||||||
Same surface the patterns use on the ESP32 (``n[i]``, ``n.write()``,
|
|
||||||
``n.fill``, ``num_leds``, ``step``, ``fill``, ``off``, ``on``,
|
|
||||||
``apply_brightness``), but ``write()`` hands the frame to a callback instead
|
|
||||||
of a NeoPixel strip.
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
class PixelBuffer:
|
|
||||||
"""NeoPixel-compatible buffer of RGB tuples."""
|
|
||||||
|
|
||||||
def __init__(self, num_leds, on_write=None):
|
|
||||||
self.n = int(num_leds)
|
|
||||||
self._px = [(0, 0, 0)] * self.n
|
|
||||||
self.on_write = on_write
|
|
||||||
|
|
||||||
def __len__(self):
|
|
||||||
return self.n
|
|
||||||
|
|
||||||
def __setitem__(self, i, color):
|
|
||||||
self._px[i] = (int(color[0]) & 0xFF, int(color[1]) & 0xFF, int(color[2]) & 0xFF)
|
|
||||||
|
|
||||||
def __getitem__(self, i):
|
|
||||||
return self._px[i]
|
|
||||||
|
|
||||||
def fill(self, color):
|
|
||||||
c = (int(color[0]) & 0xFF, int(color[1]) & 0xFF, int(color[2]) & 0xFF)
|
|
||||||
self._px = [c] * self.n
|
|
||||||
|
|
||||||
def to_bytes(self):
|
|
||||||
out = bytearray(self.n * 3)
|
|
||||||
for i, (r, g, b) in enumerate(self._px):
|
|
||||||
j = i * 3
|
|
||||||
out[j] = r
|
|
||||||
out[j + 1] = g
|
|
||||||
out[j + 2] = b
|
|
||||||
return bytes(out)
|
|
||||||
|
|
||||||
def write(self):
|
|
||||||
if self.on_write is not None:
|
|
||||||
self.on_write(self.to_bytes())
|
|
||||||
|
|
||||||
|
|
||||||
class FrameDriver:
|
|
||||||
def __init__(self, num_leds, on_write=None):
|
|
||||||
self.num_leds = int(num_leds)
|
|
||||||
self.n = PixelBuffer(self.num_leds, on_write)
|
|
||||||
self.step = 0
|
|
||||||
# Global brightness is applied per output at send time, not here.
|
|
||||||
self.b = 255
|
|
||||||
|
|
||||||
def apply_brightness(self, color, brightness_override=None):
|
|
||||||
local = brightness_override if brightness_override is not None else 255
|
|
||||||
effective_brightness = int(local * self.b / 255)
|
|
||||||
return tuple(int(c * effective_brightness / 255) for c in color)
|
|
||||||
|
|
||||||
def fill(self, color=None):
|
|
||||||
self.n.fill(color if color is not None else (0, 0, 0))
|
|
||||||
self.n.write()
|
|
||||||
|
|
||||||
def off(self, preset=None):
|
|
||||||
self.fill((0, 0, 0))
|
|
||||||
|
|
||||||
def on(self, preset):
|
|
||||||
colors = preset.c
|
|
||||||
color = colors[0] if colors else (255, 255, 255)
|
|
||||||
self.fill(self.apply_brightness(color, preset.b))
|
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
"""MicroPython compatibility for running led-driver patterns under CPython.
|
|
||||||
|
|
||||||
Installs a ``utime`` module whose clock is chosen per thread:
|
|
||||||
|
|
||||||
* ``RealClock`` — monotonic wall clock, ``sleep_ms`` really sleeps (render threads).
|
|
||||||
* ``VirtualClock`` — manual time; ``sleep_ms`` just advances it (tests, offline render).
|
|
||||||
|
|
||||||
Patterns only use ``ticks_ms``/``ticks_diff``/``ticks_add``/``sleep_ms``; tick
|
|
||||||
values never wrap here, so the diff/add helpers are plain arithmetic.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import sys
|
|
||||||
import threading
|
|
||||||
import time
|
|
||||||
import types
|
|
||||||
|
|
||||||
|
|
||||||
class RealClock:
|
|
||||||
def __init__(self):
|
|
||||||
self._t0 = time.monotonic()
|
|
||||||
|
|
||||||
def ticks_ms(self):
|
|
||||||
return int((time.monotonic() - self._t0) * 1000)
|
|
||||||
|
|
||||||
def ticks_us(self):
|
|
||||||
return int((time.monotonic() - self._t0) * 1000000)
|
|
||||||
|
|
||||||
def sleep_ms(self, ms):
|
|
||||||
if ms > 0:
|
|
||||||
time.sleep(ms / 1000.0)
|
|
||||||
|
|
||||||
|
|
||||||
class VirtualClock:
|
|
||||||
def __init__(self, start_ms=0):
|
|
||||||
self.now_us = int(start_ms) * 1000
|
|
||||||
|
|
||||||
def ticks_ms(self):
|
|
||||||
return self.now_us // 1000
|
|
||||||
|
|
||||||
def ticks_us(self):
|
|
||||||
return self.now_us
|
|
||||||
|
|
||||||
def advance_ms(self, ms):
|
|
||||||
self.now_us += int(ms * 1000)
|
|
||||||
|
|
||||||
def sleep_ms(self, ms):
|
|
||||||
if ms > 0:
|
|
||||||
self.advance_ms(ms)
|
|
||||||
|
|
||||||
|
|
||||||
_local = threading.local()
|
|
||||||
_default_clock = RealClock()
|
|
||||||
|
|
||||||
|
|
||||||
def current_clock():
|
|
||||||
return getattr(_local, "clock", None) or _default_clock
|
|
||||||
|
|
||||||
|
|
||||||
def set_thread_clock(clock):
|
|
||||||
"""Use ``clock`` for ``utime`` calls made on the current thread (None = real)."""
|
|
||||||
_local.clock = clock
|
|
||||||
|
|
||||||
|
|
||||||
def _build_utime():
|
|
||||||
mod = types.ModuleType("utime")
|
|
||||||
mod.ticks_ms = lambda: current_clock().ticks_ms()
|
|
||||||
mod.ticks_us = lambda: current_clock().ticks_us()
|
|
||||||
mod.ticks_cpu = mod.ticks_us
|
|
||||||
mod.ticks_diff = lambda a, b: a - b
|
|
||||||
mod.ticks_add = lambda a, b: a + b
|
|
||||||
mod.sleep_ms = lambda ms: current_clock().sleep_ms(ms)
|
|
||||||
mod.sleep_us = lambda us: current_clock().sleep_ms(us / 1000.0)
|
|
||||||
mod.sleep = lambda s: current_clock().sleep_ms(s * 1000.0)
|
|
||||||
mod.time = time.time
|
|
||||||
mod.__led_controller_shim__ = True
|
|
||||||
return mod
|
|
||||||
|
|
||||||
|
|
||||||
def install():
|
|
||||||
"""Register the shim as ``utime`` (idempotent; never replaces a real utime)."""
|
|
||||||
existing = sys.modules.get("utime")
|
|
||||||
if existing is not None:
|
|
||||||
return existing
|
|
||||||
mod = _build_utime()
|
|
||||||
sys.modules["utime"] = mod
|
|
||||||
return mod
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
"""Engine output drivers and the factory that builds them from config."""
|
|
||||||
|
|
||||||
from urllib.parse import parse_qs, urlparse
|
|
||||||
|
|
||||||
from engine.outputs.artnet import ArtNetOutput
|
|
||||||
from engine.outputs.base import FrameOutput, PresetOutput
|
|
||||||
from engine.outputs.ddp import DdpOutput
|
|
||||||
from engine.outputs.dmx_serial import DmxSerialOutput
|
|
||||||
from engine.outputs.sacn import SacnOutput
|
|
||||||
|
|
||||||
FRAME_PROTOCOLS = {
|
|
||||||
"ddp": DdpOutput,
|
|
||||||
"artnet": ArtNetOutput,
|
|
||||||
"sacn": SacnOutput,
|
|
||||||
"dmx_serial": DmxSerialOutput,
|
|
||||||
}
|
|
||||||
|
|
||||||
_URL_ALIASES = {"e131": "sacn", "dmx": "dmx_serial", "art-net": "artnet"}
|
|
||||||
_QUERY_KEYS = {
|
|
||||||
"pixels": "pixel_count",
|
|
||||||
"order": "color_order",
|
|
||||||
"offset": "pixel_offset",
|
|
||||||
"mode": "dmx_mode",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def open_output(cfg):
|
|
||||||
"""Build a FrameOutput from an output record (``protocol`` selects the driver)."""
|
|
||||||
protocol = str((cfg or {}).get("protocol") or "").lower()
|
|
||||||
protocol = _URL_ALIASES.get(protocol, protocol)
|
|
||||||
cls = FRAME_PROTOCOLS.get(protocol)
|
|
||||||
if cls is None:
|
|
||||||
raise ValueError(f"unknown output protocol: {protocol!r}")
|
|
||||||
return cls(cfg)
|
|
||||||
|
|
||||||
|
|
||||||
def parse_output_url(url):
|
|
||||||
"""``ddp://10.0.0.5:4048?pixels=300&order=grb`` → output config dict.
|
|
||||||
|
|
||||||
``dmx_serial:///dev/ttyUSB0?mode=open_dmx&channel=1`` for serial DMX.
|
|
||||||
"""
|
|
||||||
# urlparse rejects "_" in schemes (dmx_serial://), so split the scheme off first.
|
|
||||||
scheme, sep, rest = str(url).partition("://")
|
|
||||||
if not sep:
|
|
||||||
raise ValueError(f"output URL needs a scheme, e.g. ddp://host: {url!r}")
|
|
||||||
scheme = scheme.strip().lower()
|
|
||||||
protocol = _URL_ALIASES.get(scheme, scheme)
|
|
||||||
parsed = urlparse("udp://" + rest)
|
|
||||||
cfg = {"protocol": protocol, "name": url}
|
|
||||||
if protocol == "dmx_serial":
|
|
||||||
cfg["serial_port"] = parsed.path or parsed.netloc
|
|
||||||
else:
|
|
||||||
if parsed.hostname:
|
|
||||||
cfg["host"] = parsed.hostname
|
|
||||||
if parsed.port:
|
|
||||||
cfg["port"] = parsed.port
|
|
||||||
for key, values in parse_qs(parsed.query).items():
|
|
||||||
cfg[_QUERY_KEYS.get(key, key)] = values[-1]
|
|
||||||
return cfg
|
|
||||||
|
|
||||||
|
|
||||||
__all__ = [
|
|
||||||
"FrameOutput",
|
|
||||||
"PresetOutput",
|
|
||||||
"DdpOutput",
|
|
||||||
"ArtNetOutput",
|
|
||||||
"SacnOutput",
|
|
||||||
"DmxSerialOutput",
|
|
||||||
"FRAME_PROTOCOLS",
|
|
||||||
"open_output",
|
|
||||||
"parse_output_url",
|
|
||||||
]
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
"""Art-Net (ArtDMX) output — UDP 6454.
|
|
||||||
|
|
||||||
ArtDMX packet:
|
|
||||||
0 "Art-Net\\0"
|
|
||||||
8 OpCode 0x5000 (little-endian)
|
|
||||||
10 ProtVer 14 (big-endian)
|
|
||||||
12 Sequence 1..255 (0 disables re-ordering)
|
|
||||||
13 Physical 0
|
|
||||||
14 Port-Address: SubUni (low byte), Net (high 7 bits)
|
|
||||||
16 Length (big-endian, even, 2..512)
|
|
||||||
18 DMX data
|
|
||||||
|
|
||||||
170 RGB pixels per universe; consecutive universes from ``universe``.
|
|
||||||
Optional ArtSync (OpCode 0x5200) after each frame when ``sync`` is set.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import struct
|
|
||||||
|
|
||||||
from engine.outputs.base import UdpFrameOutput, _bool, _int, split_universes
|
|
||||||
|
|
||||||
ARTNET_PORT = 6454
|
|
||||||
ARTNET_ID = b"Art-Net\x00"
|
|
||||||
OP_DMX = 0x5000
|
|
||||||
OP_SYNC = 0x5200
|
|
||||||
PROT_VER = 14
|
|
||||||
|
|
||||||
|
|
||||||
def build_artdmx(universe, data, sequence=0, physical=0):
|
|
||||||
data = bytes(data[:512])
|
|
||||||
if len(data) % 2:
|
|
||||||
data += b"\x00"
|
|
||||||
if len(data) < 2:
|
|
||||||
data = data + bytes(2 - len(data))
|
|
||||||
universe &= 0x7FFF
|
|
||||||
return (
|
|
||||||
ARTNET_ID
|
|
||||||
+ struct.pack("<H", OP_DMX)
|
|
||||||
+ struct.pack(">H", PROT_VER)
|
|
||||||
+ bytes((sequence & 0xFF, physical & 0xFF, universe & 0xFF, (universe >> 8) & 0x7F))
|
|
||||||
+ struct.pack(">H", len(data))
|
|
||||||
+ data
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def build_artsync():
|
|
||||||
return ARTNET_ID + struct.pack("<H", OP_SYNC) + struct.pack(">H", PROT_VER) + b"\x00\x00"
|
|
||||||
|
|
||||||
|
|
||||||
class ArtNetOutput(UdpFrameOutput):
|
|
||||||
protocol = "artnet"
|
|
||||||
default_port = ARTNET_PORT
|
|
||||||
|
|
||||||
def __init__(self, cfg):
|
|
||||||
super().__init__(cfg)
|
|
||||||
if not self.host:
|
|
||||||
self.host = "255.255.255.255"
|
|
||||||
self.broadcast = True
|
|
||||||
self.universe = _int(self.cfg.get("universe"), 0, 0, 0x7FFF)
|
|
||||||
self.sync = _bool(self.cfg.get("sync"), False)
|
|
||||||
self._sequence = 0
|
|
||||||
|
|
||||||
def next_sequence(self):
|
|
||||||
self._sequence = (self._sequence % 255) + 1
|
|
||||||
return self._sequence
|
|
||||||
|
|
||||||
def packets_for(self, payload):
|
|
||||||
seq = self.next_sequence()
|
|
||||||
packets = [
|
|
||||||
build_artdmx(self.universe + i, chunk, seq)
|
|
||||||
for i, chunk in enumerate(split_universes(payload))
|
|
||||||
]
|
|
||||||
if self.sync:
|
|
||||||
packets.append(build_artsync())
|
|
||||||
return packets
|
|
||||||
|
|
||||||
async def _send_prepared(self, payload):
|
|
||||||
for packet in self.packets_for(payload):
|
|
||||||
self.sendto(packet)
|
|
||||||
@@ -1,254 +0,0 @@
|
|||||||
"""Common output-driver interface and helpers.
|
|
||||||
|
|
||||||
Two kinds of output:
|
|
||||||
|
|
||||||
* ``FrameOutput`` — the Pi renders pixels and streams raw RGB frames
|
|
||||||
(DDP, Art-Net, sACN, USB-DMX).
|
|
||||||
* ``PresetOutput`` — the device renders itself; the engine only tells it which
|
|
||||||
preset to run (our ESP32 led-drivers over Wi-Fi / ESP-NOW).
|
|
||||||
"""
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import functools
|
|
||||||
import socket
|
|
||||||
|
|
||||||
COLOR_ORDERS = {
|
|
||||||
"rgb": (0, 1, 2),
|
|
||||||
"rbg": (0, 2, 1),
|
|
||||||
"grb": (1, 0, 2),
|
|
||||||
"gbr": (1, 2, 0),
|
|
||||||
"brg": (2, 0, 1),
|
|
||||||
"bgr": (2, 1, 0),
|
|
||||||
}
|
|
||||||
|
|
||||||
DEFAULT_FPS = 40
|
|
||||||
|
|
||||||
|
|
||||||
def _int(value, default, lo=None, hi=None):
|
|
||||||
try:
|
|
||||||
v = int(value)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
v = default
|
|
||||||
if lo is not None:
|
|
||||||
v = max(lo, v)
|
|
||||||
if hi is not None:
|
|
||||||
v = min(hi, v)
|
|
||||||
return v
|
|
||||||
|
|
||||||
|
|
||||||
def _bool(value, default=False):
|
|
||||||
if isinstance(value, bool):
|
|
||||||
return value
|
|
||||||
if isinstance(value, (int, float)):
|
|
||||||
return bool(value)
|
|
||||||
if isinstance(value, str):
|
|
||||||
s = value.strip().lower()
|
|
||||||
if s in ("1", "true", "yes", "on"):
|
|
||||||
return True
|
|
||||||
if s in ("0", "false", "no", "off"):
|
|
||||||
return False
|
|
||||||
return default
|
|
||||||
|
|
||||||
|
|
||||||
class OutputStats:
|
|
||||||
def __init__(self):
|
|
||||||
self.frames = 0
|
|
||||||
self.packets = 0
|
|
||||||
self.bytes = 0
|
|
||||||
self.errors = 0
|
|
||||||
self.last_error = None
|
|
||||||
|
|
||||||
def error(self, exc):
|
|
||||||
self.errors += 1
|
|
||||||
self.last_error = repr(exc)
|
|
||||||
|
|
||||||
def to_dict(self):
|
|
||||||
return {
|
|
||||||
"frames": self.frames,
|
|
||||||
"packets": self.packets,
|
|
||||||
"bytes": self.bytes,
|
|
||||||
"errors": self.errors,
|
|
||||||
"last_error": self.last_error,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class FrameOutput:
|
|
||||||
"""Base class for pixel-streaming outputs."""
|
|
||||||
|
|
||||||
kind = "frame"
|
|
||||||
protocol = ""
|
|
||||||
# Resend the last frame this often when the pattern is static, so receivers
|
|
||||||
# don't time out (sACN drops a source after 2.5 s; DMX expects a steady stream).
|
|
||||||
keepalive_s = 1.0
|
|
||||||
|
|
||||||
def __init__(self, cfg):
|
|
||||||
cfg = dict(cfg or {})
|
|
||||||
self.cfg = cfg
|
|
||||||
self.name = str(cfg.get("name") or cfg.get("id") or self.protocol)
|
|
||||||
self.pixel_count = _int(cfg.get("pixel_count"), 60, 1, 100000)
|
|
||||||
self.pixel_offset = _int(cfg.get("pixel_offset"), 0, 0)
|
|
||||||
order = str(cfg.get("color_order") or "rgb").lower()
|
|
||||||
self.color_order = order if order in COLOR_ORDERS else "rgb"
|
|
||||||
self.reverse = _bool(cfg.get("reverse"), False)
|
|
||||||
self.brightness = _int(cfg.get("brightness"), 255, 0, 255)
|
|
||||||
self.fps = _int(cfg.get("fps"), DEFAULT_FPS, 1, 120)
|
|
||||||
self.stats = OutputStats()
|
|
||||||
self._index_map = self._build_index_map()
|
|
||||||
|
|
||||||
# -- frame preparation -------------------------------------------------
|
|
||||||
|
|
||||||
def _build_index_map(self):
|
|
||||||
"""Byte index map: out[i] = src[map[i]] (colour order + reverse)."""
|
|
||||||
order = COLOR_ORDERS[self.color_order]
|
|
||||||
n = self.pixel_count
|
|
||||||
idx = []
|
|
||||||
for p in range(n):
|
|
||||||
src_px = (n - 1 - p) if self.reverse else p
|
|
||||||
base = src_px * 3
|
|
||||||
idx.extend((base + order[0], base + order[1], base + order[2]))
|
|
||||||
return idx
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
@functools.lru_cache(maxsize=64)
|
|
||||||
def brightness_table(level):
|
|
||||||
level = max(0, min(255, int(level)))
|
|
||||||
return bytes((v * level + 127) // 255 for v in range(256))
|
|
||||||
|
|
||||||
def prepare(self, rgb, global_brightness=255):
|
|
||||||
"""Pad/truncate, apply brightness, colour order and reverse."""
|
|
||||||
need = self.pixel_count * 3
|
|
||||||
data = bytes(rgb[:need])
|
|
||||||
if len(data) < need:
|
|
||||||
data = data + bytes(need - len(data))
|
|
||||||
level = (self.brightness * max(0, min(255, int(global_brightness))) + 127) // 255
|
|
||||||
if level < 255:
|
|
||||||
data = data.translate(self.brightness_table(level))
|
|
||||||
if self.color_order == "rgb" and not self.reverse:
|
|
||||||
return data
|
|
||||||
m = self._index_map
|
|
||||||
return bytes(data[i] for i in m)
|
|
||||||
|
|
||||||
# -- lifecycle -----------------------------------------------------------
|
|
||||||
|
|
||||||
async def open(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
async def send(self, rgb, global_brightness=255):
|
|
||||||
"""Send one frame of logical RGB (pixel_count*3 bytes)."""
|
|
||||||
try:
|
|
||||||
payload = self.prepare(rgb, global_brightness)
|
|
||||||
await self._send_prepared(payload)
|
|
||||||
self.stats.frames += 1
|
|
||||||
except Exception as e:
|
|
||||||
self.stats.error(e)
|
|
||||||
|
|
||||||
async def _send_prepared(self, payload):
|
|
||||||
raise NotImplementedError
|
|
||||||
|
|
||||||
async def blackout(self):
|
|
||||||
await self.send(bytes(self.pixel_count * 3))
|
|
||||||
|
|
||||||
async def close(self):
|
|
||||||
try:
|
|
||||||
await self.blackout()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def status(self):
|
|
||||||
return {
|
|
||||||
"name": self.name,
|
|
||||||
"protocol": self.protocol,
|
|
||||||
"kind": self.kind,
|
|
||||||
"pixel_count": self.pixel_count,
|
|
||||||
**self.stats.to_dict(),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class _DatagramSink(asyncio.DatagramProtocol):
|
|
||||||
def __init__(self, owner):
|
|
||||||
self.owner = owner
|
|
||||||
|
|
||||||
def error_received(self, exc):
|
|
||||||
self.owner.stats.error(exc)
|
|
||||||
|
|
||||||
|
|
||||||
class UdpFrameOutput(FrameOutput):
|
|
||||||
"""FrameOutput that sends UDP datagrams to one host:port."""
|
|
||||||
|
|
||||||
default_port = 0
|
|
||||||
|
|
||||||
def __init__(self, cfg):
|
|
||||||
super().__init__(cfg)
|
|
||||||
self.host = str(self.cfg.get("host") or "").strip()
|
|
||||||
self.port = _int(self.cfg.get("port"), self.default_port, 1, 65535)
|
|
||||||
self.broadcast = _bool(self.cfg.get("broadcast"), False)
|
|
||||||
self._transport = None
|
|
||||||
|
|
||||||
def destination(self):
|
|
||||||
return (self.host, self.port)
|
|
||||||
|
|
||||||
def _make_socket(self):
|
|
||||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
||||||
sock.setblocking(False)
|
|
||||||
if self.broadcast or self.host.endswith(".255"):
|
|
||||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
|
||||||
return sock
|
|
||||||
|
|
||||||
async def open(self):
|
|
||||||
if self._transport is not None:
|
|
||||||
return
|
|
||||||
loop = asyncio.get_running_loop()
|
|
||||||
self._transport, _ = await loop.create_datagram_endpoint(
|
|
||||||
lambda: _DatagramSink(self), sock=self._make_socket()
|
|
||||||
)
|
|
||||||
|
|
||||||
def sendto(self, packet, addr=None):
|
|
||||||
if self._transport is None:
|
|
||||||
raise RuntimeError("output not open")
|
|
||||||
self._transport.sendto(packet, addr or self.destination())
|
|
||||||
self.stats.packets += 1
|
|
||||||
self.stats.bytes += len(packet)
|
|
||||||
|
|
||||||
async def send(self, rgb, global_brightness=255):
|
|
||||||
if self._transport is None:
|
|
||||||
try:
|
|
||||||
await self.open()
|
|
||||||
except Exception as e:
|
|
||||||
self.stats.error(e)
|
|
||||||
return
|
|
||||||
await super().send(rgb, global_brightness)
|
|
||||||
|
|
||||||
async def close(self):
|
|
||||||
await super().close()
|
|
||||||
if self._transport is not None:
|
|
||||||
self._transport.close()
|
|
||||||
self._transport = None
|
|
||||||
|
|
||||||
|
|
||||||
class PresetOutput:
|
|
||||||
"""Base class for outputs that render presets on the device itself."""
|
|
||||||
|
|
||||||
kind = "preset"
|
|
||||||
protocol = ""
|
|
||||||
|
|
||||||
def __init__(self, cfg=None):
|
|
||||||
self.cfg = dict(cfg or {})
|
|
||||||
self.name = str(self.cfg.get("name") or self.protocol)
|
|
||||||
self.stats = OutputStats()
|
|
||||||
|
|
||||||
async def open(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
async def apply(self, preset_id, preset_payload):
|
|
||||||
raise NotImplementedError
|
|
||||||
|
|
||||||
async def close(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def status(self):
|
|
||||||
return {"name": self.name, "protocol": self.protocol, "kind": self.kind, **self.stats.to_dict()}
|
|
||||||
|
|
||||||
|
|
||||||
def split_universes(data, channels_per_universe=510):
|
|
||||||
"""Split RGB bytes into DMX-universe sized chunks (170 RGB px = 510 ch)."""
|
|
||||||
return [data[i:i + channels_per_universe] for i in range(0, len(data), channels_per_universe)] or [b""]
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
"""DDP (Distributed Display Protocol) output — UDP 4048.
|
|
||||||
|
|
||||||
Header (10 bytes, big-endian):
|
|
||||||
0 flags 0x40 = version 1, | 0x01 = PUSH (last packet of a frame)
|
|
||||||
1 sequence 1..15 (0 = sequence numbers unused)
|
|
||||||
2 data type 0x0B = RGB, 8 bits per channel
|
|
||||||
3 dest id 0x01 = default output device
|
|
||||||
4 offset uint32 byte offset into the frame
|
|
||||||
8 length uint16 payload length
|
|
||||||
"""
|
|
||||||
|
|
||||||
import struct
|
|
||||||
|
|
||||||
from engine.outputs.base import UdpFrameOutput, _int
|
|
||||||
|
|
||||||
DDP_PORT = 4048
|
|
||||||
DDP_FLAG_VER1 = 0x40
|
|
||||||
DDP_FLAG_PUSH = 0x01
|
|
||||||
DDP_TYPE_RGB8 = 0x0B
|
|
||||||
DDP_ID_DISPLAY = 0x01
|
|
||||||
DDP_MAX_DATA = 1440 # 480 RGB pixels; fits a 1500-byte MTU
|
|
||||||
|
|
||||||
|
|
||||||
def build_ddp_packets(data, sequence, max_data=DDP_MAX_DATA, dest_id=DDP_ID_DISPLAY):
|
|
||||||
"""Split one frame into DDP packets; PUSH set on the last."""
|
|
||||||
packets = []
|
|
||||||
total = len(data)
|
|
||||||
offset = 0
|
|
||||||
while True:
|
|
||||||
chunk = data[offset:offset + max_data]
|
|
||||||
last = offset + len(chunk) >= total
|
|
||||||
flags = DDP_FLAG_VER1 | (DDP_FLAG_PUSH if last else 0)
|
|
||||||
header = struct.pack(
|
|
||||||
">BBBBIH", flags, sequence & 0x0F, DDP_TYPE_RGB8, dest_id, offset, len(chunk)
|
|
||||||
)
|
|
||||||
packets.append(header + bytes(chunk))
|
|
||||||
offset += len(chunk)
|
|
||||||
if last:
|
|
||||||
break
|
|
||||||
return packets
|
|
||||||
|
|
||||||
|
|
||||||
class DdpOutput(UdpFrameOutput):
|
|
||||||
protocol = "ddp"
|
|
||||||
default_port = DDP_PORT
|
|
||||||
|
|
||||||
def __init__(self, cfg):
|
|
||||||
super().__init__(cfg)
|
|
||||||
self.dest_id = _int(self.cfg.get("dest_id"), DDP_ID_DISPLAY, 0, 255)
|
|
||||||
self._sequence = 0
|
|
||||||
|
|
||||||
def next_sequence(self):
|
|
||||||
self._sequence = (self._sequence % 15) + 1
|
|
||||||
return self._sequence
|
|
||||||
|
|
||||||
def packets_for(self, payload):
|
|
||||||
return build_ddp_packets(payload, self.next_sequence(), dest_id=self.dest_id)
|
|
||||||
|
|
||||||
async def _send_prepared(self, payload):
|
|
||||||
for packet in self.packets_for(payload):
|
|
||||||
self.sendto(packet)
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
"""USB-DMX output via pyserial (one universe, 512 channels).
|
|
||||||
|
|
||||||
Modes:
|
|
||||||
enttec_pro Enttec DMX USB Pro: 0x7E, label 6, len LE, start code + data, 0xE7
|
|
||||||
open_dmx FTDI "Open DMX": 250000 baud 8N2, break, MAB, start code + 512 slots
|
|
||||||
|
|
||||||
Pixels start at DMX channel ``channel`` (1-based). Max 170 RGB pixels.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import struct
|
|
||||||
import time
|
|
||||||
|
|
||||||
from engine.outputs.base import FrameOutput, _int
|
|
||||||
|
|
||||||
ENTTEC_SOM = 0x7E
|
|
||||||
ENTTEC_EOM = 0xE7
|
|
||||||
ENTTEC_LABEL_SEND_DMX = 6
|
|
||||||
DMX_CHANNELS = 512
|
|
||||||
|
|
||||||
|
|
||||||
def dmx_universe(payload, channel=1):
|
|
||||||
"""512-slot universe with ``payload`` starting at 1-based ``channel``."""
|
|
||||||
start = max(1, int(channel)) - 1
|
|
||||||
universe = bytearray(DMX_CHANNELS)
|
|
||||||
data = bytes(payload[: max(0, DMX_CHANNELS - start)])
|
|
||||||
universe[start:start + len(data)] = data
|
|
||||||
return bytes(universe)
|
|
||||||
|
|
||||||
|
|
||||||
def build_enttec_pro(universe):
|
|
||||||
body = b"\x00" + bytes(universe) # start code 0
|
|
||||||
return bytes((ENTTEC_SOM, ENTTEC_LABEL_SEND_DMX)) + struct.pack("<H", len(body)) + body + bytes((ENTTEC_EOM,))
|
|
||||||
|
|
||||||
|
|
||||||
class DmxSerialOutput(FrameOutput):
|
|
||||||
protocol = "dmx_serial"
|
|
||||||
keepalive_s = 0.1
|
|
||||||
|
|
||||||
def __init__(self, cfg, serial_factory=None):
|
|
||||||
super().__init__(cfg)
|
|
||||||
self.serial_port = str(self.cfg.get("serial_port") or "/dev/ttyUSB0")
|
|
||||||
mode = str(self.cfg.get("dmx_mode") or "enttec_pro").lower()
|
|
||||||
self.mode = mode if mode in ("enttec_pro", "open_dmx") else "enttec_pro"
|
|
||||||
self.channel = _int(self.cfg.get("channel"), 1, 1, DMX_CHANNELS)
|
|
||||||
self.fps = min(self.fps, 44) # DMX512 refresh ceiling
|
|
||||||
self._serial_factory = serial_factory
|
|
||||||
self._ser = None
|
|
||||||
self._lock = asyncio.Lock()
|
|
||||||
|
|
||||||
def _open_serial(self):
|
|
||||||
if self._serial_factory is not None:
|
|
||||||
return self._serial_factory(self)
|
|
||||||
import serial # pyserial
|
|
||||||
|
|
||||||
if self.mode == "open_dmx":
|
|
||||||
return serial.Serial(
|
|
||||||
self.serial_port, baudrate=250000, bytesize=8,
|
|
||||||
parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_TWO, timeout=0.1,
|
|
||||||
)
|
|
||||||
return serial.Serial(self.serial_port, baudrate=57600, timeout=0.1)
|
|
||||||
|
|
||||||
async def open(self):
|
|
||||||
if self._ser is None:
|
|
||||||
self._ser = await asyncio.to_thread(self._open_serial)
|
|
||||||
|
|
||||||
def frame_bytes(self, payload):
|
|
||||||
universe = dmx_universe(payload, self.channel)
|
|
||||||
if self.mode == "enttec_pro":
|
|
||||||
return build_enttec_pro(universe)
|
|
||||||
return b"\x00" + universe
|
|
||||||
|
|
||||||
def _write(self, data):
|
|
||||||
ser = self._ser
|
|
||||||
if self.mode == "open_dmx":
|
|
||||||
ser.break_condition = True
|
|
||||||
time.sleep(0.000176) # >= 88 us break
|
|
||||||
ser.break_condition = False
|
|
||||||
time.sleep(0.000012) # >= 8 us mark-after-break
|
|
||||||
ser.write(data)
|
|
||||||
self.stats.packets += 1
|
|
||||||
self.stats.bytes += len(data)
|
|
||||||
|
|
||||||
async def _send_prepared(self, payload):
|
|
||||||
async with self._lock:
|
|
||||||
if self._ser is None:
|
|
||||||
await self.open()
|
|
||||||
await asyncio.to_thread(self._write, self.frame_bytes(payload))
|
|
||||||
|
|
||||||
async def close(self):
|
|
||||||
await super().close()
|
|
||||||
if self._ser is not None:
|
|
||||||
try:
|
|
||||||
self._ser.close()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
self._ser = None
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
"""Preset output for our own ESP32 led-drivers (Wi-Fi and ESP-NOW).
|
|
||||||
|
|
||||||
The firmware renders patterns itself, so the engine only sends the preset
|
|
||||||
definition followed by a ``select`` for the zone's device names — the same
|
|
||||||
two-message sequence the UI posts to ``/presets/push`` today.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
|
|
||||||
from engine.outputs.base import PresetOutput
|
|
||||||
from models.device import Device
|
|
||||||
from models.transport import get_current_sender
|
|
||||||
from util.driver_delivery import deliver_json_messages
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_device_macs(names, devices=None):
|
|
||||||
"""Zone device names → MACs, one distinct device per repeated name (as zones.js)."""
|
|
||||||
devices = devices if devices is not None else Device()
|
|
||||||
used = set()
|
|
||||||
rows = []
|
|
||||||
for raw in names or []:
|
|
||||||
name = str(raw or "").strip()
|
|
||||||
if not name:
|
|
||||||
continue
|
|
||||||
for mac, doc in devices.items():
|
|
||||||
if mac in used or not isinstance(doc, dict):
|
|
||||||
continue
|
|
||||||
if str(doc.get("name") or "").strip() == name:
|
|
||||||
used.add(mac)
|
|
||||||
rows.append((name, mac))
|
|
||||||
break
|
|
||||||
return rows
|
|
||||||
|
|
||||||
|
|
||||||
class DriverOutput(PresetOutput):
|
|
||||||
protocol = "driver"
|
|
||||||
|
|
||||||
def __init__(self, names, cfg=None, sender_getter=None, devices=None, save=False, delay_s=0.05):
|
|
||||||
super().__init__(cfg)
|
|
||||||
self.names = [str(n).strip() for n in (names or []) if str(n or "").strip()]
|
|
||||||
self.name = self.cfg.get("name") or ",".join(self.names) or "driver"
|
|
||||||
self._sender_getter = sender_getter or get_current_sender
|
|
||||||
self._devices = devices
|
|
||||||
self.save = bool(save)
|
|
||||||
self.delay_s = delay_s
|
|
||||||
|
|
||||||
def messages_for(self, preset_id, preset_payload):
|
|
||||||
pid = str(preset_id)
|
|
||||||
preset_msg = {"v": "1", "presets": {pid: preset_payload}}
|
|
||||||
if self.save:
|
|
||||||
preset_msg["save"] = True
|
|
||||||
messages = [json.dumps(preset_msg)]
|
|
||||||
names = list(dict.fromkeys(self.names))
|
|
||||||
if names:
|
|
||||||
messages.append(json.dumps({"v": "1", "select": {n: [pid] for n in names}}))
|
|
||||||
return messages
|
|
||||||
|
|
||||||
async def apply(self, preset_id, preset_payload):
|
|
||||||
sender = self._sender_getter()
|
|
||||||
if sender is None:
|
|
||||||
self.stats.error(RuntimeError("transport not configured"))
|
|
||||||
return 0
|
|
||||||
devices = self._devices if self._devices is not None else Device()
|
|
||||||
macs = [mac for _name, mac in resolve_device_macs(self.names, devices)]
|
|
||||||
try:
|
|
||||||
delivered, _ = await deliver_json_messages(
|
|
||||||
sender, self.messages_for(preset_id, preset_payload), macs or None, devices,
|
|
||||||
delay_s=self.delay_s,
|
|
||||||
)
|
|
||||||
self.stats.frames += 1
|
|
||||||
self.stats.packets += delivered
|
|
||||||
return delivered
|
|
||||||
except Exception as e:
|
|
||||||
self.stats.error(e)
|
|
||||||
return 0
|
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
"""sACN / E1.31 output — UDP 5568, multicast 239.255.<hi>.<lo> by default.
|
|
||||||
|
|
||||||
One data packet per universe (170 RGB pixels each), 126-byte header +
|
|
||||||
start code + up to 512 slots. Layer lengths are 12-bit, OR'd with 0x7000
|
|
||||||
(flags).
|
|
||||||
"""
|
|
||||||
|
|
||||||
import socket
|
|
||||||
import struct
|
|
||||||
import uuid
|
|
||||||
|
|
||||||
from engine.outputs.base import UdpFrameOutput, _bool, _int, split_universes
|
|
||||||
|
|
||||||
SACN_PORT = 5568
|
|
||||||
ACN_PACKET_ID = b"ASC-E1.17\x00\x00\x00"
|
|
||||||
VECTOR_ROOT_E131_DATA = 0x00000004
|
|
||||||
VECTOR_E131_DATA_PACKET = 0x00000002
|
|
||||||
VECTOR_DMP_SET_PROPERTY = 0x02
|
|
||||||
DEFAULT_PRIORITY = 100
|
|
||||||
|
|
||||||
|
|
||||||
def multicast_address(universe):
|
|
||||||
return f"239.255.{(universe >> 8) & 0xFF}.{universe & 0xFF}"
|
|
||||||
|
|
||||||
|
|
||||||
def stable_cid(seed):
|
|
||||||
"""Deterministic 16-byte CID from a name, so receivers see one source."""
|
|
||||||
return uuid.uuid5(uuid.NAMESPACE_URL, f"led-controller/sacn/{seed}").bytes
|
|
||||||
|
|
||||||
|
|
||||||
def build_e131(universe, data, sequence, cid, source_name="led-controller", priority=DEFAULT_PRIORITY):
|
|
||||||
slots = b"\x00" + bytes(data[:512]) # start code 0 + DMX
|
|
||||||
prop_count = len(slots)
|
|
||||||
dmp_len = 10 + prop_count
|
|
||||||
framing_len = 77 + dmp_len
|
|
||||||
root_len = 22 + framing_len
|
|
||||||
name = source_name.encode("utf-8")[:63].ljust(64, b"\x00")
|
|
||||||
|
|
||||||
root = (
|
|
||||||
struct.pack(">HH", 0x0010, 0x0000)
|
|
||||||
+ ACN_PACKET_ID
|
|
||||||
+ struct.pack(">HI", 0x7000 | root_len, VECTOR_ROOT_E131_DATA)
|
|
||||||
+ bytes(cid)
|
|
||||||
)
|
|
||||||
framing = (
|
|
||||||
struct.pack(">HI", 0x7000 | framing_len, VECTOR_E131_DATA_PACKET)
|
|
||||||
+ name
|
|
||||||
+ struct.pack(">BHBBH", priority & 0xFF, 0, sequence & 0xFF, 0, universe & 0xFFFF)
|
|
||||||
)
|
|
||||||
dmp = (
|
|
||||||
struct.pack(">HBBHHH", 0x7000 | dmp_len, VECTOR_DMP_SET_PROPERTY, 0xA1, 0x0000, 0x0001, prop_count)
|
|
||||||
+ slots
|
|
||||||
)
|
|
||||||
return root + framing + dmp
|
|
||||||
|
|
||||||
|
|
||||||
class SacnOutput(UdpFrameOutput):
|
|
||||||
protocol = "sacn"
|
|
||||||
default_port = SACN_PORT
|
|
||||||
|
|
||||||
def __init__(self, cfg):
|
|
||||||
super().__init__(cfg)
|
|
||||||
self.universe = _int(self.cfg.get("universe"), 1, 1, 63999)
|
|
||||||
self.priority = _int(self.cfg.get("priority"), DEFAULT_PRIORITY, 0, 200)
|
|
||||||
self.multicast = not self.host or _bool(self.cfg.get("multicast"), False)
|
|
||||||
self.source_name = str(self.cfg.get("source_name") or f"led-controller {self.name}")
|
|
||||||
self.cid = stable_cid(self.cfg.get("cid") or self.cfg.get("id") or self.name)
|
|
||||||
self._sequences = {}
|
|
||||||
|
|
||||||
def _make_socket(self):
|
|
||||||
sock = super()._make_socket()
|
|
||||||
if self.multicast:
|
|
||||||
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 8)
|
|
||||||
return sock
|
|
||||||
|
|
||||||
def _next_sequence(self, universe):
|
|
||||||
seq = (self._sequences.get(universe, -1) + 1) & 0xFF
|
|
||||||
self._sequences[universe] = seq
|
|
||||||
return seq
|
|
||||||
|
|
||||||
def packets_for(self, payload):
|
|
||||||
out = []
|
|
||||||
for i, chunk in enumerate(split_universes(payload)):
|
|
||||||
u = self.universe + i
|
|
||||||
pkt = build_e131(u, chunk, self._next_sequence(u), self.cid, self.source_name, self.priority)
|
|
||||||
addr = (multicast_address(u), self.port) if self.multicast else self.destination()
|
|
||||||
out.append((pkt, addr))
|
|
||||||
return out
|
|
||||||
|
|
||||||
async def _send_prepared(self, payload):
|
|
||||||
for packet, addr in self.packets_for(payload):
|
|
||||||
self.sendto(packet, addr)
|
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
"""Load the led-driver pattern modules (and its Preset class) for Pi-side rendering.
|
|
||||||
|
|
||||||
Mirrors ``Presets._load_dynamic_patterns`` in ``led-driver/src/presets.py``:
|
|
||||||
every ``*.py`` in the patterns dir except ``__init__.py``/``main.py``, using
|
|
||||||
the first class in the module that has ``run()``.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import importlib.util
|
|
||||||
import os
|
|
||||||
import threading
|
|
||||||
|
|
||||||
from engine import mpcompat
|
|
||||||
from util.driver_patterns import driver_patterns_dir
|
|
||||||
|
|
||||||
_MODULE_PREFIX = "led_driver_patterns."
|
|
||||||
|
|
||||||
|
|
||||||
def _load_module(name, path):
|
|
||||||
spec = importlib.util.spec_from_file_location(name, path)
|
|
||||||
module = importlib.util.module_from_spec(spec)
|
|
||||||
spec.loader.exec_module(module)
|
|
||||||
return module
|
|
||||||
|
|
||||||
|
|
||||||
class _FallbackPreset:
|
|
||||||
"""Used only when led-driver/src/preset.py is not deployed next to the patterns."""
|
|
||||||
|
|
||||||
_aliases = {"pattern": "p", "colors": "c", "delay": "d", "brightness": "b", "auto": "a"}
|
|
||||||
|
|
||||||
def __init__(self, data):
|
|
||||||
self.p, self.d, self.b, self.c, self.a = "off", 100, 127, [(255, 255, 255)], True
|
|
||||||
self.n1 = self.n2 = self.n3 = self.n4 = self.n5 = self.n6 = 0
|
|
||||||
self.edit(data)
|
|
||||||
|
|
||||||
def edit(self, data=None):
|
|
||||||
for key, value in (data or {}).items():
|
|
||||||
key = self._aliases.get(key, key)
|
|
||||||
if key in ("d", "b", "n1", "n2", "n3", "n4", "n5", "n6"):
|
|
||||||
try:
|
|
||||||
value = max(0, int(value))
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
continue
|
|
||||||
if key == "b":
|
|
||||||
value = min(255, value)
|
|
||||||
elif key == "a":
|
|
||||||
value = bool(value)
|
|
||||||
elif key not in ("p", "c"):
|
|
||||||
continue
|
|
||||||
setattr(self, key, value)
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
class PatternLibrary:
|
|
||||||
def __init__(self, patterns_dir=None):
|
|
||||||
self.patterns_dir = patterns_dir or driver_patterns_dir()
|
|
||||||
self._lock = threading.Lock()
|
|
||||||
self.classes = {}
|
|
||||||
self.errors = {}
|
|
||||||
self.preset_class = _FallbackPreset
|
|
||||||
self.load()
|
|
||||||
|
|
||||||
def load(self):
|
|
||||||
mpcompat.install()
|
|
||||||
classes, errors = {}, {}
|
|
||||||
try:
|
|
||||||
files = sorted(os.listdir(self.patterns_dir))
|
|
||||||
except OSError as e:
|
|
||||||
files = []
|
|
||||||
errors["*"] = repr(e)
|
|
||||||
for filename in files:
|
|
||||||
if not filename.endswith(".py") or filename in ("__init__.py", "main.py"):
|
|
||||||
continue
|
|
||||||
base = filename[:-3]
|
|
||||||
try:
|
|
||||||
module = _load_module(_MODULE_PREFIX + base, os.path.join(self.patterns_dir, filename))
|
|
||||||
except Exception as e:
|
|
||||||
errors[base] = repr(e)
|
|
||||||
continue
|
|
||||||
for attr_name in dir(module):
|
|
||||||
attr = getattr(module, attr_name)
|
|
||||||
if isinstance(attr, type) and hasattr(attr, "run"):
|
|
||||||
classes[base] = attr
|
|
||||||
break
|
|
||||||
preset_cls = _FallbackPreset
|
|
||||||
preset_path = os.path.join(os.path.dirname(self.patterns_dir), "preset.py")
|
|
||||||
if os.path.isfile(preset_path):
|
|
||||||
try:
|
|
||||||
preset_cls = _load_module("led_driver_preset", preset_path).Preset
|
|
||||||
except Exception as e:
|
|
||||||
errors["preset.py"] = repr(e)
|
|
||||||
with self._lock:
|
|
||||||
self.classes = classes
|
|
||||||
self.errors = errors
|
|
||||||
self.preset_class = preset_cls
|
|
||||||
return self
|
|
||||||
|
|
||||||
reload = load
|
|
||||||
|
|
||||||
def ids(self):
|
|
||||||
return sorted(set(self.classes) | {"on", "off"})
|
|
||||||
|
|
||||||
def get(self, pattern_id):
|
|
||||||
return self.classes.get(pattern_id)
|
|
||||||
|
|
||||||
def make_preset(self, payload):
|
|
||||||
return self.preset_class(dict(payload or {}))
|
|
||||||
|
|
||||||
|
|
||||||
_library = None
|
|
||||||
|
|
||||||
|
|
||||||
def get_library():
|
|
||||||
global _library
|
|
||||||
if _library is None:
|
|
||||||
_library = PatternLibrary()
|
|
||||||
return _library
|
|
||||||
@@ -1,148 +0,0 @@
|
|||||||
"""Per-zone player: render on a thread, stream frames to pixel outputs.
|
|
||||||
|
|
||||||
Modelled on portal's ``PatternPlayer``: the asyncio side only ships frames.
|
|
||||||
The render thread runs the driver pattern exactly like the ESP32 main loop,
|
|
||||||
and each ``n.write()`` wakes the sender, which pushes the newest frame to
|
|
||||||
every output (coalescing writes faster than the outputs' fps).
|
|
||||||
"""
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import time
|
|
||||||
|
|
||||||
from engine.outputs import open_output
|
|
||||||
from engine.renderer import Renderer, RenderThread
|
|
||||||
|
|
||||||
SEND_TIMEOUT_S = 0.05
|
|
||||||
|
|
||||||
|
|
||||||
def _default_driver_output(names):
|
|
||||||
from engine.outputs.driver import DriverOutput # pulls in the Wi-Fi/serial stack
|
|
||||||
|
|
||||||
return DriverOutput(names)
|
|
||||||
|
|
||||||
|
|
||||||
class ZonePlayer:
|
|
||||||
def __init__(self, targets, library, brightness_getter=None, output_factory=None,
|
|
||||||
driver_factory=None):
|
|
||||||
self.targets = targets
|
|
||||||
self.zone_id = targets.zone_id
|
|
||||||
self.library = library
|
|
||||||
self._brightness = brightness_getter or (lambda: 255)
|
|
||||||
make_output = output_factory or open_output
|
|
||||||
self.frame_outputs = [make_output(cfg) for cfg in targets.frame_cfgs]
|
|
||||||
make_driver = driver_factory or _default_driver_output
|
|
||||||
self.driver_output = make_driver(targets.driver_names) if targets.driver_names else None
|
|
||||||
self.preset_id = None
|
|
||||||
self.started_at = None
|
|
||||||
self._loop = None
|
|
||||||
self._latest = None
|
|
||||||
self._frame_event = None
|
|
||||||
self._sender_task = None
|
|
||||||
self._render = None
|
|
||||||
self.renderer = None
|
|
||||||
|
|
||||||
@property
|
|
||||||
def fps(self):
|
|
||||||
return min((o.fps for o in self.frame_outputs), default=0)
|
|
||||||
|
|
||||||
async def start(self):
|
|
||||||
self._loop = asyncio.get_running_loop()
|
|
||||||
if not self.frame_outputs:
|
|
||||||
return
|
|
||||||
for out in self.frame_outputs:
|
|
||||||
try:
|
|
||||||
await out.open()
|
|
||||||
except Exception as e:
|
|
||||||
out.stats.error(e)
|
|
||||||
self._frame_event = asyncio.Event()
|
|
||||||
self.renderer = Renderer(self.library, self.targets.frame_length, on_frame=self._on_frame_thread)
|
|
||||||
self._render = RenderThread(self.renderer, name=f"engine-zone-{self.zone_id}").start()
|
|
||||||
self._sender_task = asyncio.create_task(self._send_loop(), name=f"engine-send-{self.zone_id}")
|
|
||||||
|
|
||||||
def _on_frame_thread(self, frame):
|
|
||||||
loop = self._loop
|
|
||||||
if loop is None or loop.is_closed():
|
|
||||||
return
|
|
||||||
try:
|
|
||||||
loop.call_soon_threadsafe(self._frame_ready, frame)
|
|
||||||
except RuntimeError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def _frame_ready(self, frame):
|
|
||||||
self._latest = frame
|
|
||||||
if self._frame_event is not None:
|
|
||||||
self._frame_event.set()
|
|
||||||
|
|
||||||
async def send_frame(self, frame):
|
|
||||||
level = self._brightness()
|
|
||||||
tasks = []
|
|
||||||
for out in self.frame_outputs:
|
|
||||||
start = out.pixel_offset * 3
|
|
||||||
tasks.append(asyncio.ensure_future(out.send(frame[start:start + out.pixel_count * 3], level)))
|
|
||||||
if not tasks:
|
|
||||||
return
|
|
||||||
_done, pending = await asyncio.wait(tasks, timeout=SEND_TIMEOUT_S)
|
|
||||||
for t in pending:
|
|
||||||
t.cancel()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def keepalive_s(self):
|
|
||||||
return min((o.keepalive_s for o in self.frame_outputs), default=1.0)
|
|
||||||
|
|
||||||
async def _send_loop(self):
|
|
||||||
interval = 1.0 / max(1, self.fps)
|
|
||||||
keepalive = self.keepalive_s
|
|
||||||
while True:
|
|
||||||
try:
|
|
||||||
await asyncio.wait_for(self._frame_event.wait(), timeout=keepalive)
|
|
||||||
except asyncio.TimeoutError:
|
|
||||||
pass # no new frame: resend the last one
|
|
||||||
self._frame_event.clear()
|
|
||||||
started = time.monotonic()
|
|
||||||
frame = self._latest
|
|
||||||
if frame is not None:
|
|
||||||
await self.send_frame(frame)
|
|
||||||
rest = interval - (time.monotonic() - started)
|
|
||||||
if rest > 0:
|
|
||||||
await asyncio.sleep(rest)
|
|
||||||
|
|
||||||
async def apply(self, preset_id, payload, drivers=True):
|
|
||||||
self.preset_id = str(preset_id)
|
|
||||||
self.started_at = time.time()
|
|
||||||
if self._render is not None:
|
|
||||||
self._render.apply(preset_id, payload)
|
|
||||||
if drivers and self.driver_output is not None:
|
|
||||||
await self.driver_output.apply(preset_id, payload)
|
|
||||||
|
|
||||||
async def stop(self):
|
|
||||||
if self._render is not None:
|
|
||||||
self._render.stop()
|
|
||||||
self._render = None
|
|
||||||
if self._sender_task is not None:
|
|
||||||
self._sender_task.cancel()
|
|
||||||
try:
|
|
||||||
await self._sender_task
|
|
||||||
except (asyncio.CancelledError, Exception):
|
|
||||||
pass
|
|
||||||
self._sender_task = None
|
|
||||||
for out in self.frame_outputs:
|
|
||||||
try:
|
|
||||||
await out.close()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
if self.driver_output is not None:
|
|
||||||
await self.driver_output.close()
|
|
||||||
|
|
||||||
def status(self):
|
|
||||||
r = self.renderer
|
|
||||||
return {
|
|
||||||
"zone_id": self.zone_id,
|
|
||||||
"preset_id": self.preset_id,
|
|
||||||
"pattern": r.pattern_id if r else None,
|
|
||||||
"error": r.error if r else None,
|
|
||||||
"started_at": self.started_at,
|
|
||||||
"frame_length": self.targets.frame_length,
|
|
||||||
"fps": self.fps,
|
|
||||||
"outputs": [o.status() for o in self.frame_outputs]
|
|
||||||
+ ([self.driver_output.status()] if self.driver_output else []),
|
|
||||||
}
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
"""Resolve stored presets into driver payloads (short keys, palette refs applied)."""
|
|
||||||
|
|
||||||
from models.pallet import Palette
|
|
||||||
from models.preset import Preset as PresetModel
|
|
||||||
from models.profile import Profile
|
|
||||||
from util.espnow_message import build_preset_dict
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_palette_colors(colors, palette_refs, palette):
|
|
||||||
"""Same rule as presets.js ``resolveColorsWithPaletteRefs``."""
|
|
||||||
base = list(colors) if isinstance(colors, list) else []
|
|
||||||
refs = palette_refs if isinstance(palette_refs, list) else []
|
|
||||||
pal = palette if isinstance(palette, list) else []
|
|
||||||
out = []
|
|
||||||
for idx, color in enumerate(base):
|
|
||||||
ref = refs[idx] if idx < len(refs) else None
|
|
||||||
try:
|
|
||||||
ref = int(ref)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
ref = None
|
|
||||||
if ref is not None and 0 <= ref < len(pal) and pal[ref]:
|
|
||||||
out.append(pal[ref])
|
|
||||||
else:
|
|
||||||
out.append(color)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def profile_palette(profile_id):
|
|
||||||
if profile_id is None:
|
|
||||||
return []
|
|
||||||
profile = Profile().read(profile_id) or {}
|
|
||||||
palette_id = profile.get("palette_id")
|
|
||||||
if palette_id is None:
|
|
||||||
return []
|
|
||||||
return Palette().read(palette_id)
|
|
||||||
|
|
||||||
|
|
||||||
def preset_payload(preset_id, preset_data=None):
|
|
||||||
"""Driver payload (``p``, ``c``, ``d``, ``b``, ``a``, ``n1``..) for a stored preset."""
|
|
||||||
data = preset_data if preset_data is not None else PresetModel().read(preset_id)
|
|
||||||
if not data:
|
|
||||||
return None
|
|
||||||
data = dict(data)
|
|
||||||
refs = data.get("palette_refs")
|
|
||||||
if refs:
|
|
||||||
data["colors"] = resolve_palette_colors(
|
|
||||||
data.get("colors") or [], refs, profile_palette(data.get("profile_id"))
|
|
||||||
)
|
|
||||||
return build_preset_dict(data)
|
|
||||||
|
|
||||||
|
|
||||||
def hex_to_rgb(color):
|
|
||||||
if isinstance(color, (list, tuple)) and len(color) >= 3:
|
|
||||||
return tuple(max(0, min(255, int(c))) for c in color[:3])
|
|
||||||
s = str(color or "").strip().lstrip("#")
|
|
||||||
if len(s) == 3:
|
|
||||||
s = "".join(ch * 2 for ch in s)
|
|
||||||
try:
|
|
||||||
return (int(s[0:2], 16), int(s[2:4], 16), int(s[4:6], 16))
|
|
||||||
except (ValueError, IndexError):
|
|
||||||
return (255, 255, 255)
|
|
||||||
@@ -1,157 +0,0 @@
|
|||||||
"""Run one led-driver pattern generator and collect the frames it writes.
|
|
||||||
|
|
||||||
``Renderer`` is synchronous and clock-agnostic (tests drive it with a
|
|
||||||
``VirtualClock``). ``RenderThread`` runs a Renderer on its own thread with the
|
|
||||||
real clock, the way the ESP32 main loop calls ``Presets.tick()``: patterns may
|
|
||||||
block in ``utime.sleep_ms`` between writes and every ``n.write()`` becomes a frame.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import threading
|
|
||||||
import time
|
|
||||||
import traceback
|
|
||||||
import types
|
|
||||||
|
|
||||||
from engine import mpcompat
|
|
||||||
from engine.frame_driver import FrameDriver
|
|
||||||
from engine.presets import hex_to_rgb
|
|
||||||
|
|
||||||
BUILTIN_PATTERNS = ("on", "off")
|
|
||||||
|
|
||||||
|
|
||||||
class Renderer:
|
|
||||||
def __init__(self, library, num_leds, on_frame=None):
|
|
||||||
self.library = library
|
|
||||||
self.on_frame = on_frame
|
|
||||||
self.driver = FrameDriver(num_leds, on_write=self._frame_written)
|
|
||||||
self.preset = None
|
|
||||||
self.preset_id = None
|
|
||||||
self.pattern_id = None
|
|
||||||
self.generator = None
|
|
||||||
self.last_frame = bytes(self.driver.num_leds * 3)
|
|
||||||
self.frame_count = 0
|
|
||||||
self.error = None
|
|
||||||
|
|
||||||
def _frame_written(self, frame):
|
|
||||||
self.last_frame = frame
|
|
||||||
self.frame_count += 1
|
|
||||||
if self.on_frame is not None:
|
|
||||||
self.on_frame(frame)
|
|
||||||
|
|
||||||
def set_preset(self, preset_id, payload):
|
|
||||||
"""Select a preset, mirroring ``Presets.select`` (step reset rules included)."""
|
|
||||||
data = dict(payload or {})
|
|
||||||
colors = data.get("c", data.get("colors"))
|
|
||||||
if isinstance(colors, list):
|
|
||||||
data["c"] = [hex_to_rgb(c) for c in colors]
|
|
||||||
data.pop("colors", None)
|
|
||||||
preset = self.library.make_preset(data)
|
|
||||||
pid = str(preset_id)
|
|
||||||
if preset.p == "off" or pid != self.preset_id:
|
|
||||||
self.driver.step = 0
|
|
||||||
self.preset = preset
|
|
||||||
self.preset_id = pid
|
|
||||||
self.pattern_id = preset.p
|
|
||||||
self.error = None
|
|
||||||
self.generator = None
|
|
||||||
|
|
||||||
if preset.p in BUILTIN_PATTERNS:
|
|
||||||
getattr(self.driver, preset.p)(preset)
|
|
||||||
return True
|
|
||||||
cls = self.library.get(preset.p)
|
|
||||||
if cls is None:
|
|
||||||
self.error = f"pattern not found: {preset.p}"
|
|
||||||
self.driver.off()
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
result = cls(self.driver).run(preset)
|
|
||||||
except Exception as e:
|
|
||||||
self.error = repr(e)
|
|
||||||
return False
|
|
||||||
if isinstance(result, types.GeneratorType):
|
|
||||||
self.generator = result
|
|
||||||
return True
|
|
||||||
|
|
||||||
def tick(self):
|
|
||||||
"""Advance the pattern by one generator step (one device tick)."""
|
|
||||||
gen = self.generator
|
|
||||||
if gen is None:
|
|
||||||
return False
|
|
||||||
try:
|
|
||||||
next(gen)
|
|
||||||
return True
|
|
||||||
except StopIteration:
|
|
||||||
self.generator = None
|
|
||||||
except Exception as e:
|
|
||||||
self.error = repr(e)
|
|
||||||
print(f"[engine] pattern {self.pattern_id!r} error: {e!r}")
|
|
||||||
self.generator = None
|
|
||||||
return False
|
|
||||||
|
|
||||||
def render_virtual(self, preset_id, payload, ticks, tick_ms=1, clock=None):
|
|
||||||
"""Offline render with a virtual clock; returns the list of frames written."""
|
|
||||||
frames = []
|
|
||||||
prev_cb = self.on_frame
|
|
||||||
self.on_frame = frames.append
|
|
||||||
clock = clock or mpcompat.VirtualClock()
|
|
||||||
mpcompat.set_thread_clock(clock)
|
|
||||||
try:
|
|
||||||
self.set_preset(preset_id, payload)
|
|
||||||
for _ in range(int(ticks)):
|
|
||||||
self.tick()
|
|
||||||
clock.advance_ms(tick_ms)
|
|
||||||
finally:
|
|
||||||
mpcompat.set_thread_clock(None)
|
|
||||||
self.on_frame = prev_cb
|
|
||||||
return frames
|
|
||||||
|
|
||||||
|
|
||||||
class RenderThread:
|
|
||||||
"""Ticks a Renderer on a daemon thread; ``apply`` hot-swaps presets thread-safely."""
|
|
||||||
|
|
||||||
def __init__(self, renderer, tick_s=0.001, name="engine-render"):
|
|
||||||
self.renderer = renderer
|
|
||||||
self.tick_s = tick_s
|
|
||||||
self._pending = None
|
|
||||||
self._lock = threading.Lock()
|
|
||||||
self._wake = threading.Event()
|
|
||||||
self._stop = threading.Event()
|
|
||||||
self._thread = threading.Thread(target=self._run, name=name, daemon=True)
|
|
||||||
|
|
||||||
def start(self):
|
|
||||||
self._thread.start()
|
|
||||||
return self
|
|
||||||
|
|
||||||
def apply(self, preset_id, payload):
|
|
||||||
with self._lock:
|
|
||||||
self._pending = (preset_id, payload)
|
|
||||||
self._wake.set()
|
|
||||||
|
|
||||||
def stop(self, timeout=1.0):
|
|
||||||
self._stop.set()
|
|
||||||
self._wake.set()
|
|
||||||
if self._thread.is_alive() and threading.current_thread() is not self._thread:
|
|
||||||
self._thread.join(timeout)
|
|
||||||
|
|
||||||
def _take_pending(self):
|
|
||||||
with self._lock:
|
|
||||||
pending, self._pending = self._pending, None
|
|
||||||
return pending
|
|
||||||
|
|
||||||
def _run(self):
|
|
||||||
mpcompat.set_thread_clock(mpcompat.RealClock())
|
|
||||||
r = self.renderer
|
|
||||||
while not self._stop.is_set():
|
|
||||||
pending = self._take_pending()
|
|
||||||
if pending is not None:
|
|
||||||
try:
|
|
||||||
r.set_preset(*pending)
|
|
||||||
except Exception:
|
|
||||||
traceback.print_exc()
|
|
||||||
if r.generator is None:
|
|
||||||
# Static frame (on/off/finished): sleep until the next preset.
|
|
||||||
self._wake.wait()
|
|
||||||
self._wake.clear()
|
|
||||||
continue
|
|
||||||
r.tick()
|
|
||||||
if self.tick_s:
|
|
||||||
time.sleep(self.tick_s)
|
|
||||||
@@ -1,161 +0,0 @@
|
|||||||
"""Preset sequencer — timed chains of presets per zone (portal's SequenceRunner).
|
|
||||||
|
|
||||||
Each running sequence is an asyncio task: ``engine.play(zone, step)``,
|
|
||||||
``notify()``, ``sleep(duration_s)``, next step; loop / repeat_count decide
|
|
||||||
when it ends. Cuts are hard. At most one sequence runs per zone.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import time
|
|
||||||
|
|
||||||
|
|
||||||
class SequenceRunner:
|
|
||||||
def __init__(self, engine, sequences_model=None, notify=None):
|
|
||||||
self.engine = engine
|
|
||||||
self._model = sequences_model
|
|
||||||
self.notify = notify
|
|
||||||
self._tasks = {} # zone_id -> (sequence_id, task)
|
|
||||||
self._state = {} # sequence_id -> status dict
|
|
||||||
|
|
||||||
@property
|
|
||||||
def model(self):
|
|
||||||
if self._model is None:
|
|
||||||
from models.squence import Sequence
|
|
||||||
self._model = Sequence()
|
|
||||||
return self._model
|
|
||||||
|
|
||||||
def zone_for(self, sequence_id):
|
|
||||||
for zone_id, (sid, _task) in self._tasks.items():
|
|
||||||
if sid == str(sequence_id):
|
|
||||||
return zone_id
|
|
||||||
return None
|
|
||||||
|
|
||||||
async def play(self, sequence_id):
|
|
||||||
from engine.core import EngineError
|
|
||||||
|
|
||||||
sid = str(sequence_id)
|
|
||||||
seq = self.model.read(sid)
|
|
||||||
if not seq:
|
|
||||||
raise EngineError("Sequence not found", 404)
|
|
||||||
zone_id = seq.get("zone_id")
|
|
||||||
if zone_id in (None, ""):
|
|
||||||
raise EngineError("Sequence has no zone_id", 400)
|
|
||||||
if not seq.get("steps"):
|
|
||||||
raise EngineError("Sequence has no steps", 400)
|
|
||||||
zone_id = str(zone_id)
|
|
||||||
await self.stop_zone(zone_id)
|
|
||||||
current = self.zone_for(sid)
|
|
||||||
if current is not None:
|
|
||||||
await self.stop_zone(current)
|
|
||||||
self.model.update(sid, {"active": True})
|
|
||||||
self._state[sid] = {
|
|
||||||
"sequence_id": sid,
|
|
||||||
"zone_id": zone_id,
|
|
||||||
"step_index": 0,
|
|
||||||
"pass": 0,
|
|
||||||
"preset_id": None,
|
|
||||||
"started_at": time.time(),
|
|
||||||
"next_at": None,
|
|
||||||
"running": True,
|
|
||||||
}
|
|
||||||
task = asyncio.create_task(self._run(sid, zone_id), name=f"sequence-{sid}")
|
|
||||||
self._tasks[zone_id] = (sid, task)
|
|
||||||
return self._state[sid]
|
|
||||||
|
|
||||||
async def _run(self, sid, zone_id):
|
|
||||||
state = self._state[sid]
|
|
||||||
passes = 0
|
|
||||||
loop = asyncio.get_running_loop()
|
|
||||||
# Steps are scheduled on absolute deadlines so send latency doesn't drift the timing.
|
|
||||||
deadline = loop.time()
|
|
||||||
try:
|
|
||||||
while True:
|
|
||||||
seq = self.model.read(sid) or {}
|
|
||||||
steps = seq.get("steps") or []
|
|
||||||
if not steps:
|
|
||||||
break
|
|
||||||
for index, step in enumerate(steps):
|
|
||||||
duration = float(step.get("duration_s") or 5)
|
|
||||||
state.update(step_index=index, preset_id=str(step.get("preset_id")),
|
|
||||||
next_at=time.time() + duration)
|
|
||||||
try:
|
|
||||||
await self.engine.play(zone_id, step.get("preset_id"), source="sequence")
|
|
||||||
except Exception as e:
|
|
||||||
state["error"] = str(e)
|
|
||||||
print(f"[sequence {sid}] step {index} failed: {e}")
|
|
||||||
self._notify(state)
|
|
||||||
deadline += duration
|
|
||||||
await asyncio.sleep(max(0.0, deadline - loop.time()))
|
|
||||||
passes += 1
|
|
||||||
state["pass"] = passes
|
|
||||||
if not seq.get("loop", True):
|
|
||||||
break
|
|
||||||
repeat = int(seq.get("repeat_count") or 0)
|
|
||||||
if repeat and passes >= repeat:
|
|
||||||
break
|
|
||||||
except asyncio.CancelledError:
|
|
||||||
raise
|
|
||||||
finally:
|
|
||||||
state.update(running=False, next_at=None)
|
|
||||||
entry = self._tasks.get(zone_id)
|
|
||||||
if entry is not None and entry[0] == sid and entry[1] is asyncio.current_task():
|
|
||||||
self._tasks.pop(zone_id, None)
|
|
||||||
# Finished on its own (not cancelled): no longer active.
|
|
||||||
self.model.update(sid, {"active": False})
|
|
||||||
self._notify(state)
|
|
||||||
|
|
||||||
def _notify(self, state):
|
|
||||||
if self.notify is not None:
|
|
||||||
try:
|
|
||||||
self.notify(dict(state))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
async def _cancel(self, zone_id, persist):
|
|
||||||
entry = self._tasks.pop(str(zone_id), None)
|
|
||||||
if entry is None:
|
|
||||||
return None
|
|
||||||
sid, task = entry
|
|
||||||
task.cancel()
|
|
||||||
try:
|
|
||||||
await task
|
|
||||||
except (asyncio.CancelledError, Exception):
|
|
||||||
pass
|
|
||||||
if persist:
|
|
||||||
self.model.update(sid, {"active": False})
|
|
||||||
state = self._state.get(sid)
|
|
||||||
if state is not None:
|
|
||||||
state.update(running=False, next_at=None)
|
|
||||||
return sid
|
|
||||||
|
|
||||||
async def stop(self, sequence_id):
|
|
||||||
zone_id = self.zone_for(sequence_id)
|
|
||||||
if zone_id is None:
|
|
||||||
self.model.update(str(sequence_id), {"active": False})
|
|
||||||
return False
|
|
||||||
await self._cancel(zone_id, persist=True)
|
|
||||||
return True
|
|
||||||
|
|
||||||
async def stop_zone(self, zone_id):
|
|
||||||
return await self._cancel(zone_id, persist=True)
|
|
||||||
|
|
||||||
async def stop_all(self, persist=False):
|
|
||||||
"""Cancel every sequence; ``persist=False`` keeps ``active`` so they resume on restart."""
|
|
||||||
for zone_id in list(self._tasks):
|
|
||||||
await self._cancel(zone_id, persist=persist)
|
|
||||||
|
|
||||||
async def resume_active(self):
|
|
||||||
started = []
|
|
||||||
for sid in list(self.model.list()):
|
|
||||||
seq = self.model.read(sid) or {}
|
|
||||||
if seq.get("active"):
|
|
||||||
try:
|
|
||||||
await self.play(sid)
|
|
||||||
started.append(sid)
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[sequence {sid}] resume failed: {e}")
|
|
||||||
self.model.update(sid, {"active": False})
|
|
||||||
return started
|
|
||||||
|
|
||||||
def status(self):
|
|
||||||
return {sid: dict(s) for sid, s in self._state.items()}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
"""Resolve a zone's ``names`` into pixel outputs and ESP32 driver names.
|
|
||||||
|
|
||||||
A name that matches an enabled record in ``db/output.json`` becomes a frame
|
|
||||||
output (the Pi renders for it); every other name is treated as an led-driver
|
|
||||||
device name and gets presets + ``select`` as today.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
|
|
||||||
from models.output import Output
|
|
||||||
from models.zone import Zone
|
|
||||||
|
|
||||||
|
|
||||||
class ZoneTargets:
|
|
||||||
def __init__(self, zone_id, frame_cfgs, driver_names):
|
|
||||||
self.zone_id = str(zone_id)
|
|
||||||
self.frame_cfgs = frame_cfgs
|
|
||||||
self.driver_names = driver_names
|
|
||||||
|
|
||||||
@property
|
|
||||||
def frame_length(self):
|
|
||||||
"""Pixels the renderer must produce: outputs at offset 0 mirror the frame start."""
|
|
||||||
return max(
|
|
||||||
(int(c.get("pixel_offset") or 0) + int(c.get("pixel_count") or 0) for c in self.frame_cfgs),
|
|
||||||
default=0,
|
|
||||||
)
|
|
||||||
|
|
||||||
def signature(self):
|
|
||||||
return json.dumps(
|
|
||||||
{"frames": self.frame_cfgs, "drivers": self.driver_names}, sort_keys=True
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def zone_names(zone):
|
|
||||||
names = zone.get("names") if isinstance(zone, dict) else None
|
|
||||||
return [str(n).strip() for n in (names or []) if str(n or "").strip()]
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_zone(zone_id, zones=None, outputs=None):
|
|
||||||
zones = zones if zones is not None else Zone()
|
|
||||||
outputs = outputs if outputs is not None else Output()
|
|
||||||
zone = zones.read(zone_id)
|
|
||||||
if not zone:
|
|
||||||
return None
|
|
||||||
frame_cfgs, driver_names, seen = [], [], set()
|
|
||||||
for name in zone_names(zone):
|
|
||||||
matches = [o for o in outputs.by_name(name) if o.get("enabled", True)]
|
|
||||||
if matches:
|
|
||||||
for cfg in matches:
|
|
||||||
oid = str(cfg.get("id"))
|
|
||||||
if oid not in seen:
|
|
||||||
seen.add(oid)
|
|
||||||
frame_cfgs.append(dict(cfg))
|
|
||||||
else:
|
|
||||||
driver_names.append(name)
|
|
||||||
return ZoneTargets(zone_id, frame_cfgs, driver_names)
|
|
||||||
-24
@@ -22,9 +22,6 @@ import controllers.pattern as pattern
|
|||||||
import controllers.settings as settings_controller
|
import controllers.settings as settings_controller
|
||||||
import controllers.device as device_controller
|
import controllers.device as device_controller
|
||||||
import controllers.led_tool as led_tool_controller
|
import controllers.led_tool as led_tool_controller
|
||||||
import controllers.output as output_controller
|
|
||||||
from engine import set_engine
|
|
||||||
from engine.core import Engine
|
|
||||||
from models.transport import get_sender, set_sender, get_current_sender
|
from models.transport import get_sender, set_sender, get_current_sender
|
||||||
from models.device import Device, normalize_mac
|
from models.device import Device, normalize_mac
|
||||||
from models import wifi_ws_clients as tcp_client_registry
|
from models import wifi_ws_clients as tcp_client_registry
|
||||||
@@ -264,7 +261,6 @@ async def main(port=80):
|
|||||||
('/zones', zone, 'zone'),
|
('/zones', zone, 'zone'),
|
||||||
('/palettes', palette, 'palette'),
|
('/palettes', palette, 'palette'),
|
||||||
('/scenes', scene, 'scene'),
|
('/scenes', scene, 'scene'),
|
||||||
('/outputs', output_controller, 'output'),
|
|
||||||
]
|
]
|
||||||
|
|
||||||
# Mount model controllers as subroutes
|
# Mount model controllers as subroutes
|
||||||
@@ -279,12 +275,6 @@ async def main(port=80):
|
|||||||
app.mount(settings_controller.controller, '/settings')
|
app.mount(settings_controller.controller, '/settings')
|
||||||
app.mount(device_controller.controller, '/devices')
|
app.mount(device_controller.controller, '/devices')
|
||||||
app.mount(led_tool_controller.controller, '/led-tool')
|
app.mount(led_tool_controller.controller, '/led-tool')
|
||||||
app.mount(output_controller.controller, '/outputs')
|
|
||||||
|
|
||||||
# Pi-side animation engine: renders pixel outputs and runs sequences.
|
|
||||||
engine = set_engine(Engine(
|
|
||||||
brightness_getter=lambda: settings_controller.settings.get('global_brightness', 255),
|
|
||||||
))
|
|
||||||
|
|
||||||
tcp_client_registry.set_settings(settings)
|
tcp_client_registry.set_settings(settings)
|
||||||
tcp_client_registry.set_tcp_status_broadcaster(broadcast_device_tcp_status)
|
tcp_client_registry.set_tcp_status_broadcaster(broadcast_device_tcp_status)
|
||||||
@@ -352,15 +342,6 @@ async def main(port=80):
|
|||||||
await _send_bridge_wifi_channel(settings, sender)
|
await _send_bridge_wifi_channel(settings, sender)
|
||||||
_prime_wifi_outbound_driver_connections()
|
_prime_wifi_outbound_driver_connections()
|
||||||
|
|
||||||
async def _resume_sequences():
|
|
||||||
# Give Wi-Fi drivers a moment to connect before the first step.
|
|
||||||
await asyncio.sleep(2.0)
|
|
||||||
resumed = await engine.sequences.resume_active()
|
|
||||||
if resumed:
|
|
||||||
print(f"[engine] resumed sequences: {resumed}")
|
|
||||||
|
|
||||||
asyncio.create_task(_resume_sequences())
|
|
||||||
|
|
||||||
udp_holder = {"closing": False}
|
udp_holder = {"closing": False}
|
||||||
loop = asyncio.get_running_loop()
|
loop = asyncio.get_running_loop()
|
||||||
|
|
||||||
@@ -402,11 +383,6 @@ async def main(port=80):
|
|||||||
)
|
)
|
||||||
raise
|
raise
|
||||||
finally:
|
finally:
|
||||||
try:
|
|
||||||
# Keep sequence ``active`` flags so they resume after restart.
|
|
||||||
await engine.stop_all(persist=False)
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[engine] stop failed: {e!r}")
|
|
||||||
srv = getattr(app, "server", None)
|
srv = getattr(app, "server", None)
|
||||||
if srv is not None:
|
if srv is not None:
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -1,138 +0,0 @@
|
|||||||
"""
|
|
||||||
Pixel-output registry persisted in ``db/output.json``.
|
|
||||||
|
|
||||||
Network / DMX fixtures that the Pi renders frames for (DDP, Art-Net, sACN,
|
|
||||||
USB-DMX). Our own ESP32 led-drivers stay in ``db/device.json``. **name** is
|
|
||||||
matched against zone ``names`` the same way device names are.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from models.model import Model
|
|
||||||
|
|
||||||
OUTPUT_PROTOCOLS = ("ddp", "artnet", "sacn", "dmx_serial")
|
|
||||||
COLOR_ORDERS = ("rgb", "rbg", "grb", "gbr", "brg", "bgr")
|
|
||||||
DMX_MODES = ("enttec_pro", "open_dmx")
|
|
||||||
|
|
||||||
_DEFAULTS = {
|
|
||||||
"name": "",
|
|
||||||
"protocol": "ddp",
|
|
||||||
"host": "",
|
|
||||||
"port": None,
|
|
||||||
"universe": None,
|
|
||||||
"channel": 1,
|
|
||||||
"serial_port": "",
|
|
||||||
"dmx_mode": "enttec_pro",
|
|
||||||
"pixel_count": 60,
|
|
||||||
"pixel_offset": 0,
|
|
||||||
"color_order": "rgb",
|
|
||||||
"reverse": False,
|
|
||||||
"brightness": 255,
|
|
||||||
"fps": 40,
|
|
||||||
"enabled": True,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _int_field(doc, key, lo, hi, allow_none=False):
|
|
||||||
value = doc.get(key)
|
|
||||||
if value is None or value == "":
|
|
||||||
if allow_none:
|
|
||||||
doc[key] = None
|
|
||||||
return
|
|
||||||
raise ValueError(f"{key} is required")
|
|
||||||
try:
|
|
||||||
value = int(value)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
raise ValueError(f"{key} must be an integer")
|
|
||||||
if value < lo or value > hi:
|
|
||||||
raise ValueError(f"{key} must be between {lo} and {hi}")
|
|
||||||
doc[key] = value
|
|
||||||
|
|
||||||
|
|
||||||
def validate_output(data):
|
|
||||||
"""Return a normalised output record or raise ValueError."""
|
|
||||||
doc = dict(_DEFAULTS)
|
|
||||||
doc.update({k: v for k, v in (data or {}).items() if k != "id"})
|
|
||||||
doc["name"] = str(doc.get("name") or "").strip()
|
|
||||||
if not doc["name"]:
|
|
||||||
raise ValueError("name is required")
|
|
||||||
protocol = str(doc.get("protocol") or "").strip().lower()
|
|
||||||
if protocol not in OUTPUT_PROTOCOLS:
|
|
||||||
raise ValueError(f"protocol must be one of: {', '.join(OUTPUT_PROTOCOLS)}")
|
|
||||||
doc["protocol"] = protocol
|
|
||||||
doc["host"] = str(doc.get("host") or "").strip()
|
|
||||||
doc["serial_port"] = str(doc.get("serial_port") or "").strip()
|
|
||||||
|
|
||||||
if protocol == "ddp" and not doc["host"]:
|
|
||||||
raise ValueError("host is required for ddp")
|
|
||||||
if protocol == "dmx_serial":
|
|
||||||
if not doc["serial_port"]:
|
|
||||||
raise ValueError("serial_port is required for dmx_serial")
|
|
||||||
mode = str(doc.get("dmx_mode") or "enttec_pro").lower()
|
|
||||||
if mode not in DMX_MODES:
|
|
||||||
raise ValueError(f"dmx_mode must be one of: {', '.join(DMX_MODES)}")
|
|
||||||
doc["dmx_mode"] = mode
|
|
||||||
|
|
||||||
_int_field(doc, "port", 1, 65535, allow_none=True)
|
|
||||||
if protocol == "sacn":
|
|
||||||
_int_field(doc, "universe", 1, 63999, allow_none=True)
|
|
||||||
else:
|
|
||||||
_int_field(doc, "universe", 0, 0x7FFF, allow_none=True)
|
|
||||||
_int_field(doc, "channel", 1, 512)
|
|
||||||
_int_field(doc, "pixel_count", 1, 100000)
|
|
||||||
_int_field(doc, "pixel_offset", 0, 100000)
|
|
||||||
_int_field(doc, "brightness", 0, 255)
|
|
||||||
_int_field(doc, "fps", 1, 120)
|
|
||||||
if protocol == "dmx_serial":
|
|
||||||
max_px = (512 - doc["channel"] + 1) // 3
|
|
||||||
if doc["pixel_count"] > max_px:
|
|
||||||
raise ValueError(f"pixel_count must be at most {max_px} for one DMX universe from channel {doc['channel']}")
|
|
||||||
|
|
||||||
order = str(doc.get("color_order") or "rgb").lower()
|
|
||||||
if order not in COLOR_ORDERS:
|
|
||||||
raise ValueError(f"color_order must be one of: {', '.join(COLOR_ORDERS)}")
|
|
||||||
doc["color_order"] = order
|
|
||||||
doc["reverse"] = bool(doc.get("reverse"))
|
|
||||||
doc["enabled"] = bool(doc.get("enabled", True))
|
|
||||||
return doc
|
|
||||||
|
|
||||||
|
|
||||||
class Output(Model):
|
|
||||||
def __init__(self):
|
|
||||||
super().__init__()
|
|
||||||
|
|
||||||
def create(self, data):
|
|
||||||
doc = validate_output(data)
|
|
||||||
next_id = self.get_next_id()
|
|
||||||
doc["id"] = next_id
|
|
||||||
self[next_id] = doc
|
|
||||||
self.save()
|
|
||||||
return next_id
|
|
||||||
|
|
||||||
def read(self, id):
|
|
||||||
return self.get(str(id), None)
|
|
||||||
|
|
||||||
def update(self, id, data):
|
|
||||||
id_str = str(id)
|
|
||||||
if id_str not in self:
|
|
||||||
return False
|
|
||||||
merged = dict(self[id_str])
|
|
||||||
merged.update(data or {})
|
|
||||||
doc = validate_output(merged)
|
|
||||||
doc["id"] = id_str
|
|
||||||
self[id_str] = doc
|
|
||||||
self.save()
|
|
||||||
return True
|
|
||||||
|
|
||||||
def delete(self, id):
|
|
||||||
id_str = str(id)
|
|
||||||
if id_str not in self:
|
|
||||||
return False
|
|
||||||
self.pop(id_str)
|
|
||||||
self.save()
|
|
||||||
return True
|
|
||||||
|
|
||||||
def list(self):
|
|
||||||
return list(self.keys())
|
|
||||||
|
|
||||||
def by_name(self, name):
|
|
||||||
n = str(name or "").strip()
|
|
||||||
return [doc for doc in self.values() if isinstance(doc, dict) and doc.get("name") == n]
|
|
||||||
+16
-84
@@ -1,105 +1,37 @@
|
|||||||
from models.model import Model
|
from models.model import Model
|
||||||
|
|
||||||
DURATION_MIN_S = 0.5
|
|
||||||
DURATION_MAX_S = 600.0
|
|
||||||
DURATION_DEFAULT_S = 5.0
|
|
||||||
|
|
||||||
_LEGACY_KEYS = (
|
|
||||||
"group_name", "presets", "sequence_duration", "sequence_transition", "sequence_loop",
|
|
||||||
"sequence_repeat_count", "sequence_active", "sequence_index", "sequence_start_time",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _normalize_step(step):
|
|
||||||
"""``{"preset_id", "duration_s"}`` with duration clamped to 0.5–600 s (default 5)."""
|
|
||||||
if not isinstance(step, dict):
|
|
||||||
step = {"preset_id": step}
|
|
||||||
preset_id = step.get("preset_id")
|
|
||||||
if preset_id in (None, ""):
|
|
||||||
raise ValueError("each step needs a preset_id")
|
|
||||||
try:
|
|
||||||
duration = float(step.get("duration_s", DURATION_DEFAULT_S))
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
duration = DURATION_DEFAULT_S
|
|
||||||
duration = max(DURATION_MIN_S, min(DURATION_MAX_S, duration))
|
|
||||||
return {"preset_id": str(preset_id), "duration_s": duration}
|
|
||||||
|
|
||||||
|
|
||||||
def _normalize(data):
|
|
||||||
doc = dict(data or {})
|
|
||||||
doc["name"] = str(doc.get("name") or "").strip()
|
|
||||||
zone_id = doc.get("zone_id")
|
|
||||||
doc["zone_id"] = None if zone_id in (None, "") else str(zone_id)
|
|
||||||
doc["loop"] = bool(doc.get("loop", True))
|
|
||||||
try:
|
|
||||||
doc["repeat_count"] = max(0, int(doc.get("repeat_count") or 0))
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
raise ValueError("repeat_count must be an integer")
|
|
||||||
steps = doc.get("steps") or []
|
|
||||||
if not isinstance(steps, list):
|
|
||||||
raise ValueError("steps must be a list")
|
|
||||||
doc["steps"] = [_normalize_step(s) for s in steps]
|
|
||||||
doc["active"] = bool(doc.get("active", False))
|
|
||||||
for key in _LEGACY_KEYS:
|
|
||||||
doc.pop(key, None)
|
|
||||||
return doc
|
|
||||||
|
|
||||||
|
|
||||||
def migrate_legacy(doc):
|
|
||||||
"""Old ``presets`` + ``sequence_duration`` (ms) records → ``steps`` shape."""
|
|
||||||
if not isinstance(doc, dict) or "steps" in doc:
|
|
||||||
return doc, False
|
|
||||||
try:
|
|
||||||
duration_s = float(doc.get("sequence_duration", 3000)) / 1000.0
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
duration_s = DURATION_DEFAULT_S
|
|
||||||
migrated = {
|
|
||||||
"name": doc.get("name") or doc.get("group_name") or "",
|
|
||||||
"zone_id": doc.get("zone_id"),
|
|
||||||
"loop": bool(doc.get("sequence_loop", True)),
|
|
||||||
"repeat_count": doc.get("sequence_repeat_count") or 0,
|
|
||||||
"steps": [{"preset_id": p, "duration_s": duration_s} for p in (doc.get("presets") or [])],
|
|
||||||
"active": False,
|
|
||||||
}
|
|
||||||
return _normalize(migrated), True
|
|
||||||
|
|
||||||
|
|
||||||
class Sequence(Model):
|
class Sequence(Model):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
def load(self):
|
def create(self, group_name="", preset_names=None):
|
||||||
super().load()
|
|
||||||
changed = False
|
|
||||||
for key in list(self.keys()):
|
|
||||||
doc, migrated = migrate_legacy(self[key])
|
|
||||||
if migrated:
|
|
||||||
self[key] = doc
|
|
||||||
changed = True
|
|
||||||
if changed:
|
|
||||||
self.save()
|
|
||||||
|
|
||||||
def create(self, data=None):
|
|
||||||
doc = _normalize(data)
|
|
||||||
next_id = self.get_next_id()
|
next_id = self.get_next_id()
|
||||||
self[next_id] = doc
|
self[next_id] = {
|
||||||
|
"group_name": group_name,
|
||||||
|
"presets": preset_names if preset_names else [],
|
||||||
|
"sequence_duration": 3000, # Duration per preset in ms
|
||||||
|
"sequence_transition": 500, # Transition time in ms
|
||||||
|
"sequence_loop": False,
|
||||||
|
"sequence_repeat_count": 0, # 0 = infinite
|
||||||
|
"sequence_active": False,
|
||||||
|
"sequence_index": 0,
|
||||||
|
"sequence_start_time": 0
|
||||||
|
}
|
||||||
self.save()
|
self.save()
|
||||||
return next_id
|
return next_id
|
||||||
|
|
||||||
def read(self, id):
|
def read(self, id):
|
||||||
id_str = str(id)
|
id_str = str(id)
|
||||||
return self.get(id_str, None)
|
return self.get(id_str, None)
|
||||||
|
|
||||||
def update(self, id, data):
|
def update(self, id, data):
|
||||||
id_str = str(id)
|
id_str = str(id)
|
||||||
if id_str not in self:
|
if id_str not in self:
|
||||||
return False
|
return False
|
||||||
merged = dict(self[id_str])
|
self[id_str].update(data)
|
||||||
merged.update(data or {})
|
|
||||||
self[id_str] = _normalize(merged)
|
|
||||||
self.save()
|
self.save()
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def delete(self, id):
|
def delete(self, id):
|
||||||
id_str = str(id)
|
id_str = str(id)
|
||||||
if id_str not in self:
|
if id_str not in self:
|
||||||
@@ -107,6 +39,6 @@ class Sequence(Model):
|
|||||||
self.pop(id_str)
|
self.pop(id_str)
|
||||||
self.save()
|
self.save()
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def list(self):
|
def list(self):
|
||||||
return list(self.keys())
|
return list(self.keys())
|
||||||
@@ -124,15 +124,6 @@ def _register_ws(ip: str, ws) -> None:
|
|||||||
_send_locks[key] = asyncio.Lock()
|
_send_locks[key] = asyncio.Lock()
|
||||||
_schedule_status_broadcast(key, True)
|
_schedule_status_broadcast(key, True)
|
||||||
print(f"[WS] driver connected {key!r}")
|
print(f"[WS] driver connected {key!r}")
|
||||||
try:
|
|
||||||
loop = asyncio.get_running_loop()
|
|
||||||
except RuntimeError:
|
|
||||||
return
|
|
||||||
|
|
||||||
async def _apply_saved_brightness():
|
|
||||||
await sync_global_brightness_to_driver(key)
|
|
||||||
|
|
||||||
loop.create_task(_apply_saved_brightness())
|
|
||||||
|
|
||||||
|
|
||||||
def unregister_tcp_writer(peer_ip: str, ws=None) -> str:
|
def unregister_tcp_writer(peer_ip: str, ws=None) -> str:
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ class Zone(Model):
|
|||||||
"names": names if names else [],
|
"names": names if names else [],
|
||||||
"presets": presets if presets else [],
|
"presets": presets if presets else [],
|
||||||
"default_preset": None,
|
"default_preset": None,
|
||||||
|
"brightness": 255,
|
||||||
}
|
}
|
||||||
self.save()
|
self.save()
|
||||||
return next_id
|
return next_id
|
||||||
|
|||||||
@@ -1,219 +0,0 @@
|
|||||||
// Pixel outputs (db/output.json): DDP, Art-Net, sACN, USB-DMX fixtures the Pi renders for.
|
|
||||||
|
|
||||||
const OUTPUT_PROTOCOL_LABELS = {
|
|
||||||
ddp: 'DDP',
|
|
||||||
artnet: 'Art-Net',
|
|
||||||
sacn: 'sACN',
|
|
||||||
dmx_serial: 'USB-DMX',
|
|
||||||
};
|
|
||||||
|
|
||||||
async function fetchOutputs() {
|
|
||||||
const res = await fetch('/outputs', { headers: { Accept: 'application/json' } });
|
|
||||||
if (!res.ok) throw new Error('Failed to load outputs');
|
|
||||||
return res.json();
|
|
||||||
}
|
|
||||||
|
|
||||||
function outputSummary(out) {
|
|
||||||
const proto = OUTPUT_PROTOCOL_LABELS[out.protocol] || out.protocol;
|
|
||||||
let where = '';
|
|
||||||
if (out.protocol === 'dmx_serial') {
|
|
||||||
where = `${out.serial_port || '?'} ch ${out.channel || 1}`;
|
|
||||||
} else {
|
|
||||||
where = out.host || (out.protocol === 'sacn' ? 'multicast' : 'broadcast');
|
|
||||||
if (out.port) where += `:${out.port}`;
|
|
||||||
if (out.protocol !== 'ddp' && out.universe != null) where += ` u${out.universe}`;
|
|
||||||
}
|
|
||||||
return `${proto} · ${where} · ${out.pixel_count} px${out.enabled === false ? ' · disabled' : ''}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderOutputsList(outputs) {
|
|
||||||
const container = document.getElementById('outputs-list-modal');
|
|
||||||
if (!container) return;
|
|
||||||
container.innerHTML = '';
|
|
||||||
const ids = Object.keys(outputs || {});
|
|
||||||
if (ids.length === 0) {
|
|
||||||
const p = document.createElement('p');
|
|
||||||
p.className = 'muted-text';
|
|
||||||
p.textContent = 'No outputs yet.';
|
|
||||||
container.appendChild(p);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
ids.forEach((id) => {
|
|
||||||
const out = outputs[id];
|
|
||||||
const row = document.createElement('div');
|
|
||||||
row.className = 'profiles-row';
|
|
||||||
row.style.display = 'flex';
|
|
||||||
row.style.alignItems = 'center';
|
|
||||||
row.style.gap = '0.5rem';
|
|
||||||
row.style.flexWrap = 'wrap';
|
|
||||||
|
|
||||||
const label = document.createElement('span');
|
|
||||||
label.style.flex = '1';
|
|
||||||
label.innerHTML = '';
|
|
||||||
const name = document.createElement('strong');
|
|
||||||
name.textContent = out.name;
|
|
||||||
const meta = document.createElement('span');
|
|
||||||
meta.className = 'muted-text';
|
|
||||||
meta.textContent = ` ${outputSummary(out)}`;
|
|
||||||
label.appendChild(name);
|
|
||||||
label.appendChild(meta);
|
|
||||||
|
|
||||||
const testBtn = document.createElement('button');
|
|
||||||
testBtn.type = 'button';
|
|
||||||
testBtn.className = 'btn btn-secondary btn-small';
|
|
||||||
testBtn.textContent = 'Test';
|
|
||||||
testBtn.title = 'Red, green, blue, white, then black';
|
|
||||||
testBtn.addEventListener('click', async () => {
|
|
||||||
testBtn.disabled = true;
|
|
||||||
testBtn.textContent = 'Testing…';
|
|
||||||
try {
|
|
||||||
const res = await fetch(`/outputs/${encodeURIComponent(id)}/test`, { method: 'POST' });
|
|
||||||
const data = await res.json().catch(() => ({}));
|
|
||||||
if (!res.ok) throw new Error(data.error || res.statusText);
|
|
||||||
const st = data.status || {};
|
|
||||||
testBtn.textContent = st.errors ? `Errors: ${st.errors}` : 'Sent';
|
|
||||||
if (st.last_error) testBtn.title = st.last_error;
|
|
||||||
} catch (e) {
|
|
||||||
testBtn.textContent = 'Failed';
|
|
||||||
testBtn.title = String(e.message || e);
|
|
||||||
} finally {
|
|
||||||
testBtn.disabled = false;
|
|
||||||
setTimeout(() => { testBtn.textContent = 'Test'; }, 2500);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const editBtn = document.createElement('button');
|
|
||||||
editBtn.type = 'button';
|
|
||||||
editBtn.className = 'btn btn-secondary btn-small';
|
|
||||||
editBtn.textContent = 'Edit';
|
|
||||||
editBtn.addEventListener('click', () => openOutputEditor(id, out));
|
|
||||||
|
|
||||||
const delBtn = document.createElement('button');
|
|
||||||
delBtn.type = 'button';
|
|
||||||
delBtn.className = 'btn btn-danger btn-small';
|
|
||||||
delBtn.textContent = 'Delete';
|
|
||||||
delBtn.addEventListener('click', async () => {
|
|
||||||
if (!confirm(`Delete output "${out.name}"?`)) return;
|
|
||||||
const res = await fetch(`/outputs/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
|
||||||
if (!res.ok) {
|
|
||||||
alert('Failed to delete output.');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
loadOutputsModal();
|
|
||||||
});
|
|
||||||
|
|
||||||
row.append(label, testBtn, editBtn, delBtn);
|
|
||||||
container.appendChild(row);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function loadOutputsModal() {
|
|
||||||
const container = document.getElementById('outputs-list-modal');
|
|
||||||
try {
|
|
||||||
renderOutputsList(await fetchOutputs());
|
|
||||||
} catch (e) {
|
|
||||||
if (container) container.textContent = 'Failed to load outputs.';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function syncOutputProtocolFields() {
|
|
||||||
const proto = document.getElementById('edit-output-protocol').value;
|
|
||||||
document.querySelectorAll('#edit-output-form .engine-field').forEach((el) => {
|
|
||||||
const list = (el.dataset.protocols || '').split(/\s+/);
|
|
||||||
el.hidden = !list.includes(proto);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function setOutputField(id, value) {
|
|
||||||
const el = document.getElementById(id);
|
|
||||||
if (!el) return;
|
|
||||||
if (el.type === 'checkbox') el.checked = !!value;
|
|
||||||
else el.value = value == null ? '' : value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function openOutputEditor(id, out) {
|
|
||||||
const o = out || {
|
|
||||||
name: '', protocol: 'ddp', pixel_count: 60, pixel_offset: 0, color_order: 'rgb',
|
|
||||||
brightness: 255, fps: 40, channel: 1, dmx_mode: 'enttec_pro', enabled: true, reverse: false,
|
|
||||||
};
|
|
||||||
document.getElementById('edit-output-title').textContent = id ? 'Edit output' : 'Add output';
|
|
||||||
setOutputField('edit-output-id', id || '');
|
|
||||||
setOutputField('edit-output-name', o.name);
|
|
||||||
setOutputField('edit-output-protocol', o.protocol);
|
|
||||||
setOutputField('edit-output-host', o.host);
|
|
||||||
setOutputField('edit-output-port', o.port);
|
|
||||||
setOutputField('edit-output-universe', o.universe);
|
|
||||||
setOutputField('edit-output-serial-port', o.serial_port);
|
|
||||||
setOutputField('edit-output-dmx-mode', o.dmx_mode || 'enttec_pro');
|
|
||||||
setOutputField('edit-output-channel', o.channel || 1);
|
|
||||||
setOutputField('edit-output-pixel-count', o.pixel_count);
|
|
||||||
setOutputField('edit-output-pixel-offset', o.pixel_offset || 0);
|
|
||||||
setOutputField('edit-output-color-order', o.color_order || 'rgb');
|
|
||||||
setOutputField('edit-output-brightness', o.brightness == null ? 255 : o.brightness);
|
|
||||||
setOutputField('edit-output-fps', o.fps || 40);
|
|
||||||
setOutputField('edit-output-reverse', o.reverse);
|
|
||||||
setOutputField('edit-output-enabled', o.enabled !== false);
|
|
||||||
const err = document.getElementById('edit-output-error');
|
|
||||||
err.hidden = true;
|
|
||||||
syncOutputProtocolFields();
|
|
||||||
document.getElementById('edit-output-modal').classList.add('active');
|
|
||||||
}
|
|
||||||
|
|
||||||
function readOutputForm() {
|
|
||||||
const val = (id) => document.getElementById(id).value.trim();
|
|
||||||
const num = (id) => (val(id) === '' ? null : Number(val(id)));
|
|
||||||
return {
|
|
||||||
name: val('edit-output-name'),
|
|
||||||
protocol: val('edit-output-protocol'),
|
|
||||||
host: val('edit-output-host'),
|
|
||||||
port: num('edit-output-port'),
|
|
||||||
universe: num('edit-output-universe'),
|
|
||||||
serial_port: val('edit-output-serial-port'),
|
|
||||||
dmx_mode: val('edit-output-dmx-mode'),
|
|
||||||
channel: num('edit-output-channel') || 1,
|
|
||||||
pixel_count: num('edit-output-pixel-count'),
|
|
||||||
pixel_offset: num('edit-output-pixel-offset') || 0,
|
|
||||||
color_order: val('edit-output-color-order'),
|
|
||||||
brightness: num('edit-output-brightness'),
|
|
||||||
fps: num('edit-output-fps'),
|
|
||||||
reverse: document.getElementById('edit-output-reverse').checked,
|
|
||||||
enabled: document.getElementById('edit-output-enabled').checked,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
|
||||||
const btn = document.getElementById('outputs-btn');
|
|
||||||
const modal = document.getElementById('outputs-modal');
|
|
||||||
const editModal = document.getElementById('edit-output-modal');
|
|
||||||
const form = document.getElementById('edit-output-form');
|
|
||||||
if (!btn || !modal || !form) return;
|
|
||||||
|
|
||||||
btn.addEventListener('click', () => {
|
|
||||||
modal.classList.add('active');
|
|
||||||
loadOutputsModal();
|
|
||||||
});
|
|
||||||
document.getElementById('outputs-close-btn').addEventListener('click', () => modal.classList.remove('active'));
|
|
||||||
document.getElementById('output-add-btn').addEventListener('click', () => openOutputEditor(null, null));
|
|
||||||
document.getElementById('edit-output-close-btn').addEventListener('click', () => editModal.classList.remove('active'));
|
|
||||||
document.getElementById('edit-output-protocol').addEventListener('change', syncOutputProtocolFields);
|
|
||||||
|
|
||||||
form.addEventListener('submit', async (e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
const id = document.getElementById('edit-output-id').value;
|
|
||||||
const err = document.getElementById('edit-output-error');
|
|
||||||
err.hidden = true;
|
|
||||||
const res = await fetch(id ? `/outputs/${encodeURIComponent(id)}` : '/outputs', {
|
|
||||||
method: id ? 'PUT' : 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
||||||
body: JSON.stringify(readOutputForm()),
|
|
||||||
});
|
|
||||||
const data = await res.json().catch(() => ({}));
|
|
||||||
if (!res.ok) {
|
|
||||||
err.textContent = data.error || 'Save failed';
|
|
||||||
err.hidden = false;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
editModal.classList.remove('active');
|
|
||||||
loadOutputsModal();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
+36
-5
@@ -255,6 +255,18 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
return Number.isFinite(n) ? n : 0;
|
return Number.isFinite(n) ? n : 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const patternSupportsBackgroundColor = () => {
|
||||||
|
if (!presetPatternInput || !presetPatternInput.value) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const pattern = String(presetPatternInput.value).trim();
|
||||||
|
const meta =
|
||||||
|
(cachedPatterns && cachedPatterns[pattern]) ||
|
||||||
|
(cachedPatterns && cachedPatterns[pattern.toLowerCase()]) ||
|
||||||
|
null;
|
||||||
|
return !!(meta && typeof meta === 'object' && meta.has_background === true);
|
||||||
|
};
|
||||||
|
|
||||||
const renderPresetColors = (colors, paletteRefs) => {
|
const renderPresetColors = (colors, paletteRefs) => {
|
||||||
if (!presetColorsContainer) return;
|
if (!presetColorsContainer) return;
|
||||||
|
|
||||||
@@ -296,14 +308,21 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const swatchContainer = document.createElement('div');
|
const swatchContainer = document.createElement('div');
|
||||||
swatchContainer.style.cssText = 'display: flex; flex-wrap: wrap; gap: 0.5rem;';
|
swatchContainer.style.cssText = 'display: flex; flex-wrap: nowrap; gap: 0.5rem; align-items: flex-start; overflow-x: auto;';
|
||||||
swatchContainer.classList.add('color-swatches-container');
|
swatchContainer.classList.add('color-swatches-container');
|
||||||
|
|
||||||
|
const showBackgroundLabel = patternSupportsBackgroundColor() && currentPresetColors.length > 1;
|
||||||
currentPresetColors.forEach((color, index) => {
|
currentPresetColors.forEach((color, index) => {
|
||||||
|
const isBackgroundColor = showBackgroundLabel && index === currentPresetColors.length - 1;
|
||||||
const swatchWrapper = document.createElement('div');
|
const swatchWrapper = document.createElement('div');
|
||||||
swatchWrapper.style.cssText = 'position: relative; display: inline-block;';
|
swatchWrapper.style.cssText = 'position: relative; display: inline-block;';
|
||||||
|
if (isBackgroundColor) {
|
||||||
|
// Keep the background color swatch at the far right.
|
||||||
|
swatchWrapper.style.marginLeft = 'auto';
|
||||||
|
}
|
||||||
swatchWrapper.draggable = true;
|
swatchWrapper.draggable = true;
|
||||||
swatchWrapper.dataset.colorIndex = index;
|
swatchWrapper.dataset.colorIndex = index;
|
||||||
|
swatchWrapper.dataset.backgroundColor = isBackgroundColor ? '1' : '0';
|
||||||
const refAtIndex = currentPresetPaletteRefs[index];
|
const refAtIndex = currentPresetPaletteRefs[index];
|
||||||
swatchWrapper.dataset.paletteRef = Number.isInteger(refAtIndex) ? String(refAtIndex) : '';
|
swatchWrapper.dataset.paletteRef = Number.isInteger(refAtIndex) ? String(refAtIndex) : '';
|
||||||
swatchWrapper.classList.add('draggable-color-swatch');
|
swatchWrapper.classList.add('draggable-color-swatch');
|
||||||
@@ -424,6 +443,18 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
swatchWrapper.appendChild(swatch);
|
swatchWrapper.appendChild(swatch);
|
||||||
swatchWrapper.appendChild(colorPicker);
|
swatchWrapper.appendChild(colorPicker);
|
||||||
swatchWrapper.appendChild(removeBtn);
|
swatchWrapper.appendChild(removeBtn);
|
||||||
|
if (isBackgroundColor) {
|
||||||
|
const bgLabel = document.createElement('div');
|
||||||
|
bgLabel.textContent = 'Background';
|
||||||
|
bgLabel.style.cssText = `
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 0.72rem;
|
||||||
|
color: #cfcfcf;
|
||||||
|
letter-spacing: 0.02em;
|
||||||
|
`;
|
||||||
|
swatchWrapper.appendChild(bgLabel);
|
||||||
|
}
|
||||||
swatchContainer.appendChild(swatchWrapper);
|
swatchContainer.appendChild(swatchWrapper);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -445,6 +476,10 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const dragging = swatchContainer.querySelector('.dragging-color');
|
const dragging = swatchContainer.querySelector('.dragging-color');
|
||||||
if (!dragging) return;
|
if (!dragging) return;
|
||||||
|
const backgroundEl = swatchContainer.querySelector('.draggable-color-swatch[data-background-color="1"]');
|
||||||
|
if (backgroundEl) {
|
||||||
|
swatchContainer.appendChild(backgroundEl);
|
||||||
|
}
|
||||||
|
|
||||||
// Get new order of colors from DOM
|
// Get new order of colors from DOM
|
||||||
const colorElements = [...swatchContainer.querySelectorAll('.draggable-color-swatch')];
|
const colorElements = [...swatchContainer.querySelectorAll('.draggable-color-swatch')];
|
||||||
@@ -1859,10 +1894,6 @@ const createPresetButton = (presetId, preset, zoneId, isSelected = false) => {
|
|||||||
sendPresetViaEspNow(presetId, preset, deviceNames, false, false, '2').catch((err) => {
|
sendPresetViaEspNow(presetId, preset, deviceNames, false, false, '2').catch((err) => {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
});
|
});
|
||||||
// Pi-side engine: pixel outputs in this zone + stop any running sequence.
|
|
||||||
if (typeof window.notifyEngineZonePlay === 'function') {
|
|
||||||
window.notifyEngineZonePlay(zoneId, presetId);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (canDrag) {
|
if (canDrag) {
|
||||||
|
|||||||
@@ -1,296 +0,0 @@
|
|||||||
// Sequences: timed preset chains per zone, run by the Pi-side engine.
|
|
||||||
|
|
||||||
const SEQUENCES_POLL_MS = 1000;
|
|
||||||
let sequencesPollTimer = null;
|
|
||||||
|
|
||||||
async function fetchJson(url) {
|
|
||||||
const res = await fetch(url, { headers: { Accept: 'application/json' }, credentials: 'same-origin' });
|
|
||||||
if (!res.ok) throw new Error(`${url}: ${res.status}`);
|
|
||||||
return res.json();
|
|
||||||
}
|
|
||||||
|
|
||||||
async function loadSequenceContext() {
|
|
||||||
const [sequences, status, zonesData, presets] = await Promise.all([
|
|
||||||
fetchJson('/sequences'),
|
|
||||||
fetchJson('/sequences/status'),
|
|
||||||
fetchJson('/zones'),
|
|
||||||
fetchJson('/presets'),
|
|
||||||
]);
|
|
||||||
const order = Array.isArray(zonesData.zone_order) ? zonesData.zone_order : [];
|
|
||||||
const zones = {};
|
|
||||||
order.forEach((zid) => {
|
|
||||||
if (zonesData.zones && zonesData.zones[zid]) zones[zid] = zonesData.zones[zid];
|
|
||||||
});
|
|
||||||
return { sequences, status, zones, presets };
|
|
||||||
}
|
|
||||||
|
|
||||||
function stepSummary(seq, presets, state) {
|
|
||||||
const steps = seq.steps || [];
|
|
||||||
const total = steps.reduce((s, st) => s + Number(st.duration_s || 0), 0);
|
|
||||||
let text = `${steps.length} step${steps.length === 1 ? '' : 's'} · ${total.toFixed(1)} s`;
|
|
||||||
text += seq.loop ? (seq.repeat_count ? ` · ×${seq.repeat_count}` : ' · loop') : ' · once';
|
|
||||||
if (state && state.running) {
|
|
||||||
const p = presets[state.preset_id];
|
|
||||||
text += ` · ▶ step ${state.step_index + 1}${p ? ` (${p.name})` : ''}`;
|
|
||||||
}
|
|
||||||
return text;
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderSequencesList(ctx) {
|
|
||||||
const container = document.getElementById('sequences-list-modal');
|
|
||||||
if (!container) return;
|
|
||||||
const editMode = typeof isEditModeActive === 'function' && isEditModeActive();
|
|
||||||
container.innerHTML = '';
|
|
||||||
const ids = Object.keys(ctx.sequences || {}).filter((id) => {
|
|
||||||
const z = ctx.sequences[id].zone_id;
|
|
||||||
return z == null || ctx.zones[z]; // only this profile's zones (plus unassigned)
|
|
||||||
});
|
|
||||||
if (ids.length === 0) {
|
|
||||||
const p = document.createElement('p');
|
|
||||||
p.className = 'muted-text';
|
|
||||||
p.textContent = 'No sequences yet.';
|
|
||||||
container.appendChild(p);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
ids.forEach((id) => {
|
|
||||||
const seq = ctx.sequences[id];
|
|
||||||
const state = ctx.status[id];
|
|
||||||
const running = !!(state && state.running);
|
|
||||||
const zone = ctx.zones[seq.zone_id];
|
|
||||||
|
|
||||||
const row = document.createElement('div');
|
|
||||||
row.className = 'profiles-row';
|
|
||||||
row.style.display = 'flex';
|
|
||||||
row.style.alignItems = 'center';
|
|
||||||
row.style.gap = '0.5rem';
|
|
||||||
row.style.flexWrap = 'wrap';
|
|
||||||
|
|
||||||
const label = document.createElement('span');
|
|
||||||
label.style.flex = '1';
|
|
||||||
const name = document.createElement('strong');
|
|
||||||
name.textContent = seq.name || `Sequence ${id}`;
|
|
||||||
const meta = document.createElement('span');
|
|
||||||
meta.className = 'muted-text';
|
|
||||||
meta.textContent = ` ${zone ? zone.name : 'no zone'} · ${stepSummary(seq, ctx.presets, state)}`;
|
|
||||||
label.append(name, meta);
|
|
||||||
|
|
||||||
const playBtn = document.createElement('button');
|
|
||||||
playBtn.type = 'button';
|
|
||||||
playBtn.className = running ? 'btn btn-danger btn-small' : 'btn btn-primary btn-small';
|
|
||||||
playBtn.textContent = running ? 'Stop' : 'Play';
|
|
||||||
playBtn.disabled = !zone || !(seq.steps || []).length;
|
|
||||||
playBtn.addEventListener('click', async () => {
|
|
||||||
playBtn.disabled = true;
|
|
||||||
const res = await fetch(`/sequences/${encodeURIComponent(id)}/${running ? 'stop' : 'play'}`, {
|
|
||||||
method: 'POST', credentials: 'same-origin',
|
|
||||||
});
|
|
||||||
if (!res.ok) {
|
|
||||||
const data = await res.json().catch(() => ({}));
|
|
||||||
alert(data.error || 'Failed');
|
|
||||||
}
|
|
||||||
refreshSequencesList();
|
|
||||||
});
|
|
||||||
row.append(label, playBtn);
|
|
||||||
|
|
||||||
if (editMode) {
|
|
||||||
const editBtn = document.createElement('button');
|
|
||||||
editBtn.type = 'button';
|
|
||||||
editBtn.className = 'btn btn-secondary btn-small';
|
|
||||||
editBtn.textContent = 'Edit';
|
|
||||||
editBtn.addEventListener('click', () => openSequenceEditor(id, seq, ctx));
|
|
||||||
const delBtn = document.createElement('button');
|
|
||||||
delBtn.type = 'button';
|
|
||||||
delBtn.className = 'btn btn-danger btn-small';
|
|
||||||
delBtn.textContent = 'Delete';
|
|
||||||
delBtn.addEventListener('click', async () => {
|
|
||||||
if (!confirm(`Delete sequence "${seq.name}"?`)) return;
|
|
||||||
await fetch(`/sequences/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
|
||||||
refreshSequencesList();
|
|
||||||
});
|
|
||||||
row.append(editBtn, delBtn);
|
|
||||||
}
|
|
||||||
container.appendChild(row);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let lastSequenceCtx = null;
|
|
||||||
|
|
||||||
async function refreshSequencesList() {
|
|
||||||
try {
|
|
||||||
lastSequenceCtx = await loadSequenceContext();
|
|
||||||
renderSequencesList(lastSequenceCtx);
|
|
||||||
} catch (e) {
|
|
||||||
const container = document.getElementById('sequences-list-modal');
|
|
||||||
if (container && !lastSequenceCtx) container.textContent = 'Failed to load sequences.';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function stopSequencesPoll() {
|
|
||||||
if (sequencesPollTimer != null) {
|
|
||||||
clearInterval(sequencesPollTimer);
|
|
||||||
sequencesPollTimer = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function addStepRow(presets, step) {
|
|
||||||
const container = document.getElementById('edit-sequence-steps');
|
|
||||||
const row = document.createElement('div');
|
|
||||||
row.className = 'engine-step-row';
|
|
||||||
|
|
||||||
const select = document.createElement('select');
|
|
||||||
select.className = 'engine-step-preset';
|
|
||||||
Object.entries(presets || {}).forEach(([pid, p]) => {
|
|
||||||
const opt = document.createElement('option');
|
|
||||||
opt.value = pid;
|
|
||||||
opt.textContent = p.name || pid;
|
|
||||||
select.appendChild(opt);
|
|
||||||
});
|
|
||||||
if (step && step.preset_id != null) select.value = String(step.preset_id);
|
|
||||||
|
|
||||||
const dur = document.createElement('input');
|
|
||||||
dur.type = 'number';
|
|
||||||
dur.min = '0.5';
|
|
||||||
dur.max = '600';
|
|
||||||
dur.step = '0.5';
|
|
||||||
dur.className = 'engine-step-duration';
|
|
||||||
dur.value = step && step.duration_s != null ? step.duration_s : 5;
|
|
||||||
dur.title = 'Seconds';
|
|
||||||
|
|
||||||
const unit = document.createElement('span');
|
|
||||||
unit.className = 'muted-text';
|
|
||||||
unit.textContent = 's';
|
|
||||||
|
|
||||||
const mk = (text, title, fn) => {
|
|
||||||
const b = document.createElement('button');
|
|
||||||
b.type = 'button';
|
|
||||||
b.className = 'btn btn-secondary btn-small';
|
|
||||||
b.textContent = text;
|
|
||||||
b.title = title;
|
|
||||||
b.addEventListener('click', fn);
|
|
||||||
return b;
|
|
||||||
};
|
|
||||||
const up = mk('↑', 'Move up', () => { if (row.previousElementSibling) container.insertBefore(row, row.previousElementSibling); });
|
|
||||||
const down = mk('↓', 'Move down', () => { if (row.nextElementSibling) container.insertBefore(row.nextElementSibling, row); });
|
|
||||||
const del = mk('✕', 'Remove step', () => row.remove());
|
|
||||||
|
|
||||||
row.append(select, dur, unit, up, down, del);
|
|
||||||
container.appendChild(row);
|
|
||||||
}
|
|
||||||
|
|
||||||
function openSequenceEditor(id, seq, ctx) {
|
|
||||||
const s = seq || { name: '', zone_id: null, loop: true, repeat_count: 0, steps: [] };
|
|
||||||
document.getElementById('edit-sequence-title').textContent = id ? 'Edit sequence' : 'New sequence';
|
|
||||||
document.getElementById('edit-sequence-id').value = id || '';
|
|
||||||
document.getElementById('edit-sequence-name').value = s.name || '';
|
|
||||||
const zoneSel = document.getElementById('edit-sequence-zone');
|
|
||||||
zoneSel.innerHTML = '';
|
|
||||||
Object.entries(ctx.zones).forEach(([zid, z]) => {
|
|
||||||
const opt = document.createElement('option');
|
|
||||||
opt.value = zid;
|
|
||||||
opt.textContent = z.name || zid;
|
|
||||||
zoneSel.appendChild(opt);
|
|
||||||
});
|
|
||||||
const currentZone = s.zone_id
|
|
||||||
|| (window.zonesManager && window.zonesManager.getCurrentZoneId && window.zonesManager.getCurrentZoneId());
|
|
||||||
if (currentZone && ctx.zones[currentZone]) zoneSel.value = String(currentZone);
|
|
||||||
document.getElementById('edit-sequence-loop').checked = s.loop !== false;
|
|
||||||
document.getElementById('edit-sequence-repeat').value = s.repeat_count || 0;
|
|
||||||
const steps = document.getElementById('edit-sequence-steps');
|
|
||||||
steps.innerHTML = '';
|
|
||||||
(s.steps || []).forEach((st) => addStepRow(ctx.presets, st));
|
|
||||||
if (!(s.steps || []).length) addStepRow(ctx.presets, null);
|
|
||||||
document.getElementById('edit-sequence-error').hidden = true;
|
|
||||||
document.getElementById('edit-sequence-modal').classList.add('active');
|
|
||||||
}
|
|
||||||
|
|
||||||
function readSequenceForm() {
|
|
||||||
const steps = [];
|
|
||||||
document.querySelectorAll('#edit-sequence-steps .engine-step-row').forEach((row) => {
|
|
||||||
const pid = row.querySelector('.engine-step-preset').value;
|
|
||||||
const dur = Number(row.querySelector('.engine-step-duration').value);
|
|
||||||
if (pid) steps.push({ preset_id: pid, duration_s: Number.isFinite(dur) ? dur : 5 });
|
|
||||||
});
|
|
||||||
return {
|
|
||||||
name: document.getElementById('edit-sequence-name').value.trim(),
|
|
||||||
zone_id: document.getElementById('edit-sequence-zone').value || null,
|
|
||||||
loop: document.getElementById('edit-sequence-loop').checked,
|
|
||||||
repeat_count: Number(document.getElementById('edit-sequence-repeat').value) || 0,
|
|
||||||
steps,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Tell the engine a preset was picked on a zone: renders it on the zone's pixel
|
|
||||||
// outputs and stops any sequence there. ESP32s were already sent the preset
|
|
||||||
// by presets.js, so the engine leaves them alone (drivers: false).
|
|
||||||
async function notifyEngineZonePlay(zoneId, presetId) {
|
|
||||||
if (!zoneId || !presetId) return;
|
|
||||||
try {
|
|
||||||
await fetch(`/zones/${encodeURIComponent(zoneId)}/play`, {
|
|
||||||
method: 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json' },
|
|
||||||
credentials: 'same-origin',
|
|
||||||
body: JSON.stringify({ preset_id: String(presetId), drivers: false }),
|
|
||||||
});
|
|
||||||
} catch (e) {
|
|
||||||
console.warn('Engine zone play failed:', e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
window.notifyEngineZonePlay = notifyEngineZonePlay;
|
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
|
||||||
const btn = document.getElementById('sequences-btn');
|
|
||||||
const modal = document.getElementById('sequences-modal');
|
|
||||||
const editModal = document.getElementById('edit-sequence-modal');
|
|
||||||
const form = document.getElementById('edit-sequence-form');
|
|
||||||
if (!btn || !modal || !form) return;
|
|
||||||
|
|
||||||
btn.addEventListener('click', () => {
|
|
||||||
modal.classList.add('active');
|
|
||||||
refreshSequencesList();
|
|
||||||
stopSequencesPoll();
|
|
||||||
sequencesPollTimer = setInterval(refreshSequencesList, SEQUENCES_POLL_MS);
|
|
||||||
});
|
|
||||||
document.getElementById('sequences-close-btn').addEventListener('click', () => {
|
|
||||||
modal.classList.remove('active');
|
|
||||||
});
|
|
||||||
new MutationObserver(() => {
|
|
||||||
if (!modal.classList.contains('active')) stopSequencesPoll();
|
|
||||||
}).observe(modal, { attributes: true, attributeFilter: ['class'] });
|
|
||||||
|
|
||||||
document.getElementById('sequence-add-btn').addEventListener('click', async () => {
|
|
||||||
const ctx = lastSequenceCtx || await loadSequenceContext();
|
|
||||||
openSequenceEditor(null, null, ctx);
|
|
||||||
});
|
|
||||||
document.getElementById('edit-sequence-add-step-btn').addEventListener('click', () => {
|
|
||||||
addStepRow((lastSequenceCtx && lastSequenceCtx.presets) || {}, null);
|
|
||||||
});
|
|
||||||
document.getElementById('edit-sequence-close-btn').addEventListener('click', () => {
|
|
||||||
editModal.classList.remove('active');
|
|
||||||
});
|
|
||||||
|
|
||||||
form.addEventListener('submit', async (e) => {
|
|
||||||
e.preventDefault();
|
|
||||||
const id = document.getElementById('edit-sequence-id').value;
|
|
||||||
const err = document.getElementById('edit-sequence-error');
|
|
||||||
err.hidden = true;
|
|
||||||
const body = readSequenceForm();
|
|
||||||
if (!body.steps.length) {
|
|
||||||
err.textContent = 'Add at least one step.';
|
|
||||||
err.hidden = false;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const res = await fetch(id ? `/sequences/${encodeURIComponent(id)}` : '/sequences', {
|
|
||||||
method: id ? 'PUT' : 'POST',
|
|
||||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
||||||
body: JSON.stringify(body),
|
|
||||||
});
|
|
||||||
const data = await res.json().catch(() => ({}));
|
|
||||||
if (!res.ok) {
|
|
||||||
err.textContent = data.error || 'Save failed';
|
|
||||||
err.hidden = false;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
editModal.classList.remove('active');
|
|
||||||
refreshSequencesList();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
+4
-69
@@ -550,14 +550,14 @@ body.preset-ui-run .edit-mode-only {
|
|||||||
padding: 0;
|
padding: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Zone preset selecting area: 3 columns, vertical scroll only */
|
/* Zone preset selecting area: 8 columns on desktop, vertical scroll only */
|
||||||
#presets-list-zone {
|
#presets-list-zone {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
min-height: 0;
|
min-height: 0;
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
overflow-x: hidden;
|
overflow-x: hidden;
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
grid-template-columns: repeat(8, minmax(0, 1fr));
|
||||||
grid-auto-rows: 5rem;
|
grid-auto-rows: 5rem;
|
||||||
column-gap: 0.3rem;
|
column-gap: 0.3rem;
|
||||||
row-gap: 0.3rem;
|
row-gap: 0.3rem;
|
||||||
@@ -1261,8 +1261,8 @@ body.preset-ui-run .edit-mode-only {
|
|||||||
.color-swatches-container {
|
.color-swatches-container {
|
||||||
min-height: 80px;
|
min-height: 80px;
|
||||||
}
|
}
|
||||||
/* Presets list: 3 columns and vertical scroll (defined above); mobile same */
|
/* Presets list: 3 columns on phone-sized screens */
|
||||||
@media (max-width: 1000px) {
|
@media (max-width: 600px) {
|
||||||
#presets-list-zone {
|
#presets-list-zone {
|
||||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
padding-bottom: calc(env(safe-area-inset-bottom, 0px) + 7rem);
|
padding-bottom: calc(env(safe-area-inset-bottom, 0px) + 7rem);
|
||||||
@@ -1389,68 +1389,3 @@ body.preset-ui-run .edit-mode-only {
|
|||||||
}#settings-modal .settings-section.ap-settings-section {
|
}#settings-modal .settings-section.ap-settings-section {
|
||||||
margin-top: 1.5rem;
|
margin-top: 1.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Engine: outputs + sequences editors */
|
|
||||||
#edit-output-modal .modal-content,
|
|
||||||
#edit-sequence-modal .modal-content {
|
|
||||||
max-height: 90vh;
|
|
||||||
overflow-y: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.engine-form select {
|
|
||||||
width: 100%;
|
|
||||||
padding: 0.5rem;
|
|
||||||
background-color: #3a3a3a;
|
|
||||||
color: white;
|
|
||||||
border: 1px solid #4a4a4a;
|
|
||||||
border-radius: 4px;
|
|
||||||
font-size: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.engine-form label.engine-check {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 0.5rem;
|
|
||||||
font-weight: normal;
|
|
||||||
}
|
|
||||||
|
|
||||||
.engine-form label.engine-check input {
|
|
||||||
width: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.engine-field[hidden] {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.engine-subheading {
|
|
||||||
margin: 1.25rem 0 0.5rem;
|
|
||||||
font-size: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.engine-steps {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 0.4rem;
|
|
||||||
margin-bottom: 0.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.engine-step-row {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 0.35rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.engine-step-row select.engine-step-preset {
|
|
||||||
flex: 1;
|
|
||||||
min-width: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.engine-step-row input.engine-step-duration {
|
|
||||||
width: 5rem;
|
|
||||||
flex: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.engine-error {
|
|
||||||
margin-top: 0.75rem;
|
|
||||||
color: #ff6b6b;
|
|
||||||
}
|
|
||||||
+23
-37
@@ -17,24 +17,26 @@ function applyBrightnessSliders(val) {
|
|||||||
if (menuSlider) menuSlider.value = String(v);
|
if (menuSlider) menuSlider.value = String(v);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveGlobalBrightnessToServer(val) {
|
async function saveZoneBrightnessToServer(zoneId, val) {
|
||||||
|
if (!zoneId) return;
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/settings/settings", {
|
const res = await fetch(`/zones/${zoneId}`, {
|
||||||
method: "PUT",
|
method: "PUT",
|
||||||
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
||||||
credentials: "same-origin",
|
credentials: "same-origin",
|
||||||
body: JSON.stringify({ global_brightness: val }),
|
body: JSON.stringify({ brightness: val }),
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const err = await res.json().catch(() => ({}));
|
const err = await res.json().catch(() => ({}));
|
||||||
console.warn("global_brightness save failed:", err.error || res.status);
|
console.warn("zone brightness save failed:", err.error || res.status);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.warn("global_brightness save failed:", e);
|
console.warn("zone brightness save failed:", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function sendZoneBrightness(value) {
|
function sendZoneBrightness(zoneId, value) {
|
||||||
|
if (!zoneId) return;
|
||||||
const val = Math.max(0, Math.min(255, parseInt(value, 10) || 0));
|
const val = Math.max(0, Math.min(255, parseInt(value, 10) || 0));
|
||||||
const headerSlider = document.getElementById('header-brightness-slider');
|
const headerSlider = document.getElementById('header-brightness-slider');
|
||||||
const menuSlider = document.getElementById('menu-brightness-slider');
|
const menuSlider = document.getElementById('menu-brightness-slider');
|
||||||
@@ -50,7 +52,7 @@ function sendZoneBrightness(value) {
|
|||||||
brightnessSendTimeout = setTimeout(() => {
|
brightnessSendTimeout = setTimeout(() => {
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
await saveGlobalBrightnessToServer(val);
|
await saveZoneBrightnessToServer(zoneId, val);
|
||||||
const section = document.querySelector('.presets-section[data-zone-id]');
|
const section = document.querySelector('.presets-section[data-zone-id]');
|
||||||
const names = typeof window.parseTabDeviceNames === 'function'
|
const names = typeof window.parseTabDeviceNames === 'function'
|
||||||
? window.parseTabDeviceNames(section)
|
? window.parseTabDeviceNames(section)
|
||||||
@@ -550,11 +552,16 @@ async function loadZoneContent(zoneId) {
|
|||||||
`;
|
`;
|
||||||
|
|
||||||
// Keep header and menu brightness controls in sync.
|
// Keep header and menu brightness controls in sync.
|
||||||
const brightnessSlider = document.getElementById('header-brightness-slider');
|
const zoneBrightness =
|
||||||
const menuBrightnessSlider = document.getElementById('menu-brightness-slider');
|
typeof zone.brightness === 'number'
|
||||||
if (menuBrightnessSlider && brightnessSlider) {
|
? zone.brightness
|
||||||
menuBrightnessSlider.value = brightnessSlider.value;
|
: parseInt(String(zone.brightness ?? ''), 10);
|
||||||
}
|
const normalizedBrightness = Number.isFinite(zoneBrightness)
|
||||||
|
? Math.max(0, Math.min(255, Math.round(zoneBrightness)))
|
||||||
|
: 255;
|
||||||
|
applyBrightnessSliders(normalizedBrightness);
|
||||||
|
// Apply this zone's saved brightness when switching zones.
|
||||||
|
sendZoneBrightness(zoneId, normalizedBrightness);
|
||||||
|
|
||||||
// Trigger presets loading if the function exists
|
// Trigger presets loading if the function exists
|
||||||
if (typeof renderTabPresets === 'function') {
|
if (typeof renderTabPresets === 'function') {
|
||||||
@@ -1025,38 +1032,17 @@ document.addEventListener('DOMContentLoaded', () => {
|
|||||||
const menuBrightnessSlider = document.getElementById('menu-brightness-slider');
|
const menuBrightnessSlider = document.getElementById('menu-brightness-slider');
|
||||||
const headerBrightnessSlider = document.getElementById('header-brightness-slider');
|
const headerBrightnessSlider = document.getElementById('header-brightness-slider');
|
||||||
(async () => {
|
(async () => {
|
||||||
let fromServer = null;
|
|
||||||
try {
|
|
||||||
const res = await fetch('/settings', {
|
|
||||||
headers: { Accept: 'application/json' },
|
|
||||||
credentials: 'same-origin',
|
|
||||||
});
|
|
||||||
if (res.ok) {
|
|
||||||
const data = await res.json();
|
|
||||||
const g = data.global_brightness;
|
|
||||||
if (typeof g === 'number' && g >= 0 && g <= 255) {
|
|
||||||
fromServer = Math.round(g);
|
|
||||||
} else if (g != null && g !== '') {
|
|
||||||
const n = parseInt(String(g), 10);
|
|
||||||
if (!Number.isNaN(n) && n >= 0 && n <= 255) {
|
|
||||||
fromServer = n;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (_) {}
|
|
||||||
if (fromServer !== null) {
|
|
||||||
applyBrightnessSliders(fromServer);
|
|
||||||
}
|
|
||||||
if (menuBrightnessSlider) {
|
if (menuBrightnessSlider) {
|
||||||
menuBrightnessSlider.addEventListener('input', (e) => {
|
menuBrightnessSlider.addEventListener('input', (e) => {
|
||||||
sendZoneBrightness(e.target.value);
|
if (!currentZoneId) return;
|
||||||
|
sendZoneBrightness(currentZoneId, e.target.value);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (headerBrightnessSlider) {
|
if (headerBrightnessSlider) {
|
||||||
headerBrightnessSlider.addEventListener('input', (e) => {
|
headerBrightnessSlider.addEventListener('input', (e) => {
|
||||||
sendZoneBrightness(e.target.value);
|
if (!currentZoneId) return;
|
||||||
|
sendZoneBrightness(currentZoneId, e.target.value);
|
||||||
});
|
});
|
||||||
sendZoneBrightness(headerBrightnessSlider.value);
|
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
|||||||
@@ -21,8 +21,6 @@
|
|||||||
</div>
|
</div>
|
||||||
<button class="btn btn-secondary" id="profiles-btn">Profiles</button>
|
<button class="btn btn-secondary" id="profiles-btn">Profiles</button>
|
||||||
<button class="btn btn-secondary edit-mode-only" id="devices-btn">Devices</button>
|
<button class="btn btn-secondary edit-mode-only" id="devices-btn">Devices</button>
|
||||||
<button class="btn btn-secondary edit-mode-only" id="outputs-btn">Outputs</button>
|
|
||||||
<button class="btn btn-secondary" id="sequences-btn">Sequences</button>
|
|
||||||
<button class="btn btn-secondary edit-mode-only" id="zones-btn">Zones</button>
|
<button class="btn btn-secondary edit-mode-only" id="zones-btn">Zones</button>
|
||||||
<button class="btn btn-secondary edit-mode-only" id="presets-btn">Presets</button>
|
<button class="btn btn-secondary edit-mode-only" id="presets-btn">Presets</button>
|
||||||
<button class="btn btn-secondary edit-mode-only" id="patterns-btn">Patterns</button>
|
<button class="btn btn-secondary edit-mode-only" id="patterns-btn">Patterns</button>
|
||||||
@@ -42,8 +40,6 @@
|
|||||||
</div>
|
</div>
|
||||||
<button type="button" data-target="profiles-btn">Profiles</button>
|
<button type="button" data-target="profiles-btn">Profiles</button>
|
||||||
<button type="button" class="edit-mode-only" data-target="devices-btn">Devices</button>
|
<button type="button" class="edit-mode-only" data-target="devices-btn">Devices</button>
|
||||||
<button type="button" class="edit-mode-only" data-target="outputs-btn">Outputs</button>
|
|
||||||
<button type="button" data-target="sequences-btn">Sequences</button>
|
|
||||||
<button type="button" class="edit-mode-only" data-target="zones-btn">Tabs</button>
|
<button type="button" class="edit-mode-only" data-target="zones-btn">Tabs</button>
|
||||||
<button type="button" class="edit-mode-only" data-target="presets-btn">Presets</button>
|
<button type="button" class="edit-mode-only" data-target="presets-btn">Presets</button>
|
||||||
<button type="button" class="edit-mode-only" data-target="patterns-btn">Patterns</button>
|
<button type="button" class="edit-mode-only" data-target="patterns-btn">Patterns</button>
|
||||||
@@ -166,124 +162,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Outputs Modal (pixel outputs rendered on the Pi: DDP, Art-Net, sACN, USB-DMX) -->
|
|
||||||
<div id="outputs-modal" class="modal">
|
|
||||||
<div class="modal-content">
|
|
||||||
<h2>Outputs</h2>
|
|
||||||
<p class="muted-text">Pixel outputs the Pi renders for. Add an output's name to a zone's devices to drive it with that zone's presets.</p>
|
|
||||||
<div id="outputs-list-modal" class="profiles-list"></div>
|
|
||||||
<div class="modal-actions">
|
|
||||||
<button type="button" class="btn btn-primary" id="output-add-btn">Add output</button>
|
|
||||||
<button type="button" class="btn btn-secondary" id="outputs-close-btn">Close</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div id="edit-output-modal" class="modal">
|
|
||||||
<div class="modal-content">
|
|
||||||
<h2 id="edit-output-title">Output</h2>
|
|
||||||
<form id="edit-output-form" class="engine-form">
|
|
||||||
<input type="hidden" id="edit-output-id">
|
|
||||||
<label for="edit-output-name">Name</label>
|
|
||||||
<input type="text" id="edit-output-name" required autocomplete="off">
|
|
||||||
<label for="edit-output-protocol">Protocol</label>
|
|
||||||
<select id="edit-output-protocol">
|
|
||||||
<option value="ddp">DDP</option>
|
|
||||||
<option value="artnet">Art-Net</option>
|
|
||||||
<option value="sacn">sACN (E1.31)</option>
|
|
||||||
<option value="dmx_serial">USB-DMX</option>
|
|
||||||
</select>
|
|
||||||
<div class="engine-field" data-protocols="ddp artnet sacn">
|
|
||||||
<label for="edit-output-host">Host</label>
|
|
||||||
<input type="text" id="edit-output-host" placeholder="192.168.1.60 (blank = broadcast / multicast)" autocomplete="off">
|
|
||||||
</div>
|
|
||||||
<div class="engine-field" data-protocols="ddp artnet sacn">
|
|
||||||
<label for="edit-output-port">Port (blank = default)</label>
|
|
||||||
<input type="number" id="edit-output-port" min="1" max="65535">
|
|
||||||
</div>
|
|
||||||
<div class="engine-field" data-protocols="artnet sacn">
|
|
||||||
<label for="edit-output-universe">Start universe</label>
|
|
||||||
<input type="number" id="edit-output-universe" min="0" max="63999">
|
|
||||||
</div>
|
|
||||||
<div class="engine-field" data-protocols="dmx_serial">
|
|
||||||
<label for="edit-output-serial-port">Serial port</label>
|
|
||||||
<input type="text" id="edit-output-serial-port" placeholder="/dev/ttyUSB0" autocomplete="off">
|
|
||||||
</div>
|
|
||||||
<div class="engine-field" data-protocols="dmx_serial">
|
|
||||||
<label for="edit-output-dmx-mode">Interface</label>
|
|
||||||
<select id="edit-output-dmx-mode">
|
|
||||||
<option value="enttec_pro">Enttec DMX USB Pro</option>
|
|
||||||
<option value="open_dmx">Open DMX (FTDI)</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div class="engine-field" data-protocols="dmx_serial">
|
|
||||||
<label for="edit-output-channel">Start channel</label>
|
|
||||||
<input type="number" id="edit-output-channel" min="1" max="512" value="1">
|
|
||||||
</div>
|
|
||||||
<label for="edit-output-pixel-count">Pixels</label>
|
|
||||||
<input type="number" id="edit-output-pixel-count" min="1" value="60">
|
|
||||||
<label for="edit-output-pixel-offset">Pixel offset in zone frame</label>
|
|
||||||
<input type="number" id="edit-output-pixel-offset" min="0" value="0">
|
|
||||||
<label for="edit-output-color-order">Colour order</label>
|
|
||||||
<select id="edit-output-color-order">
|
|
||||||
<option value="rgb">RGB</option>
|
|
||||||
<option value="grb">GRB</option>
|
|
||||||
<option value="brg">BRG</option>
|
|
||||||
<option value="rbg">RBG</option>
|
|
||||||
<option value="gbr">GBR</option>
|
|
||||||
<option value="bgr">BGR</option>
|
|
||||||
</select>
|
|
||||||
<label for="edit-output-brightness">Brightness (0–255)</label>
|
|
||||||
<input type="number" id="edit-output-brightness" min="0" max="255" value="255">
|
|
||||||
<label for="edit-output-fps">Max FPS</label>
|
|
||||||
<input type="number" id="edit-output-fps" min="1" max="120" value="40">
|
|
||||||
<label class="engine-check"><input type="checkbox" id="edit-output-reverse"> Reverse</label>
|
|
||||||
<label class="engine-check"><input type="checkbox" id="edit-output-enabled" checked> Enabled</label>
|
|
||||||
<p id="edit-output-error" class="engine-error" hidden></p>
|
|
||||||
<div class="modal-actions">
|
|
||||||
<button type="submit" class="btn btn-primary">Save</button>
|
|
||||||
<button type="button" class="btn btn-secondary" id="edit-output-close-btn">Cancel</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Sequences Modal (timed preset chains per zone, run on the Pi) -->
|
|
||||||
<div id="sequences-modal" class="modal">
|
|
||||||
<div class="modal-content">
|
|
||||||
<h2>Sequences</h2>
|
|
||||||
<div id="sequences-list-modal" class="profiles-list"></div>
|
|
||||||
<div class="modal-actions">
|
|
||||||
<button type="button" class="btn btn-primary edit-mode-only" id="sequence-add-btn">New sequence</button>
|
|
||||||
<button type="button" class="btn btn-secondary" id="sequences-close-btn">Close</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div id="edit-sequence-modal" class="modal">
|
|
||||||
<div class="modal-content">
|
|
||||||
<h2 id="edit-sequence-title">Sequence</h2>
|
|
||||||
<form id="edit-sequence-form" class="engine-form">
|
|
||||||
<input type="hidden" id="edit-sequence-id">
|
|
||||||
<label for="edit-sequence-name">Name</label>
|
|
||||||
<input type="text" id="edit-sequence-name" required autocomplete="off">
|
|
||||||
<label for="edit-sequence-zone">Zone</label>
|
|
||||||
<select id="edit-sequence-zone" required></select>
|
|
||||||
<label class="engine-check"><input type="checkbox" id="edit-sequence-loop" checked> Loop</label>
|
|
||||||
<label for="edit-sequence-repeat">Repeat count (0 = forever, when looping)</label>
|
|
||||||
<input type="number" id="edit-sequence-repeat" min="0" value="0">
|
|
||||||
<h3 class="engine-subheading">Steps</h3>
|
|
||||||
<div id="edit-sequence-steps" class="engine-steps"></div>
|
|
||||||
<button type="button" class="btn btn-secondary" id="edit-sequence-add-step-btn">Add step</button>
|
|
||||||
<p id="edit-sequence-error" class="engine-error" hidden></p>
|
|
||||||
<div class="modal-actions">
|
|
||||||
<button type="submit" class="btn btn-primary">Save</button>
|
|
||||||
<button type="button" class="btn btn-secondary" id="edit-sequence-close-btn">Cancel</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Presets Modal -->
|
<!-- Presets Modal -->
|
||||||
<div id="presets-modal" class="modal">
|
<div id="presets-modal" class="modal">
|
||||||
<div class="modal-content">
|
<div class="modal-content">
|
||||||
@@ -665,7 +543,5 @@
|
|||||||
<script src="/static/patterns.js"></script>
|
<script src="/static/patterns.js"></script>
|
||||||
<script src="/static/presets.js"></script>
|
<script src="/static/presets.js"></script>
|
||||||
<script src="/static/devices.js"></script>
|
<script src="/static/devices.js"></script>
|
||||||
<script src="/static/outputs.js"></script>
|
|
||||||
<script src="/static/sequences.js"></script>
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
"""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)
|
|
||||||
@@ -1,303 +0,0 @@
|
|||||||
"""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
|
|
||||||
@@ -1,242 +0,0 @@
|
|||||||
"""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"]
|
|
||||||
@@ -1,119 +0,0 @@
|
|||||||
"""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)
|
|
||||||
@@ -1,214 +0,0 @@
|
|||||||
"""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
|
|
||||||
@@ -1,60 +1,60 @@
|
|||||||
from models.squence import Sequence
|
from models.squence import Sequence
|
||||||
|
import os
|
||||||
|
|
||||||
def test_sequence():
|
def test_sequence():
|
||||||
"""Test Sequence model CRUD operations."""
|
"""Test Sequence model CRUD operations."""
|
||||||
|
# Clean up any existing test file
|
||||||
|
if os.path.exists("Sequence.json"):
|
||||||
|
os.remove("Sequence.json")
|
||||||
|
|
||||||
sequences = Sequence()
|
sequences = Sequence()
|
||||||
|
|
||||||
print("Testing create sequence")
|
print("Testing create sequence")
|
||||||
sequence_id = sequences.create({
|
sequence_id = sequences.create("test_group", ["preset1", "preset2"])
|
||||||
"name": "test_sequence",
|
|
||||||
"zone_id": "1",
|
|
||||||
"steps": [{"preset_id": "preset1", "duration_s": 3}, {"preset_id": "preset2"}],
|
|
||||||
})
|
|
||||||
print(f"Created sequence with ID: {sequence_id}")
|
print(f"Created sequence with ID: {sequence_id}")
|
||||||
assert sequence_id is not None
|
assert sequence_id is not None
|
||||||
assert sequence_id in sequences
|
assert sequence_id in sequences
|
||||||
|
|
||||||
print("\nTesting read sequence")
|
print("\nTesting read sequence")
|
||||||
sequence = sequences.read(sequence_id)
|
sequence = sequences.read(sequence_id)
|
||||||
print(f"Read: {sequence}")
|
print(f"Read: {sequence}")
|
||||||
assert sequence is not None
|
assert sequence is not None
|
||||||
assert sequence["name"] == "test_sequence"
|
assert sequence["group_name"] == "test_group"
|
||||||
assert sequence["zone_id"] == "1"
|
assert len(sequence["presets"]) == 2
|
||||||
assert [s["preset_id"] for s in sequence["steps"]] == ["preset1", "preset2"]
|
assert "sequence_duration" in sequence
|
||||||
assert sequence["steps"][1]["duration_s"] == 5.0
|
assert "sequence_loop" in sequence
|
||||||
assert sequence["loop"] is True
|
|
||||||
assert sequence["active"] is False
|
|
||||||
|
|
||||||
print("\nTesting update sequence")
|
print("\nTesting update sequence")
|
||||||
update_data = {
|
update_data = {
|
||||||
"name": "updated_sequence",
|
"group_name": "updated_group",
|
||||||
"steps": [{"preset_id": p, "duration_s": 2} for p in ("preset3", "preset4", "preset5")],
|
"presets": ["preset3", "preset4", "preset5"],
|
||||||
"loop": False,
|
"sequence_duration": 5000,
|
||||||
"repeat_count": 3,
|
"sequence_transition": 1000,
|
||||||
|
"sequence_loop": True,
|
||||||
|
"sequence_repeat_count": 3
|
||||||
}
|
}
|
||||||
result = sequences.update(sequence_id, update_data)
|
result = sequences.update(sequence_id, update_data)
|
||||||
assert result is True
|
assert result is True
|
||||||
updated = sequences.read(sequence_id)
|
updated = sequences.read(sequence_id)
|
||||||
assert updated["name"] == "updated_sequence"
|
assert updated["group_name"] == "updated_group"
|
||||||
assert len(updated["steps"]) == 3
|
assert len(updated["presets"]) == 3
|
||||||
assert updated["loop"] is False
|
assert updated["sequence_duration"] == 5000
|
||||||
assert updated["repeat_count"] == 3
|
assert updated["sequence_loop"] is True
|
||||||
|
|
||||||
print("\nTesting list sequences")
|
print("\nTesting list sequences")
|
||||||
sequence_list = sequences.list()
|
sequence_list = sequences.list()
|
||||||
print(f"Sequence list: {sequence_list}")
|
print(f"Sequence list: {sequence_list}")
|
||||||
assert sequence_id in sequence_list
|
assert sequence_id in sequence_list
|
||||||
|
|
||||||
print("\nTesting delete sequence")
|
print("\nTesting delete sequence")
|
||||||
deleted = sequences.delete(sequence_id)
|
deleted = sequences.delete(sequence_id)
|
||||||
assert deleted is True
|
assert deleted is True
|
||||||
assert sequence_id not in sequences
|
assert sequence_id not in sequences
|
||||||
|
|
||||||
print("\nTesting read after delete")
|
print("\nTesting read after delete")
|
||||||
sequence = sequences.read(sequence_id)
|
sequence = sequences.read(sequence_id)
|
||||||
assert sequence is None
|
assert sequence is None
|
||||||
|
|
||||||
print("\nAll sequence tests passed!")
|
print("\nAll sequence tests passed!")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"""
|
"""
|
||||||
Browser automation tests using Selenium.
|
Browser automation tests using Selenium.
|
||||||
Tests run against the device in an actual browser. Target host defaults to
|
Tests run against the device in an actual browser. Target host defaults to
|
||||||
``192.168.4.1``; override with ``LED_CONTROLLER_DEVICE_IP`` (IP or hostname,
|
``127.0.0.1:5000``; override with ``LED_CONTROLLER_DEVICE_IP`` (IP or hostname,
|
||||||
or a full ``http://`` / ``https://`` base URL).
|
or a full ``http://`` / ``https://`` base URL).
|
||||||
|
|
||||||
Fixed delays between UI steps use ``LED_CONTROLLER_BROWSER_SLEEP_SCALE``
|
Fixed delays between UI steps use ``LED_CONTROLLER_BROWSER_SLEEP_SCALE``
|
||||||
@@ -49,7 +49,7 @@ from selenium.common.exceptions import (
|
|||||||
ElementNotInteractableException,
|
ElementNotInteractableException,
|
||||||
)
|
)
|
||||||
|
|
||||||
_DEFAULT_DEVICE_HOST = "192.168.4.1"
|
_DEFAULT_DEVICE_HOST = "127.0.0.1:5000"
|
||||||
|
|
||||||
|
|
||||||
def _device_base_url() -> str:
|
def _device_base_url() -> str:
|
||||||
|
|||||||
@@ -125,11 +125,6 @@ def server(monkeypatch, tmp_path_factory):
|
|||||||
import models.pattern as models_pattern # noqa: E402
|
import models.pattern as models_pattern # noqa: E402
|
||||||
import models.squence as models_sequence # noqa: E402
|
import models.squence as models_sequence # noqa: E402
|
||||||
import models.device as models_device # noqa: E402
|
import models.device as models_device # noqa: E402
|
||||||
import models.output as models_output # noqa: E402
|
|
||||||
import engine as engine_pkg # noqa: E402
|
|
||||||
|
|
||||||
# Fresh Pi-side engine per test (it caches players and sequence tasks).
|
|
||||||
engine_pkg.set_engine(None)
|
|
||||||
|
|
||||||
for cls in (
|
for cls in (
|
||||||
models_preset.Preset,
|
models_preset.Preset,
|
||||||
@@ -141,7 +136,6 @@ def server(monkeypatch, tmp_path_factory):
|
|||||||
models_pattern.Pattern,
|
models_pattern.Pattern,
|
||||||
models_sequence.Sequence,
|
models_sequence.Sequence,
|
||||||
models_device.Device,
|
models_device.Device,
|
||||||
models_output.Output,
|
|
||||||
):
|
):
|
||||||
if hasattr(cls, "_instance"):
|
if hasattr(cls, "_instance"):
|
||||||
delattr(cls, "_instance")
|
delattr(cls, "_instance")
|
||||||
@@ -176,7 +170,6 @@ def server(monkeypatch, tmp_path_factory):
|
|||||||
"controllers.pattern",
|
"controllers.pattern",
|
||||||
"controllers.settings",
|
"controllers.settings",
|
||||||
"controllers.device",
|
"controllers.device",
|
||||||
"controllers.output",
|
|
||||||
):
|
):
|
||||||
sys.modules.pop(mod_name, None)
|
sys.modules.pop(mod_name, None)
|
||||||
|
|
||||||
@@ -191,7 +184,6 @@ def server(monkeypatch, tmp_path_factory):
|
|||||||
import controllers.pattern as pattern_ctl # noqa: E402
|
import controllers.pattern as pattern_ctl # noqa: E402
|
||||||
import controllers.settings as settings_ctl # noqa: E402
|
import controllers.settings as settings_ctl # noqa: E402
|
||||||
import controllers.device as device_ctl # noqa: E402
|
import controllers.device as device_ctl # noqa: E402
|
||||||
import controllers.output as output_ctl # noqa: E402
|
|
||||||
|
|
||||||
# Configure transport sender used by /presets/send.
|
# Configure transport sender used by /presets/send.
|
||||||
from models.transport import set_sender # noqa: E402
|
from models.transport import set_sender # noqa: E402
|
||||||
@@ -219,7 +211,6 @@ def server(monkeypatch, tmp_path_factory):
|
|||||||
app.mount(pattern_ctl.controller, "/patterns")
|
app.mount(pattern_ctl.controller, "/patterns")
|
||||||
app.mount(settings_ctl.controller, "/settings")
|
app.mount(settings_ctl.controller, "/settings")
|
||||||
app.mount(device_ctl.controller, "/devices")
|
app.mount(device_ctl.controller, "/devices")
|
||||||
app.mount(output_ctl.controller, "/outputs")
|
|
||||||
|
|
||||||
@app.route("/")
|
@app.route("/")
|
||||||
def index(request):
|
def index(request):
|
||||||
@@ -536,32 +527,21 @@ def test_groups_sequences_scenes_palettes_patterns_endpoints(server):
|
|||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
|
|
||||||
# Sequences.
|
# Sequences.
|
||||||
unique_seq_name = f"pytest-seq-{uuid.uuid4().hex[:8]}"
|
unique_seq_group_name = f"pytest-seq-group-{uuid.uuid4().hex[:8]}"
|
||||||
resp = c.post(
|
resp = c.post(
|
||||||
f"{base_url}/sequences",
|
f"{base_url}/sequences",
|
||||||
json={"name": unique_seq_name, "steps": [{"preset_id": "1", "duration_s": 2}]},
|
json={"group_name": unique_seq_group_name, "presets": []},
|
||||||
)
|
)
|
||||||
assert resp.status_code == 201
|
assert resp.status_code == 201
|
||||||
sequences_list = c.get(f"{base_url}/sequences").json()
|
sequences_list = c.get(f"{base_url}/sequences").json()
|
||||||
seq_id = _find_id_by_field(sequences_list, "name", unique_seq_name)
|
seq_id = _find_id_by_field(sequences_list, "group_name", unique_seq_group_name)
|
||||||
|
|
||||||
resp = c.get(f"{base_url}/sequences/{seq_id}")
|
resp = c.get(f"{base_url}/sequences/{seq_id}")
|
||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
assert resp.json()["steps"] == [{"preset_id": "1", "duration_s": 2.0}]
|
|
||||||
|
|
||||||
resp = c.put(f"{base_url}/sequences/{seq_id}", json={"loop": False, "repeat_count": 2})
|
resp = c.put(f"{base_url}/sequences/{seq_id}", json={"sequence_duration": 1234})
|
||||||
assert resp.status_code == 200
|
|
||||||
assert resp.json()["loop"] is False and resp.json()["repeat_count"] == 2
|
|
||||||
|
|
||||||
resp = c.put(f"{base_url}/sequences/{seq_id}", json={"steps": [{"duration_s": 1}]})
|
|
||||||
assert resp.status_code == 400
|
|
||||||
|
|
||||||
# No zone_id -> cannot play.
|
|
||||||
resp = c.post(f"{base_url}/sequences/{seq_id}/play")
|
|
||||||
assert resp.status_code == 400
|
|
||||||
|
|
||||||
resp = c.get(f"{base_url}/sequences/status")
|
|
||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
|
assert resp.json()["sequence_duration"] == 1234
|
||||||
|
|
||||||
resp = c.delete(f"{base_url}/sequences/{seq_id}")
|
resp = c.delete(f"{base_url}/sequences/{seq_id}")
|
||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
@@ -784,76 +764,3 @@ def test_groups_sequences_scenes_palettes_patterns_endpoints(server):
|
|||||||
)
|
)
|
||||||
assert resp.status_code == 400
|
assert resp.status_code == 400
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def test_engine_outputs_zone_play_and_sequences(server):
|
|
||||||
c: requests.Session = server["client"]
|
|
||||||
base_url: str = server["base_url"]
|
|
||||||
sender: DummySender = server["sender"]
|
|
||||||
|
|
||||||
# Outputs CRUD + validation.
|
|
||||||
resp = c.post(f"{base_url}/outputs", json={"name": "wall", "protocol": "ddp"})
|
|
||||||
assert resp.status_code == 400 and "host" in resp.json()["error"]
|
|
||||||
resp = c.post(
|
|
||||||
f"{base_url}/outputs",
|
|
||||||
json={"name": "wall", "protocol": "ddp", "host": "127.0.0.1", "port": 9, "pixel_count": 10},
|
|
||||||
)
|
|
||||||
assert resp.status_code == 201
|
|
||||||
output_id = resp.json()["id"]
|
|
||||||
resp = c.put(f"{base_url}/outputs/{output_id}", json={"color_order": "grb"})
|
|
||||||
assert resp.status_code == 200 and resp.json()["color_order"] == "grb"
|
|
||||||
resp = c.post(f"{base_url}/outputs/{output_id}/test", json={"step_s": 0.1})
|
|
||||||
assert resp.status_code == 200 and resp.json()["status"]["frames"] > 0
|
|
||||||
|
|
||||||
# A profile gives us presets + a zone; add a pixel output and an ESP32 name to it.
|
|
||||||
resp = c.post(f"{base_url}/profiles", json={"name": f"pytest-engine-{uuid.uuid4().hex[:6]}"})
|
|
||||||
assert resp.status_code in (200, 201)
|
|
||||||
profile_id = str(resp.json().get("id") or next(iter(resp.json())))
|
|
||||||
c.post(f"{base_url}/profiles/{profile_id}/apply")
|
|
||||||
preset = c.post(f"{base_url}/presets", json={"name": "pytest-on", "pattern": "on", "colors": ["#ff0000"]})
|
|
||||||
assert preset.status_code == 201
|
|
||||||
preset_id = str(next(iter(preset.json())))
|
|
||||||
zone = c.post(f"{base_url}/zones", json={"name": "pytest-engine-zone", "names": ["wall", "dj"]})
|
|
||||||
assert zone.status_code in (200, 201)
|
|
||||||
zone_id = str(zone.json().get("id") or next(iter(zone.json())))
|
|
||||||
c.put(f"{base_url}/zones/{zone_id}", json={"names": ["wall", "dj"]})
|
|
||||||
|
|
||||||
resp = c.post(f"{base_url}/zones/{zone_id}/play", json={})
|
|
||||||
assert resp.status_code == 400
|
|
||||||
resp = c.post(f"{base_url}/zones/{zone_id}/play", json={"preset_id": "nope"})
|
|
||||||
assert resp.status_code == 404
|
|
||||||
|
|
||||||
sender.sent.clear()
|
|
||||||
resp = c.post(f"{base_url}/zones/{zone_id}/play", json={"preset_id": preset_id})
|
|
||||||
assert resp.status_code == 200, resp.text
|
|
||||||
status = resp.json()
|
|
||||||
assert status["preset_id"] == preset_id and status["frame_length"] == 10
|
|
||||||
kinds = sorted(o["kind"] for o in status["outputs"])
|
|
||||||
assert kinds == ["frame", "preset"]
|
|
||||||
# "dj" has no registered device -> preset + select still broadcast to the bridge.
|
|
||||||
sent = [json.loads(d) for d, _a in sender.sent]
|
|
||||||
assert any(m.get("presets", {}).get(preset_id) for m in sent)
|
|
||||||
assert {"v": "1", "select": {"dj": [preset_id]}} in sent
|
|
||||||
|
|
||||||
resp = c.get(f"{base_url}/zones/engine/status")
|
|
||||||
assert zone_id in resp.json()["zones"]
|
|
||||||
|
|
||||||
# Sequence on the zone.
|
|
||||||
resp = c.post(
|
|
||||||
f"{base_url}/sequences",
|
|
||||||
json={"name": "pytest-engine-seq", "zone_id": zone_id, "loop": False,
|
|
||||||
"steps": [{"preset_id": preset_id, "duration_s": 0.5}]},
|
|
||||||
)
|
|
||||||
seq_id = next(k for k, v in c.get(f"{base_url}/sequences").json().items()
|
|
||||||
if v.get("name") == "pytest-engine-seq")
|
|
||||||
resp = c.post(f"{base_url}/sequences/{seq_id}/play")
|
|
||||||
assert resp.status_code == 200 and resp.json()["zone_id"] == zone_id
|
|
||||||
assert c.get(f"{base_url}/sequences/{seq_id}").json()["active"] is True
|
|
||||||
resp = c.post(f"{base_url}/sequences/{seq_id}/stop")
|
|
||||||
assert resp.json()["stopped"] is True
|
|
||||||
assert c.get(f"{base_url}/sequences/{seq_id}").json()["active"] is False
|
|
||||||
|
|
||||||
resp = c.post(f"{base_url}/zones/{zone_id}/stop")
|
|
||||||
assert resp.json()["stopped"] is True
|
|
||||||
resp = c.delete(f"{base_url}/outputs/{output_id}")
|
|
||||||
assert resp.status_code == 200
|
|
||||||
Reference in new issue
Block a user