Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a5a7fc575f | ||
|
|
827eb97203 | ||
|
|
3cca0cffc5 | ||
|
|
d36828bde2 | ||
|
|
ed0048c795 | ||
|
|
b316edbaf9 | ||
|
|
c1b0c41ef2 | ||
|
|
3bb75d49de | ||
|
|
3d77cb448a | ||
|
|
49383c0003 | ||
|
|
7d821b9c1c | ||
|
|
9b7e387ea6 | ||
|
|
b4f0d1891e |
No files matched your search
@@ -25,6 +25,7 @@ ENV/
|
||||
Thumbs.db
|
||||
|
||||
# Project specific
|
||||
scripts/.led-controller-venv
|
||||
docs/.help-print.html
|
||||
settings.json
|
||||
*.log
|
||||
|
||||
@@ -4,3 +4,6 @@
|
||||
[submodule "led-tool"]
|
||||
path = led-tool
|
||||
url = git@git.technical.kiwi:technicalkiwi/led-tool.git
|
||||
[submodule "led-simulator"]
|
||||
path = led-simulator
|
||||
url = git@git.technical.kiwi:technicalkiwi/led-simulator.git
|
||||
@@ -19,7 +19,7 @@ websockets = "*"
|
||||
pytest = "*"
|
||||
|
||||
[requires]
|
||||
python_version = "3.12"
|
||||
python_version = "3.11"
|
||||
|
||||
[scripts]
|
||||
web = "python /home/pi/led-controller/tests/web.py"
|
||||
|
||||
Generated
+68
-79
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"_meta": {
|
||||
"hash": {
|
||||
"sha256": "18691f772c7660e4a087c90560c87a9217a09e9b6db97825d21c092a06d64b89"
|
||||
"sha256": "98da2012e549e7b62ed49a5e1717acaf535b71e8df61bf4108d25b9023be612e"
|
||||
},
|
||||
"pipfile-spec": 6,
|
||||
"requires": {
|
||||
"python_version": "3.12"
|
||||
"python_version": "3.11"
|
||||
},
|
||||
"sources": [
|
||||
{
|
||||
@@ -159,11 +159,11 @@
|
||||
},
|
||||
"certifi": {
|
||||
"hashes": [
|
||||
"sha256:027692e4402ad994f1c42e52a4997a9763c646b73e4096e4d5d6db8af1d6f0fa",
|
||||
"sha256:e887ab5cee78ea814d3472169153c2d12cd43b14bd03329a39a9c6e2e80bfba7"
|
||||
"sha256:3cb2210c8f88ba2318d29b0388d1023c8492ff72ecdde4ebdaddbb13a31b1c4a",
|
||||
"sha256:8d455352a37b71bf76a79caa83a3d6c25afee4a385d632127b6afb3963f1c580"
|
||||
],
|
||||
"markers": "python_version >= '3.7'",
|
||||
"version": "==2026.2.25"
|
||||
"version": "==2026.4.22"
|
||||
},
|
||||
"cffi": {
|
||||
"hashes": [
|
||||
@@ -392,73 +392,72 @@
|
||||
},
|
||||
"click": {
|
||||
"hashes": [
|
||||
"sha256:14162b8b3b3550a7d479eafa77dfd3c38d9dc8951f6f69c78913a8f9a7540fd5",
|
||||
"sha256:1924d2c27c5653561cd2cae4548d1406039cb79b858b747cfea24924bbc1616d"
|
||||
"sha256:398329ad4837b2ff7cbe1dd166a4c0f8900c3ca3a218de04466f38f6497f18a2",
|
||||
"sha256:a2bf429bb3033c89fa4936ffb35d5cb471e3719e1f3c8a7c3fff0b8314305613"
|
||||
],
|
||||
"markers": "python_version >= '3.10'",
|
||||
"version": "==8.3.2"
|
||||
"version": "==8.3.3"
|
||||
},
|
||||
"cryptography": {
|
||||
"hashes": [
|
||||
"sha256:04959522f938493042d595a736e7dbdff6eb6cc2339c11465b3ff89343b65f65",
|
||||
"sha256:128c5edfe5e5938b86b03941e94fac9ee793a94452ad1365c9fc3f4f62216832",
|
||||
"sha256:1d25aee46d0c6f1a501adcddb2d2fee4b979381346a78558ed13e50aa8a59067",
|
||||
"sha256:24402210aa54baae71d99441d15bb5a1919c195398a87b563df84468160a65de",
|
||||
"sha256:258514877e15963bd43b558917bc9f54cf7cf866c38aa576ebf47a77ddbc43a4",
|
||||
"sha256:35719dc79d4730d30f1c2b6474bd6acda36ae2dfae1e3c16f2051f215df33ce0",
|
||||
"sha256:397655da831414d165029da9bc483bed2fe0e75dde6a1523ec2fe63f3c46046b",
|
||||
"sha256:3986ac1dee6def53797289999eabe84798ad7817f3e97779b5061a95b0ee4968",
|
||||
"sha256:420b1e4109cc95f0e5700eed79908cef9268265c773d3a66f7af1eef53d409ef",
|
||||
"sha256:42a1e5f98abb6391717978baf9f90dc28a743b7d9be7f0751a6f56a75d14065b",
|
||||
"sha256:462ad5cb1c148a22b2e3bcc5ad52504dff325d17daf5df8d88c17dda1f75f2a4",
|
||||
"sha256:506c4ff91eff4f82bdac7633318a526b1d1309fc07ca76a3ad182cb5b686d6d3",
|
||||
"sha256:5ad9ef796328c5e3c4ceed237a183f5d41d21150f972455a9d926593a1dcb308",
|
||||
"sha256:5d1c02a14ceb9148cc7816249f64f623fbfee39e8c03b3650d842ad3f34d637e",
|
||||
"sha256:5e51be372b26ef4ba3de3c167cd3d1022934bc838ae9eaad7e644986d2a3d163",
|
||||
"sha256:60627cf07e0d9274338521205899337c5d18249db56865f943cbe753aa96f40f",
|
||||
"sha256:65814c60f8cc400c63131584e3e1fad01235edba2614b61fbfbfa954082db0ee",
|
||||
"sha256:73510b83623e080a2c35c62c15298096e2a5dc8d51c3b4e1740211839d0dea77",
|
||||
"sha256:7bbc6ccf49d05ac8f7d7b5e2e2c33830d4fe2061def88210a126d130d7f71a85",
|
||||
"sha256:80406c3065e2c55d7f49a9550fe0c49b3f12e5bfff5dedb727e319e1afb9bf99",
|
||||
"sha256:84d4cced91f0f159a7ddacad249cc077e63195c36aac40b4150e7a57e84fffe7",
|
||||
"sha256:8a469028a86f12eb7d2fe97162d0634026d92a21f3ae0ac87ed1c4a447886c83",
|
||||
"sha256:91bbcb08347344f810cbe49065914fe048949648f6bd5c2519f34619142bbe85",
|
||||
"sha256:935ce7e3cfdb53e3536119a542b839bb94ec1ad081013e9ab9b7cfd478b05006",
|
||||
"sha256:9694078c5d44c157ef3162e3bf3946510b857df5a3955458381d1c7cfc143ddb",
|
||||
"sha256:a1529d614f44b863a7b480c6d000fe93b59acee9c82ffa027cfadc77521a9f5e",
|
||||
"sha256:abad9dac36cbf55de6eb49badd4016806b3165d396f64925bf2999bcb67837ba",
|
||||
"sha256:b36a4695e29fe69215d75960b22577197aca3f7a25b9cf9d165dcfe9d80bc325",
|
||||
"sha256:b7b412817be92117ec5ed95f880defe9cf18a832e8cafacf0a22337dc1981b4d",
|
||||
"sha256:c5b1ccd1239f48b7151a65bc6dd54bcfcc15e028c8ac126d3fada09db0e07ef1",
|
||||
"sha256:cbd5fb06b62bd0721e1170273d3f4d5a277044c47ca27ee257025146c34cbdd1",
|
||||
"sha256:cdf1a610ef82abb396451862739e3fc93b071c844399e15b90726ef7470eeaf2",
|
||||
"sha256:cdfbe22376065ffcf8be74dc9a909f032df19bc58a699456a21712d6e5eabfd0",
|
||||
"sha256:d02c738dacda7dc2a74d1b2b3177042009d5cab7c7079db74afc19e56ca1b455",
|
||||
"sha256:d151173275e1728cf7839aaa80c34fe550c04ddb27b34f48c232193df8db5842",
|
||||
"sha256:d23c8ca48e44ee015cd0a54aeccdf9f09004eba9fc96f38c911011d9ff1bd457",
|
||||
"sha256:d3b99c535a9de0adced13d159c5a9cf65c325601aa30f4be08afd680643e9c15",
|
||||
"sha256:d5f7520159cd9c2154eb61eb67548ca05c5774d39e9c2c4339fd793fe7d097b2",
|
||||
"sha256:db0f493b9181c7820c8134437eb8b0b4792085d37dbb24da050476ccb664e59c",
|
||||
"sha256:e06acf3c99be55aa3b516397fe42f5855597f430add9c17fa46bf2e0fb34c9bb",
|
||||
"sha256:e4cfd68c5f3e0bfdad0d38e023239b96a2fe84146481852dffbcca442c245aa5",
|
||||
"sha256:ea42cbe97209df307fdc3b155f1b6fa2577c0defa8f1f7d3be7d31d189108ad4",
|
||||
"sha256:ebd6daf519b9f189f85c479427bbd6e9c9037862cf8fe89ee35503bd209ed902",
|
||||
"sha256:f247c8c1a1fb45e12586afbb436ef21ff1e80670b2861a90353d9b025583d246",
|
||||
"sha256:fbfd0e5f273877695cb93baf14b185f4878128b250cc9f8e617ea0c025dfb022",
|
||||
"sha256:fc9ab8856ae6cf7c9358430e49b368f3108f050031442eaeb6b9d87e4dcf4e4f",
|
||||
"sha256:fcd8eac50d9138c1d7fc53a653ba60a2bee81a505f9f8850b6b2888555a45d0e",
|
||||
"sha256:fdd1736fed309b4300346f88f74cd120c27c56852c3838cab416e7a166f67298",
|
||||
"sha256:ffca7aa1d00cf7d6469b988c581598f2259e46215e0140af408966a24cf086ce"
|
||||
"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.8' and python_full_version not in '3.9.0, 3.9.1'",
|
||||
"version": "==46.0.7"
|
||||
"version": "==47.0.0"
|
||||
},
|
||||
"esptool": {
|
||||
"hashes": [
|
||||
"sha256:9c355b7d6331cc92979cc710ae5c41f59830d1ea29ec24c467c6005a092c06d6"
|
||||
],
|
||||
"index": "pypi",
|
||||
"markers": "python_version >= '3.10'",
|
||||
"version": "==5.2.0"
|
||||
},
|
||||
"h11": {
|
||||
@@ -471,11 +470,11 @@
|
||||
},
|
||||
"idna": {
|
||||
"hashes": [
|
||||
"sha256:771a87f49d9defaf64091e6e6fe9c18d4833f140bd19464795bc32d966ca37ea",
|
||||
"sha256:795dafcc9c04ed0c1fb032c2aa73654d8e8c5023a7df64a53f39190ada629902"
|
||||
"sha256:585ea8fe5d69b9181ec1afba340451fba6ba764af97026f92a91d4eef164a242",
|
||||
"sha256:892ea0cde124a99ce773decba204c5552b69c3c67ffd5f232eb7696135bc8bb3"
|
||||
],
|
||||
"markers": "python_version >= '3.8'",
|
||||
"version": "==3.11"
|
||||
"version": "==3.13"
|
||||
},
|
||||
"intelhex": {
|
||||
"hashes": [
|
||||
@@ -502,12 +501,11 @@
|
||||
},
|
||||
"microdot": {
|
||||
"hashes": [
|
||||
"sha256:363e3ebfc80b7e0415779848c9332e4e7fb7bd365ee54d3620abffe42ed82946",
|
||||
"sha256:abfb82ca31cc430174e4761cc7356adc4bff00ea758d437c2b258883dc63f464"
|
||||
"sha256:3ba8bab39ae52bca08ee7024dfc71afb7cff089f0b6611d2a1f617abfcee749c",
|
||||
"sha256:d56824f4510e628dac711c86121957894ceaf833298e4d25f06c29d2b19a1721"
|
||||
],
|
||||
"index": "pypi",
|
||||
"markers": "python_version >= '3.8'",
|
||||
"version": "==2.6.0"
|
||||
"version": "==2.6.1"
|
||||
},
|
||||
"mpremote": {
|
||||
"hashes": [
|
||||
@@ -515,7 +513,6 @@
|
||||
"sha256:fdb5626be83dff4e53c0184f8950814cb519b524dba7f1f8b1668aa477257a31"
|
||||
],
|
||||
"index": "pypi",
|
||||
"markers": "python_version >= '3.4'",
|
||||
"version": "==1.28.0"
|
||||
},
|
||||
"outcome": {
|
||||
@@ -556,7 +553,6 @@
|
||||
"sha256:c74a7a2adf861c04d002db713dd85f84beb242228e671280bf709d765b03672b"
|
||||
],
|
||||
"index": "pypi",
|
||||
"markers": "python_version >= '3.9'",
|
||||
"version": "==2.12.1"
|
||||
},
|
||||
"pyserial": {
|
||||
@@ -675,7 +671,6 @@
|
||||
"sha256:4e6d1ef462f3626a1f0a0a9c42dd93c63bad33f9f1c1937509b8c5c8718ab56a"
|
||||
],
|
||||
"index": "pypi",
|
||||
"markers": "python_version >= '3.10'",
|
||||
"version": "==2.33.1"
|
||||
},
|
||||
"rich": {
|
||||
@@ -700,7 +695,6 @@
|
||||
"sha256:bada5c08a989f812728a4b5bea884d8e91894e939a441cc3a025201ce718581e"
|
||||
],
|
||||
"index": "pypi",
|
||||
"markers": "python_version >= '3.10'",
|
||||
"version": "==4.43.0"
|
||||
},
|
||||
"sniffio": {
|
||||
@@ -780,9 +774,7 @@
|
||||
"version": "==4.15.0"
|
||||
},
|
||||
"urllib3": {
|
||||
"extras": [
|
||||
"socks"
|
||||
],
|
||||
"extras": [],
|
||||
"hashes": [
|
||||
"sha256:1b62b6884944a57dbe321509ab94fd4d3b307075e0c2eae991ac71ee15ad38ed",
|
||||
"sha256:bf272323e553dfb2e87d9bfd225ca7b0f467b919d7bbd355436d3fd37cb0acd4"
|
||||
@@ -903,7 +895,6 @@
|
||||
"sha256:f9a2ae5c91cecc9edd47e041a930490c31c3afb1f5e6d71de3dc671bfaca02bf"
|
||||
],
|
||||
"index": "pypi",
|
||||
"markers": "python_version >= '3.9'",
|
||||
"version": "==1.1.1"
|
||||
},
|
||||
"websocket-client": {
|
||||
@@ -979,7 +970,6 @@
|
||||
"sha256:fd3cb4adb94a2a6e2b7c0d8d05cb94e6f1c81a0cf9dc2694fb65c7e8d94c42e4"
|
||||
],
|
||||
"index": "pypi",
|
||||
"markers": "python_version >= '3.10'",
|
||||
"version": "==16.0"
|
||||
},
|
||||
"wsproto": {
|
||||
@@ -1002,11 +992,11 @@
|
||||
},
|
||||
"packaging": {
|
||||
"hashes": [
|
||||
"sha256:00243ae351a257117b6a241061796684b084ed1c516a08c48a3f7e147a9d80b4",
|
||||
"sha256:b36f1fef9334a5588b4166f8bcd26a14e521f2b55e6b9de3aaa80d3ff7a37529"
|
||||
"sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e",
|
||||
"sha256:ff452ff5a3e828ce110190feff1178bb1f2ea2281fa2075aadb987c2fb221661"
|
||||
],
|
||||
"markers": "python_version >= '3.8'",
|
||||
"version": "==26.0"
|
||||
"version": "==26.2"
|
||||
},
|
||||
"pluggy": {
|
||||
"hashes": [
|
||||
@@ -1030,7 +1020,6 @@
|
||||
"sha256:b86ada508af81d19edeb213c681b1d48246c1a91d304c6c81a427674c17eb91c"
|
||||
],
|
||||
"index": "pypi",
|
||||
"markers": "python_version >= '3.10'",
|
||||
"version": "==9.0.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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`.
|
||||
@@ -0,0 +1 @@
|
||||
{}
|
||||
Binary file not shown.
@@ -0,0 +1,3 @@
|
||||
PRST1xœ%ÎÁ
|
||||
Â0Ð_‘ñšCSµJîæ'D$¶«␍ÄÝ’¦ˆˆÿntOovæ²opxz‘´zޱ¦P
|
||||
e®µp={I’g¸ÖÇηÞãlpÍñ>¦¹mÓ”ÂÎþrXŠÀ•¼�[¸Zq«l”²S:e¯þLYn1Ñ%õ‹Ï ¥/ï
|
||||
@@ -0,0 +1,2 @@
|
||||
PRST1xњ%ОAВ …б»<·,J5\Е4␍К $84SX4Ж»‹eхеНlюШЅ B
|
||||
‹+…„ЫОЬж#§,+м␍‡@ЖЏIб.сщ*Lk{ЊЖ(xJnѓХГ аjЙ°E*)°†m';ЗО©c:зОҐsЭY$‡�hЋѕuиЅ*Qлљ…В?†kJУчП=5Я
|
||||
@@ -0,0 +1 @@
|
||||
PRST1xœ%ÎA л|·, ŠÐK˜ÆP;* ␍……1Þ݉3›—ÿÿf>àø"Ì¹ÖØU–¢°Ä[É¥nì¬Ü8b2˜kz<Ó&Ãà½ÁB9¾œµ±·‚Ðj'vRñ 앃╣rRÎÖZî)Ó5-ò‡Ã÷yÒ-€
|
||||
@@ -0,0 +1,2 @@
|
||||
PRST1xœEÎÁ
|
||||
Â0Ð_‘9ç`«Qɯˆ”Ô®ˆ»e“RDüwsðô˜™Ë¼ÁñIИx”uS²¬p˜c¤ü¬»J-ç‹Ã¨éþ¨LÅrï½ÃD9¾:¿uˆK„ª9pg¥Ñ#ØÂ»Æ¾á‡Æ±qú1«ÜR¦!Mö¡Ãç��1
|
||||
@@ -0,0 +1,2 @@
|
||||
PRST1xœ=ÎÝ
|
||||
!†á[‰¯StK[¼€½‰ˆ°v*ÁTü!"º÷Ü¤Žžá�9˜¼¹4bu™VÙ…¢)…’ÿåVÎÁ…”¡÷XO“RœãÀpJöz+žr[R2ÌäÌzäœÁÔ KªÄàE;àKõ´èÓæß¶Ð²£:»Îø%¦p±ŽŽvn? ¼?�¨2ú
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,2 @@
|
||||
PRST1xœUÎÁ
|
||||
Â0ЙsM5Uò+"²µ«â¦lSDÄwiNž³3‡ý@èɈPJ2–fª•Uþn×’‹.ˆ§³Ã¨éþ¨Â‹å>‡‰3½}×9ÐZbÕ•ÄÛÀè‘]cß�¡qh7f-·”ù’&ûÁãûF9/.
|
||||
@@ -0,0 +1,2 @@
|
||||
PRST1xœEÎÁ
|
||||
Â0Ð_‘9ç`«Qɯˆ”Ô®ˆ»e“RDüwsðô˜™Ë¼ÁñIИx”uS²¬p˜c¤ü¬»J-ç‹Ã¨éþ¨LÅrï½ÃD9¾:¿uˆK„ª9pg¥Ñ#ØÂ»Æ¾á‡Æ±qú1«ÜR¦!Mö¡Çç�“1
|
||||
Binary file not shown.
@@ -0,0 +1,2 @@
|
||||
PRST1xœ%ͽÂ0àW©Ž5C~•&VÆ
|
||||
¡@�)uª4K…xwR<}ç»Á° —ks<DjÎ)¦…É•B™ë–¸ž¯µža;l¼×Ú{Üž9ïÂ4×ÁÐStl«kævÅ[a'ì…ƒpN¦œ|ˆô}ýmðý‡-‰
|
||||
@@ -0,0 +1 @@
|
||||
PRST1xœMÎ1!†á¿b¾[=5ÌNÎnÆô@I°\€Åÿ»Å.²<oÚ¼Aîéa±?,ŽÅQ�-f‚ÂìZó…xÓþÇ·œr©°'!h~<´î-Õg…k‰÷G#_ùØ0ùä^Ü#7-a;FX ka6ÂVØý˜K1ùKœø_Ÿ/ÐM4y
|
||||
Binary file not shown.
@@ -0,0 +1,2 @@
|
||||
PRST1xœ%ͽÂ0àW©Ž5C~•&VÆ
|
||||
¡@�)uª4K…xwR<}ç»Á° —ks<DjÎ)¦…É•B™ë–¸ž¯µža;l¼×Ú{Üž9ïÂ4×ÁÐStl«kævÅ[a'ì…ƒpN¦œ|ˆô}ýmðý‡-‰
|
||||
@@ -0,0 +1 @@
|
||||
PRST1xœMÎ1!†á¿b¾[=5ÌNÎnÆô@I°\€Åÿ»Å.²<oÚ¼Aîéa±?,ŽÅQ�-f‚ÂìZó…xÓþÇ·œr©°'!h~<´î-Õg…k‰÷G#_ùØ0ùä^Ü#7-a;FX ka6ÂVØý˜K1ùKœø_Ÿ/ÐM4y
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,3 @@
|
||||
PRST1xœUÎÁ‚0„áw¯=¤jú*†�
|
||||
[m\[²”ƒ1¾»…ž<}ÉÌåÿ ºÁÂsŸ$P˜]Î$ño'Y`¯88ÒÚ{ô
|
||||
7 ÷GŽ´”£5Fa"voX£Üšl–•bÛè2ÆvãXé*¦rªœ+—�Y’LC˜JM³·1•ºAÈo5qeî¿?ªð9±
|
||||
Binary file not shown.
@@ -0,0 +1,4 @@
|
||||
PRST1xśMÎÁ‚0„áwŻ=$ű*†�
|
||||
[%Y[RÚ1ľ»…^<}ÉĚĺ˙Ŕ™7�`ĺPa51rpËäŇ␍tÇĹÚ©×�Â#,ĎWtĽĺŁŞ{…™Ĺě V+�=(†Ä
|
||||
®5m¶ŐťÎŻk@×B[č
|
||||
·B˛oáq™sMu¶ çş1°=z\ľ?µ¦8>
|
||||
@@ -0,0 +1,2 @@
|
||||
PRST1xśmŹÁ‚0†ßĄ\wČ`ŮMQ^Â2ĄčâÜČ1ĆřînĚ‹‰—~í—?Mű#ďüC™›F 0IďŃ™w¶ÚşÄ˛š7Ľm�ËĺMęveýuUąo<v[şć:'§.Wop
|
||||
ƨĺDN)ąx» �<H¤)B2r"˘Śá@–Ć*ˇNŕ+&gGĄ±WC8<_ßĐéŽńpłhMţ”îýŹ!I°
|
||||
@@ -0,0 +1,2 @@
|
||||
PRST1xњUЋ;В0птТєp>°WAQґђ5X2Nд8BЬ;©hv¤·SМЃ_BдЙq(,њ’Др·Эg?ЗtEЕЅЦЦжТZіf
|
||||
·иПdНJcЊВ$ћЯ “ЮТJq…PѓЪј…t)ПР‚є]ЁАињњw,q¶ОЛи¦\Wп^rнЕ–є°yЇКѕ?Эh>Ў
|
||||
Binary file not shown.
@@ -0,0 +1,2 @@
|
||||
PRST1xœEÎM
|
||||
Â0à«Ès›Eÿ¢’ôE$¶£â¤$Ó…ˆww0góÁ{o1o°„ŠìÊì™)Ã`õ"”Y‹6§˜r�›°ÇFgƒk÷‡0-:k␍Šþ×7~“'y#ná¥Ó™ÒÃ逇Š*ÇÊéÇšÓ-Dº„Eiñù¹L2‡
|
||||
@@ -0,0 +1,3 @@
|
||||
PRST1xœ=ŽA‚0E¯B>Û.
|
||||
*š€KC*ŒØ¤¶¤Æxw�Í{™7‹y!ØÁ€)s5';9
|
||||
\å1Eï¡°XfJA~mø·1ú˜2ÌußkÙÕZo^ls\®ÉÍw”å¸mµÂDÞ>a:Q»r„á´’Bh¤Z)aW°/8tÇ‚ÓKŠ7çip“üÙàý)<¡
|
||||
@@ -0,0 +1,3 @@
|
||||
PRST1xś-ÎÁ‚0Đ_!õ‡Šdo˝ô'Ś!Ş’”–”ĺ`Ś˙î<˝ÍĚö�čfű•‹!Íž‹qs
|
||||
‹cö9J·Çý?RHy]QZkŚÖ’•Zc-n
|
||||
÷<=_ý*“Zk…Ń÷µrşŤ�óćbę„T ␍¨N ŮĹóA{p9čv–śSđý4Ęcľ?6Đ
|
||||
@@ -0,0 +1,2 @@
|
||||
PRST1x�5־A‚0…ב«�ַ¶@Dׂ- —0ֶT©�X[2ֶxwG׳ש&»˜‚yXh°M\₪�׀��‚ֹ8…�0[
|
||||
’ור/חט#%ט=ֺ¾†q”·r\…¹כ�ƒMע¥©*…ֹzף„מd5Gh¦ֵ*„Zz+6b-1l ¿´™m¦ֻל2ֺLסגה"7ֹy5�־ד:G
|
||||
@@ -0,0 +1,2 @@
|
||||
PRST1xœ-ÎÁ Ð_1ã•ÔZŽúÆ´«’ 4°Õã¿»Š§7;sÙ¢»,˜
|
||||
/îNP˜3å(í¿8¥�r�Ýa©õ¶ìŽÙ_®©ÈÐh0RpOØN¢›9ÁržI!XÓˆ�ØËW„ö{+]eSéL9�} ƒåƒ÷ªù0¿
|
||||
@@ -0,0 +1,2 @@
|
||||
PRST1x�=ЮA
|
||||
Т0аЋШw�EZ5JаK�б�ZH��L"онС�Ћ7ќџѓFЄ�с!\e�е�`�I�KдќнRHЅТ�и�ЕЮсlp-ѓу)�ЋНЕzС;=i�/ee�иiІє:Sv�=МютЁсЧЦщG.щ>ОЬ�Овсѓ,�1И
|
||||
Binary file not shown.
@@ -0,0 +1,2 @@
|
||||
PRST1xœ5ÎA‚0Ы�϶‹‚ˆ¦è%Œ!F �–´ÃÂïîhu6o2ÿ/æ ïV‚Sâ"Ѹ’碟\"(lŽ™¢—ø—tÿ¤Kˆ æ‚ÒZ-#·ò£µ¸*Üâ<Nì)I¥ÖZa Å=`ZYÝΆãN
|
||||
¾‚i„¦0RðMæ˜i3§ÌùËÃ}^¨›ùÂë␍Çü8÷
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,2 @@
|
||||
PRST1xœ5Î=Â0†á«Tk†þQ�À%*T%Ô@¥’TŽ; ÄÝIáå±ôzðÞ¾å¨ET Ž·JT,V•ŧšÃð·0‰ ‡Ë>¸8™OõS¨ËÒ`äÙ¾A]Zíª¤²²�¯@M¢ÎÉ7 v;÷-hã˜é2§Ìyg‘pŸf¦1ýTáû^
|
||||
7˜
|
||||
@@ -0,0 +1,3 @@
|
||||
PRST1x�5ΞΝ
|
||||
Β0ΰW)γ5‡ώhΉϊ"%ΪU5)›νAΔww5xϊ–™9μΑ=BI
|
||||
v>Η%Α`q"ΔA»o<ώγK�#'Ψ#6‡²ο†'ƒ3ϋΫ]%-κ²4�hvOΨVO·J„^Ι T°MΦ��ΐκ"l3»L›ΩgΊΗ«�iτ“ώSαύ��5%
|
||||
@@ -0,0 +1,4 @@
|
||||
PRST1xœMαÂ0Ð_A×5CZ ´™Q~!¨‘BR%î€ÿŽE¦gÝÝà7¢{˜
|
||||
ofŸiž
|
||||
ÇL9JõŸÞRH¹ÀœÐX{Ô½–¬µµ£ÆYášýýÁ‘ŠL:&
|
||||
îÓËéVN0œWRˆdB3[Ä]e_é+‡ÊðcÉiö�.~’¿Z|¾¡ 61
|
||||
@@ -0,0 +1 @@
|
||||
PRST1xœ5ŽAƒ E¯b¾[¨U+WiŒ¡2¶¦`š¦éÝ’nxÌ›Y¼Œ|ùPÌÚÎ�¿ˆ60l2r&.?ýýlµuâ‚Rõ|àCt%Wuß5®n½Ýƒ!OjÎiùN¹ÜN¦‚¨¢35DÑ@¤é”Ñft}ÆùÀæì²jšVÓª#TSL�-)ËìZ³ôŒßQ•AÓ
|
||||
@@ -0,0 +1 @@
|
||||
PRST1xњEО1В0Р« ПљЎiЎ ЂK „5)MЪФвоXНЂ—gщяБD72В‹lF—зВѓЙ‰pЋьoчR^@glOлаbpЛющ’И‹mУЬФлкЉ$ђдВС‚:ҐХљТЃ¬Іi/о+}еP9®L9=|а«ф‹пжg2д
|
||||
@@ -0,0 +1,2 @@
|
||||
PRST1xœ=ÎÍ
|
||||
Â0àW‘é5‡ô?ìM"} ‰vÕBMJ’D|wSž¾afû†5O!rˆ;³zç␍#{›úuu³ótDQi”N]ÑÊ^␍Öö²•�“ÀÅO÷G´Òq%¥Àȳy�ºÍ(ú•l ª¨I“AM¦Ít™>£~,Þݦ™ÏÓ˜þ+ñùÚ¦5ó
|
||||
@@ -0,0 +1,3 @@
|
||||
PRST1x°Mна
|
||||
б0ЮW▒вз╘SzTЯ%D╓╨L╣m├┬ЬНfКе\╬ДOЫ ╦'а┌)С"┤ЬЙ°ВP3╔ ⌡©П}LЖ└Й8≈dуNЖр²╝╘©?8P√⌠Zk┘√╪{ц6р╨▒#,╖▒┌≥Жb␍k└%Л4╜
|
||||
КBSь╤3C┼]ОИр╥Р≈аВ┘┘6
|
||||
@@ -0,0 +1,2 @@
|
||||
PRST1xœMÎK
|
||||
Â0…á½§ÜT£’tR$Ú«âMÉc âÞm�ˆ£þ39Oˆ»3,¦2Car¥p’¿rŽ!¦{ÀЍï‰0(œ’¿ÞŠpž‡Î…‘ƒ{À"WK„-©²‚hXMK•î;Ëú—6°¦±mìûSŠøèÇù’Æë␍»0Ø
|
||||
@@ -0,0 +1,4 @@
|
||||
PRST1xœMÎA‚0Ы˜ï¶‹RÉ€KcŠŒBR[Òc¼»l\½Éÿùɼáí“ANr˜ÙFÙ
|
||||
V+ÂÑçê?½b␍8ö½éj�‹Â—Ç,žS.ŒÖ
|
||||
;ûµù´›�Ä�|ªL½uŨ)_ƒ
|
||||
ÍN»sÞé~¬1ÜÇ×eÊ/Uø|Æœ5
|
||||
Binary file not shown.
@@ -0,0 +1,3 @@
|
||||
PRST1xœ5ŽA‚0E¯B>Û.
|
||||
*š€KCªŒBRÚ¦c¼»ÅÙ¼7óÿb>ðv"0Í\D눙Š)¤8@!ZÙ’—xOºò.¤æŠ²mµŒÜJW϶:n
|
||||
÷4¾ö4K¹ÖZ¡'gß0�¨]8ÀpZHÁW0ÕVðõÞô˜ÇŒSF“qθlˆ)<GGÝØË«¾?ð¹<
|
||||
@@ -0,0 +1,3 @@
|
||||
PRST1xœMŽ1Â0Eïò»fp
|
||||
�(K/�
|
||||
�H!©Òt@ˆ»cÈÂô¾Ÿ¿%¿�üƒá0†2F†Âìkå’þÕ˜c.ÜÝ0‘¸Î‘%œ.%Üî5ñ"•Þ…‰£J&RðkÍpµ¬¬�´HA§e•6mÜÂÉQ2p_¹kØ7Øæ’¯!ò9Lò–Æû¼Ã1ó
|
||||
Binary file not shown.
@@ -0,0 +1,2 @@
|
||||
PRST1xœ%ÎK
|
||||
Ã0Ы”éÖ‹$ýâ«”ÜFnŽ›PJï^ÇÖæI£Í|Áf&hlFæÃ6¹HPXLŒ$œãÀù|d…~àhË WxŠ{O‘iÍ�®iFòæÝî»I1@GI¤À-tޏ«œ*çÊ¥rÜ*÷Â"Á:Oƒs�¶´ò”{␍Bv/ÃÉûþ÷½8ù
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"1": {"group_name": "Main Group", "presets": ["1", "2"], "sequence_duration": 3000, "sequence_transition": 500, "sequence_loop": true, "sequence_repeat_count": 0, "sequence_active": false, "sequence_index": 0, "sequence_start_time": 0}, "2": {"group_name": "Accent Group", "presets": ["2", "3"], "sequence_duration": 2000, "sequence_transition": 300, "sequence_loop": true, "sequence_repeat_count": 0, "sequence_active": false, "sequence_index": 0, "sequence_start_time": 0}}
|
||||
{"1": {"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}}
|
||||
+53
-5
@@ -42,7 +42,7 @@ Profiles are selected with **`POST /profiles/<id>/apply`**, which sets `current_
|
||||
| Method | Path | Description |
|
||||
|--------|------|-------------|
|
||||
| GET | `/` | Main UI (`templates/index.html`) |
|
||||
| GET | `/settings` | Settings page (`templates/settings.html`) |
|
||||
| GET | `/settings/page` | Standalone settings page (`templates/settings.html`) |
|
||||
| GET | `/favicon.ico` | Empty response (204) |
|
||||
| GET | `/static/<path>` | Static files under `src/static/` |
|
||||
|
||||
@@ -72,7 +72,7 @@ Below, `<id>` values are string identifiers used by the JSON stores (numeric str
|
||||
| PUT | `/settings/settings` | Merge keys into settings and save. Returns `{"message": "Settings updated successfully"}`. |
|
||||
| GET | `/settings/wifi/ap` | Saved Wi‑Fi AP fields: `saved_ssid`, `saved_password`, `saved_channel`, `active` (Pi: `active` is always false). |
|
||||
| POST | `/settings/wifi/ap` | Body: `ssid` (required), `password`, `channel` (1–11). Persists AP-related settings. |
|
||||
| GET | `/settings/page` | Serves `templates/settings.html` (same page as `GET /settings` from the root app, for convenience). |
|
||||
| GET | `/settings/page` | Serves `templates/settings.html`. |
|
||||
|
||||
### Devices — `/devices`
|
||||
|
||||
@@ -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`
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# espnow-sender
|
||||
|
||||
Minimal MicroPython project for receiving JSON over Microdot WebSocket.
|
||||
|
||||
- WebSocket endpoint: `/ws`
|
||||
- Entry point: `main.py`
|
||||
- Message template: `msg.json`
|
||||
@@ -0,0 +1,120 @@
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
from microdot import Microdot
|
||||
from microdot.websocket import WebSocketError, with_websocket
|
||||
|
||||
import espnow
|
||||
import network
|
||||
from util import format_mac, parse_mac
|
||||
|
||||
|
||||
app = Microdot()
|
||||
_esp = None
|
||||
_known_peers = set()
|
||||
_ws_clients = set()
|
||||
|
||||
|
||||
def _init_espnow():
|
||||
global _esp
|
||||
sta = network.WLAN(network.STA_IF)
|
||||
sta.active(True)
|
||||
_esp = espnow.ESPNow()
|
||||
_esp.active(True)
|
||||
|
||||
|
||||
def _validate_envelope(obj):
|
||||
if obj.get("v") != "1":
|
||||
raise ValueError("message.v must be '1'")
|
||||
devices = obj["devices"]
|
||||
for address in devices.keys():
|
||||
parse_mac(address)
|
||||
return obj
|
||||
|
||||
|
||||
def _send_espnow(address, payload):
|
||||
if _esp is None:
|
||||
raise ValueError("espnow is not initialized")
|
||||
mac = parse_mac(address)
|
||||
msg = json.dumps(payload, separators=(",", ":")).encode("utf-8")
|
||||
if mac not in _known_peers:
|
||||
_esp.add_peer(mac)
|
||||
_known_peers.add(mac)
|
||||
_esp.send(mac, msg)
|
||||
return mac, len(msg)
|
||||
|
||||
|
||||
async def _broadcast_ws(obj):
|
||||
text = json.dumps(obj)
|
||||
dead = []
|
||||
for client in list(_ws_clients):
|
||||
try:
|
||||
await client.send(text)
|
||||
except Exception:
|
||||
dead.append(client)
|
||||
for client in dead:
|
||||
_ws_clients.discard(client)
|
||||
|
||||
|
||||
async def _espnow_receive_loop():
|
||||
while True:
|
||||
host, msg = _esp.recv(0)
|
||||
if not host:
|
||||
await asyncio.sleep(0.01)
|
||||
continue
|
||||
await _broadcast_ws(
|
||||
{
|
||||
"from": format_mac(host),
|
||||
"payload": msg.decode("utf-8"),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@app.route("/ws")
|
||||
@with_websocket
|
||||
async def ws(request, ws):
|
||||
_ws_clients.add(ws)
|
||||
while True:
|
||||
try:
|
||||
raw = await ws.receive()
|
||||
except WebSocketError:
|
||||
break
|
||||
|
||||
if not raw:
|
||||
break
|
||||
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
env = _validate_envelope(parsed)
|
||||
sent = []
|
||||
for address, payload in env["devices"].items():
|
||||
mac, payload_size = _send_espnow(address, payload)
|
||||
sent.append(
|
||||
{
|
||||
"address": format_mac(mac),
|
||||
"bytes": payload_size,
|
||||
}
|
||||
)
|
||||
except (ValueError, TypeError) as e:
|
||||
await ws.send(json.dumps({"ok": False, "error": str(e)}))
|
||||
continue
|
||||
|
||||
await ws.send(
|
||||
json.dumps(
|
||||
{
|
||||
"ok": True,
|
||||
"sent": sent,
|
||||
}
|
||||
)
|
||||
)
|
||||
_ws_clients.discard(ws)
|
||||
|
||||
|
||||
async def main(port=80):
|
||||
_init_espnow()
|
||||
asyncio.create_task(_espnow_receive_loop())
|
||||
await app.start_server(host="0.0.0.0", port=port)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main(port=80))
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"v": "1",
|
||||
"devices": {
|
||||
"ff:ff:ff:ff:ff:ff": {
|
||||
"presets": {
|
||||
"preset_id": {
|
||||
"pattern": "on",
|
||||
"colors": ["#FF0000"],
|
||||
"delay": 100,
|
||||
"brightness": 255,
|
||||
"auto": true
|
||||
}
|
||||
},
|
||||
"select": {
|
||||
"preset": "preset_id",
|
||||
"step": 0
|
||||
},
|
||||
"save": true,
|
||||
"default": "preset_id",
|
||||
"b": 255
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
def parse_mac(value):
|
||||
raw = value.strip().lower().replace(":", "").replace("-", "")
|
||||
if len(raw) != 12:
|
||||
raise ValueError("address must be 12 hex chars or aa:bb:cc:dd:ee:ff")
|
||||
try:
|
||||
return bytes.fromhex(raw)
|
||||
except ValueError:
|
||||
raise ValueError("address contains non-hex characters")
|
||||
|
||||
|
||||
def format_mac(mac_bytes):
|
||||
return ":".join("{:02x}".format(b) for b in mac_bytes)
|
||||
+1
-1
Submodule led-driver updated: 4575ef16ad...2fcaf2f064.
+1
-1
Submodule led-tool updated: eee9327e15...d6331a105c.
@@ -0,0 +1,123 @@
|
||||
// Parametric LED bar vertical stand socket
|
||||
// For a bar nominally 14 x 17 mm, 2 m long.
|
||||
// This part is intended to be screwed to an MDF base.
|
||||
|
||||
// -------------------------
|
||||
// User parameters
|
||||
// -------------------------
|
||||
bar_w = 14; // Bar width (mm)
|
||||
bar_d = 17; // Bar depth (mm)
|
||||
clearance = 0.4; // Total clearance added to each axis (mm)
|
||||
|
||||
socket_height = 36; // Height of printed socket body (mm)
|
||||
wall = 3.2; // Socket wall thickness (mm)
|
||||
base_thickness = 5; // Printed bottom plate thickness (mm)
|
||||
|
||||
// USB cable/connector side opening
|
||||
usb_notch_enable = true;
|
||||
usb_notch_w = 11;
|
||||
usb_notch_h = 9;
|
||||
usb_notch_from_bottom = 6;
|
||||
usb_notch_side = "right"; // "right" or "left"
|
||||
|
||||
// Mounting ears for MDF screws
|
||||
ear_enable = true;
|
||||
ear_len = 16;
|
||||
ear_w = 16;
|
||||
ear_thickness = base_thickness;
|
||||
screw_hole_d = 4.2; // M4 clearance. Use 3.4 for M3.
|
||||
screw_hole_edge = 5.5; // Hole center offset from ear outer corner
|
||||
|
||||
// Optional clamp lip at top to reduce wobble
|
||||
top_lip_enable = true;
|
||||
top_lip_depth = 2.0; // Intrudes into opening on each side
|
||||
top_lip_height = 3.0;
|
||||
|
||||
$fn = 48;
|
||||
|
||||
// -------------------------
|
||||
// Derived
|
||||
// -------------------------
|
||||
inner_w = bar_w + clearance;
|
||||
inner_d = bar_d + clearance;
|
||||
|
||||
outer_w = inner_w + wall * 2;
|
||||
outer_d = inner_d + wall * 2;
|
||||
outer_h = socket_height;
|
||||
|
||||
module screw_hole() {
|
||||
cylinder(h = ear_thickness + 0.2, d = screw_hole_d);
|
||||
}
|
||||
|
||||
module mounting_ear(sign_y = 1) {
|
||||
translate([outer_w / 2, sign_y * (outer_d / 2), 0])
|
||||
cube([ear_len, ear_w, ear_thickness], center = false);
|
||||
}
|
||||
|
||||
module top_lip() {
|
||||
if (top_lip_enable) {
|
||||
// Front and back lips at the top of the socket.
|
||||
translate([wall, wall, outer_h - top_lip_height])
|
||||
cube([top_lip_depth, inner_d, top_lip_height]);
|
||||
|
||||
translate([outer_w - wall - top_lip_depth, wall, outer_h - top_lip_height])
|
||||
cube([top_lip_depth, inner_d, top_lip_height]);
|
||||
}
|
||||
}
|
||||
|
||||
difference() {
|
||||
union() {
|
||||
// Main body
|
||||
cube([outer_w, outer_d, outer_h], center = false);
|
||||
|
||||
// Base plate under socket for stiffness
|
||||
translate([0, 0, -base_thickness])
|
||||
cube([outer_w, outer_d, base_thickness], center = false);
|
||||
|
||||
// Mounting ears
|
||||
if (ear_enable) {
|
||||
translate([0, 0, -ear_thickness]) {
|
||||
mounting_ear(1);
|
||||
mounting_ear(-1);
|
||||
}
|
||||
}
|
||||
|
||||
top_lip();
|
||||
}
|
||||
|
||||
// Main bar cavity
|
||||
translate([wall, wall, 0])
|
||||
cube([inner_w, inner_d, outer_h + 0.2], center = false);
|
||||
|
||||
// USB side notch
|
||||
if (usb_notch_enable) {
|
||||
if (usb_notch_side == "right") {
|
||||
translate([outer_w - wall - 0.1, (outer_d - usb_notch_w) / 2, usb_notch_from_bottom])
|
||||
cube([wall + 0.3, usb_notch_w, usb_notch_h], center = false);
|
||||
} else {
|
||||
translate([-0.2, (outer_d - usb_notch_w) / 2, usb_notch_from_bottom])
|
||||
cube([wall + 0.3, usb_notch_w, usb_notch_h], center = false);
|
||||
}
|
||||
}
|
||||
|
||||
// Screw holes in ears
|
||||
if (ear_enable) {
|
||||
// Upper ear hole
|
||||
translate([
|
||||
outer_w / 2 + ear_len - screw_hole_edge,
|
||||
outer_d / 2 + ear_w - screw_hole_edge,
|
||||
-ear_thickness - 0.05
|
||||
]) screw_hole();
|
||||
|
||||
// Lower ear hole
|
||||
translate([
|
||||
outer_w / 2 + ear_len - screw_hole_edge,
|
||||
-outer_d / 2 + screw_hole_edge,
|
||||
-ear_thickness - 0.05
|
||||
]) screw_hole();
|
||||
}
|
||||
}
|
||||
|
||||
// Print orientation helper:
|
||||
// Keep the base/ears on the bed.
|
||||
// If fit is tight, increase clearance to 0.5 or 0.6.
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
python_files = ["test_endpoints_pytest.py"]
|
||||
python_files = ["test_endpoints_pytest.py", "engine_tests/test_*.py"]
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
PORT="${PORT:-80}"
|
||||
|
||||
# On watchfiles restarts the previous process can linger briefly.
|
||||
# Proactively terminate any listener on the target port before boot.
|
||||
pids="$(ss -ltnp "sport = :$PORT" 2>/dev/null | sed -n 's/.*pid=\([0-9]\+\).*/\1/p' | sort -u)"
|
||||
if [ -n "${pids}" ]; then
|
||||
kill -TERM ${pids} 2>/dev/null || true
|
||||
sleep 0.3
|
||||
fi
|
||||
|
||||
cd "$ROOT_DIR/src"
|
||||
exec python main.py
|
||||
@@ -10,6 +10,18 @@ if [ ! -f "scripts/led-controller.service" ]; then
|
||||
echo "Run this script from the repo root."
|
||||
exit 1
|
||||
fi
|
||||
export PIPENV_VENV_IN_PROJECT="${PIPENV_VENV_IN_PROJECT:-1}"
|
||||
if command -v pipenv >/dev/null 2>&1; then
|
||||
PY="$(command -v python3)"
|
||||
if [ -z "$PY" ]; then
|
||||
echo "python3 not found; install python3." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Ensuring Pipenv deps with $PY (venv in project: .venv when PIPENV_VENV_IN_PROJECT=1)…"
|
||||
# --skip-lock: install from Pipfile only (avoids lock/Python hash mismatches on device).
|
||||
pipenv install --quiet --skip-lock --python "$PY"
|
||||
pipenv --venv > scripts/.led-controller-venv
|
||||
fi
|
||||
chmod +x scripts/start.sh
|
||||
sudo cp "scripts/led-controller.service" "$UNIT_PATH"
|
||||
sudo systemctl daemon-reload
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
[Unit]
|
||||
Description=LED Controller web server
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
# Use network.target only. Ordering after network-online.target can block `systemctl start`
|
||||
# until wait-online finishes; Wi‑Fi/DHCP delays then look like a hung start job.
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
@@ -12,6 +13,8 @@ Environment=PATH=/home/pi/.local/bin:/usr/local/bin:/usr/bin:/bin
|
||||
ExecStart=/bin/bash /home/pi/led-controller/scripts/start.sh
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
# pipenv/first bind can be slow; avoid misleading "activating" forever if misconfigured
|
||||
TimeoutStartSec=120
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
+35
-2
@@ -1,5 +1,38 @@
|
||||
#!/usr/bin/env bash
|
||||
# Start the LED controller web server (port 80 by default).
|
||||
cd "$(dirname "$0")/.."
|
||||
# Avoid `pipenv run` on the hot path — it re-resolves the env every time and is slow on a Pi.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
cd "$ROOT"
|
||||
export PORT="${PORT:-80}"
|
||||
pipenv run run
|
||||
export PIPENV_VENV_IN_PROJECT="${PIPENV_VENV_IN_PROJECT:-1}"
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
CACHE="$SCRIPT_DIR/.led-controller-venv"
|
||||
PYTHON=""
|
||||
|
||||
if [ -x "$ROOT/.venv/bin/python" ]; then
|
||||
PYTHON="$ROOT/.venv/bin/python"
|
||||
elif [ -f "$CACHE" ]; then
|
||||
_v="$(tr -d '\r\n' < "$CACHE")"
|
||||
if [ -n "$_v" ] && [ -x "$_v/bin/python" ]; then
|
||||
PYTHON="$_v/bin/python"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$PYTHON" ] && command -v pipenv >/dev/null 2>&1; then
|
||||
_v="$(cd "$ROOT" && pipenv --venv 2>/dev/null || true)"
|
||||
if [ -n "${_v:-}" ] && [ -x "$_v/bin/python" ]; then
|
||||
PYTHON="$_v/bin/python"
|
||||
printf '%s\n' "$_v" > "$CACHE" || true
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$PYTHON" ]; then
|
||||
echo 'led-controller: no venv resolved; using pipenv run (slow). Run: cd '"$ROOT"' && PIPENV_VENV_IN_PROJECT=1 pipenv install --skip-lock --python "$(command -v python3)"' >&2
|
||||
exec pipenv run run
|
||||
fi
|
||||
|
||||
cd "$ROOT/src"
|
||||
exec "$PYTHON" -u main.py
|
||||
@@ -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
|
||||
@@ -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'}
|
||||
+49
-22
@@ -1,51 +1,78 @@
|
||||
from microdot import Microdot
|
||||
from models.squence import Sequence
|
||||
from engine import get_engine
|
||||
from engine.core import EngineError
|
||||
import json
|
||||
|
||||
controller = Microdot()
|
||||
sequences = Sequence()
|
||||
|
||||
_JSON = {'Content-Type': 'application/json'}
|
||||
|
||||
|
||||
@controller.get('')
|
||||
async def list_sequences(request):
|
||||
"""List all sequences."""
|
||||
return json.dumps(sequences), 200, {'Content-Type': 'application/json'}
|
||||
return json.dumps(sequences), 200, _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>')
|
||||
async def get_sequence(request, id):
|
||||
"""Get a specific sequence by ID."""
|
||||
sequence = sequences.read(id)
|
||||
if sequence:
|
||||
return json.dumps(sequence), 200, {'Content-Type': 'application/json'}
|
||||
return json.dumps({"error": "Sequence not found"}), 404
|
||||
return json.dumps(sequence), 200, _JSON
|
||||
return json.dumps({"error": "Sequence not found"}), 404, _JSON
|
||||
|
||||
|
||||
@controller.post('')
|
||||
async def create_sequence(request):
|
||||
"""Create a new sequence."""
|
||||
"""Create a sequence: {name, zone_id, loop, repeat_count, steps: [{preset_id, duration_s}]}."""
|
||||
try:
|
||||
data = request.json or {}
|
||||
group_name = data.get("group_name", "")
|
||||
preset_names = data.get("presets", None)
|
||||
sequence_id = sequences.create(group_name, preset_names)
|
||||
if data:
|
||||
sequences.update(sequence_id, data)
|
||||
return json.dumps(sequences.read(sequence_id)), 201, {'Content-Type': 'application/json'}
|
||||
except Exception as e:
|
||||
return json.dumps({"error": str(e)}), 400
|
||||
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)}), 400, _JSON
|
||||
|
||||
|
||||
@controller.put('/<id>')
|
||||
async def update_sequence(request, id):
|
||||
"""Update an existing sequence."""
|
||||
try:
|
||||
data = request.json
|
||||
if sequences.update(id, data):
|
||||
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
|
||||
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, _JSON
|
||||
|
||||
|
||||
@controller.delete('/<id>')
|
||||
async def delete_sequence(request, id):
|
||||
"""Delete a sequence."""
|
||||
"""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
|
||||
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('/<id>/play')
|
||||
async def play_sequence(request, id):
|
||||
"""Start the sequence on its zone (replaces any sequence already running there)."""
|
||||
try:
|
||||
state = await get_engine().sequences.play(id)
|
||||
return json.dumps(state), 200, _JSON
|
||||
except EngineError as e:
|
||||
return json.dumps({"error": str(e)}), e.status, _JSON
|
||||
|
||||
|
||||
@controller.post('/<id>/stop')
|
||||
async def stop_sequence(request, id):
|
||||
"""Stop the sequence; the zone keeps showing its current preset."""
|
||||
stopped = await get_engine().sequences.stop(id)
|
||||
return json.dumps({"stopped": stopped}), 200, _JSON
|
||||
@@ -1,7 +1,11 @@
|
||||
from microdot import Microdot, send_file
|
||||
from settings import Settings
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
from microdot import Microdot, send_file
|
||||
|
||||
from models import wifi_ws_clients
|
||||
from settings import Settings
|
||||
|
||||
controller = Microdot()
|
||||
settings = Settings()
|
||||
|
||||
@@ -63,17 +67,36 @@ def _validate_wifi_channel(value):
|
||||
return ch
|
||||
|
||||
|
||||
def _validate_global_brightness(value):
|
||||
"""Return int 0–255 or raise ValueError."""
|
||||
v = int(value)
|
||||
if v < 0 or v > 255:
|
||||
raise ValueError("global_brightness must be between 0 and 255")
|
||||
return v
|
||||
|
||||
|
||||
@controller.put('/settings')
|
||||
async def update_settings(request):
|
||||
"""Update general settings."""
|
||||
try:
|
||||
data = request.json
|
||||
global_brightness_changed = False
|
||||
for key, value in data.items():
|
||||
if key == 'wifi_channel' and value is not None:
|
||||
settings[key] = _validate_wifi_channel(value)
|
||||
elif key == 'global_brightness' and value is not None:
|
||||
settings[key] = _validate_global_brightness(value)
|
||||
global_brightness_changed = True
|
||||
else:
|
||||
settings[key] = value
|
||||
settings.save()
|
||||
if global_brightness_changed:
|
||||
try:
|
||||
asyncio.get_running_loop().create_task(
|
||||
wifi_ws_clients.broadcast_global_brightness_to_tcp_drivers()
|
||||
)
|
||||
except RuntimeError:
|
||||
pass
|
||||
return json.dumps({"message": "Settings updated successfully"}), 200, {'Content-Type': 'application/json'}
|
||||
except ValueError as e:
|
||||
return json.dumps({"error": str(e)}), 400
|
||||
|
||||
@@ -211,6 +211,45 @@ 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):
|
||||
z = zones.read(id)
|
||||
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -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(),
|
||||
}
|
||||
@@ -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))
|
||||
@@ -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
|
||||
@@ -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",
|
||||
]
|
||||
@@ -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)
|
||||
@@ -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""]
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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
|
||||
@@ -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 []),
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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()}
|
||||
@@ -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)
|
||||
+24
-6
@@ -22,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
|
||||
@@ -261,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
|
||||
@@ -275,6 +279,12 @@ 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)
|
||||
@@ -284,12 +294,6 @@ async def main(port=80):
|
||||
def index(request):
|
||||
"""Serve the main web UI."""
|
||||
return send_file('templates/index.html')
|
||||
|
||||
# Serve settings page
|
||||
@app.route('/settings')
|
||||
def settings_page(request):
|
||||
"""Serve the settings page."""
|
||||
return send_file('templates/settings.html')
|
||||
|
||||
# Favicon: avoid 404 in browser console (no file needed)
|
||||
@app.route('/favicon.ico')
|
||||
@@ -348,6 +352,15 @@ async def main(port=80):
|
||||
await _send_bridge_wifi_channel(settings, sender)
|
||||
_prime_wifi_outbound_driver_connections()
|
||||
|
||||
async def _resume_sequences():
|
||||
# Give Wi-Fi drivers a moment to connect before the first step.
|
||||
await asyncio.sleep(2.0)
|
||||
resumed = await engine.sequences.resume_active()
|
||||
if resumed:
|
||||
print(f"[engine] resumed sequences: {resumed}")
|
||||
|
||||
asyncio.create_task(_resume_sequences())
|
||||
|
||||
udp_holder = {"closing": False}
|
||||
loop = asyncio.get_running_loop()
|
||||
|
||||
@@ -389,6 +402,11 @@ async def main(port=80):
|
||||
)
|
||||
raise
|
||||
finally:
|
||||
try:
|
||||
# Keep sequence ``active`` flags so they resume after restart.
|
||||
await engine.stop_all(persist=False)
|
||||
except Exception as e:
|
||||
print(f"[engine] stop failed: {e!r}")
|
||||
srv = getattr(app, "server", None)
|
||||
if srv is not None:
|
||||
try:
|
||||
|
||||
@@ -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]
|
||||
+84
-16
@@ -1,37 +1,105 @@
|
||||
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 create(self, group_name="", preset_names=None):
|
||||
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] = {
|
||||
"group_name": group_name,
|
||||
"presets": preset_names if preset_names else [],
|
||||
"sequence_duration": 3000, # Duration per preset in ms
|
||||
"sequence_transition": 500, # Transition time in ms
|
||||
"sequence_loop": False,
|
||||
"sequence_repeat_count": 0, # 0 = infinite
|
||||
"sequence_active": False,
|
||||
"sequence_index": 0,
|
||||
"sequence_start_time": 0
|
||||
}
|
||||
self[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
|
||||
self[id_str].update(data)
|
||||
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:
|
||||
@@ -39,6 +107,6 @@ class Sequence(Model):
|
||||
self.pop(id_str)
|
||||
self.save()
|
||||
return True
|
||||
|
||||
|
||||
def list(self):
|
||||
return list(self.keys())
|
||||
+23
-1
@@ -33,6 +33,13 @@ async def _to_thread(func, *args):
|
||||
return await loop.run_in_executor(None, func, *args)
|
||||
|
||||
|
||||
class NullSender:
|
||||
"""Used when no ESP-NOW UART bridge is configured or the port cannot be opened."""
|
||||
|
||||
async def send(self, data, addr=None):
|
||||
return True
|
||||
|
||||
|
||||
class SerialSender:
|
||||
def __init__(self, port, baudrate, default_addr=None):
|
||||
import serial
|
||||
@@ -62,7 +69,22 @@ def get_current_sender():
|
||||
|
||||
|
||||
def get_sender(settings):
|
||||
# Serial ESP-NOW bridge is opt-in (serial_enabled true); default off for dev / Wi-Fi-only.
|
||||
if not settings.get("serial_enabled"):
|
||||
print("[startup] serial bridge disabled (set serial_enabled true in settings.json to enable)")
|
||||
return NullSender()
|
||||
port = settings.get("serial_port", "/dev/ttyS0")
|
||||
raw_port = str(port).strip() if port is not None else ""
|
||||
if not raw_port or raw_port.lower() in ("none", "off"):
|
||||
print("[startup] serial bridge disabled (empty serial_port)")
|
||||
return NullSender()
|
||||
baudrate = settings.get("serial_baudrate", 912000)
|
||||
default_addr = settings.get("serial_destination_mac", "ffffffffffff")
|
||||
return SerialSender(port, baudrate, default_addr=default_addr)
|
||||
try:
|
||||
return SerialSender(raw_port, baudrate, default_addr=default_addr)
|
||||
except Exception as e:
|
||||
print(
|
||||
f"[startup] serial open failed ({raw_port!r}): {e}; "
|
||||
"continuing without ESP-NOW bridge (Wi-Fi drivers unchanged)"
|
||||
)
|
||||
return NullSender()
|
||||
@@ -84,6 +84,36 @@ def prune_stale_tcp_writers() -> None:
|
||||
_schedule_status_broadcast(ip, False)
|
||||
|
||||
|
||||
def _global_brightness_message_text() -> str | None:
|
||||
"""v1 JSON line for saved zone UI brightness; works with shipping driver firmware (applies ``b`` in RAM)."""
|
||||
global _settings
|
||||
if _settings is None:
|
||||
return None
|
||||
try:
|
||||
b = int(_settings.get("global_brightness", 255))
|
||||
except (TypeError, ValueError):
|
||||
b = 255
|
||||
b = max(0, min(255, b))
|
||||
return json.dumps({"v": "1", "b": b})
|
||||
|
||||
|
||||
async def sync_global_brightness_to_driver(ip: str) -> bool:
|
||||
"""Push Pi-stored global brightness to one Wi-Fi driver over the outbound WebSocket."""
|
||||
text = _global_brightness_message_text()
|
||||
if not text:
|
||||
return False
|
||||
return await send_json_line_to_ip(ip, text)
|
||||
|
||||
|
||||
async def broadcast_global_brightness_to_tcp_drivers() -> None:
|
||||
"""Push saved global brightness to every connected Wi-Fi driver."""
|
||||
text = _global_brightness_message_text()
|
||||
if not text:
|
||||
return
|
||||
for ip in list_connected_ips():
|
||||
await send_json_line_to_ip(ip, text)
|
||||
|
||||
|
||||
def _register_ws(ip: str, ws) -> None:
|
||||
key = normalize_tcp_peer_ip(ip)
|
||||
if not key:
|
||||
@@ -94,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:
|
||||
@@ -195,6 +234,27 @@ async def _recv_forward_loop(ip: str, ws) -> None:
|
||||
pass
|
||||
|
||||
|
||||
def _stagger_delay_s_for_ip(ip: str) -> float:
|
||||
"""0 .. wifi_driver_connect_stagger_max_s based on last IPv4 octet (deterministic spread)."""
|
||||
global _settings
|
||||
if _settings is None:
|
||||
return 0.0
|
||||
try:
|
||||
max_s = float(_settings.get("wifi_driver_connect_stagger_max_s", 2.5))
|
||||
except (TypeError, ValueError):
|
||||
max_s = 2.5
|
||||
if max_s <= 0:
|
||||
return 0.0
|
||||
parts = str(ip).strip().split(".")
|
||||
if len(parts) != 4:
|
||||
return 0.0
|
||||
try:
|
||||
last = int(parts[3]) % 256
|
||||
except ValueError:
|
||||
return 0.0
|
||||
return (last / 255.0) * max_s
|
||||
|
||||
|
||||
async def _driver_connection_loop(ip: str) -> None:
|
||||
global _settings
|
||||
if _settings is None:
|
||||
@@ -204,16 +264,37 @@ async def _driver_connection_loop(ip: str) -> None:
|
||||
if not path.startswith("/"):
|
||||
path = "/" + path
|
||||
uri = f"ws://{ip}:{port}{path}"
|
||||
retry_interval_s = 2.0
|
||||
retry_window_s = 30.0
|
||||
deadline = asyncio.get_running_loop().time() + retry_window_s
|
||||
try:
|
||||
retry_interval_s = float(_settings.get("wifi_driver_connect_retry_interval_s", 2.0))
|
||||
except (TypeError, ValueError):
|
||||
retry_interval_s = 2.0
|
||||
retry_interval_s = max(0.2, retry_interval_s)
|
||||
try:
|
||||
retry_window_s = float(_settings.get("wifi_driver_connect_retry_window_s", 120.0))
|
||||
except (TypeError, ValueError):
|
||||
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
|
||||
deadline = loop.time() + retry_window_s
|
||||
try:
|
||||
while True:
|
||||
now = asyncio.get_running_loop().time()
|
||||
if now >= deadline:
|
||||
now = loop.time()
|
||||
if not connected_once and now >= deadline:
|
||||
print(
|
||||
f"[WS] driver {ip} still unreachable after {int(retry_window_s)}s; "
|
||||
"stopping retries until next hello"
|
||||
f"[WS] driver {ip} still unreachable after {int(retry_window_s)}s "
|
||||
f"(initial window); stopping until next UDP hello / registry prime"
|
||||
)
|
||||
break
|
||||
try:
|
||||
@@ -222,8 +303,9 @@ async def _driver_connection_loop(ip: str) -> None:
|
||||
uri,
|
||||
ping_interval=20,
|
||||
ping_timeout=15,
|
||||
open_timeout=30,
|
||||
open_timeout=open_timeout,
|
||||
) as ws:
|
||||
connected_once = True
|
||||
_register_ws(ip, ws)
|
||||
try:
|
||||
await _recv_forward_loop(ip, ws)
|
||||
@@ -239,7 +321,9 @@ async def _driver_connection_loop(ip: str) -> None:
|
||||
n = _unreachable_counts.get(ip, 0) + 1
|
||||
_unreachable_counts[ip] = n
|
||||
if n == 1 or (n % 30) == 0:
|
||||
print(f"[WS] driver {ip} unreachable, retry in 2s: {e} (x{n})")
|
||||
print(
|
||||
f"[WS] driver {ip} unreachable, retry in {retry_interval_s}s: {e} (x{n})"
|
||||
)
|
||||
else:
|
||||
print(f"[WS] driver {ip} session error: {e!r}")
|
||||
traceback.print_exception(type(e), e, e.__traceback__)
|
||||
|
||||
@@ -57,6 +57,25 @@ 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
|
||||
# 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.
|
||||
if 'wifi_driver_connect_stagger_max_s' not in self:
|
||||
self['wifi_driver_connect_stagger_max_s'] = 2.5
|
||||
# TCP/WebSocket open timeout per attempt (seconds).
|
||||
if 'wifi_driver_ws_open_timeout' not in self:
|
||||
self['wifi_driver_ws_open_timeout'] = 45.0
|
||||
# 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
|
||||
# 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
|
||||
|
||||
def save(self):
|
||||
try:
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -1859,6 +1859,10 @@ const createPresetButton = (presetId, preset, zoneId, isSelected = false) => {
|
||||
sendPresetViaEspNow(presetId, preset, deviceNames, false, false, '2').catch((err) => {
|
||||
console.error(err);
|
||||
});
|
||||
// Pi-side engine: pixel outputs in this zone + stop any running sequence.
|
||||
if (typeof window.notifyEngineZonePlay === 'function') {
|
||||
window.notifyEngineZonePlay(zoneId, presetId);
|
||||
}
|
||||
});
|
||||
|
||||
if (canDrag) {
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
// Sequences: timed preset chains per zone, run by the Pi-side engine.
|
||||
|
||||
const SEQUENCES_POLL_MS = 1000;
|
||||
let sequencesPollTimer = null;
|
||||
|
||||
async function fetchJson(url) {
|
||||
const res = await fetch(url, { headers: { Accept: 'application/json' }, credentials: 'same-origin' });
|
||||
if (!res.ok) throw new Error(`${url}: ${res.status}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
async function loadSequenceContext() {
|
||||
const [sequences, status, zonesData, presets] = await Promise.all([
|
||||
fetchJson('/sequences'),
|
||||
fetchJson('/sequences/status'),
|
||||
fetchJson('/zones'),
|
||||
fetchJson('/presets'),
|
||||
]);
|
||||
const order = Array.isArray(zonesData.zone_order) ? zonesData.zone_order : [];
|
||||
const zones = {};
|
||||
order.forEach((zid) => {
|
||||
if (zonesData.zones && zonesData.zones[zid]) zones[zid] = zonesData.zones[zid];
|
||||
});
|
||||
return { sequences, status, zones, presets };
|
||||
}
|
||||
|
||||
function stepSummary(seq, presets, state) {
|
||||
const steps = seq.steps || [];
|
||||
const total = steps.reduce((s, st) => s + Number(st.duration_s || 0), 0);
|
||||
let text = `${steps.length} step${steps.length === 1 ? '' : 's'} · ${total.toFixed(1)} s`;
|
||||
text += seq.loop ? (seq.repeat_count ? ` · ×${seq.repeat_count}` : ' · loop') : ' · once';
|
||||
if (state && state.running) {
|
||||
const p = presets[state.preset_id];
|
||||
text += ` · ▶ step ${state.step_index + 1}${p ? ` (${p.name})` : ''}`;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function renderSequencesList(ctx) {
|
||||
const container = document.getElementById('sequences-list-modal');
|
||||
if (!container) return;
|
||||
const editMode = typeof isEditModeActive === 'function' && isEditModeActive();
|
||||
container.innerHTML = '';
|
||||
const ids = Object.keys(ctx.sequences || {}).filter((id) => {
|
||||
const z = ctx.sequences[id].zone_id;
|
||||
return z == null || ctx.zones[z]; // only this profile's zones (plus unassigned)
|
||||
});
|
||||
if (ids.length === 0) {
|
||||
const p = document.createElement('p');
|
||||
p.className = 'muted-text';
|
||||
p.textContent = 'No sequences yet.';
|
||||
container.appendChild(p);
|
||||
return;
|
||||
}
|
||||
ids.forEach((id) => {
|
||||
const seq = ctx.sequences[id];
|
||||
const state = ctx.status[id];
|
||||
const running = !!(state && state.running);
|
||||
const zone = ctx.zones[seq.zone_id];
|
||||
|
||||
const row = document.createElement('div');
|
||||
row.className = 'profiles-row';
|
||||
row.style.display = 'flex';
|
||||
row.style.alignItems = 'center';
|
||||
row.style.gap = '0.5rem';
|
||||
row.style.flexWrap = 'wrap';
|
||||
|
||||
const label = document.createElement('span');
|
||||
label.style.flex = '1';
|
||||
const name = document.createElement('strong');
|
||||
name.textContent = seq.name || `Sequence ${id}`;
|
||||
const meta = document.createElement('span');
|
||||
meta.className = 'muted-text';
|
||||
meta.textContent = ` ${zone ? zone.name : 'no zone'} · ${stepSummary(seq, ctx.presets, state)}`;
|
||||
label.append(name, meta);
|
||||
|
||||
const playBtn = document.createElement('button');
|
||||
playBtn.type = 'button';
|
||||
playBtn.className = running ? 'btn btn-danger btn-small' : 'btn btn-primary btn-small';
|
||||
playBtn.textContent = running ? 'Stop' : 'Play';
|
||||
playBtn.disabled = !zone || !(seq.steps || []).length;
|
||||
playBtn.addEventListener('click', async () => {
|
||||
playBtn.disabled = true;
|
||||
const res = await fetch(`/sequences/${encodeURIComponent(id)}/${running ? 'stop' : 'play'}`, {
|
||||
method: 'POST', credentials: 'same-origin',
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
alert(data.error || 'Failed');
|
||||
}
|
||||
refreshSequencesList();
|
||||
});
|
||||
row.append(label, playBtn);
|
||||
|
||||
if (editMode) {
|
||||
const editBtn = document.createElement('button');
|
||||
editBtn.type = 'button';
|
||||
editBtn.className = 'btn btn-secondary btn-small';
|
||||
editBtn.textContent = 'Edit';
|
||||
editBtn.addEventListener('click', () => openSequenceEditor(id, seq, ctx));
|
||||
const delBtn = document.createElement('button');
|
||||
delBtn.type = 'button';
|
||||
delBtn.className = 'btn btn-danger btn-small';
|
||||
delBtn.textContent = 'Delete';
|
||||
delBtn.addEventListener('click', async () => {
|
||||
if (!confirm(`Delete sequence "${seq.name}"?`)) return;
|
||||
await fetch(`/sequences/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
||||
refreshSequencesList();
|
||||
});
|
||||
row.append(editBtn, delBtn);
|
||||
}
|
||||
container.appendChild(row);
|
||||
});
|
||||
}
|
||||
|
||||
let lastSequenceCtx = null;
|
||||
|
||||
async function refreshSequencesList() {
|
||||
try {
|
||||
lastSequenceCtx = await loadSequenceContext();
|
||||
renderSequencesList(lastSequenceCtx);
|
||||
} catch (e) {
|
||||
const container = document.getElementById('sequences-list-modal');
|
||||
if (container && !lastSequenceCtx) container.textContent = 'Failed to load sequences.';
|
||||
}
|
||||
}
|
||||
|
||||
function stopSequencesPoll() {
|
||||
if (sequencesPollTimer != null) {
|
||||
clearInterval(sequencesPollTimer);
|
||||
sequencesPollTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function addStepRow(presets, step) {
|
||||
const container = document.getElementById('edit-sequence-steps');
|
||||
const row = document.createElement('div');
|
||||
row.className = 'engine-step-row';
|
||||
|
||||
const select = document.createElement('select');
|
||||
select.className = 'engine-step-preset';
|
||||
Object.entries(presets || {}).forEach(([pid, p]) => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = pid;
|
||||
opt.textContent = p.name || pid;
|
||||
select.appendChild(opt);
|
||||
});
|
||||
if (step && step.preset_id != null) select.value = String(step.preset_id);
|
||||
|
||||
const dur = document.createElement('input');
|
||||
dur.type = 'number';
|
||||
dur.min = '0.5';
|
||||
dur.max = '600';
|
||||
dur.step = '0.5';
|
||||
dur.className = 'engine-step-duration';
|
||||
dur.value = step && step.duration_s != null ? step.duration_s : 5;
|
||||
dur.title = 'Seconds';
|
||||
|
||||
const unit = document.createElement('span');
|
||||
unit.className = 'muted-text';
|
||||
unit.textContent = 's';
|
||||
|
||||
const mk = (text, title, fn) => {
|
||||
const b = document.createElement('button');
|
||||
b.type = 'button';
|
||||
b.className = 'btn btn-secondary btn-small';
|
||||
b.textContent = text;
|
||||
b.title = title;
|
||||
b.addEventListener('click', fn);
|
||||
return b;
|
||||
};
|
||||
const up = mk('↑', 'Move up', () => { if (row.previousElementSibling) container.insertBefore(row, row.previousElementSibling); });
|
||||
const down = mk('↓', 'Move down', () => { if (row.nextElementSibling) container.insertBefore(row.nextElementSibling, row); });
|
||||
const del = mk('✕', 'Remove step', () => row.remove());
|
||||
|
||||
row.append(select, dur, unit, up, down, del);
|
||||
container.appendChild(row);
|
||||
}
|
||||
|
||||
function openSequenceEditor(id, seq, ctx) {
|
||||
const s = seq || { name: '', zone_id: null, loop: true, repeat_count: 0, steps: [] };
|
||||
document.getElementById('edit-sequence-title').textContent = id ? 'Edit sequence' : 'New sequence';
|
||||
document.getElementById('edit-sequence-id').value = id || '';
|
||||
document.getElementById('edit-sequence-name').value = s.name || '';
|
||||
const zoneSel = document.getElementById('edit-sequence-zone');
|
||||
zoneSel.innerHTML = '';
|
||||
Object.entries(ctx.zones).forEach(([zid, z]) => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = zid;
|
||||
opt.textContent = z.name || zid;
|
||||
zoneSel.appendChild(opt);
|
||||
});
|
||||
const currentZone = s.zone_id
|
||||
|| (window.zonesManager && window.zonesManager.getCurrentZoneId && window.zonesManager.getCurrentZoneId());
|
||||
if (currentZone && ctx.zones[currentZone]) zoneSel.value = String(currentZone);
|
||||
document.getElementById('edit-sequence-loop').checked = s.loop !== false;
|
||||
document.getElementById('edit-sequence-repeat').value = s.repeat_count || 0;
|
||||
const steps = document.getElementById('edit-sequence-steps');
|
||||
steps.innerHTML = '';
|
||||
(s.steps || []).forEach((st) => addStepRow(ctx.presets, st));
|
||||
if (!(s.steps || []).length) addStepRow(ctx.presets, null);
|
||||
document.getElementById('edit-sequence-error').hidden = true;
|
||||
document.getElementById('edit-sequence-modal').classList.add('active');
|
||||
}
|
||||
|
||||
function readSequenceForm() {
|
||||
const steps = [];
|
||||
document.querySelectorAll('#edit-sequence-steps .engine-step-row').forEach((row) => {
|
||||
const pid = row.querySelector('.engine-step-preset').value;
|
||||
const dur = Number(row.querySelector('.engine-step-duration').value);
|
||||
if (pid) steps.push({ preset_id: pid, duration_s: Number.isFinite(dur) ? dur : 5 });
|
||||
});
|
||||
return {
|
||||
name: document.getElementById('edit-sequence-name').value.trim(),
|
||||
zone_id: document.getElementById('edit-sequence-zone').value || null,
|
||||
loop: document.getElementById('edit-sequence-loop').checked,
|
||||
repeat_count: Number(document.getElementById('edit-sequence-repeat').value) || 0,
|
||||
steps,
|
||||
};
|
||||
}
|
||||
|
||||
// Tell the engine a preset was picked on a zone: renders it on the zone's pixel
|
||||
// outputs and stops any sequence there. ESP32s were already sent the preset
|
||||
// by presets.js, so the engine leaves them alone (drivers: false).
|
||||
async function notifyEngineZonePlay(zoneId, presetId) {
|
||||
if (!zoneId || !presetId) return;
|
||||
try {
|
||||
await fetch(`/zones/${encodeURIComponent(zoneId)}/play`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
body: JSON.stringify({ preset_id: String(presetId), drivers: false }),
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn('Engine zone play failed:', e);
|
||||
}
|
||||
}
|
||||
window.notifyEngineZonePlay = notifyEngineZonePlay;
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const btn = document.getElementById('sequences-btn');
|
||||
const modal = document.getElementById('sequences-modal');
|
||||
const editModal = document.getElementById('edit-sequence-modal');
|
||||
const form = document.getElementById('edit-sequence-form');
|
||||
if (!btn || !modal || !form) return;
|
||||
|
||||
btn.addEventListener('click', () => {
|
||||
modal.classList.add('active');
|
||||
refreshSequencesList();
|
||||
stopSequencesPoll();
|
||||
sequencesPollTimer = setInterval(refreshSequencesList, SEQUENCES_POLL_MS);
|
||||
});
|
||||
document.getElementById('sequences-close-btn').addEventListener('click', () => {
|
||||
modal.classList.remove('active');
|
||||
});
|
||||
new MutationObserver(() => {
|
||||
if (!modal.classList.contains('active')) stopSequencesPoll();
|
||||
}).observe(modal, { attributes: true, attributeFilter: ['class'] });
|
||||
|
||||
document.getElementById('sequence-add-btn').addEventListener('click', async () => {
|
||||
const ctx = lastSequenceCtx || await loadSequenceContext();
|
||||
openSequenceEditor(null, null, ctx);
|
||||
});
|
||||
document.getElementById('edit-sequence-add-step-btn').addEventListener('click', () => {
|
||||
addStepRow((lastSequenceCtx && lastSequenceCtx.presets) || {}, null);
|
||||
});
|
||||
document.getElementById('edit-sequence-close-btn').addEventListener('click', () => {
|
||||
editModal.classList.remove('active');
|
||||
});
|
||||
|
||||
form.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
const id = document.getElementById('edit-sequence-id').value;
|
||||
const err = document.getElementById('edit-sequence-error');
|
||||
err.hidden = true;
|
||||
const body = readSequenceForm();
|
||||
if (!body.steps.length) {
|
||||
err.textContent = 'Add at least one step.';
|
||||
err.hidden = false;
|
||||
return;
|
||||
}
|
||||
const res = await fetch(id ? `/sequences/${encodeURIComponent(id)}` : '/sequences', {
|
||||
method: id ? 'PUT' : 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
err.textContent = data.error || 'Save failed';
|
||||
err.hidden = false;
|
||||
return;
|
||||
}
|
||||
editModal.classList.remove('active');
|
||||
refreshSequencesList();
|
||||
});
|
||||
});
|
||||
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user