Author SHA1 Message Date
jimmyandClaude Opus 5.5 a5a7fc575f feat(engine): Pi-side animation engine with protocol outputs and sequencer
Add src/engine, modelled on technicalkiwi/portal's player and sequence runner:

- Pixel generator: runs the unchanged led-driver patterns under CPython
  (utime shim + NeoPixel-like buffer) on a per-zone render thread and
  streams frames to pixel outputs, with keepalive for static frames.
- Output drivers: DDP, Art-Net (ArtDMX/ArtSync), sACN/E1.31, USB-DMX
  (Enttec Pro / Open DMX), plus an ESP32 preset output that reuses the
  existing preset + select delivery path. Registry in db/output.json,
  CRUD and test pattern at /outputs.
- Sequencer: timed preset chains per zone (portal step shape), deadline
  scheduling, loop/repeat, resume after restart; legacy sequence records
  are migrated. Zone play/stop, sequence and scene play/stop endpoints.
- CLI (python -m engine.cli), Outputs and Sequences modals, preset tiles
  drive pixel outputs, API/README docs, engine test suite.

ESP32 firmware is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 13:24:14 +13:00
109 changed files with 4761 additions and 12879 deletions

No files matched your search

+1 -3
View File
@@ -7,8 +7,6 @@ alwaysApply: true
1. When creating a new pattern under `led-driver/src/patterns/`, also add/update a corresponding test file in `led-driver/tests/patterns/`.
2. When adding a new pattern, ensure led-controller has `db/pattern.json`; if it does not exist, create it. Add the new pattern metadata and parameter mappings there. Optionally set **`supports_manual`** to `false` when the pattern is a poor fit for manual mode or audio beat triggers (smooth/blended animations); omit or `true` otherwise.
2. When adding a new pattern, ensure led-controller has `db/pattern.json`; if it does not exist, create it. Add the new pattern metadata and parameter mappings there.
3. When adding a new pattern, add at least one test preset entry in `db/preset.json` in led-controller that uses the new pattern.
4. For any pattern that supports both auto and manual modes, keep behaviour parity unless explicitly requested otherwise: background colour handling, colour-cycling order, and parameter timing semantics (e.g. `n2`/`n3` meaning) must match between auto and manual paths.
@@ -1,18 +0,0 @@
---
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).
-11
View File
@@ -28,17 +28,6 @@ Thumbs.db
scripts/.led-controller-venv
docs/.help-print.html
settings.json
# Track shared JSON + preset binaries; ignore other db/*.json (e.g. device, zone) locally
db/*
!db/group.json
!db/palette.json
!db/pattern.json
!db/preset.json
!db/profile.json
!db/scene.json
!db/sequence.json
!db/presets/
!db/presets/*.bin
*.log
*.db
*.sqlite
+5 -8
View File
@@ -14,8 +14,6 @@ selenium = "*"
adafruit-ampy = "*"
microdot = "*"
websockets = "*"
numpy = "*"
sounddevice = "*"
[dev-packages]
pytest = "*"
@@ -24,10 +22,9 @@ pytest = "*"
python_version = "3.11"
[scripts]
web = "python tests/web.py"
watch = "python -m watchfiles \"python tests/web.py\" src tests"
web = "python /home/pi/led-controller/tests/web.py"
watch = "python -m watchfiles 'python tests/web.py' src tests"
install = "pipenv install"
run = "sh -c 'cd src && python main.py'"
dev = "python -m watchfiles \"sh -c 'cd src && LED_CONTROLLER_LIVE_RELOAD=1 python main.py'\" src"
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'"
dev = "watchfiles \"sh -c 'cd src && python main.py'\" src"
help-pdf = "sh scripts/build_help_pdf.sh"
Generated
+57 -167
View File
@@ -1,7 +1,7 @@
{
"_meta": {
"hash": {
"sha256": "7975a888034cb3e0f68c7b866f7e69e5a1db7a5228fe1f02d6cb5f9c180de557"
"sha256": "98da2012e549e7b62ed49a5e1717acaf535b71e8df61bf4108d25b9023be612e"
},
"pipfile-spec": 6,
"requires": {
@@ -40,13 +40,6 @@
"markers": "python_version >= '3.9'",
"version": "==26.1.0"
},
"aubio": {
"hashes": [
"sha256:df1244f6c4cf5bea382c8c2d35aa43bc31f4cf631fe325ae3992c219546a4202"
],
"index": "pypi",
"version": "==0.4.9"
},
"bitarray": {
"hashes": [
"sha256:0256d57e294414bfe4fec4f852fd1d9ae361228c71b082332bf81c8b8fc69f80",
@@ -259,7 +252,7 @@
"sha256:fc7de24befaeae77ba923797c7c87834c73648a05a4bde34b3b7e5588973a453",
"sha256:fe562eb1a64e67dd297ccc4f5addea2501664954f2692b69a76449ec7913ecbf"
],
"markers": "python_version >= '3.9'",
"markers": "python_full_version >= '3.9' and platform_python_implementation != 'PyPy'",
"version": "==2.0.0"
},
"charset-normalizer": {
@@ -407,65 +400,64 @@
},
"cryptography": {
"hashes": [
"sha256:0890f502ddf7d9c6426129c3f49f5c0a39278ed7cd6322c8755ffca6ee675a13",
"sha256:0c558d2cdffd8f4bbb30fc7134c74d2ca9a476f830bb053074498fbc86f41ed6",
"sha256:16cd65b9330583e4619939b3a3843eec1e6e789744bb01e7c7e2e62e33c239c8",
"sha256:18349bbc56f4743c8b12dc32e2bccb2cf83ee8b69a3bba74ef8ae857e26b3d25",
"sha256:1e2d54c8be6152856a36f0882ab231e70f8ec7f14e93cf87db8a2ed056bf160c",
"sha256:22a5cb272895dce158b2cacdfdc3debd299019659f42947dbdac6f32d68fe832",
"sha256:27241b1dc9962e056062a8eef1991d02c3a24569c95975bd2322a8a52c6e5e12",
"sha256:2b4d59804e8408e2fea7d1fbaf218e5ec984325221db76e6a241a9abd6cdd95c",
"sha256:2eb992bbd4661238c5a397594c83f5b4dc2bc5b848c365c8f991b6780efcc5c7",
"sha256:369a6348999f94bbd53435c894377b20ab95f25a9065c283570e70150d8abc3c",
"sha256:3cb07a3ed6431663cd321ea8a000a1314c74211f823e4177fefa2255e057d1ec",
"sha256:40ba1f85eaa6959837b1d51c9767e230e14612eea4ef110ee8854ada22da1bf5",
"sha256:4defde8685ae324a9eb9d818717e93b4638ef67070ac9bc15b8ca85f63048355",
"sha256:55b7718303bf06a5753dcdccf2f3945cf18ad7bffde41b61226e4db31ab89a9c",
"sha256:561215ea3879cb1cbbf272867e2efda62476f240fb58c64de6b393ae19246741",
"sha256:58d00498e8933e4a194f3076aee1b4a97dfec1a6da444535755822fe5d8b0b86",
"sha256:59baa2cb386c4f0b9905bd6eb4c2a79a69a128408fd31d32ca4d7102d4156321",
"sha256:5a5ed8fde7a1d09376ca0b40e68cd59c69fe23b1f9768bd5824f54681626032a",
"sha256:5b012212e08b8dd5edc78ef54da83dd9892fd9105323b3993eff6bea65dc21d7",
"sha256:5c3932f4436d1cccb036cb0eaef46e6e2db91035166f1ad6505c3c9d5a635920",
"sha256:614d0949f4790582d2cc25553abd09dd723025f0c0e7c67376a1d77196743d6e",
"sha256:76341972e1eff8b4bea859f09c0d3e64b96ce931b084f9b9b7db8ef364c30eff",
"sha256:77a2ccbbe917f6710e05ba9adaa25fb5075620bf3ea6fb751997875aff4ae4bd",
"sha256:7995ef305d7165c3f11ae07f2517e5a4f1d5c18da1376a0a9ed496336b69e5f3",
"sha256:7ce4bfae76319a532a2dc68f82cc32f5676ee792a983187dac07183690e5c66f",
"sha256:7e8eac43dfca5c4cccc6dad9a80504436fca53bb9bc3100a2386d730fbe6b602",
"sha256:84cf79f0dc8b36ac5da873481716e87aef31fcfa0444f9e1d8b4b2cece142855",
"sha256:8c7378637d7d88016fa6791c159f698b3d3eed28ebf844ac36b9dc04a14dae18",
"sha256:8cd666227ef7af430aa5914a9910e0ddd703e75f039cef0825cd0da71b6b711a",
"sha256:906cbf0670286c6e0044156bc7d4af9cbb0ef6db9f73e52c3ec56ba6bdde5336",
"sha256:9071196d81abc88b3516ac8cdfad32e2b66dd4a5393a8e68a961e9161ddc6239",
"sha256:9249e3cd978541d665967ac2cb2787fd6a62bddf1e75b3e347a594d7dacf4f74",
"sha256:984a20b0f62a26f48a3396c72e4bc34c66e356d356bf370053066b3b6d54634a",
"sha256:9be5aafa5736574f8f15f262adc81b2a9869e2cfe9014d52a44633905b40d52c",
"sha256:9c459db21422be75e2809370b829a87eb37f74cd785fc4aa9ea1e5f43b47cda4",
"sha256:9ccdac7d40688ecb5a3b4a604b8a88c8002e3442d6c60aead1db2a89a041560c",
"sha256:a0e692c683f4df67815a2d258b324e66f4738bd7a96a218c826dce4f4bd05d8f",
"sha256:a5da777e32ffed6f85a7b2b3f7c5cbc88c146bfcd0a1d7baf5fcc6c52ee35dd4",
"sha256:a64697c641c7b1b2178e573cbc31c7c6684cd56883a478d75143dbb7118036db",
"sha256:ad64688338ed4bc1a6618076ba75fd7194a5f1797ac60b47afe926285adb3166",
"sha256:bd72e68b06bb1e96913f97dd4901119bc17f39d4586a5adf2d3e47bc2b9d58b5",
"sha256:c17dfe85494deaeddc5ce251aebd1d60bbe6afc8b62071bb0b469431a000124f",
"sha256:c18684a7f0cc9a3cb60328f496b8e3372def7c5d2df39ac267878b05565aaaae",
"sha256:cc90c0b39b2e3c65ef52c804b72e3c58f8a04ab2a1871272798e5f9572c17d20",
"sha256:db63bf618e5dea46c07de12e900fe1cdd2541e6dc9dbae772a70b7d4d4765f6a",
"sha256:ea8990436d914540a40ab24b6a77c0969695ed52f4a4874c5137ccf7045a7057",
"sha256:ecde28a596bead48b0cfd2a1b4416c3d43074c2d785e3a398d7ec1fc4d0f7fbb",
"sha256:f5333311663ea94f75dd408665686aaf426563556bb5283554a3539177e03b8c",
"sha256:fdfef35d751d510fcef5252703621574364fec16418c4a1e5e1055248401054b"
"sha256:0024b87d47ae2399165a6bfb20d24888881eeab83ae2566d62467c5ff0030ce7",
"sha256:07efe86201817e7d3c18781ca9770bc0db04e1e48c994be384e4602bc38f8f27",
"sha256:09f6d7bf6724f8db8b32f11eccf23efc8e759924bc5603800335cf8859a3ddbd",
"sha256:11438c7518132d95f354fa01a4aa2f806d172a061a7bed18cf18cbdacdb204d7",
"sha256:11dbb9f50a0f1bb9757b3d8c27c1101780efb8f0bdecfb12439c22a74d64c001",
"sha256:14432c8a9bcb37009784f9594a62fae211a2ae9543e96c92b2a8e4c3cd5cd0c4",
"sha256:1581aef4219f7ca2849d0250edaa3866212fb74bf5667284f46aa92f9e65c1ca",
"sha256:160ad728f128972d362e714054f6ba0067cab7fb350c5202a9ae8ae4ce3ef1a0",
"sha256:1a405c08857258c11016777e11c02bacbe7ef596faf259305d282272a3a05cbe",
"sha256:1e47422b5557bb82d3fff997e8d92cff4e28b9789576984f08c248d2b3535d93",
"sha256:20fdbe3e38fb67c385d233c89371fa27f9909f6ebca1cecc20c13518dae65475",
"sha256:2207a498b03275d0051589e326b79d4cf59985c99031b05bb292ac52631c37fe",
"sha256:256d07c78a04d6b276f5df935a9923275f53bd1522f214447fdf365494e2d515",
"sha256:2b45761c6ec22b7c726d6a829558777e32d0f1c8be7c3f3480f9c912d5ee8a10",
"sha256:2ebd84adf0728c039a3be2700289378e1c164afc6748df1a5ed456767bef9ba7",
"sha256:34b4358b925a5ea3e14384ca781a2c0ef7ac219b57bb9eacc4457078e2b19f92",
"sha256:3fb8fa48075fad7193f2e5496135c6a76ac4b2aa5a38433df0a539296b377829",
"sha256:4e1de79e047e25d6e9f8cea71c86b4a53aced64134f0f003bbcbf3655fd172c8",
"sha256:4f7722c97826770bab8ae92959a2e7b20a5e9e9bf4deae68fd86c3ca457bab52",
"sha256:51c9313e90bd1690ec5a75ed047c27c0b8e6c570029712943d6116ef9a90620b",
"sha256:5d0e362ff51041b0c0d219cc7d6924d7b8996f57ce5712bdcef71eb3c65a59cc",
"sha256:6651d32eff255423503aa276739da98c30f26c40cbeffcc6048e0d54ef704c0c",
"sha256:6eebcaf0df1d21ce1f90605c9b432dd2c4f4ab665ac29a40d5e3fc68f51b5e63",
"sha256:6f29f36582e6151d9686235e586dd35bb67491f024767d10b842e520dc6a07ac",
"sha256:7a02675e2fabd0c0fc04c868b8781863cbf1967691543c22f5470500ff840b31",
"sha256:7f1207974a904e005f762869996cf620e9bf79ecb4622f148550bb48e0eb35a7",
"sha256:7f68d6fbc7fbbcfb0939fea72c3b96a9f9a6edfc0e1b1d29778a2066030418b1",
"sha256:7fda2f02c9015db3f42bb8a22324a454516ed10a8c29ca6ece6cdbb5efe2a203",
"sha256:80887c5cbd1774683cb126f0ab4184567f080071d5acf62205acb354b4b753b7",
"sha256:835d2d7f47cdc53b3224e90810fb1d36ca94ea29cc1801fb4c1bc43876735769",
"sha256:8c1a736bbb3288005796c3f7ccb9453360d7fed483b13b9f468aea5171432923",
"sha256:9af828c0d5a65c70ec729cd7495a4bf1a67ecb66417b8f02ff125ab8a6326a74",
"sha256:9c59ab0e0fa3a180a5a9c59f3a5abe3ef90d474bc56d7fadfbe80359491b615b",
"sha256:9f8e55fe4e63613a5e1cc5819030f27b97742d720203a087802ce4ce9ceb52bb",
"sha256:9fe6b7c64926c765f9dff301f9c1b867febcda5768868ca084e18589113732ab",
"sha256:a49a3eb5341b9503fa3000a9a0db033161db90d47285291f53c2a9d2cd1b7f76",
"sha256:a9b761f012a943b7de0e828843c5688d0de94a0578d44d6c85a1bae32f87791f",
"sha256:b1c76fca783aa7698eb21eb14f9c4aa09452248ee54a627d125025a43f83e7a7",
"sha256:b9a8943e359b7615db1a3ba587994618e094ff3d6fa5a390c73d079ce18b3973",
"sha256:be12cb6a204f77ed968bcefe68086eb061695b540a3dd05edac507a3111b25f0",
"sha256:cffbba3392df0fa8629bb7f43454ee2925059ee158e23c54620b9063912b86c8",
"sha256:ed67ea4e0cfb5faa5bc7ecb6e2b8838f3807a03758eec239d6c21c8769355310",
"sha256:edd4da498015da5b9f26d38d3bfc2e90257bfa9cbed1f6767c282a0025ae649b",
"sha256:ef6b3634087f18d2155b1e8ce264e5345a753da2c5fa9815e7d41315c90f8318",
"sha256:f1557695e5c2b86e204f6ce9470497848634100787935ab7adc5397c54abd7ab",
"sha256:f5c15764f261394b22aef6b00252f5195f46f2ca300bec57149474e2538b31f8",
"sha256:f5c3296dab66202f1b18a91fa266be93d6aa0c2806ea3d67762c69f60adc71aa",
"sha256:f7db373287273d8af1414cf95dc4118b13ffdc62be521997b0f2b270771fef50",
"sha256:f9a034b642b960767fb343766ae5ba6ad653f2e890ddd82955aef288ffea8736"
],
"markers": "python_version >= '3.9' and python_full_version not in '3.9.0, 3.9.1'",
"version": "==48.0.0"
"markers": "python_version >= '3.8' and python_full_version not in '3.9.0, 3.9.1'",
"version": "==47.0.0"
},
"esptool": {
"hashes": [
"sha256:9c355b7d6331cc92979cc710ae5c41f59830d1ea29ec24c467c6005a092c06d6"
],
"index": "pypi",
"markers": "python_version >= '3.10'",
"version": "==5.2.0"
},
"h11": {
@@ -493,11 +485,11 @@
},
"markdown-it-py": {
"hashes": [
"sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49",
"sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a"
"sha256:87327c59b172c5011896038353a81343b6754500a08cd7a4973bb48c6d578147",
"sha256:cb0a2b4aa34f932c007117b194e945bd74e0ec24133ceb5bac59009cda1cb9f3"
],
"markers": "python_version >= '3.10'",
"version": "==4.2.0"
"version": "==4.0.0"
},
"mdurl": {
"hashes": [
@@ -513,7 +505,6 @@
"sha256:d56824f4510e628dac711c86121957894ceaf833298e4d25f06c29d2b19a1721"
],
"index": "pypi",
"markers": "python_version >= '3.8'",
"version": "==2.6.1"
},
"mpremote": {
@@ -522,88 +513,8 @@
"sha256:fdb5626be83dff4e53c0184f8950814cb519b524dba7f1f8b1668aa477257a31"
],
"index": "pypi",
"markers": "python_version >= '3.4'",
"version": "==1.28.0"
},
"numpy": {
"hashes": [
"sha256:07077278157d02f65c43b1b26a3886bce886f95d20aabd11f87932750dfb14ed",
"sha256:08f2e31ed5e6f04b118e49821397f12767934cfdd12a1ce86a058f91e004ee50",
"sha256:0aec54fd785890ecca25a6003fd9a5aed47ad607bbac5cd64f836ad8666f4959",
"sha256:0d35aea54ad1d420c812bfa0385c71cd7cc5bcf7c65fed95fc2cd02fe8c79827",
"sha256:0d4e437e295f18ec29bc79daf55e8a47a9113df44d66f702f02a293d93a2d6dd",
"sha256:0dfd3f9d3adbe2920b68b5cd3d51444e13a10792ec7154cd0a2f6e74d4ab3233",
"sha256:1378871da56ca8943c2ba674530924bb8ca40cd228358a3b5f302ad60cf875fc",
"sha256:15716cfef24d3a9762e3acdf87e27f58dc823d1348f765bbea6bef8c639bfa1b",
"sha256:19710a9ca9992d7174e9c52f643d4272dcd1558c5f7af7f6f8190f633bd651a7",
"sha256:23cbfd4c17357c81021f21540da84ee282b9c8fba38a03b7b9d09ba6b951421e",
"sha256:2483e4584a1cb3092da4470b38866634bafb223cbcd551ee047633fd2584599a",
"sha256:27a8d92cd10f1382a67d7cf4db7ce18341b66438bdd9f691d7b0e48d104c2a9d",
"sha256:28a650663f7314afc3e6ec620f44f333c386aad9f6fc472030865dc0ebb26ee3",
"sha256:2aa0613a5177c264ff5921051a5719d20095ea586ca88cc802c5c218d1c67d3e",
"sha256:2c194dd721e54ecad9ad387c1d35e63dce5c4450c6dc7dd5611283dda239aabb",
"sha256:2d19e6e2095506d1736b7d80595e0f252d76b89f5e715c35e06e937679ea7d7a",
"sha256:2d390634c5182175533585cc89f3608a4682ccb173cc9bb940b2881c8d6f8fa0",
"sha256:30caa73029a225b2d40d9fae193e008e24b2026b7ee1a867b7ee8d96ca1a448e",
"sha256:42c16925aa5a02362f986765f9ebabf20de75cdefdca827d14315c568dcab113",
"sha256:45dbed2ab436a9e826e302fcdcbe9133f9b0006e5af7168afb8963a6520da103",
"sha256:4636de7fd195197b7535f231b5de9e4b36d2c440b6e566d2e4e4746e6af0ca93",
"sha256:4a19d9dba1a76618dd86b164d608566f393f8ec6ac7c44f0cc879011c45e65af",
"sha256:4bbc7f303d125971f60ec0aaad5e12c62d0d2c925f0ab1273debd0e4ba37aba5",
"sha256:4d6d57903571f86180eb98f8f0c839fa9ebbfb031356d87f1361be91e433f5b7",
"sha256:4e874c976154687c1f71715b034739b45c7711bec81db01914770373d125e392",
"sha256:51fc224f7ca4d92656d5a5eb315f12eb5fe2c97a66249aa7b5f562528a3be38c",
"sha256:58c8b5929fcb8287cbd6f0a3fae19c6e03a5c48402ae792962ac465224a629a4",
"sha256:5a285b3b96f951841799528cd1f4f01cd70e7e0204b4abebac9463eecfcf2a40",
"sha256:5c70f1cc1c4efbe316a572e2d8b9b9cc44e89b95f79ca3331553fbb63716e2bf",
"sha256:62d6b0f03b694173f9fcb1fb317f7222fd0b0b103e784c6549f5e53a27718c44",
"sha256:6a246d5914aa1c820c9443ddcee9c02bec3e203b0c080349533fae17727dfd1b",
"sha256:6aa3236c78803afbcb255045fbef97a9e25a1f6c9888357d205ddc42f4d6eba5",
"sha256:6bbe4eb67390b0a0265a2c25458f6b90a409d5d069f1041e6aff1e27e3d9a79e",
"sha256:715d1c092715954784bc79e1174fc2a90093dc4dc84ea15eb14dad8abdcdeb74",
"sha256:72944b19f2324114e9dc86a159787333b77874143efcf89a5167ef83cfee8af0",
"sha256:81f4a14bee47aec54f883e0cad2d73986640c1590eb9bfaaba7ad17394481e6e",
"sha256:846300f379b5b12cc769334464656bc882e0735d27d9726568bc932fdc49d5ec",
"sha256:86b6f55f5a352b48d7fbfd2dbc3d5b780b2d79f4d3c121f33eb6efb22e9a2015",
"sha256:874f200b2a981c647340f841730fc3a2b54c9d940566a3c4149099591e2c4c3d",
"sha256:8a87ec22c87be071b6bdbd27920b129b94f2fc964358ce38f3822635a3e2e03d",
"sha256:8b3b60bb7cba2c8c81837661c488637eee696f59a877788a396d33150c35d842",
"sha256:8e3ed142f2728df44263aaf5fb1f5b0b99f4070c553a0d7f033be65338329150",
"sha256:93e15038125dc1e5345d9b5b68aa7f996ec33b98118d18c6ca0d0b7d6198b7e8",
"sha256:989824e9faf85f96ec9c7761cd8d29c531ad857bfa1daa930cba85baaecf1a9a",
"sha256:99d838547ace2c4aace6c4f76e879ddfe02bb58a80c1549928477862b7a6d6ed",
"sha256:9b2aec6af35c113b05695ebb5749a787acd63cafc83086a05771d1e1cd1e555f",
"sha256:9c585a1790d5436a5374bac930dad6ed244c046ed91b2b2a3634eb2971d21008",
"sha256:a7164afb23be6e37ad90b2f10426149fd75aee07ca55653d2aa41e66c4ef697e",
"sha256:ac6b31e35612a26483e20750126d30d0941f949426974cace8e6b5c58a3657b0",
"sha256:ad2e2ef14e0b04e544ea2fa0a36463f847f113d314aa02e5b402fdf910ef309e",
"sha256:b268594bccac7d7cf5844c7732e3f20c50921d94e36d7ec9b79e9857694b1b2f",
"sha256:b5f0362dc928a6ecd9db58868fca5e48485205e3855957bdedea308f8672ea4a",
"sha256:ba1f4fc670ed79f876f70082eff4f9583c15fb9a4b89d6188412de4d18ae2f40",
"sha256:ba203255017337d39f89bdd58417f03c4426f12beed0440cfd933cb15f8669c7",
"sha256:c901b15172510173f5cb310eae652908340f8dede90fff9e3bf6c0d8dfd92f83",
"sha256:c9b39d38a9bd2ae1becd7eac1303d031c5c110ad31f2b319c6e7d98b135c934d",
"sha256:d2a8490669bfe99a233298348acc2d824d496dee0e66e31b66a6022c2ad74a5c",
"sha256:dddbbd259598d7240b18c9d87c56a9d2fb3b02fe266f49a7c101532e78c1d871",
"sha256:df3775294accfdd75f32c74ae39fcba920c9a378a2fc18a12b6820aa8c1fb502",
"sha256:e44319a2953c738205bf3354537979eaa3998ed673395b964c1176083dd46252",
"sha256:e4a010c27ff6f210ff4c6ef34394cd61470d01014439b192ec22552ee867f2a8",
"sha256:e823b8b6edc81e747526f70f71a9c0a07ac4e7ad13020aa736bb7c9d67196115",
"sha256:e892aff75639bbef0d2a2cfd55535510df26ff92f63c92cd84ef8d4ba5a5557f",
"sha256:eea7ac5d2dce4189771cedb559c738a71512768210dc4e4753b107a2048b3d0e",
"sha256:ef4059d6e5152fa1a39f888e344c73fdc926e1b2dd58c771d67b0acfbf2aa67d",
"sha256:f169b9a863d34f5d11b8698ead99febeaa17a13ca044961aa8e2662a6c7766a0",
"sha256:f2cf083b324a467e1ab358c105f6cad5ea950f50524668a80c486ff1db24e119",
"sha256:f8474c4241bc18b750be2abea9d7a9ec84f46ef861dbacf86a4f6e043401f79e",
"sha256:f983334aea213c99992053ede6168500e5f086ce74fbc4acc3f2b00f5762e9db",
"sha256:f9e75681b59ddaa5e659898085ae0eaea229d054f2ac0c7e563a62205a700121",
"sha256:fbc356aae7adf9e6336d336b9c8111d390a05df88f1805573ebb0807bd06fd1d",
"sha256:fcfe2045fd2e8f3cb0ce9d4ba6dba6333b8fa05bb8a4939c908cd43322d14c7e"
],
"index": "pypi",
"markers": "python_version >= '3.11'",
"version": "==2.4.4"
},
"outcome": {
"hashes": [
"sha256:9dcf02e65f2971b80047b377468e72a268e15c0af3cf1238e6ff14f7f91143b8",
@@ -642,7 +553,6 @@
"sha256:c74a7a2adf861c04d002db713dd85f84beb242228e671280bf709d765b03672b"
],
"index": "pypi",
"markers": "python_version >= '3.9'",
"version": "==2.12.1"
},
"pyserial": {
@@ -761,7 +671,6 @@
"sha256:4e6d1ef462f3626a1f0a0a9c42dd93c63bad33f9f1c1937509b8c5c8718ab56a"
],
"index": "pypi",
"markers": "python_version >= '3.10'",
"version": "==2.33.1"
},
"rich": {
@@ -786,7 +695,6 @@
"sha256:bada5c08a989f812728a4b5bea884d8e91894e939a441cc3a025201ce718581e"
],
"index": "pypi",
"markers": "python_version >= '3.10'",
"version": "==4.43.0"
},
"sniffio": {
@@ -804,19 +712,6 @@
],
"version": "==2.4.0"
},
"sounddevice": {
"hashes": [
"sha256:05eb9fd6c54c38d67741441c19164c0dae8ce80453af2d8c4ad2e7823d15b722",
"sha256:1234cc9b4c9df97b6cbe748146ae0ec64dd7d6e44739e8e42eaa5b595313a103",
"sha256:22487b65198cb5bf2208755105b524f78ad173e5ab6b445bdab1c989f6698df3",
"sha256:30ff99f6c107f49d25ad16a45cacd8d91c25a1bcdd3e81a206b921a3a6405b1f",
"sha256:3861901ddd8230d2e0e8ae62ac320cdd4c688d81df89da036dcb812f757bb3e6",
"sha256:cfc6b2c49fb7f555591c78cb8ecf48d6a637fd5b6e1db5fec6ed9365d64b3519"
],
"index": "pypi",
"markers": "python_version >= '3.7'",
"version": "==0.5.5"
},
"tibs": {
"hashes": [
"sha256:01ea5258bdf942d21560dc07d532082cd04f07cfef65fedd58ae84f7d0d2562a",
@@ -879,9 +774,7 @@
"version": "==4.15.0"
},
"urllib3": {
"extras": [
"socks"
],
"extras": [],
"hashes": [
"sha256:1b62b6884944a57dbe321509ab94fd4d3b307075e0c2eae991ac71ee15ad38ed",
"sha256:bf272323e553dfb2e87d9bfd225ca7b0f467b919d7bbd355436d3fd37cb0acd4"
@@ -1002,7 +895,6 @@
"sha256:f9a2ae5c91cecc9edd47e041a930490c31c3afb1f5e6d71de3dc671bfaca02bf"
],
"index": "pypi",
"markers": "python_version >= '3.9'",
"version": "==1.1.1"
},
"websocket-client": {
@@ -1078,7 +970,6 @@
"sha256:fd3cb4adb94a2a6e2b7c0d8d05cb94e6f1c81a0cf9dc2694fb65c7e8d94c42e4"
],
"index": "pypi",
"markers": "python_version >= '3.10'",
"version": "==16.0"
},
"wsproto": {
@@ -1129,7 +1020,6 @@
"sha256:b86ada508af81d19edeb213c681b1d48246c1a91d304c6c81a427674c17eb91c"
],
"index": "pypi",
"markers": "python_version >= '3.10'",
"version": "==9.0.3"
}
}
+18
View File
@@ -41,3 +41,21 @@ LED controller web app for managing profiles, **zones**, presets, and colour pal
## 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.
## 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
View File
@@ -0,0 +1 @@
{"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 -1
View File
@@ -1 +1 @@
{"1": {"name": "group1", "devices": ["e8f60a16fb00", "e8f60a170794"], "wifi_driver_display_name": "desk", "wifi_driver_num_leds": 59, "wifi_color_order": "rgb", "wifi_startup_mode": "default", "pattern": "on", "colors": ["000000", "FF0000"], "brightness": 100, "delay": 100, "step_offset": 0, "step_increment": 1, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "output_brightness": 255}, "2": {"name": "group2", "devices": ["188b0e1560a8"], "wifi_driver_display_name": null, "wifi_driver_num_leds": null, "wifi_color_order": "rgb", "wifi_startup_mode": "default", "output_brightness": 255, "pattern": "on", "colors": ["000000", "FF0000"], "brightness": 100, "delay": 100, "step_offset": 0, "step_increment": 1, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0}, "3": {"name": "group3", "devices": ["e8f60a16f288"], "wifi_driver_display_name": null, "wifi_driver_num_leds": null, "wifi_color_order": "rgb", "wifi_startup_mode": "default", "output_brightness": 255, "pattern": "on", "colors": ["000000", "FF0000"], "brightness": 100, "delay": 100, "step_offset": 0, "step_increment": 1, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0}, "4": {"name": "group4", "devices": ["e8f60a16e79c"], "wifi_driver_display_name": null, "wifi_driver_num_leds": null, "wifi_color_order": "rgb", "wifi_startup_mode": "default", "output_brightness": 255, "pattern": "on", "colors": ["000000", "FF0000"], "brightness": 100, "delay": 100, "step_offset": 0, "step_increment": 1, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0}, "5": {"name": "desk", "devices": ["188b0e1560a8"], "wifi_driver_display_name": null, "wifi_driver_num_leds": null, "wifi_color_order": "rgb", "wifi_startup_mode": "default", "output_brightness": 255, "pattern": "on", "colors": ["000000", "FF0000"], "brightness": 100, "delay": 100, "step_offset": 0, "step_increment": 1, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": null}}
{"1": {"name": "Main Group", "devices": ["1", "2", "3"]}, "2": {"name": "Accent Group", "devices": ["4", "5"]}}
+1
View File
@@ -0,0 +1 @@
{}
+1 -1
View File
@@ -1 +1 @@
{"1": ["#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#FF00FF", "#00FFFF", "#FFFFFF", "#000000", "#050500"], "2": [], "3": [], "4": [], "5": [], "6": [], "7": ["#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#FF00FF", "#00FFFF", "#FFFFFF", "#000000"], "8": [], "9": [], "10": [], "11": [], "12": ["#890b0b", "#0b8935"], "13": []}
{"1": ["#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#FF00FF", "#00FFFF", "#FFFFFF", "#000000"], "2": [], "3": [], "4": [], "5": [], "6": [], "7": ["#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#FF00FF", "#00FFFF", "#FFFFFF", "#000000"], "8": [], "9": [], "10": [], "11": [], "12": ["#890b0b", "#0b8935"]}
+1 -280
View File
@@ -1,280 +1 @@
{
"on": {
"min_delay": 10,
"max_delay": 10000,
"max_colors": 1,
"supports_manual": true
},
"off": {
"min_delay": 10,
"max_delay": 10000,
"max_colors": 0,
"supports_manual": true
},
"colour_cycle": {
"supports_reverse": true,
"n1": "Step rate",
"mode": {
"0": "Scroll palette gradient",
"1": "Rainbow wheel (preset colours ignored)"
},
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"supports_manual": true
},
"transition": {
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"supports_manual": false
},
"chase": {
"supports_reverse": true,
"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,
"supports_manual": true,
"mode": {
"0": "Two-colour chase",
"1": "Marquee dashes (n1 on length, n2 off, n3 step)"
}
},
"pulse": {
"n1": "Attack",
"n2": "Hold",
"n3": "Decay",
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"has_background": true,
"supports_manual": 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,
"supports_manual": false
},
"blink": {
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"has_background": true,
"supports_manual": false
},
"flicker": {
"n1": "Min brightness",
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"supports_manual": true
},
"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,
"supports_manual": false
},
"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,
"has_background": true,
"supports_manual": true
},
"radiate": {
"n1": "Node spacing (LEDs)",
"n2": "Out time (ms)",
"n3": "In time (ms)",
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"has_background": true,
"supports_manual": true
},
"plasma": {
"n1": "Scale",
"n2": "Speed",
"n3": "Contrast",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"supports_manual": false
},
"bar_graph": {
"n1": "Level percent",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"has_background": true,
"supports_manual": false
},
"strobe_burst": {
"n1": "Burst count",
"n2": "Burst gap",
"n3": "Cooldown",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"has_background": true,
"supports_manual": true
},
"rain_drops": {
"n1": "Drop rate",
"n2": "Ripple width",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"has_background": true,
"supports_manual": true
},
"clock_sweep": {
"n1": "Hand width",
"n2": "Marker interval",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"has_background": true,
"supports_manual": true
},
"aurora": {
"supports_reverse": true,
"n1": "Band count (0) or spatial period LEDs (1)",
"n2": "Shimmer (0) or blend strength (1)",
"n3": "Unused (0) or drift speed (1)",
"mode": {
"0": "Colour bands + shimmer",
"1": "Sine northern wave"
},
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"has_background": true,
"supports_manual": true
},
"icicles": {
"supports_reverse": true,
"n1": "Anchor spacing (LEDs)",
"n2": "Max icicle length (LEDs)",
"n3": "Phase step per refresh",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"has_background": true,
"supports_manual": true
},
"blizzard": {
"supports_reverse": true,
"n1": "Flake density",
"n2": "Fall speed",
"n3": "Wind (128 = centred; lower/raise for drift bias)",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"has_background": true,
"supports_manual": true
},
"rime": {
"n1": "Crystallisation rate",
"n2": "Melt (decay) per refresh",
"n3": "Spark cap (LEDs refreshed per cycle)",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"has_background": true,
"supports_manual": true
},
"candle_glow": {
"n1": "Candle count",
"n2": "Glow width (LEDs)",
"n3": "Flicker strength",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"has_background": true,
"supports_manual": true
},
"orbit": {
"n1": "Orbit count",
"n2": "Base speed",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"has_background": true,
"supports_manual": true
},
"palette_morph": {
"n1": "Morph ms",
"n2": "Warp rate",
"n3": "Turbulence",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"supports_manual": false
},
"meteor": {
"supports_reverse": true,
"n1": "Tail length (0–1) or eye width (2)",
"n2": "Speed (LEDs per frame)",
"n3": "Fade amount (0), comet gap (1), or end pause frames (2)",
"mode": {
"0": "Fading meteor",
"1": "Dual comets",
"2": "Bouncing scanner"
},
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"has_background": true,
"supports_manual": true
},
"particles": {
"supports_reverse": true,
"n1": "Flake density (0) or spawn rate (1)",
"n2": "Fall speed (LEDs per frame)",
"n3": "Unused (0) or streak length (1)",
"mode": {
"0": "Snowfall flakes",
"1": "Starfall streaks"
},
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"has_background": true,
"supports_manual": true
},
"sparkle": {
"n1": "Spark density (0–1) or firefly count (2)",
"n2": "Trail decay (0) or twinkle speed (2)",
"n3": "Ice halo width LEDs (1); unused in 0 and 2",
"mode": {
"0": "Sparkle trail",
"1": "Ice burst + halo",
"2": "Fireflies"
},
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"has_background": true,
"supports_manual": true
}
}
{"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}}
+1 -1
View File
@@ -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": "colour_cycle", "colors": [], "brightness": 255, "delay": 100, "auto": true, "n1": 2, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 1, "n7": 0, "n8": 0, "profile_id": "1"}, "4": {"name": "transition", "pattern": "transition", "colors": ["#FF0000", "#00FF00", "#0000FF"], "brightness": 255, "delay": 300, "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], "background": "#000000", "manual_beat_n": 1}, "5": {"name": "chase", "pattern": "chase", "colors": ["#FFFF00", "#FF00FF"], "brightness": 8, "delay": 200, "auto": false, "n1": 30, "n2": 30, "n3": 30, "n4": 30, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [3, 4], "manual_beat_n": 1, "background": "#000000", "background_palette_ref": null}, "6": {"name": "pulse", "pattern": "pulse", "colors": ["#FF00FF"], "brightness": 255, "delay": 1000, "auto": false, "n1": 100, "n2": 0, "n3": 100, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [4], "background_color": "#ec0909", "background_palette_ref": 8, "manual_beat_n": 1, "background": "#050500"}, "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": false, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null, null, null]}, "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": "colour_cycle", "colors": [], "brightness": 255, "delay": 150, "auto": true, "n1": 1, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 1, "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": "colour_cycle", "colors": [], "brightness": 255, "delay": 150, "auto": true, "n1": 1, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 1, "n7": 0, "n8": 0, "profile_id": "2"}, "31": {"name": "DJ Rainbow", "pattern": "colour_cycle", "colors": [], "brightness": 220, "delay": 60, "n1": 12, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 1, "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": "colour_cycle", "colors": [], "brightness": 220, "delay": 60, "n1": 12, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 1, "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"},Line 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
View File
@@ -1 +1 @@
{"1": {"name": "default", "type": "zones", "zones": ["1", "9", "8", "10"], "scenes": [], "palette_id": "1"}, "2": {"name": "test", "type": "zones", "zones": ["6", "7"], "scenes": [], "palette_id": "12"}}
{"1": {"name": "default", "type": "zones", "zones": ["1", "8"], "scenes": [], "palette_id": "1"}, "2": {"name": "test", "type": "zones", "zones": ["6", "7"], "scenes": [], "palette_id": "12"}}
+1 -1
View File
@@ -1 +1 @@
{"1": {"name": "Pulse (manual)", "profile_id": "1", "group_ids": ["5"], "lanes": [[{"preset_id": "6", "beats": 1}]], "lanes_group_ids": [["5"]], "advance_mode": "beats", "steps": [{"preset_id": "6", "beats": 1}], "step_duration_ms": 3000, "simulated_bpm": 120, "sequence_transition": 500, "loop": true}, "2": {"name": "Off (1 beat)", "profile_id": "1", "group_ids": ["5"], "lanes": [[{"preset_id": "2", "beats": 1}]], "lanes_group_ids": [["5"]], "advance_mode": "beats", "steps": [{"preset_id": "2", "beats": 1}], "step_duration_ms": 3000, "simulated_bpm": 120, "sequence_transition": 500, "loop": false}, "3": {"name": "On (1 beat)", "profile_id": "1", "group_ids": ["5"], "lanes": [[{"preset_id": "1", "beats": 1}]], "lanes_group_ids": [["5"]], "advance_mode": "beats", "steps": [{"preset_id": "1", "beats": 1}], "step_duration_ms": 3000, "simulated_bpm": 120, "sequence_transition": 500, "loop": false}, "4": {"name": "Rainbow \u2192 transition \u2192 off", "profile_id": "1", "group_ids": ["5"], "lanes": [[{"preset_id": "3", "beats": 4}, {"preset_id": "4", "beats": 4}, {"preset_id": "2", "beats": 2}]], "lanes_group_ids": [["5"]], "advance_mode": "beats", "steps": [{"preset_id": "3", "beats": 4}, {"preset_id": "4", "beats": 4}, {"preset_id": "2", "beats": 2}], "step_duration_ms": 3000, "simulated_bpm": 100, "sequence_transition": 500, "loop": true}, "5": {"name": "Manual pulse + chase", "profile_id": "1", "group_ids": ["5"], "lanes": [[{"preset_id": "6", "beats": 2}, {"preset_id": "5", "beats": 2}]], "lanes_group_ids": [["5"]], "advance_mode": "beats", "steps": [{"preset_id": "6", "beats": 2}, {"preset_id": "5", "beats": 2}], "step_duration_ms": 3000, "simulated_bpm": 120, "sequence_transition": 500, "loop": false}, "6": {"name": "RGB solid cycle", "profile_id": "1", "group_ids": ["5"], "lanes": [[{"preset_id": "11", "beats": 2}, {"preset_id": "12", "beats": 2}, {"preset_id": "9", "beats": 2}, {"preset_id": "10", "beats": 2}]], "lanes_group_ids": [["5"]], "advance_mode": "beats", "steps": [{"preset_id": "11", "beats": 2}, {"preset_id": "12", "beats": 2}, {"preset_id": "9", "beats": 2}, {"preset_id": "10", "beats": 2}], "step_duration_ms": 3000, "simulated_bpm": 90, "sequence_transition": 500, "loop": true}, "7": {"name": "Winter trio", "profile_id": "1", "group_ids": ["5"], "lanes": [[{"preset_id": "64", "beats": 8}, {"preset_id": "65", "beats": 8}, {"preset_id": "66", "beats": 8}]], "lanes_group_ids": [["5"]], "advance_mode": "beats", "steps": [{"preset_id": "64", "beats": 8}, {"preset_id": "65", "beats": 8}, {"preset_id": "66", "beats": 8}], "step_duration_ms": 3000, "simulated_bpm": 80, "sequence_transition": 500, "loop": true}, "8": {"name": "Fast rainbow", "profile_id": "1", "group_ids": ["5"], "lanes": [[{"preset_id": "1", "beats": 1}, {"preset_id": "3", "beats": 4}]], "lanes_group_ids": [["5"]], "advance_mode": "beats", "steps": [{"preset_id": "1", "beats": 1}, {"preset_id": "3", "beats": 4}], "step_duration_ms": 3000, "simulated_bpm": 180, "sequence_transition": 500, "loop": true}, "9": {"name": "Off then on", "profile_id": "1", "group_ids": ["5"], "lanes": [[{"preset_id": "2", "beats": 2}, {"preset_id": "1", "beats": 4}]], "lanes_group_ids": [["5"]], "advance_mode": "beats", "steps": [{"preset_id": "2", "beats": 2}, {"preset_id": "1", "beats": 4}], "step_duration_ms": 3000, "simulated_bpm": 120, "sequence_transition": 500, "loop": false}, "10": {"name": "Twinkle + flame", "profile_id": "1", "group_ids": ["5"], "lanes": [[{"preset_id": "41", "beats": 6}]], "lanes_group_ids": [["5"]], "advance_mode": "beats", "steps": [{"preset_id": "41", "beats": 6}], "step_duration_ms": 3000, "simulated_bpm": 110, "sequence_transition": 500, "loop": true}, "11": {"name": "radiate chase", "profile_id": "1", "group_ids": [], "lanes": [[{"preset_id": "42", "beats": 12}, {"preset_id": "5", "beats": 4}]], "lanes_group_ids": [[]], "advance_mode": "beats", "steps": [{"preset_id": "42", "beats": 12}, {"preset_id": "5", "beats": 4}], "step_duration_ms": 3000, "simulated_bpm": 120, "sequence_transition": 500, "loop": true}}
{"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
View File
@@ -0,0 +1 @@
{"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"]}}
+51 -3
View File
@@ -159,6 +159,9 @@ Stored preset records can include:
| 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>/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`
@@ -190,15 +193,60 @@ Stored preset records can include:
| PUT | `/scenes/<id>` | Update. |
| 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`
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 |
|--------|------|-------------|
| 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. |
| POST | `/sequences` | Create; may use `group_name`, `presets` in body. |
| PUT | `/sequences/<id>` | Update. |
| DELETE | `/sequences/<id>` | Delete. |
| POST | `/sequences` | Create (body as above). 400 on invalid steps. |
| PUT | `/sequences/<id>` | Update (merged, then re-validated). |
| DELETE | `/sequences/<id>` | Stop if running, then 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`
Submodule led-tool updated: 1edcb8b1f7...d6331a105c.
+1 -3
View File
@@ -1,5 +1,3 @@
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py"]
# ``tests/models/`` is a package name clash with ``src/models``; run via tests/models/run_all.py
norecursedirs = ["models"]
python_files = ["test_endpoints_pytest.py", "engine_tests/test_*.py"]
-253
View File
@@ -1,253 +0,0 @@
#!/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
+33 -277
View File
@@ -2,14 +2,10 @@ from microdot import Microdot
from models.device import (
Device,
derive_device_mac,
normalize_mac,
validate_device_transport,
validate_device_type,
)
from models.group import Group
from models.transport import get_current_sender
from settings import get_settings
from util.brightness_combine import effective_brightness_for_mac
from models.wifi_ws_clients import (
normalize_tcp_peer_ip,
send_json_line_to_ip,
@@ -56,28 +52,8 @@ def _compact_v1_json(*, presets=None, select=None, save=False):
# Seconds after identify blink before selecting built-in ``off`` (tests may monkeypatch).
IDENTIFY_OFF_DELAY_S = 2.0
def _validate_output_brightness(value):
if value is None:
return None
try:
b = int(value)
except (TypeError, ValueError):
raise ValueError("output_brightness must be an integer 0–255")
if b < 0 or b > 255:
raise ValueError("output_brightness must be between 0 and 255")
return b
def _brightness_save_message_json(b_val: int) -> str:
b_val = max(0, min(255, int(b_val)))
return json.dumps({"v": "1", "b": b_val, "save": True}, separators=(",", ":"))
controller = Microdot()
devices = Device()
_group_registry = Group()
_pi_settings = get_settings()
def _device_live_connected(dev_dict):
@@ -167,107 +143,6 @@ async def _identify_send_off_after_delay(sender, transport, wifi_ip, dev_id, nam
pass
async def send_identify_to_device(dev_id: str) -> tuple[int, str]:
"""
Send the same identify blink as ``POST /devices/<id>/identify``.
Returns ``(http_status, "")`` on success, or ``(status, error_message)`` on failure
(status matches the single-device route).
"""
dev = devices.read(dev_id)
if not dev:
return 404, "Device not found"
sender = get_current_sender()
if not sender:
return 503, "Transport not configured"
name = str(dev.get("name") or "").strip()
if not name:
return 400, "Device must have a name to identify"
transport = dev.get("transport") or "espnow"
wifi_ip = None
if transport == "wifi":
wifi_ip = dev.get("address")
if not wifi_ip:
return 400, "Device has no IP address"
try:
msg = _compact_v1_json(
presets={_IDENTIFY_PRESET_KEY: dict(_IDENTIFY_DRIVER_PRESET)},
select={name: [_IDENTIFY_PRESET_KEY]},
)
if transport == "wifi":
ok = await send_json_line_to_ip(wifi_ip, msg)
if not ok:
return 503, "Wi-Fi driver not connected"
else:
await sender.send(msg, addr=dev_id)
asyncio.create_task(
_identify_send_off_after_delay(sender, transport, wifi_ip, dev_id, name)
)
except Exception as e:
return 503, str(e)
return 200, ""
async def send_identify_to_group_devices(macs: list[str]) -> tuple[int, list[dict]]:
"""
Identify every listed registry MAC in one delivery round: merged ``select`` and a single
ESP-NOW split envelope when multiple peers share the serial bridge (avoids per-device
``SerialSender`` lock serialisation). Wi-Fi peers are sent in parallel as in
``deliver_json_messages``.
"""
from util.driver_delivery import deliver_json_messages
errors: list[dict] = []
sender = get_current_sender()
if not sender:
return 0, [{"mac": "*", "error": "Transport not configured"}]
merged_select: dict[str, list[str]] = {}
valid_macs: list[str] = []
for dev_id in macs:
dev = devices.read(dev_id)
if not dev:
errors.append({"mac": dev_id, "error": "Device not found"})
continue
name = str(dev.get("name") or "").strip()
if not name:
errors.append({"mac": dev_id, "error": "Device must have a name to identify"})
continue
transport = (dev.get("transport") or "espnow").strip().lower()
if transport == "wifi":
if not dev.get("address"):
errors.append({"mac": dev_id, "error": "Device has no IP address"})
continue
merged_select[name] = [_IDENTIFY_PRESET_KEY]
valid_macs.append(dev_id)
if not merged_select:
return 0, errors
try:
msg = _compact_v1_json(
presets={_IDENTIFY_PRESET_KEY: dict(_IDENTIFY_DRIVER_PRESET)},
select=merged_select,
)
await deliver_json_messages(sender, [msg], valid_macs, devices, delay_s=0)
except Exception as e:
return 0, errors + [{"mac": "*", "error": str(e)}]
for dev_id in valid_macs:
dev = devices.read(dev_id) or {}
name = str(dev.get("name") or "").strip()
transport = (dev.get("transport") or "espnow").strip().lower()
wifi_ip = dev.get("address") if transport == "wifi" else None
asyncio.create_task(
_identify_send_off_after_delay(sender, transport, wifi_ip, dev_id, name)
)
return len(valid_macs), errors
@controller.get("")
async def list_devices(request):
"""List all devices (includes ``connected`` for live Wi-Fi WebSocket presence)."""
@@ -279,42 +154,6 @@ async def list_devices(request):
return json.dumps(devices_data), 200, {"Content-Type": "application/json"}
@controller.post("/resolve-brightness")
async def resolve_brightness_batch(request):
"""
POST JSON ``{ \"macs\": [\"..\"], \"zone_brightness\": optional 0–255 }``.
Returns ``{ \"values\": { mac: combined_int } }`` — global × group(s) × device × zone (optional).
"""
try:
data = request.json or {}
except Exception:
data = {}
macs = data.get("macs")
if not isinstance(macs, list):
return json.dumps({"error": "macs must be an array"}), 400, {
"Content-Type": "application/json",
}
zb = None
if isinstance(data, dict) and data.get("zone_brightness") is not None:
try:
zb = _validate_output_brightness(data.get("zone_brightness"))
except ValueError as e:
return json.dumps({"error": str(e)}), 400, {"Content-Type": "application/json"}
values = {}
for raw in macs:
m = normalize_mac(str(raw))
if not m:
continue
values[m] = effective_brightness_for_mac(
_pi_settings,
_group_registry,
devices,
m,
zone_brightness=zb,
)
return json.dumps({"values": values}), 200, {"Content-Type": "application/json"}
@controller.get("/<id>")
async def get_device(request, id):
"""Get a device by ID (includes ``connected`` for live Wi-Fi WebSocket presence)."""
@@ -400,17 +239,7 @@ async def update_device(request, id):
data["transport"] = validate_device_transport(data.get("transport"))
if "zones" in data and isinstance(data["zones"], list):
data["zones"] = [str(t) for t in data["zones"]]
if "output_brightness" in data:
data["output_brightness"] = _validate_output_brightness(data.get("output_brightness"))
prev_doc = devices.read(id)
if devices.update(id, data):
if prev_doc and "name" in data:
on = str(prev_doc.get("name") or "").strip()
nn = str(data.get("name") or "").strip()
if on and nn and on != nn:
from util.beat_driver_route import remap_beat_route_device_name
remap_beat_route_device_name(on, nn)
return json.dumps(devices.read(id)), 200, {"Content-Type": "application/json"}
return json.dumps({"error": "Device not found"}), 404, {
"Content-Type": "application/json",
@@ -442,124 +271,51 @@ async def identify_device(request, id):
this device name — same combined shape as profile sends the driver already accepts over TCP
/ ESP-NOW. No ``save``. After ``IDENTIFY_OFF_DELAY_S``, a background task selects ``off``.
"""
status, err = await send_identify_to_device(id)
if status == 200:
return json.dumps({"message": "Identify sent"}), 200, {
"Content-Type": "application/json",
}
return json.dumps({"error": err}), status, {"Content-Type": "application/json"}
@controller.post("/<id>/brightness")
async def push_device_output_brightness(request, id):
"""
Push combined brightness to the driver: global × group(s) × device × optional ``zone_brightness``
in JSON body — single ``b`` (``v``/``b``/``save``). Wi‑Fi or ESP‑NOW.
"""
dev = devices.read(id)
if not dev:
return json.dumps({"error": "Device not found"}), 404, {
"Content-Type": "application/json",
}
body = request.json or {}
zb = None
if isinstance(body, dict) and body.get("zone_brightness") is not None:
try:
zb = _validate_output_brightness(body.get("zone_brightness"))
except ValueError as e:
return json.dumps({"error": str(e)}), 400, {"Content-Type": "application/json"}
b_val = effective_brightness_for_mac(
_pi_settings,
_group_registry,
devices,
id,
zone_brightness=zb,
)
msg = _brightness_save_message_json(b_val)
transport = (dev.get("transport") or "espnow").strip().lower()
sender = get_current_sender()
if not sender:
return json.dumps({"error": "Transport not configured"}), 503, {
"Content-Type": "application/json",
}
name = str(dev.get("name") or "").strip()
if not name:
return json.dumps({"error": "Device must have a name to identify"}), 400, {
"Content-Type": "application/json",
}
transport = dev.get("transport") or "espnow"
wifi_ip = None
if transport == "wifi":
ip = normalize_tcp_peer_ip(str(dev.get("address") or ""))
if not ip:
wifi_ip = dev.get("address")
if not wifi_ip:
return json.dumps({"error": "Device has no IP address"}), 400, {
"Content-Type": "application/json",
}
ok = await send_json_line_to_ip(ip, msg)
if not ok:
return json.dumps({"error": "Wi-Fi driver not connected"}), 503, {
"Content-Type": "application/json",
}
else:
sender = get_current_sender()
if not sender:
return json.dumps({"error": "Transport not configured"}), 503, {
"Content-Type": "application/json",
}
try:
try:
msg = _compact_v1_json(
presets={_IDENTIFY_PRESET_KEY: dict(_IDENTIFY_DRIVER_PRESET)},
select={name: [_IDENTIFY_PRESET_KEY]},
)
if transport == "wifi":
ok = await send_json_line_to_ip(wifi_ip, msg)
if not ok:
return json.dumps({"error": "Wi-Fi driver not connected"}), 503, {
"Content-Type": "application/json",
}
else:
await sender.send(msg, addr=id)
except Exception as e:
return json.dumps({"error": str(e)}), 503, {"Content-Type": "application/json"}
return json.dumps({"message": "brightness sent", "brightness": b_val}), 200, {
"Content-Type": "application/json",
}
@controller.post("/<id>/driver-config")
async def push_driver_config(request, id):
"""
Push ``device_config`` to a Wi‑Fi LED driver over WebSocket.
Body JSON: optional ``name``, ``num_leds``, ``color_order``, ``startup_mode`` (default|last|off).
"""
dev = devices.read(id)
if not dev:
return json.dumps({"error": "Device not found"}), 404, {
"Content-Type": "application/json",
}
if (dev.get("transport") or "").lower() != "wifi":
return json.dumps({"error": "driver-config is only for Wi-Fi devices"}), 400, {
"Content-Type": "application/json",
}
wifi_ip = str(dev.get("address") or "").strip()
if not wifi_ip:
return json.dumps({"error": "Device has no IP address"}), 400, {
"Content-Type": "application/json",
}
body = request.json or {}
dc = {}
if isinstance(body.get("name"), str) and body["name"].strip():
dc["name"] = body["name"].strip()
if "num_leds" in body:
try:
n = int(body["num_leds"])
if 1 <= n <= 2048:
dc["num_leds"] = n
except (TypeError, ValueError):
pass
if isinstance(body.get("color_order"), str):
co = body["color_order"].strip().lower()
if co in ("rgb", "rbg", "grb", "gbr", "brg", "bgr"):
dc["color_order"] = co
if isinstance(body.get("startup_mode"), str):
sm = body["startup_mode"].strip().lower()
if sm in ("default", "last", "off"):
dc["startup_mode"] = sm
if not dc:
return json.dumps(
{
"error": "Provide at least one of name, num_leds, color_order, startup_mode"
}
), 400, {"Content-Type": "application/json"}
msg = json.dumps(
{"v": "1", "device_config": dc, "save": True}, separators=(",", ":")
)
ok = await send_json_line_to_ip(wifi_ip, msg)
if not ok:
return json.dumps({"error": "Wi-Fi driver not connected"}), 503, {
"Content-Type": "application/json",
}
return json.dumps({"message": "driver-config sent"}), 200, {
asyncio.create_task(
_identify_send_off_after_delay(sender, transport, wifi_ip, id, name)
)
except Exception as e:
return json.dumps({"error": str(e)}), 503, {"Content-Type": "application/json"}
return json.dumps({"message": "Identify sent"}), 200, {
"Content-Type": "application/json",
}
+21 -330
View File
@@ -1,359 +1,50 @@
from microdot import Microdot
from microdot.session import with_session
import asyncio
from models.group import Group
from models.device import Device
from models.transport import get_current_sender
from models.wifi_ws_clients import normalize_tcp_peer_ip, send_json_line_to_ip
from settings import get_settings
from util.brightness_combine import effective_brightness_for_mac
import json
controller = Microdot()
groups = Group()
devices = Device()
_pi_settings = get_settings()
@controller.get('')
async def list_groups(request):
"""List all groups."""
return json.dumps(groups), 200, {'Content-Type': 'application/json'}
def _group_doc_visible_for_profile(doc, profile_id):
if not isinstance(doc, dict):
return False
scoped = doc.get("profile_id")
if scoped is None:
scoped = doc.get("profileId")
if scoped is None or str(scoped).strip() == "":
return True
if not profile_id:
return False
return str(scoped).strip() == str(profile_id).strip()
def _filtered_groups_dict(session):
from controllers.zone import get_current_profile_id
pid = get_current_profile_id(session)
out = {}
for gid, doc in groups.items():
if not isinstance(doc, dict):
continue
if _group_doc_visible_for_profile(doc, pid):
out[str(gid)] = doc
return out
@controller.get("")
@with_session
async def list_groups(request, session):
"""List groups visible for the current profile (shared + profile-scoped)."""
return json.dumps(_filtered_groups_dict(session)), 200, {"Content-Type": "application/json"}
@controller.get("/<id>")
@with_session
async def get_group(request, session, id):
"""Get a specific group by ID (404 if scoped to another profile)."""
@controller.get('/<id>')
async def get_group(request, id):
"""Get a specific group by ID."""
group = groups.read(id)
if not group or not isinstance(group, dict):
return json.dumps({"error": "Group not found"}), 404
from controllers.zone import get_current_profile_id
if group:
return json.dumps(group), 200, {'Content-Type': 'application/json'}
return json.dumps({"error": "Group not found"}), 404
if not _group_doc_visible_for_profile(group, get_current_profile_id(session)):
return json.dumps({"error": "Group not found"}), 404
return json.dumps(group), 200, {"Content-Type": "application/json"}
def _sanitize_group_profile_id_write(data, session):
"""Allow ``profile_id`` only for the active profile, or null to share across profiles."""
if not isinstance(data, dict):
return
from controllers.zone import get_current_profile_id
cur = get_current_profile_id(session)
if "profile_id" not in data and "profileId" not in data:
return
raw = data.get("profile_id")
if raw is None and "profileId" in data:
raw = data.get("profileId")
if raw is None or raw == "":
data.pop("profileId", None)
data["profile_id"] = None
return
if not cur or str(raw).strip() != str(cur).strip():
data.pop("profileId", None)
data.pop("profile_id", None)
@controller.post("")
@with_session
async def create_group(request, session):
"""Create a new group (omit ``profile_id`` for shared; or ``profile_scoped``: true for this profile only)."""
@controller.post('')
async def create_group(request):
"""Create a new group."""
try:
data = dict(request.json or {})
data = request.json or {}
name = data.get("name", "")
profile_scoped = bool(data.pop("profile_scoped", False))
_sanitize_group_profile_id_write(data, session)
group_id = groups.create(name)
if data:
groups.update(group_id, data)
if profile_scoped:
from controllers.zone import get_current_profile_id
cur = get_current_profile_id(session)
if cur:
groups.update(group_id, {"profile_id": str(cur)})
return json.dumps(groups.read(group_id)), 201, {"Content-Type": "application/json"}
return json.dumps(groups.read(group_id)), 201, {'Content-Type': 'application/json'}
except Exception as e:
return json.dumps({"error": str(e)}), 400
@controller.put("/<id>")
@with_session
async def update_group(request, session, id):
@controller.put('/<id>')
async def update_group(request, id):
"""Update an existing group."""
try:
data = request.json
if not isinstance(data, dict):
return json.dumps({"error": "Invalid JSON"}), 400, {"Content-Type": "application/json"}
data = dict(data)
_sanitize_group_profile_id_write(data, session)
if groups.update(id, data):
g = groups.read(id)
if g:
return json.dumps(g), 200, {"Content-Type": "application/json"}
return json.dumps(groups.read(id)), 200, {'Content-Type': 'application/json'}
return json.dumps({"error": "Group not found"}), 404
except Exception as e:
return json.dumps({"error": str(e)}), 400
@controller.delete("/<id>")
@with_session
async def delete_group(request, session, id):
"""Delete a group (not allowed for another profile's scoped group)."""
g = groups.read(id)
if not g or not isinstance(g, dict):
return json.dumps({"error": "Group not found"}), 404
from controllers.zone import get_current_profile_id
if not _group_doc_visible_for_profile(g, get_current_profile_id(session)):
return json.dumps({"error": "Group not found"}), 404
@controller.delete('/<id>')
async def delete_group(request, id):
"""Delete a group."""
if groups.delete(id):
return json.dumps({"message": "Group deleted successfully"}), 200
return json.dumps({"error": "Group not found"}), 404
def _group_driver_config_payload(doc):
"""Build ``device_config`` dict from stored group Wi‑Fi defaults (non-empty only)."""
dc = {}
if not isinstance(doc, dict):
return dc
nm = doc.get("wifi_driver_display_name")
if isinstance(nm, str) and nm.strip():
dc["name"] = nm.strip()
nled = doc.get("wifi_driver_num_leds")
if nled is not None:
try:
n = int(nled)
if 1 <= n <= 2048:
dc["num_leds"] = n
except (TypeError, ValueError):
pass
co = doc.get("wifi_color_order")
if isinstance(co, str):
c = co.strip().lower()
if c in ("rgb", "rbg", "grb", "gbr", "brg", "bgr"):
dc["color_order"] = c
sm = doc.get("wifi_startup_mode")
if isinstance(sm, str):
s = sm.strip().lower()
if s in ("default", "last", "off"):
dc["startup_mode"] = s
return dc
def _read_group_for_session(session, id):
g = groups.read(id)
if not g or not isinstance(g, dict):
return None
from controllers.zone import get_current_profile_id
if not _group_doc_visible_for_profile(g, get_current_profile_id(session)):
return None
return g
@controller.post("/<id>/driver-config")
@with_session
async def push_group_driver_config(request, session, id):
"""
Push group Wi‑Fi defaults to every Wi‑Fi device listed in the group (TCP WebSocket).
Uses stored ``wifi_*`` fields on the group; optional JSON body may override for this send only.
"""
gdoc = _read_group_for_session(session, id)
if not gdoc:
return json.dumps({"error": "Group not found"}), 404
body = request.json or {}
merged = dict(gdoc)
if isinstance(body, dict):
for k in (
"wifi_driver_display_name",
"wifi_driver_num_leds",
"wifi_color_order",
"wifi_startup_mode",
):
if k in body:
merged[k] = body[k]
dc = _group_driver_config_payload(merged)
if not dc:
return json.dumps(
{"error": "No driver defaults on this group (set display name, LEDs, colour order, or power-on pattern)"}
), 400, {"Content-Type": "application/json"}
mac_list = gdoc.get("devices") if isinstance(gdoc.get("devices"), list) else []
sent = 0
errors = []
msg = json.dumps(
{"v": "1", "device_config": dc, "save": True}, separators=(",", ":")
)
tasks = []
meta_macs = []
for mac in mac_list:
m = str(mac).strip().lower().replace(":", "").replace("-", "")
if len(m) != 12:
continue
dev = devices.read(m)
if not dev:
errors.append({"mac": m, "error": "not in registry"})
continue
if (dev.get("transport") or "").lower() != "wifi":
continue
ip = normalize_tcp_peer_ip(str(dev.get("address") or ""))
if not ip:
errors.append({"mac": m, "error": "no IP"})
continue
tasks.append(send_json_line_to_ip(ip, msg))
meta_macs.append(m)
if tasks:
results = await asyncio.gather(*tasks, return_exceptions=True)
for m, r in zip(meta_macs, results):
if r is True:
sent += 1
elif isinstance(r, Exception):
errors.append({"mac": m, "error": str(r)})
else:
errors.append({"mac": m, "error": "driver not connected"})
return json.dumps(
{"message": "driver-config sent", "sent": sent, "errors": errors}
), 200, {"Content-Type": "application/json"}
def _brightness_save_message_json(b_val: int) -> str:
b_val = max(0, min(255, int(b_val)))
return json.dumps({"v": "1", "b": b_val, "save": True}, separators=(",", ":"))
@controller.post("/<id>/brightness")
@with_session
async def push_group_output_brightness(request, session, id):
"""
Push combined brightness (global × group(s) × device) to each member — one ``b`` per device.
"""
gdoc = _read_group_for_session(session, id)
if not gdoc:
return json.dumps({"error": "Group not found"}), 404
mac_list = gdoc.get("devices") if isinstance(gdoc.get("devices"), list) else []
sent = 0
errors = []
sender = get_current_sender()
async def _push_brightness_one(m: str, dev: dict) -> tuple[str, bool, str | None]:
b_val = effective_brightness_for_mac(
_pi_settings,
groups,
devices,
m,
zone_brightness=None,
)
msg = _brightness_save_message_json(b_val)
transport = (dev.get("transport") or "espnow").strip().lower()
if transport == "wifi":
ip = normalize_tcp_peer_ip(str(dev.get("address") or ""))
if not ip:
return m, False, "no IP"
ok = await send_json_line_to_ip(ip, msg)
return m, bool(ok), None if ok else "driver not connected"
if not sender:
return m, False, "transport not configured"
try:
await sender.send(msg, addr=m)
return m, True, None
except Exception as e:
return m, False, str(e)
tasks: list = []
for mac in mac_list:
m = str(mac).strip().lower().replace(":", "").replace("-", "")
if len(m) != 12:
continue
dev = devices.read(m)
if not dev:
errors.append({"mac": m, "error": "not in registry"})
continue
tasks.append(_push_brightness_one(m, dev))
if tasks:
results = await asyncio.gather(*tasks, return_exceptions=True)
for r in results:
if isinstance(r, Exception):
errors.append({"mac": "*", "error": str(r)})
continue
m, ok, err = r
if ok:
sent += 1
elif err:
errors.append({"mac": m, "error": err})
return json.dumps(
{"message": "brightness sent", "sent": sent, "errors": errors}
), 200, {"Content-Type": "application/json"}
@controller.post("/<id>/identify")
@with_session
async def identify_group_devices(request, session, id):
"""
Run the same identify blink as ``POST /devices/<id>/identify`` for every registry member
in parallel so all drivers in the group blink together.
"""
_ = request
gdoc = _read_group_for_session(session, id)
if not gdoc:
return json.dumps({"error": "Group not found"}), 404, {"Content-Type": "application/json"}
mac_list = gdoc.get("devices") if isinstance(gdoc.get("devices"), list) else []
if not mac_list:
return json.dumps({"error": "Group has no devices"}), 400, {"Content-Type": "application/json"}
from controllers.device import send_identify_to_group_devices
normalized: list[str] = []
errors: list[dict] = []
for mac in mac_list:
m = str(mac).strip().lower().replace(":", "").replace("-", "")
if len(m) != 12:
errors.append({"mac": str(mac), "error": "invalid MAC"})
continue
normalized.append(m)
if not normalized:
return json.dumps(
{"message": "identify group done", "sent": 0, "errors": errors}
), 200, {"Content-Type": "application/json"}
sent, batch_errors = await send_identify_to_group_devices(normalized)
errors.extend(batch_errors)
return json.dumps(
{"message": "identify group done", "sent": sent, "errors": errors}
), 200, {"Content-Type": "application/json"}
+85
View File
@@ -0,0 +1,85 @@
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
-8
View File
@@ -367,8 +367,6 @@ async def create_driver_pattern(request):
Body JSON:
name, code (required),
min_delay, max_delay, max_colors (optional numbers),
has_background (optional bool),
supports_manual (optional bool, default true if omitted in db),
n1..n8 (optional string labels),
overwrite (optional, default true).
"""
@@ -411,12 +409,6 @@ async def create_driver_pattern(request):
"Content-Type": "application/json"
}
if "has_background" in data:
meta["has_background"] = bool(data.get("has_background"))
if "supports_manual" in data:
meta["supports_manual"] = bool(data.get("supports_manual"))
for i in range(1, 9):
nk = "n%d" % i
if nk not in data:
+1 -62
View File
@@ -2,30 +2,16 @@ from microdot import Microdot
from microdot.session import with_session
from models.preset import Preset
from models.profile import Profile
from models.pallet import Palette
from models.device import Device, normalize_mac
from models.transport import get_current_sender
from util.driver_delivery import deliver_json_messages, deliver_preset_broadcast_then_per_device
from util.espnow_message import build_message, build_preset_dict
from util.profile_bundle import export_preset_bundle, import_preset_bundle
import json
controller = Microdot()
presets = Preset()
profiles = Profile()
def _palette_colors_for_profile(profile_id):
prof = profiles.read(str(profile_id))
if not isinstance(prof, dict):
return None
pid = prof.get("palette_id") or prof.get("paletteId")
if not pid:
return None
cols = Palette().read(str(pid))
return cols if isinstance(cols, list) else None
def get_current_profile_id(session=None):
"""Get the current active profile ID from session or fallback to first."""
profile_list = profiles.list()
@@ -51,41 +37,6 @@ async def list_presets(request, session):
}
return json.dumps(scoped), 200, {'Content-Type': 'application/json'}
@controller.get('/<preset_id>/export')
@with_session
async def export_preset(request, session, preset_id):
"""Export one preset as a JSON bundle."""
current_profile_id = get_current_profile_id(session)
preset = presets.read(preset_id)
if not preset or str(preset.get("profile_id")) != str(current_profile_id):
return json.dumps({"error": "Preset not found"}), 404, {'Content-Type': 'application/json'}
try:
bundle = export_preset_bundle(preset_id, presets)
return json.dumps(bundle), 200, {'Content-Type': 'application/json'}
except ValueError as e:
return json.dumps({"error": str(e)}), 404, {'Content-Type': 'application/json'}
@controller.post('/import')
@with_session
async def import_preset(request, session):
"""Import a preset bundle into the current profile."""
try:
current_profile_id = get_current_profile_id(session)
if not current_profile_id:
return json.dumps({"error": "No profile available"}), 404, {'Content-Type': 'application/json'}
body = request.json or {}
bundle = body.get("bundle") if isinstance(body, dict) else body
if not isinstance(bundle, dict):
return json.dumps({"error": "Expected JSON bundle"}), 400, {'Content-Type': 'application/json'}
new_id, preset_data = import_preset_bundle(bundle, presets, current_profile_id)
return json.dumps({new_id: preset_data}), 201, {'Content-Type': 'application/json'}
except ValueError as e:
return json.dumps({"error": str(e)}), 400, {'Content-Type': 'application/json'}
except Exception as e:
return json.dumps({"error": str(e)}), 400, {'Content-Type': 'application/json'}
@controller.get('/<preset_id>')
@with_session
async def get_preset(request, session, preset_id):
@@ -202,7 +153,6 @@ async def send_presets(request, session):
# Build API-compliant preset map keyed by preset ID, include name
current_profile_id = get_current_profile_id(session)
palette_colors = _palette_colors_for_profile(current_profile_id)
presets_by_name = {}
for pid in preset_ids:
preset_data = presets.read(str(pid))
@@ -211,7 +161,7 @@ async def send_presets(request, session):
if str(preset_data.get("profile_id")) != str(current_profile_id):
continue
preset_key = str(pid)
preset_payload = build_preset_dict(preset_data, palette_colors)
preset_payload = build_preset_dict(preset_data)
preset_payload["name"] = preset_data.get("name", "")
presets_by_name[preset_key] = preset_payload
@@ -365,17 +315,6 @@ async def push_driver_messages(request, session):
except Exception:
return json.dumps({"error": "Send failed"}), 503, {'Content-Type': 'application/json'}
try:
from util import sequence_playback as seq_pb
from util.beat_driver_route import sync_beat_route_from_push_sequence
preserve = bool(seq_pb.playback_status().get("active"))
sync_beat_route_from_push_sequence(
seq, target_macs=target_list, preserve_parallel_lane_routes=preserve
)
except Exception:
pass
return json.dumps({
"message": "Delivered",
"deliveries": deliveries,
+172 -238
View File
@@ -3,15 +3,12 @@ from microdot.session import with_session
from models.profile import Profile
from models.zone import Zone
from models.preset import Preset
from models.sequence import Sequence
from util.profile_bundle import export_profile_bundle, import_profile_bundle
import json
controller = Microdot()
profiles = Profile()
zones = Zone()
presets = Preset()
sequences = Sequence()
@controller.get('')
@with_session
@@ -57,64 +54,18 @@ async def get_current_profile(request, session):
return json.dumps({"id": current_id, "profile": profile}), 200, {'Content-Type': 'application/json'}
return json.dumps({"error": "No profile available"}), 404
@controller.post('/import')
@controller.get('/<id>')
@with_session
async def import_profile(request, session):
"""Import a profile bundle (optionally apply as current profile)."""
try:
body = request.json or {}
bundle = body.get("bundle") if isinstance(body, dict) else body
if not isinstance(bundle, dict):
return json.dumps({"error": "Expected JSON bundle"}), 400, {'Content-Type': 'application/json'}
name = body.get("name") if isinstance(body, dict) else None
apply_raw = body.get("apply", True) if isinstance(body, dict) else True
if isinstance(apply_raw, str):
apply = apply_raw.strip().lower() in ("1", "true", "yes", "on")
else:
apply = bool(apply_raw)
new_profile_id, profile_data = import_profile_bundle(
bundle,
profiles,
zones,
presets,
sequences,
profiles._palette_model,
name=str(name).strip() if name else None,
)
if apply:
session['current_profile'] = str(new_profile_id)
session.save()
return (
json.dumps({new_profile_id: profile_data, "id": new_profile_id}),
201,
{'Content-Type': 'application/json'},
)
except ValueError as e:
return json.dumps({"error": str(e)}), 400, {'Content-Type': 'application/json'}
except Exception as e:
return json.dumps({"error": str(e)}), 400, {'Content-Type': 'application/json'}
@controller.get('/<id>/export')
async def export_profile(request, id):
"""Export profile, zones, presets, sequences, and palette as a JSON bundle."""
try:
bundle = export_profile_bundle(
str(id),
profiles,
zones,
presets,
sequences,
profiles._palette_model,
)
return json.dumps(bundle), 200, {'Content-Type': 'application/json'}
except ValueError as e:
return json.dumps({"error": str(e)}), 404, {'Content-Type': 'application/json'}
except Exception as e:
return json.dumps({"error": str(e)}), 400, {'Content-Type': 'application/json'}
async def get_profile(request, id, session):
"""Get a specific profile by ID."""
# Handle 'current' as a special case
if id == 'current':
return await get_current_profile(request, session)
profile = profiles.read(id)
if profile:
return json.dumps(profile), 200, {'Content-Type': 'application/json'}
return json.dumps({"error": "Profile not found"}), 404
@controller.post('/<id>/apply')
@with_session
@@ -126,6 +77,167 @@ async def apply_profile(request, session, id):
session.save()
return json.dumps({"message": "Profile applied", "id": str(id)}), 200, {'Content-Type': 'application/json'}
@controller.post('')
async def create_profile(request):
"""Create a new profile."""
try:
data = dict(request.json or {})
name = data.get("name", "")
seed_raw = data.get("seed_dj_zone", False)
if isinstance(seed_raw, str):
seed_dj_zone = seed_raw.strip().lower() in ("1", "true", "yes", "on")
else:
seed_dj_zone = bool(seed_raw)
# Request-only flag: do not persist on profile records.
data.pop("seed_dj_zone", None)
profile_id = profiles.create(name)
# Avoid persisting request-only fields.
data.pop("name", None)
if data:
profiles.update(profile_id, data)
# New profiles always start with a default zone pre-populated with starter presets.
default_preset_ids = []
default_preset_defs = [
{
"name": "on",
"pattern": "on",
"colors": ["#FFFFFF"],
"brightness": 255,
"delay": 100,
"auto": True,
},
{
"name": "off",
"pattern": "off",
"colors": [],
"brightness": 0,
"delay": 100,
"auto": True,
},
{
"name": "rainbow",
"pattern": "rainbow",
"colors": [],
"brightness": 255,
"delay": 100,
"auto": True,
"n1": 2,
},
{
"name": "Colour Cycle",
"pattern": "colour_cycle",
"colors": ["#FF0000", "#00FF00", "#0000FF"],
"brightness": 255,
"delay": 100,
"auto": True,
"n1": 1,
},
{
"name": "transition",
"pattern": "transition",
"colors": ["#FF0000", "#00FF00", "#0000FF"],
"brightness": 255,
"delay": 500,
"auto": True,
},
{
"name": "flicker",
"pattern": "flicker",
"colors": ["#FFB84D"],
"brightness": 255,
"delay": 80,
"auto": True,
"n1": 30,
},
{
"name": "flame",
"pattern": "flame",
"colors": [],
"brightness": 255,
"delay": 50,
"auto": True,
"n1": 35,
"n2": 2600,
"n3": 0,
"n4": 0,
},
{
"name": "twinkle",
"pattern": "twinkle",
"colors": ["#78C8FF", "#508CFF", "#B478FF", "#64DCE8", "#A0C8FF"],
"brightness": 255,
"delay": 55,
"auto": True,
"n1": 72,
"n2": 140,
"n3": 2,
"n4": 6,
},
]
for preset_data in default_preset_defs:
pid = presets.create(profile_id)
presets.update(pid, preset_data)
default_preset_ids.append(str(pid))
default_tab_id = zones.create(name="default", names=["1"], presets=[default_preset_ids])
zones.update(default_tab_id, {
"presets_flat": default_preset_ids,
"default_preset": default_preset_ids[0] if default_preset_ids else None,
})
profile = profiles.read(profile_id) or {}
profile_tabs = profile.get("zones", []) if isinstance(profile.get("zones", []), list) else []
profile_tabs.append(str(default_tab_id))
if seed_dj_zone:
# Seed a DJ-focused zone with three starter presets.
seeded_preset_ids = []
preset_defs = [
{
"name": "DJ Rainbow",
"pattern": "rainbow",
"colors": [],
"brightness": 220,
"delay": 60,
"n1": 12,
},
{
"name": "DJ Single Color",
"pattern": "on",
"colors": ["#ff00ff"],
"brightness": 220,
"delay": 100,
},
{
"name": "DJ Transition",
"pattern": "transition",
"colors": ["#ff0000", "#00ff00", "#0000ff"],
"brightness": 220,
"delay": 250,
},
]
for preset_data in preset_defs:
pid = presets.create(profile_id)
presets.update(pid, preset_data)
seeded_preset_ids.append(str(pid))
dj_tab_id = zones.create(name="dj", names=["dj"], presets=[seeded_preset_ids])
zones.update(dj_tab_id, {
"presets_flat": seeded_preset_ids,
"default_preset": seeded_preset_ids[0] if seeded_preset_ids else None,
})
profile_tabs.append(str(dj_tab_id))
profiles.update(profile_id, {"zones": profile_tabs})
profile_data = profiles.read(profile_id)
return json.dumps({profile_id: profile_data}), 201, {'Content-Type': 'application/json'}
except Exception as e:
return json.dumps({"error": str(e)}), 400
@controller.post('/<id>/clone')
async def clone_profile(request, id):
@@ -239,184 +351,6 @@ async def clone_profile(request, id):
except Exception as e:
return json.dumps({"error": str(e)}), 400
@controller.get('/<id>')
@with_session
async def get_profile(request, id, session):
"""Get a specific profile by ID."""
# Handle 'current' as a special case
if id == 'current':
return await get_current_profile(request, session)
profile = profiles.read(id)
if profile:
return json.dumps(profile), 200, {'Content-Type': 'application/json'}
return json.dumps({"error": "Profile not found"}), 404
@controller.post('')
async def create_profile(request):
"""Create a new profile."""
try:
data = dict(request.json or {})
name = data.get("name", "")
seed_raw = data.get("seed_dj_zone", False)
if isinstance(seed_raw, str):
seed_dj_zone = seed_raw.strip().lower() in ("1", "true", "yes", "on")
else:
seed_dj_zone = bool(seed_raw)
# Request-only flag: do not persist on profile records.
data.pop("seed_dj_zone", None)
profile_id = profiles.create(name)
# Avoid persisting request-only fields.
data.pop("name", None)
if data:
profiles.update(profile_id, data)
# New profiles always start with a default zone pre-populated with starter presets.
default_preset_ids = []
default_preset_defs = [
{
"name": "on",
"pattern": "on",
"colors": ["#FFFFFF"],
"brightness": 255,
"delay": 100,
"auto": True,
},
{
"name": "off",
"pattern": "off",
"colors": [],
"brightness": 0,
"delay": 100,
"auto": True,
},
{
"name": "rainbow",
"pattern": "colour_cycle",
"colors": [],
"brightness": 255,
"delay": 100,
"auto": True,
"n1": 2,
"mode": 1,
},
{
"name": "Colour Cycle",
"pattern": "colour_cycle",
"colors": ["#FF0000", "#00FF00", "#0000FF"],
"brightness": 255,
"delay": 100,
"auto": True,
"n1": 1,
},
{
"name": "transition",
"pattern": "transition",
"colors": ["#FF0000", "#00FF00", "#0000FF"],
"brightness": 255,
"delay": 500,
"auto": True,
},
{
"name": "flicker",
"pattern": "flicker",
"colors": ["#FFB84D"],
"brightness": 255,
"delay": 80,
"auto": True,
"n1": 30,
},
{
"name": "flame",
"pattern": "flame",
"colors": [],
"brightness": 255,
"delay": 50,
"auto": True,
"n1": 35,
"n2": 2600,
"n3": 0,
"n4": 0,
},
{
"name": "twinkle",
"pattern": "twinkle",
"colors": ["#78C8FF", "#508CFF", "#B478FF", "#64DCE8", "#A0C8FF"],
"brightness": 255,
"delay": 55,
"auto": True,
"n1": 72,
"n2": 140,
"n3": 2,
"n4": 6,
},
]
for preset_data in default_preset_defs:
pid = presets.create(profile_id)
presets.update(pid, preset_data)
default_preset_ids.append(str(pid))
default_tab_id = zones.create(name="default", names=["1"], presets=[default_preset_ids])
zones.update(default_tab_id, {
"presets_flat": default_preset_ids,
"default_preset": default_preset_ids[0] if default_preset_ids else None,
})
profile = profiles.read(profile_id) or {}
profile_tabs = profile.get("zones", []) if isinstance(profile.get("zones", []), list) else []
profile_tabs.append(str(default_tab_id))
if seed_dj_zone:
# Seed a DJ-focused zone with three starter presets.
seeded_preset_ids = []
preset_defs = [
{
"name": "DJ Rainbow",
"pattern": "colour_cycle",
"colors": [],
"brightness": 220,
"delay": 60,
"n1": 12,
"mode": 1,
},
{
"name": "DJ Single Color",
"pattern": "on",
"colors": ["#ff00ff"],
"brightness": 220,
"delay": 100,
},
{
"name": "DJ Transition",
"pattern": "transition",
"colors": ["#ff0000", "#00ff00", "#0000ff"],
"brightness": 220,
"delay": 250,
},
]
for preset_data in preset_defs:
pid = presets.create(profile_id)
presets.update(pid, preset_data)
seeded_preset_ids.append(str(pid))
dj_tab_id = zones.create(name="dj", names=["dj"], presets=[seeded_preset_ids])
zones.update(dj_tab_id, {
"presets_flat": seeded_preset_ids,
"default_preset": seeded_preset_ids[0] if seeded_preset_ids else None,
})
profile_tabs.append(str(dj_tab_id))
profiles.update(profile_id, {"zones": profile_tabs})
profile_data = profiles.read(profile_id)
return json.dumps({profile_id: profile_data}), 201, {'Content-Type': 'application/json'}
except Exception as e:
return json.dumps({"error": str(e)}), 400
@controller.put('/current')
@with_session
async def update_current_profile(request, session):
+34
View File
@@ -47,3 +47,37 @@ async def delete_scene(request, id):
if scenes.delete(id):
return json.dumps({"message": "Scene deleted successfully"}), 200
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'}
+53 -273
View File
@@ -1,298 +1,78 @@
from microdot import Microdot
from microdot.session import with_session
from models.sequence import Sequence
from models.profile import Profile
from models.transport import get_current_sender
from models.preset import Preset
from util.profile_bundle import export_sequence_bundle, import_sequence_bundle
from models.squence import Sequence
from engine import get_engine
from engine.core import EngineError
import json
controller = Microdot()
sequences = Sequence()
profiles = Profile()
presets = Preset()
_JSON = {'Content-Type': 'application/json'}
def get_current_profile_id(session=None):
"""Get the current active profile ID from session or fallback to first."""
profile_list = profiles.list()
session_profile = None
if session is not None:
session_profile = session.get("current_profile")
if session_profile and session_profile in profile_list:
return session_profile
if profile_list:
return profile_list[0]
return None
@controller.get('')
async def list_sequences(request):
"""List all sequences."""
return json.dumps(sequences), 200, _JSON
@controller.get("")
@with_session
async def list_sequences(request, session):
"""List sequences for the current profile."""
sequences.load()
current_profile_id = get_current_profile_id(session)
if not current_profile_id:
return json.dumps({}), 200, {"Content-Type": "application/json"}
scoped = {
sid: sdata
for sid, sdata in sequences.items()
if isinstance(sdata, dict)
and str(sdata.get("profile_id")) == str(current_profile_id)
}
return json.dumps(scoped), 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>/export")
@with_session
async def export_sequence(request, session, id):
"""Export a sequence and referenced presets as a JSON bundle."""
current_profile_id = get_current_profile_id(session)
if not current_profile_id:
return json.dumps({"error": "No profile available"}), 404, {"Content-Type": "application/json"}
@controller.get('/<id>')
async def get_sequence(request, id):
"""Get a specific sequence by ID."""
sequence = sequences.read(id)
if sequence:
return json.dumps(sequence), 200, _JSON
return json.dumps({"error": "Sequence not found"}), 404, _JSON
@controller.post('')
async def create_sequence(request):
"""Create a sequence: {name, zone_id, loop, repeat_count, steps: [{preset_id, duration_s}]}."""
try:
bundle = export_sequence_bundle(
id,
sequences,
presets,
profile_id=current_profile_id,
)
return json.dumps(bundle), 200, {"Content-Type": "application/json"}
sequence_id = sequences.create(request.json or {})
return json.dumps(sequences.read(sequence_id)), 201, _JSON
except ValueError as e:
return json.dumps({"error": str(e)}), 404, {"Content-Type": "application/json"}
return json.dumps({"error": str(e)}), 400, _JSON
@controller.post("/import")
@with_session
async def import_sequence(request, session):
"""Import a sequence bundle into the current profile."""
@controller.put('/<id>')
async def update_sequence(request, id):
"""Update an existing sequence."""
try:
current_profile_id = get_current_profile_id(session)
if not current_profile_id:
return (
json.dumps({"error": "No profile available"}),
404,
{"Content-Type": "application/json"},
)
body = request.json or {}
bundle = body.get("bundle") if isinstance(body, dict) else body
if not isinstance(bundle, dict):
return (
json.dumps({"error": "Expected JSON bundle"}),
400,
{"Content-Type": "application/json"},
)
new_id, seq_data = import_sequence_bundle(bundle, sequences, presets, current_profile_id)
return (
json.dumps({new_id: seq_data}),
201,
{"Content-Type": "application/json"},
)
if sequences.update(id, request.json or {}):
return json.dumps(sequences.read(id)), 200, _JSON
return json.dumps({"error": "Sequence not found"}), 404, _JSON
except ValueError as e:
return json.dumps({"error": str(e)}), 400, {"Content-Type": "application/json"}
except Exception as e:
return json.dumps({"error": str(e)}), 400, {"Content-Type": "application/json"}
return json.dumps({"error": str(e)}), 400, _JSON
@controller.get("/<id>")
@with_session
async def get_sequence(request, session, id):
"""Get a specific sequence by ID (current profile only)."""
sequences.load()
current_profile_id = get_current_profile_id(session)
seq = sequences.read(id)
if (
seq
and current_profile_id
and str(seq.get("profile_id")) == str(current_profile_id)
):
return json.dumps(seq), 200, {"Content-Type": "application/json"}
return json.dumps({"error": "Sequence not found"}), 404
@controller.post("")
@with_session
async def create_sequence(request, session):
"""Create a new sequence for the current profile."""
try:
try:
data = request.json or {}
except Exception:
return (
json.dumps({"error": "Invalid JSON"}),
400,
{"Content-Type": "application/json"},
)
current_profile_id = get_current_profile_id(session)
if not current_profile_id:
return (
json.dumps({"error": "No profile available"}),
404,
{"Content-Type": "application/json"},
)
sequence_id = sequences.create(current_profile_id)
if not isinstance(data, dict):
data = {}
data = dict(data)
data["profile_id"] = str(current_profile_id)
if sequences.update(sequence_id, data):
seq_data = sequences.read(sequence_id)
return (
json.dumps({sequence_id: seq_data}),
201,
{"Content-Type": "application/json"},
)
return (
json.dumps({"error": "Failed to create sequence"}),
400,
{"Content-Type": "application/json"},
)
except Exception as e:
return json.dumps({"error": str(e)}), 400, {"Content-Type": "application/json"}
@controller.put("/<id>")
@with_session
async def update_sequence(request, session, id):
"""Update an existing sequence (current profile only)."""
try:
current_profile_id = get_current_profile_id(session)
seq = sequences.read(id)
if not seq or str(seq.get("profile_id")) != str(current_profile_id):
return json.dumps({"error": "Sequence not found"}), 404
data = request.json
if not isinstance(data, dict):
return (
json.dumps({"error": "Invalid JSON"}),
400,
{"Content-Type": "application/json"},
)
data = dict(data)
data["profile_id"] = str(current_profile_id)
if sequences.update(id, data):
try:
from util.sequence_playback import stop_if_playing_sequence
stop_if_playing_sequence(str(id))
except Exception:
pass
return json.dumps(sequences.read(id)), 200, {"Content-Type": "application/json"}
return json.dumps({"error": "Sequence not found"}), 404
except Exception as e:
return json.dumps({"error": str(e)}), 400, {"Content-Type": "application/json"}
@controller.delete("/<id>")
@with_session
async def delete_sequence(request, session, id):
"""Delete a sequence (current profile only)."""
current_profile_id = get_current_profile_id(session)
seq = sequences.read(id)
if not seq or str(seq.get("profile_id")) != str(current_profile_id):
return json.dumps({"error": "Sequence not found"}), 404
try:
from util.sequence_playback import stop_if_playing_sequence
stop_if_playing_sequence(str(id))
except Exception:
pass
@controller.delete('/<id>')
async def delete_sequence(request, id):
"""Delete a sequence (stops it first if running)."""
await get_engine().sequences.stop(id)
if sequences.delete(id):
return (
json.dumps({"message": "Sequence deleted successfully"}),
200,
{"Content-Type": "application/json"},
)
return json.dumps({"error": "Sequence not found"}), 404
return json.dumps({"message": "Sequence deleted successfully"}), 200, _JSON
return json.dumps({"error": "Sequence not found"}), 404, _JSON
@controller.post("/sync-phase")
@with_session
async def sync_sequence_beat_phase(request, session):
"""Align beat counters while a sequence is playing (body: {\"mode\": \"step\"|\"pass\"})."""
_ = session
@controller.post('/<id>/play')
async def play_sequence(request, id):
"""Start the sequence on its zone (replaces any sequence already running there)."""
try:
data = request.json or {}
except Exception:
data = {}
if not isinstance(data, dict):
data = {}
mode = data.get("mode") or data.get("align") or "step"
try:
from util.sequence_playback import sync_beat_phase
if not await sync_beat_phase(str(mode)):
return (
json.dumps({"error": "No sequence is playing"}),
409,
{"Content-Type": "application/json"},
)
from util.audio_detector import anchor_shared_bar_phase
anchor_shared_bar_phase()
return json.dumps({"ok": True, "mode": str(mode).strip().lower()}), 200, {
"Content-Type": "application/json"
}
except Exception as e:
return json.dumps({"error": str(e)}), 500, {"Content-Type": "application/json"}
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("/stop")
@with_session
async def stop_sequence_playback(request, session):
"""Stop server-driven zone sequence playback."""
_ = request
try:
from util.sequence_playback import stop_playback
await stop_playback(clear_devices=True)
return json.dumps({"ok": True}), 200, {"Content-Type": "application/json"}
except Exception as e:
return json.dumps({"error": str(e)}), 500, {"Content-Type": "application/json"}
@controller.post("/<id>/play")
@with_session
async def play_sequence(request, session, id):
"""Start server-driven playback for a sequence in a zone (body: {\"zone_id\": \"...\"})."""
if not get_current_sender():
return (
json.dumps({"error": "Transport not configured"}),
503,
{"Content-Type": "application/json"},
)
current_profile_id = get_current_profile_id(session)
if not current_profile_id:
return (
json.dumps({"error": "No profile available"}),
404,
{"Content-Type": "application/json"},
)
try:
data = request.json or {}
except Exception:
data = {}
if not isinstance(data, dict):
data = {}
zone_id = data.get("zone_id") or data.get("zoneId")
if zone_id is None or str(zone_id).strip() == "":
return (
json.dumps({"error": "zone_id required"}),
400,
{"Content-Type": "application/json"},
)
zone_id = str(zone_id).strip()
try:
from util.sequence_playback import start
play_opts = data if isinstance(data, dict) else None
await start(zone_id, str(id), str(current_profile_id), play_opts)
from util.sequence_playback import pending_play_status
body = {"ok": True, **pending_play_status()}
return json.dumps(body), 200, {"Content-Type": "application/json"}
except ValueError as e:
return json.dumps({"error": str(e)}), 400, {"Content-Type": "application/json"}
except RuntimeError as e:
return json.dumps({"error": str(e)}), 503, {"Content-Type": "application/json"}
except Exception as e:
return json.dumps({"error": str(e)}), 500, {"Content-Type": "application/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
+3 -21
View File
@@ -4,10 +4,10 @@ import json
from microdot import Microdot, send_file
from models import wifi_ws_clients
from settings import get_settings
from settings import Settings
controller = Microdot()
settings = get_settings()
settings = Settings()
@controller.get('')
async def get_settings(request):
@@ -75,21 +75,7 @@ def _validate_global_brightness(value):
return v
def _validate_sequence_switch_wait(value):
s = str(value).strip().lower()
if s not in ("beat", "downbeat"):
raise ValueError("sequence_switch_wait must be beat or downbeat")
return s
def _validate_audio_beat_phase_ms(value):
v = int(value)
if v < 0 or v > 500:
raise ValueError("audio_beat_phase_ms must be between 0 and 500")
return v
@controller.put('')
@controller.put('/settings')
async def update_settings(request):
"""Update general settings."""
try:
@@ -101,10 +87,6 @@ async def update_settings(request):
elif key == 'global_brightness' and value is not None:
settings[key] = _validate_global_brightness(value)
global_brightness_changed = True
elif key == 'sequence_switch_wait' and value is not None:
settings[key] = _validate_sequence_switch_wait(value)
elif key == 'audio_beat_phase_ms' and value is not None:
settings[key] = _validate_audio_beat_phase_ms(value)
else:
settings[key] = value
settings.save()
+41 -21
View File
@@ -145,7 +145,6 @@ async def zone_content_fragment(request, session, id):
@controller.get("")
@with_session
async def list_zones(request, session):
zones.load()
profile_id = get_current_profile_id(session)
current_zone_id = get_current_zone_id(request, session)
zone_order = get_profile_zone_order(profile_id) if profile_id else []
@@ -212,9 +211,47 @@ 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>")
async def get_zone(request, id):
zones.load()
z = zones.read(id)
if z:
return json.dumps(z), 200, {"Content-Type": "application/json"}
@@ -292,8 +329,6 @@ async def create_zone(request, session):
ids_str = request.form.get("ids", "1").strip()
names = [i.strip() for i in ids_str.split(",") if i.strip()]
preset_ids = None
group_ids = []
content_kind = None
else:
data = request.json or {}
name = data.get("name", "")
@@ -301,20 +336,11 @@ async def create_zone(request, session):
if names is None:
names = data.get("ids")
preset_ids = data.get("presets", None)
group_ids = data.get("group_ids")
if group_ids is None:
group_ids = []
if isinstance(group_ids, list):
group_ids = [str(x) for x in group_ids if x is not None]
else:
group_ids = []
raw_kind = data.get("content_kind")
content_kind = raw_kind if raw_kind in ("presets", "sequences") else None
if not name:
return json.dumps({"error": "Zone name cannot be empty"}), 400
zid = zones.create(name, names, preset_ids, group_ids, content_kind)
zid = zones.create(name, names, preset_ids)
profile_id = get_current_profile_id(session)
if profile_id:
@@ -346,13 +372,7 @@ async def clone_zone(request, session, id):
data = request.json or {}
source_name = source.get("name") or f"Zone {id}"
new_name = data.get("name") or f"{source_name} Copy"
clone_id = zones.create(
new_name,
source.get("names"),
source.get("presets"),
source.get("group_ids"),
source.get("content_kind"),
)
clone_id = zones.create(new_name, source.get("names"), source.get("presets"))
extra = {k: v for k, v in source.items() if k not in ("name", "names", "presets")}
if extra:
zones.update(clone_id, extra)
+25
View File
@@ -0,0 +1,25 @@
"""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
+148
View File
@@ -0,0 +1,148 @@
"""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()
+89
View File
@@ -0,0 +1,89 @@
"""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(),
}
+68
View File
@@ -0,0 +1,68 @@
"""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))
+86
View File
@@ -0,0 +1,86 @@
"""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
+72
View File
@@ -0,0 +1,72 @@
"""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",
]
+78
View File
@@ -0,0 +1,78 @@
"""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)
+254
View File
@@ -0,0 +1,254 @@
"""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""]
+61
View File
@@ -0,0 +1,61 @@
"""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)
+97
View File
@@ -0,0 +1,97 @@
"""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
+75
View File
@@ -0,0 +1,75 @@
"""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
+92
View File
@@ -0,0 +1,92 @@
"""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)
+116
View File
@@ -0,0 +1,116 @@
"""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
+148
View File
@@ -0,0 +1,148 @@
"""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 []),
}
+61
View File
@@ -0,0 +1,61 @@
"""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)
+157
View File
@@ -0,0 +1,157 @@
"""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)
+161
View File
@@ -0,0 +1,161 @@
"""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()}
+56
View File
@@ -0,0 +1,56 @@
"""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)
+37 -243
View File
@@ -2,7 +2,6 @@ import asyncio
import errno
import json
import os
import secrets
import signal
import socket
import threading
@@ -10,7 +9,7 @@ import traceback
from microdot import Microdot, send_file
from microdot.websocket import with_websocket
from microdot.session import Session
from settings import get_settings
from settings import Settings
import controllers.preset as preset
import controllers.profile as profile
@@ -23,6 +22,9 @@ import controllers.pattern as pattern
import controllers.settings as settings_controller
import controllers.device as device_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.device import Device, normalize_mac
from models import wifi_ws_clients as tcp_client_registry
@@ -32,18 +34,12 @@ from util.device_status_broadcaster import (
register_device_status_ws,
unregister_device_status_ws,
)
from util.audio_detector import AudioBeatDetector
_tcp_device_lock = threading.Lock()
DISCOVERY_UDP_PORT = 8766
def _live_reload_enabled() -> bool:
v = os.environ.get("LED_CONTROLLER_LIVE_RELOAD", "").strip().lower()
return v not in ("", "0", "false", "no")
def _register_udp_device_sync(
device_name: str, peer_ip: str, mac, device_type=None
) -> None:
@@ -159,12 +155,8 @@ async def _periodic_wifi_driver_hello_loop(settings, udp_holder) -> None:
sock.setblocking(False)
loop = asyncio.get_running_loop()
try:
while not udp_holder.get("closing"):
slept = 0.0
while slept < interval and not udp_holder.get("closing"):
chunk = min(1.0, interval - slept)
await asyncio.sleep(chunk)
slept += chunk
while True:
await asyncio.sleep(interval)
if udp_holder.get("closing"):
break
try:
@@ -248,7 +240,7 @@ async def _send_bridge_wifi_channel(settings, sender):
async def main(port=80):
settings = get_settings()
settings = Settings()
print(settings)
print("Starting")
@@ -257,29 +249,6 @@ async def main(port=80):
set_sender(sender)
app = Microdot()
audio_detector = AudioBeatDetector()
try:
from util import audio_detector as audio_detector_module
audio_detector_module.set_shared_beat_detector(audio_detector)
except Exception as e:
print(f"[startup] audio detector shared registration skipped: {e!r}")
try:
from util.audio_run_persist import coerce_audio_device, read_audio_run_state
persisted = read_audio_run_state()
if persisted.get("enabled"):
dev = coerce_audio_device(persisted.get("device"))
audio_detector.start(device=dev)
print("[startup] audio beat detector started from saved run state")
except Exception as e:
print(f"[startup] audio auto-start skipped: {e!r}")
from util import beat_driver_route
beat_driver_route.set_beat_route_main_loop(asyncio.get_running_loop())
from util import sequence_playback as seq_pb
seq_pb.ensure_beat_consumer_started()
# Initialize sessions with a secret key from settings
secret_key = settings.get('session_secret_key', 'led-controller-secret-key-change-in-production')
@@ -295,6 +264,7 @@ async def main(port=80):
('/zones', zone, 'zone'),
('/palettes', palette, 'palette'),
('/scenes', scene, 'scene'),
('/outputs', output_controller, 'output'),
]
# Mount model controllers as subroutes
@@ -309,160 +279,27 @@ async def main(port=80):
app.mount(settings_controller.controller, '/settings')
app.mount(device_controller.controller, '/devices')
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_tcp_status_broadcaster(broadcast_device_tcp_status)
live_reload = _live_reload_enabled()
dev_build_id = secrets.token_hex(12) if live_reload else None
if live_reload:
print(
"[dev] LED_CONTROLLER_LIVE_RELOAD: browser refreshes when the server process restarts"
)
if dev_build_id:
@app.route("/__dev/build-id")
def dev_build_id_route(request):
_ = request
return (
dev_build_id,
200,
{
"Content-Type": "text/plain; charset=utf-8",
"Cache-Control": "no-store",
},
)
# Serve index.html at root (cwd is src/ when run via pipenv run run)
@app.route("/")
@app.route('/')
def index(request):
"""Serve the main web UI."""
if dev_build_id:
try:
with open("templates/index.html", encoding="utf-8") as f:
html = f.read()
tag = '<script src="/static/dev-live-reload.js" defer></script>'
if "</body>" in html:
html = html.replace("</body>", tag + "\n</body>", 1)
return html, 200, {"Content-Type": "text/html; charset=utf-8"}
except OSError:
pass
return send_file("templates/index.html")
return send_file('templates/index.html')
# Favicon: avoid 404 in browser console (no file needed)
@app.route('/favicon.ico')
def favicon(request):
return '', 204
@app.route('/api/audio/devices')
async def audio_devices(request):
_ = request
try:
return {
"devices": audio_detector.list_input_devices(),
"diagnostics": audio_detector.diagnostics(),
}
except Exception as e:
return {"error": str(e)}, 500
@app.route('/api/audio/start', methods=['POST'])
async def audio_start(request):
payload = request.json if isinstance(request.json, dict) else {}
device = payload.get("device", None)
if device in ("", None):
device = None
else:
try:
device = int(device)
except (TypeError, ValueError):
pass
try:
audio_detector.start(device=device)
from util.audio_run_persist import write_audio_run_state
write_audio_run_state(
enabled=True,
device=device,
device_override=str(payload.get("device_override") or ""),
device_select=str(payload.get("device_select") or ""),
)
return {"ok": True, "status": audio_detector.status()}
except Exception as e:
return {"ok": False, "error": str(e)}, 500
@app.route('/api/audio/stop', methods=['POST'])
async def audio_stop(request):
_ = request
audio_detector.stop()
from util.audio_run_persist import write_audio_run_state
write_audio_run_state(enabled=False)
return {"ok": True, "status": audio_detector.status()}
@app.route('/api/audio/reset', methods=['POST'])
async def audio_reset(request):
"""Clear beat/BPM tracking state without stopping the detector."""
_ = request
ok = audio_detector.reset_tracking()
if not ok:
return {"ok": False, "error": "Audio detector is not running"}, 409
return {"ok": True, "status": audio_detector.status()}
@app.route('/api/audio/anchor-bar', methods=['POST'])
async def audio_anchor_bar(request):
"""Mark the current moment as bar beat 1 (downbeat)."""
_ = request
ok = audio_detector.anchor_bar_phase()
if not ok:
return {"ok": False, "error": "Audio detector is not running"}, 409
return {"ok": True, "status": audio_detector.status()}
@app.route('/api/audio/status')
async def audio_status(request):
_ = request
from util import beat_driver_route
from util import sequence_playback
st = audio_detector.status()
st["sequence"] = sequence_playback.playback_status()
st["manual_beat_stride"] = beat_driver_route.manual_beat_stride_status()
seq = st.get("sequence")
beat_readout = ""
if isinstance(seq, dict) and str(seq.get("beat_readout") or "").strip():
beat_readout = str(seq.get("beat_readout") or "").strip()
elif st.get("running"):
mb = st.get("manual_beat_stride")
if isinstance(mb, dict) and mb.get("active"):
try:
n = int(mb.get("stride_n") or 1)
except (TypeError, ValueError):
n = 1
n = max(1, min(64, n))
try:
bi = int(mb.get("beat_in_stride") or 1)
except (TypeError, ValueError):
bi = 1
pos = min(n, max(1, bi))
beat_readout = f"{pos}/{n}"
else:
try:
bs = int(st.get("beat_seq") or 0)
except (TypeError, ValueError):
bs = 0
if bs > 0:
beat_readout = str(bs)
st["beat_readout"] = beat_readout
from util.audio_run_persist import read_audio_run_state
st["beat_phase_ms"] = int(settings.get("audio_beat_phase_ms") or 0)
seq_wait = str(settings.get("sequence_switch_wait") or "beat").strip().lower()
if seq_wait not in ("beat", "downbeat"):
seq_wait = "beat"
st["sequence_switch_wait"] = seq_wait
st["audio_run"] = read_audio_run_state()
return {"status": st}
# Static file route
@app.route("/static/<path:path>")
def static_handler(request, path):
@@ -515,30 +352,21 @@ async def main(port=80):
await _send_bridge_wifi_channel(settings, sender)
_prime_wifi_outbound_driver_connections()
udp_holder = {"closing": False, "shutting_down": False}
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}
loop = asyncio.get_running_loop()
server_tasks: list[asyncio.Task] = []
def _graceful_shutdown(*_args):
if udp_holder.get("shutting_down"):
raise SystemExit(0)
udp_holder["shutting_down"] = True
print("[server] shutting down...")
udp_holder["closing"] = True
try:
audio_detector.stop()
except Exception:
pass
try:
from util import sequence_playback as seq_pb
seq_pb.stop()
for attr in ("_pending_beat_task", "_sim_beat_task"):
t = getattr(seq_pb, attr, None)
if t is not None and not t.done():
t.cancel()
except Exception:
pass
u = udp_holder.get("sock")
if u is not None:
try:
@@ -547,13 +375,7 @@ async def main(port=80):
pass
tcp_client_registry.cancel_all_driver_tasks()
if getattr(app, "server", None) is not None:
try:
app.shutdown()
except Exception:
pass
for t in server_tasks:
if not t.done():
t.cancel()
app.shutdown()
shutdown_handlers_registered = False
try:
@@ -566,21 +388,11 @@ async def main(port=80):
# Await HTTP + UDP discovery; bind failures (e.g. port 80 in use) surface here.
try:
server_tasks[:] = [
asyncio.create_task(
app.start_server(host="0.0.0.0", port=port), name="http"
),
asyncio.create_task(
_run_udp_discovery_server(udp_holder), name="udp"
),
asyncio.create_task(
_periodic_wifi_driver_hello_loop(settings, udp_holder),
name="hello",
),
]
await asyncio.gather(*server_tasks)
except asyncio.CancelledError:
pass
await asyncio.gather(
app.start_server(host="0.0.0.0", port=port),
_run_udp_discovery_server(udp_holder),
_periodic_wifi_driver_hello_loop(settings, udp_holder),
)
except OSError as e:
if e.errno == errno.EADDRINUSE:
print(
@@ -591,9 +403,10 @@ async def main(port=80):
raise
finally:
try:
audio_detector.stop()
except Exception:
pass
# 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)
if srv is not None:
try:
@@ -605,21 +418,6 @@ async def main(port=80):
app.server = None
except Exception:
pass
udp_holder["closing"] = True
for t in list(server_tasks):
if not t.done():
t.cancel()
if server_tasks:
await asyncio.gather(*server_tasks, return_exceptions=True)
pending = [
t
for t in asyncio.all_tasks(loop)
if t is not asyncio.current_task() and not t.done()
]
for t in pending:
t.cancel()
if pending:
await asyncio.gather(*pending, return_exceptions=True)
if shutdown_handlers_registered:
for sig in (signal.SIGINT, signal.SIGTERM):
try:
@@ -629,9 +427,5 @@ async def main(port=80):
if __name__ == "__main__":
import os
port = int(os.environ.get("PORT", 80))
try:
asyncio.run(main(port=port))
except KeyboardInterrupt:
print("[server] interrupted")
asyncio.run(main(port=port))
-23
View File
@@ -38,29 +38,6 @@ def normalize_mac(mac):
return None
def resolve_device_mac_for_select_routing(devices, name_key):
"""
Map a v1 ``select`` map key to device storage id (MAC).
Matches the registry **name**, or ``led-<12hex>`` as a MAC hint (default driver
name form) so routing still works after the device is renamed in the registry.
"""
k = str(name_key or "").strip()
if not k:
return None
for did in devices.list():
doc = devices.read(did) or {}
if str(doc.get("name") or "").strip() == k:
m = normalize_mac(did)
if m:
return m
if k.startswith("led-"):
m = normalize_mac(k[4:])
if m and devices.read(m):
return m
return None
def derive_device_mac(mac=None, address=None, transport="espnow"):
"""
Resolve the device MAC used as storage id.
+1 -58
View File
@@ -1,71 +1,14 @@
from models.model import Model
class Group(Model):
"""Device groups (members + optional Wi‑Fi driver defaults); also pattern fields for sequences.
Omit ``profile_id`` (or set it null) for a **shared** group: every profile can attach it to
zones and sequences. Set ``profile_id`` to a profile id to show the group only when that
profile is active (still one global record in ``group.json``).
"""
def __init__(self):
super().__init__()
def load(self):
super().load()
changed = False
for gid, doc in list(self.items()):
if not isinstance(doc, dict):
continue
if self._migrate_record(doc):
changed = True
if changed:
self.save()
def _migrate_record(self, doc):
changed = False
raw_dev = doc.get("devices")
if raw_dev is None:
doc["devices"] = []
changed = True
elif isinstance(raw_dev, list):
norm = []
for x in raw_dev:
if x is None:
continue
s = str(x).strip().lower().replace(":", "").replace("-", "")
if len(s) == 12 and all(c in "0123456789abcdef" for c in s):
norm.append(s)
else:
norm.append(str(x).strip())
if norm != raw_dev:
doc["devices"] = norm
changed = True
for key in (
"wifi_driver_display_name",
"wifi_driver_num_leds",
"wifi_color_order",
"wifi_startup_mode",
):
if key not in doc:
doc[key] = None
changed = True
if "output_brightness" not in doc:
doc["output_brightness"] = 255
changed = True
return changed
def create(self, name=""):
next_id = self.get_next_id()
self[next_id] = {
"name": name,
"devices": [],
"wifi_driver_display_name": None,
"wifi_driver_num_leds": None,
"wifi_color_order": None,
"wifi_startup_mode": None,
"output_brightness": 255,
"pattern": "on",
"colors": ["000000", "FF0000"],
"brightness": 100,
@@ -79,7 +22,7 @@ class Group(Model):
"n5": 0,
"n6": 0,
"n7": 0,
"n8": 0,
"n8": 0
}
self.save()
return next_id
+138
View File
@@ -0,0 +1,138 @@
"""
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]
-5
View File
@@ -15,9 +15,6 @@ class Preset(Model):
if default_profile_id is not None:
preset_data["profile_id"] = str(default_profile_id)
changed = True
if isinstance(preset_data, dict) and "group_ids" in preset_data:
preset_data.pop("group_ids", None)
changed = True
if changed:
self.save()
except Exception:
@@ -29,7 +26,6 @@ class Preset(Model):
"name": "",
"pattern": "",
"colors": [],
"background": "#000000",
"brightness": 0,
"delay": 0,
"n1": 0,
@@ -40,7 +36,6 @@ class Preset(Model):
"n6": 0,
"n7": 0,
"n8": 0,
"manual_beat_n": 1,
"profile_id": str(profile_id) if profile_id is not None else None,
}
self.save()
-159
View File
@@ -1,159 +0,0 @@
from models.model import Model
class Sequence(Model):
def load(self):
super().load()
self._migrate_after_load()
def _migrate_after_load(self):
try:
from models.profile import Profile
profiles = Profile()
profile_list = profiles.list()
default_profile_id = profile_list[0] if profile_list else None
except Exception:
default_profile_id = None
changed = False
for _sid, doc in list(self.items()):
if not isinstance(doc, dict):
continue
if not isinstance(doc.get("steps"), list):
presets = doc.get("presets")
if isinstance(presets, list) and presets:
doc["steps"] = [
{"preset_id": str(p), "group_ids": []} for p in presets
]
else:
doc["steps"] = []
changed = True
if "step_duration_ms" not in doc:
dur = doc.get("sequence_duration")
doc["step_duration_ms"] = (
int(dur) if isinstance(dur, (int, float)) else 3000
)
changed = True
if "loop" not in doc:
doc["loop"] = bool(doc.get("sequence_loop", False))
changed = True
if "name" not in doc:
doc["name"] = str(doc.get("group_name") or "")
changed = True
if "profile_id" not in doc and default_profile_id is not None:
doc["profile_id"] = str(default_profile_id)
changed = True
if not isinstance(doc.get("lanes"), list):
steps = doc.get("steps")
if isinstance(steps, list) and steps:
doc["lanes"] = [list(steps)]
else:
doc["lanes"] = [[]]
changed = True
if "group_ids" not in doc or not isinstance(doc.get("group_ids"), list):
doc["group_ids"] = []
changed = True
if doc.get("advance_mode") != "beats":
doc["advance_mode"] = "beats"
changed = True
if "simulated_bpm" not in doc:
doc["simulated_bpm"] = 120
changed = True
else:
try:
sb = int(float(doc["simulated_bpm"]))
doc["simulated_bpm"] = max(30, min(300, sb))
except (TypeError, ValueError):
doc["simulated_bpm"] = 120
changed = True
if "sequence_transition" not in doc:
doc["sequence_transition"] = 500
changed = True
# Ensure each step has beats (beat-based advance); default 1
for lane in doc.get("lanes") or []:
if not isinstance(lane, list):
continue
for step in lane:
if not isinstance(step, dict):
continue
if "beats" not in step:
step["beats"] = 1
changed = True
# Per-lane group ids (parallel to ``lanes``)
lanes_list = [x for x in (doc.get("lanes") or []) if isinstance(x, list)]
n_lanes = len(lanes_list)
lg = doc.get("lanes_group_ids")
if n_lanes and (not isinstance(lg, list) or len(lg) != n_lanes):
shared = doc.get("group_ids") if isinstance(doc.get("group_ids"), list) else []
shared_s = [str(x).strip() for x in shared if x is not None and str(x).strip()]
if n_lanes == 1 and lanes_list[0]:
first = lanes_list[0][0] if isinstance(lanes_list[0][0], dict) else {}
step_g = (
first.get("group_ids")
if isinstance(first.get("group_ids"), list)
else []
)
step_s = [
str(x).strip() for x in step_g if x is not None and str(x).strip()
]
doc["lanes_group_ids"] = [step_s if step_s else list(shared_s)]
else:
doc["lanes_group_ids"] = [list(shared_s) for _ in range(n_lanes)]
changed = True
if changed:
self.save()
def create(self, profile_id=None):
next_id = self.get_next_id()
self[next_id] = {
"name": "",
"profile_id": str(profile_id) if profile_id is not None else None,
"group_ids": [],
"lanes": [[]],
"lanes_group_ids": [[]],
"advance_mode": "beats",
"steps": [],
"step_duration_ms": 3000,
"simulated_bpm": 120,
"sequence_transition": 500,
"loop": True,
}
self.save()
return next_id
def read(self, id):
id_str = str(id)
return self.get(id_str, None)
def update(self, id, data):
id_str = str(id)
if id_str not in self:
return False
if not isinstance(data, dict):
return False
data = dict(data)
steps = data.get("steps")
lanes = data.get("lanes")
if isinstance(steps, list) and steps:
lanes_ok = (
isinstance(lanes, list)
and lanes
and any(isinstance(x, list) and len(x) > 0 for x in lanes)
)
if not lanes_ok:
data["lanes"] = [list(steps)]
self[id_str].update(data)
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())
+112
View File
@@ -0,0 +1,112 @@
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):
def __init__(self):
super().__init__()
def load(self):
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()
self[next_id] = doc
self.save()
return next_id
def read(self, id):
id_str = str(id)
return self.get(id_str, 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 {})
self[id_str] = _normalize(merged)
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())
+21 -12
View File
@@ -124,6 +124,15 @@ def _register_ws(ip: str, ws) -> None:
_send_locks[key] = asyncio.Lock()
_schedule_status_broadcast(key, True)
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:
@@ -261,33 +270,33 @@ async def _driver_connection_loop(ip: str) -> None:
retry_interval_s = 2.0
retry_interval_s = max(0.2, retry_interval_s)
try:
max_boot_attempts = int(_settings.get("wifi_driver_initial_connect_attempts", 4))
retry_window_s = float(_settings.get("wifi_driver_connect_retry_window_s", 120.0))
except (TypeError, ValueError):
max_boot_attempts = 4
max_boot_attempts = max(1, max_boot_attempts)
retry_window_s = 120.0
retry_window_s = max(5.0, retry_window_s)
try:
open_timeout = float(_settings.get("wifi_driver_ws_open_timeout", 45.0))
except (TypeError, ValueError):
open_timeout = 45.0
open_timeout = max(5.0, open_timeout)
loop = asyncio.get_running_loop()
stagger = _stagger_delay_s_for_ip(ip)
if stagger > 0:
await asyncio.sleep(stagger)
# Only bound boot-time: after we have connected once, keep retrying (Wi-Fi drops, reboots).
connected_once = False
boot_attempts = 0
deadline = loop.time() + retry_window_s
try:
while True:
if not connected_once:
if boot_attempts >= max_boot_attempts:
print(
f"[WS] driver {ip} still unreachable after {max_boot_attempts} "
f"initial dial attempt(s); stopping until next UDP hello / registry prime"
)
break
boot_attempts += 1
now = loop.time()
if not connected_once and now >= deadline:
print(
f"[WS] driver {ip} still unreachable after {int(retry_window_s)}s "
f"(initial window); stopping until next UDP hello / registry prime"
)
break
try:
print(f"[WS] connecting to {uri!r}")
async with websockets.connect(
+4 -95
View File
@@ -19,11 +19,7 @@ def _maybe_migrate_tab_json_to_zone():
class Zone(Model):
"""Preset layout row (stored in ``db/zone.json``); legacy storage was ``tab.json`` / Tab.
Optional ``content_kind`` on a row: ``\"presets\"`` (preset tiles only) or ``\"sequences\"``
(sequence tiles only). Legacy rows without ``content_kind`` are inferred on load.
"""
"""Preset layout row (stored in ``db/zone.json``); legacy storage was ``tab.json`` / Tab."""
def __init__(self):
if not getattr(Zone, "_migration_checked", False):
@@ -31,98 +27,14 @@ class Zone(Model):
Zone._migration_checked = True
super().__init__()
def load(self):
super().load()
changed = False
for zid, doc in list(self.items()):
if not isinstance(doc, dict):
continue
if "group_ids" not in doc:
doc["group_ids"] = []
changed = True
if "preset_group_ids" not in doc or not isinstance(doc.get("preset_group_ids"), dict):
doc["preset_group_ids"] = {}
changed = True
if "sequence_ids" not in doc or not isinstance(doc.get("sequence_ids"), list):
doc["sequence_ids"] = []
changed = True
if not self._normalized_content_kind(doc):
doc["content_kind"] = self._infer_content_kind(doc)
changed = True
if changed:
self.save()
@staticmethod
def _normalized_content_kind(doc):
if not isinstance(doc, dict):
return None
kind = doc.get("content_kind")
return kind if kind in ("presets", "sequences") else None
@staticmethod
def _preset_ids_in_doc(doc):
if not isinstance(doc, dict):
return []
flat = doc.get("presets_flat")
if isinstance(flat, list):
return [str(x) for x in flat if x is not None and str(x).strip()]
presets = doc.get("presets")
if not isinstance(presets, list) or not presets:
return []
if isinstance(presets[0], str):
return [str(x) for x in presets if x is not None and str(x).strip()]
if isinstance(presets[0], list):
out = []
for row in presets:
if isinstance(row, list):
out.extend(str(x) for x in row if x is not None and str(x).strip())
return out
return []
@classmethod
def _infer_content_kind(cls, doc):
kind = cls._normalized_content_kind(doc)
if kind:
return kind
seq_ids = [
str(x).strip()
for x in (doc.get("sequence_ids") or [])
if x is not None and str(x).strip()
]
preset_ids = cls._preset_ids_in_doc(doc)
if seq_ids and not preset_ids:
return "sequences"
return "presets"
def _enforce_content_kind_invariants(self, doc):
"""Presets-only zones hold no sequences; sequences-only hold no preset tiles."""
kind = self._normalized_content_kind(doc)
if kind == "presets":
doc["sequence_ids"] = []
elif kind == "sequences":
doc["presets"] = []
doc["presets_flat"] = []
def create(self, name="", names=None, presets=None, group_ids=None, content_kind=None):
def create(self, name="", names=None, presets=None):
next_id = self.get_next_id()
gid_list = []
if isinstance(group_ids, list):
gid_list = [str(x).strip() for x in group_ids if x is not None and str(x).strip()]
doc = {
self[next_id] = {
"name": name,
"names": names if names else [],
"group_ids": gid_list,
"preset_group_ids": {},
"presets": presets if presets else [],
"default_preset": None,
"brightness": 255,
}
if content_kind in ("presets", "sequences"):
doc["content_kind"] = content_kind
if "sequence_ids" not in doc:
doc["sequence_ids"] = []
self._enforce_content_kind_invariants(doc)
self[next_id] = doc
self.save()
return next_id
@@ -134,10 +46,7 @@ class Zone(Model):
id_str = str(id)
if id_str not in self:
return False
patch = data if isinstance(data, dict) else {}
self[id_str].update(patch)
if "content_kind" in patch:
self._enforce_content_kind_invariants(self[id_str])
self[id_str].update(data)
self.save()
return True
+6 -39
View File
@@ -12,15 +12,11 @@ def _settings_path():
return "settings.json"
_settings_singleton: "Settings | None" = None
class Settings(dict):
SETTINGS_FILE = None # Set in __init__ from _settings_path()
def __init__(self, *, quiet: bool = False):
def __init__(self):
super().__init__()
self._quiet = quiet
if Settings.SETTINGS_FILE is None:
Settings.SETTINGS_FILE = _settings_path()
self.load() # Load settings from file during initialization
@@ -61,8 +57,8 @@ class Settings(dict):
# down (0 disables). Helps drivers that reconnect after seeing traffic on 8766.
if 'wifi_driver_hello_interval_s' not in self:
self['wifi_driver_hello_interval_s'] = 10.0
# Legacy key (no longer read): initial outbound dial limit uses
# wifi_driver_initial_connect_attempts instead.
# Outbound WebSocket dial: total seconds to keep trying before first success
# (many devices booting at once need more than a short window).
if 'wifi_driver_connect_retry_window_s' not in self:
self['wifi_driver_connect_retry_window_s'] = 120.0
# Spread outbound dials 0..N s by device IP so six+ drivers do not all hit the AP at once.
@@ -74,31 +70,19 @@ class Settings(dict):
# Pause between outbound WebSocket dial attempts (seconds).
if 'wifi_driver_connect_retry_interval_s' not in self:
self['wifi_driver_connect_retry_interval_s'] = 2.0
# Outbound dial attempts to the saved driver IP before first success; then wait for UDP discovery.
if 'wifi_driver_initial_connect_attempts' not in self:
self['wifi_driver_initial_connect_attempts'] = 4
# UART to ESP32 ESP-NOW bridge; default off (Wi-Fi drivers need no serial).
if 'serial_enabled' not in self:
self['serial_enabled'] = False
# Zone UI global brightness (0–255); shared across browsers/devices.
if 'global_brightness' not in self:
self['global_brightness'] = 255
# Sequence tile start: wait for beat or downbeat (server-owned).
if 'sequence_switch_wait' not in self:
self['sequence_switch_wait'] = 'beat'
elif str(self.get('sequence_switch_wait', '')).strip().lower() == 'phrase':
self['sequence_switch_wait'] = 'beat'
# Beat flash alignment delay (ms); applied by all UI clients polling audio status.
if 'audio_beat_phase_ms' not in self:
self['audio_beat_phase_ms'] = 0
def save(self):
try:
j = json.dumps(self)
with open(self.SETTINGS_FILE, 'w') as file:
file.write(j)
if not getattr(self, "_quiet", False):
print("Settings saved successfully.")
print("Settings saved successfully.")
except Exception as e:
print(f"Error saving settings: {e}")
@@ -109,11 +93,9 @@ class Settings(dict):
loaded_settings = json.load(file)
self.update(loaded_settings)
loaded_from_file = True
if not getattr(self, "_quiet", False):
print("Settings loaded successfully.")
print("Settings loaded successfully.")
except Exception as e:
if not getattr(self, "_quiet", False):
print(f"Error loading settings: {e}")
print(f"Error loading settings")
self.clear()
finally:
# Ensure defaults are set even if file exists but is missing keys
@@ -121,18 +103,3 @@ class Settings(dict):
# Only save if file didn't exist or was invalid
if not loaded_from_file:
self.save()
def get_settings() -> Settings:
"""Process-wide settings instance (avoid re-reading settings.json on every request)."""
global _settings_singleton
if _settings_singleton is None:
_settings_singleton = Settings()
return _settings_singleton
def reload_settings() -> Settings:
"""Re-read settings.json (e.g. after external file edit)."""
global _settings_singleton
_settings_singleton = Settings(quiet=True)
return _settings_singleton
-571
View File
@@ -1,571 +0,0 @@
(() => {
let pollTimer = null;
let lastBeatSeq = 0;
let lastLoggedSequenceBeatFractions = "";
/** Prior poll had server zone sequence playback active (`status.sequence.active === true`). */
let prevZoneSequencePlaybackActive = false;
/**
* After sequence playback ends/stops while audio keeps running, keep header # idle until the
* next beat bumps `beat_seq` (avoids the stuck final cumulative value vs sequence readout).
*/
let headerBeatStickyIdleAfterSeq = false;
/** Suppresses duplicate `console.log` when the same `beat_seq` + server `beat_readout` repeats. */
let lastBeatConsoleKey = "";
/** @type {Set<ReturnType<typeof setTimeout>>} */
const pendingBeatPhaseTimers = new Set();
function el(id) {
return document.getElementById(id);
}
/** @param {Record<string, unknown>} status */
function updateBeatReadoutDisplays(status) {
const text = String((status && status.beat_readout) || "").trim();
for (const id of ["audio-top-beat-readout", "audio-modal-beat-readout"]) {
const n = el(id);
if (n) n.textContent = text;
}
}
/**
* On each new audio `beat_seq`, log server `beat_readout` once (deduped when poll repeats the
* same `beat_seq` + line).
* @param {Record<string, unknown>} status
*/
function logServerBeatConsoleOnPollEdge(status) {
const beatSeq = Number((status && status.beat_seq) || 0);
const line = String((status && status.beat_readout) || "").trim();
const key = `${beatSeq}\t${line}`;
if (key !== lastBeatConsoleKey) {
lastBeatConsoleKey = key;
if (!line) return;
const seq = /** @type {Record<string, unknown>|undefined} */ (status && status.sequence);
const seqBeats = !!seq && !!seq.active;
let out = line;
if (seqBeats) {
const nLanes = Number(seq && seq.num_lanes);
const lanesNote =
Number.isFinite(nLanes) && nLanes > 1
? `lane 1 of ${nLanes} (readout is for this lane only)`
: "lane 1";
out = `${line} — ${lanesNote}`;
}
console.log(out);
}
}
function updateBpmDisplay(bpm) {
const node = el("audio-bpm-value");
if (!node) return;
node.textContent = Number.isFinite(bpm) ? bpm.toFixed(1) : "--";
const topNode = el("audio-top-bpm-value");
if (topNode) {
topNode.textContent = Number.isFinite(bpm) ? bpm.toFixed(1) : "--";
}
}
/** Zone sequence playback (server); only when `active === true` is beat X/Y meaningful. */
function sequencePlaybackActiveFromStatus(status) {
const seq = /** @type {Record<string, unknown>|undefined} */ (
status && status.sequence
);
return !!(seq && seq.active);
}
/** Build sequence beat fractions for debug logging (browser console only). */
function formatSequenceBeatFractionsForLog(status) {
const seq = /** @type {Record<string, unknown>|undefined} */ (status && status.sequence);
if (!seq || !seq.active) return null;
const laneBeatAt = Number(seq.lane0_beat_in_step);
const laneBeatsPerStep = Number(seq.lane0_beats_per_step);
if (
!Number.isFinite(laneBeatAt) ||
laneBeatAt <= 0 ||
!Number.isFinite(laneBeatsPerStep) ||
laneBeatsPerStep <= 0
) {
return null;
}
const presetFraction = `${Math.floor(laneBeatAt)}/${Math.floor(laneBeatsPerStep)}`;
const sequenceBeatAt = Number(seq.sequence_beat_at);
const sequenceBeatsPerPass = Number(seq.sequence_beats_per_pass);
if (
!Number.isFinite(sequenceBeatAt) ||
sequenceBeatAt <= 0 ||
!Number.isFinite(sequenceBeatsPerPass) ||
sequenceBeatsPerPass <= 0
) {
return null;
}
const sequenceFraction = `${Math.floor(sequenceBeatAt)}/${Math.floor(sequenceBeatsPerPass)}`;
return `${presetFraction} ${sequenceFraction}`;
}
function updateHitTypeDisplay(hitType, confidence) {
const node = el("audio-hit-type-value");
if (!node) return;
const label = String(hitType || "unknown").toLowerCase();
const conf = Number.isFinite(confidence) ? ` (${confidence.toFixed(2)})` : "";
node.textContent = `${label}${conf}`;
}
/** @param {Record<string, unknown>} status */
function updateBarPhaseDisplay(status) {
const readout = String((status && status.bar_phase_readout) || "").trim();
const phaseConf = Number((status && status.phase_confidence) || 0);
const downbeat = !!(status && status.is_downbeat);
let text = readout || "--";
if (readout && Number.isFinite(phaseConf) && phaseConf > 0) {
text = `${text} (${Math.round(phaseConf * 100)}%)`;
}
for (const id of ["audio-bar-phase-value", "audio-top-bar-phase"]) {
const node = el(id);
if (!node) continue;
node.textContent = status && status.running ? text : "";
node.classList.toggle("is-downbeat", downbeat && !!readout);
}
}
function setTopBpmVisible(on) {
const top = el("audio-top-indicator");
if (!top) return;
top.classList.toggle("audio-running", !!on);
}
function setNavResetVisible(on) {
for (const id of ["audio-nav-reset-btn", "audio-nav-reset-mobile"]) {
const node = el(id);
if (node) node.hidden = !on;
}
}
async function resetAudioTracking() {
try {
const res = await fetch("/api/audio/reset", {
method: "POST",
headers: { Accept: "application/json" },
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
console.warn("audio reset failed", data.error || res.status);
return;
}
await pollStatus();
} catch (e) {
console.warn("audio reset failed", e);
}
}
function updateSequenceSyncControls(zoneSeqActive) {
const topSync = el("audio-top-beat-sync");
if (topSync) topSync.disabled = !zoneSeqActive;
const modalBeat = el("audio-modal-beat-readout");
if (modalBeat) modalBeat.disabled = !zoneSeqActive;
const passBtn = el("audio-sync-pass-btn");
if (passBtn) passBtn.disabled = !zoneSeqActive;
}
async function syncSequenceBeatPhase(mode) {
const res = await fetch("/sequences/sync-phase", {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ mode: mode || "step" }),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data.error || `Sync failed (${res.status})`);
}
await pollStatus();
}
function isTypingTarget(target) {
if (!target || typeof target !== "object") return false;
const tag = String(target.tagName || "").toLowerCase();
return tag === "input" || tag === "textarea" || tag === "select" || target.isContentEditable;
}
function flashBeat() {
const node = el("audio-beat-flash");
if (!node) return;
node.classList.add("active");
setTimeout(() => node.classList.remove("active"), 80);
const syncBtn = el("audio-top-beat-sync");
const top = el("audio-top-indicator");
if (syncBtn && top && top.classList.contains("audio-running")) {
syncBtn.classList.add("flash");
setTimeout(() => syncBtn.classList.remove("flash"), 90);
}
}
function clearBeatPhaseTimers() {
pendingBeatPhaseTimers.forEach((t) => clearTimeout(t));
pendingBeatPhaseTimers.clear();
}
function getBeatPhaseDelayMs() {
const inp = el("audio-beat-phase-ms");
if (inp && String(inp.value).trim() !== "") {
const n = parseInt(String(inp.value).trim(), 10);
if (Number.isFinite(n)) return Math.min(500, Math.max(0, n));
}
return 0;
}
async function persistBeatPhaseMs() {
const ms = getBeatPhaseDelayMs();
try {
await fetch("/settings", {
method: "PUT",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ audio_beat_phase_ms: ms }),
});
} catch (e) {
console.warn("beat phase ms save failed", e);
}
}
function scheduleBeatPhaseFire(seq, delayMs) {
let tid = null;
const run = () => {
if (tid != null) pendingBeatPhaseTimers.delete(tid);
flashBeat();
try {
window.dispatchEvent(
new CustomEvent("ledControllerAudioBeat", { detail: { beatSeq: seq } }),
);
} catch (e) {
/* ignore */
}
};
if (delayMs <= 0) {
run();
return;
}
tid = setTimeout(run, delayMs);
pendingBeatPhaseTimers.add(tid);
}
/** Stop detector and polling; does not clear “resume on load” prefs (used before restart). */
async function stopAudioOnly() {
setTopBpmVisible(false);
setNavResetVisible(false);
clearBeatPhaseTimers();
if (pollTimer) {
clearInterval(pollTimer);
pollTimer = null;
}
lastBeatSeq = 0;
prevZoneSequencePlaybackActive = false;
headerBeatStickyIdleAfterSeq = false;
lastBeatConsoleKey = "";
updateBeatReadoutDisplays({});
try {
await fetch("/api/audio/stop", { method: "POST" });
} catch (e) {
console.warn("audio stop failed", e);
}
}
/** User-initiated stop (run intent cleared on server). */
async function stopAudio() {
await stopAudioOnly();
}
async function pollStatus() {
try {
const res = await fetch("/api/audio/status", { cache: "no-store" });
const data = await res.json();
const status = data?.status || {};
if (status.error && String(status.error).trim()) {
const node = el("audio-hit-type-value");
if (node) {
node.textContent = String(status.error).trim().slice(0, 120);
}
updateBeatReadoutDisplays({});
updateBpmDisplay(null);
setTopBpmVisible(!!status.running);
setNavResetVisible(!!status.running);
if (!status.running && pollTimer) {
clearInterval(pollTimer);
pollTimer = null;
}
return;
}
const zoneSeqActive = sequencePlaybackActiveFromStatus(status);
setTopBpmVisible(!!status.running || zoneSeqActive);
setNavResetVisible(!!status.running);
updateSequenceSyncControls(zoneSeqActive);
updateBpmDisplay(status.bpm);
updateHitTypeDisplay(status.beat_type, Number(status.beat_type_confidence));
updateBarPhaseDisplay(status);
applyServerAudioUiFields(status);
if (typeof window.applySequenceSwitchWaitFromServer === "function") {
window.applySequenceSwitchWaitFromServer(status.sequence_switch_wait);
}
/*
* `status.beat_seq` is cumulative since Audio Start — used only for flash / sticky idle
* after sequence ends. Preset and sequence loop counts come from `manual_beat_stride` /
* `sequence` on each poll.
*/
const beatSeq = Number(status.beat_seq || 0);
const endedSeq = prevZoneSequencePlaybackActive && !zoneSeqActive;
const startedSeq = !prevZoneSequencePlaybackActive && zoneSeqActive;
prevZoneSequencePlaybackActive = zoneSeqActive;
if (startedSeq) {
headerBeatStickyIdleAfterSeq = false;
lastLoggedSequenceBeatFractions = "";
}
if (endedSeq) {
headerBeatStickyIdleAfterSeq = true;
clearBeatPhaseTimers();
lastBeatSeq = beatSeq;
}
if (!zoneSeqActive && headerBeatStickyIdleAfterSeq) {
if (beatSeq > lastBeatSeq) {
lastBeatSeq = beatSeq;
logServerBeatConsoleOnPollEdge(status);
scheduleBeatPhaseFire(beatSeq, getBeatPhaseDelayMs());
headerBeatStickyIdleAfterSeq = false;
}
} else if (beatSeq > lastBeatSeq) {
lastBeatSeq = beatSeq;
logServerBeatConsoleOnPollEdge(status);
scheduleBeatPhaseFire(beatSeq, getBeatPhaseDelayMs());
}
const beatFractions = formatSequenceBeatFractionsForLog(status);
if (beatFractions) {
if (beatFractions !== lastLoggedSequenceBeatFractions) {
lastLoggedSequenceBeatFractions = beatFractions;
}
} else {
lastLoggedSequenceBeatFractions = "";
}
updateBeatReadoutDisplays(status);
} catch (e) {
console.warn("audio status poll failed", e);
}
}
async function startAudio() {
await stopAudioOnly();
const override = (el("audio-device-override")?.value || "").trim();
const selected = el("audio-device-select")?.value || "";
const rawDevice = override !== "" ? override : selected;
const numeric = rawDevice !== "" && /^-?\d+$/.test(rawDevice) ? Number(rawDevice) : rawDevice;
const body = {
device: rawDevice === "" ? null : numeric,
device_override: override,
device_select: selected,
};
const res = await fetch("/api/audio/start", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data.error || "Failed to start audio detector");
}
updateBpmDisplay(null);
updateHitTypeDisplay("unknown", NaN);
pollTimer = setInterval(pollStatus, 250);
await pollStatus();
}
async function refreshDevices() {
const select = el("audio-device-select");
const debug = el("audio-devices-debug");
if (!select) return;
const current = select.value;
const res = await fetch("/api/audio/devices");
const data = await res.json();
const inputs = Array.isArray(data?.devices) ? data.devices.slice() : [];
if (debug) {
debug.value = JSON.stringify(data?.diagnostics || data, null, 2);
}
inputs.sort((a, b) => {
const am = String(a?.name || "").toLowerCase().includes("monitor");
const bm = String(b?.name || "").toLowerCase().includes("monitor");
if (am !== bm) return am ? -1 : 1;
return Number(a?.id || 0) - Number(b?.id || 0);
});
select.innerHTML = '<option value="">System default input</option>';
let defaultId = "";
inputs.forEach((d, idx) => {
const option = document.createElement("option");
option.value = String(d.id);
option.textContent = d.label || d.name || `Input ${idx + 1}`;
if (d.is_default) {
defaultId = String(d.id);
}
select.appendChild(option);
});
if (current) {
select.value = current;
} else if (defaultId) {
select.value = defaultId;
}
}
function bind() {
const modal = el("audio-modal");
const openBtn = el("audio-btn");
const closeBtn = el("audio-close-btn");
const startBtn = el("audio-start-btn");
const stopBtn = el("audio-stop-btn");
const navResetBtn = el("audio-nav-reset-btn");
const refreshBtn = el("audio-refresh-btn");
if (!modal || !openBtn) return;
openBtn.addEventListener("click", async () => {
modal.classList.add("active");
try {
await refreshDevices();
} catch (e) {
console.warn("audio device refresh failed", e);
}
});
if (closeBtn) {
closeBtn.addEventListener("click", () => {
modal.classList.remove("active");
});
}
if (startBtn) {
startBtn.addEventListener("click", async () => {
try {
await startAudio();
await refreshDevices();
} catch (e) {
console.error("audio start failed", e);
alert("Failed to start audio input. Check mic permissions.");
}
});
}
if (stopBtn) {
stopBtn.addEventListener("click", async () => {
await stopAudio();
});
}
if (navResetBtn) {
navResetBtn.addEventListener("click", () => resetAudioTracking());
}
if (refreshBtn) {
refreshBtn.addEventListener("click", async () => {
try {
await refreshDevices();
} catch (e) {
console.error("refresh devices failed", e);
}
});
}
const phaseInp = el("audio-beat-phase-ms");
if (phaseInp) {
phaseInp.addEventListener("change", () => {
void persistBeatPhaseMs();
});
phaseInp.addEventListener("input", () => {
void persistBeatPhaseMs();
});
}
const bindSync = (node, mode) => {
if (!node) return;
node.addEventListener("click", async () => {
try {
await syncSequenceBeatPhase(mode);
} catch (e) {
console.warn("sequence beat sync failed", e);
}
});
};
bindSync(el("audio-top-beat-sync"), "step");
bindSync(el("audio-modal-beat-readout"), "step");
bindSync(el("audio-sync-pass-btn"), "pass");
document.addEventListener("keydown", (ev) => {
if (ev.defaultPrevented || ev.repeat || isTypingTarget(ev.target)) return;
const k = String(ev.key || "").toLowerCase();
if (k !== "s") return;
ev.preventDefault();
const mode = ev.shiftKey ? "pass" : "step";
void syncSequenceBeatPhase(mode).catch((e) => console.warn("sequence beat sync failed", e));
});
}
async function resumePollingIfDetectorRunning() {
try {
const res = await fetch("/api/audio/status", { cache: "no-store" });
const data = await res.json();
const status = data?.status || {};
if (status.running && !pollTimer) {
pollTimer = setInterval(pollStatus, 250);
lastBeatSeq = Number(status.beat_seq || 0);
prevZoneSequencePlaybackActive = sequencePlaybackActiveFromStatus(status);
await pollStatus();
}
} catch (e) {
console.warn("audio resume poll check failed", e);
}
}
/** Apply server-owned audio UI fields from status (device form, beat phase delay). */
function applyServerAudioUiFields(status) {
if (!status || typeof status !== "object") return;
const run = status.audio_run;
if (run && typeof run === "object") {
const ov = el("audio-device-override");
const sel = el("audio-device-select");
if (ov && run.device_override != null) ov.value = String(run.device_override);
if (sel && run.device_select) sel.value = String(run.device_select);
}
const phaseInp = el("audio-beat-phase-ms");
if (
phaseInp &&
status.beat_phase_ms != null &&
document.activeElement !== phaseInp
) {
const ms = parseInt(String(status.beat_phase_ms), 10);
if (Number.isFinite(ms)) {
phaseInp.value = String(Math.min(500, Math.max(0, ms)));
}
}
}
async function loadServerAudioUiFields() {
try {
await refreshDevices();
} catch (e) {
console.warn("audio device list refresh failed", e);
}
try {
const res = await fetch("/api/audio/status", { cache: "no-store" });
const data = await res.json();
applyServerAudioUiFields(data?.status || {});
} catch (e) {
console.warn("audio status load failed", e);
}
}
/** Called from sequences.js when server playback starts/stops without audio polling. */
window.ledControllerSequencePlaybackChanged = (active) => {
updateSequenceSyncControls(!!active);
if (active) {
setTopBpmVisible(true);
return;
}
if (!pollTimer) {
setTopBpmVisible(false);
updateSequenceSyncControls(false);
}
};
document.addEventListener("DOMContentLoaded", async () => {
bind();
await loadServerAudioUiFields();
await resumePollingIfDetectorRunning();
});
})();
-48
View File
@@ -1,48 +0,0 @@
/** Download/upload JSON bundles for profile, preset, and sequence import/export. */
window.downloadJsonFile = function downloadJsonFile(filename, data) {
const text = typeof data === 'string' ? data : JSON.stringify(data, null, 2);
const blob = new Blob([text], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename || 'bundle.json';
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
};
window.pickJsonFile = function pickJsonFile() {
return new Promise((resolve) => {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'application/json,.json';
input.style.display = 'none';
document.body.appendChild(input);
input.addEventListener('change', () => {
const file = input.files && input.files[0];
input.remove();
if (!file) {
resolve(null);
return;
}
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => resolve(null);
reader.readAsText(file);
});
input.click();
});
};
window.parseJsonFileText = function parseJsonFileText(text) {
if (text == null || text === '') {
return null;
}
try {
return JSON.parse(text);
} catch (e) {
return null;
}
};
-25
View File
@@ -1,25 +0,0 @@
/* Polls server build id; full reload when watchfiles restarts Python (new process = new id). */
(function () {
var prev = null;
function tick() {
fetch('/__dev/build-id', { cache: 'no-store', credentials: 'same-origin' })
.then(function (r) {
return r.ok ? r.text() : '';
})
.then(function (id) {
id = (id || '').trim();
if (!id) return;
if (prev === null) {
prev = id;
return;
}
if (id !== prev) {
prev = id;
window.location.reload();
}
})
.catch(function () {});
}
setInterval(tick, 750);
tick();
})();
+18 -232
View File
@@ -149,10 +149,8 @@ function applyTransportVisibility(transport) {
const isWifi = transport === 'wifi';
const esp = document.getElementById('edit-device-address-espnow');
const wifiWrap = document.getElementById('edit-device-address-wifi-wrap');
const drvWrap = document.getElementById('edit-device-wifi-driver-wrap');
if (esp) esp.hidden = isWifi;
if (wifiWrap) wifiWrap.hidden = !isWifi;
if (drvWrap) drvWrap.hidden = !isWifi;
}
function getAddressForPayload(transport) {
@@ -168,63 +166,6 @@ function getAddressForPayload(transport) {
return hex || null;
}
function collectDeviceEditPayload() {
const idInput = document.getElementById('edit-device-id');
const nameInput = document.getElementById('edit-device-name');
const typeSel = document.getElementById('edit-device-type');
const transportSel = document.getElementById('edit-device-transport');
const devId = idInput && idInput.value;
const transport = (transportSel && transportSel.value) || 'espnow';
const address = getAddressForPayload(transport);
const obr = document.getElementById('edit-device-output-brightness');
let output_brightness = 255;
if (obr && obr.value !== '') {
const n = parseInt(obr.value, 10);
output_brightness = !Number.isNaN(n) ? Math.max(0, Math.min(255, n)) : 255;
}
const payload = {
name: nameInput ? nameInput.value.trim() : '',
type: (typeSel && typeSel.value) || 'led',
transport,
address,
output_brightness,
};
if (transport === 'wifi') {
const dn = document.getElementById('edit-device-wifi-driver-name');
const nl = document.getElementById('edit-device-wifi-num-leds');
const co = document.getElementById('edit-device-wifi-color-order');
const ws = document.getElementById('edit-device-wifi-startup-mode');
if (dn && dn.value.trim()) payload.wifi_driver_display_name = dn.value.trim();
if (nl && nl.value !== '') {
const n = parseInt(nl.value, 10);
if (!Number.isNaN(n) && n >= 1) payload.wifi_driver_num_leds = n;
}
if (co && co.value) payload.wifi_color_order = co.value;
if (ws && ws.value) payload.wifi_startup_mode = ws.value;
}
return { devId, payload };
}
function refreshEditDeviceDebug() {
const ta = document.getElementById('edit-device-debug');
if (!ta) return;
try {
const { devId, payload } = collectDeviceEditPayload();
const loaded = window.__editDeviceLoadedSnapshot;
ta.value = JSON.stringify(
{
device_id: devId || null,
loaded_from_server: loaded != null ? loaded : null,
save_payload_preview: payload,
},
null,
2,
);
} catch (e) {
ta.value = String(e);
}
}
async function loadDevicesModal() {
const container = document.getElementById('devices-list-modal');
if (!container) return;
@@ -366,11 +307,6 @@ function renderDevicesList(devices) {
}
function openEditDeviceModal(devId, dev) {
try {
window.__editDeviceLoadedSnapshot = dev ? JSON.parse(JSON.stringify(dev)) : null;
} catch (e) {
window.__editDeviceLoadedSnapshot = dev || null;
}
const modal = document.getElementById('edit-device-modal');
const idInput = document.getElementById('edit-device-id');
const storageLabel = document.getElementById('edit-device-storage-id');
@@ -389,83 +325,20 @@ function openEditDeviceModal(devId, dev) {
applyTransportVisibility(tr);
setAddressToBoxes(addressBoxes, tr === 'espnow' ? ((dev && dev.address) || '') : '');
if (wifiInput) wifiInput.value = tr === 'wifi' ? ((dev && dev.address) || '') : '';
const wName = document.getElementById('edit-device-wifi-driver-name');
const wLeds = document.getElementById('edit-device-wifi-num-leds');
const wCo = document.getElementById('edit-device-wifi-color-order');
const wStart = document.getElementById('edit-device-wifi-startup-mode');
if (wName) {
const savedDisp =
dev && Object.prototype.hasOwnProperty.call(dev, 'wifi_driver_display_name')
? dev.wifi_driver_display_name
: undefined;
if (savedDisp != null && String(savedDisp).trim() !== '') {
wName.value = String(savedDisp).trim();
} else {
wName.value = dev && dev.name ? String(dev.name) : '';
}
}
if (wLeds) {
wLeds.value =
dev && dev.wifi_driver_num_leds != null && dev.wifi_driver_num_leds !== ''
? String(dev.wifi_driver_num_leds)
: '';
}
if (wCo) {
const co = (dev && dev.wifi_color_order) || 'rgb';
wCo.value = ['rgb', 'rbg', 'grb', 'gbr', 'brg', 'bgr'].includes(String(co).toLowerCase())
? String(co).toLowerCase()
: 'rgb';
}
if (wStart) {
const sm = (dev && dev.wifi_startup_mode) || 'default';
wStart.value = ['default', 'last', 'off'].includes(String(sm).toLowerCase())
? String(sm).toLowerCase()
: 'default';
}
const obr = document.getElementById('edit-device-output-brightness');
const obv = document.getElementById('edit-device-output-brightness-value');
if (obr) {
let bv = 255;
if (dev && dev.output_brightness != null && dev.output_brightness !== '') {
const n = parseInt(String(dev.output_brightness), 10);
if (!Number.isNaN(n)) bv = Math.max(0, Math.min(255, n));
}
obr.value = String(bv);
if (obv) obv.textContent = String(bv);
}
refreshEditDeviceDebug();
modal.classList.add('active');
}
async function updateDevice(devId, name, type, transport, address, wifiDriverFields, outputBrightness) {
async function updateDevice(devId, name, type, transport, address) {
try {
const payload = {
name,
type: type || 'led',
transport: transport || 'espnow',
address,
};
if (typeof outputBrightness === 'number') {
payload.output_brightness = Math.max(0, Math.min(255, Math.round(outputBrightness)));
}
if (transport === 'wifi' && wifiDriverFields && typeof wifiDriverFields === 'object') {
if (wifiDriverFields.wifi_driver_display_name != null) {
payload.wifi_driver_display_name = wifiDriverFields.wifi_driver_display_name;
}
if (wifiDriverFields.wifi_driver_num_leds != null) {
payload.wifi_driver_num_leds = wifiDriverFields.wifi_driver_num_leds;
}
if (wifiDriverFields.wifi_color_order != null) {
payload.wifi_color_order = wifiDriverFields.wifi_color_order;
}
if (wifiDriverFields.wifi_startup_mode != null) {
payload.wifi_startup_mode = wifiDriverFields.wifi_startup_mode;
}
}
const res = await fetch(`/devices/${encodeURIComponent(devId)}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
body: JSON.stringify({
name,
type: type || 'led',
transport: transport || 'espnow',
address,
}),
});
const data = await res.json().catch(() => ({}));
if (res.ok) {
@@ -481,41 +354,6 @@ async function updateDevice(devId, name, type, transport, address, wifiDriverFie
}
}
async function pushWifiDriverConfig(devId, fields) {
const push = {};
if (fields.name != null && String(fields.name).trim()) push.name = String(fields.name).trim();
if (fields.num_leds != null && fields.num_leds !== '') {
const n = parseInt(String(fields.num_leds), 10);
if (!Number.isNaN(n) && n >= 1) push.num_leds = n;
}
if (fields.color_order != null && String(fields.color_order).trim()) {
push.color_order = String(fields.color_order).trim().toLowerCase();
}
if (fields.startup_mode != null && String(fields.startup_mode).trim()) {
const sm = String(fields.startup_mode).trim().toLowerCase();
if (sm === 'default' || sm === 'last' || sm === 'off') push.startup_mode = sm;
}
if (Object.keys(push).length === 0) return { ok: true, skipped: true };
try {
const res = await fetch(`/devices/${encodeURIComponent(devId)}/driver-config`, {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify(push),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
alert(data.error || 'Could not send settings to the driver (is it connected?)');
return { ok: false };
}
return { ok: true };
} catch (e) {
console.error('pushWifiDriverConfig:', e);
alert('Could not send settings to the driver');
return { ok: false };
}
}
document.addEventListener('DOMContentLoaded', () => {
window.addEventListener('deviceTcpStatus', (ev) => {
const { ip, connected } = ev.detail || {};
@@ -542,19 +380,10 @@ document.addEventListener('DOMContentLoaded', () => {
makeHexAddressBoxes(document.getElementById('edit-device-address-boxes'));
const devOutBr = document.getElementById('edit-device-output-brightness');
const devOutBrVal = document.getElementById('edit-device-output-brightness-value');
if (devOutBr && devOutBrVal) {
devOutBr.addEventListener('input', () => {
devOutBrVal.textContent = devOutBr.value;
});
}
const transportEdit = document.getElementById('edit-device-transport');
if (transportEdit) {
transportEdit.addEventListener('change', () => {
applyTransportVisibility(transportEdit.value);
refreshEditDeviceDebug();
});
}
@@ -591,67 +420,24 @@ document.addEventListener('DOMContentLoaded', () => {
}
if (editForm) {
editForm.addEventListener('input', () => refreshEditDeviceDebug());
editForm.addEventListener('change', () => refreshEditDeviceDebug());
editForm.addEventListener('submit', async (e) => {
e.preventDefault();
const { devId, payload } = collectDeviceEditPayload();
const idInput = document.getElementById('edit-device-id');
const nameInput = document.getElementById('edit-device-name');
const typeSel = document.getElementById('edit-device-type');
const transportSel = document.getElementById('edit-device-transport');
const devId = idInput && idInput.value;
if (!devId) return;
const transport = payload.transport || 'espnow';
let wifiDriverFields = null;
if (transport === 'wifi') {
wifiDriverFields = {};
if (payload.wifi_driver_display_name != null) {
wifiDriverFields.wifi_driver_display_name = payload.wifi_driver_display_name;
}
if (payload.wifi_driver_num_leds != null) {
wifiDriverFields.wifi_driver_num_leds = payload.wifi_driver_num_leds;
}
if (payload.wifi_color_order != null) {
wifiDriverFields.wifi_color_order = payload.wifi_color_order;
}
if (payload.wifi_startup_mode != null) {
wifiDriverFields.wifi_startup_mode = payload.wifi_startup_mode;
}
}
const transport = (transportSel && transportSel.value) || 'espnow';
const address = getAddressForPayload(transport);
const ok = await updateDevice(
devId,
payload.name,
payload.type,
nameInput ? nameInput.value.trim() : '',
(typeSel && typeSel.value) || 'led',
transport,
payload.address,
wifiDriverFields,
payload.output_brightness,
address
);
if (!ok) return;
try {
const brRes = await fetch(`/devices/${encodeURIComponent(devId)}/brightness`, {
method: 'POST',
credentials: 'same-origin',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({}),
});
if (!brRes.ok && brRes.status !== 503) {
const brData = await brRes.json().catch(() => ({}));
console.warn('brightness push:', brData.error || brRes.status);
}
} catch (e) {
console.warn('brightness push failed', e);
}
if (transport === 'wifi' && wifiDriverFields) {
const dn = document.getElementById('edit-device-wifi-driver-name');
const nl = document.getElementById('edit-device-wifi-num-leds');
const co = document.getElementById('edit-device-wifi-color-order');
const ws = document.getElementById('edit-device-wifi-startup-mode');
const pushRes = await pushWifiDriverConfig(devId, {
name: dn ? dn.value : '',
num_leds: nl ? nl.value : '',
color_order: co ? co.value : '',
startup_mode: ws ? ws.value : '',
});
if (!pushRes.ok) return;
}
editDeviceModal.classList.remove('active');
if (ok) editDeviceModal.classList.remove('active');
});
}
if (editCloseBtn) {
-571
View File
@@ -1,571 +0,0 @@
// Device groups: members (MAC ids) + Wi‑Fi driver defaults; persisted via /groups.
// Without ``profile_id``, a group is shared across all profiles; with ``profile_id`` it is listed only for that profile.
async function getCurrentProfileIdForGroups() {
try {
const res = await fetch('/profiles/current', {
headers: { Accept: 'application/json' },
credentials: 'same-origin',
});
if (!res.ok) return null;
const data = await res.json();
const id = data && (data.id || (data.profile && data.profile.id));
return id != null ? String(id) : null;
} catch {
return null;
}
}
async function fetchGroupsMap() {
try {
const response = await fetch('/groups', {
headers: { Accept: 'application/json' },
credentials: 'same-origin',
});
if (!response.ok) return {};
const data = await response.json();
return data && typeof data === 'object' ? data : {};
} catch (e) {
console.error('fetchGroupsMap:', e);
return {};
}
}
async function fetchDevicesMapForGroups() {
try {
const response = await fetch('/devices', { headers: { Accept: 'application/json' } });
if (!response.ok) return {};
const data = await response.json();
return data && typeof data === 'object' ? data : {};
} catch (e) {
console.error('fetchDevicesMapForGroups:', e);
return {};
}
}
function renderGroupDevicesEditor(containerEl, macRows, devicesMap) {
if (!containerEl) return;
containerEl.innerHTML = '';
const entries = Object.entries(devicesMap || {}).sort(([a], [b]) => a.localeCompare(b));
macRows.forEach((row, idx) => {
const div = document.createElement('div');
div.className = 'zone-device-row profiles-row';
const label = document.createElement('span');
label.className = 'zone-device-row-label';
const strong = document.createElement('strong');
strong.textContent = row.label || row.mac || '—';
label.appendChild(strong);
label.appendChild(document.createTextNode(' '));
const sub = document.createElement('span');
sub.className = 'muted-text';
sub.textContent = row.mac || '';
label.appendChild(sub);
const rm = document.createElement('button');
rm.type = 'button';
rm.className = 'btn btn-danger btn-small';
rm.textContent = 'Remove';
rm.addEventListener('click', () => {
macRows.splice(idx, 1);
renderGroupDevicesEditor(containerEl, macRows, devicesMap);
});
div.appendChild(label);
div.appendChild(rm);
containerEl.appendChild(div);
});
const macsInRows = new Set(macRows.map((r) => r.mac).filter(Boolean));
const addWrap = document.createElement('div');
addWrap.className = 'zone-devices-add profiles-actions';
const sel = document.createElement('select');
sel.className = 'zone-device-add-select';
sel.appendChild(new Option('Add device…', ''));
entries.forEach(([mac, d]) => {
if (macsInRows.has(mac)) return;
const labelName = d && d.name ? String(d.name).trim() : '';
const optLabel = labelName ? `${labelName} — ${mac}` : mac;
sel.appendChild(new Option(optLabel, mac));
});
const addBtn = document.createElement('button');
addBtn.type = 'button';
addBtn.className = 'btn btn-primary btn-small';
addBtn.textContent = 'Add';
addBtn.addEventListener('click', () => {
const mac = sel.value;
if (!mac || !devicesMap[mac]) return;
const n = String((devicesMap[mac].name || '').trim() || mac);
macRows.push({ mac, label: n });
sel.value = '';
renderGroupDevicesEditor(containerEl, macRows, devicesMap);
});
addWrap.appendChild(sel);
addWrap.appendChild(addBtn);
containerEl.appendChild(addWrap);
refreshEditGroupDebug();
}
function collectGroupEditPayload() {
const idInput = document.getElementById('edit-group-id');
const nameInput = document.getElementById('edit-group-name');
const gid = idInput && idInput.value;
const rows = window.__editGroupDeviceRows || [];
const devices = rows.map((r) => r.mac).filter(Boolean);
const payload = {
name: nameInput ? nameInput.value.trim() : '',
devices,
};
const dn = document.getElementById('edit-group-wifi-driver-name');
const nl = document.getElementById('edit-group-wifi-num-leds');
const co = document.getElementById('edit-group-wifi-color-order');
const ws = document.getElementById('edit-group-wifi-startup-mode');
if (dn && dn.value.trim()) payload.wifi_driver_display_name = dn.value.trim();
else payload.wifi_driver_display_name = null;
if (nl && nl.value !== '') {
const n = parseInt(nl.value, 10);
if (!Number.isNaN(n) && n >= 1) payload.wifi_driver_num_leds = n;
else payload.wifi_driver_num_leds = null;
} else payload.wifi_driver_num_leds = null;
if (co && co.value) payload.wifi_color_order = co.value;
if (ws && ws.value) payload.wifi_startup_mode = ws.value;
const gob = document.getElementById('edit-group-output-brightness');
if (gob && gob.value !== '') {
const nb = parseInt(gob.value, 10);
if (!Number.isNaN(nb)) payload.output_brightness = Math.max(0, Math.min(255, nb));
}
return { gid, payload };
}
function refreshEditGroupDebug() {
const ta = document.getElementById('edit-group-debug');
if (!ta) return;
try {
const { gid, payload } = collectGroupEditPayload();
const loaded = window.__editGroupLoadedSnapshot;
ta.value = JSON.stringify(
{
group_id: gid || null,
loaded_from_server: loaded != null ? loaded : null,
save_payload_preview: payload,
},
null,
2,
);
} catch (e) {
ta.value = String(e);
}
}
function syncGroupShareCheckboxFromDoc(g) {
const cb = document.getElementById('edit-group-share-all-profiles');
if (!cb) return;
const raw = g && (g.profile_id != null ? g.profile_id : g.profileId);
const scoped = raw != null && String(raw).trim() !== '';
cb.checked = !scoped;
}
function loadWifiFieldsFromGroup(g) {
const wName = document.getElementById('edit-group-wifi-driver-name');
const wLeds = document.getElementById('edit-group-wifi-num-leds');
const wCo = document.getElementById('edit-group-wifi-color-order');
const wStart = document.getElementById('edit-group-wifi-startup-mode');
if (wName) {
const v = g && Object.prototype.hasOwnProperty.call(g, 'wifi_driver_display_name')
? g.wifi_driver_display_name
: null;
wName.value = v != null && String(v).trim() !== '' ? String(v).trim() : '';
}
if (wLeds) {
const v = g && g.wifi_driver_num_leds;
wLeds.value =
v != null && v !== '' && String(v).trim() !== ''
? String(v)
: '';
}
if (wCo) {
const co = (g && g.wifi_color_order) || 'rgb';
wCo.value = ['rgb', 'rbg', 'grb', 'gbr', 'brg', 'bgr'].includes(String(co).toLowerCase())
? String(co).toLowerCase()
: 'rgb';
}
if (wStart) {
const sm = (g && g.wifi_startup_mode) || 'default';
wStart.value = ['default', 'last', 'off'].includes(String(sm).toLowerCase())
? String(sm).toLowerCase()
: 'default';
}
const gob = document.getElementById('edit-group-output-brightness');
const gobv = document.getElementById('edit-group-output-brightness-value');
if (gob) {
let bv = 255;
if (g && g.output_brightness != null && g.output_brightness !== '') {
const n = parseInt(String(g.output_brightness), 10);
if (!Number.isNaN(n)) bv = Math.max(0, Math.min(255, n));
}
gob.value = String(bv);
if (gobv) gobv.textContent = String(bv);
}
}
async function openEditGroupModal(groupId, groupDoc) {
const modal = document.getElementById('edit-group-modal');
const idInput = document.getElementById('edit-group-id');
const nameInput = document.getElementById('edit-group-name');
const editor = document.getElementById('edit-group-devices-editor');
let g = groupDoc;
if (!g || typeof g !== 'object') {
try {
const response = await fetch(`/groups/${encodeURIComponent(groupId)}`, {
credentials: 'same-origin',
headers: { Accept: 'application/json' },
});
if (response.ok) g = await response.json();
} catch (e) {
console.error(e);
}
}
g = g || {};
try {
window.__editGroupLoadedSnapshot = JSON.parse(JSON.stringify(g));
} catch (e) {
window.__editGroupLoadedSnapshot = g;
}
if (idInput) idInput.value = groupId;
if (nameInput) nameInput.value = g.name || '';
const dm = await fetchDevicesMapForGroups();
const macs = Array.isArray(g.devices) ? g.devices : [];
window.__editGroupDeviceRows = macs.map((m) => {
const mac = String(m).trim().toLowerCase().replace(/:/g, '').replace(/-/g, '');
const d = dm[mac];
return {
mac,
label: d && d.name ? String(d.name).trim() : mac,
};
});
renderGroupDevicesEditor(editor, window.__editGroupDeviceRows, dm);
loadWifiFieldsFromGroup(g);
syncGroupShareCheckboxFromDoc(g);
refreshEditGroupDebug();
if (modal) modal.classList.add('active');
}
async function loadGroupsModal() {
const container = document.getElementById('groups-list-modal');
if (!container) return;
container.innerHTML = '<span class="muted-text">Loading...</span>';
try {
const data = await fetchGroupsMap();
renderGroupsList(data || {});
} catch (e) {
console.error('loadGroupsModal:', e);
container.innerHTML = '<span class="muted-text">Failed to load groups.</span>';
}
}
function renderGroupsList(groups) {
const container = document.getElementById('groups-list-modal');
if (!container) return;
container.innerHTML = '';
const ids = Object.keys(groups).filter((k) => groups[k] && typeof groups[k] === 'object');
if (ids.length === 0) {
const p = document.createElement('p');
p.className = 'muted-text';
p.textContent = 'No groups yet. Create one to assign devices and Wi‑Fi defaults.';
container.appendChild(p);
return;
}
ids.sort((a, b) => parseInt(a, 10) - parseInt(b, 10));
ids.forEach((gid) => {
const g = groups[gid];
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');
const devs = Array.isArray(g.devices) ? g.devices : [];
label.textContent = `${g.name || gid} (${devs.length} device${devs.length === 1 ? '' : 's'})`;
const meta = document.createElement('div');
meta.className = 'muted-text';
meta.style.fontSize = '0.8em';
const rawPid = g.profile_id != null ? g.profile_id : g.profileId;
const scoped = rawPid != null && String(rawPid).trim() !== '';
meta.textContent = scoped ? `This profile only (${rawPid})` : 'Shared across profiles';
const editBtn = document.createElement('button');
editBtn.className = 'btn btn-secondary btn-small';
editBtn.textContent = 'Edit';
editBtn.addEventListener('click', () => openEditGroupModal(gid, g));
const brightBtn = document.createElement('button');
brightBtn.className = 'btn btn-secondary btn-small';
brightBtn.type = 'button';
brightBtn.textContent = 'Apply brightness';
brightBtn.title = 'Push group output brightness to Wi‑Fi drivers in this group';
brightBtn.addEventListener('click', async () => {
try {
const res = await fetch(`/groups/${encodeURIComponent(gid)}/brightness`, {
method: 'POST',
credentials: 'same-origin',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({}),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
alert(data.error || 'Apply brightness failed');
return;
}
const n = typeof data.sent === 'number' ? data.sent : 0;
alert(
n
? `Sent brightness to ${n} driver(s).`
: 'No Wi‑Fi drivers received brightness (check connections).',
);
} catch (err) {
console.error(err);
alert('Apply brightness failed');
}
});
const applyBtn = document.createElement('button');
applyBtn.className = 'btn btn-primary btn-small';
applyBtn.type = 'button';
applyBtn.textContent = 'Apply defaults to drivers';
applyBtn.title = 'Push Wi‑Fi defaults to each connected driver in this group';
applyBtn.addEventListener('click', async () => {
try {
const res = await fetch(`/groups/${encodeURIComponent(gid)}/driver-config`, {
method: 'POST',
credentials: 'same-origin',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({}),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
alert(data.error || 'Apply failed');
return;
}
const n = typeof data.sent === 'number' ? data.sent : 0;
alert(
n
? `Sent defaults to ${n} driver(s).`
: 'No Wi‑Fi drivers received the config (check defaults and connections).',
);
} catch (err) {
console.error(err);
alert('Apply failed');
}
});
const identifyBtn = document.createElement('button');
identifyBtn.className = 'btn btn-secondary btn-small';
identifyBtn.type = 'button';
identifyBtn.textContent = 'Identify';
identifyBtn.title =
'Identify all devices in this group at once (red blink at 10 Hz)';
identifyBtn.addEventListener('click', async () => {
await identifyGroupById(gid);
});
const delBtn = document.createElement('button');
delBtn.className = 'btn btn-danger btn-small';
delBtn.textContent = 'Delete';
delBtn.addEventListener('click', async () => {
if (!confirm(`Delete group "${g.name || gid}"? Zones referencing it may need updating.`)) return;
try {
const res = await fetch(`/groups/${encodeURIComponent(gid)}`, {
method: 'DELETE',
credentials: 'same-origin',
});
if (res.ok) await loadGroupsModal();
else {
const data = await res.json().catch(() => ({}));
alert(data.error || 'Delete failed');
}
} catch (err) {
console.error(err);
alert('Delete failed');
}
});
const left = document.createElement('div');
left.style.flex = '1';
left.style.minWidth = '0';
left.appendChild(label);
left.appendChild(meta);
row.appendChild(left);
row.appendChild(editBtn);
row.appendChild(brightBtn);
row.appendChild(applyBtn);
row.appendChild(identifyBtn);
row.appendChild(delBtn);
container.appendChild(row);
});
}
async function identifyGroupById(gid) {
if (!gid) return;
try {
const res = await fetch(`/groups/${encodeURIComponent(gid)}/identify`, {
method: 'POST',
credentials: 'same-origin',
headers: { Accept: 'application/json' },
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
alert(data.error || 'Identify failed');
return;
}
const n = typeof data.sent === 'number' ? data.sent : 0;
const errs = Array.isArray(data.errors) ? data.errors : [];
const failed = errs.filter((e) => e && e.error).length;
let msg = n ? `Identify sent to ${n} device(s).` : 'No devices received identify.';
if (failed) {
msg += ` ${failed} failed — see console for details.`;
console.warn('Group identify errors', errs);
}
alert(msg);
} catch (e) {
console.error(e);
alert('Identify failed');
}
}
document.addEventListener('DOMContentLoaded', () => {
const groupsBtn = document.getElementById('groups-btn');
const groupsModal = document.getElementById('groups-modal');
const groupsCloseBtn = document.getElementById('groups-close-btn');
const newNameInput = document.getElementById('new-group-name');
const createBtn = document.getElementById('create-group-btn');
const editForm = document.getElementById('edit-group-form');
const editCloseBtn = document.getElementById('edit-group-close-btn');
const editModal = document.getElementById('edit-group-modal');
if (groupsBtn && groupsModal) {
groupsBtn.addEventListener('click', () => {
groupsModal.classList.add('active');
loadGroupsModal();
});
}
if (groupsCloseBtn && groupsModal) {
groupsCloseBtn.addEventListener('click', () => groupsModal.classList.remove('active'));
}
const grpOutBr = document.getElementById('edit-group-output-brightness');
const grpOutBrVal = document.getElementById('edit-group-output-brightness-value');
if (grpOutBr && grpOutBrVal) {
grpOutBr.addEventListener('input', () => {
grpOutBrVal.textContent = grpOutBr.value;
});
}
const editIdentifyBtn = document.getElementById('edit-group-identify-btn');
if (editIdentifyBtn) {
editIdentifyBtn.addEventListener('click', async () => {
const idInput = document.getElementById('edit-group-id');
const gid = idInput && idInput.value;
if (!gid) return;
await identifyGroupById(gid);
});
}
const createHandler = async () => {
const name = newNameInput && newNameInput.value.trim();
if (!name) return;
const profileOnly = document.getElementById('new-group-profile-only');
try {
const res = await fetch('/groups', {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({
name,
profile_scoped: !!(profileOnly && profileOnly.checked),
}),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
alert(data.error || 'Create failed');
return;
}
if (newNameInput) newNameInput.value = '';
if (profileOnly) profileOnly.checked = false;
await loadGroupsModal();
} catch (e) {
console.error(e);
alert('Create failed');
}
};
if (createBtn) createBtn.addEventListener('click', createHandler);
if (newNameInput) {
newNameInput.addEventListener('keypress', (ev) => {
if (ev.key === 'Enter') createHandler();
});
}
if (editForm) {
editForm.addEventListener('input', () => refreshEditGroupDebug());
editForm.addEventListener('change', () => refreshEditGroupDebug());
editForm.addEventListener('submit', async (e) => {
e.preventDefault();
const { gid, payload } = collectGroupEditPayload();
if (!gid) return;
const shareCb = document.getElementById('edit-group-share-all-profiles');
if (shareCb && shareCb.checked) {
payload.profile_id = null;
} else {
const pid = await getCurrentProfileIdForGroups();
payload.profile_id = pid || null;
}
try {
const res = await fetch(`/groups/${encodeURIComponent(gid)}`, {
method: 'PUT',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify(payload),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
alert(data.error || 'Save failed');
return;
}
try {
await fetch(`/groups/${encodeURIComponent(gid)}/brightness`, {
method: 'POST',
credentials: 'same-origin',
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify({}),
});
} catch (_) {
/* ignore push errors after save */
}
if (editModal) editModal.classList.remove('active');
await loadGroupsModal();
} catch (err) {
console.error(err);
alert('Save failed');
}
});
}
if (editCloseBtn && editModal) {
editCloseBtn.addEventListener('click', () => editModal.classList.remove('active'));
}
window.openDeviceGroupsModal = async () => {
const gm = document.getElementById('groups-modal');
if (!gm) return;
gm.classList.add('active');
try {
await loadGroupsModal();
} catch (e) {
console.error('openDeviceGroupsModal', e);
}
};
});
+1 -1
View File
@@ -131,7 +131,7 @@ document.addEventListener('DOMContentLoaded', () => {
return;
}
try {
const response = await fetch('/settings', {
const response = await fetch('/settings/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
-117
View File
@@ -1,117 +0,0 @@
/**
* Bluetooth / USB HID numpad shortcuts (browser focus required).
*
* Numpad1–9,0 → zone 1–10 (visible zone list order)
* NumpadEnter → sequence beat sync (step), same as S
* NumpadDecimal → sequence beat sync (pass), same as Shift+S
* NumpadMultiply → reset audio detector
* NumpadAdd → brightness +16
* NumpadSubtract → brightness −16
* NumpadDivide → stop zone sequence playback
*/
(() => {
const BRIGHTNESS_STEP = 16;
function isTypingTarget(target) {
if (!target || typeof target !== "object") return false;
const tag = String(target.tagName || "").toLowerCase();
return tag === "input" || tag === "textarea" || tag === "select" || target.isContentEditable;
}
function zoneIdsInListOrder() {
return [...document.querySelectorAll("#zones-list .zone-button[data-zone-id]")]
.map((el) => el.getAttribute("data-zone-id"))
.filter((id) => id != null && id !== "");
}
async function selectZoneByListIndex(oneBased) {
const order = zoneIdsInListOrder();
if (oneBased < 1 || oneBased > order.length) return;
const zoneId = order[oneBased - 1];
if (window.tabsManager && typeof window.tabsManager.selectZone === "function") {
await window.tabsManager.selectZone(zoneId);
} else if (typeof selectZone === "function") {
await selectZone(zoneId);
}
}
async function syncSequenceBeatPhase(mode) {
const res = await fetch("/sequences/sync-phase", {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ mode: mode || "step" }),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data.error || `Sync failed (${res.status})`);
}
}
async function resetAudioTracking() {
const res = await fetch("/api/audio/reset", {
method: "POST",
headers: { Accept: "application/json" },
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data.error || `Reset failed (${res.status})`);
}
}
function adjustZoneBrightness(delta) {
const zoneId =
(window.tabsManager && typeof window.tabsManager.getCurrentTabId === "function"
? window.tabsManager.getCurrentTabId()
: null) ||
(window.tabsManager && typeof window.tabsManager.getCurrentZoneId === "function"
? window.tabsManager.getCurrentZoneId()
: null);
if (!zoneId) return;
const slider =
document.getElementById("header-brightness-slider") ||
document.getElementById("menu-brightness-slider");
if (!slider) return;
const cur = parseInt(slider.value, 10);
const base = Number.isFinite(cur) ? cur : 127;
const next = Math.max(0, Math.min(255, base + delta));
if (String(slider.value) === String(next)) return;
slider.value = String(next);
slider.dispatchEvent(new Event("input", { bubbles: true }));
}
async function stopSequencePlayback() {
if (typeof window.stopZoneSequencePlayback === "function") {
await window.stopZoneSequencePlayback(true);
}
}
/** @type {Record<string, () => void | Promise<void>>} */
const actions = {
NumpadEnter: () => syncSequenceBeatPhase("step"),
NumpadDecimal: () => syncSequenceBeatPhase("pass"),
NumpadMultiply: () => resetAudioTracking(),
NumpadAdd: () => adjustZoneBrightness(BRIGHTNESS_STEP),
NumpadSubtract: () => adjustZoneBrightness(-BRIGHTNESS_STEP),
NumpadDivide: () => stopSequencePlayback(),
Numpad1: () => selectZoneByListIndex(1),
Numpad2: () => selectZoneByListIndex(2),
Numpad3: () => selectZoneByListIndex(3),
Numpad4: () => selectZoneByListIndex(4),
Numpad5: () => selectZoneByListIndex(5),
Numpad6: () => selectZoneByListIndex(6),
Numpad7: () => selectZoneByListIndex(7),
Numpad8: () => selectZoneByListIndex(8),
Numpad9: () => selectZoneByListIndex(9),
Numpad0: () => selectZoneByListIndex(10),
};
document.addEventListener("keydown", (ev) => {
if (ev.defaultPrevented || ev.repeat || isTypingTarget(ev.target)) return;
const code = ev.code;
if (!code || !code.startsWith("Numpad")) return;
const action = actions[code];
if (!action) return;
ev.preventDefault();
Promise.resolve(action()).catch((e) => console.warn("numpad shortcut failed:", e));
});
})();
+219
View File
@@ -0,0 +1,219 @@
// 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();
});
});
+2 -36
View File
@@ -33,33 +33,6 @@ document.addEventListener('DOMContentLoaded', () => {
return Number.isFinite(t) ? t : def;
};
const coercePresetAuto = (preset) => {
if (!preset || typeof preset !== 'object') {
return true;
}
const v =
preset.auto !== undefined && preset.auto !== null ? preset.auto : preset.a;
if (typeof v === 'boolean') {
return v;
}
if (v === 0 || v === '0') {
return false;
}
if (v === 1 || v === '1') {
return true;
}
if (typeof v === 'string') {
const l = v.trim().toLowerCase();
if (['false', '0', 'no', 'off'].includes(l)) {
return false;
}
if (['true', '1', 'yes', 'on'].includes(l)) {
return true;
}
}
return true;
};
const getCurrentProfileId = async () => {
try {
const response = await fetch('/profiles/current', { headers: { Accept: 'application/json' } });
@@ -558,7 +531,6 @@ document.addEventListener('DOMContentLoaded', () => {
const colors = Array.isArray(preset.colors) && preset.colors.length
? preset.colors
: ['#FFFFFF'];
const presetAuto = coercePresetAuto(preset);
wirePresets[presetId] = {
pattern: preset.pattern || 'off',
colors,
@@ -566,19 +538,13 @@ document.addEventListener('DOMContentLoaded', () => {
brightness: typeof preset.brightness === 'number'
? preset.brightness
: (typeof preset.br === 'number' ? preset.br : 127),
auto: presetAuto,
a: presetAuto,
auto: typeof preset.auto === 'boolean' ? preset.auto : true,
n1: coercePresetInt(preset.n1),
n2: coercePresetInt(preset.n2),
n3: coercePresetInt(preset.n3),
n4: coercePresetInt(preset.n4),
n5: coercePresetInt(preset.n5),
n6: (() => {
if (preset.mode !== undefined && preset.mode !== null && preset.mode !== '') {
return coercePresetInt(preset.mode);
}
return coercePresetInt(preset.n6);
})(),
n6: coercePresetInt(preset.n6),
};
});
if (!Object.keys(wirePresets).length) {
+105 -889
View File
File diff suppressed because it is too large. Load diff
-76
View File
@@ -6,7 +6,6 @@ document.addEventListener("DOMContentLoaded", () => {
const newProfileInput = document.getElementById("new-profile-name");
const newProfileSeedDjInput = document.getElementById("new-profile-seed-dj");
const createProfileButton = document.getElementById("create-profile-btn");
const importProfileButton = document.getElementById("import-profile-btn");
if (!profilesButton || !profilesModal || !profilesList) {
return;
@@ -102,26 +101,6 @@ document.addEventListener("DOMContentLoaded", () => {
}
});
const exportButton = document.createElement("button");
exportButton.className = "btn btn-secondary btn-small";
exportButton.textContent = "Export";
exportButton.addEventListener("click", async () => {
try {
const response = await fetch(`/profiles/${profileId}/export`, {
headers: { Accept: "application/json" },
});
if (!response.ok) {
throw new Error("Export failed");
}
const bundle = await response.json();
const safeName = ((profile && profile.name) || profileId).replace(/[^\w.-]+/g, "_");
window.downloadJsonFile(`profile-${safeName}.json`, bundle);
} catch (error) {
console.error("Export profile failed:", error);
alert("Failed to export profile.");
}
});
const cloneButton = document.createElement("button");
cloneButton.className = "btn btn-secondary btn-small";
cloneButton.textContent = "Clone";
@@ -198,7 +177,6 @@ document.addEventListener("DOMContentLoaded", () => {
row.appendChild(label);
row.appendChild(applyButton);
if (editMode) {
row.appendChild(exportButton);
row.appendChild(cloneButton);
row.appendChild(deleteButton);
}
@@ -298,60 +276,6 @@ document.addEventListener("DOMContentLoaded", () => {
if (createProfileButton) {
createProfileButton.addEventListener("click", createProfile);
}
const importProfile = async () => {
if (!isEditModeActive()) {
return;
}
const text = await window.pickJsonFile();
if (!text) {
return;
}
const bundle = window.parseJsonFileText(text);
if (!bundle || typeof bundle !== "object") {
alert("Invalid JSON file.");
return;
}
const defaultName =
(bundle.profile && bundle.profile.name) || "Imported profile";
const name = prompt("Profile name for import:", defaultName);
if (name === null) {
return;
}
const trimmed = String(name).trim();
if (!trimmed) {
alert("Profile name cannot be empty.");
return;
}
try {
const response = await fetch("/profiles/import", {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ bundle, name: trimmed, apply: true }),
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw new Error(err.error || "Import failed");
}
const data = await response.json();
const newProfileId = data.id || Object.keys(data).find((k) => k !== "id");
if (newProfileId) {
await fetch(`/profiles/${newProfileId}/apply`, {
method: "POST",
headers: { Accept: "application/json" },
});
}
await loadProfiles();
await refreshTabsForActiveProfile();
} catch (error) {
console.error("Import profile failed:", error);
alert(error.message || "Failed to import profile.");
}
};
if (importProfileButton) {
importProfileButton.addEventListener("click", importProfile);
}
if (newProfileInput) {
newProfileInput.addEventListener("keypress", (event) => {
if (event.key === "Enter") {
+258 -1263
View File
File diff suppressed because it is too large. Load diff
+89 -519
View File
@@ -94,11 +94,10 @@ header {
background-color: #1a1a1a;
padding: 0.75rem 1rem;
display: flex;
flex-direction: column;
align-items: stretch;
justify-content: flex-start;
justify-content: space-between;
align-items: center;
border-bottom: 2px solid #4a4a4a;
gap: 0.65rem;
gap: 0.75rem;
}
header h1 {
@@ -106,18 +105,6 @@ header h1 {
font-weight: 600;
}
/* Top header row: BPM, brightness, desktop buttons, mobile menu (above zone tabs) */
.header-end {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
justify-content: flex-end;
margin-left: 0;
width: 100%;
min-width: 0;
}
.header-actions {
display: flex;
gap: 0.5rem;
@@ -128,7 +115,6 @@ header h1 {
.header-menu-mobile {
display: none;
position: relative;
align-items: center;
}
.main-menu-dropdown {
@@ -197,134 +183,6 @@ header h1 {
width: 8.5rem;
}
.audio-top-indicator {
display: none;
align-items: center;
gap: 0.35rem;
min-width: 9rem;
}
.audio-top-indicator.audio-running {
display: inline-flex;
}
.audio-top-indicator .audio-top-beat-sync {
flex: 1;
min-width: 0;
}
.audio-top-beat-sync {
display: inline-flex;
align-items: center;
gap: 0.4rem;
width: 100%;
min-height: 2.25rem;
padding: 0.3rem 0.55rem;
border: 1px solid #4a4a4a;
border-radius: 6px;
background-color: #1a1a1a;
cursor: pointer;
font-family: inherit;
text-align: left;
}
.audio-top-beat-sync:disabled {
cursor: default;
opacity: 0.85;
}
.audio-top-beat-sync:not(:disabled):hover {
border-color: #6a6a6a;
background-color: #2a2a2a;
}
.audio-top-indicator-extra {
font-size: 0.62rem;
color: #9e9e9e;
line-height: 1.25;
text-align: right;
max-width: 16rem;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.audio-top-indicator-label {
font-size: 0.72rem;
color: #bdbdbd;
letter-spacing: 0.05em;
}
.audio-top-indicator-value {
font-size: 1rem;
font-weight: 700;
color: #ffd54f;
min-width: 2.4rem;
text-align: right;
}
.audio-top-beat-readout {
font-size: 0.75rem;
color: #b0bec5;
line-height: 1.25;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex: 1;
min-width: 2rem;
text-align: right;
}
.audio-top-beat-readout:empty {
display: none;
}
.audio-top-beat-readout:not(:empty)::before {
content: "·";
margin-right: 0.35rem;
color: #757575;
}
.audio-top-bar-phase {
font-size: 0.7rem;
color: #90a4ae;
line-height: 1.25;
white-space: nowrap;
}
.audio-top-bar-phase:empty {
display: none;
}
.audio-top-bar-phase:not(:empty)::before {
content: "·";
margin-right: 0.35rem;
color: #757575;
}
.audio-top-bar-phase.is-downbeat {
color: #ffab91;
}
.audio-top-indicator-subvalue {
font-size: 0.75rem;
color: #9e9e9e;
min-width: 2.2rem;
text-align: right;
}
.audio-top-beat-sync.flash {
background-color: #ff5252;
border-color: #ff8a80;
}
.audio-top-beat-sync.flash .audio-top-indicator-value,
.audio-top-beat-sync.flash .audio-top-indicator-label,
.audio-top-beat-sync.flash .audio-top-beat-readout,
.audio-top-beat-sync.flash .audio-top-beat-readout::before {
color: #fff;
}
/* Header/menu actions that should only appear in Edit mode */
body.preset-ui-run .edit-mode-only {
display: none !important;
@@ -381,9 +239,8 @@ body.preset-ui-run .edit-mode-only {
.zones-container {
background-color: transparent;
padding: 0;
flex: 0 0 auto;
width: 100%;
padding: 0.5rem 0;
flex: 1;
min-width: 0;
align-self: stretch;
display: flex;
@@ -646,39 +503,6 @@ body.preset-ui-run .edit-mode-only {
font-weight: 500;
}
.preset-mode-field {
margin-top: 0.75rem;
margin-bottom: 0.25rem;
}
.preset-mode-field label {
display: block;
font-weight: 500;
margin-bottom: 0.35rem;
}
.preset-mode-input {
display: block;
width: 100%;
max-width: 100%;
box-sizing: border-box;
padding: 0.5rem 0.6rem;
background-color: #3a3a3a;
color: #fff;
border: 1px solid #4a4a4a;
border-radius: 4px;
font-size: 1rem;
}
.preset-mode-input:focus {
outline: none;
border-color: #6a9fff;
}
#preset-editor-modal .preset-mode-field {
grid-column: 1 / -1;
}
.n-input {
flex: 0 0 var(--n-input-width, 5ch);
width: var(--n-input-width, 5ch);
@@ -726,16 +550,15 @@ body.preset-ui-run .edit-mode-only {
padding: 0;
}
/* Zone preset selecting area: 8 columns on desktop, vertical scroll only */
/* Zone preset selecting area: 3 columns, vertical scroll only */
#presets-list-zone {
flex: 1;
min-height: 0;
overflow-y: auto;
overflow-x: hidden;
display: grid;
grid-template-columns: repeat(8, minmax(0, 1fr));
/* min-content height prevents taller tiles (edit actions, wrapping) from overlapping the next row and stealing clicks */
grid-auto-rows: minmax(5rem, auto);
grid-template-columns: repeat(3, minmax(0, 1fr));
grid-auto-rows: 5rem;
column-gap: 0.3rem;
row-gap: 0.3rem;
align-content: start;
@@ -887,95 +710,6 @@ body.preset-ui-run .edit-mode-only {
display: block;
}
.audio-bpm-readout {
font-size: 2rem;
font-weight: 700;
letter-spacing: 0.05em;
color: #ffd54f;
text-align: center;
padding: 0.4rem;
background-color: #1a1a1a;
border: 1px solid #4a4a4a;
border-radius: 6px;
}
.audio-bpm-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.75rem;
}
.audio-bpm-row .audio-bpm-readout {
flex: 0 0 auto;
min-width: 5rem;
}
#audio-modal .audio-settings-section {
margin-top: 1rem;
}
#audio-modal .audio-settings-section .audio-modal-beat-readout {
display: block;
width: 100%;
max-width: none;
}
.audio-modal-beat-readout {
flex: 1;
min-width: 10rem;
min-height: 2.25rem;
font-size: 0.85rem;
line-height: 1.35;
text-align: center;
border: 1px solid #4a4a4a;
border-radius: 6px;
background-color: #252525;
padding: 0.35rem 0.65rem;
cursor: pointer;
font-family: inherit;
color: #b0bec5;
}
.audio-modal-beat-readout:disabled {
cursor: default;
opacity: 0.55;
}
.audio-modal-beat-readout:not(:disabled):hover {
border-color: #6a6a6a;
background-color: #333;
color: #e0e0e0;
}
.audio-hit-type-readout {
font-size: 1.1rem;
font-weight: 600;
letter-spacing: 0.04em;
color: #81d4fa;
text-transform: lowercase;
text-align: center;
padding: 0.35rem;
background-color: #1a1a1a;
border: 1px solid #4a4a4a;
border-radius: 6px;
}
.audio-beat-flash {
width: 100%;
height: 56px;
border-radius: 6px;
border: 1px solid #4a4a4a;
background: #202020;
box-shadow: inset 0 0 0 0 rgba(255, 82, 82, 0.5);
transition: background-color 80ms linear, box-shadow 120ms linear;
}
.audio-beat-flash.active {
background: #ff5252;
box-shadow: inset 0 0 24px 6px rgba(255, 255, 255, 0.35);
}
.patterns-list {
display: flex;
flex-direction: column;
@@ -1015,43 +749,17 @@ body.preset-ui-run .edit-mode-only {
flex-direction: row;
align-items: stretch;
min-width: 0;
min-height: 5rem;
min-height: 0;
}
.preset-tile-row-top {
display: flex;
flex-direction: row;
align-items: stretch;
flex: 1;
min-width: 0;
min-height: 5rem;
.preset-tile-row--run .preset-tile-actions {
display: none;
}
.preset-tile-main {
flex: 1;
min-width: 0;
height: 5rem;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 0.12rem;
}
.preset-tile-main .preset-tile-groups {
font-size: 0.68rem;
font-weight: 500;
line-height: 1.15;
opacity: 0.88;
text-align: center;
max-width: 100%;
padding: 0 0.35rem;
box-sizing: border-box;
word-break: break-word;
}
.preset-tile-row--run .preset-tile-actions {
display: none;
}
/* Edit only beside the preset tile in edit mode. */
@@ -1080,98 +788,13 @@ body.preset-ui-run .edit-mode-only {
white-space: normal;
}
.nav-slide-toggle-wrap {
display: inline-flex;
align-items: center;
gap: 0.4rem;
flex-shrink: 0;
}
.nav-slide-toggle-side-label {
font-size: 0.82rem;
color: #888;
user-select: none;
line-height: 1;
}
.nav-slide-toggle-wrap:not(.nav-slide-toggle-wrap--downbeat) .nav-slide-toggle-side-label--beat,
.nav-slide-toggle-wrap--downbeat .nav-slide-toggle-side-label--downbeat {
color: #e8e8e8;
font-weight: 500;
}
.nav-slide-toggle-switch {
position: relative;
width: 2.75rem;
height: 1.4rem;
padding: 0;
margin: 0;
color: inherit;
font: inherit;
appearance: none;
border: 1px solid #4a4a4a;
border-radius: 999px;
background-color: #2a2a2a;
cursor: pointer;
flex-shrink: 0;
}
.nav-slide-toggle-switch:hover {
border-color: #666;
}
.nav-slide-toggle-switch:focus-visible {
outline: 2px solid #7b6fd6;
outline-offset: 2px;
}
.nav-slide-toggle-track {
display: block;
width: 100%;
height: 100%;
border-radius: inherit;
}
.nav-slide-toggle-thumb {
position: absolute;
top: 50%;
left: 2px;
width: 1rem;
height: 1rem;
border-radius: 50%;
background-color: #bdbdbd;
transform: translateY(-50%);
transition: left 0.2s ease, background-color 0.2s ease;
}
.nav-slide-toggle-switch.seq-switch-toggle--downbeat {
.ui-mode-toggle--edit {
background-color: #4a3f8f;
border-color: #7b6fd6;
border: 1px solid #7b6fd6;
}
.nav-slide-toggle-switch.seq-switch-toggle--downbeat:hover {
.ui-mode-toggle--edit:hover {
background-color: #5a4f9f;
border-color: #8b7fe6;
}
.nav-slide-toggle-switch.seq-switch-toggle--downbeat .nav-slide-toggle-thumb {
left: calc(100% - 1rem - 2px);
transform: translateY(-50%);
background-color: #e8e4ff;
}
.main-menu-dropdown .nav-slide-toggle-wrap--mobile {
display: flex;
justify-content: center;
align-items: center;
gap: 0.35rem;
width: 100%;
max-width: 100%;
box-sizing: border-box;
padding: 0.45rem 0.5rem;
border-bottom: 1px solid #333;
flex-shrink: 1;
min-width: 0;
}
/* Preset select buttons inside the zone grid */
@@ -1305,46 +928,6 @@ body.preset-ui-run .edit-mode-only {
display: flex;
}
/* Stack sequence modals below groups / preset editor so in-modal actions stay visible */
#sequence-editor-modal.active,
#sequences-modal.active {
z-index: 1040;
}
#groups-modal.active,
#edit-group-modal.active,
#presets-modal.active {
z-index: 1050;
}
#preset-editor-modal.active {
z-index: 1060;
}
/* Child / overlay modals: must paint above preset editor (1060) and list modals (1050). */
#color-palette-modal.active,
#pattern-editor-modal.active,
#edit-device-modal.active,
#edit-zone-modal.active {
z-index: 1070;
}
/* Patterns library (often used next to presets); below preset editor, above sequences. */
#patterns-modal.active {
z-index: 1055;
}
/* Header / global dialogs */
#help-modal.active,
#audio-modal.active,
#settings-modal.active,
#led-tool-modal.active {
z-index: 1080;
}
/* JS-appended overlays (e.g. preset “From Palette”, add-preset-to-zone) — must sit above #preset-editor-modal */
.modal.modal-child-overlay.active {
z-index: 1080;
}
.modal-content {
background-color: #2e2e2e;
padding: 2rem;
@@ -1409,73 +992,20 @@ body.preset-ui-run .edit-mode-only {
/* Mobile-friendly layout */
@media (max-width: 1000px) {
header {
flex-direction: column;
align-items: stretch;
gap: 0.5rem;
}
header h1 {
flex-direction: row;
align-items: center;
gap: 0.25rem;
} header h1 {
font-size: 1.1rem;
}
/* On mobile, hide header buttons; all actions (including Tabs) are in the Menu dropdown */
} /* On mobile, hide header buttons; all actions (including Tabs) are in the Menu dropdown */
.header-actions {
display: none;
}
/* Beat/downbeat toggle lives in the mobile menu only */
#seq-switch-toggle-wrap {
display: none !important;
}
.main-menu-dropdown {
max-width: min(16rem, calc(100vw - 1rem));
}
#seq-switch-toggle-wrap-mobile .nav-slide-toggle-side-label {
font-size: 0.7rem;
flex-shrink: 1;
min-width: 0;
}
#seq-switch-toggle-wrap-mobile .nav-slide-toggle-switch.seq-switch-toggle {
width: 3.6rem;
height: 1.25rem;
flex-shrink: 0;
}
#seq-switch-toggle-wrap-mobile .nav-slide-toggle-switch .nav-slide-toggle-thumb {
width: 0.9rem;
height: 0.9rem;
}
#seq-switch-toggle-wrap-mobile .nav-slide-toggle-switch.seq-switch-toggle--downbeat .nav-slide-toggle-thumb {
left: calc(100% - 0.9rem - 2px);
transform: translateY(-50%);
}
.header-menu-mobile {
display: flex;
flex-direction: row;
align-items: center;
gap: 0.35rem;
display: block;
margin-top: 0;
}
.header-end {
gap: 0.35rem;
flex-shrink: 0;
}
.header-end .audio-top-indicator {
min-width: 5rem;
flex-shrink: 0;
}
.header-end .audio-top-beat-sync {
padding: 0.2rem 0.4rem;
min-height: 2rem;
gap: 0.3rem;
margin-left: auto;
}
.btn {
@@ -1484,9 +1014,8 @@ body.preset-ui-run .edit-mode-only {
}
.zones-container {
padding: 0.35rem 0 0;
padding: 0.5rem 0;
border-bottom: none;
width: 100%;
}
.zone-content {
@@ -1613,22 +1142,6 @@ body.preset-ui-run .edit-mode-only {
min-width: 8rem;
}
.zone-content-kind-row {
display: flex;
flex-wrap: nowrap;
align-items: center;
gap: 1rem;
margin: 0.35rem 0 0.75rem;
}
.zone-content-kind-row label {
display: inline-flex;
align-items: center;
gap: 0.35rem;
margin: 0;
white-space: nowrap;
}
.zone-devices-label {
display: block;
margin-top: 0.75rem;
@@ -1748,8 +1261,8 @@ body.preset-ui-run .edit-mode-only {
.color-swatches-container {
min-height: 80px;
}
/* Presets list: 3 columns on phone-sized screens */
@media (max-width: 600px) {
/* Presets list: 3 columns and vertical scroll (defined above); mobile same */
@media (max-width: 1000px) {
#presets-list-zone {
grid-template-columns: repeat(3, minmax(0, 1fr));
padding-bottom: calc(env(safe-area-inset-bottom, 0px) + 7rem);
@@ -1866,14 +1379,6 @@ body.preset-ui-run .edit-mode-only {
}
}
.sequence-step-drag-handle:active {
cursor: grabbing;
}
.sequence-step-row.dragging {
opacity: 0.65;
}
/* Settings modal */
#settings-modal .modal-content {
max-width: 900px;
@@ -1884,3 +1389,68 @@ body.preset-ui-run .edit-mode-only {
}#settings-modal .settings-section.ap-settings-section {
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;
}
+128 -507
View File
@@ -1,12 +1,6 @@
// Zone management JavaScript
let currentZoneId = null;
let brightnessSendTimeout = null;
/**
* When true, the next `loadZoneContent` skips `sendZoneBrightness` (run/edit toggle: same zone, UI only).
*/
let suppressZoneContentDriverSideEffects = false;
/** First successful `loadZoneContent` after open: skip hardware brightness push (read-only hydration). */
let isFirstZoneContentHydration = true;
function clamp255(n) {
const v = parseInt(n, 10);
@@ -23,26 +17,24 @@ function applyBrightnessSliders(val) {
if (menuSlider) menuSlider.value = String(v);
}
async function saveZoneBrightnessToServer(zoneId, val) {
if (!zoneId) return;
async function saveGlobalBrightnessToServer(val) {
try {
const res = await fetch(`/zones/${zoneId}`, {
const res = await fetch("/settings/settings", {
method: "PUT",
headers: { "Content-Type": "application/json", Accept: "application/json" },
credentials: "same-origin",
body: JSON.stringify({ brightness: val }),
body: JSON.stringify({ global_brightness: val }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
console.warn("zone brightness save failed:", err.error || res.status);
console.warn("global_brightness save failed:", err.error || res.status);
}
} catch (e) {
console.warn("zone brightness save failed:", e);
console.warn("global_brightness save failed:", e);
}
}
function sendZoneBrightness(zoneId, value) {
if (!zoneId) return;
function sendZoneBrightness(value) {
const val = Math.max(0, Math.min(255, parseInt(value, 10) || 0));
const headerSlider = document.getElementById('header-brightness-slider');
const menuSlider = document.getElementById('menu-brightness-slider');
@@ -58,7 +50,7 @@ function sendZoneBrightness(zoneId, value) {
brightnessSendTimeout = setTimeout(() => {
(async () => {
try {
await saveZoneBrightnessToServer(zoneId, val);
await saveGlobalBrightnessToServer(val);
const section = document.querySelector('.presets-section[data-zone-id]');
const names = typeof window.parseTabDeviceNames === 'function'
? window.parseTabDeviceNames(section)
@@ -70,47 +62,6 @@ function sendZoneBrightness(zoneId, value) {
? await window.tabsManager.resolveTabDeviceMacs(names)
: [];
if (typeof window.postDriverSequence === 'function') {
if (targetMacs.length > 0) {
let resolved = {};
try {
const rr = await fetch('/devices/resolve-brightness', {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
macs: targetMacs,
zone_brightness: val,
}),
});
if (rr.ok) {
const pack = await rr.json().catch(() => ({}));
if (pack && pack.values && typeof pack.values === 'object') {
resolved = pack.values;
}
}
} catch (re) {
console.warn('resolve-brightness failed:', re);
}
for (const mac of targetMacs) {
const k = String(mac).toLowerCase();
const b =
resolved[k] != null && resolved[k] !== ''
? parseInt(resolved[k], 10)
: val;
const bv = Number.isNaN(b)
? val
: Math.max(0, Math.min(255, b));
await window.postDriverSequence(
[{ v: '1', b: bv, save: true }],
[mac],
0,
);
}
return;
}
await window.postDriverSequence([{ v: '1', b: val, save: true }], targetMacs, 0);
return;
}
@@ -154,225 +105,8 @@ async function fetchDevicesMap() {
}
}
async function fetchGroupsMap() {
try {
const response = await fetch("/groups", {
headers: { Accept: "application/json" },
credentials: "same-origin",
});
if (!response.ok) return {};
const data = await response.json();
return data && typeof data === "object" ? data : {};
} catch (e) {
console.error("fetchGroupsMap:", e);
return {};
}
}
/**
* Resolve registry names + MACs for a zone document (``group_ids`` expands groups;
* otherwise ``names`` only).
*/
async function computeZoneTargets(zone) {
const dm = await fetchDevicesMap();
const gids = Array.isArray(zone && zone.group_ids)
? zone.group_ids.map((x) => String(x).trim()).filter((x) => x.length > 0)
: [];
if (gids.length > 0) {
const gm = await fetchGroupsMap();
const seen = new Set();
const names = [];
const macs = [];
for (const gid of gids) {
const g = gm[gid];
if (!g || !Array.isArray(g.devices)) continue;
for (const raw of g.devices) {
const m = String(raw || "")
.trim()
.toLowerCase()
.replace(/:/g, "")
.replace(/-/g, "");
if (m.length !== 12) continue;
if (seen.has(m)) continue;
seen.add(m);
const d = dm[m];
const n = d && String((d.name || "").trim()) ? String(d.name).trim() : m;
names.push(n);
macs.push(m);
}
}
return { names, macs };
}
const zoneNames = Array.isArray(zone && zone.names) ? zone.names : [];
const rows = namesToRows(zoneNames, dm);
return {
names: rowsToNames(rows),
macs: [...new Set(rows.map((r) => r.mac).filter(Boolean))],
};
}
/** Tab device list for sequences: zone ``group_ids`` first, else legacy ``names`` only. */
async function computeZoneNamesTargets(zone) {
const gids = Array.isArray(zone && zone.group_ids)
? zone.group_ids.map((x) => String(x).trim()).filter((x) => x.length > 0)
: [];
if (gids.length > 0) {
const t = await resolveTargetsFromGroupIds(gids);
return {
names: Array.isArray(t.names) ? t.names : [],
macs: Array.isArray(t.macs) ? [...new Set(t.macs.filter(Boolean))] : [],
};
}
const dm = await fetchDevicesMap();
const zoneNames = Array.isArray(zone && zone.names) ? zone.names : [];
const rows = namesToRows(zoneNames, dm);
return {
names: rowsToNames(rows),
macs: [...new Set(rows.map((r) => r.mac).filter(Boolean))],
};
}
function normalizeDeviceMac(raw) {
return String(raw || "")
.trim()
.toLowerCase()
.replace(/:/g, "")
.replace(/-/g, "");
}
/** Flat preset ids on a zone document (grid or flat). */
function tabPresetIdsInZoneDoc(zoneDoc) {
let ids = [];
if (Array.isArray(zoneDoc && zoneDoc.presets_flat)) {
ids = zoneDoc.presets_flat.slice();
} else if (Array.isArray(zoneDoc && zoneDoc.presets)) {
if (zoneDoc.presets.length && typeof zoneDoc.presets[0] === "string") {
ids = zoneDoc.presets.slice();
} else if (zoneDoc.presets.length && Array.isArray(zoneDoc.presets[0])) {
ids = zoneDoc.presets.flat();
}
}
return (ids || []).filter(Boolean);
}
/** Group ids used for standalone presets on this zone: zone ``group_ids`` only. */
function effectiveGroupIdsForZonePreset(zoneDoc) {
return Array.isArray(zoneDoc && zoneDoc.group_ids)
? zoneDoc.group_ids.map((x) => String(x).trim()).filter((x) => x.length > 0)
: [];
}
/** Resolve device names + MACs from a list of group ids (same rules as zone group expansion). */
async function resolveTargetsFromGroupIds(groupIds) {
const dm = await fetchDevicesMap();
const gids = Array.isArray(groupIds)
? groupIds.map((x) => String(x).trim()).filter((x) => x.length > 0)
: [];
if (!gids.length) {
return { names: [], macs: [] };
}
const gm = await fetchGroupsMap();
const seen = new Set();
const names = [];
const macs = [];
for (const gid of gids) {
const g = gm[gid];
if (!g || !Array.isArray(g.devices)) continue;
for (const raw of g.devices) {
const m = normalizeDeviceMac(raw);
if (m.length !== 12) continue;
if (seen.has(m)) continue;
seen.add(m);
const d = dm[m];
const n = d && String((d.name || "").trim()) ? String(d.name).trim() : m;
names.push(n);
macs.push(m);
}
}
return { names, macs };
}
/** Device names for standalone presets: zone ``group_ids``, or all devices on the tab (``names``). */
async function resolveDeviceNamesForZonePreset(zoneDoc, presetId) {
void presetId;
const gids = effectiveGroupIdsForZonePreset(zoneDoc);
if (gids.length) {
const t = await resolveTargetsFromGroupIds(gids);
if (t.names.length) return t.names;
}
const zt = await computeZoneTargets(zoneDoc);
return Array.isArray(zt.names) ? zt.names.slice() : [];
}
/** Union of devices targeted by standalone presets on the zone (same as zone preset targeting). */
async function computeZonePresetUnionTargets(zoneDoc) {
return await computeZoneTargets(zoneDoc);
}
/**
* Device names for one sequence step. Empty stepGroupIds => all zone tab devices (``names`` only).
* Otherwise: lane groups intersected with that tab device list (not zone ``group_ids``).
*/
async function resolveSequenceStepDeviceNames(zone, stepGroupIds) {
const zoneT = await computeZoneNamesTargets(zone);
const names = Array.isArray(zoneT.names) ? zoneT.names : [];
const macs = Array.isArray(zoneT.macs) ? zoneT.macs : [];
const gids = Array.isArray(stepGroupIds)
? stepGroupIds.map((x) => String(x).trim()).filter((x) => x.length > 0)
: [];
if (!gids.length) {
return names.slice();
}
const zoneMacSet = new Set(
macs.map((m) => normalizeDeviceMac(m)).filter((m) => m.length === 12),
);
const zoneNameByMac = new Map();
for (let i = 0; i < macs.length; i++) {
const m = normalizeDeviceMac(macs[i]);
if (m.length === 12 && !zoneNameByMac.has(m)) {
zoneNameByMac.set(m, names[i] || m);
}
}
const gm = await fetchGroupsMap();
const stepMacs = new Set();
for (const gid of gids) {
const g = gm[gid];
if (!g || !Array.isArray(g.devices)) continue;
for (const raw of g.devices) {
const m = normalizeDeviceMac(raw);
if (m.length !== 12 || !zoneMacSet.has(m)) continue;
stepMacs.add(m);
}
}
const out = [];
for (const m of stepMacs) {
const n = zoneNameByMac.get(m);
if (n) out.push(n);
}
return out;
}
async function resolveZoneDeviceMacsFromZoneData(zone) {
const t = await computeZoneTargets(zone);
return t.macs;
}
/** Registry MACs for zone device names (order matches zone names; skips unknown names). */
async function resolveZoneDeviceMacs(zoneNames) {
const section = document.querySelector(".presets-section[data-zone-id]");
if (section) {
const enc = section.getAttribute("data-zone-target-macs-json");
if (enc) {
try {
const macs = JSON.parse(decodeURIComponent(enc));
if (Array.isArray(macs) && macs.length) {
return [...new Set(macs.map((m) => String(m).toLowerCase()))];
}
} catch (e) {
/* fall through */
}
}
}
const dm = await fetchDevicesMap();
const rows = namesToRows(Array.isArray(zoneNames) ? zoneNames : [], dm);
const macs = rows.map((r) => r.mac).filter(Boolean);
@@ -400,10 +134,10 @@ function rowsToNames(rows) {
return (rows || []).map((r) => String(r.name || "").trim()).filter((n) => n.length > 0);
}
function renderZoneGroupsEditor(containerEl, rows, groupsMap) {
function renderZoneDevicesEditor(containerEl, rows, devicesMap) {
if (!containerEl) return;
containerEl.innerHTML = "";
const entries = Object.entries(groupsMap || {}).sort(([a], [b]) => a.localeCompare(b));
const entries = Object.entries(devicesMap || {}).sort(([a], [b]) => a.localeCompare(b));
rows.forEach((row, idx) => {
const div = document.createElement("div");
@@ -411,12 +145,12 @@ function renderZoneGroupsEditor(containerEl, rows, groupsMap) {
const label = document.createElement("span");
label.className = "zone-device-row-label";
const strong = document.createElement("strong");
strong.textContent = row.name || row.id || "—";
strong.textContent = row.name || "—";
label.appendChild(strong);
label.appendChild(document.createTextNode(" "));
const sub = document.createElement("span");
sub.className = "muted-text";
sub.textContent = `group ${row.id}`;
sub.textContent = row.mac ? row.mac : "(not in registry)";
label.appendChild(sub);
const rm = document.createElement("button");
@@ -425,42 +159,53 @@ function renderZoneGroupsEditor(containerEl, rows, groupsMap) {
rm.textContent = "Remove";
rm.addEventListener("click", () => {
rows.splice(idx, 1);
renderZoneGroupsEditor(containerEl, rows, groupsMap);
renderZoneDevicesEditor(containerEl, rows, devicesMap);
});
div.appendChild(label);
div.appendChild(rm);
containerEl.appendChild(div);
});
const idsInRows = new Set(rows.map((r) => String(r.id)));
const macsInRows = new Set(rows.map((r) => r.mac).filter(Boolean));
const addWrap = document.createElement("div");
addWrap.className = "zone-devices-add profiles-actions";
const sel = document.createElement("select");
sel.className = "zone-device-add-select";
sel.appendChild(new Option("Add group…", ""));
entries.forEach(([gid, g]) => {
if (idsInRows.has(gid)) return;
const gn = g && g.name ? String(g.name).trim() : "";
const optLabel = gn ? `${gn} (${gid})` : `Group ${gid}`;
sel.appendChild(new Option(optLabel, gid));
sel.appendChild(new Option("Add device…", ""));
entries.forEach(([mac, d]) => {
if (macsInRows.has(mac)) return;
const labelName = d && d.name ? String(d.name).trim() : "";
const optLabel = labelName ? `${labelName} — ${mac}` : mac;
sel.appendChild(new Option(optLabel, mac));
});
const addBtn = document.createElement("button");
addBtn.type = "button";
addBtn.className = "btn btn-primary btn-small";
addBtn.textContent = "Add";
addBtn.addEventListener("click", () => {
const gid = sel.value;
if (!gid || !groupsMap[gid]) return;
const gn = groupsMap[gid].name ? String(groupsMap[gid].name).trim() : gid;
rows.push({ id: gid, name: gn });
const mac = sel.value;
if (!mac || !devicesMap[mac]) return;
const n = String((devicesMap[mac].name || "").trim() || mac);
rows.push({ mac, name: n });
sel.value = "";
renderZoneGroupsEditor(containerEl, rows, groupsMap);
renderZoneDevicesEditor(containerEl, rows, devicesMap);
});
addWrap.appendChild(sel);
addWrap.appendChild(addBtn);
containerEl.appendChild(addWrap);
}
/** Default device name list when creating a zone (refined in Edit zone). */
async function defaultDeviceNamesForNewTab() {
const dm = await fetchDevicesMap();
const macs = Object.keys(dm);
if (macs.length > 0) {
const m0 = macs[0];
return [String((dm[m0].name || "").trim() || m0)];
}
return ["1"];
}
/** Read zone device names from the presets section (JSON attr preferred; legacy comma list fallback). */
function parseTabDeviceNames(section) {
if (!section) return [];
@@ -490,83 +235,6 @@ function escapeHtmlAttr(s) {
.replace(/</g, "&lt;");
}
/** @returns {null | 'presets' | 'sequences'} */
function normalizeZoneContentKind(zoneDoc) {
const k = zoneDoc && zoneDoc.content_kind;
if (k === 'presets' || k === 'sequences') return k;
return null;
}
/** Display/save kind when ``content_kind`` is missing (legacy rows). */
function effectiveZoneContentKind(zoneDoc) {
const explicit = normalizeZoneContentKind(zoneDoc);
if (explicit) return explicit;
const seqIds = Array.isArray(zoneDoc && zoneDoc.sequence_ids)
? zoneDoc.sequence_ids.filter(Boolean)
: [];
const presetIds = tabPresetIdsInZoneDoc(zoneDoc || {});
if (seqIds.length > 0 && presetIds.length === 0) return 'sequences';
return 'presets';
}
/** @returns {'presets' | 'sequences'} */
function editModalContentKindSelected() {
const radio = document.querySelector('input[name="edit-zone-content-kind"]:checked');
return radio && radio.value === 'sequences' ? 'sequences' : 'presets';
}
function activeZoneContentKind(zoneDoc, zoneId) {
const modal = document.getElementById('edit-zone-modal');
const editingId = document.getElementById('edit-zone-id')?.value;
if (
modal &&
modal.classList.contains('active') &&
zoneId != null &&
zoneId !== '' &&
String(editingId) === String(zoneId)
) {
return editModalContentKindSelected();
}
return effectiveZoneContentKind(zoneDoc);
}
/** True when the zone row has an explicit presets vs sequences type (not legacy inferred). */
function zoneHasExplicitContentKind(zoneDoc) {
return normalizeZoneContentKind(zoneDoc) !== null;
}
/** @returns {boolean} */
function zoneAllowsPresets(zoneDoc, zoneId) {
void zoneId;
if (!zoneHasExplicitContentKind(zoneDoc)) return true;
return effectiveZoneContentKind(zoneDoc) === 'presets';
}
/** @returns {boolean} */
function zoneAllowsSequences(zoneDoc, zoneId) {
void zoneId;
if (!zoneHasExplicitContentKind(zoneDoc)) return true;
return effectiveZoneContentKind(zoneDoc) === 'sequences';
}
function applyZoneContentKindEditModal(kind) {
const presetsBlock = document.getElementById('edit-zone-block-presets');
const groupsBlock = document.getElementById('edit-zone-block-groups');
const seqBlock = document.getElementById('edit-zone-block-sequences');
const vis = (el, show) => {
if (el) el.style.display = show ? '' : 'none';
};
const k = kind === 'sequences' ? 'sequences' : 'presets';
vis(groupsBlock, true);
vis(presetsBlock, k === 'presets');
vis(seqBlock, k === 'sequences');
}
window.normalizeZoneContentKind = normalizeZoneContentKind;
window.effectiveZoneContentKind = effectiveZoneContentKind;
window.zoneAllowsPresets = zoneAllowsPresets;
window.zoneAllowsSequences = zoneAllowsSequences;
// Load tabs list
async function loadZones() {
try {
@@ -624,13 +292,13 @@ function renderZonesList(tabs, tabOrder, currentZoneId) {
const zone = tabs[zoneId];
if (zone) {
const activeClass = zoneId === currentZoneId ? 'active' : '';
const disp = zone.name || `Zone ${zoneId}`;
const tabName = zone.name || `Zone ${zoneId}`;
html += `
<button class="zone-button ${activeClass}"
data-zone-id="${zoneId}"
title="${editMode ? 'Click to select, right-click to edit' : 'Click to select'}"
onclick="selectZone('${zoneId}')">
${escapeHtmlAttr(disp)}
${tabName}
</button>
`;
}
@@ -670,10 +338,9 @@ function renderZonesListModal(tabs, tabOrder, currentZoneId) {
row.dataset.zoneId = String(zoneId);
const label = document.createElement("span");
const disp = zone.name || `Zone ${zoneId}`;
label.textContent = disp;
label.textContent = (zone && zone.name) || zoneId;
if (String(zoneId) === String(currentZoneId)) {
label.textContent = `✓ ${disp}`;
label.textContent = `✓ ${label.textContent}`;
label.style.fontWeight = "bold";
label.style.color = "#FFD700";
}
@@ -870,16 +537,12 @@ async function loadZoneContent(zoneId) {
// Render zone content (presets section)
const tabName = zone.name || `Zone ${zoneId}`;
const targets = await computeZoneTargets(zone);
const namesJsonAttr = encodeURIComponent(JSON.stringify(targets.names));
const macsJsonAttr = encodeURIComponent(JSON.stringify(targets.macs));
const legacyOk =
targets.names.length > 0 && !targets.names.some((n) => /[",]/.test(String(n)));
const legacyAttr = legacyOk
? ` data-device-names="${escapeHtmlAttr(targets.names.join(","))}"`
: "";
const names = Array.isArray(zone.names) ? zone.names : [];
const namesJsonAttr = encodeURIComponent(JSON.stringify(names));
const legacyOk = names.length > 0 && !names.some((n) => /[",]/.test(String(n)));
const legacyAttr = legacyOk ? ` data-device-names="${escapeHtmlAttr(names.join(","))}"` : "";
container.innerHTML = `
<div class="presets-section" data-zone-id="${zoneId}" data-device-names-json="${namesJsonAttr}" data-zone-target-macs-json="${macsJsonAttr}"${legacyAttr}>
<div class="presets-section" data-zone-id="${zoneId}" data-device-names-json="${namesJsonAttr}"${legacyAttr}>
<div id="presets-list-zone" class="presets-list">
<!-- Presets will be loaded here by presets.js -->
</div>
@@ -887,21 +550,10 @@ async function loadZoneContent(zoneId) {
`;
// Keep header and menu brightness controls in sync.
const zoneBrightness =
typeof zone.brightness === 'number'
? zone.brightness
: parseInt(String(zone.brightness ?? ''), 10);
const normalizedBrightness = Number.isFinite(zoneBrightness)
? Math.max(0, Math.min(255, Math.round(zoneBrightness)))
: 255;
applyBrightnessSliders(normalizedBrightness);
const initialHydration = isFirstZoneContentHydration;
if (isFirstZoneContentHydration) {
isFirstZoneContentHydration = false;
}
if (!suppressZoneContentDriverSideEffects && !initialHydration) {
// Apply this zone's saved brightness when switching zones (not initial page load or UI-only strip refresh).
sendZoneBrightness(zoneId, normalizedBrightness);
const brightnessSlider = document.getElementById('header-brightness-slider');
const menuBrightnessSlider = document.getElementById('menu-brightness-slider');
if (menuBrightnessSlider && brightnessSlider) {
menuBrightnessSlider.value = brightnessSlider.value;
}
// Trigger presets loading if the function exists
@@ -980,7 +632,8 @@ async function sendProfilePresets() {
continue;
}
zonesWithPresets += 1;
const targets = await resolveZoneDeviceMacsFromZoneData(tabData);
const zoneNames = Array.isArray(tabData.names) ? tabData.names : [];
const targets = await resolveZoneDeviceMacs(zoneNames);
const payload = { preset_ids: presetIds };
if (tabData.default_preset) {
payload.default = tabData.default_preset;
@@ -1023,7 +676,17 @@ async function sendProfilePresets() {
}
function tabPresetIdsInOrder(tabData) {
return tabPresetIdsInZoneDoc(tabData);
let ids = [];
if (Array.isArray(tabData.presets_flat)) {
ids = tabData.presets_flat.slice();
} else if (Array.isArray(tabData.presets)) {
if (tabData.presets.length && typeof tabData.presets[0] === "string") {
ids = tabData.presets.slice();
} else if (tabData.presets.length && Array.isArray(tabData.presets[0])) {
ids = tabData.presets.flat();
}
}
return (ids || []).filter(Boolean);
}
// Presets already on the zone (remove) and presets available to add (select).
@@ -1044,12 +707,6 @@ async function refreshEditTabPresetsUi(zoneId) {
return;
}
const tabData = await tabRes.json();
if (!zoneAllowsPresets(tabData, zoneId)) {
currentEl.innerHTML =
'<span class="muted-text">This zone is for sequences only. Presets are hidden.</span>';
addEl.innerHTML = '<span class="muted-text">—</span>';
return;
}
const inTabIds = tabPresetIdsInOrder(tabData);
const inTabSet = new Set(inTabIds.map((id) => String(id)));
@@ -1073,12 +730,8 @@ async function refreshEditTabPresetsUi(zoneId) {
for (const presetId of inTabIds) {
const preset = allPresets[presetId] || {};
const name = preset.name || presetId;
const block = document.createElement("div");
block.style.cssText =
"border:1px solid rgba(255,255,255,0.12);border-radius:6px;padding:0.5rem 0.65rem;margin-bottom:0.65rem;";
const top = makeRow();
const row = makeRow();
const label = document.createElement("span");
label.style.fontWeight = "600";
label.textContent = name;
const removeBtn = document.createElement("button");
removeBtn.type = "button";
@@ -1090,11 +743,9 @@ async function refreshEditTabPresetsUi(zoneId) {
await window.removePresetFromTab(zoneId, presetId);
await refreshEditTabPresetsUi(zoneId);
});
top.appendChild(label);
top.appendChild(removeBtn);
block.appendChild(top);
currentEl.appendChild(block);
row.appendChild(label);
row.appendChild(removeBtn);
currentEl.appendChild(row);
}
}
@@ -1155,6 +806,7 @@ async function openEditZoneModal(zoneId, zone) {
const modal = document.getElementById("edit-zone-modal");
const idInput = document.getElementById("edit-zone-id");
const nameInput = document.getElementById("edit-zone-name");
const editor = document.getElementById("edit-zone-devices-editor");
let tabData = zone;
if (!tabData || typeof tabData !== "object" || tabData.error) {
@@ -1172,64 +824,39 @@ async function openEditZoneModal(zoneId, zone) {
if (idInput) idInput.value = zoneId;
if (nameInput) nameInput.value = tabData.name || "";
const groupsEditor = document.getElementById("edit-zone-groups-editor");
const groupsMap = await fetchGroupsMap();
const rawGids = Array.isArray(tabData.group_ids) ? tabData.group_ids : [];
window.__editTabGroupRows = rawGids.map((gid) => {
const id = String(gid);
const g = groupsMap[id];
return { id, name: g && g.name ? String(g.name).trim() : id };
});
renderZoneGroupsEditor(groupsEditor, window.__editTabGroupRows, groupsMap);
const kind = effectiveZoneContentKind(tabData);
document.querySelectorAll('input[name="edit-zone-content-kind"]').forEach((radio) => {
radio.checked = radio.value === kind;
});
const devicesMap = await fetchDevicesMap();
const zoneNames =
Array.isArray(tabData.names) && tabData.names.length > 0 ? tabData.names : ["1"];
window.__editTabDeviceRows = namesToRows(zoneNames, devicesMap);
renderZoneDevicesEditor(editor, window.__editTabDeviceRows, devicesMap);
if (modal) modal.classList.add("active");
applyZoneContentKindEditModal(kind);
await refreshEditTabPresetsUi(zoneId);
if (typeof window.refreshEditTabSequencesUi === "function") {
await window.refreshEditTabSequencesUi(zoneId);
}
}
// Update an existing zone (name, group list; devices come from groups only).
async function updateZone(zoneId, name, groupRows, contentKind) {
function normalizeTabNamesArg(namesOrString) {
if (Array.isArray(namesOrString)) {
return namesOrString.map((n) => String(n).trim()).filter((n) => n.length > 0);
}
if (typeof namesOrString === "string" && namesOrString.trim()) {
return namesOrString.split(",").map((id) => id.trim()).filter((id) => id.length > 0);
}
return ["1"];
}
// Update an existing zone
async function updateZone(zoneId, name, namesOrString) {
try {
const gids = Array.isArray(groupRows)
? groupRows.map((r) => String(r.id || "").trim()).filter((x) => x.length > 0)
: [];
const ck =
contentKind === 'sequences' || contentKind === 'presets' ? contentKind : 'presets';
let existing = {};
try {
const cur = await fetch(`/zones/${encodeURIComponent(zoneId)}`, {
headers: { Accept: 'application/json' },
});
if (cur.ok) {
const j = await cur.json();
if (j && typeof j === 'object') existing = j;
}
} catch (_) {
/* use empty existing */
}
let names = normalizeTabNamesArg(namesOrString);
if (!names.length) names = ["1"];
const response = await fetch(`/zones/${zoneId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
...existing,
name: name,
names: [],
group_ids: gids,
preset_group_ids:
existing.preset_group_ids && typeof existing.preset_group_ids === 'object'
? existing.preset_group_ids
: {},
content_kind: ck,
names: names
})
});
@@ -1252,11 +879,11 @@ async function updateZone(zoneId, name, groupRows, contentKind) {
}
}
// Create a new zone (add devices in Edit zone). ``contentKind`` is ``'presets'`` | ``'sequences'``.
async function createZone(name, contentKind) {
// Create a new zone
async function createZone(name, namesOrString) {
try {
const ck =
contentKind === 'sequences' || contentKind === 'presets' ? contentKind : 'presets';
let names = normalizeTabNamesArg(namesOrString);
if (!names.length) names = ["1"];
const response = await fetch('/zones', {
method: 'POST',
headers: {
@@ -1264,9 +891,7 @@ async function createZone(name, contentKind) {
},
body: JSON.stringify({
name: name,
names: [],
group_ids: [],
content_kind: ck,
names: names
})
});
@@ -1347,12 +972,8 @@ document.addEventListener('DOMContentLoaded', () => {
const name = newTabNameInput.value.trim();
if (name) {
const kindRadio = document.querySelector(
'input[name="new-zone-content-kind"]:checked',
);
const contentKind =
kindRadio && kindRadio.value === 'sequences' ? 'sequences' : 'presets';
await createZone(name, contentKind);
const deviceNames = await defaultDeviceNamesForNewTab();
await createZone(name, deviceNames);
if (newTabNameInput) newTabNameInput.value = "";
}
};
@@ -1369,18 +990,6 @@ document.addEventListener('DOMContentLoaded', () => {
});
}
document.querySelectorAll('input[name="edit-zone-content-kind"]').forEach((radio) => {
radio.addEventListener('change', async () => {
applyZoneContentKindEditModal(editModalContentKindSelected());
const zoneId = document.getElementById('edit-zone-id')?.value;
if (!zoneId) return;
await refreshEditTabPresetsUi(zoneId);
if (typeof window.refreshEditTabSequencesUi === 'function') {
await window.refreshEditTabSequencesUi(zoneId);
}
});
});
// Set up edit zone form
const editZoneForm = document.getElementById('edit-zone-form');
if (editZoneForm) {
@@ -1391,10 +1000,15 @@ document.addEventListener('DOMContentLoaded', () => {
const zoneId = idInput ? idInput.value : null;
const name = nameInput ? nameInput.value.trim() : "";
const groupRows = window.__editTabGroupRows || [];
const rows = window.__editTabDeviceRows || [];
const deviceNames = rowsToNames(rows);
if (zoneId && name) {
await updateZone(zoneId, name, groupRows, editModalContentKindSelected());
if (deviceNames.length === 0) {
alert("Add at least one device.");
return;
}
await updateZone(zoneId, name, deviceNames);
editZoneForm.reset();
}
});
@@ -1411,31 +1025,47 @@ document.addEventListener('DOMContentLoaded', () => {
const menuBrightnessSlider = document.getElementById('menu-brightness-slider');
const headerBrightnessSlider = document.getElementById('header-brightness-slider');
(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) {
menuBrightnessSlider.addEventListener('input', (e) => {
if (!currentZoneId) return;
sendZoneBrightness(currentZoneId, e.target.value);
sendZoneBrightness(e.target.value);
});
}
if (headerBrightnessSlider) {
headerBrightnessSlider.addEventListener('input', (e) => {
if (!currentZoneId) return;
sendZoneBrightness(currentZoneId, e.target.value);
sendZoneBrightness(e.target.value);
});
sendZoneBrightness(headerBrightnessSlider.value);
}
})();
// When run/edit mode toggles, refresh tabs UI so edit actions show/hide immediately.
document.querySelectorAll('.ui-mode-toggle').forEach((btn) => {
btn.addEventListener('click', async () => {
suppressZoneContentDriverSideEffects = true;
try {
await loadZones();
if (zonesModal && zonesModal.classList.contains("active")) {
await loadZonesModal();
}
} finally {
suppressZoneContentDriverSideEffects = false;
await loadZones();
if (zonesModal && zonesModal.classList.contains("active")) {
await loadZonesModal();
}
});
});
@@ -1450,17 +1080,8 @@ window.zonesManager = {
updateZone,
openEditZoneModal,
resolveZoneDeviceMacs,
resolveZoneDeviceMacsFromZoneData,
resolveTabDeviceMacs: resolveZoneDeviceMacs,
getCurrentZoneId: () => currentZoneId,
computeZoneTargets,
computeZoneNamesTargets,
computeZonePresetUnionTargets,
effectiveGroupIdsForZonePreset,
resolveDeviceNamesForZonePreset,
resolveSequenceStepDeviceNames,
fetchGroupsMap,
renderZoneGroupsEditor,
};
window.tabsManager = window.zonesManager;
window.tabsManager.getCurrentTabId = () => currentZoneId;
+140 -329
View File
@@ -9,52 +9,32 @@
<body>
<div class="app-container">
<header>
<div class="header-end">
<div class="nav-slide-toggle-wrap seq-switch-toggle-wrap edit-mode-only" id="seq-switch-toggle-wrap">
<span class="nav-slide-toggle-side-label nav-slide-toggle-side-label--beat">Beat</span>
<button type="button" role="switch" class="nav-slide-toggle-switch seq-switch-toggle" id="seq-switch-toggle" aria-pressed="false" aria-label="Switch sequence on beat" title="When starting a sequence: wait for beat or downbeat">
<span class="nav-slide-toggle-track" aria-hidden="true"><span class="nav-slide-toggle-thumb"></span></span>
</button>
<span class="nav-slide-toggle-side-label nav-slide-toggle-side-label--downbeat">Downbeat</span>
<div class="zones-container">
<div id="zones-list">
Loading zones...
</div>
<div id="audio-top-indicator" class="audio-top-indicator">
<button type="button" id="audio-top-beat-sync" class="audio-top-beat-sync" disabled title="Sync step to music (S)">
<span class="audio-top-indicator-label">BPM</span>
<span id="audio-top-bpm-value" class="audio-top-indicator-value">--</span>
<span id="audio-top-beat-readout" class="audio-top-beat-readout" aria-live="polite"></span>
<span id="audio-top-bar-phase" class="audio-top-bar-phase" aria-live="polite" title="Bar phase (beat in bar)"></span>
</button>
</div>
<div class="header-actions">
</div>
<div class="header-actions">
<div class="header-brightness-control">
<label for="header-brightness-slider">Brightness</label>
<input type="range" id="header-brightness-slider" min="0" max="255" value="255">
</div>
<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="groups-btn">Groups</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="presets-btn">Presets</button>
<button class="btn btn-secondary edit-mode-only" id="sequences-btn">Sequences</button>
<button class="btn btn-secondary edit-mode-only" id="patterns-btn">Patterns</button>
<button class="btn btn-secondary edit-mode-only" id="color-palette-btn">Colour Palette</button>
<button class="btn btn-secondary edit-mode-only" id="send-profile-presets-btn">Send Presets</button>
<button class="btn btn-secondary edit-mode-only" id="led-tool-btn">LED Tool</button>
<button class="btn btn-secondary" id="audio-btn">Audio</button>
<button type="button" class="btn btn-secondary" id="audio-nav-reset-btn" hidden title="Clear stuck BPM / beat tracking">Reset detector</button>
<button class="btn btn-secondary" id="help-btn">Help</button>
<button type="button" class="btn btn-secondary ui-mode-toggle" id="ui-mode-toggle" aria-pressed="false" title="Switch preset strip mode — label is the mode you will switch to">Edit mode</button>
</div>
<div class="header-menu-mobile">
</div>
<div class="header-menu-mobile">
<button class="btn btn-secondary" id="main-menu-btn">Menu</button>
<div id="main-menu-dropdown" class="main-menu-dropdown">
<div class="nav-slide-toggle-wrap nav-slide-toggle-wrap--mobile seq-switch-toggle-wrap" id="seq-switch-toggle-wrap-mobile">
<span class="nav-slide-toggle-side-label nav-slide-toggle-side-label--beat">Beat</span>
<button type="button" role="switch" class="nav-slide-toggle-switch seq-switch-toggle" id="seq-switch-toggle-mobile" aria-pressed="false" aria-label="Switch sequence on beat" title="Beat or downbeat">
<span class="nav-slide-toggle-track" aria-hidden="true"><span class="nav-slide-toggle-thumb"></span></span>
</button>
<span class="nav-slide-toggle-side-label nav-slide-toggle-side-label--downbeat">Downbeat</span>
</div>
<button type="button" class="ui-mode-toggle" id="ui-mode-toggle-mobile" aria-pressed="false">Edit mode</button>
<div class="menu-brightness-control">
<label for="menu-brightness-slider">Brightness</label>
@@ -62,24 +42,16 @@
</div>
<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="groups-btn">Groups</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="presets-btn">Presets</button>
<button type="button" class="edit-mode-only" data-target="sequences-btn">Sequences</button>
<button type="button" class="edit-mode-only" data-target="patterns-btn">Patterns</button>
<button type="button" class="edit-mode-only" data-target="color-palette-btn">Colour Palette</button>
<button type="button" class="edit-mode-only" data-target="send-profile-presets-btn">Send Presets</button>
<button type="button" class="edit-mode-only" data-target="led-tool-btn">LED Tool</button>
<button type="button" data-target="audio-btn">Audio</button>
<button type="button" id="audio-nav-reset-mobile" data-target="audio-nav-reset-btn" hidden>Reset detector</button>
<button type="button" data-target="help-btn">Help</button>
</div>
</div>
</div>
<div class="zones-container">
<div id="zones-list">
Loading zones...
</div>
</div>
</header>
@@ -100,10 +72,6 @@
<input type="text" id="new-zone-name" placeholder="Zone name">
<button class="btn btn-primary" id="create-zone-btn">Create</button>
</div>
<div class="zone-content-kind-row muted-text">
<label><input type="radio" name="new-zone-content-kind" value="presets" checked> Presets</label>
<label><input type="radio" name="new-zone-content-kind" value="sequences"> Sequences</label>
</div>
<div id="zones-list-modal" class="profiles-list"></div>
<div class="modal-actions">
<button class="btn btn-secondary" id="zones-close-btn">Close</button>
@@ -117,32 +85,18 @@
<h2>Edit Zone</h2>
<form id="edit-zone-form">
<input type="hidden" id="edit-zone-id">
<div class="modal-actions" style="margin-bottom: 1rem;">
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-secondary" onclick="document.getElementById('edit-zone-modal').classList.remove('active')">Close</button>
</div>
<label>Zone Name:</label>
<input type="text" id="edit-zone-name" placeholder="Enter zone name" required>
<div class="zone-content-kind-row muted-text">
<label><input type="radio" name="edit-zone-content-kind" value="presets" checked> Presets</label>
<label><input type="radio" name="edit-zone-content-kind" value="sequences"> Sequences</label>
</div>
<div id="edit-zone-block-groups">
<label class="zone-devices-label">Device groups on this zone</label>
<div id="edit-zone-groups-editor" class="zone-devices-editor"></div>
</div>
<div id="edit-zone-block-presets">
<label class="zone-devices-label">Devices in this zone</label>
<div id="edit-zone-devices-editor" class="zone-devices-editor"></div>
<label class="zone-presets-section-label">Presets on this zone</label>
<div id="edit-zone-presets-current" class="profiles-list edit-zone-presets-scroll"></div>
<label class="zone-presets-section-label">Add presets to this zone</label>
<div id="edit-zone-presets-list" class="profiles-list edit-zone-presets-scroll"></div>
</div>
<div id="edit-zone-block-sequences">
<label class="zone-presets-section-label">Sequences on this zone</label>
<div id="edit-zone-sequences-current" class="profiles-list edit-zone-presets-scroll"></div>
<label class="zone-presets-section-label">Add a sequence to this zone</label>
<div id="edit-zone-sequences-list" class="profiles-list edit-zone-presets-scroll"></div>
</div>
<div class="modal-actions">
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-secondary" onclick="document.getElementById('edit-zone-modal').classList.remove('active')">Close</button>
</div>
</form>
</div>
</div>
@@ -154,7 +108,6 @@
<div class="profiles-actions">
<input type="text" id="new-profile-name" placeholder="Profile name">
<button class="btn btn-primary" id="create-profile-btn">Create</button>
<button type="button" class="btn btn-secondary" id="import-profile-btn">Import</button>
</div>
<div class="form-group" style="margin-top: 0.5rem; margin-bottom: 0;">
<label style="display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0;">
@@ -180,78 +133,6 @@
</div>
</div>
<!-- Device groups: members + Wi‑Fi driver defaults (zones reference groups for presets) -->
<div id="groups-modal" class="modal">
<div class="modal-content">
<h2>Device groups</h2>
<p class="muted-text" style="margin-top:0;">Assign drivers to a group, set Wi‑Fi defaults once per group, then attach groups to a zone for standalone presets (sequences use each lane’s groups only). By default new groups are <strong>shared</strong> across all profiles; tick “this profile only” to hide a group from other profiles.</p>
<div class="profiles-actions zone-modal-create-row">
<input type="text" id="new-group-name" placeholder="Group name">
<label class="muted-text" style="display:inline-flex;align-items:center;gap:0.35rem;white-space:nowrap;">
<input type="checkbox" id="new-group-profile-only"> This profile only
</label>
<button class="btn btn-primary" id="create-group-btn">Create</button>
</div>
<div id="groups-list-modal" class="profiles-list"></div>
<div class="modal-actions">
<button class="btn btn-secondary" id="groups-close-btn">Close</button>
</div>
</div>
</div>
<div id="edit-group-modal" class="modal">
<div class="modal-content">
<h2>Edit device group</h2>
<form id="edit-group-form">
<input type="hidden" id="edit-group-id">
<label for="edit-group-name">Group name</label>
<input type="text" id="edit-group-name" required autocomplete="off">
<label class="muted-text" style="display:flex;align-items:flex-start;gap:0.5rem;margin-top:0.5rem;">
<input type="checkbox" id="edit-group-share-all-profiles" style="margin-top:0.2rem;">
<span>Share with all profiles (untick to keep this group on the <strong>current profile only</strong>)</span>
</label>
<label class="zone-devices-label">Devices in this group</label>
<div id="edit-group-devices-editor" class="zone-devices-editor"></div>
<div class="profiles-actions" style="margin-top: 0.5rem;">
<button type="button" class="btn btn-secondary btn-small" id="edit-group-identify-btn">Identify devices in group</button>
</div>
<p class="muted-text" style="margin-top:0.25rem;">Runs identify on every driver in the group at the same time so they blink together.</p>
<label for="edit-group-output-brightness" style="margin-top:0.75rem;display:block;">Group output brightness (0–255)</label>
<div class="profiles-actions" style="align-items: center; gap: 0.75rem;">
<input type="range" id="edit-group-output-brightness" min="0" max="255" value="255" style="flex:1;">
<span id="edit-group-output-brightness-value" class="muted-text" style="min-width:2.5rem;">255</span>
</div>
<p class="muted-text" style="margin-top:0.75rem;margin-bottom:0.35rem;">Wi‑Fi driver defaults (apply to all members via <strong>Apply defaults to drivers</strong> on the list)</p>
<label for="edit-group-wifi-driver-name">Display name</label>
<input type="text" id="edit-group-wifi-driver-name" placeholder="hello / discovery name" autocomplete="off">
<label for="edit-group-wifi-num-leds" style="margin-top:0.5rem;display:block;">Number of LEDs</label>
<input type="number" id="edit-group-wifi-num-leds" min="1" max="2048" step="1" placeholder="119">
<label for="edit-group-wifi-color-order" style="margin-top:0.5rem;display:block;">Colour order</label>
<select id="edit-group-wifi-color-order">
<option value="rgb">RGB</option>
<option value="rbg">RBG</option>
<option value="grb">GRB</option>
<option value="gbr">GBR</option>
<option value="brg">BRG</option>
<option value="bgr">BGR</option>
</select>
<label for="edit-group-wifi-startup-mode" style="margin-top:0.5rem;display:block;">Power-on pattern</label>
<select id="edit-group-wifi-startup-mode">
<option value="default">Default preset</option>
<option value="last">Last preset</option>
<option value="off">Off</option>
</select>
<label for="edit-group-debug" style="margin-top:1rem;display:block;">Debug</label>
<small class="muted-text" style="display:block;margin-bottom:0.35rem;">Stored row and the JSON preview for <strong>Save</strong> (updates as you edit).</small>
<textarea id="edit-group-debug" rows="8" readonly spellcheck="false" style="width:100%;font-family:monospace;resize:vertical;"></textarea>
<div class="modal-actions">
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-secondary" id="edit-group-close-btn">Cancel</button>
</div>
</form>
</div>
</div>
<div id="edit-device-modal" class="modal">
<div class="modal-content">
<h2>Edit device</h2>
@@ -277,37 +158,6 @@
<label for="edit-device-address-wifi">Address (IP or hostname)</label>
<input type="text" id="edit-device-address-wifi" placeholder="192.168.1.50" autocomplete="off">
</div>
<div id="edit-device-wifi-driver-wrap" hidden>
<p class="muted-text" style="margin-top:0.75rem;margin-bottom:0.35rem;">On-device settings (sent over Wi‑Fi when connected). For shared defaults across several drivers, use <strong>Groups</strong>.</p>
<label for="edit-device-wifi-driver-name">Display name</label>
<input type="text" id="edit-device-wifi-driver-name" placeholder="hello / discovery name" autocomplete="off">
<label for="edit-device-wifi-num-leds" style="margin-top:0.5rem;display:block;">Number of LEDs</label>
<input type="number" id="edit-device-wifi-num-leds" min="1" max="2048" step="1" placeholder="119">
<label for="edit-device-wifi-color-order" style="margin-top:0.5rem;display:block;">Colour order</label>
<select id="edit-device-wifi-color-order">
<option value="rgb">RGB</option>
<option value="rbg">RBG</option>
<option value="grb">GRB</option>
<option value="gbr">GBR</option>
<option value="brg">BRG</option>
<option value="bgr">BGR</option>
</select>
<label for="edit-device-wifi-startup-mode" style="margin-top:0.5rem;display:block;">Power-on pattern</label>
<select id="edit-device-wifi-startup-mode">
<option value="default">Default preset</option>
<option value="last">Last preset</option>
<option value="off">Off</option>
</select>
</div>
<label for="edit-device-output-brightness" style="margin-top:0.75rem;display:block;">Output brightness (0–255)</label>
<div class="profiles-actions" style="align-items: center; gap: 0.75rem;">
<input type="range" id="edit-device-output-brightness" min="0" max="255" value="255" style="flex:1;">
<span id="edit-device-output-brightness-value" class="muted-text" style="min-width:2.5rem;">255</span>
</div>
<small class="muted-text" style="display:block;margin-top:0.25rem;">Saved on the device; use <strong>Save</strong> to push to the driver (when connected).</small>
<label for="edit-device-debug" style="margin-top:1rem;display:block;">Debug</label>
<small class="muted-text" style="display:block;margin-bottom:0.35rem;">Stored registry row and the JSON preview for <strong>Save</strong> (updates as you edit).</small>
<textarea id="edit-device-debug" rows="8" readonly spellcheck="false" style="width:100%;font-family:monospace;resize:vertical;"></textarea>
<div class="modal-actions">
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-secondary" id="edit-device-close-btn">Cancel</button>
@@ -316,13 +166,130 @@
</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 -->
<div id="presets-modal" class="modal">
<div class="modal-content">
<h2>Presets</h2>
<div class="modal-actions">
<button class="btn btn-primary" id="preset-add-btn">Add</button>
<button type="button" class="btn btn-secondary" id="import-preset-btn">Import</button>
<button class="btn btn-danger" id="preset-clear-device-btn">Clear Device Presets</button>
</div>
<div id="presets-list" class="profiles-list"></div>
@@ -332,54 +299,6 @@
</div>
</div>
<!-- Sequences Modal -->
<div id="sequences-modal" class="modal">
<div class="modal-content">
<h2>Sequences</h2>
<div class="modal-actions">
<button type="button" class="btn btn-primary" id="sequence-add-btn">Add</button>
<button type="button" class="btn btn-secondary" id="import-sequence-btn">Import</button>
<button type="button" class="btn btn-secondary" id="sequences-open-presets-btn">Presets</button>
</div>
<div id="sequences-list" class="profiles-list"></div>
<div class="modal-actions">
<button type="button" class="btn btn-secondary" id="sequences-close-btn">Close</button>
</div>
</div>
</div>
<!-- Sequence Editor Modal -->
<div id="sequence-editor-modal" class="modal">
<div class="modal-content">
<h2>Sequence</h2>
<div class="preset-editor-field">
<label for="sequence-editor-name">Name</label>
<input type="text" id="sequence-editor-name" placeholder="Sequence name" style="width:100%;max-width:24rem;">
</div>
<div id="sequence-editor-beats-panel" style="margin:0 0 0.75rem 0;">
<p class="muted-text" style="font-size:0.85em;margin:0 0 0.5rem 0;">
Each step runs for the number of <strong>beats</strong> you set on that step.
When the header <strong>Audio</strong> detector is running, real beats advance the sequence.
When it is stopped, the server uses <strong>simulated</strong> beats at the BPM below.
</p>
<label for="sequence-editor-simulated-bpm" style="display:block;margin-bottom:0.25rem;">Simulated BPM (when audio is off)</label>
<input type="number" id="sequence-editor-simulated-bpm" min="30" max="300" value="120" style="width:6rem;" title="Used only while the audio detector is stopped">
<p id="sequence-editor-bpm-live" class="muted-text" style="font-size:0.85em;margin:0.5rem 0 0 0;">—</p>
<label style="display:block;margin-top:0.65rem;">
<input type="checkbox" id="sequence-editor-loop" checked>
Loop sequence (restart from the first step after the last)
</label>
</div>
<div id="sequence-editor-lanes"></div>
<div class="modal-actions preset-editor-modal-actions">
<button type="button" class="btn btn-secondary btn-small" id="sequence-editor-add-lane-btn">Add lane</button>
<button type="button" class="btn btn-danger" id="sequence-editor-delete-btn">Delete</button>
<button type="button" class="btn btn-primary" id="sequence-editor-save-btn">Save</button>
<button type="button" class="btn btn-secondary" id="sequence-editor-close-btn">Close</button>
</div>
</div>
</div>
<!-- Preset Editor Modal -->
<div id="preset-editor-modal" class="modal">
<div class="modal-content">
@@ -405,36 +324,6 @@
<label for="preset-delay-input">Delay (ms)</label>
<input type="number" id="preset-delay-input" placeholder="Delay" min="0" max="10000" value="0">
</div>
<div class="preset-editor-field">
<label for="preset-background-input">Background</label>
<div class="profiles-actions" style="gap: 0.4rem;">
<button type="button" class="btn btn-secondary btn-small" id="preset-background-btn" title="Choose background colour">#000000</button>
<button type="button" class="btn btn-secondary btn-small" id="preset-background-from-palette-btn">From Palette</button>
<input type="color" id="preset-background-input" value="#000000" title="Background colour used in patterns with background support" style="position:absolute;opacity:0;pointer-events:none;width:1px;height:1px;">
</div>
</div>
</div>
<div class="form-group" style="margin-top: 0.5rem; margin-bottom: 0;">
<label id="preset-manual-mode-label" style="display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0;">
<input type="checkbox" id="preset-manual-mode-input">
Manual mode (single-shot where supported)
</label>
<p id="preset-manual-mode-hint" class="muted-text" style="display: none; margin-top: 0.35rem; font-size: 0.85em;"></p>
<div id="preset-manual-beat-n-wrap" class="preset-editor-field" style="display: none; margin-top: 0.5rem;">
<label for="preset-manual-beat-n-input">Audio beat: every</label>
<input type="number" id="preset-manual-beat-n-input" min="1" max="64" value="1" style="width: 4rem;" title="Controller only; not sent to pattern logic" autocomplete="off">
<span class="muted-text" style="font-size: 0.85em;">beats (this app only)</span>
</div>
</div>
<div class="preset-editor-field" id="preset-reverse-group" hidden>
<label for="preset-reverse-input" style="display:flex;align-items:center;gap:0.5rem;margin-bottom:0;">
<input type="checkbox" id="preset-reverse-input">
Reverse direction (strip installed upside down)
</label>
</div>
<div class="preset-editor-field preset-mode-field" id="preset-mode-group" hidden>
<label for="preset-mode-input" id="preset-mode-label">Mode</label>
<select id="preset-mode-input" class="preset-mode-input"></select>
</div>
<div class="n-params-grid">
<div class="n-param-group">
@@ -593,20 +482,19 @@
<li><strong>Select zone</strong>: left-click a zone button in the top bar.</li>
<li><strong>Select preset</strong>: left-click a preset tile to send a <code>select</code> message to all devices in the zone.</li>
<li><strong>Profiles</strong>: open <strong>Profiles</strong> to apply a profile. Profile editing actions are hidden in Run mode.</li>
<li><strong>Devices</strong>: open <strong>Devices</strong> to see drivers (Wi-Fi clients appear when they connect); edit addresses or remove rows.</li>
<li><strong>Groups</strong>: define device groups, Wi‑Fi driver defaults, then assign groups to zones.</li>
<li><strong>Devices</strong>: open <strong>Devices</strong> to see drivers (Wi-Fi clients appear when they connect); edit or remove rows as needed.</li>
<li><strong>Send all presets</strong>: this action is available in <strong>Edit mode</strong> and pushes every preset used in the current zone to all zone devices.</li>
<li><strong>Switch modes</strong>: use the mode button in the menu. The button label shows the mode you will switch to.</li>
</ul>
<h3>Edit mode</h3>
<ul>
<li><strong>Tabs</strong>: create, edit, and manage zones and which <strong>device groups</strong> each zone drives.</li>
<li><strong>Tabs</strong>: create, edit, and manage tabs and device assignments.</li>
<li><strong>Presets</strong>: create/manage reusable presets and edit preset details.</li>
<li><strong>Preset tiles</strong>: each tile shows <strong>Edit</strong> and <strong>Remove</strong> controls in Edit mode.</li>
<li><strong>Reorder presets</strong>: drag and drop preset tiles to save zone order.</li>
<li><strong>Profiles</strong>: create/clone/delete profiles. New profiles get a populated <strong>default</strong> zone and can optionally seed a <strong>DJ zone</strong>.</li>
<li><strong>Devices</strong>: registry rows are keyed by <strong>MAC</strong>; edit a device for transport/IP and per-driver Wi‑Fi settings, or use <strong>Groups</strong> for shared defaults.</li>
<li><strong>Devices</strong>: view, edit, or remove registry entries (tabs use <strong>names</strong>; each row is keyed by <strong>MAC</strong>).</li>
<li><strong>Colour Palette</strong>: build profile colours and use <strong>From Palette</strong> in preset editor to add linked colours (badge <strong>P</strong>) that update when palette colours change.</li>
</ul>
@@ -623,80 +511,6 @@
</div>
</div>
<!-- Audio Modal -->
<div id="audio-modal" class="modal">
<div class="modal-content">
<h2>Audio Beat Detection</h2>
<p class="muted-text">Select an input device and start beat detection.</p>
<div class="form-group">
<label for="audio-device-select">Input device</label>
<div class="profiles-actions">
<select id="audio-device-select" style="flex: 1;">
<option value="">Default input</option>
</select>
<button type="button" class="btn btn-secondary" id="audio-refresh-btn">Refresh</button>
</div>
<small>Tip: for Pulse/pipewire playback capture, use a source containing <code>monitor</code>.</small>
</div>
<div class="form-group">
<label for="audio-device-override">Manual device override (optional)</label>
<input type="text" id="audio-device-override" placeholder='e.g. 3 or "alsa_output....monitor"'>
</div>
<div class="form-group">
<label>Current BPM</label>
<div class="audio-bpm-row">
<div id="audio-bpm-value" class="audio-bpm-readout">--</div>
</div>
</div>
<div class="form-group">
<label>Detected hit type</label>
<div id="audio-hit-type-value" class="audio-hit-type-readout">unknown</div>
</div>
<div class="form-group">
<label>Bar phase</label>
<div class="audio-bpm-row">
<div id="audio-bar-phase-value" class="audio-bpm-readout" title="Beat in bar (kick hints downbeat)">--</div>
</div>
<small class="muted-text">Bar uses kick-heavy hits (default 4/4). Tap <strong>Sync</strong> on a downbeat to lock bar phase.</small>
</div>
<div class="form-group">
<label>Flash on beat</label>
<div id="audio-beat-flash" class="audio-beat-flash" aria-hidden="true"></div>
</div>
<div class="settings-section audio-settings-section">
<h3>Audio settings</h3>
<div class="form-group">
<label for="audio-beat-phase-ms">Beat phase shift (ms)</label>
<input type="number" id="audio-beat-phase-ms" min="0" max="500" step="5" value="0" style="width:6rem;">
<small class="muted-text">Delays beat flashes so they line up with what you hear (saved on the controller).</small>
</div>
<div class="form-group">
<label>Beat sync</label>
<button type="button" id="audio-modal-beat-readout" class="audio-modal-beat-readout muted-text" disabled title="Sync step to music (S)" aria-live="polite"></button>
<small class="muted-text">While a sequence is playing, tap the BPM/beat button in the header on a downbeat to align the step counter. Shortcut: <kbd>S</kbd>.</small>
</div>
<div class="form-group">
<label>Sequence alignment</label>
<div class="profiles-actions" style="flex-wrap: wrap;">
<button type="button" class="btn btn-secondary" id="audio-sync-pass-btn">Restart pass</button>
</div>
<small class="muted-text"><strong>Restart pass</strong> jumps to step 1 of the sequence (<kbd>Shift+S</kbd>). Use <strong>Reset detector</strong> in the header (while audio is running) to clear stuck BPM/beat tracking without stopping audio.</small>
</div>
</div>
<div class="modal-actions">
<button type="button" class="btn btn-primary" id="audio-start-btn">Start</button>
<button type="button" class="btn btn-secondary" id="audio-stop-btn">Stop</button>
<button type="button" class="btn btn-secondary" id="audio-close-btn">Close</button>
</div>
<div class="form-group" style="margin-top: 0.75rem;">
<label for="audio-devices-debug">Detected devices (Python)</label>
<textarea id="audio-devices-debug" rows="8" readonly style="width:100%; font-family:monospace; resize:vertical;"></textarea>
</div>
</div>
</div>
<!-- Settings Modal -->
<div id="settings-modal" class="modal">
<div class="modal-content">
@@ -842,19 +656,16 @@
</div>
<!-- Styles moved to /static/style.css -->
<script src="/static/groups.js"></script>
<script src="/static/zones.js"></script>
<script src="/static/help.js"></script>
<script src="/static/led_tool.js"></script>
<script src="/static/color_palette.js"></script>
<script src="/static/bundle_io.js"></script>
<script src="/static/profiles.js"></script>
<script src="/static/zone_palette.js"></script>
<script src="/static/patterns.js"></script>
<script src="/static/presets.js"></script>
<script src="/static/sequences.js"></script>
<script src="/static/devices.js"></script>
<script src="/static/audio.js"></script>
<script src="/static/numpad.js"></script>
<script src="/static/outputs.js"></script>
<script src="/static/sequences.js"></script>
</body>
</html>
+1 -1
View File
@@ -261,7 +261,7 @@
return;
}
try {
const response = await fetch('/settings', {
const response = await fetch('/settings/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ wifi_channel: wifiChannel }),
-534
View File
@@ -1,534 +0,0 @@
import collections
import importlib.util
import os
import queue
import threading
import time
from typing import Any
_HOLDOVER_BPM_MIN = 30.0
_HOLDOVER_BPM_MAX = 300.0
_HOLDOVER_MAX_S = 300.0
class AudioBeatDetector:
def __init__(self):
self._lock = threading.Lock()
self._thread = None
self._stream = None
self._running = False
self._stop_event = threading.Event()
self._runtime = None
self._pending_reset = False
self._holdover_thread: threading.Thread | None = None
self._holdover_stop = threading.Event()
self._holdover_active = False
self._status = {
"running": False,
"bpm": None,
"last_beat_ts": None,
"beat_seq": 0,
"beat_type": "unknown",
"beat_type_confidence": 0.0,
"bar_beat": 1,
"beats_per_bar": 4,
"is_downbeat": False,
"phase_confidence": 0.0,
"bar_phase_readout": "1/4",
"error": None,
"device": None,
}
def list_input_devices(self):
import sounddevice as sd
devices = sd.query_devices()
hostapis = sd.query_hostapis()
default_input_idx = None
try:
default_input_idx = int(sd.default.device[0])
except Exception:
default_input_idx = None
out = []
for idx, dev in enumerate(devices):
name = str(dev.get("name", f"Input {idx}"))
chans = int(dev.get("max_input_channels", 0))
is_monitor_named = "monitor" in name.lower()
if chans <= 0 and not is_monitor_named:
continue
sr = int(dev.get("default_samplerate", 44100))
hostapi_idx = int(dev.get("hostapi", -1))
hostapi_name = (
str(hostapis[hostapi_idx].get("name", "unknown"))
if 0 <= hostapi_idx < len(hostapis)
else "unknown"
)
is_default = default_input_idx is not None and idx == default_input_idx
ch_label = f"{chans}ch" if chans > 0 else "0ch?"
label = f"[{idx}] {name} ({ch_label} @ {sr}Hz, {hostapi_name})"
if is_default:
label = f"{label} [default]"
if is_monitor_named:
label = f"{label} [monitor]"
out.append(
{
"id": idx,
"name": name,
"label": label,
"max_input_channels": chans,
"default_samplerate": sr,
"is_default": is_default,
"hostapi": hostapi_name,
}
)
return out
def diagnostics(self):
import sounddevice as sd
devices = sd.query_devices()
hostapis = sd.query_hostapis()
default_input = None
try:
default_input = sd.default.device[0]
except Exception:
default_input = None
return {
"default_input": default_input,
"hostapis": hostapis,
"devices": devices,
}
def start(self, device=None):
should_restart = False
with self._lock:
should_restart = self._running
if should_restart:
self.stop()
with self._lock:
self._stop_event.clear()
self._status.update(
{
"running": True,
"bpm": None,
"last_beat_ts": None,
"beat_seq": 0,
"beat_type": "unknown",
"beat_type_confidence": 0.0,
"bar_beat": 1,
"beats_per_bar": 4,
"is_downbeat": False,
"phase_confidence": 0.0,
"bar_phase_readout": "1/4",
"error": None,
"device": device,
}
)
self._running = True
self._thread = threading.Thread(
target=self._run_loop, args=(device,), daemon=True
)
self._thread.start()
def stop(self):
self._stop_bpm_holdover()
with self._lock:
self._stop_event.set()
t = self._thread
stream = self._stream
try:
import sounddevice as sd
sd.stop(ignore_errors=True)
except Exception:
pass
if stream is not None:
try:
stream.abort()
except Exception:
pass
try:
stream.stop()
except Exception:
pass
try:
stream.close()
except Exception:
pass
if t and t.is_alive():
t.join(timeout=3.0)
with self._lock:
self._running = False
self._thread = None
self._stream = None
self._pending_reset = False
self._status["running"] = False
def status(self):
with self._lock:
st = dict(self._status)
holdover = self._holdover_active
last = st.get("last_beat_ts")
if st.get("running") and last is not None and not holdover:
try:
if (time.time() - float(last)) > 4.0:
st["bpm"] = None
except (TypeError, ValueError):
pass
return st
def _apply_tracking_reset_status(self) -> None:
"""Refresh published status after a tracking reset (lock must be held)."""
bpb = max(1, int(self._status.get("beats_per_bar") or 4))
self._status.update(
{
"running": True,
"beat_type": "unknown",
"beat_type_confidence": 0.0,
"bar_beat": 1,
"is_downbeat": True,
"phase_confidence": 0.0,
"bar_phase_readout": f"1/{bpb}",
}
)
def _clamp_holdover_bpm(self, bpm: Any) -> float | None:
try:
v = float(bpm)
except (TypeError, ValueError):
return None
if not (_HOLDOVER_BPM_MIN <= v <= _HOLDOVER_BPM_MAX):
return None
return v
def _holdover_interval_s(self, bpm: float) -> float:
return 60.0 / max(_HOLDOVER_BPM_MIN, min(_HOLDOVER_BPM_MAX, float(bpm)))
def _stop_bpm_holdover(self) -> None:
with self._lock:
self._holdover_active = False
self._holdover_stop.set()
t = self._holdover_thread
if t and t.is_alive() and t is not threading.current_thread():
t.join(timeout=2.0)
with self._lock:
if self._holdover_thread is t:
self._holdover_thread = None
def _advance_holdover_bar_phase_locked(self) -> dict:
"""Advance bar phase for one synthetic beat (lock must be held)."""
bpb = max(1, int(self._status.get("beats_per_bar") or 4))
prev = int(self._status.get("bar_beat") or 1)
bar_beat = (prev % bpb) + 1
is_downbeat = bar_beat == 1
bar_readout = f"{bar_beat}/{bpb}"
self._status["bar_beat"] = bar_beat
self._status["is_downbeat"] = is_downbeat
self._status["bar_phase_readout"] = bar_readout
return {
"bar_beat": bar_beat,
"beats_per_bar": bpb,
"is_downbeat": is_downbeat,
"bar_phase_readout": bar_readout,
}
def _emit_holdover_beat(self, bpm: float) -> None:
now = time.time()
with self._lock:
if not self._running or not self._holdover_active:
return
self._advance_holdover_bar_phase_locked()
self._status["last_beat_ts"] = now
self._status["bpm"] = float(bpm)
self._status["beat_type"] = "holdover"
self._status["beat_type_confidence"] = 0.0
self._status["beat_seq"] = int(self._status.get("beat_seq", 0)) + 1
try:
from util import sequence_playback as seq_pb
seq_pb.push_thread_beat()
except Exception as e:
print(f"[audio] holdover beat queue: {e}")
def _holdover_loop(self, bpm: float, started_at: float) -> None:
interval = self._holdover_interval_s(bpm)
while not self._holdover_stop.is_set():
with self._lock:
if not self._running or not self._holdover_active:
return
if (time.time() - started_at) > _HOLDOVER_MAX_S:
self._holdover_active = False
return
last = self._status.get("last_beat_ts")
if last is not None:
try:
delay = max(0.02, float(last) + interval - time.time())
except (TypeError, ValueError):
delay = interval
else:
delay = interval
if self._holdover_stop.wait(delay):
return
self._emit_holdover_beat(bpm)
def _start_bpm_holdover(self, bpm: float) -> None:
bpm_v = self._clamp_holdover_bpm(bpm)
if bpm_v is None:
return
self._stop_bpm_holdover()
self._holdover_stop.clear()
started_at = time.time()
with self._lock:
self._holdover_active = True
self._holdover_thread = threading.Thread(
target=self._holdover_loop,
args=(bpm_v, started_at),
name="audio-bpm-holdover",
daemon=True,
)
t = self._holdover_thread
t.start()
def _process_pending_reset(self, runtime) -> None:
"""Run ``reset_state`` on the audio thread (safe for aubio tempo)."""
with self._lock:
if not self._pending_reset:
return
self._pending_reset = False
try:
runtime.reset_state()
with self._lock:
self._apply_tracking_reset_status()
except Exception as e:
print(f"[audio] pending reset: {e}")
def reset_tracking(self) -> bool:
"""Clear detector tempo history without stopping the input stream."""
holdover_bpm = None
with self._lock:
if not self._running or self._runtime is None:
return False
holdover_bpm = self._clamp_holdover_bpm(self._status.get("bpm"))
self._pending_reset = True
self._apply_tracking_reset_status()
if holdover_bpm is not None:
self._start_bpm_holdover(holdover_bpm)
return True
def _set_error(self, msg):
print(f"[audio] {msg}")
with self._lock:
self._status["error"] = msg
self._status["running"] = False
self._running = False
def anchor_bar_phase(self) -> bool:
"""Mark the current moment as bar beat 1 (downbeat), e.g. after manual sync."""
with self._lock:
rt = self._runtime
if rt is None:
return False
try:
rt.anchor_bar_phase(time.time())
with self._lock:
self._status["bar_beat"] = 1
self._status["is_downbeat"] = True
self._status["bar_phase_readout"] = f"1/{int(self._status.get('beats_per_bar') or 4)}"
self._status["phase_confidence"] = max(
float(self._status.get("phase_confidence") or 0.0), 0.85
)
return True
except Exception as e:
print(f"[audio] anchor_bar_phase: {e}")
return False
def _record_beat(self, bpm, beat_type="unknown", beat_type_confidence=0.0, **phase_fields):
self._stop_bpm_holdover()
now = time.time()
with self._lock:
self._status["last_beat_ts"] = now
self._status["bpm"] = bpm
self._status["beat_type"] = beat_type
self._status["beat_type_confidence"] = float(beat_type_confidence or 0.0)
self._status["beat_seq"] = int(self._status.get("beat_seq", 0)) + 1
if phase_fields.get("bar_beat") is not None:
self._status["bar_beat"] = int(phase_fields["bar_beat"])
if phase_fields.get("beats_per_bar") is not None:
self._status["beats_per_bar"] = int(phase_fields["beats_per_bar"])
if phase_fields.get("is_downbeat") is not None:
self._status["is_downbeat"] = bool(phase_fields["is_downbeat"])
if phase_fields.get("phase_confidence") is not None:
self._status["phase_confidence"] = float(phase_fields["phase_confidence"])
if phase_fields.get("bar_phase_readout"):
self._status["bar_phase_readout"] = str(phase_fields["bar_phase_readout"])
try:
from util import sequence_playback as seq_pb
seq_pb.push_thread_beat()
except Exception as e:
print(f"[audio] sequence beat queue: {e}")
def _run_loop(self, device):
try:
import argparse
import numpy as np
import sounddevice as sd
except Exception as e:
self._set_error(f"audio deps unavailable: {e}")
return
try:
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
beat_detect_path = os.path.join(root_dir, "tests", "beat_detect.py")
spec = importlib.util.spec_from_file_location("beat_detect_runtime", beat_detect_path)
if spec is None or spec.loader is None:
raise RuntimeError("cannot load tests/beat_detect.py")
beat_mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(beat_mod)
if device is None:
try:
device = int(sd.default.device[0])
except Exception:
device = -1
if device is None or device < 0:
raise RuntimeError(
"no default input device; open Audio, pick an input, then Start"
)
dev_info = sd.query_devices(device, "input")
sample_rate = int(dev_info["default_samplerate"])
args = argparse.Namespace(
mode="aubio",
device=device,
sample_rate=sample_rate,
hop_size=256,
win_mult=2,
min_band_hz=45.0,
max_band_hz=180.0,
energy_weight=0.7,
flux_weight=0.3,
threshold_multiplier=1.35,
ema_alpha=0.08,
min_ioi_ms=100.0,
bpm_window=8,
post_url="",
aubio_method="default",
aubio_threshold=0.14,
beats_per_bar=4,
)
runtime = beat_mod.BeatDetectRuntime(args)
runtime.setup(sample_rate=sample_rate)
with self._lock:
self._runtime = runtime
hop_size = runtime.frame_size
audio_q = queue.Queue(maxsize=64)
def callback(indata, frames, _time_info, status):
_ = frames
if status:
print(f"[audio] status: {status}")
mono = np.asarray(indata[:, 0], dtype=np.float32)
if not audio_q.full():
audio_q.put_nowait(mono)
stream = sd.InputStream(
device=device,
channels=1,
samplerate=sample_rate,
blocksize=hop_size,
callback=callback,
)
with self._lock:
self._stream = stream
stream.start()
try:
while not self._stop_event.is_set():
self._process_pending_reset(runtime)
try:
frame = audio_q.get(timeout=0.1)
except queue.Empty:
continue
self._process_pending_reset(runtime)
if frame.shape[0] != hop_size:
if frame.shape[0] > hop_size:
frame = frame[:hop_size]
else:
frame = np.pad(frame, (0, hop_size - frame.shape[0]))
event = runtime.process_frame(frame, now_s=time.time())
if event is None:
continue
bpm = event.get("bpm")
self._record_beat(
bpm,
beat_type=event.get("beat_type", "unknown"),
beat_type_confidence=event.get("beat_type_confidence", 0.0),
bar_beat=event.get("bar_beat"),
beats_per_bar=event.get("beats_per_bar"),
is_downbeat=event.get("is_downbeat"),
phase_confidence=event.get("phase_confidence"),
bar_phase_readout=event.get("bar_phase_readout"),
)
finally:
try:
stream.stop()
except Exception:
pass
try:
stream.close()
except Exception:
pass
with self._lock:
if self._stream is stream:
self._stream = None
except Exception as e:
self._set_error(f"detector failed: {e}")
return
finally:
with self._lock:
self._running = False
self._status["running"] = False
self._runtime = None
# Set from ``main`` so sequence playback can tell real audio from simulated beats.
_shared_beat_detector = None
def set_shared_beat_detector(det):
global _shared_beat_detector
_shared_beat_detector = det
def shared_beat_detector_running():
d = _shared_beat_detector
if d is None:
return False
try:
return bool(d.status().get("running"))
except Exception:
return False
def shared_beat_status_snapshot() -> dict:
"""Thread-safe copy of live detector status, or {} if audio is off."""
d = _shared_beat_detector
if d is None:
return {}
try:
return dict(d.status())
except Exception:
return {}
def anchor_shared_bar_phase() -> bool:
"""Anchor bar phase on the shared detector (no-op if audio is off)."""
d = _shared_beat_detector
if d is None:
return False
try:
return bool(d.anchor_bar_phase())
except Exception:
return False
-96
View File
@@ -1,96 +0,0 @@
"""Persist whether the audio beat detector should be running (survives process restarts)."""
from __future__ import annotations
import json
import os
from typing import Any, Dict, Optional
def _db_path() -> str:
base = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
return os.path.join(base, "db", "audio_run.json")
def coerce_audio_device(device: Any) -> Optional[Any]:
"""Match ``/api/audio/start`` body coercion (None = host default input)."""
if device in ("", None):
return None
try:
return int(device)
except (TypeError, ValueError):
return device
def read_audio_run_state() -> Dict[str, Any]:
path = _db_path()
try:
with open(path, "r", encoding="utf-8") as f:
raw = json.load(f)
except (OSError, json.JSONDecodeError, TypeError):
return {"enabled": False, "device": None}
if not isinstance(raw, dict):
return {
"enabled": False,
"device": None,
"device_override": "",
"device_select": "",
}
enabled = bool(raw.get("enabled"))
dev = raw.get("device", None)
return {
"enabled": enabled,
"device": dev,
"device_override": str(raw.get("device_override") or ""),
"device_select": str(raw.get("device_select") or ""),
}
def write_audio_run_state(
*,
enabled: bool,
device: Any = None,
device_override: str | None = None,
device_select: str | None = None,
) -> None:
"""Write run intent. When ``enabled`` is false, keep device fields from the previous file."""
path = _db_path()
prev = read_audio_run_state()
if enabled:
data = {
"enabled": True,
"device": device,
"device_override": (
str(device_override)
if device_override is not None
else str(prev.get("device_override") or "")
),
"device_select": (
str(device_select)
if device_select is not None
else str(prev.get("device_select") or "")
),
}
if device_select is None and device is not None:
data["device_select"] = str(device)
else:
data = {
"enabled": False,
"device": prev.get("device"),
"device_override": (
str(device_override)
if device_override is not None
else str(prev.get("device_override") or "")
),
"device_select": (
str(device_select)
if device_select is not None
else str(prev.get("device_select") or "")
),
}
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
except OSError as e:
print(f"[audio_run_persist] save failed: {e!r}")
-639
View File
@@ -1,639 +0,0 @@
"""Server-side routing of audio beats to LED drivers (no browser required)."""
from __future__ import annotations
import asyncio
import json
import os
import threading
from typing import Any, Dict, List, Optional, Set, Tuple
_route_lock = threading.Lock()
# Per-lane manual routes: key ``-1`` = legacy single-route (preset push / UI); keys ``0..n`` =
# zone sequence lanes so every manual lane gets its own stride counter and wire.
_lane_manual: Dict[int, Dict[str, Any]] = {}
# Public mirror for ``get_beat_route`` / header UI (derived from lane table).
_beat_route: Dict[str, Any] = {
"enabled": False,
"device_names": [],
"wire_preset_id": "2",
"is_manual": False,
"pattern": "",
"manual_beat_n": 1,
}
_beat_counter: int = 0
_preset_session_beats: int = 0
_main_loop: Optional[asyncio.AbstractEventLoop] = None
def set_beat_route_main_loop(loop: asyncio.AbstractEventLoop) -> None:
global _main_loop
_main_loop = loop
def _pick_display_lane_key() -> Optional[int]:
"""Lane key used for header stride readout (prefer sequence lane 0)."""
if not _lane_manual:
return None
if 0 in _lane_manual:
return 0
seq_keys = [k for k in _lane_manual if isinstance(k, int) and k >= 0]
if seq_keys:
return min(seq_keys)
if -1 in _lane_manual:
return -1
return min(_lane_manual.keys())
def _sync_public_beat_route_from_lane_table() -> None:
"""Mirror ``_lane_manual`` into legacy ``_beat_route`` shape for API consumers."""
global _beat_route, _beat_counter
pick = _pick_display_lane_key()
if pick is None:
_beat_route = {
"enabled": False,
"device_names": [],
"wire_preset_id": "2",
"is_manual": False,
"pattern": "",
"manual_beat_n": 1,
}
_beat_counter = 0
return
e = _lane_manual[pick]
_beat_route = {
"enabled": True,
"device_names": list(e.get("device_names") or []),
"wire_preset_id": str(e.get("wire_preset_id") or "2"),
"is_manual": True,
"pattern": str(e.get("pattern") or ""),
"manual_beat_n": int(e.get("manual_beat_n") or 1),
}
_beat_counter = int(e.get("beat_counter", 0))
def update_beat_route(payload: Dict[str, Any]) -> None:
"""Internal: set or clear routing from explicit fields (tests / future APIs)."""
global _lane_manual, _beat_route, _beat_counter, _preset_session_beats
if not isinstance(payload, dict):
return
with _route_lock:
if payload.get("enabled") is False:
_lane_manual.clear()
_beat_route = {
**_beat_route,
"enabled": False,
"is_manual": False,
"device_names": [],
}
_beat_counter = 0
_preset_session_beats = 0
return
old = dict(_beat_route)
names = payload.get("device_names")
if not isinstance(names, list):
names = []
try:
n_raw = int(payload.get("manual_beat_n", 1))
except (TypeError, ValueError):
n_raw = 1
manual_n = max(1, min(64, n_raw))
new_wire = str(payload.get("wire_preset_id") or "2")
old_wire = str(old.get("wire_preset_id") or "2")
if not old.get("enabled") or old_wire != new_wire:
_preset_session_beats = 0
clean_names = [str(n).strip() for n in names if str(n).strip()]
_lane_manual.clear()
_lane_manual[-1] = {
"device_names": clean_names,
"wire_preset_id": new_wire,
"pattern": str(payload.get("pattern") or "").strip(),
"manual_beat_n": manual_n,
"beat_counter": 0,
}
_sync_public_beat_route_from_lane_table()
def get_beat_route() -> Dict[str, Any]:
with _route_lock:
return dict(_beat_route)
def manual_beat_stride_status() -> Dict[str, Any]:
"""Audio-beat stride for a live manual preset (not sequence). For UI readout with BPM.
``beat_in_stride`` is always in ``1..stride_n`` when ``active`` (1-based within the stride).
With multiple sequence manual lanes, reflects lane 0 (or the smallest lane index).
"""
with _route_lock:
pick = _pick_display_lane_key()
if pick is None or pick not in _lane_manual:
wid = str(_beat_route.get("wire_preset_id") or "").strip()
return {"active": False, "preset_session_beats": 0, "wire_preset_id": wid}
e = _lane_manual[pick]
c = int(e.get("beat_counter", 0))
psb = int(_preset_session_beats)
wid = str(e.get("wire_preset_id") or "").strip()
try:
n = int(e.get("manual_beat_n") or 1)
except (TypeError, ValueError):
n = 1
n = max(1, min(64, n))
if c <= 0:
return {
"active": True,
"beat_in_stride": 1,
"stride_n": n,
"preset_session_beats": psb,
"wire_preset_id": wid,
}
beat_in_stride = ((c - 1) % n) + 1
return {
"active": True,
"beat_in_stride": beat_in_stride,
"stride_n": n,
"preset_session_beats": psb,
"wire_preset_id": wid,
}
def _coerce_manual_beat_n(body: Any) -> int:
"""Beats between audio-triggered selects (led-controller only); default 1 = every beat."""
if not isinstance(body, dict):
return 1
raw = body.get("manual_beat_n")
if raw is None:
return 1
try:
n = int(raw)
except (TypeError, ValueError):
return 1
return max(1, min(64, n))
def _coerce_auto_from_body(body: Any) -> bool:
"""Match JS ``coercePresetAuto`` / ``build_preset_dict`` (default: auto-run)."""
if not isinstance(body, dict):
return True
raw = body.get("auto", body.get("a", True))
if isinstance(raw, bool):
return raw
if raw is None:
return True
if isinstance(raw, int):
return raw != 0
if isinstance(raw, str):
lowered = raw.strip().lower()
if lowered in ("false", "0", "no", "off"):
return False
if lowered in ("true", "1", "yes", "on"):
return True
return True
def _registry_names_for_macs(macs: Optional[List[str]]) -> List[str]:
"""Resolve push ``targets`` MAC list to registry device names (order preserved, de-duplicated)."""
if not macs:
return []
from models.device import Device, normalize_mac
devices = Device()
out: List[str] = []
seen: Set[str] = set()
for raw in macs:
m = normalize_mac(str(raw))
if not m:
continue
doc = devices.read(m) or {}
nm = str(doc.get("name") or "").strip()
if nm and nm not in seen:
seen.add(nm)
out.append(nm)
return out
def _single_manual_wire_preset(
merged_presets: Dict[str, Any],
) -> tuple[Optional[str], Optional[Dict[str, Any]]]:
"""If exactly one manual (non-auto) preset is present, return its wire id and body."""
manual: List[tuple[str, Dict[str, Any]]] = []
for wid, body in merged_presets.items():
if not isinstance(body, dict):
continue
if _coerce_auto_from_body(body):
continue
manual.append((str(wid).strip(), body))
if len(manual) != 1:
return None, None
return manual[0][0], manual[0][1]
def _apply_manual_beat_route(
device_names: List[str],
wire_preset_id: str,
preset_body: Any,
) -> None:
"""Enable audio→driver routing for one manual preset (clears all lanes, including sequence)."""
global _lane_manual
if not device_names:
with _route_lock:
_lane_manual.clear()
_sync_public_beat_route_from_lane_table()
return
if not isinstance(preset_body, dict):
with _route_lock:
_lane_manual.clear()
_sync_public_beat_route_from_lane_table()
return
if _coerce_auto_from_body(preset_body):
with _route_lock:
_lane_manual.clear()
_sync_public_beat_route_from_lane_table()
return
pattern = str(preset_body.get("pattern") or preset_body.get("p") or "").strip()
if pattern and not _pattern_supports_manual(pattern):
with _route_lock:
_lane_manual.clear()
_sync_public_beat_route_from_lane_table()
return
names = [str(n).strip() for n in device_names if str(n).strip()]
with _route_lock:
_lane_manual.clear()
_lane_manual[-1] = {
"device_names": names,
"wire_preset_id": str(wire_preset_id).strip(),
"pattern": pattern,
"manual_beat_n": _coerce_manual_beat_n(preset_body),
"beat_counter": 0,
}
_sync_public_beat_route_from_lane_table()
def _apply_manual_beat_route_standalone_overlay(
device_names: List[str],
wire_preset_id: str,
preset_body: Any,
) -> None:
"""Register manual beat routing on lane ``-1`` only, keeping sequence lanes ``0..n`` intact."""
global _lane_manual
if not device_names:
with _route_lock:
_lane_manual.pop(-1, None)
_sync_public_beat_route_from_lane_table()
return
if not isinstance(preset_body, dict):
with _route_lock:
_lane_manual.pop(-1, None)
_sync_public_beat_route_from_lane_table()
return
if _coerce_auto_from_body(preset_body):
with _route_lock:
_lane_manual.pop(-1, None)
_sync_public_beat_route_from_lane_table()
return
pattern = str(preset_body.get("pattern") or preset_body.get("p") or "").strip()
if pattern and not _pattern_supports_manual(pattern):
with _route_lock:
_lane_manual.pop(-1, None)
_sync_public_beat_route_from_lane_table()
return
names = [str(n).strip() for n in device_names if str(n).strip()]
with _route_lock:
if _sequence_lane_covers_standalone_overlay(names, str(wire_preset_id).strip()):
_lane_manual.pop(-1, None)
_sync_public_beat_route_from_lane_table()
return
_lane_manual[-1] = {
"device_names": names,
"wire_preset_id": str(wire_preset_id).strip(),
"pattern": pattern,
"manual_beat_n": _coerce_manual_beat_n(preset_body),
"beat_counter": 0,
}
_sync_public_beat_route_from_lane_table()
def set_sequence_manual_lane_route(
lane_index: int,
device_names: List[str],
wire_preset_id: str,
preset_body: Any,
) -> None:
"""Register or update one sequence lane's manual beat route (parallel lanes, independent strides)."""
global _lane_manual
names = [str(n).strip() for n in (device_names or []) if str(n).strip()]
if not names or not isinstance(preset_body, dict) or _coerce_auto_from_body(preset_body):
with _route_lock:
if lane_index in _lane_manual:
del _lane_manual[lane_index]
_sync_public_beat_route_from_lane_table()
return
pattern = str(preset_body.get("pattern") or preset_body.get("p") or "").strip()
if pattern and not _pattern_supports_manual(pattern):
with _route_lock:
if lane_index in _lane_manual:
del _lane_manual[lane_index]
_sync_public_beat_route_from_lane_table()
return
mn = _coerce_manual_beat_n(preset_body)
wid = str(wire_preset_id).strip()
with _route_lock:
old = _lane_manual.get(lane_index)
bc = 0
if (
old
and str(old.get("wire_preset_id") or "") == wid
and int(old.get("manual_beat_n") or 1) == mn
and set(old.get("device_names") or []) == set(names)
):
bc = int(old.get("beat_counter", 0))
_lane_manual[lane_index] = {
"device_names": names,
"wire_preset_id": wid,
"pattern": pattern,
"manual_beat_n": mn,
"beat_counter": bc,
}
overlay = _lane_manual.get(-1)
if overlay and _lane_route_targets_key(names, wid) == _lane_route_targets_key(
overlay.get("device_names") or [], str(overlay.get("wire_preset_id") or "")
):
_lane_manual.pop(-1, None)
_sync_public_beat_route_from_lane_table()
def clear_sequence_manual_lane_route(lane_index: int) -> None:
"""Remove beat routing for one sequence lane (e.g. step switched to auto)."""
global _lane_manual
with _route_lock:
if lane_index in _lane_manual:
del _lane_manual[lane_index]
_sync_public_beat_route_from_lane_table()
def _lane_route_targets_key(device_names: List[str], wire_preset_id: str) -> Tuple[Tuple[str, ...], str]:
names = tuple(sorted({str(n).strip() for n in (device_names or []) if str(n).strip()}))
return names, str(wire_preset_id or "").strip()
def _sequence_lane_covers_standalone_overlay(device_names: List[str], wire_preset_id: str) -> bool:
"""True when a sequence lane (0..n) already routes the same device(s) and wire preset."""
key = _lane_route_targets_key(device_names, wire_preset_id)
for lane_key, entry in _lane_manual.items():
if not isinstance(lane_key, int) or lane_key < 0:
continue
other = _lane_route_targets_key(
entry.get("device_names") or [], str(entry.get("wire_preset_id") or "")
)
if other == key:
return True
return False
def mark_manual_select_sent_for_targets(
device_names: List[str], wire_preset_id: str
) -> None:
"""A ``select`` was just sent for these targets; skip one duplicate on the next beat."""
key = _lane_route_targets_key(device_names, wire_preset_id)
with _route_lock:
for entry in _lane_manual.values():
if not isinstance(entry, dict):
continue
other = _lane_route_targets_key(
entry.get("device_names") or [], str(entry.get("wire_preset_id") or "")
)
if other == key:
entry["suppress_next_notify"] = True
def mark_sequence_manual_lane_select_sent(lane_index: int) -> None:
"""A ``select`` was just sent for this lane; skip one duplicate on the next beat."""
with _route_lock:
e = _lane_manual.get(lane_index)
if e is not None:
e["suppress_next_notify"] = True
def sync_beat_route_from_push_sequence(
sequence: List[Any],
target_macs: Optional[List[str]] = None,
*,
preserve_parallel_lane_routes: bool = False,
) -> None:
"""
Update beat routing from a ``/presets/push`` body ``sequence`` (list of v1 dicts).
With a ``select`` map: use its keys as device names (existing behaviour).
Without ``select`` (e.g. manual preset loaded without immediate select): if ``target_macs``
is set and the merged ``presets`` contain exactly one manual preset, enable routing using
registry names for those MACs so the first advance is on the next audio beat.
When ``preserve_parallel_lane_routes`` is true (e.g. zone sequence playback is active), an
auto preset in ``select`` does not clear manual routing — other lanes still receive
``notify_beat_detected``. A manual preset in ``select`` is applied on lane ``-1`` only so
sequence lanes ``0..n`` keep their stride counters and wire ids.
"""
merged_presets: Dict[str, Any] = {}
last_select: Optional[Dict[str, Any]] = None
for item in sequence:
if isinstance(item, str):
try:
item = json.loads(item)
except (TypeError, ValueError):
continue
if not isinstance(item, dict) or item.get("v") != "1":
continue
pr = item.get("presets")
if isinstance(pr, dict):
merged_presets.update(pr)
sel = item.get("select")
if isinstance(sel, dict) and sel:
last_select = sel
if last_select:
device_names = [str(k).strip() for k in last_select.keys() if str(k).strip()]
if not device_names:
if not preserve_parallel_lane_routes:
update_beat_route({"enabled": False})
return
wire_ids: Set[str] = set()
for name in device_names:
val = last_select.get(name)
if isinstance(val, list) and val:
wire_ids.add(str(val[0]).strip())
elif val is not None:
wire_ids.add(str(val).strip())
if len(wire_ids) != 1:
if not preserve_parallel_lane_routes:
update_beat_route({"enabled": False})
return
wire_preset_id = wire_ids.pop()
preset_body = merged_presets.get(wire_preset_id)
if preset_body is None:
for k, v in merged_presets.items():
if str(k).strip() == wire_preset_id:
preset_body = v
break
if preset_body is None:
if not preserve_parallel_lane_routes:
update_beat_route({"enabled": False})
return
if _coerce_auto_from_body(preset_body):
if not preserve_parallel_lane_routes:
update_beat_route({"enabled": False})
return
if preserve_parallel_lane_routes:
_apply_manual_beat_route_standalone_overlay(
device_names, wire_preset_id, preset_body
)
else:
_apply_manual_beat_route(device_names, wire_preset_id, preset_body)
mark_manual_select_sent_for_targets(device_names, wire_preset_id)
return
wire_id, body = _single_manual_wire_preset(merged_presets)
if wire_id and body is not None:
names = _registry_names_for_macs(target_macs)
if preserve_parallel_lane_routes:
_apply_manual_beat_route_standalone_overlay(names, wire_id, body)
else:
_apply_manual_beat_route(names, wire_id, body)
return
if not preserve_parallel_lane_routes:
update_beat_route({"enabled": False})
def _pattern_supports_manual(pattern_key: str) -> bool:
if not pattern_key:
return True
try:
here = os.path.dirname(os.path.abspath(__file__))
root = os.path.abspath(os.path.join(here, "..", ".."))
path = os.path.join(root, "db", "pattern.json")
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
meta = data.get(pattern_key)
if meta is None:
meta = data.get(pattern_key.lower())
if not isinstance(meta, dict):
return True
return meta.get("supports_manual") is not False
except OSError:
return True
def remap_beat_route_device_name(old_name: str, new_name: str) -> None:
"""Update cached audio-beat target names after a device registry rename."""
global _lane_manual
o = str(old_name or "").strip()
n = str(new_name or "").strip()
if not o or not n or o == n:
return
with _route_lock:
any_changed = False
for e in _lane_manual.values():
names = e.get("device_names") or []
if not isinstance(names, list):
continue
new_list: List[str] = []
row_changed = False
for item in names:
if str(item).strip() == o:
new_list.append(n)
row_changed = True
else:
new_list.append(str(item))
if row_changed:
e["device_names"] = new_list
any_changed = True
if any_changed:
_sync_public_beat_route_from_lane_table()
async def _deliver_select(device_names: List[str], wire_preset_id: str) -> None:
from models.device import Device
from models.device import resolve_device_mac_for_select_routing
from models.transport import get_current_sender
from util.driver_delivery import deliver_json_messages
sender = get_current_sender()
if not sender:
return
devices = Device()
seen_macs: List[str] = []
seen_set: Set[str] = set()
for n in device_names:
mac = resolve_device_mac_for_select_routing(devices, n)
if mac and mac not in seen_set:
seen_set.add(mac)
seen_macs.append(mac)
if not seen_macs:
return
select: Dict[str, Any] = {}
for mac in seen_macs:
doc = devices.read(mac) or {}
nm = str(doc.get("name") or "").strip()
if nm:
select[nm] = [wire_preset_id]
if not select:
return
msg = json.dumps({"v": "1", "select": select}, separators=(",", ":"))
try:
await deliver_json_messages(sender, [msg], seen_macs, devices, delay_s=0.05)
except Exception as e:
print(f"[beat-route] deliver failed: {e}")
async def _deliver_select_batch(pairs: List[Tuple[List[str], str]]) -> None:
for names, pid in pairs:
await _deliver_select(names, pid)
def notify_beat_detected() -> None:
"""Invoked from the audio thread when a beat is detected."""
global _preset_session_beats
work: List[Tuple[List[str], str]] = []
with _route_lock:
if not _lane_manual:
return
work = []
seen_targets: Set[Tuple[Tuple[str, ...], str]] = set()
for key in sorted(_lane_manual.keys()):
e = _lane_manual[key]
names = e.get("device_names") or []
if not isinstance(names, list) or not names:
continue
pattern = str(e.get("pattern") or "")
if pattern and not _pattern_supports_manual(pattern):
continue
if e.pop("suppress_next_notify", False):
continue
try:
n = int(e.get("manual_beat_n") or 1)
except (TypeError, ValueError):
n = 1
n = max(1, min(64, n))
e["beat_counter"] = int(e.get("beat_counter", 0)) + 1
c = int(e["beat_counter"])
if (c - 1) % n != 0:
continue
wire = str(e.get("wire_preset_id") or "2")
target_key = _lane_route_targets_key(names, wire)
if target_key in seen_targets:
continue
seen_targets.add(target_key)
work.append((list(names), wire))
if work:
_preset_session_beats += 1
if not work:
return
loop = _main_loop
if loop is None:
return
try:
asyncio.run_coroutine_threadsafe(_deliver_select_batch(work), loop)
except Exception as e:
print(f"[beat-route] schedule failed: {e}")
+1 -3
View File
@@ -43,8 +43,6 @@ import json
import struct
from typing import Any, Dict, List, Optional, Tuple
from util.espnow_message import wire_n6
BINARY_ENVELOPE_VERSION_1 = 1
BINARY_ENVELOPE_VERSION_2 = 2
HEADER_LEN = 5
@@ -110,7 +108,7 @@ def _pack_preset_dict(name: str, preset: Dict[str, Any]) -> bytes:
n3 = _clamp_i16(preset.get("n3", 0))
n4 = _clamp_i16(preset.get("n4", 0))
n5 = _clamp_i16(preset.get("n5", 0))
n6 = _clamp_i16(wire_n6(preset))
n6 = _clamp_i16(preset.get("n6", 0))
parts.append(
struct.pack(
"<HBBhhhhhh",
-86
View File
@@ -1,86 +0,0 @@
"""
Combine global, group, device (and optional zone) brightness into one 0–255 wire value.
Formula: ``(f1/255) * (f2/255) * ... * (fn/255) * 255`` with integer rounding — one ``b`` sent to the driver.
"""
from __future__ import annotations
from models.device import normalize_mac
def clamp255(value) -> int:
try:
v = int(value)
except (TypeError, ValueError):
return 255
return max(0, min(255, v))
def multiply_brightness_factors(factors: list) -> int:
"""Product ``(f1/255)*(f2/255)*...*255``; each factor clamped to 0..255."""
if not factors:
return 255
fs = [clamp255(f) for f in factors]
if len(fs) == 1:
return fs[0]
num = 1
for f in fs:
num *= f
den = 255 ** (len(fs) - 1)
return max(0, min(255, (num + den // 2) // den))
def _mac_in_device_list(raw_list, target_mac: str) -> bool:
tm = normalize_mac(target_mac)
if not tm:
return False
if not isinstance(raw_list, list):
return False
for raw in raw_list:
if normalize_mac(str(raw)) == tm:
return True
return False
def effective_brightness_for_mac(
settings_obj,
groups_model,
devices_model,
mac: str,
*,
zone_brightness=None,
) -> int:
"""
Factors (each 0..255): Pi **global_brightness**, each group's **output_brightness**
(neutral 255 if the device is in no group), device **output_brightness** (default 255),
optional **zone_brightness** from the zone slider when applying live.
"""
m = normalize_mac(mac)
if not m:
return 255
g_global = clamp255(settings_obj.get("global_brightness", 255))
dev_doc = devices_model.read(m)
if dev_doc is not None and dev_doc.get("output_brightness") is not None:
d_b = clamp255(dev_doc.get("output_brightness"))
else:
d_b = 255
group_factors = []
for _gid, gdoc in groups_model.items():
if not isinstance(gdoc, dict):
continue
if not _mac_in_device_list(gdoc.get("devices"), m):
continue
group_factors.append(clamp255(gdoc.get("output_brightness", 255)))
if not group_factors:
group_factors = [255]
factors = [g_global, *group_factors, d_b]
if zone_brightness is not None:
factors.append(clamp255(zone_brightness))
return multiply_brightness_factors(factors)
+7 -80
View File
@@ -78,64 +78,13 @@ def build_select_message(device_name, preset_name, step=None):
return {device_name: select_list}
def _hex_from_background_raw(bg_raw):
"""Coerce ``background`` / ``bg`` field to a ``#RRGGBB`` string (driver wire format)."""
if isinstance(bg_raw, str):
bg = bg_raw if bg_raw.startswith("#") else f"#{bg_raw}"
return bg
if isinstance(bg_raw, (list, tuple)) and len(bg_raw) == 3:
return f"#{int(bg_raw[0]):02x}{int(bg_raw[1]):02x}{int(bg_raw[2]):02x}"
return "#000000"
def resolve_preset_background_hex(preset_data, palette_colors=None):
"""
Resolved background as ``#RRGGBB``. When ``palette_colors`` is a non-empty list and
``background_palette_ref`` is set, uses that palette index; otherwise stored ``background`` / ``bg``.
"""
if not isinstance(preset_data, dict):
return "#000000"
pal = list(palette_colors) if isinstance(palette_colors, list) else []
ref = preset_data.get("background_palette_ref", preset_data.get("backgroundPaletteRef"))
if pal and ref is not None:
try:
idx = int(ref)
except (TypeError, ValueError):
idx = None
else:
if isinstance(idx, int) and 0 <= idx < len(pal):
c = pal[idx]
if isinstance(c, str) and c.strip().startswith("#"):
s = c.strip()
if len(s) == 7 and all(ch in "0123456789abcdefABCDEF" for ch in s[1:]):
return s.upper()
bg_raw = preset_data.get("background", preset_data.get("bg", "#000000"))
return _hex_from_background_raw(bg_raw)
def wire_n6(preset_data, default=0):
"""Resolve style mode for the wire (``n6``); preset may store ``mode`` or ``n6``."""
if not isinstance(preset_data, dict):
return default
if preset_data.get("mode") is not None:
try:
return max(0, int(preset_data["mode"]))
except (TypeError, ValueError):
pass
try:
return max(0, int(preset_data.get("n6", default) or 0))
except (TypeError, ValueError):
return default
def build_preset_dict(preset_data, palette_colors=None):
def build_preset_dict(preset_data):
"""
Convert preset data to API-compliant format.
Args:
preset_data: Dictionary with preset fields (may include name, pattern, colors, etc.)
palette_colors: Optional list of ``#RRGGBB`` strings for ``background_palette_ref`` resolution.
Returns:
Dictionary with preset in API-compliant format (without name field)
@@ -170,53 +119,31 @@ def build_preset_dict(preset_data, palette_colors=None):
else:
colors = ["#FFFFFF"]
def _coerce_auto(raw):
if isinstance(raw, bool):
return raw
if raw is None:
return True
if isinstance(raw, int):
return raw != 0
if isinstance(raw, str):
lowered = raw.strip().lower()
if lowered in ("false", "0", "no", "off"):
return False
if lowered in ("true", "1", "yes", "on"):
return True
return True
auto_raw = preset_data.get("auto", preset_data.get("a", True))
auto_bool = _coerce_auto(auto_raw)
bg = resolve_preset_background_hex(preset_data, palette_colors)
# Build payload using the short keys expected by led-driver
preset = {
"p": preset_data.get("pattern", preset_data.get("p", "off")),
"c": colors,
"d": preset_data.get("delay", preset_data.get("d", 100)),
"b": preset_data.get("brightness", preset_data.get("b", preset_data.get("br", 127))),
"a": auto_bool,
"bg": bg,
"a": preset_data.get("auto", preset_data.get("a", True)),
"n1": preset_data.get("n1", 0),
"n2": preset_data.get("n2", 0),
"n3": preset_data.get("n3", 0),
"n4": preset_data.get("n4", 0),
"n5": preset_data.get("n5", 0),
"n6": wire_n6(preset_data),
"n6": preset_data.get("n6", 0)
}
return preset
def build_presets_dict(presets_data, palette_colors=None):
def build_presets_dict(presets_data):
"""
Convert multiple presets to API-compliant format.
Args:
presets_data: Dictionary mapping preset names to preset data
palette_colors: Optional list of ``#RRGGBB`` strings for background palette ref resolution.
Returns:
Dictionary mapping preset names to API-compliant preset objects
@@ -236,7 +163,7 @@ def build_presets_dict(presets_data, palette_colors=None):
"""
result = {}
for preset_name, preset_data in presets_data.items():
result[preset_name] = build_preset_dict(preset_data, palette_colors)
result[preset_name] = build_preset_dict(preset_data)
return result
-441
View File
@@ -1,441 +0,0 @@
"""Export/import profile bundles (profile, zones, presets, sequences, palette)."""
from __future__ import annotations
import copy
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
BUNDLE_VERSION = 1
KIND_PROFILE = "profile"
KIND_PRESET = "preset"
KIND_SEQUENCE = "sequence"
def _allocate_id(model, cache: Dict[str, int]) -> str:
if "next" not in cache:
max_id = max((int(k) for k in model.keys() if str(k).isdigit()), default=0)
cache["next"] = max_id + 1
next_id = str(cache["next"])
cache["next"] += 1
return next_id
def _palette_colors(palette_model, palette_id) -> List:
if not palette_id:
return []
try:
colors = palette_model.read(str(palette_id))
except Exception:
colors = None
if isinstance(colors, list):
return list(colors)
if isinstance(colors, dict) and isinstance(colors.get("colors"), list):
return list(colors["colors"])
return []
def _walk_preset_refs(value, out: Set[str]) -> None:
if isinstance(value, list):
for item in value:
_walk_preset_refs(item, out)
elif value is not None and value != "":
out.add(str(value))
def _preset_ids_in_zone(zone: Dict[str, Any]) -> Set[str]:
ids: Set[str] = set()
if not isinstance(zone, dict):
return ids
_walk_preset_refs(zone.get("presets"), ids)
_walk_preset_refs(zone.get("presets_flat"), ids)
if zone.get("default_preset") not in (None, ""):
ids.add(str(zone["default_preset"]))
return ids
def _preset_ids_in_sequence(seq: Dict[str, Any]) -> Set[str]:
ids: Set[str] = set()
if not isinstance(seq, dict):
return ids
for lane in seq.get("lanes") or []:
if not isinstance(lane, list):
continue
for step in lane:
if isinstance(step, dict) and step.get("preset_id") not in (None, ""):
ids.add(str(step["preset_id"]))
for step in seq.get("steps") or []:
if isinstance(step, dict) and step.get("preset_id") not in (None, ""):
ids.add(str(step["preset_id"]))
return ids
def _map_preset_container(
value,
id_map: Dict[str, str],
preset_cache: Dict[str, int],
new_profile_id: str,
new_presets: Dict[str, Dict[str, Any]],
presets_model,
) -> Any:
if isinstance(value, list):
return [
_map_preset_container(v, id_map, preset_cache, new_profile_id, new_presets, presets_model)
for v in value
]
if value is None:
return None
preset_id = str(value)
if preset_id in id_map:
return id_map[preset_id]
preset_data = presets_model.read(preset_id)
if not preset_data:
return None
new_preset_id = _allocate_id(presets_model, preset_cache)
clone_data = dict(preset_data)
clone_data["profile_id"] = str(new_profile_id)
new_presets[new_preset_id] = clone_data
id_map[preset_id] = new_preset_id
return new_preset_id
def _map_sequence_lanes(
seq: Dict[str, Any],
preset_id_map: Dict[str, str],
) -> Dict[str, Any]:
out = copy.deepcopy(seq)
lanes = out.get("lanes")
if isinstance(lanes, list):
for lane in lanes:
if not isinstance(lane, list):
continue
for step in lane:
if not isinstance(step, dict):
continue
pid = step.get("preset_id")
if pid is not None and str(pid) in preset_id_map:
step["preset_id"] = preset_id_map[str(pid)]
steps = out.get("steps")
if isinstance(steps, list):
for step in steps:
if not isinstance(step, dict):
continue
pid = step.get("preset_id")
if pid is not None and str(pid) in preset_id_map:
step["preset_id"] = preset_id_map[str(pid)]
return out
def export_profile_bundle(
profile_id: str,
profiles_model,
zones_model,
presets_model,
sequences_model,
palette_model,
) -> Dict[str, Any]:
source = profiles_model.read(profile_id)
if not source:
raise ValueError("Profile not found")
zone_ids = source.get("zones")
if not isinstance(zone_ids, list) or not zone_ids:
zone_ids = source.get("zone_order") or []
zone_ids = [str(z) for z in zone_ids if z is not None]
zones_out: Dict[str, Any] = {}
preset_ids: Set[str] = set()
sequence_ids: Set[str] = set()
for zid in zone_ids:
zone = zones_model.read(zid)
if not zone:
continue
zones_out[zid] = copy.deepcopy(zone)
preset_ids |= _preset_ids_in_zone(zone)
for sid in zone.get("sequence_ids") or []:
if sid is not None and str(sid).strip():
sequence_ids.add(str(sid))
sequences_out: Dict[str, Any] = {}
for sid in sequence_ids:
seq = sequences_model.read(sid)
if not seq or str(seq.get("profile_id")) != str(profile_id):
continue
sequences_out[sid] = copy.deepcopy(seq)
preset_ids |= _preset_ids_in_sequence(seq)
presets_out: Dict[str, Any] = {}
for pid in preset_ids:
pdata = presets_model.read(pid)
if pdata and str(pdata.get("profile_id")) == str(profile_id):
presets_out[pid] = copy.deepcopy(pdata)
profile_doc = copy.deepcopy(source)
profile_doc.pop("palette", None)
return {
"version": BUNDLE_VERSION,
"kind": KIND_PROFILE,
"profile": profile_doc,
"palette": {"colors": _palette_colors(palette_model, source.get("palette_id"))},
"zones": zones_out,
"presets": presets_out,
"sequences": sequences_out,
}
def import_profile_bundle(
bundle: Dict[str, Any],
profiles_model,
zones_model,
presets_model,
sequences_model,
palette_model,
*,
name: Optional[str] = None,
) -> Tuple[str, Dict[str, Any]]:
if not isinstance(bundle, dict):
raise ValueError("Invalid bundle")
if bundle.get("version") not in (BUNDLE_VERSION, str(BUNDLE_VERSION)):
raise ValueError("Unsupported bundle version")
if bundle.get("kind") not in (KIND_PROFILE, None):
raise ValueError("Not a profile bundle")
source_profile = bundle.get("profile")
if not isinstance(source_profile, dict):
raise ValueError("Bundle missing profile")
source_name = source_profile.get("name") or "Imported profile"
new_name = (name or source_name).strip() or source_name
profile_type = source_profile.get("type", "zones")
profile_cache: Dict[str, int] = {}
palette_cache: Dict[str, int] = {}
zone_cache: Dict[str, int] = {}
preset_cache: Dict[str, int] = {}
sequence_cache: Dict[str, int] = {}
new_profile_id = _allocate_id(profiles_model, profile_cache)
new_palette_id = _allocate_id(palette_model, palette_cache)
palette_in = bundle.get("palette") or {}
palette_colors = palette_in.get("colors") if isinstance(palette_in, dict) else []
if not isinstance(palette_colors, list):
palette_colors = []
preset_id_map: Dict[str, str] = {}
new_presets: Dict[str, Dict[str, Any]] = {}
new_zones: Dict[str, Dict[str, Any]] = {}
new_sequences: Dict[str, Dict[str, Any]] = {}
sequence_id_map: Dict[str, str] = {}
zones_in = bundle.get("zones") if isinstance(bundle.get("zones"), dict) else {}
presets_in = bundle.get("presets") if isinstance(bundle.get("presets"), dict) else {}
sequences_in = bundle.get("sequences") if isinstance(bundle.get("sequences"), dict) else {}
for old_pid, pdata in presets_in.items():
if not isinstance(pdata, dict):
continue
new_pid = _allocate_id(presets_model, preset_cache)
clone = copy.deepcopy(pdata)
clone["profile_id"] = str(new_profile_id)
new_presets[new_pid] = clone
preset_id_map[str(old_pid)] = new_pid
for old_sid, sdata in sequences_in.items():
if not isinstance(sdata, dict):
continue
new_sid = _allocate_id(sequences_model, sequence_cache)
clone = _map_sequence_lanes(sdata, preset_id_map)
clone["profile_id"] = str(new_profile_id)
new_sequences[new_sid] = clone
sequence_id_map[str(old_sid)] = new_sid
source_zone_order = source_profile.get("zones")
if not isinstance(source_zone_order, list):
source_zone_order = list(zones_in.keys())
cloned_zone_ids: List[str] = []
for old_zid in source_zone_order:
zone = zones_in.get(str(old_zid))
if not isinstance(zone, dict):
continue
new_zid = _allocate_id(zones_model, zone_cache)
clone_data: Dict[str, Any] = {
"name": zone.get("name") or f"Zone {old_zid}",
"names": list(zone.get("names") or []),
}
mapped_presets = _map_preset_container(
zone.get("presets"),
preset_id_map,
preset_cache,
new_profile_id,
new_presets,
presets_model,
)
if mapped_presets is not None:
clone_data["presets"] = mapped_presets
extra = {
k: v
for k, v in zone.items()
if k not in ("name", "names", "presets")
}
if "presets_flat" in extra:
extra["presets_flat"] = _map_preset_container(
extra.get("presets_flat"),
preset_id_map,
preset_cache,
new_profile_id,
new_presets,
presets_model,
)
if "default_preset" in extra and extra["default_preset"] is not None:
old_dp = str(extra["default_preset"])
if old_dp in preset_id_map:
extra["default_preset"] = preset_id_map[old_dp]
if "sequence_ids" in extra and isinstance(extra.get("sequence_ids"), list):
extra["sequence_ids"] = [
sequence_id_map.get(str(s), str(s))
for s in extra["sequence_ids"]
if s is not None
]
clone_data.update(extra)
new_zones[new_zid] = clone_data
cloned_zone_ids.append(new_zid)
new_profile_data = {
"name": new_name,
"type": profile_type,
"zones": cloned_zone_ids,
"scenes": list(source_profile.get("scenes", []))
if isinstance(source_profile.get("scenes"), list)
else [],
"palette_id": str(new_palette_id),
}
palette_model[str(new_palette_id)] = list(palette_colors)
for pid, pdata in new_presets.items():
presets_model[pid] = pdata
for zid, zdata in new_zones.items():
zones_model[zid] = zdata
for sid, sdata in new_sequences.items():
sequences_model[sid] = sdata
profiles_model[str(new_profile_id)] = new_profile_data
palette_model.save()
presets_model.save()
zones_model.save()
sequences_model.save()
profiles_model.save()
return str(new_profile_id), new_profile_data
def export_preset_bundle(preset_id: str, presets_model) -> Dict[str, Any]:
preset = presets_model.read(preset_id)
if not preset:
raise ValueError("Preset not found")
return {
"version": BUNDLE_VERSION,
"kind": KIND_PRESET,
"preset": copy.deepcopy(preset),
}
def import_preset_bundle(
bundle: Dict[str, Any],
presets_model,
profile_id: str,
) -> Tuple[str, Dict[str, Any]]:
if not isinstance(bundle, dict):
raise ValueError("Invalid bundle")
if bundle.get("kind") != KIND_PRESET:
raise ValueError("Not a preset bundle")
preset = bundle.get("preset")
if not isinstance(preset, dict):
raise ValueError("Bundle missing preset")
new_id = presets_model.create(profile_id)
data = copy.deepcopy(preset)
data["profile_id"] = str(profile_id)
presets_model.update(new_id, data)
return str(new_id), presets_model.read(new_id) or data
def export_sequence_bundle(
sequence_id: str,
sequences_model,
presets_model,
*,
profile_id: Optional[str] = None,
) -> Dict[str, Any]:
seq = sequences_model.read(sequence_id)
if not seq:
raise ValueError("Sequence not found")
if profile_id is not None and str(seq.get("profile_id")) != str(profile_id):
raise ValueError("Sequence not found")
pid = str(profile_id or seq.get("profile_id") or "")
preset_ids = _preset_ids_in_sequence(seq)
presets_out: Dict[str, Any] = {}
for old_pid in preset_ids:
pdata = presets_model.read(old_pid)
if pdata and (not pid or str(pdata.get("profile_id")) == pid):
presets_out[old_pid] = copy.deepcopy(pdata)
return {
"version": BUNDLE_VERSION,
"kind": KIND_SEQUENCE,
"sequence": copy.deepcopy(seq),
"presets": presets_out,
}
def import_sequence_bundle(
bundle: Dict[str, Any],
sequences_model,
presets_model,
profile_id: str,
) -> Tuple[str, Dict[str, Any]]:
if not isinstance(bundle, dict):
raise ValueError("Invalid bundle")
if bundle.get("kind") != KIND_SEQUENCE:
raise ValueError("Not a sequence bundle")
seq = bundle.get("sequence")
if not isinstance(seq, dict):
raise ValueError("Bundle missing sequence")
preset_cache: Dict[str, int] = {}
preset_id_map: Dict[str, str] = {}
new_presets: Dict[str, Dict[str, Any]] = {}
presets_in = bundle.get("presets") if isinstance(bundle.get("presets"), dict) else {}
for old_pid, pdata in presets_in.items():
if not isinstance(pdata, dict):
continue
new_pid = _allocate_id(presets_model, preset_cache)
clone = copy.deepcopy(pdata)
clone["profile_id"] = str(profile_id)
new_presets[new_pid] = clone
preset_id_map[str(old_pid)] = new_pid
for old_pid in _preset_ids_in_sequence(seq):
op = str(old_pid)
if op not in preset_id_map:
pdata = presets_model.read(op)
if pdata:
new_pid = _allocate_id(presets_model, preset_cache)
clone = copy.deepcopy(pdata)
clone["profile_id"] = str(profile_id)
new_presets[new_pid] = clone
preset_id_map[op] = new_pid
for pid, pdata in new_presets.items():
presets_model[pid] = pdata
if new_presets:
presets_model.save()
new_seq_id = sequences_model.create(profile_id)
mapped = _map_sequence_lanes(seq, preset_id_map)
mapped["profile_id"] = str(profile_id)
sequences_model.update(new_seq_id, mapped)
return str(new_seq_id), sequences_model.read(new_seq_id) or mapped
File diff suppressed because it is too large. Load diff
Binary file not shown.
-545
View File
@@ -1,545 +0,0 @@
#!/usr/bin/env python3
"""Live beat detection utility with custom/aubio/hybrid modes."""
from __future__ import annotations
import argparse
import collections
import queue
import sys
import time
from typing import Deque
try:
import numpy as np
except ImportError as exc:
raise SystemExit(
"Missing dependency: numpy. Install with `pip install numpy`."
) from exc
try:
import sounddevice as sd
except ImportError as exc:
raise SystemExit(
"Missing dependency: sounddevice. Install with `pip install sounddevice`."
) from exc
try:
import requests
except ImportError:
requests = None
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Beat detector utility")
parser.add_argument(
"--mode",
choices=("custom", "aubio", "hybrid"),
default="aubio",
help="Detection mode",
)
parser.add_argument("--device", default=None, help="Input device name or index")
parser.add_argument(
"--sample-rate",
type=int,
default=0,
help="Audio sample rate (0 = use selected device default)",
)
parser.add_argument("--hop-size", type=int, default=256, help="Frame hop size in samples")
parser.add_argument("--win-mult", type=int, default=2, help="Aubio window size multiplier")
parser.add_argument(
"--min-band-hz",
type=float,
default=45.0,
help="Low frequency bound used for beat energy",
)
parser.add_argument(
"--max-band-hz",
type=float,
default=180.0,
help="High frequency bound used for beat energy",
)
parser.add_argument(
"--energy-weight",
type=float,
default=0.7,
help="Weight for low-band energy component (0..1)",
)
parser.add_argument(
"--flux-weight",
type=float,
default=0.3,
help="Weight for spectral flux component (0..1)",
)
parser.add_argument(
"--threshold-multiplier",
type=float,
default=1.35,
help="Custom-mode threshold multiplier vs adaptive baseline",
)
parser.add_argument(
"--ema-alpha",
type=float,
default=0.08,
help="Adaptive baseline smoothing (higher reacts faster)",
)
parser.add_argument(
"--min-ioi-ms",
type=float,
default=85.0,
help="Minimum time between beats in milliseconds",
)
parser.add_argument(
"--bpm-window",
type=int,
default=8,
help="How many recent beat intervals to use for BPM estimate",
)
parser.add_argument(
"--post-url",
default="",
help="Optional HTTP URL to POST beat events",
)
parser.add_argument(
"--aubio-method",
default="default",
choices=("default", "specdiff", "hfc", "complex", "phase", "energy"),
help="Aubio tempo method",
)
parser.add_argument(
"--aubio-threshold",
type=float,
default=0.12,
help="Aubio detection threshold",
)
return parser.parse_args()
def _estimate_bpm(beat_times: Deque[float]) -> float | None:
if len(beat_times) < 3:
return None
intervals = np.diff(np.array(beat_times, dtype=np.float64))
valid = intervals[(intervals > 0.2) & (intervals < 2.0)]
if valid.size == 0:
return None
return 60.0 / float(np.median(valid))
def _is_plausible_ioi(
last_trigger_s: float,
beat_times: Deque[float],
now_s: float,
*,
min_ratio: float = 0.42,
max_ratio: float = 2.5,
) -> bool:
"""Reject double-time / half-time false triggers vs recent median interval."""
if last_trigger_s <= 0 or len(beat_times) < 2:
return True
ioi = now_s - last_trigger_s
if ioi <= 0:
return False
intervals = np.diff(np.array(list(beat_times)[-8:], dtype=np.float64))
if intervals.size == 0:
return True
med = float(np.median(intervals))
if med < 0.05:
return True
return (ioi >= med * min_ratio) and (ioi <= med * max_ratio)
class BarPhaseTracker:
"""Track beat-in-bar from downbeat counting (kick hints)."""
def __init__(self, beats_per_bar: int = 4, kick_conf_min: float = 1.15):
self.beats_per_bar = max(1, int(beats_per_bar))
self.kick_conf_min = float(kick_conf_min)
self.bar_beat = 1
self.is_downbeat = True
self.confidence = 0.0
self._last_downbeat_s = 0.0
self._aligned_kicks = 0
self._total_beats = 0
def reset(self) -> None:
self.bar_beat = 1
self.is_downbeat = True
self.confidence = 0.0
self._last_downbeat_s = 0.0
self._aligned_kicks = 0
self._total_beats = 0
def anchor_downbeat(self, now_s: float) -> None:
self.bar_beat = 1
self.is_downbeat = True
self._last_downbeat_s = float(now_s)
self.confidence = max(self.confidence, 0.85)
def _bar_duration_s(
self, bpm: float | None, median_ioi: float | None
) -> float | None:
if bpm is not None and bpm > 0:
return (60.0 / float(bpm)) * self.beats_per_bar
if median_ioi is not None and median_ioi > 0:
return float(median_ioi) * self.beats_per_bar
return None
@staticmethod
def _near_whole_bars(elapsed: float, bar_dur: float, tol: float = 0.14) -> bool:
if bar_dur <= 0 or elapsed <= 0:
return False
n = elapsed / bar_dur
nearest = max(1, round(n))
return abs(n - nearest) <= tol
def on_beat(
self,
now_s: float,
beat_type: str,
beat_type_conf: float,
*,
bpm: float | None = None,
median_ioi: float | None = None,
) -> dict[str, int | float | bool | str]:
self._total_beats += 1
bar_dur = self._bar_duration_s(bpm, median_ioi)
is_kick = (
str(beat_type or "").lower() == "kick"
and float(beat_type_conf or 0.0) >= self.kick_conf_min
)
downbeat_locked = False
if is_kick:
if self._last_downbeat_s <= 0 or self._total_beats <= 2:
downbeat_locked = True
elif bar_dur and self._near_whole_bars(
now_s - self._last_downbeat_s, bar_dur
):
downbeat_locked = True
elif is_kick and self.bar_beat >= max(2, self.beats_per_bar - 1):
downbeat_locked = True
prev_bar_beat = int(self.bar_beat)
if downbeat_locked:
self.bar_beat = 1
self.is_downbeat = True
self._last_downbeat_s = float(now_s)
self._aligned_kicks += 1
elif self._total_beats <= 1:
self.bar_beat = 1
self.is_downbeat = True
else:
self.bar_beat = (prev_bar_beat % self.beats_per_bar) + 1
self.is_downbeat = self.bar_beat == 1
if self._total_beats >= self.beats_per_bar:
bars_seen = max(1, self._total_beats // self.beats_per_bar)
self.confidence = min(1.0, self._aligned_kicks / bars_seen)
return {
"bar_beat": int(self.bar_beat),
"beats_per_bar": int(self.beats_per_bar),
"is_downbeat": bool(self.is_downbeat),
"phase_confidence": round(float(self.confidence), 3),
"bar_phase_readout": f"{int(self.bar_beat)}/{int(self.beats_per_bar)}",
}
def _resolve_bpm(
beat_times: Deque[float],
aubio_bpm: float | None,
) -> float | None:
estimated = _estimate_bpm(beat_times)
if estimated is None:
return aubio_bpm
if aubio_bpm is None or aubio_bpm <= 0:
return estimated
ratio = float(aubio_bpm) / estimated
if ratio > 1.75 or ratio < 0.57:
return estimated
return estimated
def _load_aubio_if_needed(mode: str):
if mode == "custom":
return None
try:
import aubio
return aubio
except ImportError:
dist_packages = "/usr/lib/python3/dist-packages"
if dist_packages not in sys.path:
sys.path.append(dist_packages)
try:
import aubio
return aubio
except ImportError:
raise SystemExit("aubio not installed; use --mode custom or install aubio")
class BeatDetectRuntime:
"""Reusable detector runtime so web and CLI can share logic."""
def __init__(self, args):
self.args = args
self.aubio = _load_aubio_if_needed(args.mode)
self.sample_rate = 0
self.frame_size = 0
self.tempo = None
self.band_mask = None
self.freqs = None
self.window = None
self.prev_mag = None
self.kick_mask = None
self.snare_mask = None
self.hat_mask = None
self.baseline = 1e-6
self.beat_times: Deque[float] = collections.deque(
maxlen=max(2, args.bpm_window + 1)
)
self.last_trigger_s = 0.0
self.debounce_s = float(args.min_ioi_ms) / 1000.0
bpb = int(getattr(args, "beats_per_bar", 4) or 4)
self.bar_phase = BarPhaseTracker(beats_per_bar=bpb)
def setup(self, sample_rate: int):
self.sample_rate = int(sample_rate)
self.frame_size = max(128, int(self.args.hop_size))
win_size = max(1024, self.frame_size * max(2, self.args.win_mult))
freqs = np.fft.rfftfreq(self.frame_size, d=1.0 / self.sample_rate)
self.freqs = freqs
self.band_mask = (freqs >= self.args.min_band_hz) & (
freqs <= self.args.max_band_hz
)
self.kick_mask = (freqs >= 40.0) & (freqs <= 140.0)
self.snare_mask = (freqs >= 140.0) & (freqs <= 3000.0)
self.hat_mask = (freqs >= 5000.0) & (freqs <= 12000.0)
if not np.any(self.band_mask):
raise ValueError("Invalid band range for current sample rate")
self.window = np.hanning(self.frame_size).astype(np.float32)
self.prev_mag = np.zeros(freqs.shape[0], dtype=np.float32)
self.baseline = 1e-6
self.last_trigger_s = 0.0
self.beat_times.clear()
self.tempo = None
if self.aubio is not None:
self._init_aubio_tempo(win_size)
def _init_aubio_tempo(self, win_size: int):
self.tempo = self.aubio.tempo(
self.args.aubio_method, win_size, self.frame_size, self.sample_rate
)
if hasattr(self.tempo, "set_threshold"):
self.tempo.set_threshold(float(self.args.aubio_threshold))
if hasattr(self.tempo, "set_minioi_ms"):
self.tempo.set_minioi_ms(float(self.args.min_ioi_ms))
def reset_tempo_state(self) -> None:
"""Clear tempo/aubio history without losing bar phase."""
self.baseline = 1e-6
if self.prev_mag is not None:
self.prev_mag[:] = 0.0
self.beat_times.clear()
self.last_trigger_s = 0.0
if self.aubio is not None and self.sample_rate > 0:
win_size = max(1024, self.frame_size * max(2, self.args.win_mult))
self._init_aubio_tempo(win_size)
def reset_state(self):
"""Full reset (manual): tempo history and bar phase."""
self.reset_tempo_state()
self.bar_phase.reset()
def anchor_bar_phase(self, now_s: float | None = None) -> None:
if now_s is None:
now_s = time.time()
self.bar_phase.anchor_downbeat(now_s)
def _classify_hit(self, mag: np.ndarray):
total = float(np.mean(mag) + 1e-9)
kick = float(np.mean(mag[self.kick_mask])) / total if np.any(self.kick_mask) else 0.0
snare = float(np.mean(mag[self.snare_mask])) / total if np.any(self.snare_mask) else 0.0
hat = float(np.mean(mag[self.hat_mask])) / total if np.any(self.hat_mask) else 0.0
scores = {
"kick": kick,
"snare": snare,
"hat": hat,
}
label, value = max(scores.items(), key=lambda kv: kv[1])
if value < 1.15:
return "unknown", value
return label, value
def process_frame(self, frame: np.ndarray, now_s: float | None = None):
if self.window is None or self.band_mask is None:
raise RuntimeError("Runtime not setup")
if frame.shape[0] != self.frame_size:
if frame.shape[0] > self.frame_size:
frame = frame[: self.frame_size]
else:
frame = np.pad(frame, (0, self.frame_size - frame.shape[0]))
f32 = frame.astype(np.float32)
rms = float(np.sqrt(np.mean(f32 * f32) + 1e-12))
db = 20.0 * np.log10(max(rms, 1e-12))
mag = np.abs(np.fft.rfft(f32 * self.window)).astype(np.float32)
band_energy = float(np.mean(mag[self.band_mask]))
flux = float(np.mean(np.maximum(0.0, mag - self.prev_mag)))
self.prev_mag[:] = mag
weight_sum = max(1e-6, self.args.energy_weight + self.args.flux_weight)
score = ((self.args.energy_weight * band_energy) + (self.args.flux_weight * flux)) / weight_sum
self.baseline = ((1.0 - self.args.ema_alpha) * self.baseline) + (
self.args.ema_alpha * score
)
threshold = self.baseline * self.args.threshold_multiplier
custom_hit = score > threshold
aubio_hit = False
aubio_bpm = None
if self.tempo is not None:
aubio_hit = bool(self.tempo(f32)[0])
val = float(self.tempo.get_bpm())
aubio_bpm = val if val > 0 else None
if now_s is None:
now_s = time.time()
if (now_s - self.last_trigger_s) < self.debounce_s:
return None
if self.args.mode == "custom":
should_trigger = custom_hit
elif self.args.mode == "aubio":
should_trigger = aubio_hit
else:
should_trigger = custom_hit or aubio_hit
if should_trigger and not _is_plausible_ioi(
self.last_trigger_s, self.beat_times, now_s
):
should_trigger = False
if not should_trigger:
return None
self.last_trigger_s = now_s
self.beat_times.append(now_s)
bpm = _resolve_bpm(self.beat_times, aubio_bpm)
strength = score / max(1e-9, self.baseline)
beat_type, beat_type_conf = self._classify_hit(mag)
median_ioi = None
if len(self.beat_times) >= 2:
intervals = np.diff(np.array(self.beat_times, dtype=np.float64))
if intervals.size > 0:
median_ioi = float(np.median(intervals))
phase = self.bar_phase.on_beat(
now_s,
beat_type,
beat_type_conf,
bpm=bpm,
median_ioi=median_ioi,
)
if self.args.mode == "custom":
src = "custom"
elif self.args.mode == "aubio":
src = "aubio"
elif custom_hit and aubio_hit:
src = "both"
elif custom_hit:
src = "custom"
else:
src = "aubio"
return {
"ts": now_s,
"bpm": bpm,
"src": src,
"score": score,
"threshold": threshold,
"strength": strength,
"beat_type": beat_type,
"beat_type_confidence": beat_type_conf,
"db": db,
**phase,
}
def main() -> int:
args = parse_args()
runtime = BeatDetectRuntime(args)
if args.post_url and requests is None:
raise SystemExit("`requests` is required for --post-url (pip install requests)")
if args.sample_rate > 0:
sample_rate = args.sample_rate
else:
dev_info = sd.query_devices(args.device, "input")
sample_rate = int(dev_info["default_samplerate"])
runtime.setup(sample_rate=sample_rate)
frame_size = runtime.frame_size
audio_q: "queue.Queue[np.ndarray]" = queue.Queue(maxsize=64)
def audio_callback(indata, frames, _time_info, status):
_ = frames
if status:
print(f"audio status: {status}")
mono = np.asarray(indata[:, 0], dtype=np.float32)
if not audio_q.full():
audio_q.put_nowait(mono)
print(
"Listening... Ctrl+C to stop. "
f"mode={args.mode} sr={sample_rate} hop={frame_size} "
f"band={args.min_band_hz:.0f}-{args.max_band_hz:.0f}Hz "
f"custom_th={args.threshold_multiplier:.2f} aubio_th={args.aubio_threshold:.2f} "
f"min_ioi={args.min_ioi_ms:.0f}ms"
)
with sd.InputStream(
device=args.device,
channels=1,
samplerate=sample_rate,
blocksize=frame_size,
callback=audio_callback,
):
try:
while True:
try:
frame = audio_q.get(timeout=0.1)
except queue.Empty:
continue
if frame.shape[0] != frame_size:
if frame.shape[0] > frame_size:
frame = frame[:frame_size]
else:
frame = np.pad(frame, (0, frame_size - frame.shape[0]))
event = runtime.process_frame(frame, now_s=time.time())
if event is None:
continue
now_s = event["ts"]
bpm = event["bpm"]
bpm_text = f"{bpm:.1f}" if isinstance(bpm, (float, int)) else "--"
src = event["src"]
print(
f"[{args.mode}] BEAT bpm={bpm_text} src={src} type={event['beat_type']} "
f"type_conf={event['beat_type_confidence']:.2f} strength={event['strength']:.2f} "
f"db={event['db']:.1f} "
f"score={event['score']:.3e} threshold={event['threshold']:.3e}"
)
if args.post_url and requests is not None:
try:
requests.post(
args.post_url,
json={"beat": True, "source": src, "ts": now_s, "bpm": bpm},
timeout=0.5,
)
except Exception as exc:
print(f"post failed: {exc}")
except KeyboardInterrupt:
print("\nStopped.")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+37
View File
@@ -0,0 +1,37 @@
"""Output registry validation."""
import pytest
from models.output import validate_output
def test_valid_records_are_normalised():
doc = validate_output({"name": " wall ", "protocol": "DDP", "host": "10.0.0.5", "pixel_count": "300",
"color_order": "GRB"})
assert doc["name"] == "wall" and doc["protocol"] == "ddp" and doc["pixel_count"] == 300
assert doc["color_order"] == "grb" and doc["enabled"] is True and doc["port"] is None
art = validate_output({"name": "a", "protocol": "artnet", "universe": 0, "pixel_count": 170})
assert art["universe"] == 0 and art["host"] == ""
sacn = validate_output({"name": "s", "protocol": "sacn", "universe": 5})
assert sacn["universe"] == 5
dmx = validate_output({"name": "d", "protocol": "dmx_serial", "serial_port": "/dev/ttyUSB0",
"channel": 1, "pixel_count": 170})
assert dmx["dmx_mode"] == "enttec_pro"
@pytest.mark.parametrize("data,message", [
({"protocol": "ddp", "host": "x"}, "name"),
({"name": "a", "protocol": "foo"}, "protocol"),
({"name": "a", "protocol": "ddp"}, "host"),
({"name": "a", "protocol": "dmx_serial"}, "serial_port"),
({"name": "a", "protocol": "dmx_serial", "serial_port": "/dev/x", "dmx_mode": "bad"}, "dmx_mode"),
({"name": "a", "protocol": "dmx_serial", "serial_port": "/dev/x", "channel": 500, "pixel_count": 10}, "pixel_count"),
({"name": "a", "protocol": "sacn", "universe": 0}, "universe"),
({"name": "a", "protocol": "artnet", "pixel_count": 0}, "pixel_count"),
({"name": "a", "protocol": "artnet", "brightness": 300}, "brightness"),
({"name": "a", "protocol": "artnet", "color_order": "rgbw"}, "color_order"),
({"name": "a", "protocol": "ddp", "host": "h", "port": "abc"}, "port"),
])
def test_invalid_records(data, message):
with pytest.raises(ValueError, match=message):
validate_output(data)
+303
View File
@@ -0,0 +1,303 @@
"""Protocol driver tests: packet layout, universe splitting, frame prep, UDP, DMX, ESP32."""
import asyncio
import json
import socket
import struct
import pytest
from engine.outputs import open_output, parse_output_url
from engine.outputs.artnet import ArtNetOutput, build_artdmx, build_artsync
from engine.outputs.base import FrameOutput
from engine.outputs.ddp import DdpOutput, build_ddp_packets
from engine.outputs.dmx_serial import DmxSerialOutput, build_enttec_pro, dmx_universe
from engine.outputs.sacn import SacnOutput, build_e131, multicast_address
def frame(pixels, value=None):
if value is None:
return bytes(i % 256 for i in range(pixels * 3))
return bytes(value) * pixels
# -- base -------------------------------------------------------------------
def test_prepare_pads_truncates_and_scales():
out = FrameOutput({"pixel_count": 2})
assert out.prepare(b"\x10\x20\x30") == b"\x10\x20\x30\x00\x00\x00"
assert out.prepare(bytes(range(9))) == bytes(range(6))
half = FrameOutput({"pixel_count": 1, "brightness": 128})
assert half.prepare(b"\xff\x80\x00") == bytes((128, 64, 0))
assert out.prepare(b"\xff\xff\xff\xff\xff\xff", global_brightness=0) == bytes(6)
@pytest.mark.parametrize("order,expected", [
("rgb", b"\x01\x02\x03"), ("grb", b"\x02\x01\x03"), ("bgr", b"\x03\x02\x01"),
("brg", b"\x03\x01\x02"), ("rbg", b"\x01\x03\x02"), ("gbr", b"\x02\x03\x01"),
])
def test_color_order(order, expected):
assert FrameOutput({"pixel_count": 1, "color_order": order}).prepare(b"\x01\x02\x03") == expected
def test_reverse():
out = FrameOutput({"pixel_count": 2, "reverse": True, "color_order": "grb"})
assert out.prepare(b"\x01\x02\x03\x04\x05\x06") == b"\x05\x04\x06\x02\x01\x03"
def test_parse_output_url():
cfg = parse_output_url("ddp://10.0.0.5:4049?pixels=300&order=grb")
assert cfg["protocol"] == "ddp" and cfg["host"] == "10.0.0.5" and cfg["port"] == 4049
assert cfg["pixel_count"] == "300" and cfg["color_order"] == "grb"
out = open_output(cfg)
assert isinstance(out, DdpOutput) and out.pixel_count == 300 and out.port == 4049
dmx = parse_output_url("dmx_serial:///dev/ttyUSB1?mode=open_dmx&channel=4")
assert dmx["serial_port"] == "/dev/ttyUSB1" and dmx["dmx_mode"] == "open_dmx"
assert isinstance(open_output(parse_output_url("e131://?universe=2")), SacnOutput)
with pytest.raises(ValueError):
open_output({"protocol": "nope"})
# -- DDP --------------------------------------------------------------------
def test_ddp_packets_split_and_push():
data = frame(600) # 1800 bytes -> 1440 + 360
packets = build_ddp_packets(data, sequence=3)
assert len(packets) == 2
for pkt, (offset, length, push) in zip(packets, [(0, 1440, False), (1440, 360, True)]):
flags, seq, dtype, dest, off, ln = struct.unpack(">BBBBIH", pkt[:10])
assert flags & 0x40 and bool(flags & 0x01) == push
assert seq == 3 and dtype == 0x0B and dest == 1
assert off == offset and ln == length == len(pkt) - 10
assert b"".join(p[10:] for p in packets) == data
def test_ddp_three_packets_and_sequence_wraps():
out = DdpOutput({"host": "127.0.0.1", "pixel_count": 1000})
pkts = out.packets_for(frame(1000)) # 3000 bytes -> 3 packets
assert [struct.unpack(">I", p[4:8])[0] for p in pkts] == [0, 1440, 2880]
assert [p[0] & 0x01 for p in pkts] == [0, 0, 1]
seqs = [out.next_sequence() for _ in range(16)]
assert seqs[0] == 2 and 0 not in seqs and max(seqs) == 15 and seqs[-1] == 2
# -- Art-Net ----------------------------------------------------------------
def test_artdmx_header():
pkt = build_artdmx(0x1234, b"\x01\x02\x03", sequence=7)
assert pkt[:8] == b"Art-Net\x00"
assert struct.unpack("<H", pkt[8:10])[0] == 0x5000
assert struct.unpack(">H", pkt[10:12])[0] == 14
assert pkt[12] == 7 and pkt[13] == 0
assert pkt[14] == 0x34 and pkt[15] == 0x12 # SubUni, Net
assert struct.unpack(">H", pkt[16:18])[0] == 4 # padded to even
assert pkt[18:] == b"\x01\x02\x03\x00"
def test_artnet_universe_split():
out = ArtNetOutput({"host": "127.0.0.1", "universe": 3, "pixel_count": 400})
pkts = out.packets_for(out.prepare(frame(400)))
assert [p[14] for p in pkts] == [3, 4, 5]
assert [struct.unpack(">H", p[16:18])[0] for p in pkts] == [510, 510, 180]
assert len({p[12] for p in pkts}) == 1
def test_artnet_sequence_wrap_and_sync():
out = ArtNetOutput({"host": "127.0.0.1", "sync": True, "pixel_count": 1})
seqs = [out.next_sequence() for _ in range(256)]
assert seqs[0] == 1 and seqs[254] == 255 and seqs[255] == 1
pkts = out.packets_for(out.prepare(frame(1)))
assert pkts[-1] == build_artsync()
assert struct.unpack("<H", pkts[-1][8:10])[0] == 0x5200
def test_artnet_defaults_to_broadcast():
out = ArtNetOutput({})
assert out.host == "255.255.255.255" and out.broadcast
# -- sACN -------------------------------------------------------------------
def test_e131_layout():
cid = bytes(range(16))
pkt = build_e131(300, b"\x0a\x0b\x0c", sequence=9, cid=cid, source_name="test")
assert len(pkt) == 126 + 3
assert pkt[4:16] == b"ASC-E1.17\x00\x00\x00"
root_fl = struct.unpack(">H", pkt[16:18])[0]
assert root_fl >> 12 == 0x7 and root_fl & 0x0FFF == len(pkt) - 16
assert struct.unpack(">I", pkt[18:22])[0] == 4
assert pkt[22:38] == cid
framing_fl = struct.unpack(">H", pkt[38:40])[0]
assert framing_fl & 0x0FFF == len(pkt) - 38
assert struct.unpack(">I", pkt[40:44])[0] == 2
assert pkt[44:48] == b"test"
assert pkt[108] == 100 # priority
assert pkt[111] == 9 # sequence
assert struct.unpack(">H", pkt[113:115])[0] == 300
dmp_fl = struct.unpack(">H", pkt[115:117])[0]
assert dmp_fl & 0x0FFF == len(pkt) - 115
assert pkt[117] == 0x02 and pkt[118] == 0xA1
assert struct.unpack(">H", pkt[123:125])[0] == 4 # start code + 3 slots
assert pkt[125] == 0 and pkt[126:] == b"\x0a\x0b\x0c"
def test_sacn_multicast_split_and_stable_cid():
assert multicast_address(1) == "239.255.0.1"
assert multicast_address(300) == "239.255.1.44"
out = SacnOutput({"name": "roof", "universe": 1, "pixel_count": 200})
pkts = out.packets_for(out.prepare(frame(200)))
assert [addr for _p, addr in pkts] == [("239.255.0.1", 5568), ("239.255.0.2", 5568)]
again = SacnOutput({"name": "roof", "universe": 1, "pixel_count": 200})
assert out.cid == again.cid and len(out.cid) == 16
pkts2 = out.packets_for(out.prepare(frame(200)))
assert pkts2[0][0][111] == (pkts[0][0][111] + 1) & 0xFF
uni = SacnOutput({"host": "10.0.0.9", "universe": 5, "pixel_count": 1})
assert uni.packets_for(uni.prepare(frame(1)))[0][1] == ("10.0.0.9", 5568)
# -- UDP round trip ---------------------------------------------------------
def _udp_receiver():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("127.0.0.1", 0))
sock.settimeout(2.0)
return sock
@pytest.mark.parametrize("cls,pixels,expected_packets", [(DdpOutput, 600, 2), (ArtNetOutput, 400, 3)])
def test_udp_round_trip(cls, pixels, expected_packets):
recv = _udp_receiver()
port = recv.getsockname()[1]
async def go():
out = cls({"host": "127.0.0.1", "port": port, "pixel_count": pixels})
await out.send(frame(pixels))
await asyncio.sleep(0.05)
if out._transport:
out._transport.close()
return out
out = asyncio.run(go())
got = [recv.recvfrom(2048)[0] for _ in range(expected_packets)]
recv.close()
assert out.stats.frames == 1 and out.stats.packets == expected_packets and out.stats.errors == 0
if cls is DdpOutput:
assert b"".join(p[10:] for p in got) == frame(pixels)
else:
assert got[0][:8] == b"Art-Net\x00"
# -- USB-DMX ----------------------------------------------------------------
class FakeSerial:
def __init__(self, output):
self.writes = []
self.breaks = []
self.closed = False
self._bc = False
@property
def break_condition(self):
return self._bc
@break_condition.setter
def break_condition(self, value):
self._bc = value
self.breaks.append(value)
def write(self, data):
self.writes.append(bytes(data))
def close(self):
self.closed = True
def test_dmx_universe_channel_offset():
u = dmx_universe(b"\x01\x02\x03", channel=10)
assert len(u) == 512 and u[9:12] == b"\x01\x02\x03" and u[:9] == bytes(9)
assert dmx_universe(bytes(600), channel=1) == bytes(512)
def test_enttec_pro_framing():
pkt = build_enttec_pro(bytes(512))
assert pkt[0] == 0x7E and pkt[1] == 6
assert struct.unpack("<H", pkt[2:4])[0] == 513
assert pkt[4] == 0 and pkt[-1] == 0xE7 and len(pkt) == 518
@pytest.mark.parametrize("mode", ["enttec_pro", "open_dmx"])
def test_dmx_serial_send(mode):
holder = {}
def factory(output):
holder["ser"] = FakeSerial(output)
return holder["ser"]
async def go():
out = DmxSerialOutput({"serial_port": "/dev/null", "dmx_mode": mode, "channel": 4, "pixel_count": 2},
serial_factory=factory)
await out.send(b"\x0a\x0b\x0c\x0d\x0e\x0f")
await out.close()
return out
out = asyncio.run(go())
ser = holder["ser"]
assert out.stats.errors == 0 and ser.closed
data = ser.writes[0]
if mode == "enttec_pro":
universe = data[5:-1]
assert data[0] == 0x7E and ser.breaks == []
else:
assert len(data) == 513 and data[0] == 0
universe = data[1:]
assert ser.breaks[:2] == [True, False]
assert universe[3:9] == b"\x0a\x0b\x0c\x0d\x0e\x0f"
assert ser.writes[-1].count(0) >= 512 # close() sends black
# -- ESP32 preset output --------------------------------------------------------
class FakeSender:
def __init__(self):
self.sent = []
async def send(self, data, addr=None):
self.sent.append((data, addr))
return True
class FakeDevices(dict):
def read(self, mac):
return self.get(mac)
def test_driver_output_matches_presets_push():
from engine.outputs.driver import DriverOutput, resolve_device_macs
devices = FakeDevices({
"aaaaaaaaaaaa": {"name": "roof", "transport": "espnow", "address": "aaaaaaaaaaaa"},
"bbbbbbbbbbbb": {"name": "roof", "transport": "espnow", "address": "bbbbbbbbbbbb"},
"cccccccccccc": {"name": "dj", "transport": "espnow", "address": "cccccccccccc"},
})
assert resolve_device_macs(["roof", "roof", "nobody"], devices) == [
("roof", "aaaaaaaaaaaa"), ("roof", "bbbbbbbbbbbb")]
sender = FakeSender()
out = DriverOutput(["dj"], sender_getter=lambda: sender, devices=devices, delay_s=0)
payload = {"p": "rainbow", "c": ["#FF0000"], "d": 100, "b": 32, "a": True,
"n1": 2, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0}
delivered = asyncio.run(out.apply("3", payload))
assert delivered == 2
msgs = [json.loads(d) for d, _a in sender.sent]
assert [a for _d, a in sender.sent] == ["cccccccccccc", "cccccccccccc"]
# Same two-message sequence presets.js sends via /presets/push (without save).
assert msgs[0] == {"v": "1", "presets": {"3": payload}}
assert msgs[1] == {"v": "1", "select": {"dj": ["3"]}}
def test_driver_output_without_sender_records_error():
from engine.outputs.driver import DriverOutput
out = DriverOutput(["dj"], sender_getter=lambda: None, devices=FakeDevices())
assert asyncio.run(out.apply("1", {"p": "on"})) == 0
assert out.stats.errors == 1
+242
View File
@@ -0,0 +1,242 @@
"""ZonePlayer + Engine: frames reach pixel outputs, presets reach ESP32 drivers."""
import asyncio
import pytest
from engine.core import Engine, EngineError
from engine.outputs.base import FrameOutput
from engine.pattern_loader import PatternLibrary
from engine.player import ZonePlayer
from engine.zone_targets import ZoneTargets, resolve_zone
LIB = PatternLibrary()
class RecordingOutput(FrameOutput):
protocol = "test"
keepalive_s = 0.2
def __init__(self, cfg):
super().__init__(cfg)
self.sent = []
self.levels = []
self.closed = False
async def send(self, rgb, global_brightness=255):
self.levels.append(global_brightness)
await super().send(rgb, global_brightness)
async def _send_prepared(self, payload):
self.sent.append(payload)
async def close(self):
await super().close()
self.closed = True
class RecordingDriver:
kind = "preset"
def __init__(self, names):
self.names = names
self.applied = []
self.closed = False
async def apply(self, preset_id, payload):
self.applied.append((preset_id, payload))
async def close(self):
self.closed = True
def status(self):
return {"name": ",".join(self.names), "kind": "preset", "frames": len(self.applied),
"packets": 0, "errors": 0, "last_error": None}
def make_player(cfgs, drivers=(), brightness=255):
made = {"outputs": [], "driver": None}
def output_factory(cfg):
out = RecordingOutput(cfg)
made["outputs"].append(out)
return out
def driver_factory(names):
made["driver"] = RecordingDriver(names)
return made["driver"]
targets = ZoneTargets("z1", cfgs, list(drivers))
player = ZonePlayer(targets, LIB, lambda: brightness, output_factory=output_factory,
driver_factory=driver_factory)
return player, made
def test_frames_split_per_output_offset_and_brightness():
async def go():
player, made = make_player(
[{"name": "a", "pixel_count": 2, "fps": 60},
{"name": "b", "pixel_count": 1, "pixel_offset": 2, "color_order": "grb", "fps": 60}],
brightness=128,
)
assert player.targets.frame_length == 3
await player.start()
await player.apply("1", {"p": "on", "c": ["#ff8000"], "b": 255})
await asyncio.sleep(0.15)
await player.stop()
return made
made = asyncio.run(go())
a, b = made["outputs"]
assert a.sent[0] == bytes((128, 64, 0)) * 2
assert b.sent[0] == bytes((64, 128, 0)) # grb
assert set(a.levels[:-1]) == {128} # last send is the black frame from close()
assert a.closed and b.closed and a.sent[-1] == bytes(6) # black on stop
def test_animated_pattern_streams_and_keepalive_resends_static():
async def go():
player, made = make_player([{"name": "a", "pixel_count": 8, "fps": 60}])
await player.start()
await player.apply("1", {"p": "rainbow", "c": [], "d": 10, "b": 255, "n1": 8})
await asyncio.sleep(0.4)
rainbow_frames = len(made["outputs"][0].sent)
await player.apply("2", {"p": "on", "c": ["#00ff00"], "b": 255})
await asyncio.sleep(0.1)
before = len(made["outputs"][0].sent)
await asyncio.sleep(0.5) # static frame -> keepalive resends (0.2 s)
after = len(made["outputs"][0].sent)
await player.stop()
return rainbow_frames, before, after, made
rainbow_frames, before, after, made = asyncio.run(go())
assert rainbow_frames >= 10
assert after - before >= 2
assert made["outputs"][0].sent[before] == bytes((0, 255, 0)) * 8
def test_mixed_zone_drives_esp32_and_pixels_together():
async def go():
player, made = make_player([{"name": "ddp", "pixel_count": 4}], drivers=["dj"])
await player.start()
await player.apply("7", {"p": "on", "c": ["#ffffff"], "b": 255})
await asyncio.sleep(0.1)
status = player.status()
await player.stop()
return made, status
made, status = asyncio.run(go())
assert made["driver"].applied == [("7", {"p": "on", "c": ["#ffffff"], "b": 255})]
assert made["outputs"][0].sent
assert status["preset_id"] == "7" and len(status["outputs"]) == 2
assert made["driver"].closed
def test_drivers_false_skips_esp32():
async def go():
player, made = make_player([{"name": "ddp", "pixel_count": 1}], drivers=["dj"])
await player.start()
await player.apply("1", {"p": "on", "c": ["#ffffff"], "b": 255}, drivers=False)
await asyncio.sleep(0.05)
await player.stop()
return made
made = asyncio.run(go())
assert made["driver"].applied == [] and made["outputs"][0].sent
def test_driver_only_zone_has_no_render_thread():
async def go():
player, made = make_player([], drivers=["roof"])
await player.start()
await player.apply("1", {"p": "rainbow"})
await player.stop()
return player, made
player, made = asyncio.run(go())
assert player.renderer is None and made["driver"].applied
# -- Engine --------------------------------------------------------------------
class FakeZones(dict):
def read(self, id):
return self.get(str(id))
class FakeOutputs(dict):
def by_name(self, name):
return [o for o in self.values() if o.get("name") == name]
def test_resolve_zone_splits_outputs_and_drivers():
zones = FakeZones({"1": {"names": ["roof", "wall", "wall", "dj"]}})
outputs = FakeOutputs({
"1": {"id": "1", "name": "wall", "pixel_count": 100, "enabled": True},
"2": {"id": "2", "name": "wall", "pixel_count": 50, "pixel_offset": 100, "enabled": True},
"3": {"id": "3", "name": "dj", "pixel_count": 10, "enabled": False},
})
t = resolve_zone("1", zones, outputs)
assert [c["id"] for c in t.frame_cfgs] == ["1", "2"]
assert t.driver_names == ["roof", "dj"] # disabled output falls back to device name
assert t.frame_length == 150
assert resolve_zone("9", zones, outputs) is None
def make_engine(targets_by_zone, payloads):
created = []
def factory(targets, library, brightness):
player, made = make_player(targets.frame_cfgs, targets.driver_names)
created.append((player, made))
return player
eng = Engine(
library=LIB,
zone_resolver=lambda zid: targets_by_zone.get(zid),
payload_resolver=lambda pid: payloads.get(pid),
player_factory=factory,
sequences_model=FakeSequences(),
)
return eng, created
class FakeSequences(dict):
def read(self, id):
return self.get(str(id))
def update(self, id, data):
if str(id) not in self:
return False
self[str(id)].update(data)
return True
def list(self):
return list(self.keys())
def test_engine_play_reuses_player_and_rebuilds_on_target_change():
targets = {"1": ZoneTargets("1", [{"name": "a", "pixel_count": 2}], ["dj"])}
payloads = {"10": {"p": "on", "c": ["#ff0000"]}, "11": {"p": "off"}}
async def go():
eng, created = make_engine(targets, payloads)
await eng.play("1", "10")
await eng.play("1", "11")
assert len(created) == 1
targets["1"] = ZoneTargets("1", [{"name": "a", "pixel_count": 3}], ["dj"])
await eng.play("1", "10")
assert len(created) == 2 and created[0][1]["outputs"][0].closed
with pytest.raises(EngineError):
await eng.play("1", "missing")
with pytest.raises(EngineError):
await eng.play("nozone", "10")
status = eng.status()
assert status["zones"]["1"]["preset_id"] == "10"
assert await eng.stop("1") is True
assert eng.status()["zones"] == {}
await eng.stop_all()
return created
created = asyncio.run(go())
assert [p for p, _ in created[0][1]["driver"].applied] == ["10", "11"]
+119
View File
@@ -0,0 +1,119 @@
"""The unchanged led-driver patterns run under the CPython shim."""
import threading
import time
import pytest
from engine import mpcompat
from engine.pattern_loader import PatternLibrary
from engine.renderer import Renderer, RenderThread
LIB = PatternLibrary()
NUM_LEDS = 24
def payload(pattern, **kw):
base = {"p": pattern, "c": ["#ff0000", "#00ff00", "#0000ff"], "d": 40, "b": 255, "a": True,
"n1": 5, "n2": 5, "n3": 5, "n4": 5, "n5": 0, "n6": 0}
base.update(kw)
return base
def test_library_loads_every_driver_pattern():
assert LIB.errors == {}
assert LIB.preset_class.__module__ == "led_driver_preset"
assert len(LIB.classes) >= 30
assert {"rainbow", "pulse", "chase", "on", "off"} <= set(LIB.ids())
@pytest.mark.parametrize("pattern", sorted(LIB.classes))
def test_pattern_renders(pattern):
r = Renderer(LIB, NUM_LEDS)
frames = r.render_virtual("1", payload(pattern), ticks=200, tick_ms=5)
assert r.error is None
assert frames, f"{pattern} wrote no frames"
assert all(len(f) == NUM_LEDS * 3 for f in frames)
@pytest.mark.parametrize("pattern", ["rainbow", "colour_cycle", "plasma", "aurora", "scanner", "transition"])
def test_animated_patterns_change(pattern):
frames = Renderer(LIB, NUM_LEDS).render_virtual("1", payload(pattern), ticks=400, tick_ms=5)
assert len(set(frames)) > 3
def test_on_and_off_builtins():
r = Renderer(LIB, 3)
frames = r.render_virtual("1", {"p": "on", "c": ["#ff8000"], "b": 255}, ticks=5)
assert frames == [bytes((255, 128, 0)) * 3] and r.generator is None
frames = r.render_virtual("2", {"p": "off"}, ticks=5)
assert frames == [bytes(9)]
def test_preset_brightness_applies_like_device():
frames = Renderer(LIB, 1).render_virtual("1", {"p": "on", "c": ["#ffffff"], "b": 128}, ticks=1)
assert frames[-1] == bytes((128, 128, 128))
def test_step_reset_rules_match_presets_select():
r = Renderer(LIB, 4)
r.render_virtual("1", payload("rainbow", n1=10), ticks=100, tick_ms=50)
assert r.driver.step != 0
kept = r.driver.step
r.set_preset("1", payload("rainbow", n1=10)) # same preset again = beat, keeps step
assert r.driver.step == kept
r.set_preset("2", payload("rainbow")) # different preset resets
assert r.driver.step == 0
def test_unknown_pattern_goes_dark():
r = Renderer(LIB, 2)
frames = r.render_virtual("1", {"p": "does_not_exist"}, ticks=3)
assert r.error and frames == [bytes(6)]
def test_virtual_clock_sleep_does_not_block():
started = time.monotonic()
frames = Renderer(LIB, 4).render_virtual("1", payload("heartbeat", d=500), ticks=50)
assert time.monotonic() - started < 2.0
assert len(frames) > 10
def test_render_thread_real_clock_and_hot_swap():
got = []
lock = threading.Lock()
def on_frame(f):
with lock:
got.append(f)
r = Renderer(LIB, 4, on_frame=on_frame)
t = RenderThread(r).start()
try:
t.apply("1", payload("rainbow", d=10, n1=8))
time.sleep(0.3)
with lock:
n_rainbow = len(got)
assert n_rainbow >= 5
t.apply("2", {"p": "on", "c": ["#0000ff"], "b": 255})
time.sleep(0.1)
with lock:
assert got[-1] == bytes((0, 0, 255)) * 4
assert r.pattern_id == "on"
finally:
t.stop()
assert not t._thread.is_alive()
def test_shim_installed_as_utime():
import sys
assert getattr(sys.modules["utime"], "__led_controller_shim__", False)
clock = mpcompat.VirtualClock(1000)
mpcompat.set_thread_clock(clock)
try:
import utime
assert utime.ticks_ms() == 1000
utime.sleep_ms(250)
assert utime.ticks_diff(utime.ticks_ms(), 1000) == 250
finally:
mpcompat.set_thread_clock(None)
+214
View File
@@ -0,0 +1,214 @@
"""Sequence model normalisation/migration and the SequenceRunner."""
import asyncio
import pytest
from engine.core import EngineError
from engine.sequence_runner import SequenceRunner
from models.squence import _normalize, migrate_legacy
class FakeSequences(dict):
def read(self, id):
return self.get(str(id))
def update(self, id, data):
if str(id) not in self:
return False
self[str(id)].update(data)
return True
def list(self):
return list(self.keys())
class FakeEngine:
def __init__(self):
self.plays = []
async def play(self, zone_id, preset_id, source="manual"):
self.plays.append((zone_id, str(preset_id), source))
def seq(zone="1", steps=("a", "b"), duration=0.02, **kw):
doc = {"name": "s", "zone_id": zone, "loop": True, "repeat_count": 0, "active": False,
"steps": [{"preset_id": p, "duration_s": duration} for p in steps]}
doc.update(kw)
return doc
# -- model ----------------------------------------------------------------------
def test_normalize_clamps_and_defaults():
doc = _normalize({"name": " x ", "zone_id": 2, "steps": [
{"preset_id": 1, "duration_s": 0.01}, {"preset_id": "2", "duration_s": 9999}, {"preset_id": "3"}]})
assert doc["name"] == "x" and doc["zone_id"] == "2" and doc["loop"] is True
assert [s["duration_s"] for s in doc["steps"]] == [0.5, 600.0, 5.0]
assert doc["steps"][0]["preset_id"] == "1"
with pytest.raises(ValueError):
_normalize({"steps": [{"duration_s": 3}]})
def test_migrate_legacy_record():
legacy = {"group_name": "Main Group", "presets": ["1", "2"], "sequence_duration": 3000,
"sequence_transition": 500, "sequence_loop": False, "sequence_repeat_count": 2,
"sequence_active": True, "sequence_index": 1, "sequence_start_time": 0}
doc, migrated = migrate_legacy(legacy)
assert migrated
assert doc == {"name": "Main Group", "zone_id": None, "loop": False, "repeat_count": 2,
"steps": [{"preset_id": "1", "duration_s": 3.0}, {"preset_id": "2", "duration_s": 3.0}],
"active": False}
same, migrated = migrate_legacy(doc)
assert not migrated and same is doc
# -- runner ---------------------------------------------------------------------
def test_steps_play_in_order_and_repeat_count_ends():
async def go():
model = FakeSequences({"1": seq(steps=("a", "b", "c"), repeat_count=2)})
eng = FakeEngine()
runner = SequenceRunner(eng, sequences_model=model)
await runner.play("1")
assert model["1"]["active"] is True
await asyncio.sleep(0.4)
return eng, model, runner
eng, model, runner = asyncio.run(go())
assert [p for _z, p, _s in eng.plays] == ["a", "b", "c", "a", "b", "c"]
assert all(s == "sequence" for _z, _p, s in eng.plays)
assert model["1"]["active"] is False
st = runner.status()["1"]
assert st["running"] is False and st["pass"] == 2
def test_no_loop_plays_once():
async def go():
model = FakeSequences({"1": seq(loop=False)})
eng = FakeEngine()
await SequenceRunner(eng, sequences_model=model).play("1")
await asyncio.sleep(0.2)
return eng
assert [p for _z, p, _s in asyncio.run(go()).plays] == ["a", "b"]
def test_infinite_loop_until_stop():
async def go():
model = FakeSequences({"1": seq()})
eng = FakeEngine()
runner = SequenceRunner(eng, sequences_model=model)
await runner.play("1")
await asyncio.sleep(0.25)
assert await runner.stop("1") is True
n = len(eng.plays)
await asyncio.sleep(0.1)
return eng, n, model
eng, n, model = asyncio.run(go())
assert n >= 6 and len(eng.plays) == n
assert model["1"]["active"] is False
def test_new_sequence_replaces_old_on_same_zone():
async def go():
model = FakeSequences({"1": seq(steps=("a",)), "2": seq(steps=("z",))})
eng = FakeEngine()
runner = SequenceRunner(eng, sequences_model=model)
await runner.play("1")
await asyncio.sleep(0.05)
await runner.play("2")
await asyncio.sleep(0.05)
plays_after_switch = list(eng.plays)
await runner.stop_all()
return plays_after_switch, model, runner
plays, model, runner = asyncio.run(go())
switch = plays.index(("1", "z", "sequence"))
assert all(p == "z" for _z, p, _s in plays[switch:])
assert model["1"]["active"] is False
assert runner.status()["1"]["running"] is False
def test_stop_all_keeps_active_for_resume():
async def go():
model = FakeSequences({"1": seq(), "2": seq(zone="2")})
eng = FakeEngine()
runner = SequenceRunner(eng, sequences_model=model)
await runner.play("1")
await runner.play("2")
await runner.stop_all(persist=False)
assert model["1"]["active"] and model["2"]["active"]
fresh = SequenceRunner(FakeEngine(), sequences_model=model)
resumed = await fresh.resume_active()
await fresh.stop_all()
return resumed
assert sorted(asyncio.run(go())) == ["1", "2"]
def test_play_errors():
async def go():
model = FakeSequences({"nozone": seq(zone=None), "empty": seq(steps=())})
runner = SequenceRunner(FakeEngine(), sequences_model=model)
for sid in ("missing", "nozone", "empty"):
with pytest.raises(EngineError):
await runner.play(sid)
asyncio.run(go())
def test_failing_step_does_not_kill_sequence():
class Flaky(FakeEngine):
async def play(self, zone_id, preset_id, source="manual"):
await super().play(zone_id, preset_id, source)
if preset_id == "a":
raise EngineError("Preset not found", 404)
async def go():
model = FakeSequences({"1": seq(loop=False)})
eng = Flaky()
runner = SequenceRunner(eng, sequences_model=model)
await runner.play("1")
await asyncio.sleep(0.2)
return eng, runner
eng, runner = asyncio.run(go())
assert [p for _z, p, _s in eng.plays] == ["a", "b"]
assert runner.status()["1"]["error"] == "Preset not found"
def test_manual_engine_play_stops_zone_sequence():
from engine.core import Engine
from engine.zone_targets import ZoneTargets
class NullPlayer:
def __init__(self, targets, library, brightness):
self.targets = targets
async def start(self):
pass
async def apply(self, preset_id, payload, drivers=True):
pass
async def stop(self):
pass
def status(self):
return {}
async def go():
model = FakeSequences({"1": seq(zone="5", steps=("a", "b"))})
eng = Engine(library=object(), zone_resolver=lambda z: ZoneTargets(z, [], ["dj"]),
payload_resolver=lambda p: {"p": "on"}, player_factory=NullPlayer,
sequences_model=model)
await eng.sequences.play("1")
await asyncio.sleep(0.03)
await eng.play("5", "x") # manual pick
return eng, model
eng, model = asyncio.run(go())
assert eng.sequences.zone_for("1") is None
assert model["1"]["active"] is False
-75
View File
@@ -1,75 +0,0 @@
#!/usr/bin/env python3
"""Generate a click-track WAV file at a known BPM.
Example:
python tests/make_bpm_test_audio.py --bpm 128 --seconds 60 --output tests/audio_128bpm.wav
"""
from __future__ import annotations
import argparse
import math
import struct
import wave
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Generate known-BPM click track")
parser.add_argument("--bpm", type=float, required=True, help="Target BPM (e.g. 120)")
parser.add_argument("--seconds", type=float, default=30.0, help="Audio duration in seconds")
parser.add_argument("--sample-rate", type=int, default=44100, help="Sample rate")
parser.add_argument("--click-ms", type=float, default=25.0, help="Click length in milliseconds")
parser.add_argument(
"--output",
default="tests/bpm_test.wav",
help="Output WAV path",
)
return parser.parse_args()
def main() -> int:
args = parse_args()
if args.bpm <= 0:
raise SystemExit("--bpm must be > 0")
if args.seconds <= 0:
raise SystemExit("--seconds must be > 0")
sample_rate = int(args.sample_rate)
total_samples = int(args.seconds * sample_rate)
beat_interval = 60.0 / float(args.bpm)
click_samples = max(1, int((args.click_ms / 1000.0) * sample_rate))
data = [0.0] * total_samples
beat_index = 0
t = 0.0
while t < args.seconds:
start = int(t * sample_rate)
# Slight accent every 4 beats to help human counting.
freq = 1760.0 if beat_index % 4 == 0 else 1320.0
amp = 0.9 if beat_index % 4 == 0 else 0.6
for i in range(click_samples):
idx = start + i
if idx >= total_samples:
break
env = math.exp(-8.0 * (i / click_samples))
s = amp * env * math.sin((2.0 * math.pi * freq * i) / sample_rate)
data[idx] += s
t += beat_interval
beat_index += 1
with wave.open(args.output, "wb") as wf:
wf.setnchannels(1)
wf.setsampwidth(2)
wf.setframerate(sample_rate)
frames = bytearray()
for s in data:
clipped = max(-1.0, min(1.0, s))
frames.extend(struct.pack("<h", int(clipped * 32767)))
wf.writeframes(bytes(frames))
print(f"Wrote {args.output} at {args.bpm:.2f} BPM for {args.seconds:.1f}s")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+3 -5
View File
@@ -25,20 +25,18 @@ def test_preset():
print("\nTesting update preset")
update_data = {
"name": "test_preset",
"pattern": "colour_cycle",
"pattern": "on",
"colors": ["#FF0000", "#00FF00"],
"delay": 100,
"brightness": 127,
"n1": 10,
"n2": 20,
"mode": 1,
"n2": 20
}
result = presets.update(preset_id, update_data)
assert result is True
updated = presets.read(preset_id)
assert updated["name"] == "test_preset"
assert updated["pattern"] == "colour_cycle"
assert updated["mode"] == 1
assert updated["pattern"] == "on"
assert updated["delay"] == 100
print("\nTesting list presets")
+20 -41
View File
@@ -1,19 +1,16 @@
from models.sequence import Sequence
import os
_HERE = os.path.dirname(os.path.abspath(__file__))
_PROJECT_DB = os.path.normpath(os.path.join(_HERE, "..", "..", "db", "sequence.json"))
from models.squence import Sequence
def test_sequence():
"""Test Sequence model CRUD operations."""
if os.path.exists(_PROJECT_DB):
os.remove(_PROJECT_DB)
sequences = Sequence()
print("Testing create sequence")
sequence_id = sequences.create("1")
sequence_id = sequences.create({
"name": "test_sequence",
"zone_id": "1",
"steps": [{"preset_id": "preset1", "duration_s": 3}, {"preset_id": "preset2"}],
})
print(f"Created sequence with ID: {sequence_id}")
assert sequence_id is not None
assert sequence_id in sequences
@@ -22,45 +19,27 @@ def test_sequence():
sequence = sequences.read(sequence_id)
print(f"Read: {sequence}")
assert sequence is not None
assert sequence["profile_id"] == "1"
assert sequence["steps"] == []
assert sequence["lanes"] == [[]]
assert sequence.get("lanes_group_ids") == [[]]
assert sequence.get("advance_mode") == "beats"
assert sequence.get("simulated_bpm") == 120
assert sequence["step_duration_ms"] == 3000
assert sequence["name"] == "test_sequence"
assert sequence["zone_id"] == "1"
assert [s["preset_id"] for s in sequence["steps"]] == ["preset1", "preset2"]
assert sequence["steps"][1]["duration_s"] == 5.0
assert sequence["loop"] is True
assert sequence.get("sequence_transition") == 500
assert sequence["active"] is False
print("\nTesting update sequence")
update_data = {
"name": "updated_seq",
"steps": [
{"preset_id": "5", "group_ids": ["1"], "beats": 2},
{"preset_id": "6", "group_ids": [], "beats": 4},
],
"lanes_group_ids": [["1"]],
"step_duration_ms": 5000,
"loop": True,
"advance_mode": "beats",
"simulated_bpm": 128,
"name": "updated_sequence",
"steps": [{"preset_id": p, "duration_s": 2} for p in ("preset3", "preset4", "preset5")],
"loop": False,
"repeat_count": 3,
}
result = sequences.update(sequence_id, update_data)
assert result is True
updated = sequences.read(sequence_id)
assert updated["name"] == "updated_seq"
assert len(updated["steps"]) == 2
assert updated["steps"][0]["preset_id"] == "5"
assert updated["steps"][0]["group_ids"] == ["1"]
assert updated["steps"][0].get("beats") == 2
assert isinstance(updated.get("lanes"), list)
assert len(updated["lanes"]) == 1
assert len(updated["lanes"][0]) == 2
assert updated["lanes"][0][0]["beats"] == 2
assert updated.get("advance_mode") == "beats"
assert updated.get("simulated_bpm") == 128
assert updated["step_duration_ms"] == 5000
assert updated["loop"] is True
assert updated["name"] == "updated_sequence"
assert len(updated["steps"]) == 3
assert updated["loop"] is False
assert updated["repeat_count"] == 3
print("\nTesting list sequences")
sequence_list = sequences.list()
@@ -79,5 +58,5 @@ def test_sequence():
print("\nAll sequence tests passed!")
if __name__ == "__main__":
if __name__ == '__main__':
test_sequence()
-171
View File
@@ -1,171 +0,0 @@
#!/usr/bin/env python3
"""Play a click track with tempo variation for BPM detector testing.
Examples:
python tests/play_varying_click_track.py --start-bpm 90 --end-bpm 150 --seconds 60
python tests/play_varying_click_track.py --pattern steps --step-bpms 100,120,140,160 --step-seconds 8
"""
from __future__ import annotations
import argparse
import math
import time
import numpy as np
import sounddevice as sd
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Play varying-BPM click track")
parser.add_argument("--device", default=None, help="Output audio device name or index")
parser.add_argument("--sample-rate", type=int, default=44100, help="Output sample rate")
parser.add_argument("--seconds", type=float, default=60.0, help="Playback duration")
parser.add_argument(
"--stabilize-seconds",
type=float,
default=5.0,
help="Play initial BPM for this many seconds before varying",
)
parser.add_argument("--pattern", choices=("sweep", "steps"), default="sweep")
# Sweep options
parser.add_argument("--start-bpm", type=float, default=90.0, help="Sweep start BPM")
parser.add_argument("--end-bpm", type=float, default=150.0, help="Sweep end BPM")
# Step options
parser.add_argument(
"--step-bpms",
default="100,120,140,160",
help="Comma-separated BPMs for step mode",
)
parser.add_argument("--step-seconds", type=float, default=8.0, help="Seconds per BPM step")
# Click tone options
parser.add_argument("--click-ms", type=float, default=25.0, help="Click duration")
parser.add_argument("--accent-every", type=int, default=4, help="Accent every N beats")
parser.add_argument(
"--hold-beats",
type=int,
default=1,
help="Hold BPM for this many beats before recalculating",
)
return parser.parse_args()
def bpm_for_time(t_s: float, args: argparse.Namespace, step_bpms: list[float]) -> float:
if t_s < args.stabilize_seconds:
return args.start_bpm if args.pattern == "sweep" else (step_bpms[0] if step_bpms else 120.0)
adj_t = t_s - args.stabilize_seconds
if args.pattern == "sweep":
active_seconds = max(1e-6, args.seconds - args.stabilize_seconds)
if active_seconds <= 0:
return args.start_bpm
alpha = min(1.0, max(0.0, adj_t / active_seconds))
return args.start_bpm + (args.end_bpm - args.start_bpm) * alpha
if not step_bpms:
return 120.0
if args.step_seconds <= 0:
return step_bpms[0]
idx = int(adj_t // args.step_seconds) % len(step_bpms)
return step_bpms[idx]
def main() -> int:
args = parse_args()
if args.seconds <= 0:
raise SystemExit("--seconds must be > 0")
if args.sample_rate <= 0:
raise SystemExit("--sample-rate must be > 0")
step_bpms = [float(x.strip()) for x in args.step_bpms.split(",") if x.strip()]
click_samples = max(1, int(args.click_ms * args.sample_rate / 1000.0))
state = {
"t": 0.0, # playback time in seconds
"next_beat": 0.0,
"beat_idx": 0,
"current_bpm": 0.0,
"held_bpm": 0.0,
"hold_counter": 0,
"click_remaining": 0,
"click_phase": 0,
"click_freq": 1320.0,
"click_amp": 0.6,
}
def callback(outdata, frames, _time_info, status):
if status:
print(f"audio status: {status}")
block = np.zeros(frames, dtype=np.float32)
for i in range(frames):
t = state["t"]
dynamic_bpm = bpm_for_time(t, args, step_bpms)
state["current_bpm"] = dynamic_bpm
bpm = state["held_bpm"] if state["held_bpm"] > 0 else dynamic_bpm
beat_interval = 60.0 / max(1e-6, bpm)
if t >= state["next_beat"]:
hold_beats = max(1, int(args.hold_beats))
if state["hold_counter"] <= 0:
state["held_bpm"] = dynamic_bpm
state["hold_counter"] = hold_beats
state["hold_counter"] -= 1
bpm = state["held_bpm"]
beat_interval = 60.0 / max(1e-6, bpm)
state["beat_idx"] += 1
state["next_beat"] = t + beat_interval
state["click_remaining"] = click_samples
state["click_phase"] = 0
accented = (
args.accent_every > 0 and state["beat_idx"] % args.accent_every == 1
)
state["click_freq"] = 1760.0 if accented else 1320.0
state["click_amp"] = 0.9 if accented else 0.6
if state["click_remaining"] > 0:
p = state["click_phase"]
env = math.exp(-8.0 * (p / click_samples))
sample = state["click_amp"] * env * math.sin(
2.0 * math.pi * state["click_freq"] * (p / args.sample_rate)
)
block[i] = sample
state["click_phase"] += 1
state["click_remaining"] -= 1
state["t"] += 1.0 / args.sample_rate
outdata[:, 0] = block
print(
f"Playing varying click track for {args.seconds:.1f}s ({args.pattern}), "
f"stabilize={args.stabilize_seconds:.1f}s"
)
with sd.OutputStream(
samplerate=args.sample_rate,
channels=1,
dtype="float32",
callback=callback,
device=args.device,
blocksize=0,
):
start = time.time()
last_printed_beat = 0
while (time.time() - start) < args.seconds:
beat_idx = int(state["beat_idx"])
if beat_idx != last_printed_beat:
last_printed_beat = beat_idx
print(
f"beat={beat_idx:04d} bpm={state['held_bpm']:.2f} "
f"(target={state['current_bpm']:.2f})"
)
time.sleep(0.05)
print("Done.")
return 0
if __name__ == "__main__":
raise SystemExit(main())
-61
View File
@@ -1,61 +0,0 @@
"""Reset detector must not stop the stream or clear ``running``."""
import os
import sys
import time
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC_PATH = os.path.join(PROJECT_ROOT, "src")
if SRC_PATH not in sys.path:
sys.path.insert(0, SRC_PATH)
from util.audio_detector import AudioBeatDetector # noqa: E402
class _FakeRuntime:
def __init__(self):
self.reset_calls = 0
def reset_state(self):
self.reset_calls += 1
def test_reset_tracking_false_when_not_running():
det = AudioBeatDetector()
assert det.reset_tracking() is False
def test_reset_tracking_queues_on_audio_thread():
det = AudioBeatDetector()
rt = _FakeRuntime()
with det._lock:
det._running = True
det._runtime = rt
det._status["running"] = True
det._status["bpm"] = 128.0
det._status["beat_seq"] = 7
assert det.reset_tracking() is True
assert rt.reset_calls == 0
assert det._pending_reset is True
st = det.status()
assert st["running"] is True
assert st["bpm"] == 128.0
assert st["beat_seq"] == 7
det._process_pending_reset(rt)
assert rt.reset_calls == 1
assert det._pending_reset is False
assert det.status()["running"] is True
def test_status_keeps_bpm_during_holdover():
det = AudioBeatDetector()
with det._lock:
det._running = True
det._holdover_active = True
det._status["running"] = True
det._status["bpm"] = 128.0
det._status["last_beat_ts"] = time.time() - 10.0
assert det.status()["bpm"] == 128.0
-70
View File
@@ -1,70 +0,0 @@
"""Bar phase (beat-in-bar) tracking for audio beat detection."""
import os
import sys
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if PROJECT_ROOT not in sys.path:
sys.path.insert(0, PROJECT_ROOT)
from tests.beat_detect import BarPhaseTracker # noqa: E402
def test_bar_phase_increments_on_non_kick_beats():
tr = BarPhaseTracker(beats_per_bar=4)
r1 = tr.on_beat(1.0, "snare", 1.3, bpm=120.0)
assert r1["bar_beat"] == 1
r2 = tr.on_beat(1.5, "snare", 1.2, bpm=120.0)
assert r2["bar_beat"] == 2
r3 = tr.on_beat(2.0, "hat", 1.1, bpm=120.0)
assert r3["bar_beat"] == 3
def test_kick_near_bar_boundary_resets_to_downbeat():
tr = BarPhaseTracker(beats_per_bar=4)
tr.on_beat(0.0, "kick", 1.4, bpm=120.0)
tr.on_beat(0.5, "snare", 1.2, bpm=120.0)
tr.on_beat(1.0, "snare", 1.2, bpm=120.0)
tr.on_beat(1.5, "snare", 1.2, bpm=120.0)
r = tr.on_beat(2.0, "kick", 1.5, bpm=120.0)
assert r["bar_beat"] == 1
assert r["is_downbeat"] is True
def test_anchor_downbeat_sets_confidence():
tr = BarPhaseTracker(beats_per_bar=4)
tr.anchor_downbeat(10.0)
assert tr.bar_beat == 1
assert tr.confidence >= 0.85
def test_reset_tempo_preserves_bar_phase():
from argparse import Namespace
from tests.beat_detect import BeatDetectRuntime # noqa: E402
args = Namespace(
mode="custom",
hop_size=256,
win_mult=2,
min_band_hz=45.0,
max_band_hz=180.0,
energy_weight=0.7,
flux_weight=0.3,
threshold_multiplier=1.35,
ema_alpha=0.08,
min_ioi_ms=100.0,
bpm_window=8,
aubio_method="default",
aubio_threshold=0.12,
beats_per_bar=4,
)
rt = BeatDetectRuntime(args)
rt.setup(44100)
rt.bar_phase.on_beat(0.0, "kick", 1.5, bpm=120.0)
rt.bar_phase.on_beat(0.5, "snare", 1.2, bpm=120.0)
assert rt.bar_phase.bar_beat == 2
rt.reset_tempo_state()
assert rt.bar_phase.bar_beat == 2
rt.reset_state()
assert rt.bar_phase.bar_beat == 1
-28
View File
@@ -1,28 +0,0 @@
"""Beat interval plausibility helpers (audio detector)."""
import os
import sys
from collections import deque
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if PROJECT_ROOT not in sys.path:
sys.path.insert(0, PROJECT_ROOT)
from tests.beat_detect import _is_plausible_ioi, _resolve_bpm # noqa: E402
def test_is_plausible_ioi_rejects_double_time():
times = deque([0.0, 0.5, 1.0])
assert _is_plausible_ioi(1.0, times, 1.15) is False
def test_is_plausible_ioi_accepts_steady_grid():
times = deque([0.0, 0.5, 1.0])
assert _is_plausible_ioi(1.0, times, 1.5) is True
def test_resolve_bpm_prefers_intervals_over_wrong_aubio():
times = deque([0.0, 0.5, 1.0, 1.5, 2.0])
bpm = _resolve_bpm(times, 70.0)
assert bpm is not None
assert abs(bpm - 120.0) < 5.0
-105
View File
@@ -1,105 +0,0 @@
"""Manual beat route: suppress duplicate select after sequence step change."""
import os
import sys
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC_PATH = os.path.join(PROJECT_ROOT, "src")
if SRC_PATH not in sys.path:
sys.path.insert(0, SRC_PATH)
from util import beat_driver_route as bdr # noqa: E402
def _patch_delivery(monkeypatch):
delivered = []
async def fake_batch(pairs):
delivered.extend(pairs)
def fake_schedule(coro, _loop):
import asyncio
asyncio.run(coro)
monkeypatch.setattr(bdr, "_deliver_select_batch", fake_batch)
monkeypatch.setattr(bdr, "_main_loop", object())
monkeypatch.setattr("asyncio.run_coroutine_threadsafe", fake_schedule)
return delivered
def test_suppress_next_notify_skips_one_select(monkeypatch):
delivered = _patch_delivery(monkeypatch)
bdr.set_sequence_manual_lane_route(
0,
["desk"],
"5",
{"p": "chase", "a": False, "manual_beat_n": 1},
)
bdr.mark_sequence_manual_lane_select_sent(0)
bdr.notify_beat_detected()
assert delivered == []
bdr.notify_beat_detected()
assert delivered == [(["desk"], "5")]
def test_suppress_does_not_advance_beat_counter(monkeypatch):
delivered = _patch_delivery(monkeypatch)
bdr.set_sequence_manual_lane_route(
0,
["desk"],
"42",
{"p": "radiate", "a": False, "manual_beat_n": 2},
)
bdr.mark_sequence_manual_lane_select_sent(0)
bdr.notify_beat_detected()
assert delivered == []
bdr.notify_beat_detected()
assert delivered == [(["desk"], "42")]
delivered.clear()
bdr.notify_beat_detected()
assert delivered == []
bdr.notify_beat_detected()
assert delivered == [(["desk"], "42")]
def test_duplicate_lanes_dedupe_to_one_select_per_beat(monkeypatch):
delivered = _patch_delivery(monkeypatch)
body = {"p": "radiate", "a": False, "manual_beat_n": 1}
entry = {
"device_names": ["desk"],
"wire_preset_id": "42",
"pattern": "radiate",
"manual_beat_n": 1,
"beat_counter": 0,
}
with bdr._route_lock:
bdr._lane_manual.clear()
bdr._lane_manual[-1] = dict(entry)
bdr._lane_manual[0] = dict(entry)
bdr.notify_beat_detected()
assert delivered == [(["desk"], "42")]
def test_standalone_overlay_skipped_when_sequence_lane_covers(monkeypatch):
delivered = _patch_delivery(monkeypatch)
body = {"p": "radiate", "a": False, "manual_beat_n": 1}
bdr.set_sequence_manual_lane_route(1, ["desk"], "42", body)
bdr._apply_manual_beat_route_standalone_overlay(["desk"], "42", body)
with bdr._route_lock:
assert -1 not in bdr._lane_manual
assert 1 in bdr._lane_manual
bdr.notify_beat_detected()
assert delivered == [(["desk"], "42")]
-15
View File
@@ -29,21 +29,6 @@ def test_pack_parse_v2_brightness_only():
assert data == {"v": "1", "b": 128}
def test_pack_parse_v2_mode_maps_to_n6():
raw = pack_binary_envelope_v2(
presets={
"m": {
"p": "meteor",
"c": ["#aabbcc"],
"mode": 2,
"n6": 0,
}
},
)
data = parse_binary_envelope_v2(raw)
assert data["presets"]["m"]["n6"] == 2
def test_pack_parse_v2_full():
raw = pack_binary_envelope_v2(
presets={
+2 -45
View File
@@ -2,7 +2,7 @@
"""
Browser automation tests using Selenium.
Tests run against the device in an actual browser. Target host defaults to
``127.0.0.1:5000``; override with ``LED_CONTROLLER_DEVICE_IP`` (IP or hostname,
``192.168.4.1``; override with ``LED_CONTROLLER_DEVICE_IP`` (IP or hostname,
or a full ``http://`` / ``https://`` base URL).
Fixed delays between UI steps use ``LED_CONTROLLER_BROWSER_SLEEP_SCALE``
@@ -49,7 +49,7 @@ from selenium.common.exceptions import (
ElementNotInteractableException,
)
_DEFAULT_DEVICE_HOST = "127.0.0.1:5000"
_DEFAULT_DEVICE_HOST = "192.168.4.1"
def _device_base_url() -> str:
@@ -750,46 +750,6 @@ def test_presets_ui(browser: BrowserTest) -> bool:
print(f"\nBrowser presets UI tests: {passed}/{total} passed")
return passed == total
def test_preset_editor_palette_child_modal_zindex(browser: BrowserTest) -> bool:
"""
Regression: preset editor 'From Palette' builds a body-appended .modal without an id.
It must use .modal-child-overlay so z-index clears #preset-editor-modal (1060).
"""
print("\n=== Testing preset child overlay z-index ===")
if not browser.setup():
return False
try:
if not browser.navigate("/"):
return False
z_editor, z_child = browser.driver.execute_script(
"""
const ed = document.getElementById('preset-editor-modal');
if (!ed) { return [0, 0]; }
ed.classList.add('active');
const m = document.createElement('div');
m.className = 'modal active modal-child-overlay';
m.innerHTML = '<div class="modal-content"><p>stack probe</p></div>';
document.body.appendChild(m);
const ze = parseInt(getComputedStyle(ed).zIndex, 10) || 0;
const zc = parseInt(getComputedStyle(m).zIndex, 10) || 0;
m.remove();
ed.classList.remove('active');
return [ze, zc];
"""
)
print(f" preset-editor z-index={z_editor} modal-child-overlay z-index={z_child}")
if z_child > z_editor >= 1000:
print("✓ Child overlay stacks above preset editor")
return True
print("✗ Child overlay did not stack above preset editor")
return False
except Exception as e:
print(f"✗ z-index probe failed: {e}")
return False
finally:
browser.teardown()
def test_color_palette_ui(browser: BrowserTest) -> bool:
"""Test color palette UI in browser."""
print("\n=== Testing Color Palette UI in Browser ===")
@@ -1145,9 +1105,6 @@ def main():
results.append(("Zones UI", test_zones_ui(browser)))
results.append(("Profiles UI", test_profiles_ui(browser)))
results.append(("Presets UI", test_presets_ui(browser)))
results.append(
("Preset palette child z-index", test_preset_editor_palette_child_modal_zindex(browser))
)
results.append(("Color Palette UI", test_color_palette_ui(browser)))
results.append(("Preset Drag and Drop", test_preset_drag_and_drop(browser)))
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more