From 71bd320661092ef152604c4b2e915aaf9d1b6361 Mon Sep 17 00:00:00 2001 From: jimmy Date: Mon, 2 Nov 2026 20:29:48 +1300 Subject: [PATCH] feat(v2): move web UI into v2, remove legacy MicroPython app Move the web assets and templates under v2/web, drop the old src/, lib/ and scripts, and update firmware, tools, docs and db files. Add the audio page, LED test scripts and VPN autoconnect script. Co-Authored-By: Claude Sonnet 5.5 --- Makefile | 6 +- Pipfile | 30 - Pipfile.lock | 1026 -------- README.md | 97 +- db/device.json | 2 +- db/pattern.json | 2 +- db/preset.json | 2 +- db/profile.json | 2 +- db/zone.json | 2 +- docs/API.md | 1 + led-driver | 2 +- lib/microdot/__init__.py | 2 - lib/microdot/helpers.py | 8 - lib/microdot/microdot.py | 1450 ----------- lib/microdot/session.py | 225 -- lib/microdot/utemplate.py | 70 - lib/microdot/websocket.py | 231 -- lib/utemplate/__init__.py | 0 lib/utemplate/compiled.py | 14 - lib/utemplate/recompile.py | 21 - lib/utemplate/source.py | 188 -- pyproject.toml | 3 - scripts/dev-run.sh | 16 - scripts/install-boot-service.sh | 32 - scripts/led-controller.service | 20 - scripts/led-test/.gitignore | 1 + scripts/led-test/CMakeLists.txt | 3 + scripts/led-test/dependencies.lock | 20 + scripts/led-test/main/CMakeLists.txt | 1 + scripts/led-test/main/idf_component.yml | 2 + scripts/led-test/main/main.c | 29 + .../espressif__led_strip/.component_hash | 1 + .../espressif__led_strip/CHANGELOG.md | 54 + .../espressif__led_strip/CHECKSUMS.json | 1 + .../espressif__led_strip/CMakeLists.txt | 31 + .../espressif__led_strip/Doxyfile | 28 + .../espressif__led_strip/LICENSE | 202 ++ .../espressif__led_strip/README.md | 97 + .../espressif__led_strip/api.md | 454 ++++ .../led_strip_rmt_ws2812/CMakeLists.txt | 8 + .../examples/led_strip_rmt_ws2812/README.md | 31 + .../led_strip_rmt_ws2812/main/CMakeLists.txt | 2 + .../main/idf_component.yml | 5 + .../main/led_strip_rmt_ws2812_main.c | 75 + .../led_strip_spi_ws2812/CMakeLists.txt | 8 + .../examples/led_strip_spi_ws2812/README.md | 31 + .../led_strip_spi_ws2812/main/CMakeLists.txt | 2 + .../main/idf_component.yml | 6 + .../main/led_strip_spi_ws2812_main.c | 69 + .../espressif__led_strip/idf_component.yml | 9 + .../espressif__led_strip/include/led_strip.h | 111 + .../include/led_strip_rmt.h | 53 + .../include/led_strip_spi.h | 46 + .../include/led_strip_types.h | 54 + .../interface/led_strip_interface.h | 95 + .../espressif__led_strip/src/led_strip_api.c | 94 + .../src/led_strip_rmt_dev.c | 164 ++ .../src/led_strip_rmt_dev_idf4.c | 194 ++ .../src/led_strip_rmt_encoder.c | 146 ++ .../src/led_strip_rmt_encoder.h | 38 + .../src/led_strip_spi_dev.c | 211 ++ scripts/led-test/sdkconfig | 2202 +++++++++++++++++ scripts/led-test/sdkconfig.defaults | 1 + scripts/setup-port80.sh | 35 - scripts/setup-vpn-autoconnect.sh | 82 + scripts/start.sh | 38 - scripts/test-port80.sh | 33 - src/boot.py | 6 - src/controllers/__init__.py | 1 - src/controllers/device.py | 393 --- src/controllers/group.py | 50 - src/controllers/led_tool.py | 189 -- src/controllers/output.py | 85 - src/controllers/palette.py | 58 - src/controllers/pattern.py | 500 ---- src/controllers/preset.py | 322 --- src/controllers/profile.py | 390 --- src/controllers/scene.py | 83 - src/controllers/sequence.py | 78 - src/controllers/settings.py | 110 - src/controllers/zone.py | 400 --- src/engine/__init__.py | 25 - src/engine/cli.py | 148 -- src/engine/core.py | 89 - src/engine/frame_driver.py | 68 - src/engine/mpcompat.py | 86 - src/engine/outputs/__init__.py | 72 - src/engine/outputs/artnet.py | 78 - src/engine/outputs/base.py | 254 -- src/engine/outputs/ddp.py | 61 - src/engine/outputs/dmx_serial.py | 97 - src/engine/outputs/driver.py | 75 - src/engine/outputs/sacn.py | 92 - src/engine/pattern_loader.py | 116 - src/engine/player.py | 148 -- src/engine/presets.py | 61 - src/engine/renderer.py | 157 -- src/engine/sequence_runner.py | 161 -- src/engine/zone_targets.py | 56 - src/main.py | 431 ---- src/models/__init__.py | 1 - src/models/device.py | 285 --- src/models/group.py | 51 - src/models/http_driver.py | 125 - src/models/model.py | 113 - src/models/output.py | 138 -- src/models/pallet.py | 45 - src/models/pattern.py | 38 - src/models/preset.py | 69 - src/models/profile.py | 69 - src/models/scene.py | 38 - src/models/serial.py | 12 - src/models/squence.py | 112 - src/models/transport.py | 90 - src/models/wifi_peer.py | 8 - src/models/wifi_ws_clients.py | 365 --- src/models/zone.py | 62 - src/profile.py | 0 src/settings.py | 105 - src/static/app.js | 1734 ------------- src/static/main.js | 81 - src/static/rgb-slider.js | 195 -- src/static/styles.css | 37 - src/util/README.md | 80 - src/util/device_status_broadcaster.py | 52 - src/util/driver_delivery.py | 224 -- src/util/driver_patterns.py | 53 - src/util/espnow_message.py | 194 -- src/util/message.py | 25 - tests/README.md | 47 - tests/async_tcp_server.py | 182 -- tests/conftest.py | 14 - tests/device_ws_cycle.py | 300 --- tests/engine_tests/test_output_model.py | 37 - tests/engine_tests/test_outputs.py | 303 --- tests/engine_tests/test_player.py | 242 -- tests/engine_tests/test_renderer.py | 119 - tests/engine_tests/test_sequences.py | 214 -- tests/models/__init__.py | 1 - tests/models/run_all.py | 62 - tests/models/test_device.py | 168 -- tests/models/test_group.py | 61 - tests/models/test_model.py | 55 - tests/models/test_palette.py | 64 - tests/models/test_preset.py | 60 - tests/models/test_profile.py | 60 - tests/models/test_sequence.py | 62 - tests/models/test_zone.py | 57 - tests/p2p.py | 105 - tests/tcp_test_server.py | 216 -- tests/test_binary_envelope.py | 93 - tests/test_browser.py | 1131 --------- tests/test_endpoints.py | 596 ----- tests/test_endpoints_pytest.py | 859 ------- tests/test_main_old.py | 16 - tests/test_pattern_ota_send.py | 99 - tests/udp_server.py | 89 - tests/web.py | 342 --- tests/ws.py | 193 -- v2/dependencies.lock | 13 +- v2/docs/BENCH_TEST.md | 6 +- v2/main/CMakeLists.txt | 9 +- v2/main/api.c | 45 + v2/main/idf_component.yml | 1 + v2/main/main.c | 138 ++ v2/main/ota.c | 32 +- v2/main/ota.h | 2 + v2/main/store.c | 2 +- v2/main/store.h | 2 +- v2/main/web.c | 70 +- v2/main/web.h | 4 +- v2/partitions.csv | 3 +- {src/util => v2/test}/binary_envelope.py | 0 v2/test/env_check.py | 4 +- v2/tools/build_web.sh | 46 +- v2/tools/ota.py | 59 +- v2/web/static/audio.js | 188 ++ {src => v2/web}/static/color_palette.js | 0 {src => v2/web}/static/devices.js | 29 +- {src => v2/web}/static/help.js | 98 + {src => v2/web}/static/htmx.min.js | 0 {src => v2/web}/static/led_tool.js | 0 {src => v2/web}/static/list_search.js | 0 {src => v2/web}/static/outputs.js | 0 {src => v2/web}/static/patterns.js | 0 {src => v2/web}/static/presets.js | 84 +- {src => v2/web}/static/profiles.js | 0 {src => v2/web}/static/sequences.js | 0 {src => v2/web}/static/style.css | 135 + {src => v2/web}/static/zone_palette.js | 0 {src => v2/web}/static/zones.js | 0 {src => v2/web}/templates/index.html | 88 + {src => v2/web}/templates/settings.html | 0 193 files changed, 5605 insertions(+), 18860 deletions(-) delete mode 100644 Pipfile delete mode 100644 Pipfile.lock delete mode 100644 lib/microdot/__init__.py delete mode 100644 lib/microdot/helpers.py delete mode 100644 lib/microdot/microdot.py delete mode 100644 lib/microdot/session.py delete mode 100644 lib/microdot/utemplate.py delete mode 100644 lib/microdot/websocket.py delete mode 100644 lib/utemplate/__init__.py delete mode 100644 lib/utemplate/compiled.py delete mode 100644 lib/utemplate/recompile.py delete mode 100644 lib/utemplate/source.py delete mode 100644 pyproject.toml delete mode 100644 scripts/dev-run.sh delete mode 100755 scripts/install-boot-service.sh delete mode 100644 scripts/led-controller.service create mode 100644 scripts/led-test/.gitignore create mode 100644 scripts/led-test/CMakeLists.txt create mode 100644 scripts/led-test/dependencies.lock create mode 100644 scripts/led-test/main/CMakeLists.txt create mode 100644 scripts/led-test/main/idf_component.yml create mode 100644 scripts/led-test/main/main.c create mode 100644 scripts/led-test/managed_components/espressif__led_strip/.component_hash create mode 100644 scripts/led-test/managed_components/espressif__led_strip/CHANGELOG.md create mode 100644 scripts/led-test/managed_components/espressif__led_strip/CHECKSUMS.json create mode 100644 scripts/led-test/managed_components/espressif__led_strip/CMakeLists.txt create mode 100644 scripts/led-test/managed_components/espressif__led_strip/Doxyfile create mode 100644 scripts/led-test/managed_components/espressif__led_strip/LICENSE create mode 100644 scripts/led-test/managed_components/espressif__led_strip/README.md create mode 100644 scripts/led-test/managed_components/espressif__led_strip/api.md create mode 100644 scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/CMakeLists.txt create mode 100644 scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/README.md create mode 100644 scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/main/CMakeLists.txt create mode 100644 scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/main/idf_component.yml create mode 100644 scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/main/led_strip_rmt_ws2812_main.c create mode 100644 scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/CMakeLists.txt create mode 100644 scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/README.md create mode 100644 scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/main/CMakeLists.txt create mode 100644 scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/main/idf_component.yml create mode 100644 scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/main/led_strip_spi_ws2812_main.c create mode 100644 scripts/led-test/managed_components/espressif__led_strip/idf_component.yml create mode 100644 scripts/led-test/managed_components/espressif__led_strip/include/led_strip.h create mode 100644 scripts/led-test/managed_components/espressif__led_strip/include/led_strip_rmt.h create mode 100644 scripts/led-test/managed_components/espressif__led_strip/include/led_strip_spi.h create mode 100644 scripts/led-test/managed_components/espressif__led_strip/include/led_strip_types.h create mode 100644 scripts/led-test/managed_components/espressif__led_strip/interface/led_strip_interface.h create mode 100644 scripts/led-test/managed_components/espressif__led_strip/src/led_strip_api.c create mode 100644 scripts/led-test/managed_components/espressif__led_strip/src/led_strip_rmt_dev.c create mode 100644 scripts/led-test/managed_components/espressif__led_strip/src/led_strip_rmt_dev_idf4.c create mode 100644 scripts/led-test/managed_components/espressif__led_strip/src/led_strip_rmt_encoder.c create mode 100644 scripts/led-test/managed_components/espressif__led_strip/src/led_strip_rmt_encoder.h create mode 100644 scripts/led-test/managed_components/espressif__led_strip/src/led_strip_spi_dev.c create mode 100644 scripts/led-test/sdkconfig create mode 100644 scripts/led-test/sdkconfig.defaults delete mode 100755 scripts/setup-port80.sh create mode 100755 scripts/setup-vpn-autoconnect.sh delete mode 100755 scripts/start.sh delete mode 100755 scripts/test-port80.sh delete mode 100644 src/boot.py delete mode 100644 src/controllers/__init__.py delete mode 100644 src/controllers/device.py delete mode 100644 src/controllers/group.py delete mode 100644 src/controllers/led_tool.py delete mode 100644 src/controllers/output.py delete mode 100644 src/controllers/palette.py delete mode 100644 src/controllers/pattern.py delete mode 100644 src/controllers/preset.py delete mode 100644 src/controllers/profile.py delete mode 100644 src/controllers/scene.py delete mode 100644 src/controllers/sequence.py delete mode 100644 src/controllers/settings.py delete mode 100644 src/controllers/zone.py delete mode 100644 src/engine/__init__.py delete mode 100644 src/engine/cli.py delete mode 100644 src/engine/core.py delete mode 100644 src/engine/frame_driver.py delete mode 100644 src/engine/mpcompat.py delete mode 100644 src/engine/outputs/__init__.py delete mode 100644 src/engine/outputs/artnet.py delete mode 100644 src/engine/outputs/base.py delete mode 100644 src/engine/outputs/ddp.py delete mode 100644 src/engine/outputs/dmx_serial.py delete mode 100644 src/engine/outputs/driver.py delete mode 100644 src/engine/outputs/sacn.py delete mode 100644 src/engine/pattern_loader.py delete mode 100644 src/engine/player.py delete mode 100644 src/engine/presets.py delete mode 100644 src/engine/renderer.py delete mode 100644 src/engine/sequence_runner.py delete mode 100644 src/engine/zone_targets.py delete mode 100644 src/main.py delete mode 100644 src/models/__init__.py delete mode 100644 src/models/device.py delete mode 100644 src/models/group.py delete mode 100644 src/models/http_driver.py delete mode 100644 src/models/model.py delete mode 100644 src/models/output.py delete mode 100644 src/models/pallet.py delete mode 100644 src/models/pattern.py delete mode 100644 src/models/preset.py delete mode 100644 src/models/profile.py delete mode 100644 src/models/scene.py delete mode 100644 src/models/serial.py delete mode 100644 src/models/squence.py delete mode 100644 src/models/transport.py delete mode 100644 src/models/wifi_peer.py delete mode 100644 src/models/wifi_ws_clients.py delete mode 100644 src/models/zone.py delete mode 100644 src/profile.py delete mode 100644 src/settings.py delete mode 100644 src/static/app.js delete mode 100644 src/static/main.js delete mode 100644 src/static/rgb-slider.js delete mode 100644 src/static/styles.css delete mode 100644 src/util/README.md delete mode 100644 src/util/device_status_broadcaster.py delete mode 100644 src/util/driver_delivery.py delete mode 100644 src/util/driver_patterns.py delete mode 100644 src/util/espnow_message.py delete mode 100644 src/util/message.py delete mode 100644 tests/README.md delete mode 100644 tests/async_tcp_server.py delete mode 100644 tests/conftest.py delete mode 100644 tests/device_ws_cycle.py delete mode 100644 tests/engine_tests/test_output_model.py delete mode 100644 tests/engine_tests/test_outputs.py delete mode 100644 tests/engine_tests/test_player.py delete mode 100644 tests/engine_tests/test_renderer.py delete mode 100644 tests/engine_tests/test_sequences.py delete mode 100644 tests/models/__init__.py delete mode 100644 tests/models/run_all.py delete mode 100644 tests/models/test_device.py delete mode 100644 tests/models/test_group.py delete mode 100644 tests/models/test_model.py delete mode 100644 tests/models/test_palette.py delete mode 100644 tests/models/test_preset.py delete mode 100644 tests/models/test_profile.py delete mode 100644 tests/models/test_sequence.py delete mode 100644 tests/models/test_zone.py delete mode 100644 tests/p2p.py delete mode 100644 tests/tcp_test_server.py delete mode 100644 tests/test_binary_envelope.py delete mode 100644 tests/test_browser.py delete mode 100644 tests/test_endpoints.py delete mode 100644 tests/test_endpoints_pytest.py delete mode 100644 tests/test_main_old.py delete mode 100644 tests/test_pattern_ota_send.py delete mode 100644 tests/udp_server.py delete mode 100755 tests/web.py delete mode 100644 tests/ws.py rename {src/util => v2/test}/binary_envelope.py (100%) create mode 100644 v2/web/static/audio.js rename {src => v2/web}/static/color_palette.js (100%) rename {src => v2/web}/static/devices.js (93%) rename {src => v2/web}/static/help.js (65%) rename {src => v2/web}/static/htmx.min.js (100%) rename {src => v2/web}/static/led_tool.js (100%) rename {src => v2/web}/static/list_search.js (100%) rename {src => v2/web}/static/outputs.js (100%) rename {src => v2/web}/static/patterns.js (100%) rename {src => v2/web}/static/presets.js (96%) rename {src => v2/web}/static/profiles.js (100%) rename {src => v2/web}/static/sequences.js (100%) rename {src => v2/web}/static/style.css (92%) rename {src => v2/web}/static/zone_palette.js (100%) rename {src => v2/web}/static/zones.js (100%) rename {src => v2/web}/templates/index.html (86%) rename {src => v2/web}/templates/settings.html (100%) diff --git a/Makefile b/Makefile index 089f6ae..daa60d6 100644 --- a/Makefile +++ b/Makefile @@ -29,7 +29,7 @@ help: @echo "v2 controller (ESP32-S3):" @echo " make build minify + gzip the web UI, then build the firmware" @echo " make flash flash firmware and web UI to PORT ($(PORT))" - @echo " make ota HOST=ip build, then upload the firmware over Ethernet (no USB)" + @echo " make ota HOST=ip build, then upload the firmware (web UI included) over Ethernet (no USB)" @echo " make monitor serial console on PORT (Ctrl-] to quit)" @echo " make flash-monitor flash, then open the console" @echo " make log [SECS=10] print the console for SECS seconds and exit (no terminal needed)" @@ -55,7 +55,7 @@ flash: build ota: build @test -n "$(HOST)" || { echo "usage: make ota HOST="; exit 1; } - python3 $(V2)/tools/ota.py $(HOST) $(V2)/build/led_controller_v2.bin + python3 $(V2)/tools/ota.py $(HOST) monitor: $(DOCKER_RUN) $(TTY) $(DEVICE) $(IDF_IMAGE) idf.py -p $(PORT) monitor @@ -88,7 +88,7 @@ test: test-driver test-envelope test-driver: python3 $(V2)/tools/run_driver_tests.py -# The C envelope packer must produce the same bytes as src/util/binary_envelope.py +# The C envelope packer must produce the same bytes as v2/test/binary_envelope.py test-envelope: @tmp=$$(mktemp -d); \ (cd $(V2)/test && python3 env_check.py) > $$tmp/py.txt; \ diff --git a/Pipfile b/Pipfile deleted file mode 100644 index 77dd016..0000000 --- a/Pipfile +++ /dev/null @@ -1,30 +0,0 @@ -[[source]] -url = "https://pypi.org/simple" -verify_ssl = true -name = "pypi" - -[packages] -mpremote = "*" -pyserial = "*" -esptool = "*" -pyjwt = "*" -watchfiles = "*" -requests = "*" -selenium = "*" -adafruit-ampy = "*" -microdot = "*" -websockets = "*" - -[dev-packages] -pytest = "*" - -[requires] -python_version = "3.11" - -[scripts] -web = "python /home/pi/led-controller/tests/web.py" -watch = "python -m watchfiles 'python tests/web.py' src tests" -install = "pipenv install" -run = "sh -c 'cd src && python main.py'" -dev = "watchfiles \"sh -c 'cd src && python main.py'\" src" -help-pdf = "sh scripts/build_help_pdf.sh" diff --git a/Pipfile.lock b/Pipfile.lock deleted file mode 100644 index 0b90b1e..0000000 --- a/Pipfile.lock +++ /dev/null @@ -1,1026 +0,0 @@ -{ - "_meta": { - "hash": { - "sha256": "98da2012e549e7b62ed49a5e1717acaf535b71e8df61bf4108d25b9023be612e" - }, - "pipfile-spec": 6, - "requires": { - "python_version": "3.11" - }, - "sources": [ - { - "name": "pypi", - "url": "https://pypi.org/simple", - "verify_ssl": true - } - ] - }, - "default": { - "adafruit-ampy": { - "hashes": [ - "sha256:4a74812226e53c17d01eb828633424bc4f4fe76b9499a7b35eba6fc2532635b7", - "sha256:f4cba36f564096f2aafd173f7fbabb845365cc3bb3f41c37541edf98b58d3976" - ], - "index": "pypi", - "version": "==1.1.0" - }, - "anyio": { - "hashes": [ - "sha256:08b310f9e24a9594186fd75b4f73f4a4152069e3853f1ed8bfbf58369f4ad708", - "sha256:334b70e641fd2221c1505b3890c69882fe4a2df910cba14d97019b90b24439dc" - ], - "markers": "python_version >= '3.10'", - "version": "==4.13.0" - }, - "attrs": { - "hashes": [ - "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", - "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32" - ], - "markers": "python_version >= '3.9'", - "version": "==26.1.0" - }, - "bitarray": { - "hashes": [ - "sha256:0256d57e294414bfe4fec4f852fd1d9ae361228c71b082332bf81c8b8fc69f80", - "sha256:03fe327549f177040b32f7faa736dc152be936d8b264d8b84f94c75f1379bfa1", - "sha256:07626f76a248fce5ebbb10fb0d4899d3c7f908ba21cb2fb4f5a7a9daf24c20cd", - "sha256:0793c51d3b1c7410bde1f7254fff71fabff1bc0cdeba1fa51319ac4e7931df3d", - "sha256:0a33f8931ac91ebc23ce4decb99ed8fdddba2bafd2af3bb2781bcfd9878d4822", - "sha256:0a661f3492462e7adf8a054fb7414a22fc8251f1e18b9d8cbcf008d2dc85f012", - "sha256:0c8c66f5d8055cb84ad0ea14af57b3579cb0b6db589f2086f5e33f0922cf2354", - "sha256:0da5f17bed67ffe1d72f79fbf98403513a6e51a4f9b8293c1ff8a64e121242be", - "sha256:0f099a4a77daf9bb99787070854894fe588c7d6988ea729f970ba2b3b82c7559", - "sha256:10c0caabff00ab0631d1e4fd25f56c7a5cf0f068426e5860d28dbbb972b509bf", - "sha256:133648c3405564e7fef9103f1768cb018de1b4976f3d8beff09cd4acea73bfe4", - "sha256:154a19e1dcd430494fdad7d1a0fb36383baaa363e1cb9d5a7b744cd2418c44d2", - "sha256:18f3a2c8908e63a66d3994808254397a5f989b1fb91087c33739f62bf1a1a064", - "sha256:190a3482818d69faef176171c7cae10d55cb4dd0c686b5aced7f592b5e5591c1", - "sha256:190b20cbffc9cd7f308f7a57d406119c3af3ae197613325fd2d92d99c8882ad6", - "sha256:1d7b786a1ddd9b8dda17c445060a94a465cba2e113603ae7bdc5364efc1efd11", - "sha256:20e412527ec1aac7e3a6542b32a9c34bb852c954676b05008f0e3d58c390a0ac", - "sha256:21add0aa968496a2bd8341d85720d09808e22e0adc7dbefc1e0f8f67c4b83f36", - "sha256:2762db8049b230520358ac742cbc57bceaacebe34e5d25c096f2b4bc3887a3a8", - "sha256:29c8c10a49d6a9586f592116618b99c3dabcb24d881b7a649e0691ef87f314c4", - "sha256:2b9916867fa1ed815739e3e37dda458f397dee25a0e293b808839cfc2a396ca0", - "sha256:2da2ca9495668ab77132a911f6bd530d2bfe686d10467584894efc3b66e9ffb5", - "sha256:2dc07dab252c63c4f6600e200b26fa05207db6b650d41ae88ab0cec4d6c59459", - "sha256:300e3026d17ae3328320ba78d3165bdb1c43d0dfdbc461a69ebbdc005d9ce0b3", - "sha256:30d42c34da2974a5e2e0b51c57ecf89892c1e83ed67e1084d1e27eefc27add91", - "sha256:329b994944993c45c3845047476ef4f231fe1a53972f18f8d005fd12fac163e1", - "sha256:3a5e594b4be2dbfe021cee8d6d7d96e9bb19dee7ed7be351f43bca7a0619b978", - "sha256:3b9358f6437a5fa0c765ffae5810c9830547baf4bcf469438b82845c3f33f998", - "sha256:3b9790ae107fc8648155f120e80a58ef8e94424efefff5b355de84061de6a18b", - "sha256:40d1b57012bf9b4fefd25345aaa95aab3ca510cc693f33c2cb02a4b771d8e51a", - "sha256:430fe5150816445c8294a36ce2612360037342d750cea179efe5de38c66670a8", - "sha256:4494c599effa16064f2b600f6eb28115182d6826847d795a55691339788d8a4d", - "sha256:478b9f0ea86f957624dd2b159066855716f78db94666e9b04babe85fc013e01b", - "sha256:4b7d7d10a1c82050efbb9a83d7a43974f70cf8f021afb86463b42e4ac4e5a46b", - "sha256:4c7ce072191ba23a4a4876452ccd5f2a67b926e66a248d052d39e9969cd3ab47", - "sha256:4da256fc567a57ded2a4aa962fc9e9d430ab740e5c67be9e98a63ef4eb467f2f", - "sha256:4e34f1cb6cdb036c5f4a839a2b74419f75fa36177a70c4bab2867f48973cbe44", - "sha256:4fb869faf4b484cb213199ced1e2732091559107637d429fc25d0a9731f5f630", - "sha256:539880ddf9a8cc54c9e6126e7d072c991563f0c90ef73b3519a783d53df00352", - "sha256:55f4b105a1686eb486069a9e578d502d1998e890d8144012225de9e0450aeabd", - "sha256:5743f532e408cfd716fa16776b5a6447b83ff2cf39021fb5f8d052aa0f331508", - "sha256:5b67b869f860eb19055e2560844d8c7d0935245938935bdb764b3e683e2014e2", - "sha256:5e30d8e399f38ae1ec86aa9be76d20ba15872dd0c41b4b46d1b78905857363b9", - "sha256:660e11b9932f58f10151d0febd11f77d3b0d48d6fa4dd4686d8983f40187101e", - "sha256:67125404d12547443d74113862a80c10310cf875aff8dbfc5548fee1d9737123", - "sha256:6956ef0259a037f10da767741aca82925f6f9978bb6dceb5344e56ce0629ab07", - "sha256:698c37fca3761af69a09a1d39cc0492f7e8cb9e263af39a288dce8f3b8a9e2bc", - "sha256:69c8298e8197b113f765a2ea60f49ceb8e1ea9eb308140b3cdc611e0d1de70b8", - "sha256:6ef49462a615de062dcac8281944d0b036fe1e9c96a6c690bf6cf5e4b5488f0e", - "sha256:6f92d12a46b2a67d56194bb5d226dabf586b386d1f1a5e25be5b745a3080dbba", - "sha256:70f70ea138e69ec3159e4a38fef52443cb8eb81388aeb241b273265ea16387c5", - "sha256:72a0e87b2196120523fc6194ca6b580fcffa12d7daa4d57a16d7838e60f82d0e", - "sha256:72b32d8c471930c95d49640ec99f7694f9b040ca1342ff03ed69d3aea90f9339", - "sha256:746e25f17ba4203b5933773782cf2d30bca5cdb66a9ba5d48a53a6c795aedc57", - "sha256:75e33c9187da271d1dbeb2582ab2df2e441346492098f67559b09173ea4edde4", - "sha256:7875abfd90f2ae3aa22d50f3fa1c93bbae456458cc73d3179b838f07bed1fc10", - "sha256:78ab0d4166cf35c73054d1e04f224af1edc3cb4d75da8b6f74f4cff7c300f358", - "sha256:78cbda57a2808d994517b53571eaa2d9299359f63aa71cf4bc94210169aad8b1", - "sha256:7c133052737c7c75bfa49f5ba71918166fe988995b26a0d2f263a79bf8fed58a", - "sha256:7eae9e763fbd32f19f2a66dfc2e37906f8422e0c4ad4a6c9dcf9d3246740812e", - "sha256:814bb54db2a016026efc055a3527461e5eb551c0d91b32eeade003829ff84311", - "sha256:81ede1f094f26eeaff62e029ff1bc4e84e9d568f20d4669f64dcf7c7b18a28fc", - "sha256:838fd67b3d00c5a64181073282a2c0bf8f76465da4844d5e79d2dbbc64c987dc", - "sha256:89c7c125a0913d71ba9cc1fa8e14c7cfe1517b1c1f45416e1f9babcedd3b545d", - "sha256:8a345b5dc8ab8cafdf338e08530d48fe3f73df27f4ff569be793c7a7e7bb6b6b", - "sha256:8c3fe25871f1758519a3ad8dcafb1bd95c5d1aaeb122e6492ac739ab11fa5907", - "sha256:8e12d50d4d65c74bd877e15c276992263b878456a7cfcf72521e7205a553557f", - "sha256:9adacf6fdadeeb96e6c902aef08d02d2f45429fdbf0a75b80307e435156066f8", - "sha256:9befda0dbd27ed95fba1c26be4bf98a49ba166b3c91beb5fc04364c130ce950c", - "sha256:9fa5620f7f352f9706924c0e2071a212be36421f09ee064b0fd7e1128289fcdb", - "sha256:a681bbf9f94027d66e15974cd207cec1a2993837b9c45acf5f6b22a67632b1c2", - "sha256:ab363a5baae965fb3438f2137583853ad9c77d7e45f2a62ba63e609a34d792ea", - "sha256:ac49519fcfeb4a7ecdf6b7d0ec6cac409e59f94c1bb54630db577a97893b6e38", - "sha256:ad5a71c1ef4a2e404c2c888db09226c821d9d14eff8813e1da873572f5fbb89d", - "sha256:af01133e78e5528ee282ceb1cf4bc54aecb937c2001913e751452ad7dffbbeb1", - "sha256:b3118ec012a799456f7fca6cc002c078590578b7640fbaab52d8ecb9a651f1c1", - "sha256:b46b7aec9272fd81c984e723e599957629a91204120b3e7f0933f138e0792fdf", - "sha256:ba0339d6aa80615a17f47fabc5700485e9469121d658458f95cdd2003288c28b", - "sha256:c08cd5b19c570e1e9e094a6ce70d35bb39d12360e0763474ed9374229f174fcc", - "sha256:c0b367a00e8c88a714b2384c97dedcc85340547b3a54b6037a42fca5554d0576", - "sha256:c263ed9922942353a954cfbcd5f81b7626c0e20dc7f3e53d4926e8bc560ab845", - "sha256:c3387c314695f9790dce12fcf44357197ebf773651b6a4195f5e091cf500ae73", - "sha256:c4fd3399eaf6f1c77ea3132611efbc3d7a8c0eb899793387b3266be221dc75fd", - "sha256:cac0145491619287ff893853bf3ca4d98d5ef94b617271184a5af68a06ac301a", - "sha256:cd9b848c17ef034f2ae31b2a1bd9276710c2baf03509f1f3fa4dc4382b0a1b53", - "sha256:ced27af6aee28782260bfa5643797937e96a6489bca972202834017208cf74f5", - "sha256:cf99e36c0f6ae5643ecef7ad7e1194aeb4a9798d9cff60b20ac041533fa6db0a", - "sha256:d7d5f7f6f80388ce94849775da5f4082ab5e123e259972961970e190d60f5d2b", - "sha256:dc2cab92c42991b711132bc52405680e075d1505d4356c4468bc6e9c93d49137", - "sha256:ddcd25a1f72b2b545fb27e17882046a6c161f3f24514b2e028c00c58ed73a2dd", - "sha256:defa3c12cb06b2fd2066a9e21bf00aab96465be84d9585c8c05195f080510506", - "sha256:df3ffa6ef88166bb36f5d1492e71e664868b9b8b6afd55821e0ac0cb96625441", - "sha256:e127b2e7fc533728295196f9265d12834530f475bc6cd6f74619df415d04b8b1", - "sha256:e9ff57452fcadfd1a379314234657b8f4e9967ae64480ddf7c2fd82139bc8cf8", - "sha256:eb9fa02b9f5bbdb1d036a0c68999337793fa244528e0ce825e4b97cb7f7db99f", - "sha256:ec3d0a6c37a816ea6e3550697c60d90861c9b0f982a98a40b59ac1f7a360bfa9", - "sha256:ef123b6aead12e0784f72970e8d94a96ac0d0aa4438c7ab9235e2f8669a0a5ae", - "sha256:f90bb3c680804ec9630bcf8c0965e54b4de84d33b17d7da57c87c30f0c64c6f5", - "sha256:fb1df55f5700187c6db4b47dbdaf8a0653a111341ac7fccc596b397aa3399e65", - "sha256:fd68db1a0f5d9374a7b735414efe48d2b3ecbf0adea39299bb48030988f16149", - "sha256:fd6b5b6df14f98b2e7e474c1c7ea55fc32dcab038b3b34b76a591dec8ba50915", - "sha256:fd7e3158be382f8f140caccc0dc7742a7553ce4bf2978982abe3054d2cedd705", - "sha256:fe989bbed9d6f332c1e24d333936f3fa1375f380cd8028da0b985dcdefa6015a", - "sha256:ff2ca039a161d49a8c713f5380def315c6f793df5fe348b94782b1dbee37a644" - ], - "version": "==3.8.1" - }, - "bitstring": { - "hashes": [ - "sha256:e682ac522bb63e041d16cbc9d0ca86a4f00194db16d0847c7efe066f836b2e37", - "sha256:feac49524fcf3ef27e6081e86f02b10d2adf6c3773bf22fbe0e7eea9534bc737" - ], - "markers": "python_version >= '3.8'", - "version": "==4.4.0" - }, - "certifi": { - "hashes": [ - "sha256:3cb2210c8f88ba2318d29b0388d1023c8492ff72ecdde4ebdaddbb13a31b1c4a", - "sha256:8d455352a37b71bf76a79caa83a3d6c25afee4a385d632127b6afb3963f1c580" - ], - "markers": "python_version >= '3.7'", - "version": "==2026.4.22" - }, - "cffi": { - "hashes": [ - "sha256:00bdf7acc5f795150faa6957054fbbca2439db2f775ce831222b66f192f03beb", - "sha256:07b271772c100085dd28b74fa0cd81c8fb1a3ba18b21e03d7c27f3436a10606b", - "sha256:087067fa8953339c723661eda6b54bc98c5625757ea62e95eb4898ad5e776e9f", - "sha256:0a1527a803f0a659de1af2e1fd700213caba79377e27e4693648c2923da066f9", - "sha256:0cf2d91ecc3fcc0625c2c530fe004f82c110405f101548512cce44322fa8ac44", - "sha256:0f6084a0ea23d05d20c3edcda20c3d006f9b6f3fefeac38f59262e10cef47ee2", - "sha256:12873ca6cb9b0f0d3a0da705d6086fe911591737a59f28b7936bdfed27c0d47c", - "sha256:19f705ada2530c1167abacb171925dd886168931e0a7b78f5bffcae5c6b5be75", - "sha256:1cd13c99ce269b3ed80b417dcd591415d3372bcac067009b6e0f59c7d4015e65", - "sha256:1e3a615586f05fc4065a8b22b8152f0c1b00cdbc60596d187c2a74f9e3036e4e", - "sha256:1f72fb8906754ac8a2cc3f9f5aaa298070652a0ffae577e0ea9bd480dc3c931a", - "sha256:1fc9ea04857caf665289b7a75923f2c6ed559b8298a1b8c49e59f7dd95c8481e", - "sha256:203a48d1fb583fc7d78a4c6655692963b860a417c0528492a6bc21f1aaefab25", - "sha256:2081580ebb843f759b9f617314a24ed5738c51d2aee65d31e02f6f7a2b97707a", - "sha256:21d1152871b019407d8ac3985f6775c079416c282e431a4da6afe7aefd2bccbe", - "sha256:24b6f81f1983e6df8db3adc38562c83f7d4a0c36162885ec7f7b77c7dcbec97b", - "sha256:256f80b80ca3853f90c21b23ee78cd008713787b1b1e93eae9f3d6a7134abd91", - "sha256:28a3a209b96630bca57cce802da70c266eb08c6e97e5afd61a75611ee6c64592", - "sha256:2c8f814d84194c9ea681642fd164267891702542f028a15fc97d4674b6206187", - "sha256:2de9a304e27f7596cd03d16f1b7c72219bd944e99cc52b84d0145aefb07cbd3c", - "sha256:38100abb9d1b1435bc4cc340bb4489635dc2f0da7456590877030c9b3d40b0c1", - "sha256:3925dd22fa2b7699ed2617149842d2e6adde22b262fcbfada50e3d195e4b3a94", - "sha256:3e17ed538242334bf70832644a32a7aae3d83b57567f9fd60a26257e992b79ba", - "sha256:3e837e369566884707ddaf85fc1744b47575005c0a229de3327f8f9a20f4efeb", - "sha256:3f4d46d8b35698056ec29bca21546e1551a205058ae1a181d871e278b0b28165", - "sha256:44d1b5909021139fe36001ae048dbdde8214afa20200eda0f64c068cac5d5529", - "sha256:45d5e886156860dc35862657e1494b9bae8dfa63bf56796f2fb56e1679fc0bca", - "sha256:4647afc2f90d1ddd33441e5b0e85b16b12ddec4fca55f0d9671fef036ecca27c", - "sha256:4671d9dd5ec934cb9a73e7ee9676f9362aba54f7f34910956b84d727b0d73fb6", - "sha256:53f77cbe57044e88bbd5ed26ac1d0514d2acf0591dd6bb02a3ae37f76811b80c", - "sha256:5eda85d6d1879e692d546a078b44251cdd08dd1cfb98dfb77b670c97cee49ea0", - "sha256:5fed36fccc0612a53f1d4d9a816b50a36702c28a2aa880cb8a122b3466638743", - "sha256:61d028e90346df14fedc3d1e5441df818d095f3b87d286825dfcbd6459b7ef63", - "sha256:66f011380d0e49ed280c789fbd08ff0d40968ee7b665575489afa95c98196ab5", - "sha256:6824f87845e3396029f3820c206e459ccc91760e8fa24422f8b0c3d1731cbec5", - "sha256:6c6c373cfc5c83a975506110d17457138c8c63016b563cc9ed6e056a82f13ce4", - "sha256:6d02d6655b0e54f54c4ef0b94eb6be0607b70853c45ce98bd278dc7de718be5d", - "sha256:6d50360be4546678fc1b79ffe7a66265e28667840010348dd69a314145807a1b", - "sha256:730cacb21e1bdff3ce90babf007d0a0917cc3e6492f336c2f0134101e0944f93", - "sha256:737fe7d37e1a1bffe70bd5754ea763a62a066dc5913ca57e957824b72a85e205", - "sha256:74a03b9698e198d47562765773b4a8309919089150a0bb17d829ad7b44b60d27", - "sha256:7553fb2090d71822f02c629afe6042c299edf91ba1bf94951165613553984512", - "sha256:7a66c7204d8869299919db4d5069a82f1561581af12b11b3c9f48c584eb8743d", - "sha256:7cc09976e8b56f8cebd752f7113ad07752461f48a58cbba644139015ac24954c", - "sha256:81afed14892743bbe14dacb9e36d9e0e504cd204e0b165062c488942b9718037", - "sha256:8941aaadaf67246224cee8c3803777eed332a19d909b47e29c9842ef1e79ac26", - "sha256:89472c9762729b5ae1ad974b777416bfda4ac5642423fa93bd57a09204712322", - "sha256:8ea985900c5c95ce9db1745f7933eeef5d314f0565b27625d9a10ec9881e1bfb", - "sha256:8eca2a813c1cb7ad4fb74d368c2ffbbb4789d377ee5bb8df98373c2cc0dee76c", - "sha256:92b68146a71df78564e4ef48af17551a5ddd142e5190cdf2c5624d0c3ff5b2e8", - "sha256:9332088d75dc3241c702d852d4671613136d90fa6881da7d770a483fd05248b4", - "sha256:94698a9c5f91f9d138526b48fe26a199609544591f859c870d477351dc7b2414", - "sha256:9a67fc9e8eb39039280526379fb3a70023d77caec1852002b4da7e8b270c4dd9", - "sha256:9de40a7b0323d889cf8d23d1ef214f565ab154443c42737dfe52ff82cf857664", - "sha256:a05d0c237b3349096d3981b727493e22147f934b20f6f125a3eba8f994bec4a9", - "sha256:afb8db5439b81cf9c9d0c80404b60c3cc9c3add93e114dcae767f1477cb53775", - "sha256:b18a3ed7d5b3bd8d9ef7a8cb226502c6bf8308df1525e1cc676c3680e7176739", - "sha256:b1e74d11748e7e98e2f426ab176d4ed720a64412b6a15054378afdb71e0f37dc", - "sha256:b21e08af67b8a103c71a250401c78d5e0893beff75e28c53c98f4de42f774062", - "sha256:b4c854ef3adc177950a8dfc81a86f5115d2abd545751a304c5bcf2c2c7283cfe", - "sha256:b882b3df248017dba09d6b16defe9b5c407fe32fc7c65a9c69798e6175601be9", - "sha256:baf5215e0ab74c16e2dd324e8ec067ef59e41125d3eade2b863d294fd5035c92", - "sha256:c649e3a33450ec82378822b3dad03cc228b8f5963c0c12fc3b1e0ab940f768a5", - "sha256:c654de545946e0db659b3400168c9ad31b5d29593291482c43e3564effbcee13", - "sha256:c6638687455baf640e37344fe26d37c404db8b80d037c3d29f58fe8d1c3b194d", - "sha256:c8d3b5532fc71b7a77c09192b4a5a200ea992702734a2e9279a37f2478236f26", - "sha256:cb527a79772e5ef98fb1d700678fe031e353e765d1ca2d409c92263c6d43e09f", - "sha256:cf364028c016c03078a23b503f02058f1814320a56ad535686f90565636a9495", - "sha256:d48a880098c96020b02d5a1f7d9251308510ce8858940e6fa99ece33f610838b", - "sha256:d68b6cef7827e8641e8ef16f4494edda8b36104d79773a334beaa1e3521430f6", - "sha256:d9b29c1f0ae438d5ee9acb31cadee00a58c46cc9c0b2f9038c6b0b3470877a8c", - "sha256:d9b97165e8aed9272a6bb17c01e3cc5871a594a446ebedc996e2397a1c1ea8ef", - "sha256:da68248800ad6320861f129cd9c1bf96ca849a2771a59e0344e88681905916f5", - "sha256:da902562c3e9c550df360bfa53c035b2f241fed6d9aef119048073680ace4a18", - "sha256:dbd5c7a25a7cb98f5ca55d258b103a2054f859a46ae11aaf23134f9cc0d356ad", - "sha256:dd4f05f54a52fb558f1ba9f528228066954fee3ebe629fc1660d874d040ae5a3", - "sha256:de8dad4425a6ca6e4e5e297b27b5c824ecc7581910bf9aee86cb6835e6812aa7", - "sha256:e11e82b744887154b182fd3e7e8512418446501191994dbf9c9fc1f32cc8efd5", - "sha256:e6e73b9e02893c764e7e8d5bb5ce277f1a009cd5243f8228f75f842bf937c534", - "sha256:f73b96c41e3b2adedc34a7356e64c8eb96e03a3782b535e043a986276ce12a49", - "sha256:f93fd8e5c8c0a4aa1f424d6173f14a892044054871c771f8566e4008eaa359d2", - "sha256:fc33c5141b55ed366cfaad382df24fe7dcbc686de5be719b207bb248e3053dc5", - "sha256:fc7de24befaeae77ba923797c7c87834c73648a05a4bde34b3b7e5588973a453", - "sha256:fe562eb1a64e67dd297ccc4f5addea2501664954f2692b69a76449ec7913ecbf" - ], - "markers": "python_full_version >= '3.9' and platform_python_implementation != 'PyPy'", - "version": "==2.0.0" - }, - "charset-normalizer": { - "hashes": [ - "sha256:007d05ec7321d12a40227aae9e2bc6dca73f3cb21058999a1df9e193555a9dcc", - "sha256:03853ed82eeebbce3c2abfdbc98c96dc205f32a79627688ac9a27370ea61a49c", - "sha256:07d9e39b01743c3717745f4c530a6349eadbfa043c7577eef86c502c15df2c67", - "sha256:08e721811161356f97b4059a9ba7bafb23ea5ee2255402c42881c214e173c6b4", - "sha256:0c96c3b819b5c3e9e165495db84d41914d6894d55181d2d108cc1a69bfc9cce0", - "sha256:0ea948db76d31190bf08bd371623927ee1339d5f2a0b4b1b4a4439a65298703c", - "sha256:0f7eb884681e3938906ed0434f20c63046eacd0111c4ba96f27b76084cd679f5", - "sha256:12a6fff75f6bc66711b73a2f0addfc4c8c15a20e805146a02d147a318962c444", - "sha256:12d8baf840cc7889b37c7c770f478adea7adce3dcb3944d02ec87508e2dcf153", - "sha256:14265bfe1f09498b9d8ec91e9ec9fa52775edf90fcbde092b25f4a33d444fea9", - "sha256:16d971e29578a5e97d7117866d15889a4a07befe0e87e703ed63cd90cb348c01", - "sha256:177a0ba5f0211d488e295aaf82707237e331c24788d8d76c96c5a41594723217", - "sha256:1a87ca9d5df6fe460483d9a5bbf2b18f620cbed41b432e2bddb686228282d10b", - "sha256:1c2a768fdd44ee4a9339a9b0b130049139b8ce3c01d2ce09f67f5a68048d477c", - "sha256:1c2aed2e5e41f24ea8ef1590b8e848a79b56f3a5564a65ceec43c9d692dc7d8a", - "sha256:1dc8b0ea451d6e69735094606991f32867807881400f808a106ee1d963c46a83", - "sha256:1efde3cae86c8c273f1eb3b287be7d8499420cf2fe7585c41d370d3e790054a5", - "sha256:202389074300232baeb53ae2569a60901f7efadd4245cf3a3bf0617d60b439d7", - "sha256:203104ed3e428044fd943bc4bf45fa73c0730391f9621e37fe39ecf477b128cb", - "sha256:2257141f39fe65a3fdf38aeccae4b953e5f3b3324f4ff0daf9f15b8518666a2c", - "sha256:298930cec56029e05497a76988377cbd7457ba864beeea92ad7e844fe74cd1f1", - "sha256:2cd4a60d0e2fb04537162c62bbbb4182f53541fe0ede35cdf270a1c1e723cc42", - "sha256:2d6eb928e13016cea4f1f21d1e10c1cebd5a421bc57ddf5b1142ae3f86824fab", - "sha256:2fe249cb4651fd12605b7288b24751d8bfd46d35f12a20b1ba33dea122e690df", - "sha256:30b8d1d8c52a48c2c5690e152c169b673487a2a58de1ec7393196753063fcd5e", - "sha256:320ade88cfb846b8cd6b4ddf5ee9e80ee0c1f52401f2456b84ae1ae6a1a5f207", - "sha256:3534e7dcbdcf757da6b85a0bbf5b6868786d5982dd959b065e65481644817a18", - "sha256:36836d6ff945a00b88ba1e4572d721e60b5b8c98c155d465f56ad19d68f23734", - "sha256:38c0109396c4cfc574d502df99742a45c72c08eff0a36158b6f04000043dbf38", - "sha256:3946fa46a0cf3e4c8cb1cc52f56bb536310d34f25f01ca9b6c16afa767dab110", - "sha256:3bec022aec2c514d9cf199522a802bd007cd588ab17ab2525f20f9c34d067c18", - "sha256:3c9a494bc5ec77d43cea229c4f6db1e4d8fe7e1bbffa8b6f0f0032430ff8ab44", - "sha256:3dce51d0f5e7951f8bb4900c257dad282f49190fdbebecd4ba99bcc41fef404d", - "sha256:3dedcc22d73ec993f42055eff4fcfed9318d1eeb9a6606c55892a26964964e48", - "sha256:4042d5c8f957e15221d423ba781e85d553722fc4113f523f2feb7b188cc34c5e", - "sha256:481551899c856c704d58119b5025793fa6730adda3571971af568f66d2424bb5", - "sha256:4dc1e73c36828f982bfe79fadf5919923f8a6f4df2860804db9a98c48824ce8d", - "sha256:4e5163c14bffd570ef2affbfdd77bba66383890797df43dc8b4cc7d6f500bf53", - "sha256:511ef87c8aec0783e08ac18565a16d435372bc1ac25a91e6ac7f5ef2b0bff790", - "sha256:532bc9bf33a68613fd7d65e4b1c71a6a38d7d42604ecf239c77392e9b4e8998c", - "sha256:54523e136b8948060c0fa0bc7b1b50c32c186f2fceee897a495406bb6e311d2b", - "sha256:5649fd1c7bade02f320a462fdefd0b4bd3ce036065836d4f42e0de958038e116", - "sha256:56be790f86bfb2c98fb742ce566dfb4816e5a83384616ab59c49e0604d49c51d", - "sha256:5b77459df20e08151cd6f8b9ef8ef1f961ef73d85c21a555c7eed5b79410ec10", - "sha256:5ed6ab538499c8644b8a3e18debabcd7ce684f3fa91cf867521a7a0279cab2d6", - "sha256:6178f72c5508bfc5fd446a5905e698c6212932f25bcdd4b47a757a50605a90e2", - "sha256:6370e8686f662e6a3941ee48ed4742317cafbe5707e36406e9df792cdb535776", - "sha256:64f02c6841d7d83f832cd97ccf8eb8a906d06eb95d5276069175c696b024b60a", - "sha256:65bcd23054beab4d166035cabbc868a09c1a49d1efe458fe8e4361215df40265", - "sha256:66671f93accb62ed07da56613636f3641f1a12c13046ce91ffc923721f23c008", - "sha256:6696b7688f54f5af4462118f0bfa7c1621eeb87154f77fa04b9295ce7a8f2943", - "sha256:6785f414ae0f3c733c437e0f3929197934f526d19dfaa75e18fdb4f94c6fb374", - "sha256:67f6279d125ca0046a7fd386d01b311c6363844deac3e5b069b514ba3e63c246", - "sha256:6c114670c45346afedc0d947faf3c7f701051d2518b943679c8ff88befe14f8e", - "sha256:6e0d51f618228538a3e8f46bd246f87a6cd030565e015803691603f55e12afb5", - "sha256:6ed74185b2db44f41ef35fd1617c5888e59792da9bbc9190d6c7300617182616", - "sha256:708838739abf24b2ceb208d0e22403dd018faeef86ddac04319a62ae884c4f15", - "sha256:715479b9a2802ecac752a3b0efa2b0b60285cf962ee38414211abdfccc233b41", - "sha256:733784b6d6def852c814bce5f318d25da2ee65dd4839a0718641c696e09a2960", - "sha256:750e02e074872a3fad7f233b47734166440af3cdea0add3e95163110816d6752", - "sha256:752a45dc4a6934060b3b0dab47e04edc3326575f82be64bc4fc293914566503e", - "sha256:7579e913a5339fb8fa133f6bbcfd8e6749696206cf05acdbdca71a1b436d8e72", - "sha256:7641bb8895e77f921102f72833904dcd9901df5d6d72a2ab8f31d04b7e51e4e7", - "sha256:7804338df6fcc08105c7745f1502ba68d900f45fd770d5bdd5288ddccb8a42d8", - "sha256:80d04837f55fc81da168b98de4f4b797ef007fc8a79ab71c6ec9bc4dd662b15b", - "sha256:813c0e0132266c08eb87469a642cb30aaff57c5f426255419572aaeceeaa7bf4", - "sha256:82b271f5137d07749f7bf32f70b17ab6eaabedd297e75dce75081a24f76eb545", - "sha256:84c018e49c3bf790f9c2771c45e9313a08c2c2a6342b162cd650258b57817706", - "sha256:8751d2787c9131302398b11e6c8068053dcb55d5a8964e114b6e196cf16cb366", - "sha256:8778f0c7a52e56f75d12dae53ae320fae900a8b9b4164b981b9c5ce059cd1fcb", - "sha256:87fad7d9ba98c86bcb41b2dc8dbb326619be2562af1f8ff50776a39e55721c5a", - "sha256:8d828b6667a32a728a1ad1d93957cdf37489c57b97ae6c4de2860fa749b8fc1e", - "sha256:8e385e4267ab76874ae30db04c627faaaf0b509e1ccc11a95b3fc3e83f855c00", - "sha256:92a0a01ead5e668468e952e4238cccd7c537364eb7d851ab144ab6627dbbe12f", - "sha256:94e1885b270625a9a828c9793b4d52a64445299baa1fea5a173bf1d3dd9a1a5a", - "sha256:a180c5e59792af262bf263b21a3c49353f25945d8d9f70628e73de370d55e1e1", - "sha256:a277ab8928b9f299723bc1a2dabb1265911b1a76341f90a510368ca44ad9ab66", - "sha256:a5fe03b42827c13cdccd08e6c0247b6a6d4b5e3cdc53fd1749f5896adcdc2356", - "sha256:a6c5863edfbe888d9eff9c8b8087354e27618d9da76425c119293f11712a6319", - "sha256:a89c23ef8d2c6b27fd200a42aa4ac72786e7c60d40efdc76e6011260b6e949c4", - "sha256:adb2597b428735679446b46c8badf467b4ca5f5056aae4d51a19f9570301b1ad", - "sha256:ae196f021b5e7c78e918242d217db021ed2a6ace2bc6ae94c0fc596221c7f58d", - "sha256:ae89db9e5f98a11a4bf50407d4363e7b09b31e55bc117b4f7d80aab97ba009e5", - "sha256:aed52fea0513bac0ccde438c188c8a471c4e0f457c2dd20cdbf6ea7a450046c7", - "sha256:aef65cd602a6d0e0ff6f9930fcb1c8fec60dd2cfcb6facaf4bdb0e5873042db0", - "sha256:af21eb4409a119e365397b2adbaca4c9ccab56543a65d5dbd9f920d6ac29f686", - "sha256:b14b2d9dac08e28bb8046a1a0434b1750eb221c8f5b87a68f4fa11a6f97b5e34", - "sha256:bb6d88045545b26da47aa879dd4a89a71d1dce0f0e549b1abcb31dfe4a8eac49", - "sha256:bb8cc7534f51d9a017b93e3e85b260924f909601c3df002bcdb58ddb4dc41a5c", - "sha256:bc17a677b21b3502a21f66a8cc64f5bfad4df8a0b8434d661666f8ce90ac3af1", - "sha256:bd6c2a1c7573c64738d716488d2cdd3c00e340e4835707d8fdb8dc1a66ef164e", - "sha256:bd9b23791fe793e4968dba0c447e12f78e425c59fc0e3b97f6450f4781f3ee60", - "sha256:c03a41a8784091e67a39648f70c5f97b5b6a37f216896d44d2cdcb82615339a0", - "sha256:c0f081d69a6e58272819b70288d3221a6ee64b98df852631c80f293514d3b274", - "sha256:c35abb8bfff0185efac5878da64c45dafd2b37fb0383add1be155a763c1f083d", - "sha256:c36c333c39be2dbca264d7803333c896ab8fa7d4d6f0ab7edb7dfd7aea6e98c0", - "sha256:c45e9440fb78f8ddabcf714b68f936737a121355bf59f3907f4e17721b9d1aae", - "sha256:c593052c465475e64bbfe5dbd81680f64a67fdc752c56d7a0ae205dc8aeefe0f", - "sha256:cdd68a1fb318e290a2077696b7eb7a21a49163c455979c639bf5a5dcdc46617d", - "sha256:ce3412fbe1e31eb81ea42f4169ed94861c56e643189e1e75f0041f3fe7020abe", - "sha256:cf1493cd8607bec4d8a7b9b004e699fcf8f9103a9284cc94962cb73d20f9d4a3", - "sha256:cf29836da5119f3c8a8a70667b0ef5fdca3bb12f80fd06487cfa575b3909b393", - "sha256:d4a48e5b3c2a489fae013b7589308a40146ee081f6f509e047e0e096084ceca1", - "sha256:d560742f3c0d62afaccf9f41fe485ed69bd7661a241f86a3ef0f0fb8b1a397af", - "sha256:d6038d37043bced98a66e68d3aa2b6a35505dc01328cd65217cefe82f25def44", - "sha256:d61f00a0869d77422d9b2aba989e2d24afa6ffd552af442e0e58de4f35ea6d00", - "sha256:d635aab80466bc95771bb78d5370e74d36d1fe31467b6b29b8b57b2a3cd7d22c", - "sha256:dca4bbc466a95ba9c0234ef56d7dd9509f63da22274589ebd4ed7f1f4d4c54e3", - "sha256:dd915403e231e6b1809fe9b6d9fc55cf8fb5e02765ac625d9cd623342a7905d7", - "sha256:e044c39e41b92c845bc815e5ae4230804e8e7bc29e399b0437d64222d92809dd", - "sha256:e060d01aec0a910bdccb8be71faf34e7799ce36950f8294c8bf612cba65a2c9e", - "sha256:e1421b502d83040e6d7fb2fb18dff63957f720da3d77b2fbd3187ceb63755d7b", - "sha256:e17b8d5d6a8c47c85e68ca8379def1303fd360c3e22093a807cd34a71cd082b8", - "sha256:e5f4d355f0a2b1a31bc3edec6795b46324349c9cb25eed068049e4f472fb4259", - "sha256:e712b419df8ba5e42b226c510472b37bd57b38e897d3eca5e8cfd410a29fa859", - "sha256:e74327fb75de8986940def6e8dee4f127cc9752bee7355bb323cc5b2659b6d46", - "sha256:e80c8378d8f3d83cd3164da1ad2df9e37a666cdde7b1cb2298ed0b558064be30", - "sha256:e8ac484bf18ce6975760921bb6148041faa8fef0547200386ea0b52b5d27bf7b", - "sha256:eca9705049ad3c7345d574e3510665cb2cf844c2f2dcfe675332677f081cbd46", - "sha256:ed065083d0898c9d5b4bbec7b026fd755ff7454e6e8b73a67f8c744b13986e24", - "sha256:edac0f1ab77644605be2cbba52e6b7f630731fc42b34cb0f634be1a6eface56a", - "sha256:effc3f449787117233702311a1b7d8f59cba9ced946ba727bdc329ec69028e24", - "sha256:f22dec1690b584cea26fade98b2435c132c1b5f68e39f5a0b7627cd7ae31f1dc", - "sha256:f495a1652cf3fbab2eb0639776dad966c2fb874d79d87ca07f9d5f059b8bd215", - "sha256:f496c9c3cc02230093d8330875c4c3cdfc3b73612a5fd921c65d39cbcef08063", - "sha256:f59099f9b66f0d7145115e6f80dd8b1d847176df89b234a5a6b3f00437aa0832", - "sha256:f59ad4c0e8f6bba240a9bb85504faa1ab438237199d4cce5f622761507b8f6a6", - "sha256:fbccdc05410c9ee21bbf16a35f4c1d16123dcdeb8a1d38f33654fa21d0234f79", - "sha256:fea24543955a6a729c45a73fe90e08c743f0b3334bbf3201e6c4bc1b0c7fa464" - ], - "markers": "python_version >= '3.7'", - "version": "==3.4.7" - }, - "click": { - "hashes": [ - "sha256:398329ad4837b2ff7cbe1dd166a4c0f8900c3ca3a218de04466f38f6497f18a2", - "sha256:a2bf429bb3033c89fa4936ffb35d5cb471e3719e1f3c8a7c3fff0b8314305613" - ], - "markers": "python_version >= '3.10'", - "version": "==8.3.3" - }, - "cryptography": { - "hashes": [ - "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": "==47.0.0" - }, - "esptool": { - "hashes": [ - "sha256:9c355b7d6331cc92979cc710ae5c41f59830d1ea29ec24c467c6005a092c06d6" - ], - "index": "pypi", - "version": "==5.2.0" - }, - "h11": { - "hashes": [ - "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", - "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86" - ], - "markers": "python_version >= '3.8'", - "version": "==0.16.0" - }, - "idna": { - "hashes": [ - "sha256:585ea8fe5d69b9181ec1afba340451fba6ba764af97026f92a91d4eef164a242", - "sha256:892ea0cde124a99ce773decba204c5552b69c3c67ffd5f232eb7696135bc8bb3" - ], - "markers": "python_version >= '3.8'", - "version": "==3.13" - }, - "intelhex": { - "hashes": [ - "sha256:87cc5225657524ec6361354be928adfd56bcf2a3dcc646c40f8f094c39c07db4", - "sha256:892b7361a719f4945237da8ccf754e9513db32f5628852785aea108dcd250093" - ], - "version": "==2.3.0" - }, - "markdown-it-py": { - "hashes": [ - "sha256:87327c59b172c5011896038353a81343b6754500a08cd7a4973bb48c6d578147", - "sha256:cb0a2b4aa34f932c007117b194e945bd74e0ec24133ceb5bac59009cda1cb9f3" - ], - "markers": "python_version >= '3.10'", - "version": "==4.0.0" - }, - "mdurl": { - "hashes": [ - "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", - "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba" - ], - "markers": "python_version >= '3.7'", - "version": "==0.1.2" - }, - "microdot": { - "hashes": [ - "sha256:3ba8bab39ae52bca08ee7024dfc71afb7cff089f0b6611d2a1f617abfcee749c", - "sha256:d56824f4510e628dac711c86121957894ceaf833298e4d25f06c29d2b19a1721" - ], - "index": "pypi", - "version": "==2.6.1" - }, - "mpremote": { - "hashes": [ - "sha256:2df2a50f3c8098cae8c732dbf2541e7e58185e7896513b45d05196901e049334", - "sha256:fdb5626be83dff4e53c0184f8950814cb519b524dba7f1f8b1668aa477257a31" - ], - "index": "pypi", - "version": "==1.28.0" - }, - "outcome": { - "hashes": [ - "sha256:9dcf02e65f2971b80047b377468e72a268e15c0af3cf1238e6ff14f7f91143b8", - "sha256:e771c5ce06d1415e356078d3bdd68523f284b4ce5419828922b6871e65eda82b" - ], - "markers": "python_version >= '3.7'", - "version": "==1.3.0.post0" - }, - "platformdirs": { - "hashes": [ - "sha256:3bfa75b0ad0db84096ae777218481852c0ebc6c727b3168c1b9e0118e458cf0a", - "sha256:e61adb1d5e5cb3441b4b7710bea7e4c12250ca49439228cc1021c00dcfac0917" - ], - "markers": "python_version >= '3.10'", - "version": "==4.9.6" - }, - "pycparser": { - "hashes": [ - "sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29", - "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992" - ], - "markers": "implementation_name != 'PyPy'", - "version": "==3.0" - }, - "pygments": { - "hashes": [ - "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", - "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176" - ], - "markers": "python_version >= '3.9'", - "version": "==2.20.0" - }, - "pyjwt": { - "hashes": [ - "sha256:28ca37c070cad8ba8cd9790cd940535d40274d22f80ab87f3ac6a713e6e8454c", - "sha256:c74a7a2adf861c04d002db713dd85f84beb242228e671280bf709d765b03672b" - ], - "index": "pypi", - "version": "==2.12.1" - }, - "pyserial": { - "hashes": [ - "sha256:3c77e014170dfffbd816e6ffc205e9842efb10be9f58ec16d3e8675b4925cddb", - "sha256:c4451db6ba391ca6ca299fb3ec7bae67a5c55dde170964c7a14ceefec02f2cf0" - ], - "index": "pypi", - "version": "==3.5" - }, - "pysocks": { - "hashes": [ - "sha256:08e69f092cc6dbe92a0fdd16eeb9b9ffbc13cadfe5ca4c7bd92ffb078b293299", - "sha256:2725bd0a9925919b9b51739eea5f9e2bae91e83288108a9ad338b2e3a4435ee5", - "sha256:3f8804571ebe159c380ac6de37643bb4685970655d3bba243530d6558b799aa0" - ], - "version": "==1.7.1" - }, - "python-dotenv": { - "hashes": [ - "sha256:1d8214789a24de455a8b8bd8ae6fe3c6b69a5e3d64aa8a8e5d68e694bbcb285a", - "sha256:2c371a91fbd7ba082c2c1dc1f8bf89ca22564a087c2c287cd9b662adde799cf3" - ], - "markers": "python_version >= '3.10'", - "version": "==1.2.2" - }, - "pyyaml": { - "hashes": [ - "sha256:00c4bdeba853cc34e7dd471f16b4114f4162dc03e6b7afcc2128711f0eca823c", - "sha256:0150219816b6a1fa26fb4699fb7daa9caf09eb1999f3b70fb6e786805e80375a", - "sha256:02893d100e99e03eda1c8fd5c441d8c60103fd175728e23e431db1b589cf5ab3", - "sha256:02ea2dfa234451bbb8772601d7b8e426c2bfa197136796224e50e35a78777956", - "sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6", - "sha256:10892704fc220243f5305762e276552a0395f7beb4dbf9b14ec8fd43b57f126c", - "sha256:16249ee61e95f858e83976573de0f5b2893b3677ba71c9dd36b9cf8be9ac6d65", - "sha256:1d37d57ad971609cf3c53ba6a7e365e40660e3be0e5175fa9f2365a379d6095a", - "sha256:1ebe39cb5fc479422b83de611d14e2c0d3bb2a18bbcb01f229ab3cfbd8fee7a0", - "sha256:214ed4befebe12df36bcc8bc2b64b396ca31be9304b8f59e25c11cf94a4c033b", - "sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1", - "sha256:22ba7cfcad58ef3ecddc7ed1db3409af68d023b7f940da23c6c2a1890976eda6", - "sha256:27c0abcb4a5dac13684a37f76e701e054692a9b2d3064b70f5e4eb54810553d7", - "sha256:28c8d926f98f432f88adc23edf2e6d4921ac26fb084b028c733d01868d19007e", - "sha256:2e71d11abed7344e42a8849600193d15b6def118602c4c176f748e4583246007", - "sha256:34d5fcd24b8445fadc33f9cf348c1047101756fd760b4dacb5c3e99755703310", - "sha256:37503bfbfc9d2c40b344d06b2199cf0e96e97957ab1c1b546fd4f87e53e5d3e4", - "sha256:3c5677e12444c15717b902a5798264fa7909e41153cdf9ef7ad571b704a63dd9", - "sha256:3ff07ec89bae51176c0549bc4c63aa6202991da2d9a6129d7aef7f1407d3f295", - "sha256:41715c910c881bc081f1e8872880d3c650acf13dfa8214bad49ed4cede7c34ea", - "sha256:418cf3f2111bc80e0933b2cd8cd04f286338bb88bdc7bc8e6dd775ebde60b5e0", - "sha256:44edc647873928551a01e7a563d7452ccdebee747728c1080d881d68af7b997e", - "sha256:4a2e8cebe2ff6ab7d1050ecd59c25d4c8bd7e6f400f5f82b96557ac0abafd0ac", - "sha256:4ad1906908f2f5ae4e5a8ddfce73c320c2a1429ec52eafd27138b7f1cbe341c9", - "sha256:501a031947e3a9025ed4405a168e6ef5ae3126c59f90ce0cd6f2bfc477be31b7", - "sha256:5190d403f121660ce8d1d2c1bb2ef1bd05b5f68533fc5c2ea899bd15f4399b35", - "sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb", - "sha256:5cf4e27da7e3fbed4d6c3d8e797387aaad68102272f8f9752883bc32d61cb87b", - "sha256:5e0b74767e5f8c593e8c9b5912019159ed0533c70051e9cce3e8b6aa699fcd69", - "sha256:5ed875a24292240029e4483f9d4a4b8a1ae08843b9c54f43fcc11e404532a8a5", - "sha256:5fcd34e47f6e0b794d17de1b4ff496c00986e1c83f7ab2fb8fcfe9616ff7477b", - "sha256:5fdec68f91a0c6739b380c83b951e2c72ac0197ace422360e6d5a959d8d97b2c", - "sha256:6344df0d5755a2c9a276d4473ae6b90647e216ab4757f8426893b5dd2ac3f369", - "sha256:64386e5e707d03a7e172c0701abfb7e10f0fb753ee1d773128192742712a98fd", - "sha256:652cb6edd41e718550aad172851962662ff2681490a8a711af6a4d288dd96824", - "sha256:66291b10affd76d76f54fad28e22e51719ef9ba22b29e1d7d03d6777a9174198", - "sha256:66e1674c3ef6f541c35191caae2d429b967b99e02040f5ba928632d9a7f0f065", - "sha256:6adc77889b628398debc7b65c073bcb99c4a0237b248cacaf3fe8a557563ef6c", - "sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c", - "sha256:7c6610def4f163542a622a73fb39f534f8c101d690126992300bf3207eab9764", - "sha256:7f047e29dcae44602496db43be01ad42fc6f1cc0d8cd6c83d342306c32270196", - "sha256:8098f252adfa6c80ab48096053f512f2321f0b998f98150cea9bd23d83e1467b", - "sha256:850774a7879607d3a6f50d36d04f00ee69e7fc816450e5f7e58d7f17f1ae5c00", - "sha256:8d1fab6bb153a416f9aeb4b8763bc0f22a5586065f86f7664fc23339fc1c1fac", - "sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8", - "sha256:8dc52c23056b9ddd46818a57b78404882310fb473d63f17b07d5c40421e47f8e", - "sha256:9149cad251584d5fb4981be1ecde53a1ca46c891a79788c0df828d2f166bda28", - "sha256:93dda82c9c22deb0a405ea4dc5f2d0cda384168e466364dec6255b293923b2f3", - "sha256:96b533f0e99f6579b3d4d4995707cf36df9100d67e0c8303a0c55b27b5f99bc5", - "sha256:9c57bb8c96f6d1808c030b1687b9b5fb476abaa47f0db9c0101f5e9f394e97f4", - "sha256:9c7708761fccb9397fe64bbc0395abcae8c4bf7b0eac081e12b809bf47700d0b", - "sha256:9f3bfb4965eb874431221a3ff3fdcddc7e74e3b07799e0e84ca4a0f867d449bf", - "sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5", - "sha256:a80cb027f6b349846a3bf6d73b5e95e782175e52f22108cfa17876aaeff93702", - "sha256:b30236e45cf30d2b8e7b3e85881719e98507abed1011bf463a8fa23e9c3e98a8", - "sha256:b3bc83488de33889877a0f2543ade9f70c67d66d9ebb4ac959502e12de895788", - "sha256:b865addae83924361678b652338317d1bd7e79b1f4596f96b96c77a5a34b34da", - "sha256:b8bb0864c5a28024fac8a632c443c87c5aa6f215c0b126c449ae1a150412f31d", - "sha256:ba1cc08a7ccde2d2ec775841541641e4548226580ab850948cbfda66a1befcdc", - "sha256:bdb2c67c6c1390b63c6ff89f210c8fd09d9a1217a465701eac7316313c915e4c", - "sha256:c1ff362665ae507275af2853520967820d9124984e0f7466736aea23d8611fba", - "sha256:c2514fceb77bc5e7a2f7adfaa1feb2fb311607c9cb518dbc378688ec73d8292f", - "sha256:c3355370a2c156cffb25e876646f149d5d68f5e0a3ce86a5084dd0b64a994917", - "sha256:c458b6d084f9b935061bc36216e8a69a7e293a2f1e68bf956dcd9e6cbcd143f5", - "sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26", - "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", - "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", - "sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be", - "sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c", - "sha256:efd7b85f94a6f21e4932043973a7ba2613b059c4a000551892ac9f1d11f5baf3", - "sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6", - "sha256:fa160448684b4e94d80416c0fa4aac48967a969efe22931448d853ada8baf926", - "sha256:fc09d0aa354569bc501d4e787133afc08552722d3ab34836a80547331bb5d4a0" - ], - "markers": "python_version >= '3.8'", - "version": "==6.0.3" - }, - "reedsolo": { - "hashes": [ - "sha256:2b6a3e402a1ee3e1eea3f932f81e6c0b7bbc615588074dca1dbbcdeb055002bd", - "sha256:c1359f02742751afe0f1c0de9f0772cc113835aa2855d2db420ea24393c87732" - ], - "version": "==1.7.0" - }, - "requests": { - "hashes": [ - "sha256:18817f8c57c6263968bc123d237e3b8b08ac046f5456bd1e307ee8f4250d3517", - "sha256:4e6d1ef462f3626a1f0a0a9c42dd93c63bad33f9f1c1937509b8c5c8718ab56a" - ], - "index": "pypi", - "version": "==2.33.1" - }, - "rich": { - "hashes": [ - "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", - "sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36" - ], - "markers": "python_full_version >= '3.9.0'", - "version": "==15.0.0" - }, - "rich-click": { - "hashes": [ - "sha256:022997c1e30731995bdbc8ec2f82819340d42543237f033a003c7b1f843fc5dc", - "sha256:2f99120fca78f536e07b114d3b60333bc4bb2a0969053b1250869bcdc1b5351b" - ], - "markers": "python_version >= '3.8'", - "version": "==1.9.7" - }, - "selenium": { - "hashes": [ - "sha256:4f97639055dcfa9eadf8ccf549ba7b0e49c655d4e2bde19b9a44e916b754e769", - "sha256:bada5c08a989f812728a4b5bea884d8e91894e939a441cc3a025201ce718581e" - ], - "index": "pypi", - "version": "==4.43.0" - }, - "sniffio": { - "hashes": [ - "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", - "sha256:f4324edc670a0f49750a81b895f35c3adb843cca46f0530f79fc1babb23789dc" - ], - "markers": "python_version >= '3.7'", - "version": "==1.3.1" - }, - "sortedcontainers": { - "hashes": [ - "sha256:25caa5a06cc30b6b83d11423433f65d1f9d76c4c6a0c90e3379eaa43b9bfdb88", - "sha256:a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0" - ], - "version": "==2.4.0" - }, - "tibs": { - "hashes": [ - "sha256:01ea5258bdf942d21560dc07d532082cd04f07cfef65fedd58ae84f7d0d2562a", - "sha256:0a7ce857ef05c59dc61abadc31c4b9b1e3c62f9e5fb29217988c308936aea71e", - "sha256:130bc68ff500fc8185677df7a97350b5d5339e6ba7e325bc3031337f6424ede7", - "sha256:173dfbecb2309edd9771f453580c88cf251e775613461566b23dbd756b3d54cb", - "sha256:1906729038b85c3b4c040aa28a456d85bc976d0c5007177350eb73374ffa0fd0", - "sha256:1b56583db148e5094d781c3d746815dbcbb6378c6f813c8ce291efd4ab21da8b", - "sha256:1d5521cc6768bfa6282a0c591ba06b079ab91b5c7d5696925ad2abac59779a54", - "sha256:1f95d5db62960205a1e9eba73ce67dc14e7366ae080cd4e5b6f005ebd90faf02", - "sha256:29480bf03e3372a5f9cc59ea0541f76f8efd696d4f0d214715e94247c342a037", - "sha256:2a618de62004d9217d2d2ab0f7f9bbdd098c12642dc01f07b3fb00f0b5f3131a", - "sha256:42725200f1b02687ed6e6a1c01e0ec150dc829d21d901ffc74cc0ac4d821f57f", - "sha256:477608f9b87e24a22ab6d50b81da04a5cb59bfa49598ff7ec5165035a18fb392", - "sha256:4b7510235379368b7523f624d46e0680f3706e3a3965877a6583cdcb598b8bac", - "sha256:501728d096e10d9a165aa526743d47418a6bbfd7b084fa47ecb22be7641d3edb", - "sha256:63255749f937c5e6fedcc7d54e7bd359aef711017e6855f373b0510a14ee2215", - "sha256:6a9feed5931b881809a950eca0e01e757113e2383a2af06a3e6982f110c869e2", - "sha256:76746f01b3db9dbd802f5e615f11f68df7a29ecef521b082dca53f3fa7d0084f", - "sha256:77103a9f1af72ac4cf5006828d0fb21578d19ce55fd990e9a1c8e46fd549561f", - "sha256:7d6592ed93c6748acd39df484c1ee24d40ee247c2a20ca38ba03363506fd24f3", - "sha256:847709c108800ad6a45efaf9a040628278956938a4897f7427a2587013dc3b98", - "sha256:859f05315ffb307d3474c505d694f3a547f00730a024c982f5f60316a5505b3c", - "sha256:a61d36155f8ab8642e1b6744e13822f72050fc7ec4f86ec6965295afa04949e2", - "sha256:a883ca13a922a66b2c1326a9c188123a574741a72510a4bf52fd6f97db191e44", - "sha256:ac0aa2aae38f7325c91c261ce1d18f769c4c7033c98d6ea3ea5534585cf16452", - "sha256:ace018a057459e3dccd06a4aae1c5c8cd57e352b263dcef534ae39bf3e03b5cf", - "sha256:ad61df93b50f875b277ab736c5d37b6bce56f9abce489a22f4e02d9daa2966e3", - "sha256:b9535dc7b7484904a58b51bd8e64da7efbf1d8466ff7e84ed1d78f4ddc561c99", - "sha256:d4f3ff613d486650816bc5516760c0382a2cc0ca8aeddd8914d011bc3b81d9a2", - "sha256:e13b9c7ff2604b0146772025e1ac6f85c8c625bf6ac73736ff671eaf357dda41", - "sha256:f5eea45851c960628a2bd29847765d55e19a687c5374456ad2c8cf6410eb1efa", - "sha256:f70bd250769381c73110d6f24feaf8b6fcd44f680b3cb28a20ea06db3d04fb6f" - ], - "markers": "python_version >= '3.8'", - "version": "==0.5.7" - }, - "trio": { - "hashes": [ - "sha256:3bd5d87f781d9b0192d592aef28691f8951d6c2e41b7e1da4c25cde6c180ae9b", - "sha256:a29b92b73f09d4b48ed249acd91073281a7f1063f09caba5dc70465b5c7aa970" - ], - "markers": "python_version >= '3.10'", - "version": "==0.33.0" - }, - "trio-websocket": { - "hashes": [ - "sha256:22c72c436f3d1e264d0910a3951934798dcc5b00ae56fc4ee079d46c7cf20fae", - "sha256:df605665f1db533f4a386c94525870851096a223adcb97f72a07e8b4beba45b6" - ], - "markers": "python_version >= '3.8'", - "version": "==0.12.2" - }, - "typing-extensions": { - "hashes": [ - "sha256:0cea48d173cc12fa28ecabc3b837ea3cf6f38c6d1136f85cbaaf598984861466", - "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548" - ], - "markers": "python_version >= '3.9'", - "version": "==4.15.0" - }, - "urllib3": { - "extras": [], - "hashes": [ - "sha256:1b62b6884944a57dbe321509ab94fd4d3b307075e0c2eae991ac71ee15ad38ed", - "sha256:bf272323e553dfb2e87d9bfd225ca7b0f467b919d7bbd355436d3fd37cb0acd4" - ], - "markers": "python_version >= '3.9'", - "version": "==2.6.3" - }, - "watchfiles": { - "hashes": [ - "sha256:00485f441d183717038ed2e887a7c868154f216877653121068107b227a2f64c", - "sha256:03fa0f5237118a0c5e496185cafa92878568b652a2e9a9382a5151b1a0380a43", - "sha256:04e78dd0b6352db95507fd8cb46f39d185cf8c74e4cf1e4fbad1d3df96faf510", - "sha256:059098c3a429f62fc98e8ec62b982230ef2c8df68c79e826e37b895bc359a9c0", - "sha256:08af70fd77eee58549cd69c25055dc344f918d992ff626068242259f98d598a2", - "sha256:0b495de0bb386df6a12b18335a0285dda90260f51bdb505503c02bcd1ce27a8b", - "sha256:130e4876309e8686a5e37dba7d5e9bc77e6ed908266996ca26572437a5271e18", - "sha256:14e0b1fe858430fc0251737ef3824c54027bedb8c37c38114488b8e131cf8219", - "sha256:17ef139237dfced9da49fb7f2232c86ca9421f666d78c264c7ffca6601d154c3", - "sha256:1a0bb430adb19ef49389e1ad368450193a90038b5b752f4ac089ec6942c4dff4", - "sha256:1db5d7ae38ff20153d542460752ff397fcf5c96090c1230803713cf3147a6803", - "sha256:28475ddbde92df1874b6c5c8aaeb24ad5be47a11f87cde5a28ef3835932e3e94", - "sha256:2edc3553362b1c38d9f06242416a5d8e9fe235c204a4072e988ce2e5bb1f69f6", - "sha256:30f7da3fb3f2844259cba4720c3fc7138eb0f7b659c38f3bfa65084c7fc7abce", - "sha256:311ff15a0bae3714ffb603e6ba6dbfba4065ab60865d15a6ec544133bdb21099", - "sha256:319b27255aacd9923b8a276bb14d21a5f7ff82564c744235fc5eae58d95422ae", - "sha256:35c53bd62a0b885bf653ebf6b700d1bf05debb78ad9292cf2a942b23513dc4c4", - "sha256:36193ed342f5b9842edd3532729a2ad55c4160ffcfa3700e0d54be496b70dd43", - "sha256:39574d6370c4579d7f5d0ad940ce5b20db0e4117444e39b6d8f99db5676c52fd", - "sha256:399600947b170270e80134ac854e21b3ccdefa11a9529a3decc1327088180f10", - "sha256:3a476189be23c3686bc2f4321dd501cb329c0a0469e77b7b534ee10129ae6374", - "sha256:3ad9fe1dae4ab4212d8c91e80b832425e24f421703b5a42ef2e4a1e215aff051", - "sha256:3bc570d6c01c206c46deb6e935a260be44f186a2f05179f52f7fcd2be086a94d", - "sha256:3dbd8cbadd46984f802f6d479b7e3afa86c42d13e8f0f322d669d79722c8ec34", - "sha256:3e6f39af2eab0118338902798b5aa6664f46ff66bc0280de76fca67a7f262a49", - "sha256:3f53fa183d53a1d7a8852277c92b967ae99c2d4dcee2bfacff8868e6e30b15f7", - "sha256:3f6d37644155fb5beca5378feb8c1708d5783145f2a0f1c4d5a061a210254844", - "sha256:3f7eb7da0eb23aa2ba036d4f616d46906013a68caf61b7fdbe42fc8b25132e77", - "sha256:3fa0b59c92278b5a7800d3ee7733da9d096d4aabcfabb9a928918bd276ef9b9b", - "sha256:421e29339983e1bebc281fab40d812742268ad057db4aee8c4d2bce0af43b741", - "sha256:4b943d3668d61cfa528eb949577479d3b077fd25fb83c641235437bc0b5bc60e", - "sha256:526e86aced14a65a5b0ec50827c745597c782ff46b571dbfe46192ab9e0b3c33", - "sha256:52e06553899e11e8074503c8e716d574adeeb7e68913115c4b3653c53f9bae42", - "sha256:544364b2b51a9b0c7000a4b4b02f90e9423d97fbbf7e06689236443ebcad81ab", - "sha256:5524298e3827105b61951a29c3512deb9578586abf3a7c5da4a8069df247cccc", - "sha256:55c7475190662e202c08c6c0f4d9e345a29367438cf8e8037f3155e10a88d5a5", - "sha256:563b116874a9a7ce6f96f87cd0b94f7faf92d08d0021e837796f0a14318ef8da", - "sha256:57ca5281a8b5e27593cb7d82c2ac927ad88a96ed406aa446f6344e4328208e9e", - "sha256:5c85794a4cfa094714fb9c08d4a218375b2b95b8ed1666e8677c349906246c05", - "sha256:5f3bde70f157f84ece3765b42b4a52c6ac1a50334903c6eaf765362f6ccca88a", - "sha256:5f3f58818dc0b07f7d9aa7fe9eb1037aecb9700e63e1f6acfed13e9fef648f5d", - "sha256:5fac835b4ab3c6487b5dbad78c4b3724e26bcc468e886f8ba8cc4306f68f6701", - "sha256:620bae625f4cb18427b1bb1a2d9426dc0dd5a5ba74c7c2cdb9de405f7b129863", - "sha256:672b8adf25b1a0d35c96b5888b7b18699d27d4194bac8beeae75be4b7a3fc9b2", - "sha256:6aae418a8b323732fa89721d86f39ec8f092fc2af67f4217a2b07fd3e93c6101", - "sha256:6c3631058c37e4a0ec440bf583bc53cdbd13e5661bb6f465bc1d88ee9a0a4d02", - "sha256:6c9c9262f454d1c4d8aaa7050121eb4f3aea197360553699520767daebf2180b", - "sha256:6e43d39a741e972bab5d8100b5cdacf69db64e34eb19b6e9af162bccf63c5cc6", - "sha256:7365b92c2e69ee952902e8f70f3ba6360d0d596d9299d55d7d386df84b6941fb", - "sha256:743185e7372b7bc7c389e1badcc606931a827112fbbd37f14c537320fca08620", - "sha256:74472234c8370669850e1c312490f6026d132ca2d396abfad8830b4f1c096957", - "sha256:74d5012b7630714b66be7b7b7a78855ef7ad58e8650c73afc4c076a1f480a8d6", - "sha256:77a13aea58bc2b90173bc69f2a90de8e282648939a00a602e1dc4ee23e26b66d", - "sha256:79ff6c6eadf2e3fc0d7786331362e6ef1e51125892c75f1004bd6b52155fb956", - "sha256:831a62658609f0e5c64178211c942ace999517f5770fe9436be4c2faeba0c0ef", - "sha256:836398932192dae4146c8f6f737d74baeac8b70ce14831a239bdb1ca882fc261", - "sha256:842178b126593addc05acf6fce960d28bc5fae7afbaa2c6c1b3a7b9460e5be02", - "sha256:8526e8f916bb5b9a0a777c8317c23ce65de259422bba5b31325a6fa6029d33af", - "sha256:859e43a1951717cc8de7f4c77674a6d389b106361585951d9e69572823f311d9", - "sha256:88863fbbc1a7312972f1c511f202eb30866370ebb8493aef2812b9ff28156a21", - "sha256:89eef07eee5e9d1fda06e38822ad167a044153457e6fd997f8a858ab7564a336", - "sha256:8c89f9f2f740a6b7dcc753140dd5e1ab9215966f7a3530d0c0705c83b401bd7d", - "sha256:8c91ed27800188c2ae96d16e3149f199d62f86c7af5f5f4d2c61a3ed8cd3666c", - "sha256:8ca65483439f9c791897f7db49202301deb6e15fe9f8fe2fed555bf986d10c31", - "sha256:8fbe85cb3201c7d380d3d0b90e63d520f15d6afe217165d7f98c9c649654db81", - "sha256:91d4c9a823a8c987cce8fa2690923b069966dabb196dd8d137ea2cede885fde9", - "sha256:9bb9f66367023ae783551042d31b1d7fd422e8289eedd91f26754a66f44d5cff", - "sha256:a173cb5c16c4f40ab19cecf48a534c409f7ea983ab8fed0741304a1c0a31b3f2", - "sha256:a36d8efe0f290835fd0f33da35042a1bb5dc0e83cbc092dcf69bce442579e88e", - "sha256:a55f3e9e493158d7bfdb60a1165035f1cf7d320914e7b7ea83fe22c6023b58fc", - "sha256:a625815d4a2bdca61953dbba5a39d60164451ef34c88d751f6c368c3ea73d404", - "sha256:a916a2932da8f8ab582f242c065f5c81bed3462849ca79ee357dd9551b0e9b01", - "sha256:ac3cc5759570cd02662b15fbcd9d917f7ecd47efe0d6b40474eafd246f91ea18", - "sha256:acb08650863767cbc58bca4813b92df4d6c648459dcaa3d4155681962b2aa2d3", - "sha256:aebfd0861a83e6c3d1110b78ad54704486555246e542be3e2bb94195eabb2606", - "sha256:afaeff7696e0ad9f02cbb8f56365ff4686ab205fcf9c4c5b6fdfaaa16549dd04", - "sha256:b27cf2eb1dda37b2089e3907d8ea92922b673c0c427886d4edc6b94d8dfe5db3", - "sha256:b2cd9e04277e756a2e2d2543d65d1e2166d6fd4c9b183f8808634fda23f17b14", - "sha256:b9c4702f29ca48e023ffd9b7ff6b822acdf47cb1ff44cb490a3f1d5ec8987e9c", - "sha256:bbe1ef33d45bc71cf21364df962af171f96ecaeca06bd9e3d0b583efb12aec82", - "sha256:bd404be08018c37350f0d6e34676bd1e2889990117a2b90070b3007f172d0610", - "sha256:bf0a91bfb5574a2f7fc223cf95eeea79abfefa404bf1ea5e339c0c1560ae99a0", - "sha256:bfb5862016acc9b869bb57284e6cb35fdf8e22fe59f7548858e2f971d045f150", - "sha256:bfff9740c69c0e4ed32416f013f3c45e2ae42ccedd1167ef2d805c000b6c71a5", - "sha256:c1f5210f1b8fc91ead1283c6fd89f70e76fb07283ec738056cf34d51e9c1d62c", - "sha256:c2047d0b6cea13b3316bdbafbfa0c4228ae593d995030fda39089d36e64fc03a", - "sha256:c22c776292a23bfc7237a98f791b9ad3144b02116ff10d820829ce62dff46d0b", - "sha256:c755367e51db90e75b19454b680903631d41f9e3607fbd941d296a020c2d752d", - "sha256:c882d69f6903ef6092bedfb7be973d9319940d56b8427ab9187d1ecd73438a70", - "sha256:cb467c999c2eff23a6417e58d75e5828716f42ed8289fe6b77a7e5a91036ca70", - "sha256:cdab464fee731e0884c35ae3588514a9bcf718d0e2c82169c1c4a85cc19c3c7f", - "sha256:ce19e06cbda693e9e7686358af9cd6f5d61312ab8b00488bc36f5aabbaf77e24", - "sha256:ce70f96a46b894b36eba678f153f052967a0d06d5b5a19b336ab0dbbd029f73e", - "sha256:cf57a27fb986c6243d2ee78392c503826056ffe0287e8794503b10fb51b881be", - "sha256:d1715143123baeeaeadec0528bb7441103979a1d5f6fd0e1f915383fea7ea6d5", - "sha256:d6ff426a7cb54f310d51bfe83fe9f2bbe40d540c741dc974ebc30e6aa238f52e", - "sha256:d7e7067c98040d646982daa1f37a33d3544138ea155536c2e0e63e07ff8a7e0f", - "sha256:db476ab59b6765134de1d4fe96a1a9c96ddf091683599be0f26147ea1b2e4b88", - "sha256:dcc5c24523771db3a294c77d94771abcfcb82a0e0ee8efd910c37c59ec1b31bb", - "sha256:de6da501c883f58ad50db3a32ad397b09ad29865b5f26f64c24d3e3281685849", - "sha256:e84087b432b6ac94778de547e08611266f1f8ffad28c0ee4c82e028b0fc5966d", - "sha256:eef58232d32daf2ac67f42dea51a2c80f0d03379075d44a587051e63cc2e368c", - "sha256:f096076119da54a6080e8920cbdaac3dbee667eb91dcc5e5b78840b87415bd44", - "sha256:f0ab1c1af0cb38e3f598244c17919fb1a84d1629cc08355b0074b6d7f53138ac", - "sha256:f27db948078f3823a6bb3b465180db8ebecf26dd5dae6f6180bd87383b6b4428", - "sha256:f537afb3276d12814082a2e9b242bdcf416c2e8fd9f799a737990a1dbe906e5b", - "sha256:f57b396167a2565a4e8b5e56a5a1c537571733992b226f4f1197d79e94cf0ae5", - "sha256:f8979280bdafff686ba5e4d8f97840f929a87ed9cdf133cbbd42f7766774d2aa", - "sha256:f9a2ae5c91cecc9edd47e041a930490c31c3afb1f5e6d71de3dc671bfaca02bf" - ], - "index": "pypi", - "version": "==1.1.1" - }, - "websocket-client": { - "hashes": [ - "sha256:9e813624b6eb619999a97dc7958469217c3176312b3a16a4bd1bc7e08a46ec98", - "sha256:af248a825037ef591efbf6ed20cc5faa03d3b47b9e5a2230a529eeee1c1fc3ef" - ], - "markers": "python_version >= '3.9'", - "version": "==1.9.0" - }, - "websockets": { - "hashes": [ - "sha256:0298d07ee155e2e9fda5be8a9042200dd2e3bb0b8a38482156576f863a9d457c", - "sha256:04cdd5d2d1dacbad0a7bf36ccbcd3ccd5a30ee188f2560b7a62a30d14107b31a", - "sha256:08d7af67b64d29823fed316505a89b86705f2b7981c07848fb5e3ea3020c1abe", - "sha256:152284a83a00c59b759697b7f9e9cddf4e3c7861dd0d964b472b70f78f89e80e", - "sha256:1637db62fad1dc833276dded54215f2c7fa46912301a24bd94d45d46a011ceec", - "sha256:19c4dc84098e523fd63711e563077d39e90ec6702aff4b5d9e344a60cb3c0cb1", - "sha256:1c1b30e4f497b0b354057f3467f56244c603a79c0d1dafce1d16c283c25f6e64", - "sha256:2b9f1e0d69bc60a4a87349d50c09a037a2607918746f07de04df9e43252c77a3", - "sha256:31a52addea25187bde0797a97d6fc3d2f92b6f72a9370792d65a6e84615ac8a8", - "sha256:32da954ffa2814258030e5a57bc73a3635463238e797c7375dc8091327434206", - "sha256:335c23addf3d5e6a8633f9f8eda77efad001671e80b95c491dd0924587ece0b3", - "sha256:3425ac5cf448801335d6fdc7ae1eb22072055417a96cc6b31b3861f455fbc156", - "sha256:349f83cd6c9a415428ee1005cadb5c2c56f4389bc06a9af16103c3bc3dcc8b7d", - "sha256:37b31c1623c6605e4c00d466c9d633f9b812ea430c11c8a278774a1fde1acfa9", - "sha256:417b28978cdccab24f46400586d128366313e8a96312e4b9362a4af504f3bbad", - "sha256:485c49116d0af10ac698623c513c1cc01c9446c058a4e61e3bf6c19dff7335a2", - "sha256:4a1aba3340a8dca8db6eb5a7986157f52eb9e436b74813764241981ca4888f03", - "sha256:50f23cdd8343b984957e4077839841146f67a3d31ab0d00e6b824e74c5b2f6e8", - "sha256:52a0fec0e6c8d9a784c2c78276a48a2bdf099e4ccc2a4cad53b27718dbfd0230", - "sha256:52ac480f44d32970d66763115edea932f1c5b1312de36df06d6b219f6741eed8", - "sha256:5569417dc80977fc8c2d43a86f78e0a5a22fee17565d78621b6bb264a115d4ea", - "sha256:569d01a4e7fba956c5ae4fc988f0d4e187900f5497ce46339c996dbf24f17641", - "sha256:583b7c42688636f930688d712885cf1531326ee05effd982028212ccc13e5957", - "sha256:5a4b4cc550cb665dd8a47f868c8d04c8230f857363ad3c9caf7a0c3bf8c61ca6", - "sha256:5f451484aeb5cafee1ccf789b1b66f535409d038c56966d6101740c1614b86c6", - "sha256:5f6261a5e56e8d5c42a4497b364ea24d94d9563e8fbd44e78ac40879c60179b5", - "sha256:6e5a82b677f8f6f59e8dfc34ec06ca6b5b48bc4fcda346acd093694cc2c24d8f", - "sha256:71c989cbf3254fbd5e84d3bff31e4da39c43f884e64f2551d14bb3c186230f00", - "sha256:781caf5e8eee67f663126490c2f96f40906594cb86b408a703630f95550a8c3e", - "sha256:7be95cfb0a4dae143eaed2bcba8ac23f4892d8971311f1b06f3c6b78952ee70b", - "sha256:7d837379b647c0c4c2355c2499723f82f1635fd2c26510e1f587d89bc2199e72", - "sha256:86890e837d61574c92a97496d590968b23c2ef0aeb8a9bc9421d174cd378ae39", - "sha256:878b336ac47938b474c8f982ac2f7266a540adc3fa4ad74ae96fea9823a02cc9", - "sha256:8b6e209ffee39ff1b6d0fa7bfef6de950c60dfb91b8fcead17da4ee539121a79", - "sha256:8cc451a50f2aee53042ac52d2d053d08bf89bcb31ae799cb4487587661c038a0", - "sha256:8d7f0659570eefb578dacde98e24fb60af35350193e4f56e11190787bee77dac", - "sha256:8e1dab317b6e77424356e11e99a432b7cb2f3ec8c5ab4dabbcee6add48f72b35", - "sha256:8ff32bb86522a9e5e31439a58addbb0166f0204d64066fb955265c4e214160f0", - "sha256:95724e638f0f9c350bb1c2b0a7ad0e83d9cc0c9259f3ea94e40d7b02a2179ae5", - "sha256:9b5aca38b67492ef518a8ab76851862488a478602229112c4b0d58d63a7a4d5c", - "sha256:a069d734c4a043182729edd3e9f247c3b2a4035415a9172fd0f1b71658a320a8", - "sha256:a0b31e0b424cc6b5a04b8838bbaec1688834b2383256688cf47eb97412531da1", - "sha256:a35539cacc3febb22b8f4d4a99cc79b104226a756aa7400adc722e83b0d03244", - "sha256:a5e18a238a2b2249c9a9235466b90e96ae4795672598a58772dd806edc7ac6d3", - "sha256:a653aea902e0324b52f1613332ddf50b00c06fdaf7e92624fbf8c77c78fa5767", - "sha256:abf050a199613f64c886ea10f38b47770a65154dc37181bfaff70c160f45315a", - "sha256:af80d74d4edfa3cb9ed973a0a5ba2b2a549371f8a741e0800cb07becdd20f23d", - "sha256:b14dc141ed6d2dde437cddb216004bcac6a1df0935d79656387bd41632ba0bbd", - "sha256:b784ca5de850f4ce93ec85d3269d24d4c82f22b7212023c974c401d4980ebc5e", - "sha256:bc59589ab64b0022385f429b94697348a6a234e8ce22544e3681b2e9331b5944", - "sha256:c0204dc62a89dc9d50d682412c10b3542d748260d743500a85c13cd1ee4bde82", - "sha256:c0ee0e63f23914732c6d7e0cce24915c48f3f1512ec1d079ed01fc629dab269d", - "sha256:caab51a72c51973ca21fa8a18bd8165e1a0183f1ac7066a182ff27107b71e1a4", - "sha256:d6297ce39ce5c2e6feb13c1a996a2ded3b6832155fcfc920265c76f24c7cceb5", - "sha256:daa3b6ff70a9241cf6c7fc9e949d41232d9d7d26fd3522b1ad2b4d62487e9904", - "sha256:df57afc692e517a85e65b72e165356ed1df12386ecb879ad5693be08fac65dde", - "sha256:e0334872c0a37b606418ac52f6ab9cfd17317ac26365f7f65e203e2d0d0d359f", - "sha256:e6578ed5b6981005df1860a56e3617f14a6c307e6a71b4fff8c48fdc50f3ed2c", - "sha256:eaded469f5e5b7294e2bdca0ab06becb6756ea86894a47806456089298813c89", - "sha256:f4a32d1bd841d4bcbffdcb3d2ce50c09c3909fbead375ab28d0181af89fd04da", - "sha256:fd3cb4adb94a2a6e2b7c0d8d05cb94e6f1c81a0cf9dc2694fb65c7e8d94c42e4" - ], - "index": "pypi", - "version": "==16.0" - }, - "wsproto": { - "hashes": [ - "sha256:61eea322cdf56e8cc904bd3ad7573359a242ba65688716b0710a5eb12beab584", - "sha256:b86885dcf294e15204919950f666e06ffc6c7c114ca900b060d6e16293528294" - ], - "markers": "python_version >= '3.10'", - "version": "==1.3.2" - } - }, - "develop": { - "iniconfig": { - "hashes": [ - "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", - "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12" - ], - "markers": "python_version >= '3.10'", - "version": "==2.3.0" - }, - "packaging": { - "hashes": [ - "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", - "sha256:ff452ff5a3e828ce110190feff1178bb1f2ea2281fa2075aadb987c2fb221661" - ], - "markers": "python_version >= '3.8'", - "version": "==26.2" - }, - "pluggy": { - "hashes": [ - "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", - "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746" - ], - "markers": "python_version >= '3.9'", - "version": "==1.6.0" - }, - "pygments": { - "hashes": [ - "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", - "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176" - ], - "markers": "python_version >= '3.9'", - "version": "==2.20.0" - }, - "pytest": { - "hashes": [ - "sha256:2c5efc453d45394fdd706ade797c0a81091eccd1d6e4bccfcd476e2b8e0ab5d9", - "sha256:b86ada508af81d19edeb213c681b1d48246c1a91d304c6c81a427674c17eb91c" - ], - "index": "pypi", - "version": "==9.0.3" - } - } -} diff --git a/README.md b/README.md index bad815e..1764d7b 100644 --- a/README.md +++ b/README.md @@ -1,68 +1,43 @@ # led-controller -LED controller web app for managing profiles, **zones**, presets, and colour palettes, and sending commands to LED devices. Outbound paths include: +ESP32-S3 controller for LED drivers: W5500 Ethernet, web UI, I2S microphone beat detection and an ESP-NOW link to the drivers. The firmware lives in [`v2/`](v2/); see [`v2/docs/BENCH_TEST.md`](v2/docs/BENCH_TEST.md) for the bench tests. -- **Serial → ESP-NOW bridge**: JSON lines over UART to an ESP32 that forwards ESP-NOW frames (configure `serial_port` and baud in `settings.json` / Settings model). -- **Wi-Fi LED drivers**: TCP JSON lines (default port **8765** on the Pi; drivers discover the controller via **UDP 8766** broadcast). - -## Run - -- One-time setup for port 80 without root: `sudo scripts/setup-port80.sh` -- Start app: `pipenv run run` (override listen port with the **`PORT`** environment variable) -- Dev watcher (auto-restart on `src/` changes): `pipenv run dev` -- Regenerate **`docs/help.pdf`** from **`docs/help.md`**: `pipenv run help-pdf` (requires **pandoc** and **chromium** on the host) - -## UI modes - -- **Run mode**: focused control view. Select zones/presets and apply profiles. Editing actions are hidden. -- **Edit mode**: management view. Shows **Zones**, Presets, Patterns, Colour Palette, and Send Presets controls, plus per-tile preset edit/remove and drag-reorder. - -## Profiles - -- Applying a profile updates session scope and refreshes the active zone content. -- In **Run mode**, Profiles supports apply-only behaviour (no create/clone/delete). -- In **Edit mode**, Profiles supports create/clone/delete. -- Creating a profile always creates a populated `default` zone (starter presets). -- Optional **DJ zone** seeding creates: - - `dj` zone bound to device name `dj` - - starter DJ presets (rainbow, single colour, transition) - -## Preset colours and palette linking - -- In preset editor, selecting a colour picker value auto-adds it when the picker closes. -- Use **From Palette** to add a palette-linked preset colour. -- Linked colours are stored as palette references and shown with a `P` badge. -- When profile palette colours change, linked preset colours update across that profile. - -## Brightness and search - -- The header **Brightness** slider sets the server-wide `global_brightness` (saved via `PUT /settings`, broadcast to connected drivers, and re-sent when a Wi-Fi driver reconnects). -- The Devices, Zones and Presets modals have a client-side search filter. - -## API docs - -- Main API reference: `docs/API.md` -- User guide: `docs/help.md` -- Full specification: `docs/SPECIFICATION.md` - -## 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/`): +## Build and flash ```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 +make build # minify the web UI from v2/web, then build the firmware (ESP-IDF in Docker) +make flash # flash over USB +make ota HOST= # update firmware (web UI included) over Ethernet, no USB (POST /ota) +make monitor # serial console +make test # driver unit tests and the C/Python envelope cross-check ``` -Tests: `pipenv run pytest tests/engine_tests`. +`make` lists every target. The web UI sources are in `v2/web/` (`static/`, `templates/`, `audio.html`). + +## Other directories + +- `led-driver/` (submodule): MicroPython firmware for the ESP32 LED drivers. +- `led-tool/` (submodule): `led-cli`, configures drivers over serial and updates the controller over Ethernet (`led-cli --ota HOST`). +- `led-simulator/` (submodule), `espnow-sender/`: test helpers. +- `db/`: stored zones, presets and devices, importable with `PUT /db/`. + +## Docs + +- API reference: `docs/API.md` +- User guide: `docs/help.md` (`scripts/build_help_pdf.sh` regenerates `docs/help.pdf`) +- Specification: `docs/SPECIFICATION.md` + +## Network + +The controller advertises `.local` over mDNS (default `led-controller`, plus an `_http._tcp` service). Both settings below come from `/settings` and apply on reboot. + +`static_ips` is a list of networks to try, in order, each time the Ethernet link comes up. The first entry whose gateway answers ARP is used; if none does (or the list is empty) the controller uses DHCP. `netmask` defaults to `255.255.255.0`, `dns` to the gateway. + +```bash +curl -X PUT http://led-controller.local/settings/settings -H 'Content-Type: application/json' -d '{ + "hostname": "stage", + "static_ips": [ + {"ip": "192.168.1.50", "netmask": "255.255.255.0", "gw": "192.168.1.1"}, + {"ip": "10.0.0.50", "netmask": "255.255.255.0", "gw": "10.0.0.1"} + ]}' +``` diff --git a/db/device.json b/db/device.json index 7e39ceb..afa437a 100644 --- a/db/device.json +++ b/db/device.json @@ -1 +1 @@ -{"188b0e1560a8": {"id": "188b0e1560a8", "name": "led-188b0e1560a8", "type": "led", "transport": "wifi", "address": "10.1.1.192", "default_pattern": null, "zones": []}, "f0f5bdfb9d30": {"id": "f0f5bdfb9d30", "name": "led-f0f5bdfb9d30", "type": "led", "transport": "wifi", "address": "10.1.1.232", "default_pattern": null, "zones": []}} \ No newline at end of file +{"e8f60a16e074": {"id": "e8f60a16e074", "name": "mirror", "type": "led", "transport": "wifi", "address": "192.168.1.199", "default_pattern": null, "zones": []}, "e8f60a16d51c": {"id": "e8f60a16d51c", "name": "mirror", "type": "led", "transport": "wifi", "address": "192.168.1.77", "default_pattern": null, "zones": []}, "e8f60a170d68": {"id": "e8f60a170d68", "name": "mirror", "type": "led", "transport": "wifi", "address": "192.168.1.217", "default_pattern": null, "zones": []}, "588c81a1182c": {"id": "588c81a1182c", "name": "dj", "type": "led", "transport": "wifi", "address": "192.168.1.114", "default_pattern": null, "zones": []}, "dcb4d99988c8": {"id": "dcb4d99988c8", "name": "roof", "type": "led", "transport": "wifi", "address": "192.168.1.158", "default_pattern": null, "zones": []}, "48f6ee2097c0": {"id": "48f6ee2097c0", "name": "roof", "type": "led", "transport": "wifi", "address": "192.168.1.246", "default_pattern": null, "zones": []}, "48f6ee211d8c": {"id": "48f6ee211d8c", "name": "roof", "type": "led", "transport": "wifi", "address": "192.168.1.55", "default_pattern": null, "zones": []}, "dcb4d99b0e34": {"id": "dcb4d99b0e34", "name": "roof", "type": "led", "transport": "wifi", "address": "192.168.1.167", "default_pattern": null, "zones": []}, "588c81a337fc": {"id": "588c81a337fc", "name": "inner", "type": "led", "transport": "wifi", "address": "192.168.1.110", "default_pattern": null, "zones": []}, "588c81a32e1c": {"id": "588c81a32e1c", "name": "outer", "type": "led", "transport": "wifi", "address": "192.168.1.250", "default_pattern": null, "zones": []}, "e8f60a16f288": {"id": "e8f60a16f288", "name": "mirror", "type": "led", "transport": "wifi", "address": "192.168.1.249", "default_pattern": null, "zones": []}, "e4b323c53870": {"id": "e4b323c53870", "name": "speaker1", "type": "led", "transport": "wifi", "address": "192.168.1.23", "default_pattern": null, "zones": []}, "e8f60a16eba4": {"id": "e8f60a16eba4", "name": "speaker2", "type": "led", "transport": "wifi", "address": "192.168.1.31", "default_pattern": null, "zones": []}, "e8f60a1707c0": {"id": "e8f60a1707c0", "name": "speaker3", "type": "led", "transport": "wifi", "address": "192.168.1.134", "default_pattern": null, "zones": []}, "e8f60a16fb14": {"id": "e8f60a16fb14", "name": "speaker4", "type": "led", "transport": "wifi", "address": "192.168.1.30", "default_pattern": null, "zones": []}, "e8f60a16e57c": {"id": "e8f60a16e57c", "name": "speaker5", "type": "led", "transport": "wifi", "address": "192.168.1.63", "default_pattern": null, "zones": []}, "e8f60a16f1b4": {"id": "e8f60a16f1b4", "name": "speaker6", "type": "led", "transport": "wifi", "address": "192.168.1.224", "default_pattern": null, "zones": []}, "e4b323c5ad6c": {"id": "e4b323c5ad6c", "name": "speaker7", "type": "led", "transport": "wifi", "address": "192.168.1.94", "default_pattern": null, "zones": []}, "588c81a200d8": {"id": "588c81a200d8", "name": "speaker8", "type": "led", "transport": "wifi", "address": "192.168.1.122", "default_pattern": null, "zones": []}, "a085e34efaec": {"id": "a085e34efaec", "name": "alleyway", "type": "led", "transport": "wifi", "address": "192.168.1.22", "default_pattern": null, "zones": []}, "e8f60a16f94c": {"id": "e8f60a16f94c", "name": "speaker10", "type": "led", "transport": "wifi", "address": "192.168.1.195", "default_pattern": null, "zones": []}, "e8f60a1701a8": {"id": "e8f60a1701a8", "name": "speaker9", "type": "led", "transport": "wifi", "address": "192.168.1.179", "default_pattern": null, "zones": []}} \ No newline at end of file diff --git a/db/pattern.json b/db/pattern.json index a437e8c..378940e 100644 --- a/db/pattern.json +++ b/db/pattern.json @@ -1 +1 @@ -{"on": {"min_delay": 10, "max_delay": 10000, "max_colors": 1}, "off": {"min_delay": 10, "max_delay": 10000, "max_colors": 0}, "rainbow": {"n1": "Step Rate", "min_delay": 10, "max_delay": 10000, "max_colors": 0}, "colour_cycle": {"n1": "Step Rate", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "transition": {"min_delay": 10, "max_delay": 10000, "max_colors": 10}, "chase": {"n1": "Colour 1 Length", "n2": "Colour 2 Length", "n3": "Step 1", "n4": "Step 2", "min_delay": 10, "max_delay": 10000, "max_colors": 2}, "pulse": {"n1": "Attack", "n2": "Hold", "n3": "Decay", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "circle": {"n1": "Head Rate", "n2": "Max Length", "n3": "Tail Rate", "n4": "Min Length", "min_delay": 10, "max_delay": 10000, "max_colors": 2}, "blink": {"min_delay": 10, "max_delay": 10000, "max_colors": 10}, "flicker": {"n1": "Min brightness", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "flame": {"n1": "Min brightness", "n2": "Breath period (ms)", "n3": "Spark gap min (ms, 0=default 10\u201330 s, -1=off)", "n4": "Spark gap max (ms)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "twinkle": {"n1": "Twinkle activity (1\u2013255, higher = more changes)", "n2": "Density (0\u2013255, higher = more of the strip lit)", "n3": "Min adjacent LEDs per twinkle (same as max for fixed length)", "n4": "Max adjacent LEDs per twinkle (same as min for fixed length)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "radiate": {"n1": "Node spacing (LEDs)", "n2": "Out time (ms)", "n3": "In time (ms)", "min_delay": 10, "max_delay": 10000, "max_colors": 2}, "meteor_rain": {"n1": "Tail length", "n2": "Speed (LEDs per frame)", "n3": "Fade amount (1-255)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "scanner": {"n1": "Eye width", "n2": "End pause (frames)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "gradient_scroll": {"n1": "Scroll step rate", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "comet_dual": {"n1": "Tail length", "n2": "Speed", "n3": "Gap", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "sparkle_trail": {"n1": "Spark density", "n2": "Decay", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "wave": {"n1": "Wavelength", "n2": "Amplitude", "n3": "Drift speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "plasma": {"n1": "Scale", "n2": "Speed", "n3": "Contrast", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "segment_chase": {"n1": "Segment size", "n2": "Phase step", "n3": "Segment phase offset", "n4": "Gap per segment", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "bar_graph": {"n1": "Level percent", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "breathing_dual": {"n1": "Phase offset", "n2": "Ease", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "strobe_burst": {"n1": "Burst count", "n2": "Burst gap", "n3": "Cooldown", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "rain_drops": {"n1": "Drop rate", "n2": "Ripple width", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "fireflies": {"n1": "Count", "n2": "Twinkle speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "clock_sweep": {"n1": "Hand width", "n2": "Marker interval", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "marquee": {"n1": "On length", "n2": "Off length", "n3": "Step", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "aurora": {"n1": "Band count", "n2": "Shimmer", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "snowfall": {"n1": "Flake density", "n2": "Fall speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "heartbeat": {"n1": "Pulse 1 ms", "n2": "Pulse 2 ms", "n3": "Pause ms", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "orbit": {"n1": "Orbit count", "n2": "Base speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "palette_morph": {"n1": "Morph ms", "n2": "Warp rate", "n3": "Turbulence", "max_colors": 10, "min_delay": 10, "max_delay": 10000}} \ No newline at end of file +{"on": {"min_delay": 10, "max_delay": 10000, "max_colors": 1}, "off": {"min_delay": 10, "max_delay": 10000, "max_colors": 0}, "rainbow": {"n1": "Step Rate", "min_delay": 10, "max_delay": 10000, "max_colors": 0}, "colour_cycle": {"n1": "Step Rate", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "transition": {"min_delay": 10, "max_delay": 10000, "max_colors": 10}, "chase": {"n1": "Colour 1 Length", "n2": "Colour 2 Length", "n3": "Step 1", "n4": "Step 2", "min_delay": 10, "max_delay": 10000, "max_colors": 2}, "pulse": {"n1": "Attack", "n2": "Hold", "n3": "Decay", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "circle": {"n1": "Head Rate", "n2": "Max Length", "n3": "Tail Rate", "n4": "Min Length", "min_delay": 10, "max_delay": 10000, "max_colors": 2}, "blink": {"min_delay": 10, "max_delay": 10000, "max_colors": 10}, "flicker": {"n1": "Min brightness", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "flame": {"n1": "Min brightness", "n2": "Breath period (ms)", "n3": "Spark gap min (ms, 0=default 10\u201330 s, -1=off)", "n4": "Spark gap max (ms)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "twinkle": {"n1": "Twinkle activity (1\u2013255, higher = more changes)", "n2": "Density (0\u2013255, higher = more of the strip lit)", "n3": "Min adjacent LEDs per twinkle (same as max for fixed length)", "n4": "Max adjacent LEDs per twinkle (same as min for fixed length)", "min_delay": 84, "max_delay": 10000, "max_colors": 10}, "radiate": {"n1": "Node spacing (LEDs)", "n2": "Out time (ms)", "n3": "In time (ms)", "min_delay": 10, "max_delay": 10000, "max_colors": 2}, "meteor_rain": {"n1": "Tail length", "n2": "Speed (LEDs per frame)", "n3": "Fade amount (1-255)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "scanner": {"n1": "Eye width", "n2": "End pause (frames)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "gradient_scroll": {"n1": "Scroll step rate", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "comet_dual": {"n1": "Tail length", "n2": "Speed", "n3": "Gap", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "sparkle_trail": {"n1": "Spark density", "n2": "Decay", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "wave": {"n1": "Wavelength", "n2": "Amplitude", "n3": "Drift speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "plasma": {"n1": "Scale", "n2": "Speed", "n3": "Contrast", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "segment_chase": {"n1": "Segment size", "n2": "Phase step", "n3": "Segment phase offset", "n4": "Gap per segment", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "bar_graph": {"n1": "Level percent", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "breathing_dual": {"n1": "Phase offset", "n2": "Ease", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "strobe_burst": {"n1": "Burst count", "n2": "Burst gap", "n3": "Cooldown", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "rain_drops": {"n1": "Drop rate", "n2": "Ripple width", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "fireflies": {"n1": "Count", "n2": "Twinkle speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "clock_sweep": {"n1": "Hand width", "n2": "Marker interval", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "marquee": {"n1": "On length", "n2": "Off length", "n3": "Step", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "aurora": {"n1": "Band count", "n2": "Shimmer", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "snowfall": {"n1": "Flake density", "n2": "Fall speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "heartbeat": {"n1": "Pulse 1 ms", "n2": "Pulse 2 ms", "n3": "Pause ms", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "orbit": {"n1": "Orbit count", "n2": "Base speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "palette_morph": {"n1": "Morph ms", "n2": "Warp rate", "n3": "Turbulence", "max_colors": 10, "min_delay": 10, "max_delay": 10000}} \ No newline at end of file diff --git a/db/preset.json b/db/preset.json index e42d91c..6d6ce9a 100644 --- a/db/preset.json +++ b/db/preset.json @@ -1 +1 @@ -{"1": {"name": "on", "pattern": "on", "colors": ["#FFFFFF"], "brightness": 255, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "2": {"name": "off", "pattern": "off", "colors": [], "brightness": 0, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "3": {"name": "rainbow", "pattern": "rainbow", "colors": [], "brightness": 255, "delay": 100, "auto": true, "n1": 2, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "4": {"name": "transition", "pattern": "transition", "colors": ["#FF0000", "#00FF00", "#0000FF", "#FFFFFF", "#0000FF", "#FFFF00"], "brightness": 255, "delay": 5000, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null, null, 6, 2, 3]}, "5": {"name": "chase", "pattern": "chase", "colors": ["#FF0000", "#0000FF"], "brightness": 255, "delay": 200, "auto": true, "n1": 5, "n2": 5, "n3": 1, "n4": 1, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "6": {"name": "pulse", "pattern": "pulse", "colors": ["#00FF00"], "brightness": 255, "delay": 500, "auto": true, "n1": 1000, "n2": 500, "n3": 1000, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "7": {"name": "circle", "pattern": "circle", "colors": ["#FFA500", "#800080"], "brightness": 255, "delay": 200, "auto": true, "n1": 2, "n2": 10, "n3": 2, "n4": 5, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "8": {"name": "blink", "pattern": "blink", "colors": ["#FF0000", "#00FF00", "#0000FF", "#FFFF00"], "brightness": 255, "delay": 1000, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "9": {"name": "warm white", "pattern": "on", "colors": ["#FFF5E6"], "brightness": 200, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "10": {"name": "cool white", "pattern": "on", "colors": ["#E6F2FF"], "brightness": 200, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "11": {"name": "red", "pattern": "on", "colors": ["#FF0000"], "brightness": 255, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "12": {"name": "blue", "pattern": "on", "colors": ["#0000FF"], "brightness": 255, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "13": {"name": "rainbow slow", "pattern": "rainbow", "colors": [], "brightness": 255, "delay": 150, "auto": true, "n1": 1, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "14": {"name": "pulse slow", "pattern": "pulse", "colors": ["#FF6600"], "brightness": 255, "delay": 800, "auto": true, "n1": 2000, "n2": 1000, "n3": 2000, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "15": {"name": "blink red green", "pattern": "blink", "colors": ["#FF0000", "#00FF00"], "brightness": 255, "delay": 500, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "30": {"name": "rainbow slow", "pattern": "rainbow", "colors": [], "brightness": 255, "delay": 150, "auto": true, "n1": 1, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "31": {"name": "DJ Rainbow", "pattern": "rainbow", "colors": [], "brightness": 220, "delay": 60, "n1": 12, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "32": {"name": "DJ Single Color", "pattern": "on", "colors": ["#ff00ff"], "brightness": 220, "delay": 100, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "33": {"name": "DJ Transition", "pattern": "transition", "colors": ["#ff0000", "#00ff00", "#0000ff"], "brightness": 220, "delay": 250, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "34": {"name": "DJ Rainbow", "pattern": "rainbow", "colors": [], "brightness": 220, "delay": 60, "n1": 12, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "35": {"name": "DJ Single Color", "pattern": "on", "colors": ["#ff00ff"], "brightness": 220, "delay": 100, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "36": {"name": "DJ Transition", "pattern": "transition", "colors": ["#ff0000", "#00ff00", "#0000ff"], "brightness": 220, "delay": 250, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "37": {"name": "tranistion2", "pattern": "transition", "colors": ["#FF0000", "#FFFF00", "#FF00FF"], "brightness": 128, "delay": 1000, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [0, 3, 4]}, "38": {"name": "Colour Cycle", "pattern": "colour_cycle", "colors": ["#FF0000", "#0000FF"], "brightness": 255, "delay": 100, "auto": true, "n1": 1, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null]}, "39": {"name": "flicker", "pattern": "flicker", "colors": ["#ae00ff"], "brightness": 255, "delay": 50, "auto": true, "n1": 100, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null]}, "40": {"name": "flame", "pattern": "flame", "colors": ["#ffc800"], "brightness": 128, "delay": 50, "auto": true, "n1": 35, "n2": 2600, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null]}, "41": {"name": "twinkle", "pattern": "twinkle", "colors": ["#78C8FF", "#508CFF", "#B478FF", "#64DCE8", "#A0C8FF"], "brightness": 255, "delay": 100, "auto": true, "n1": 150, "n2": 20, "n3": 0, "n4": 10, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null, null, null, null]}, "42": {"name": "radiate", "pattern": "radiate", "colors": ["#a600ff", "#000a0a"], "brightness": 255, "delay": 5000, "auto": true, "n1": 30, "n2": 900, "n3": 4000, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null]}, "43": {"name": "test meteor rain", "pattern": "meteor_rain", "colors": ["#FF5000", "#0080FF"], "brightness": 200, "delay": 40, "auto": true, "n1": 50, "n2": 1, "n3": 200, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null]}, "44": {"name": "test scanner", "pattern": "scanner", "colors": ["#FF0000"], "brightness": 255, "delay": 30, "auto": true, "n1": 4, "n2": 2, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "45": {"name": "test gradient scroll", "pattern": "gradient_scroll", "colors": ["#FF0000", "#00FF00", "#0000FF"], "brightness": 220, "delay": 60, "auto": true, "n1": 2, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "46": {"name": "test comet dual", "pattern": "comet_dual", "colors": ["#FFAA00", "#00AAFF"], "brightness": 200, "delay": 60, "auto": true, "n1": 8, "n2": 1, "n3": 3, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "47": {"name": "test sparkle trail", "pattern": "sparkle_trail", "colors": ["#88CCFF", "#FFFFFF"], "brightness": 200, "delay": 60, "auto": true, "n1": 24, "n2": 210, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "48": {"name": "test wave", "pattern": "wave", "colors": ["#00B4FF"], "brightness": 200, "delay": 60, "auto": true, "n1": 12, "n2": 180, "n3": 1, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "49": {"name": "test plasma", "pattern": "plasma", "colors": ["#FF0066"], "brightness": 200, "delay": 60, "auto": true, "n1": 6, "n2": 2, "n3": 2, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "50": {"name": "test segment chase", "pattern": "segment_chase", "colors": ["#FF0000", "#0000FF"], "brightness": 200, "delay": 60, "auto": true, "n1": 4, "n2": 1, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "51": {"name": "test bar graph", "pattern": "bar_graph", "colors": ["#00FF00", "#102010"], "brightness": 200, "delay": 60, "auto": true, "n1": 60, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "52": {"name": "test breathing dual", "pattern": "breathing_dual", "colors": ["#FF0088", "#00AAFF"], "brightness": 200, "delay": 60, "auto": true, "n1": 128, "n2": 1, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "53": {"name": "test strobe burst", "pattern": "strobe_burst", "colors": ["#FFFFFF"], "brightness": 200, "delay": 60, "auto": true, "n1": 3, "n2": 60, "n3": 400, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "54": {"name": "test rain drops", "pattern": "rain_drops", "colors": ["#90C8FF"], "brightness": 200, "delay": 60, "auto": true, "n1": 32, "n2": 3, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "55": {"name": "test fireflies", "pattern": "fireflies", "colors": ["#FFD060", "#90FF90"], "brightness": 200, "delay": 60, "auto": true, "n1": 6, "n2": 8, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "56": {"name": "test clock sweep", "pattern": "clock_sweep", "colors": ["#FFFFFF", "#202020"], "brightness": 200, "delay": 60, "auto": true, "n1": 1, "n2": 5, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "57": {"name": "test marquee", "pattern": "marquee", "colors": ["#FFFFFF"], "brightness": 200, "delay": 60, "auto": true, "n1": 3, "n2": 2, "n3": 1, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "58": {"name": "test aurora", "pattern": "aurora", "colors": ["#2CC88C", "#5078FF", "#A050DC"], "brightness": 200, "delay": 60, "auto": true, "n1": 3, "n2": 40, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "59": {"name": "test snowfall", "pattern": "snowfall", "colors": ["#FFFFFF", "#B0DCFF"], "brightness": 200, "delay": 60, "auto": true, "n1": 20, "n2": 1, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "60": {"name": "test heartbeat", "pattern": "heartbeat", "colors": ["#FF2840"], "brightness": 200, "delay": 60, "auto": true, "n1": 120, "n2": 80, "n3": 500, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "61": {"name": "test orbit", "pattern": "orbit", "colors": ["#FFFFFF", "#00B4FF", "#FF0077"], "brightness": 200, "delay": 60, "auto": true, "n1": 3, "n2": 1, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "62": {"name": "test palette morph", "pattern": "palette_morph", "colors": ["#FF0000", "#00FF00", "#0000FF"], "brightness": 200, "delay": 60, "auto": true, "n1": 1200, "n2": 200, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}} \ No newline at end of file +{"1": {"name": "on", "pattern": "on", "colors": [], "brightness": 32, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": []}, "2": {"name": "off", "pattern": "off", "colors": [], "brightness": 0, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "3": {"name": "rainbow", "pattern": "rainbow", "colors": [], "brightness": 32, "delay": 100, "auto": true, "n1": 2, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": []}, "4": {"name": "transition", "pattern": "transition", "colors": ["#0000FF", "#FF00FF", "#FF0000", "#00FF00", "#FFFF00", "#00FFFF"], "brightness": 32, "delay": 5000, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [2, 4, 0, 1, 3, 5]}, "5": {"name": "chase", "pattern": "chase", "colors": ["#006b12", "#2b02c0"], "brightness": 66, "delay": 150, "auto": true, "n1": 4, "n2": 4, "n3": 5, "n4": 1, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null]}, "6": {"name": "pulse", "pattern": "pulse", "colors": ["#f5e400"], "brightness": 255, "delay": 300, "auto": true, "n1": 200, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null]}, "7": {"name": "circle", "pattern": "circle", "colors": ["#ffbb00", "#000000"], "brightness": 64, "delay": 10, "auto": true, "n1": 25, "n2": 120, "n3": 27, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, 7]}, "8": {"name": "blink", "pattern": "blink", "colors": ["#FF0000", "#00FF00", "#0000FF", "#FFFF00"], "brightness": 255, "delay": 1000, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "9": {"name": "warm white", "pattern": "on", "colors": ["#FFF5E6"], "brightness": 255, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null]}, "10": {"name": "cool white", "pattern": "on", "colors": ["#E6F2FF"], "brightness": 200, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "11": {"name": "red", "pattern": "on", "colors": ["#FF0000"], "brightness": 64, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null]}, "12": {"name": "blue", "pattern": "on", "colors": ["#0000FF"], "brightness": 255, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "13": {"name": "rainbow slow", "pattern": "rainbow", "colors": [], "brightness": 255, "delay": 150, "auto": true, "n1": 1, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "14": {"name": "pulse slow", "pattern": "pulse", "colors": ["#FF6600", "#FF00FF", "#FFFF00"], "brightness": 127, "delay": 100, "auto": true, "n1": 2000, "n2": 1000, "n3": 1000, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, 4, 3]}, "15": {"name": "blink red green", "pattern": "blink", "colors": ["#FF0000", "#00FF00"], "brightness": 255, "delay": 500, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "30": {"name": "rainbow slow", "pattern": "rainbow", "colors": [], "brightness": 255, "delay": 150, "auto": true, "n1": 1, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "31": {"name": "DJ Rainbow", "pattern": "rainbow", "colors": [], "brightness": 220, "delay": 60, "n1": 12, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "32": {"name": "DJ Single Color", "pattern": "on", "colors": ["#ff00ff"], "brightness": 220, "delay": 100, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "33": {"name": "DJ Transition", "pattern": "transition", "colors": ["#ff0000", "#00ff00", "#0000ff"], "brightness": 220, "delay": 250, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "34": {"name": "DJ Rainbow", "pattern": "rainbow", "colors": [], "brightness": 220, "delay": 60, "n1": 12, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "35": {"name": "DJ Single Color", "pattern": "on", "colors": ["#ff00ff"], "brightness": 220, "delay": 100, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "36": {"name": "DJ Transition", "pattern": "transition", "colors": ["#ff0000", "#00ff00", "#0000ff"], "brightness": 220, "delay": 250, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "37": {"name": "tranistion2", "pattern": "transition", "colors": ["#FF0000", "#FFFF00"], "brightness": 128, "delay": 1000, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [0, 3]}, "38": {"name": "Colour Cycle", "pattern": "colour_cycle", "colors": ["#FF0000", "#000000"], "brightness": 255, "delay": 100, "auto": true, "n1": 1, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [0, null]}, "39": {"name": "flicker", "pattern": "flicker", "colors": ["#ae00ff"], "brightness": 255, "delay": 50, "auto": true, "n1": 100, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null]}, "40": {"name": "flame", "pattern": "flame", "colors": ["#ffc800", "#00FFFF", "#0000FF"], "brightness": 64, "delay": 50, "auto": true, "n1": 32, "n2": 1000, "n3": 50, "n4": 100, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, 5, 2]}, "41": {"name": "twinkle", "pattern": "twinkle", "colors": ["#78C8FF", "#508CFF", "#B478FF", "#64DCE8", "#A0C8FF"], "brightness": 64, "delay": 300, "auto": true, "n1": 200, "n2": 40, "n3": 2, "n4": 10, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null, null, null, null]}, "42": {"name": "radiate", "pattern": "radiate", "colors": ["#a600ff", "#ffff00"], "brightness": 32, "delay": 2001, "auto": true, "n1": 100, "n2": 900, "n3": 900, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null]}, "43": {"name": "test meteor rain", "pattern": "meteor_rain", "colors": ["#FF5000", "#0080FF"], "brightness": 255, "delay": 100, "auto": true, "n1": 100, "n2": 10, "n3": 240, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null]}, "44": {"name": "test scanner", "pattern": "scanner", "colors": ["#00ff04"], "brightness": 32, "delay": 3, "auto": true, "n1": 10, "n2": 7, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null]}, "45": {"name": "test gradient scroll", "pattern": "gradient_scroll", "colors": ["#FF0000", "#00FF00", "#0000FF", "#00FFFF", "#FF00FF"], "brightness": 50, "delay": 60, "auto": true, "n1": 2, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null, 2, 5, 4]}, "46": {"name": "test comet dual", "pattern": "comet_dual", "colors": ["#ffffff", "#000000", "#00FFFF", "#FF00FF"], "brightness": 200, "delay": 20, "auto": true, "n1": 500, "n2": 1, "n3": 10, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null, 5, 4]}, "47": {"name": "test sparkle trail", "pattern": "sparkle_trail", "colors": ["#88CCFF", "#FF00FF", "#FFFF00"], "brightness": 255, "delay": 300, "auto": true, "n1": 24, "n2": 100, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, 4, 3]}, "48": {"name": "test wave", "pattern": "wave", "colors": ["#00B4FF"], "brightness": 200, "delay": 60, "auto": true, "n1": 12, "n2": 180, "n3": 1, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "49": {"name": "test plasma", "pattern": "plasma", "colors": ["#FF0066", "#0000FF", "#00FFFF"], "brightness": 64, "delay": 60, "auto": true, "n1": 5, "n2": 10, "n3": 10, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, 2, 5]}, "50": {"name": "test segment chase", "pattern": "segment_chase", "colors": ["#000000", "#f5f5f5"], "brightness": 200, "delay": 60, "auto": true, "n1": 10, "n2": 4, "n3": 1, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null]}, "51": {"name": "test bar graph", "pattern": "bar_graph", "colors": ["#00FF00", "#102010"], "brightness": 200, "delay": 60, "auto": true, "n1": 60, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "52": {"name": "test breathing dual", "pattern": "breathing_dual", "colors": ["#FF0088", "#00AAFF"], "brightness": 200, "delay": 60, "auto": true, "n1": 128, "n2": 1, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "53": {"name": "test strobe burst", "pattern": "strobe_burst", "colors": ["#FFFFFF"], "brightness": 200, "delay": 60, "auto": true, "n1": 3, "n2": 60, "n3": 400, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "54": {"name": "test rain drops", "pattern": "rain_drops", "colors": ["#e60000", "#e5a50a"], "brightness": 200, "delay": 20, "auto": true, "n1": 200, "n2": 2, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null]}, "55": {"name": "test fireflies", "pattern": "fireflies", "colors": ["#a51d2d", "#000000"], "brightness": 255, "delay": 300, "auto": true, "n1": 50, "n2": 100, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, 7]}, "56": {"name": "test clock sweep", "pattern": "clock_sweep", "colors": ["#FFFFFF", "#202020"], "brightness": 200, "delay": 60, "auto": true, "n1": 1, "n2": 5, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "57": {"name": "test marquee", "pattern": "marquee", "colors": ["#FFFFFF"], "brightness": 200, "delay": 60, "auto": true, "n1": 10, "n2": 10, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null]}, "58": {"name": "test aurora", "pattern": "aurora", "colors": ["#2CC88C", "#5078FF", "#A050DC"], "brightness": 200, "delay": 60, "auto": true, "n1": 3, "n2": 40, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null, null]}, "59": {"name": "test snowfall", "pattern": "snowfall", "colors": ["#FFFFFF"], "brightness": 200, "delay": 200, "auto": true, "n1": 150, "n2": 5, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null]}, "60": {"name": "test heartbeat", "pattern": "heartbeat", "colors": ["#FF2840"], "brightness": 200, "delay": 60, "auto": true, "n1": 120, "n2": 80, "n3": 500, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "61": {"name": "test orbit", "pattern": "orbit", "colors": ["#FFFFFF", "#00B4FF", "#FF0077"], "brightness": 200, "delay": 60, "auto": true, "n1": 3, "n2": 1, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "62": {"name": "test palette morph", "pattern": "palette_morph", "colors": ["#FF0000", "#0000FF", "#FF00FF"], "brightness": 200, "delay": 1000, "auto": true, "n1": 100, "n2": 10, "n3": 100, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null, 4]}, "63": {"name": "cyan", "pattern": "on", "colors": ["#00FFFF"], "brightness": 6, "delay": 0, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [5]}, "64": {"name": "twinkle2", "pattern": "twinkle", "colors": ["#FF0000", "#FFFFFF", "#FF00FF"], "brightness": 127, "delay": 200, "n1": 64, "n2": 128, "n3": 1, "n4": 10, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [0, 6, 4]}, "65": {"name": "pink", "pattern": "on", "colors": ["#ff8605"], "brightness": 32, "delay": 0, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null]}, "66": {"name": "green", "pattern": "on", "colors": ["#00FF00"], "brightness": 6, "delay": 0, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [1]}, "67": {"name": "purple", "pattern": "on", "colors": ["#f500ff"], "brightness": 6, "delay": 0, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null]}} \ No newline at end of file diff --git a/db/profile.json b/db/profile.json index d74ac27..9872c31 100644 --- a/db/profile.json +++ b/db/profile.json @@ -1 +1 @@ -{"1": {"name": "default", "type": "zones", "zones": ["1", "8"], "scenes": [], "palette_id": "1"}, "2": {"name": "test", "type": "zones", "zones": ["6", "7"], "scenes": [], "palette_id": "12"}} \ No newline at end of file +{"1": {"name": "default", "type": "zones", "zones": ["1", "8", "9", "10", "11", "12", "13"], "scenes": [], "palette_id": "1"}, "2": {"name": "test", "type": "zones", "zones": ["6", "7"], "scenes": [], "palette_id": "12"}} \ No newline at end of file diff --git a/db/zone.json b/db/zone.json index 1552682..9fce9e7 100644 --- a/db/zone.json +++ b/db/zone.json @@ -1 +1 @@ -{"1": {"name": "default", "names": ["led-188b0e1560a8", "led-f0f5bdfb9d30"], "presets": [["4", "2", "7"], ["3", "14", "5"], ["8", "9", "1"], ["6", "38", "42"], ["39", "40", "41"], ["43", "44", "45"], ["46", "47", "48"], ["49", "50", "51"], ["52", "53", "54"], ["55", "56", "57"], ["58", "59", "60"], ["61", "62"]], "presets_flat": ["4", "2", "7", "3", "14", "5", "8", "9", "1", "6", "38", "42", "39", "40", "41", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62"], "default_preset": "41"}, "2": {"name": "default", "names": ["1", "2", "3", "4", "5", "6", "7", "8", "0", "a"], "presets": [["16", "17", "18"], ["19", "20", "21"], ["22", "23", "24"], ["25", "26", "27"], ["28", "29", "30"]], "presets_flat": ["16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30"]}, "3": {"name": "default", "names": ["1"], "presets": [], "default_preset": null}, "4": {"name": "default", "names": ["1"], "presets": [], "default_preset": null}, "5": {"name": "dj", "names": ["dj"], "presets": [["31", "32", "33"]], "default_preset": "31", "presets_flat": ["31", "32", "33"]}, "6": {"name": "default", "names": ["1"], "presets": [], "default_preset": null, "presets_flat": []}, "7": {"name": "dj", "names": ["dj"], "presets": [["34", "35", "36"]], "default_preset": "34", "presets_flat": ["34", "35", "36"]}, "8": {"name": "test", "names": ["led-188b0e1560a8"], "presets": [["1", "2", "3"], ["4", "5"]], "default_preset": "1", "presets_flat": ["1", "2", "3", "4", "5"]}} \ No newline at end of file +{"1": {"name": "mirror", "names": ["mirror", "mirror", "mirror", "mirror"], "presets": [["4", "2", "3"], ["14", "5", "9"], ["42", "39", "40"], ["38", "55", "43"], ["44", "45", "46"], ["64", "50", "47"], ["49", "54", "58"], ["59", "41", "57"]], "presets_flat": ["4", "2", "3", "14", "5", "9", "42", "39", "40", "38", "55", "43", "44", "45", "46", "64", "50", "47", "49", "54", "58", "59", "41", "57"], "default_preset": "5"}, "2": {"name": "default", "names": ["1", "2", "3", "4", "5", "6", "7", "8", "0", "a"], "presets": [["16", "17", "18"], ["19", "20", "21"], ["22", "23", "24"], ["25", "26", "27"], ["28", "29", "30"]], "presets_flat": ["16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30"]}, "3": {"name": "default", "names": ["1"], "presets": [], "default_preset": null}, "4": {"name": "default", "names": ["1"], "presets": [], "default_preset": null}, "5": {"name": "dj", "names": ["dj"], "presets": [["31", "32", "33"]], "default_preset": "31", "presets_flat": ["31", "32", "33"]}, "6": {"name": "default", "names": ["1"], "presets": [], "default_preset": null, "presets_flat": []}, "7": {"name": "dj", "names": ["dj"], "presets": [["34", "35", "36"]], "default_preset": "34", "presets_flat": ["34", "35", "36"]}, "8": {"name": "dj", "names": ["dj"], "presets": [["1", "2", "3"], ["4", "5", "66"], ["63", "65", "11"], ["67"]], "default_preset": "11", "presets_flat": ["1", "2", "3", "4", "5", "66", "63", "65", "11", "67"]}, "9": {"name": "roof", "names": ["roof", "roof", "roof", "roof"], "presets": [["5", "3", "42"], ["2", "1", "55"], ["4", "11", "9"], ["6"]], "default_preset": "3", "presets_flat": ["5", "3", "42", "2", "1", "55", "4", "11", "9", "6"]}, "10": {"name": "inner", "names": ["inner"], "presets": [["3", "46", "7"], ["55", "54", "37"], ["1", "2", "5"], ["6"]], "default_preset": "7", "presets_flat": ["3", "46", "7", "55", "54", "37", "1", "2", "5", "6"]}, "11": {"name": "outer", "names": ["outer"], "presets": [["3", "46", "7"], ["55", "54", "37"], ["2", "1"]], "default_preset": "46", "presets_flat": ["3", "46", "7", "55", "54", "37", "2", "1"]}, "12": {"name": "speakers", "names": ["speaker1", "speaker2", "speaker4", "speaker3", "speaker8", "speaker5", "speaker7", "speaker6", "speaker10", "speaker9"], "presets": [["4", "2", "41"], ["64", "3", "14"], ["5", "42", "40"], ["43", "45", "46"], ["47", "49", "54"], ["55", "59"]], "default_preset": "4", "presets_flat": ["4", "2", "41", "64", "3", "14", "5", "42", "40", "43", "45", "46", "47", "49", "54", "55", "59"]}, "13": {"name": "alleyway", "names": ["alleyway"], "presets": [["4", "2", "3"], ["14", "5", "9"], ["42", "39", "40"], ["38", "41", "43"], ["44", "45", "46"], ["50", "47", "49"], ["54", "55", "57"], ["58", "59"]], "default_preset": "4", "presets_flat": ["4", "2", "3", "14", "5", "9", "42", "39", "40", "38", "41", "43", "44", "45", "46", "50", "47", "49", "54", "55", "57", "58", "59"]}} \ No newline at end of file diff --git a/docs/API.md b/docs/API.md index 19cf6b2..472a42b 100644 --- a/docs/API.md +++ b/docs/API.md @@ -70,6 +70,7 @@ Below, `` values are string identifiers used by the JSON stores (numeric str |--------|------|-------------| | GET | `/settings` | Full settings object (from `settings.json` / `Settings` model). | | PUT | `/settings/settings` | Merge keys into settings and save. Returns `{"message": "Settings updated successfully"}`. | +| POST | `/reboot` | v2 controller: restart the board. Replies `{"message":"rebooting"}` first, then reboots after 0.5 s. Network settings (`hostname`, `static_ips`) apply on the next boot. | | 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`. | diff --git a/led-driver b/led-driver index 2fcaf2f..940d1d0 160000 --- a/led-driver +++ b/led-driver @@ -1 +1 @@ -Subproject commit 2fcaf2f06425cb668d527c525d6d406a372ce4b3 +Subproject commit 940d1d0a77b8a80543ccce54d0e60bebd9269332 diff --git a/lib/microdot/__init__.py b/lib/microdot/__init__.py deleted file mode 100644 index 68cb381..0000000 --- a/lib/microdot/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from microdot.microdot import Microdot, Request, Response, abort, redirect, \ - send_file # noqa: F401 \ No newline at end of file diff --git a/lib/microdot/helpers.py b/lib/microdot/helpers.py deleted file mode 100644 index 664e58c..0000000 --- a/lib/microdot/helpers.py +++ /dev/null @@ -1,8 +0,0 @@ -try: - from functools import wraps -except ImportError: # pragma: no cover - # MicroPython does not currently implement functools.wraps - def wraps(wrapped): - def _(wrapper): - return wrapper - return _ diff --git a/lib/microdot/microdot.py b/lib/microdot/microdot.py deleted file mode 100644 index 0513f21..0000000 --- a/lib/microdot/microdot.py +++ /dev/null @@ -1,1450 +0,0 @@ -""" -microdot --------- - -The ``microdot`` module defines a few classes that help implement HTTP-based -servers for MicroPython and standard Python. -""" -import asyncio -import io -import json -import time - -try: - from inspect import iscoroutinefunction, iscoroutine - from functools import partial - - async def invoke_handler(handler, *args, **kwargs): - """Invoke a handler and return the result. - - This method runs sync handlers in a thread pool executor. - """ - if iscoroutinefunction(handler): - ret = await handler(*args, **kwargs) - else: - ret = await asyncio.get_running_loop().run_in_executor( - None, partial(handler, *args, **kwargs)) - return ret -except ImportError: # pragma: no cover - def iscoroutine(coro): - return hasattr(coro, 'send') and hasattr(coro, 'throw') - - async def invoke_handler(handler, *args, **kwargs): - """Invoke a handler and return the result. - - This method runs sync handlers in the asyncio thread, which can - potentially cause blocking and performance issues. - """ - ret = handler(*args, **kwargs) - if iscoroutine(ret): - ret = await ret - return ret - -try: - from sys import print_exception -except ImportError: # pragma: no cover - import traceback - - def print_exception(exc): - traceback.print_exc() - -MUTED_SOCKET_ERRORS = [ - 32, # Broken pipe - 54, # Connection reset by peer - 104, # Connection reset by peer - 128, # Operation on closed socket -] - - -def urldecode_str(s): - s = s.replace('+', ' ') - parts = s.split('%') - if len(parts) == 1: - return s - result = [parts[0]] - for item in parts[1:]: - if item == '': - result.append('%') - else: - code = item[:2] - result.append(chr(int(code, 16))) - result.append(item[2:]) - return ''.join(result) - - -def urldecode_bytes(s): - s = s.replace(b'+', b' ') - parts = s.split(b'%') - if len(parts) == 1: - return s.decode() - result = [parts[0]] - for item in parts[1:]: - if item == b'': - result.append(b'%') - else: - code = item[:2] - result.append(bytes([int(code, 16)])) - result.append(item[2:]) - return b''.join(result).decode() - - -def urlencode(s): - return s.replace('+', '%2B').replace(' ', '+').replace( - '%', '%25').replace('?', '%3F').replace('#', '%23').replace( - '&', '%26').replace('=', '%3D') - - -class NoCaseDict(dict): - """A subclass of dictionary that holds case-insensitive keys. - - :param initial_dict: an initial dictionary of key/value pairs to - initialize this object with. - - Example:: - - >>> d = NoCaseDict() - >>> d['Content-Type'] = 'text/html' - >>> print(d['Content-Type']) - text/html - >>> print(d['content-type']) - text/html - >>> print(d['CONTENT-TYPE']) - text/html - >>> del d['cOnTeNt-TyPe'] - >>> print(d) - {} - """ - def __init__(self, initial_dict=None): - super().__init__(initial_dict or {}) - self.keymap = {k.lower(): k for k in self.keys() if k.lower() != k} - - def __setitem__(self, key, value): - kl = key.lower() - key = self.keymap.get(kl, key) - if kl != key: - self.keymap[kl] = key - super().__setitem__(key, value) - - def __getitem__(self, key): - kl = key.lower() - return super().__getitem__(self.keymap.get(kl, kl)) - - def __delitem__(self, key): - kl = key.lower() - super().__delitem__(self.keymap.get(kl, kl)) - - def __contains__(self, key): - kl = key.lower() - return self.keymap.get(kl, kl) in self.keys() - - def get(self, key, default=None): - kl = key.lower() - return super().get(self.keymap.get(kl, kl), default) - - def update(self, other_dict): - for key, value in other_dict.items(): - self[key] = value - - -def mro(cls): # pragma: no cover - """Return the method resolution order of a class. - - This is a helper function that returns the method resolution order of a - class. It is used by Microdot to find the best error handler to invoke for - the raised exception. - - In CPython, this function returns the ``__mro__`` attribute of the class. - In MicroPython, this function implements a recursive depth-first scanning - of the class hierarchy. - """ - if hasattr(cls, 'mro'): - return cls.__mro__ - - def _mro(cls): - m = [cls] - for base in cls.__bases__: - m += _mro(base) - return m - - mro_list = _mro(cls) - - # If a class appears multiple times (due to multiple inheritance) remove - # all but the last occurence. This matches the method resolution order - # of MicroPython, but not CPython. - mro_pruned = [] - for i in range(len(mro_list)): - base = mro_list.pop(0) - if base not in mro_list: - mro_pruned.append(base) - return mro_pruned - - -class MultiDict(dict): - """A subclass of dictionary that can hold multiple values for the same - key. It is used to hold key/value pairs decoded from query strings and - form submissions. - - :param initial_dict: an initial dictionary of key/value pairs to - initialize this object with. - - Example:: - - >>> d = MultiDict() - >>> d['sort'] = 'name' - >>> d['sort'] = 'email' - >>> print(d['sort']) - 'name' - >>> print(d.getlist('sort')) - ['name', 'email'] - """ - def __init__(self, initial_dict=None): - super().__init__() - if initial_dict: - for key, value in initial_dict.items(): - self[key] = value - - def __setitem__(self, key, value): - if key not in self: - super().__setitem__(key, []) - super().__getitem__(key).append(value) - - def __getitem__(self, key): - return super().__getitem__(key)[0] - - def get(self, key, default=None, type=None): - """Return the value for a given key. - - :param key: The key to retrieve. - :param default: A default value to use if the key does not exist. - :param type: A type conversion callable to apply to the value. - - If the multidict contains more than one value for the requested key, - this method returns the first value only. - - Example:: - - >>> d = MultiDict() - >>> d['age'] = '42' - >>> d.get('age') - '42' - >>> d.get('age', type=int) - 42 - >>> d.get('name', default='noname') - 'noname' - """ - if key not in self: - return default - value = self[key] - if type is not None: - value = type(value) - return value - - def getlist(self, key, type=None): - """Return all the values for a given key. - - :param key: The key to retrieve. - :param type: A type conversion callable to apply to the values. - - If the requested key does not exist in the dictionary, this method - returns an empty list. - - Example:: - - >>> d = MultiDict() - >>> d.getlist('items') - [] - >>> d['items'] = '3' - >>> d.getlist('items') - ['3'] - >>> d['items'] = '56' - >>> d.getlist('items') - ['3', '56'] - >>> d.getlist('items', type=int) - [3, 56] - """ - if key not in self: - return [] - values = super().__getitem__(key) - if type is not None: - values = [type(value) for value in values] - return values - - -class AsyncBytesIO: - """An async wrapper for BytesIO.""" - def __init__(self, data): - self.stream = io.BytesIO(data) - - async def read(self, n=-1): - return self.stream.read(n) - - async def readline(self): # pragma: no cover - return self.stream.readline() - - async def readexactly(self, n): # pragma: no cover - return self.stream.read(n) - - async def readuntil(self, separator=b'\n'): # pragma: no cover - return self.stream.readuntil(separator=separator) - - async def awrite(self, data): # pragma: no cover - return self.stream.write(data) - - async def aclose(self): # pragma: no cover - pass - - -class Request: - """An HTTP request.""" - #: Specify the maximum payload size that is accepted. Requests with larger - #: payloads will be rejected with a 413 status code. Applications can - #: change this maximum as necessary. - #: - #: Example:: - #: - #: Request.max_content_length = 1 * 1024 * 1024 # 1MB requests allowed - max_content_length = 16 * 1024 - - #: Specify the maximum payload size that can be stored in ``body``. - #: Requests with payloads that are larger than this size and up to - #: ``max_content_length`` bytes will be accepted, but the application will - #: only be able to access the body of the request by reading from - #: ``stream``. Set to 0 if you always access the body as a stream. - #: - #: Example:: - #: - #: Request.max_body_length = 4 * 1024 # up to 4KB bodies read - max_body_length = 16 * 1024 - - #: Specify the maximum length allowed for a line in the request. Requests - #: with longer lines will not be correctly interpreted. Applications can - #: change this maximum as necessary. - #: - #: Example:: - #: - #: Request.max_readline = 16 * 1024 # 16KB lines allowed - max_readline = 2 * 1024 - - class G: - pass - - def __init__(self, app, client_addr, method, url, http_version, headers, - body=None, stream=None, sock=None): - #: The application instance to which this request belongs. - self.app = app - #: The address of the client, as a tuple (host, port). - self.client_addr = client_addr - #: The HTTP method of the request. - self.method = method - #: The request URL, including the path and query string. - self.url = url - #: The path portion of the URL. - self.path = url - #: The query string portion of the URL. - self.query_string = None - #: The parsed query string, as a - #: :class:`MultiDict ` object. - self.args = {} - #: A dictionary with the headers included in the request. - self.headers = headers - #: A dictionary with the cookies included in the request. - self.cookies = {} - #: The parsed ``Content-Length`` header. - self.content_length = 0 - #: The parsed ``Content-Type`` header. - self.content_type = None - #: A general purpose container for applications to store data during - #: the life of the request. - self.g = Request.G() - - self.http_version = http_version - if '?' in self.path: - self.path, self.query_string = self.path.split('?', 1) - self.args = self._parse_urlencoded(self.query_string) - - if 'Content-Length' in self.headers: - self.content_length = int(self.headers['Content-Length']) - if 'Content-Type' in self.headers: - self.content_type = self.headers['Content-Type'] - if 'Cookie' in self.headers: - for cookie in self.headers['Cookie'].split(';'): - name, value = cookie.strip().split('=', 1) - self.cookies[name] = value - - self._body = body - self.body_used = False - self._stream = stream - self.sock = sock - self._json = None - self._form = None - self.after_request_handlers = [] - - @staticmethod - async def create(app, client_reader, client_writer, client_addr): - """Create a request object. - - :param app: The Microdot application instance. - :param client_reader: An input stream from where the request data can - be read. - :param client_writer: An output stream where the response data can be - written. - :param client_addr: The address of the client, as a tuple. - - This method is a coroutine. It returns a newly created ``Request`` - object. - """ - # request line - line = (await Request._safe_readline(client_reader)).strip().decode() - if not line: # pragma: no cover - return None - method, url, http_version = line.split() - http_version = http_version.split('/', 1)[1] - - # headers - headers = NoCaseDict() - content_length = 0 - while True: - line = (await Request._safe_readline( - client_reader)).strip().decode() - if line == '': - break - header, value = line.split(':', 1) - value = value.strip() - headers[header] = value - if header.lower() == 'content-length': - content_length = int(value) - - # body - body = b'' - if content_length and content_length <= Request.max_body_length: - body = await client_reader.readexactly(content_length) - stream = None - else: - body = b'' - stream = client_reader - - return Request(app, client_addr, method, url, http_version, headers, - body=body, stream=stream, - sock=(client_reader, client_writer)) - - def _parse_urlencoded(self, urlencoded): - data = MultiDict() - if len(urlencoded) > 0: # pragma: no branch - if isinstance(urlencoded, str): - for kv in [pair.split('=', 1) - for pair in urlencoded.split('&') if pair]: - data[urldecode_str(kv[0])] = urldecode_str(kv[1]) \ - if len(kv) > 1 else '' - elif isinstance(urlencoded, bytes): # pragma: no branch - for kv in [pair.split(b'=', 1) - for pair in urlencoded.split(b'&') if pair]: - data[urldecode_bytes(kv[0])] = urldecode_bytes(kv[1]) \ - if len(kv) > 1 else b'' - return data - - @property - def body(self): - """The body of the request, as bytes.""" - return self._body - - @property - def stream(self): - """The body of the request, as a bytes stream.""" - if self._stream is None: - self._stream = AsyncBytesIO(self._body) - return self._stream - - @property - def json(self): - """The parsed JSON body, or ``None`` if the request does not have a - JSON body.""" - if self._json is None: - if self.content_type is None: - return None - mime_type = self.content_type.split(';')[0] - if mime_type != 'application/json': - return None - self._json = json.loads(self.body.decode()) - return self._json - - @property - def form(self): - """The parsed form submission body, as a - :class:`MultiDict ` object, or ``None`` if the - request does not have a form submission.""" - if self._form is None: - if self.content_type is None: - return None - mime_type = self.content_type.split(';')[0] - if mime_type != 'application/x-www-form-urlencoded': - return None - self._form = self._parse_urlencoded(self.body) - return self._form - - def after_request(self, f): - """Register a request-specific function to run after the request is - handled. Request-specific after request handlers run at the very end, - after the application's own after request handlers. The function must - take two arguments, the request and response objects. The return value - of the function must be the updated response object. - - Example:: - - @app.route('/') - def index(request): - # register a request-specific after request handler - @req.after_request - def func(request, response): - # ... - return response - - return 'Hello, World!' - - Note that the function is not called if the request handler raises an - exception and an error response is returned instead. - """ - self.after_request_handlers.append(f) - return f - - @staticmethod - async def _safe_readline(stream): - line = (await stream.readline()) - if len(line) > Request.max_readline: - raise ValueError('line too long') - return line - - -class Response: - """An HTTP response class. - - :param body: The body of the response. If a dictionary or list is given, - a JSON formatter is used to generate the body. If a file-like - object or an async generator is given, a streaming response is - used. If a string is given, it is encoded from UTF-8. Else, - the body should be a byte sequence. - :param status_code: The numeric HTTP status code of the response. The - default is 200. - :param headers: A dictionary of headers to include in the response. - :param reason: A custom reason phrase to add after the status code. The - default is "OK" for responses with a 200 status code and - "N/A" for any other status codes. - """ - types_map = { - 'css': 'text/css', - 'gif': 'image/gif', - 'html': 'text/html', - 'jpg': 'image/jpeg', - 'js': 'application/javascript', - 'json': 'application/json', - 'png': 'image/png', - 'txt': 'text/plain', - } - - send_file_buffer_size = 1024 - - #: The content type to use for responses that do not explicitly define a - #: ``Content-Type`` header. - default_content_type = 'text/plain' - - #: The default cache control max age used by :meth:`send_file`. A value - #: of ``None`` means that no ``Cache-Control`` header is added. - default_send_file_max_age = None - - #: Special response used to signal that a response does not need to be - #: written to the client. Used to exit WebSocket connections cleanly. - already_handled = None - - def __init__(self, body='', status_code=200, headers=None, reason=None): - if body is None and status_code == 200: - body = '' - status_code = 204 - self.status_code = status_code - self.headers = NoCaseDict(headers or {}) - self.reason = reason - if isinstance(body, (dict, list)): - self.body = json.dumps(body).encode() - self.headers['Content-Type'] = 'application/json; charset=UTF-8' - elif isinstance(body, str): - self.body = body.encode() - else: - # this applies to bytes, file-like objects or generators - self.body = body - self.is_head = False - - def set_cookie(self, cookie, value, path=None, domain=None, expires=None, - max_age=None, secure=False, http_only=False, - partitioned=False): - """Add a cookie to the response. - - :param cookie: The cookie's name. - :param value: The cookie's value. - :param path: The cookie's path. - :param domain: The cookie's domain. - :param expires: The cookie expiration time, as a ``datetime`` object - or a correctly formatted string. - :param max_age: The cookie's ``Max-Age`` value. - :param secure: The cookie's ``secure`` flag. - :param http_only: The cookie's ``HttpOnly`` flag. - :param partitioned: Whether the cookie is partitioned. - """ - http_cookie = '{cookie}={value}'.format(cookie=cookie, value=value) - if path: - http_cookie += '; Path=' + path - if domain: - http_cookie += '; Domain=' + domain - if expires: - if isinstance(expires, str): - http_cookie += '; Expires=' + expires - else: # pragma: no cover - http_cookie += '; Expires=' + time.strftime( - '%a, %d %b %Y %H:%M:%S GMT', expires.timetuple()) - if max_age is not None: - http_cookie += '; Max-Age=' + str(max_age) - if secure: - http_cookie += '; Secure' - if http_only: - http_cookie += '; HttpOnly' - if partitioned: - http_cookie += '; Partitioned' - if 'Set-Cookie' in self.headers: - self.headers['Set-Cookie'].append(http_cookie) - else: - self.headers['Set-Cookie'] = [http_cookie] - - def delete_cookie(self, cookie, **kwargs): - """Delete a cookie. - - :param cookie: The cookie's name. - :param kwargs: Any cookie opens and flags supported by - ``set_cookie()`` except ``expires`` and ``max_age``. - """ - self.set_cookie(cookie, '', expires='Thu, 01 Jan 1970 00:00:01 GMT', - max_age=0, **kwargs) - - def complete(self): - if isinstance(self.body, bytes) and \ - 'Content-Length' not in self.headers: - self.headers['Content-Length'] = str(len(self.body)) - if 'Content-Type' not in self.headers: - self.headers['Content-Type'] = self.default_content_type - if 'charset=' not in self.headers['Content-Type']: - self.headers['Content-Type'] += '; charset=UTF-8' - - async def write(self, stream): - self.complete() - - try: - # status code - reason = self.reason if self.reason is not None else \ - ('OK' if self.status_code == 200 else 'N/A') - await stream.awrite('HTTP/1.0 {status_code} {reason}\r\n'.format( - status_code=self.status_code, reason=reason).encode()) - - # headers - for header, value in self.headers.items(): - values = value if isinstance(value, list) else [value] - for value in values: - await stream.awrite('{header}: {value}\r\n'.format( - header=header, value=value).encode()) - await stream.awrite(b'\r\n') - - # body - if not self.is_head: - iter = self.body_iter() - async for body in iter: - if isinstance(body, str): # pragma: no cover - body = body.encode() - try: - await stream.awrite(body) - except OSError as exc: # pragma: no cover - if exc.errno in MUTED_SOCKET_ERRORS or \ - exc.args[0] == 'Connection lost': - if hasattr(iter, 'aclose'): - await iter.aclose() - raise - if hasattr(iter, 'aclose'): # pragma: no branch - await iter.aclose() - - except OSError as exc: # pragma: no cover - if exc.errno in MUTED_SOCKET_ERRORS or \ - exc.args[0] == 'Connection lost': - pass - else: - raise - - def body_iter(self): - if hasattr(self.body, '__anext__'): - # response body is an async generator - return self.body - - response = self - - class iter: - ITER_UNKNOWN = 0 - ITER_SYNC_GEN = 1 - ITER_FILE_OBJ = 2 - ITER_NO_BODY = -1 - - def __aiter__(self): - if response.body: - self.i = self.ITER_UNKNOWN # need to determine type - else: - self.i = self.ITER_NO_BODY - return self - - async def __anext__(self): - if self.i == self.ITER_NO_BODY: - await self.aclose() - raise StopAsyncIteration - if self.i == self.ITER_UNKNOWN: - if hasattr(response.body, 'read'): - self.i = self.ITER_FILE_OBJ - elif hasattr(response.body, '__next__'): - self.i = self.ITER_SYNC_GEN - return next(response.body) - else: - self.i = self.ITER_NO_BODY - return response.body - elif self.i == self.ITER_SYNC_GEN: - try: - return next(response.body) - except StopIteration: - await self.aclose() - raise StopAsyncIteration - buf = response.body.read(response.send_file_buffer_size) - if iscoroutine(buf): # pragma: no cover - buf = await buf - if len(buf) < response.send_file_buffer_size: - self.i = self.ITER_NO_BODY - return buf - - async def aclose(self): - if hasattr(response.body, 'close'): - result = response.body.close() - if iscoroutine(result): # pragma: no cover - await result - - return iter() - - @classmethod - def redirect(cls, location, status_code=302): - """Return a redirect response. - - :param location: The URL to redirect to. - :param status_code: The 3xx status code to use for the redirect. The - default is 302. - """ - if '\x0d' in location or '\x0a' in location: - raise ValueError('invalid redirect URL') - return cls(status_code=status_code, headers={'Location': location}) - - @classmethod - def send_file(cls, filename, status_code=200, content_type=None, - stream=None, max_age=None, compressed=False, - file_extension=''): - """Send file contents in a response. - - :param filename: The filename of the file. - :param status_code: The 3xx status code to use for the redirect. The - default is 302. - :param content_type: The ``Content-Type`` header to use in the - response. If omitted, it is generated - automatically from the file extension of the - ``filename`` parameter. - :param stream: A file-like object to read the file contents from. If - a stream is given, the ``filename`` parameter is only - used when generating the ``Content-Type`` header. - :param max_age: The ``Cache-Control`` header's ``max-age`` value in - seconds. If omitted, the value of the - :attr:`Response.default_send_file_max_age` attribute is - used. - :param compressed: Whether the file is compressed. If ``True``, the - ``Content-Encoding`` header is set to ``gzip``. A - string with the header value can also be passed. - Note that when using this option the file must have - been compressed beforehand. This option only sets - the header. - :param file_extension: A file extension to append to the ``filename`` - parameter when opening the file, including the - dot. The extension given here is not considered - when generating the ``Content-Type`` header. - - Security note: The filename is assumed to be trusted. Never pass - filenames provided by the user without validating and sanitizing them - first. - """ - if content_type is None: - if compressed and filename.endswith('.gz'): - ext = filename[:-3].split('.')[-1] - else: - ext = filename.split('.')[-1] - if ext in Response.types_map: - content_type = Response.types_map[ext] - else: - content_type = 'application/octet-stream' - headers = {'Content-Type': content_type} - - if max_age is None: - max_age = cls.default_send_file_max_age - if max_age is not None: - headers['Cache-Control'] = 'max-age={}'.format(max_age) - - if compressed: - headers['Content-Encoding'] = compressed \ - if isinstance(compressed, str) else 'gzip' - - f = stream or open(filename + file_extension, 'rb') - return cls(body=f, status_code=status_code, headers=headers) - - -class URLPattern(): - def __init__(self, url_pattern): - self.url_pattern = url_pattern - self.segments = [] - self.regex = None - pattern = '' - use_regex = False - for segment in url_pattern.lstrip('/').split('/'): - if segment and segment[0] == '<': - if segment[-1] != '>': - raise ValueError('invalid URL pattern') - segment = segment[1:-1] - if ':' in segment: - type_, name = segment.rsplit(':', 1) - else: - type_ = 'string' - name = segment - parser = None - if type_ == 'string': - parser = self._string_segment - pattern += '/([^/]+)' - elif type_ == 'int': - parser = self._int_segment - pattern += '/(-?\\d+)' - elif type_ == 'path': - use_regex = True - pattern += '/(.+)' - elif type_.startswith('re:'): - use_regex = True - pattern += '/({pattern})'.format(pattern=type_[3:]) - else: - raise ValueError('invalid URL segment type') - self.segments.append({'parser': parser, 'name': name, - 'type': type_}) - else: - pattern += '/' + segment - self.segments.append({'parser': self._static_segment(segment)}) - if use_regex: - import re - self.regex = re.compile('^' + pattern + '$') - - def match(self, path): - args = {} - if self.regex: - g = self.regex.match(path) - if not g: - return - i = 1 - for segment in self.segments: - if 'name' not in segment: - continue - value = g.group(i) - if segment['type'] == 'int': - value = int(value) - args[segment['name']] = value - i += 1 - else: - if len(path) == 0 or path[0] != '/': - return - path = path[1:] - args = {} - for segment in self.segments: - if path is None: - return - arg, path = segment['parser'](path) - if arg is None: - return - if 'name' in segment: - args[segment['name']] = arg - if path is not None: - return - return args - - def _static_segment(self, segment): - def _static(value): - s = value.split('/', 1) - if s[0] == segment: - return '', s[1] if len(s) > 1 else None - return None, None - return _static - - def _string_segment(self, value): - s = value.split('/', 1) - if len(s[0]) == 0: - return None, None - return s[0], s[1] if len(s) > 1 else None - - def _int_segment(self, value): - s = value.split('/', 1) - try: - return int(s[0]), s[1] if len(s) > 1 else None - except ValueError: - return None, None - - -class HTTPException(Exception): - def __init__(self, status_code, reason=None): - self.status_code = status_code - self.reason = reason or str(status_code) + ' error' - - def __repr__(self): # pragma: no cover - return 'HTTPException: {}'.format(self.status_code) - - -class Microdot: - """An HTTP application class. - - This class implements an HTTP application instance and is heavily - influenced by the ``Flask`` class of the Flask framework. It is typically - declared near the start of the main application script. - - Example:: - - from microdot import Microdot - - app = Microdot() - """ - - def __init__(self): - self.url_map = [] - self.before_request_handlers = [] - self.after_request_handlers = [] - self.after_error_request_handlers = [] - self.error_handlers = {} - self.shutdown_requested = False - self.options_handler = self.default_options_handler - self.debug = False - self.server = None - - def route(self, url_pattern, methods=None): - """Decorator that is used to register a function as a request handler - for a given URL. - - :param url_pattern: The URL pattern that will be compared against - incoming requests. - :param methods: The list of HTTP methods to be handled by the - decorated function. If omitted, only ``GET`` requests - are handled. - - The URL pattern can be a static path (for example, ``/users`` or - ``/api/invoices/search``) or a path with dynamic components enclosed - in ``<`` and ``>`` (for example, ``/users/`` or - ``/invoices//products``). Dynamic path components can also - include a type prefix, separated from the name with a colon (for - example, ``/users/``). The type can be ``string`` (the - default), ``int``, ``path`` or ``re:[regular-expression]``. - - The first argument of the decorated function must be - the request object. Any path arguments that are specified in the URL - pattern are passed as keyword arguments. The return value of the - function must be a :class:`Response` instance, or the arguments to - be passed to this class. - - Example:: - - @app.route('/') - def index(request): - return 'Hello, world!' - """ - def decorated(f): - self.url_map.append( - ([m.upper() for m in (methods or ['GET'])], - URLPattern(url_pattern), f)) - return f - return decorated - - def get(self, url_pattern): - """Decorator that is used to register a function as a ``GET`` request - handler for a given URL. - - :param url_pattern: The URL pattern that will be compared against - incoming requests. - - This decorator can be used as an alias to the ``route`` decorator with - ``methods=['GET']``. - - Example:: - - @app.get('/users/') - def get_user(request, id): - # ... - """ - return self.route(url_pattern, methods=['GET']) - - def post(self, url_pattern): - """Decorator that is used to register a function as a ``POST`` request - handler for a given URL. - - :param url_pattern: The URL pattern that will be compared against - incoming requests. - - This decorator can be used as an alias to the``route`` decorator with - ``methods=['POST']``. - - Example:: - - @app.post('/users') - def create_user(request): - # ... - """ - return self.route(url_pattern, methods=['POST']) - - def put(self, url_pattern): - """Decorator that is used to register a function as a ``PUT`` request - handler for a given URL. - - :param url_pattern: The URL pattern that will be compared against - incoming requests. - - This decorator can be used as an alias to the ``route`` decorator with - ``methods=['PUT']``. - - Example:: - - @app.put('/users/') - def edit_user(request, id): - # ... - """ - return self.route(url_pattern, methods=['PUT']) - - def patch(self, url_pattern): - """Decorator that is used to register a function as a ``PATCH`` request - handler for a given URL. - - :param url_pattern: The URL pattern that will be compared against - incoming requests. - - This decorator can be used as an alias to the ``route`` decorator with - ``methods=['PATCH']``. - - Example:: - - @app.patch('/users/') - def edit_user(request, id): - # ... - """ - return self.route(url_pattern, methods=['PATCH']) - - def delete(self, url_pattern): - """Decorator that is used to register a function as a ``DELETE`` - request handler for a given URL. - - :param url_pattern: The URL pattern that will be compared against - incoming requests. - - This decorator can be used as an alias to the ``route`` decorator with - ``methods=['DELETE']``. - - Example:: - - @app.delete('/users/') - def delete_user(request, id): - # ... - """ - return self.route(url_pattern, methods=['DELETE']) - - def before_request(self, f): - """Decorator to register a function to run before each request is - handled. The decorated function must take a single argument, the - request object. - - Example:: - - @app.before_request - def func(request): - # ... - """ - self.before_request_handlers.append(f) - return f - - def after_request(self, f): - """Decorator to register a function to run after each request is - handled. The decorated function must take two arguments, the request - and response objects. The return value of the function must be an - updated response object. - - Example:: - - @app.after_request - def func(request, response): - # ... - return response - """ - self.after_request_handlers.append(f) - return f - - def after_error_request(self, f): - """Decorator to register a function to run after an error response is - generated. The decorated function must take two arguments, the request - and response objects. The return value of the function must be an - updated response object. The handler is invoked for error responses - generated by Microdot, as well as those returned by application-defined - error handlers. - - Example:: - - @app.after_error_request - def func(request, response): - # ... - return response - """ - self.after_error_request_handlers.append(f) - return f - - def errorhandler(self, status_code_or_exception_class): - """Decorator to register a function as an error handler. Error handler - functions for numeric HTTP status codes must accept a single argument, - the request object. Error handler functions for Python exceptions - must accept two arguments, the request object and the exception - object. - - :param status_code_or_exception_class: The numeric HTTP status code or - Python exception class to - handle. - - Examples:: - - @app.errorhandler(404) - def not_found(request): - return 'Not found' - - @app.errorhandler(RuntimeError) - def runtime_error(request, exception): - return 'Runtime error' - """ - def decorated(f): - self.error_handlers[status_code_or_exception_class] = f - return f - return decorated - - def mount(self, subapp, url_prefix=''): - """Mount a sub-application, optionally under the given URL prefix. - - :param subapp: The sub-application to mount. - :param url_prefix: The URL prefix to mount the application under. - """ - for methods, pattern, handler in subapp.url_map: - self.url_map.append( - (methods, URLPattern(url_prefix + pattern.url_pattern), - handler)) - for handler in subapp.before_request_handlers: - self.before_request_handlers.append(handler) - for handler in subapp.after_request_handlers: - self.after_request_handlers.append(handler) - for handler in subapp.after_error_request_handlers: - self.after_error_request_handlers.append(handler) - for status_code, handler in subapp.error_handlers.items(): - self.error_handlers[status_code] = handler - - @staticmethod - def abort(status_code, reason=None): - """Abort the current request and return an error response with the - given status code. - - :param status_code: The numeric status code of the response. - :param reason: The reason for the response, which is included in the - response body. - - Example:: - - from microdot import abort - - @app.route('/users/') - def get_user(id): - user = get_user_by_id(id) - if user is None: - abort(404) - return user.to_dict() - """ - raise HTTPException(status_code, reason) - - async def start_server(self, host='0.0.0.0', port=5000, debug=False, - ssl=None): - """Start the Microdot web server as a coroutine. This coroutine does - not normally return, as the server enters an endless listening loop. - The :func:`shutdown` function provides a method for terminating the - server gracefully. - - :param host: The hostname or IP address of the network interface that - will be listening for requests. A value of ``'0.0.0.0'`` - (the default) indicates that the server should listen for - requests on all the available interfaces, and a value of - ``127.0.0.1`` indicates that the server should listen - for requests only on the internal networking interface of - the host. - :param port: The port number to listen for requests. The default is - port 5000. - :param debug: If ``True``, the server logs debugging information. The - default is ``False``. - :param ssl: An ``SSLContext`` instance or ``None`` if the server should - not use TLS. The default is ``None``. - - This method is a coroutine. - - Example:: - - import asyncio - from microdot import Microdot - - app = Microdot() - - @app.route('/') - async def index(request): - return 'Hello, world!' - - async def main(): - await app.start_server(debug=True) - - asyncio.run(main()) - """ - self.debug = debug - - async def serve(reader, writer): - if not hasattr(writer, 'awrite'): # pragma: no cover - # CPython provides the awrite and aclose methods in 3.8+ - async def awrite(self, data): - self.write(data) - await self.drain() - - async def aclose(self): - self.close() - await self.wait_closed() - - from types import MethodType - writer.awrite = MethodType(awrite, writer) - writer.aclose = MethodType(aclose, writer) - - await self.handle_request(reader, writer) - - if self.debug: # pragma: no cover - print('Starting async server on {host}:{port}...'.format( - host=host, port=port)) - - try: - self.server = await asyncio.start_server(serve, host, port, - ssl=ssl) - except TypeError: # pragma: no cover - self.server = await asyncio.start_server(serve, host, port) - - while True: - try: - if hasattr(self.server, 'serve_forever'): # pragma: no cover - try: - await self.server.serve_forever() - except asyncio.CancelledError: - pass - await self.server.wait_closed() - break - except AttributeError: # pragma: no cover - # the task hasn't been initialized in the server object yet - # wait a bit and try again - await asyncio.sleep(0.1) - - def run(self, host='0.0.0.0', port=5000, debug=False, ssl=None): - """Start the web server. This function does not normally return, as - the server enters an endless listening loop. The :func:`shutdown` - function provides a method for terminating the server gracefully. - - :param host: The hostname or IP address of the network interface that - will be listening for requests. A value of ``'0.0.0.0'`` - (the default) indicates that the server should listen for - requests on all the available interfaces, and a value of - ``127.0.0.1`` indicates that the server should listen - for requests only on the internal networking interface of - the host. - :param port: The port number to listen for requests. The default is - port 5000. - :param debug: If ``True``, the server logs debugging information. The - default is ``False``. - :param ssl: An ``SSLContext`` instance or ``None`` if the server should - not use TLS. The default is ``None``. - - Example:: - - from microdot import Microdot - - app = Microdot() - - @app.route('/') - async def index(request): - return 'Hello, world!' - - app.run(debug=True) - """ - asyncio.run(self.start_server(host=host, port=port, debug=debug, - ssl=ssl)) # pragma: no cover - - def shutdown(self): - """Request a server shutdown. The server will then exit its request - listening loop and the :func:`run` function will return. This function - can be safely called from a route handler, as it only schedules the - server to terminate as soon as the request completes. - - Example:: - - @app.route('/shutdown') - def shutdown(request): - request.app.shutdown() - return 'The server is shutting down...' - """ - self.server.close() - - def find_route(self, req): - method = req.method.upper() - if method == 'OPTIONS' and self.options_handler: - return self.options_handler(req) - if method == 'HEAD': - method = 'GET' - f = 404 - for route_methods, route_pattern, route_handler in self.url_map: - req.url_args = route_pattern.match(req.path) - if req.url_args is not None: - if method in route_methods: - f = route_handler - break - else: - f = 405 - return f - - def default_options_handler(self, req): - allow = [] - for route_methods, route_pattern, route_handler in self.url_map: - if route_pattern.match(req.path) is not None: - allow.extend(route_methods) - if 'GET' in allow: - allow.append('HEAD') - allow.append('OPTIONS') - return {'Allow': ', '.join(allow)} - - async def handle_request(self, reader, writer): - req = None - try: - req = await Request.create(self, reader, writer, - writer.get_extra_info('peername')) - except Exception as exc: # pragma: no cover - print_exception(exc) - - res = await self.dispatch_request(req) - if res != Response.already_handled: # pragma: no branch - await res.write(writer) - try: - await writer.aclose() - except OSError as exc: # pragma: no cover - if exc.errno in MUTED_SOCKET_ERRORS: - pass - else: - raise - if self.debug and req: # pragma: no cover - print('{method} {path} {status_code}'.format( - method=req.method, path=req.path, - status_code=res.status_code)) - - async def dispatch_request(self, req): - after_request_handled = False - if req: - if req.content_length > req.max_content_length: - if 413 in self.error_handlers: - res = await invoke_handler(self.error_handlers[413], req) - else: - res = 'Payload too large', 413 - else: - f = self.find_route(req) - try: - res = None - if callable(f): - for handler in self.before_request_handlers: - res = await invoke_handler(handler, req) - if res: - break - if res is None: - res = await invoke_handler( - f, req, **req.url_args) - if isinstance(res, int): - res = '', res - if isinstance(res, tuple): - if isinstance(res[0], int): - res = ('', res[0], - res[1] if len(res) > 1 else {}) - body = res[0] - if isinstance(res[1], int): - status_code = res[1] - headers = res[2] if len(res) > 2 else {} - else: - status_code = 200 - headers = res[1] - res = Response(body, status_code, headers) - elif not isinstance(res, Response): - res = Response(res) - for handler in self.after_request_handlers: - res = await invoke_handler( - handler, req, res) or res - for handler in req.after_request_handlers: - res = await invoke_handler( - handler, req, res) or res - after_request_handled = True - elif isinstance(f, dict): - res = Response(headers=f) - elif f in self.error_handlers: - res = await invoke_handler(self.error_handlers[f], req) - else: - res = 'Not found', f - except HTTPException as exc: - if exc.status_code in self.error_handlers: - res = self.error_handlers[exc.status_code](req) - else: - res = exc.reason, exc.status_code - except Exception as exc: - print_exception(exc) - exc_class = None - res = None - if exc.__class__ in self.error_handlers: - exc_class = exc.__class__ - else: - for c in mro(exc.__class__)[1:]: - if c in self.error_handlers: - exc_class = c - break - if exc_class: - try: - res = await invoke_handler( - self.error_handlers[exc_class], req, exc) - except Exception as exc2: # pragma: no cover - print_exception(exc2) - if res is None: - if 500 in self.error_handlers: - res = await invoke_handler( - self.error_handlers[500], req) - else: - res = 'Internal server error', 500 - else: - if 400 in self.error_handlers: - res = await invoke_handler(self.error_handlers[400], req) - else: - res = 'Bad request', 400 - if isinstance(res, tuple): - res = Response(*res) - elif not isinstance(res, Response): - res = Response(res) - if not after_request_handled: - for handler in self.after_error_request_handlers: - res = await invoke_handler( - handler, req, res) or res - res.is_head = (req and req.method == 'HEAD') - return res - - -Response.already_handled = Response() - -abort = Microdot.abort -redirect = Response.redirect -send_file = Response.send_file \ No newline at end of file diff --git a/lib/microdot/session.py b/lib/microdot/session.py deleted file mode 100644 index 78ce2e6..0000000 --- a/lib/microdot/session.py +++ /dev/null @@ -1,225 +0,0 @@ -try: - import jwt - HAS_JWT = True -except ImportError: - HAS_JWT = False - try: - import ubinascii - except ImportError: - import binascii as ubinascii - try: - import uhashlib as hashlib - except ImportError: - import hashlib - try: - import uhmac as hmac - except ImportError: - try: - import hmac - except ImportError: - hmac = None - import json - -from microdot.microdot import invoke_handler -from microdot.helpers import wraps - - -class SessionDict(dict): - """A session dictionary. - - The session dictionary is a standard Python dictionary that has been - extended with convenience ``save()`` and ``delete()`` methods. - """ - def __init__(self, request, session_dict): - super().__init__(session_dict) - self.request = request - - def save(self): - """Update the session cookie.""" - self.request.app._session.update(self.request, self) - - def delete(self): - """Delete the session cookie.""" - self.request.app._session.delete(self.request) - - -class Session: - """Session handling - - :param app: The application instance. - :param secret_key: The secret key, as a string or bytes object. - :param cookie_options: A dictionary with cookie options to pass as - arguments to :meth:`Response.set_cookie() - `. - """ - secret_key = None - - def __init__(self, app=None, secret_key=None, cookie_options=None): - self.secret_key = secret_key - self.cookie_options = cookie_options or {} - if app is not None: - self.initialize(app) - - def initialize(self, app, secret_key=None, cookie_options=None): - if secret_key is not None: - self.secret_key = secret_key - if cookie_options is not None: - self.cookie_options = cookie_options - if 'path' not in self.cookie_options: - self.cookie_options['path'] = '/' - if 'http_only' not in self.cookie_options: - self.cookie_options['http_only'] = True - app._session = self - - def get(self, request): - """Retrieve the user session. - - :param request: The client request. - - The return value is a session dictionary with the data stored in the - user's session, or ``{}`` if the session data is not available or - invalid. - """ - if not self.secret_key: - raise ValueError('The session secret key is not configured') - if hasattr(request.g, '_session'): - return request.g._session - session = request.cookies.get('session') - if session is None: - request.g._session = SessionDict(request, {}) - return request.g._session - request.g._session = SessionDict(request, self.decode(session)) - return request.g._session - - def update(self, request, session): - """Update the user session. - - :param request: The client request. - :param session: A dictionary with the update session data for the user. - - Applications would normally not call this method directly, instead they - would use the :meth:`SessionDict.save` method on the session - dictionary, which calls this method. For example:: - - @app.route('/') - @with_session - def index(request, session): - session['foo'] = 'bar' - session.save() - return 'Hello, World!' - - Calling this method adds a cookie with the updated session to the - request currently being processed. - """ - if not self.secret_key: - raise ValueError('The session secret key is not configured') - - encoded_session = self.encode(session) - - @request.after_request - def _update_session(request, response): - response.set_cookie('session', encoded_session, - **self.cookie_options) - return response - - def delete(self, request): - """Remove the user session. - - :param request: The client request. - - Applications would normally not call this method directly, instead they - would use the :meth:`SessionDict.delete` method on the session - dictionary, which calls this method. For example:: - - @app.route('/') - @with_session - def index(request, session): - session.delete() - return 'Hello, World!' - - Calling this method adds a cookie removal header to the request - currently being processed. - """ - @request.after_request - def _delete_session(request, response): - response.delete_cookie('session', **self.cookie_options) - return response - - def encode(self, payload, secret_key=None): - """Encode session data using JWT if available, otherwise use simple HMAC.""" - if HAS_JWT: - return jwt.encode(payload, secret_key or self.secret_key, - algorithm='HS256') - else: - # Simple encoding for MicroPython: base64(json) + HMAC signature - key = (secret_key or self.secret_key).encode() if isinstance(secret_key or self.secret_key, str) else (secret_key or self.secret_key) - payload_json = json.dumps(payload) - payload_b64 = ubinascii.b2a_base64(payload_json.encode()).decode().strip() - - # Create HMAC signature - if hmac: - # Use hmac module if available - h = hmac.new(key, payload_json.encode(), hashlib.sha256) - else: - # Fallback: simple SHA256(key + message) - h = hashlib.sha256(key + payload_json.encode()) - signature = ubinascii.b2a_base64(h.digest()).decode().strip() - - return f"{payload_b64}.{signature}" - - def decode(self, session, secret_key=None): - """Decode session data using JWT if available, otherwise use simple HMAC.""" - if HAS_JWT: - try: - payload = jwt.decode(session, secret_key or self.secret_key, - algorithms=['HS256']) - except jwt.exceptions.PyJWTError: # pragma: no cover - return {} - return payload - else: - try: - # Simple decoding for MicroPython - if '.' not in session: - return {} - - payload_b64, signature = session.rsplit('.', 1) - payload_json = ubinascii.a2b_base64(payload_b64).decode() - - # Verify HMAC signature - key = (secret_key or self.secret_key).encode() if isinstance(secret_key or self.secret_key, str) else (secret_key or self.secret_key) - if hmac: - # Use hmac module if available - h = hmac.new(key, payload_json.encode(), hashlib.sha256) - else: - # Fallback: simple SHA256(key + message) - h = hashlib.sha256(key + payload_json.encode()) - expected_signature = ubinascii.b2a_base64(h.digest()).decode().strip() - - if signature != expected_signature: - return {} - - return json.loads(payload_json) - except Exception: - return {} - - -def with_session(f): - """Decorator that passes the user session to the route handler. - - The session dictionary is passed to the decorated function as an argument - after the request object. Example:: - - @app.route('/') - @with_session - def index(request, session): - return 'Hello, World!' - - Note that the decorator does not save the session. To update the session, - call the :func:`session.save() ` method. - """ - @wraps(f) - async def wrapper(request, *args, **kwargs): - return await invoke_handler( - f, request, request.app._session.get(request), *args, **kwargs) - - return wrapper diff --git a/lib/microdot/utemplate.py b/lib/microdot/utemplate.py deleted file mode 100644 index 16d0398..0000000 --- a/lib/microdot/utemplate.py +++ /dev/null @@ -1,70 +0,0 @@ -from utemplate import recompile - -_loader = None - - -class Template: - """A template object. - - :param template: The filename of the template to render, relative to the - configured template directory. - """ - @classmethod - def initialize(cls, template_dir='templates', - loader_class=recompile.Loader): - """Initialize the templating subsystem. - - :param template_dir: the directory where templates are stored. This - argument is optional. The default is to load - templates from a *templates* subdirectory. - :param loader_class: the ``utemplate.Loader`` class to use when loading - templates. This argument is optional. The default - is the ``recompile.Loader`` class, which - automatically recompiles templates when they - change. - """ - global _loader - _loader = loader_class(None, template_dir) - - def __init__(self, template): - if _loader is None: # pragma: no cover - self.initialize() - #: The name of the template - self.name = template - self.template = _loader.load(template) - - def generate(self, *args, **kwargs): - """Return a generator that renders the template in chunks, with the - given arguments.""" - return self.template(*args, **kwargs) - - def render(self, *args, **kwargs): - """Render the template with the given arguments and return it as a - string.""" - return ''.join(self.generate(*args, **kwargs)) - - def generate_async(self, *args, **kwargs): - """Return an asynchronous generator that renders the template in - chunks, using the given arguments.""" - class sync_to_async_iter(): - def __init__(self, iter): - self.iter = iter - - def __aiter__(self): - return self - - async def __anext__(self): - try: - return next(self.iter) - except StopIteration: - raise StopAsyncIteration - - return sync_to_async_iter(self.generate(*args, **kwargs)) - - async def render_async(self, *args, **kwargs): - """Render the template with the given arguments asynchronously and - return it as a string.""" - response = '' - async for chunk in self.generate_async(*args, **kwargs): - response += chunk - return response diff --git a/lib/microdot/websocket.py b/lib/microdot/websocket.py deleted file mode 100644 index 0fb6f7c..0000000 --- a/lib/microdot/websocket.py +++ /dev/null @@ -1,231 +0,0 @@ -import binascii -import hashlib -from microdot import Request, Response -from microdot.microdot import MUTED_SOCKET_ERRORS, print_exception -from microdot.helpers import wraps - - -class WebSocketError(Exception): - """Exception raised when an error occurs in a WebSocket connection.""" - pass - - -class WebSocket: - """A WebSocket connection object. - - An instance of this class is sent to handler functions to manage the - WebSocket connection. - """ - CONT = 0 - TEXT = 1 - BINARY = 2 - CLOSE = 8 - PING = 9 - PONG = 10 - - #: Specify the maximum message size that can be received when calling the - #: ``receive()`` method. Messages with payloads that are larger than this - #: size will be rejected and the connection closed. Set to 0 to disable - #: the size check (be aware of potential security issues if you do this), - #: or to -1 to use the value set in - #: ``Request.max_body_length``. The default is -1. - #: - #: Example:: - #: - #: WebSocket.max_message_length = 4 * 1024 # up to 4KB messages - max_message_length = -1 - - def __init__(self, request): - self.request = request - self.closed = False - - async def handshake(self): - response = self._handshake_response() - await self.request.sock[1].awrite( - b'HTTP/1.1 101 Switching Protocols\r\n') - await self.request.sock[1].awrite(b'Upgrade: websocket\r\n') - await self.request.sock[1].awrite(b'Connection: Upgrade\r\n') - await self.request.sock[1].awrite( - b'Sec-WebSocket-Accept: ' + response + b'\r\n\r\n') - - async def receive(self): - """Receive a message from the client.""" - while True: - opcode, payload = await self._read_frame() - send_opcode, data = self._process_websocket_frame(opcode, payload) - if send_opcode: # pragma: no cover - await self.send(data, send_opcode) - elif data: # pragma: no branch - return data - - async def send(self, data, opcode=None): - """Send a message to the client. - - :param data: the data to send, given as a string or bytes. - :param opcode: a custom frame opcode to use. If not given, the opcode - is ``TEXT`` or ``BINARY`` depending on the type of the - data. - """ - frame = self._encode_websocket_frame( - opcode or (self.TEXT if isinstance(data, str) else self.BINARY), - data) - await self.request.sock[1].awrite(frame) - - async def close(self): - """Close the websocket connection.""" - if not self.closed: # pragma: no cover - self.closed = True - await self.send(b'', self.CLOSE) - - def _handshake_response(self): - connection = False - upgrade = False - websocket_key = None - for header, value in self.request.headers.items(): - h = header.lower() - if h == 'connection': - connection = True - if 'upgrade' not in value.lower(): - return self.request.app.abort(400) - elif h == 'upgrade': - upgrade = True - if not value.lower() == 'websocket': - return self.request.app.abort(400) - elif h == 'sec-websocket-key': - websocket_key = value - if not connection or not upgrade or not websocket_key: - return self.request.app.abort(400) - d = hashlib.sha1(websocket_key.encode()) - d.update(b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11') - return binascii.b2a_base64(d.digest())[:-1] - - @classmethod - def _parse_frame_header(cls, header): - fin = header[0] & 0x80 - opcode = header[0] & 0x0f - if fin == 0 or opcode == cls.CONT: # pragma: no cover - raise WebSocketError('Continuation frames not supported') - has_mask = header[1] & 0x80 - length = header[1] & 0x7f - if length == 126: - length = -2 - elif length == 127: - length = -8 - return fin, opcode, has_mask, length - - def _process_websocket_frame(self, opcode, payload): - if opcode == self.TEXT: - payload = payload.decode() - elif opcode == self.BINARY: - pass - elif opcode == self.CLOSE: - raise WebSocketError('Websocket connection closed') - elif opcode == self.PING: - return self.PONG, payload - elif opcode == self.PONG: # pragma: no branch - return None, None - return None, payload - - @classmethod - def _encode_websocket_frame(cls, opcode, payload): - frame = bytearray() - frame.append(0x80 | opcode) - if opcode == cls.TEXT: - payload = payload.encode() - if len(payload) < 126: - frame.append(len(payload)) - elif len(payload) < (1 << 16): - frame.append(126) - frame.extend(len(payload).to_bytes(2, 'big')) - else: - frame.append(127) - frame.extend(len(payload).to_bytes(8, 'big')) - frame.extend(payload) - return frame - - async def _read_frame(self): - header = await self.request.sock[0].read(2) - if len(header) != 2: # pragma: no cover - raise WebSocketError('Websocket connection closed') - fin, opcode, has_mask, length = self._parse_frame_header(header) - if length == -2: - length = await self.request.sock[0].read(2) - length = int.from_bytes(length, 'big') - elif length == -8: - length = await self.request.sock[0].read(8) - length = int.from_bytes(length, 'big') - max_allowed_length = Request.max_body_length \ - if self.max_message_length == -1 else self.max_message_length - if length > max_allowed_length: - raise WebSocketError('Message too large') - if has_mask: # pragma: no cover - mask = await self.request.sock[0].read(4) - payload = await self.request.sock[0].read(length) - if has_mask: # pragma: no cover - payload = bytes(x ^ mask[i % 4] for i, x in enumerate(payload)) - return opcode, payload - - -async def websocket_upgrade(request): - """Upgrade a request handler to a websocket connection. - - This function can be called directly inside a route function to process a - WebSocket upgrade handshake, for example after the user's credentials are - verified. The function returns the websocket object:: - - @app.route('/echo') - async def echo(request): - if not authenticate_user(request): - abort(401) - ws = await websocket_upgrade(request) - while True: - message = await ws.receive() - await ws.send(message) - """ - ws = WebSocket(request) - await ws.handshake() - - @request.after_request - async def after_request(request, response): - return Response.already_handled - - return ws - - -def websocket_wrapper(f, upgrade_function): - @wraps(f) - async def wrapper(request, *args, **kwargs): - ws = await upgrade_function(request) - try: - await f(request, ws, *args, **kwargs) - except OSError as exc: - if exc.errno not in MUTED_SOCKET_ERRORS: # pragma: no cover - raise - except WebSocketError: - pass - except Exception as exc: - print_exception(exc) - finally: # pragma: no cover - try: - await ws.close() - except Exception: - pass - return Response.already_handled - return wrapper - - -def with_websocket(f): - """Decorator to make a route a WebSocket endpoint. - - This decorator is used to define a route that accepts websocket - connections. The route then receives a websocket object as a second - argument that it can use to send and receive messages:: - - @app.route('/echo') - @with_websocket - async def echo(request, ws): - while True: - message = await ws.receive() - await ws.send(message) - """ - return websocket_wrapper(f, websocket_upgrade) diff --git a/lib/utemplate/__init__.py b/lib/utemplate/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/lib/utemplate/compiled.py b/lib/utemplate/compiled.py deleted file mode 100644 index 006e6f5..0000000 --- a/lib/utemplate/compiled.py +++ /dev/null @@ -1,14 +0,0 @@ -class Loader: - - def __init__(self, pkg, dir): - if dir == ".": - dir = "" - else: - dir = dir.replace("/", ".") + "." - if pkg and pkg != "__main__": - dir = pkg + "." + dir - self.p = dir - - def load(self, name): - name = name.replace(".", "_") - return __import__(self.p + name, None, None, (name,)).render \ No newline at end of file diff --git a/lib/utemplate/recompile.py b/lib/utemplate/recompile.py deleted file mode 100644 index b9bae4e..0000000 --- a/lib/utemplate/recompile.py +++ /dev/null @@ -1,21 +0,0 @@ -# (c) 2014-2020 Paul Sokolovsky. MIT license. -try: - from uos import stat, remove -except: - from os import stat, remove -from . import source - - -class Loader(source.Loader): - - def load(self, name): - o_path = self.pkg_path + self.compiled_path(name) - i_path = self.pkg_path + self.dir + "/" + name - try: - o_stat = stat(o_path) - i_stat = stat(i_path) - if i_stat[8] > o_stat[8]: - # input file is newer, remove output to force recompile - remove(o_path) - finally: - return super().load(name) \ No newline at end of file diff --git a/lib/utemplate/source.py b/lib/utemplate/source.py deleted file mode 100644 index 0ff4651..0000000 --- a/lib/utemplate/source.py +++ /dev/null @@ -1,188 +0,0 @@ -# (c) 2014-2019 Paul Sokolovsky. MIT license. -from . import compiled - - -class Compiler: - - START_CHAR = "{" - STMNT = "%" - STMNT_END = "%}" - EXPR = "{" - EXPR_END = "}}" - - def __init__(self, file_in, file_out, indent=0, seq=0, loader=None): - self.file_in = file_in - self.file_out = file_out - self.loader = loader - self.seq = seq - self._indent = indent - self.stack = [] - self.in_literal = False - self.flushed_header = False - self.args = "*a, **d" - - def indent(self, adjust=0): - if not self.flushed_header: - self.flushed_header = True - self.indent() - self.file_out.write("def render%s(%s):\n" % (str(self.seq) if self.seq else "", self.args)) - self.stack.append("def") - self.file_out.write(" " * (len(self.stack) + self._indent + adjust)) - - def literal(self, s): - if not s: - return - if not self.in_literal: - self.indent() - self.file_out.write('yield """') - self.in_literal = True - self.file_out.write(s.replace('"', '\\"')) - - def close_literal(self): - if self.in_literal: - self.file_out.write('"""\n') - self.in_literal = False - - def render_expr(self, e): - self.indent() - self.file_out.write('yield str(' + e + ')\n') - - def parse_statement(self, stmt): - tokens = stmt.split(None, 1) - if tokens[0] == "args": - if len(tokens) > 1: - self.args = tokens[1] - else: - self.args = "" - elif tokens[0] == "set": - self.indent() - self.file_out.write(stmt[3:].strip() + "\n") - elif tokens[0] == "include": - if not self.flushed_header: - # If there was no other output, we still need a header now - self.indent() - tokens = tokens[1].split(None, 1) - args = "" - if len(tokens) > 1: - args = tokens[1] - if tokens[0][0] == "{": - self.indent() - # "1" as fromlist param is uPy hack - self.file_out.write('_ = __import__(%s.replace(".", "_"), None, None, 1)\n' % tokens[0][2:-2]) - self.indent() - self.file_out.write("yield from _.render(%s)\n" % args) - return - - with self.loader.input_open(tokens[0][1:-1]) as inc: - self.seq += 1 - c = Compiler(inc, self.file_out, len(self.stack) + self._indent, self.seq) - inc_id = self.seq - self.seq = c.compile() - self.indent() - self.file_out.write("yield from render%d(%s)\n" % (inc_id, args)) - elif len(tokens) > 1: - if tokens[0] == "elif": - assert self.stack[-1] == "if" - self.indent(-1) - self.file_out.write(stmt + ":\n") - else: - self.indent() - self.file_out.write(stmt + ":\n") - self.stack.append(tokens[0]) - else: - if stmt.startswith("end"): - assert self.stack[-1] == stmt[3:] - self.stack.pop(-1) - elif stmt == "else": - assert self.stack[-1] == "if" - self.indent(-1) - self.file_out.write("else:\n") - else: - assert False - - def parse_line(self, l): - while l: - start = l.find(self.START_CHAR) - if start == -1: - self.literal(l) - return - self.literal(l[:start]) - self.close_literal() - sel = l[start + 1] - #print("*%s=%s=" % (sel, EXPR)) - if sel == self.STMNT: - end = l.find(self.STMNT_END) - assert end > 0 - stmt = l[start + len(self.START_CHAR + self.STMNT):end].strip() - self.parse_statement(stmt) - end += len(self.STMNT_END) - l = l[end:] - if not self.in_literal and l == "\n": - break - elif sel == self.EXPR: - # print("EXPR") - end = l.find(self.EXPR_END) - assert end > 0 - expr = l[start + len(self.START_CHAR + self.EXPR):end].strip() - self.render_expr(expr) - end += len(self.EXPR_END) - l = l[end:] - else: - self.literal(l[start]) - l = l[start + 1:] - - def header(self): - self.file_out.write("# Autogenerated file\n") - - def compile(self): - self.header() - for l in self.file_in: - self.parse_line(l) - self.close_literal() - return self.seq - - -class Loader(compiled.Loader): - - def __init__(self, pkg, dir): - super().__init__(pkg, dir) - self.dir = dir - if pkg == "__main__": - # if pkg isn't really a package, don't bother to use it - # it means we're running from "filesystem directory", not - # from a package. - pkg = None - - self.pkg_path = "" - if pkg: - p = __import__(pkg) - if isinstance(p.__path__, str): - # uPy - self.pkg_path = p.__path__ - else: - # CPy - self.pkg_path = p.__path__[0] - self.pkg_path += "/" - - def input_open(self, template): - path = self.pkg_path + self.dir + "/" + template - return open(path) - - def compiled_path(self, template): - return self.dir + "/" + template.replace(".", "_") + ".py" - - def load(self, name): - try: - return super().load(name) - except (OSError, ImportError): - pass - - compiled_path = self.pkg_path + self.compiled_path(name) - - f_in = self.input_open(name) - f_out = open(compiled_path, "w") - c = Compiler(f_in, f_out, loader=self) - c.compile() - f_in.close() - f_out.close() - return super().load(name) \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml deleted file mode 100644 index 6d1f643..0000000 --- a/pyproject.toml +++ /dev/null @@ -1,3 +0,0 @@ -[tool.pytest.ini_options] -testpaths = ["tests"] -python_files = ["test_endpoints_pytest.py", "engine_tests/test_*.py"] diff --git a/scripts/dev-run.sh b/scripts/dev-run.sh deleted file mode 100644 index 8d183bc..0000000 --- a/scripts/dev-run.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/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 diff --git a/scripts/install-boot-service.sh b/scripts/install-boot-service.sh deleted file mode 100755 index 2474eee..0000000 --- a/scripts/install-boot-service.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env bash -# Install systemd service so LED controller starts at boot. -# Run once: sudo scripts/install-boot-service.sh -set -e -cd "$(dirname "$0")/.." -REPO="$(pwd)" -SERVICE_NAME="led-controller.service" -UNIT_PATH="/etc/systemd/system/$SERVICE_NAME" -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 -sudo systemctl enable "$SERVICE_NAME" -echo "Installed and enabled $SERVICE_NAME" -echo "Start now: sudo systemctl start $SERVICE_NAME" -echo "Status: sudo systemctl status $SERVICE_NAME" -echo "Logs: journalctl -u $SERVICE_NAME -f" diff --git a/scripts/led-controller.service b/scripts/led-controller.service deleted file mode 100644 index 8ea489b..0000000 --- a/scripts/led-controller.service +++ /dev/null @@ -1,20 +0,0 @@ -[Unit] -Description=LED Controller web server -# 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 -User=pi -WorkingDirectory=/home/pi/led-controller -Environment=PORT=80 -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 diff --git a/scripts/led-test/.gitignore b/scripts/led-test/.gitignore new file mode 100644 index 0000000..567609b --- /dev/null +++ b/scripts/led-test/.gitignore @@ -0,0 +1 @@ +build/ diff --git a/scripts/led-test/CMakeLists.txt b/scripts/led-test/CMakeLists.txt new file mode 100644 index 0000000..7d22ea6 --- /dev/null +++ b/scripts/led-test/CMakeLists.txt @@ -0,0 +1,3 @@ +cmake_minimum_required(VERSION 3.16) +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(led_test) diff --git a/scripts/led-test/dependencies.lock b/scripts/led-test/dependencies.lock new file mode 100644 index 0000000..1a4adf4 --- /dev/null +++ b/scripts/led-test/dependencies.lock @@ -0,0 +1,20 @@ +dependencies: + espressif/led_strip: + component_hash: 28c6509a727ef74925b372ed404772aeedf11cce10b78c3f69b3c66799095e2d + dependencies: + - name: idf + require: private + version: '>=4.4' + source: + registry_url: https://components.espressif.com/ + type: service + version: 2.5.5 + idf: + source: + type: idf + version: 5.5.5 +direct_dependencies: +- espressif/led_strip +manifest_hash: 08e0dee6eca83e7d8d73c22998d68a19eb9f0d1566cff539c1124b10b36f26e6 +target: esp32c3 +version: 2.0.0 diff --git a/scripts/led-test/main/CMakeLists.txt b/scripts/led-test/main/CMakeLists.txt new file mode 100644 index 0000000..52a3b94 --- /dev/null +++ b/scripts/led-test/main/CMakeLists.txt @@ -0,0 +1 @@ +idf_component_register(SRCS "main.c" INCLUDE_DIRS ".") diff --git a/scripts/led-test/main/idf_component.yml b/scripts/led-test/main/idf_component.yml new file mode 100644 index 0000000..34c4239 --- /dev/null +++ b/scripts/led-test/main/idf_component.yml @@ -0,0 +1,2 @@ +dependencies: + espressif/led_strip: "^2.5.0" diff --git a/scripts/led-test/main/main.c b/scripts/led-test/main/main.c new file mode 100644 index 0000000..f8a28c1 --- /dev/null +++ b/scripts/led-test/main/main.c @@ -0,0 +1,29 @@ +// Steady WS2812 signal on GPIO 10 for probing with a meter: the first 10 LEDs green, a frame +// every 20 ms so the pin never idles. The data pin should read roughly 0.3-1 V DC against GND. +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "led_strip.h" +#include "esp_log.h" + +#define LED_GPIO 10 +#define NUM_LEDS 200 +#define LIT 10 + +static const char *TAG = "led_test"; + +void app_main(void) +{ + led_strip_handle_t strip; + led_strip_config_t cfg = { .strip_gpio_num = LED_GPIO, .max_leds = NUM_LEDS }; + led_strip_rmt_config_t rmt = { .resolution_hz = 10 * 1000 * 1000 }; + ESP_ERROR_CHECK(led_strip_new_rmt_device(&cfg, &rmt, &strip)); + for (int i = 0; i < LIT; i++) + led_strip_set_pixel(strip, i, 0, 120, 0); + ESP_LOGI(TAG, "sending to GPIO %d continuously", LED_GPIO); + for (unsigned n = 0;; n++) { + led_strip_refresh(strip); + if (n % 250 == 0) + ESP_LOGI(TAG, "frames sent: %u", n); + vTaskDelay(pdMS_TO_TICKS(20)); + } +} diff --git a/scripts/led-test/managed_components/espressif__led_strip/.component_hash b/scripts/led-test/managed_components/espressif__led_strip/.component_hash new file mode 100644 index 0000000..f9d6fcb --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/.component_hash @@ -0,0 +1 @@ +28c6509a727ef74925b372ed404772aeedf11cce10b78c3f69b3c66799095e2d \ No newline at end of file diff --git a/scripts/led-test/managed_components/espressif__led_strip/CHANGELOG.md b/scripts/led-test/managed_components/espressif__led_strip/CHANGELOG.md new file mode 100644 index 0000000..66906b6 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/CHANGELOG.md @@ -0,0 +1,54 @@ +## 2.5.5 + +- Simplified the led_strip component dependency, the time of full build with ESP-IDF v5.3 can now be shorter. + +## 2.5.4 + +- Inserted extra delay when initialize the SPI LED device, to ensure all LEDs are in the reset state correctly + +## 2.5.3 + +- Extend reset time (280us) to support WS2812B-V5 + +## 2.5.2 + +- Added API reference doc (api.md) + +## 2.5.0 + +- Enabled support for IDF4.4 and above + - with RMT backend only +- Added API `led_strip_set_pixel_hsv` + +## 2.4.0 + +- Support configurable SPI mode to control leds + - recommend enabling DMA when using SPI mode + +## 2.3.0 + +- Support configurable RMT channel size by setting `mem_block_symbols` + +## 2.2.0 + +- Support for 4 components RGBW leds (SK6812): + - in led_strip_config_t new fields + led_pixel_format, controlling byte format (LED_PIXEL_FORMAT_GRB, LED_PIXEL_FORMAT_GRBW) + led_model, used to configure bit timing (LED_MODEL_WS2812, LED_MODEL_SK6812) + - new API led_strip_set_pixel_rgbw + - new interface type set_pixel_rgbw + +## 2.1.0 + +- Support DMA feature, which offloads the CPU by a lot when it comes to drive a bunch of LEDs +- Support various RMT clock sources +- Acquire and release the power management lock before and after each refresh +- New driver flag: `invert_out` which can invert the led control signal by hardware + +## 2.0.0 + +- Reimplemented the driver using the new RMT driver (`driver/rmt_tx.h`) + +## 1.0.0 + +- Initial driver version, based on the legacy RMT driver (`driver/rmt.h`) diff --git a/scripts/led-test/managed_components/espressif__led_strip/CHECKSUMS.json b/scripts/led-test/managed_components/espressif__led_strip/CHECKSUMS.json new file mode 100644 index 0000000..a6d2ae5 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/CHECKSUMS.json @@ -0,0 +1 @@ +{"version": "1.0", "algorithm": "sha256", "created_at": "2025-05-21T16:14:59.641729+00:00", "files": [{"path": "CMakeLists.txt", "size": 1131, "hash": "527e1c93841dcf98e4e30767c0b55ec117e1af52638eb72a7aec23d25a31074b"}, {"path": "api.md", "size": 12932, "hash": "fa49f00d63cab790d2e3ffb1cc2436ec337fab336f55a8c2730aa1d923b655e4"}, {"path": "LICENSE", "size": 11358, "hash": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"}, {"path": "CHANGELOG.md", "size": 1469, "hash": "8f323462bb2f1c0159b2e2c5fef08628d47a7ff55ef9829221889c2486bbfad8"}, {"path": "idf_component.yml", "size": 335, "hash": "12ff580cba4f58c8c41cff96d0c81bc001d40d99ad15ba16afabce64261d4b8a"}, {"path": "README.md", "size": 4920, "hash": "f94c5b61f704ec6247450b3252e35b6130b5350edff560dd172f3a7345fac637"}, {"path": "Doxyfile", "size": 684, "hash": "f05e35d4108be9b46398fbd7c0cef9880c0e802abbe36a36a49c7a0ac4126826"}, {"path": "interface/led_strip_interface.h", "size": 2934, "hash": "5b7d0c326d0d0d9748830d4aec46d765400e1446055d4a1197c83111e937d74c"}, {"path": "include/led_strip_spi.h", "size": 1596, "hash": "d79f3a803834ff28930a32380a48afe0977de167d31d673589e98c2a3cf66e5f"}, {"path": "include/led_strip_types.h", "size": 1352, "hash": "13fb81ed62bcaa6d8686c5b095c45adede526bcba3980ad0f9341c38b4bedc96"}, {"path": "include/led_strip_rmt.h", "size": 1876, "hash": "d3d6f0880f7443c21b48c1715e524282688ce9743085b4d7358322f6714b82d2"}, {"path": "include/led_strip.h", "size": 3586, "hash": "f01e0f282fe3042b03381495c616eae211d0b75d04c64e29b3dc92721fbadc4f"}, {"path": "src/led_strip_spi_dev.c", "size": 9346, "hash": "bff2b2e1dc3240d21b1679fba42f0f4395bf9449b21ee3c2408bbc1ae1b9c211"}, {"path": "src/led_strip_rmt_encoder.h", "size": 977, "hash": "690381c35ace2703a5c7156f6547a8524f4cbfe5bef40be619e2097960120a40"}, {"path": "src/led_strip_rmt_dev_idf4.c", "size": 7143, "hash": "81b4a239b554f1ed3326b5380490316a9602bc606a00691a5f325adcbdf2145c"}, {"path": "src/led_strip_api.c", "size": 2575, "hash": "2a8be1284ed6b2ad000907bca3829f71a499aa0d06d47f078d6306392dcc4f4c"}, {"path": "src/led_strip_rmt_encoder.c", "size": 6097, "hash": "7e349a50bd3a161932200dd3da24a6e7316438e0e31615aed6d20deeb3917558"}, {"path": "src/led_strip_rmt_dev.c", "size": 6885, "hash": "3a41df64f2582f3abedd4bddf3111a6bba4a1f886d58dd8391ac2b903ea82e9f"}, {"path": "examples/led_strip_rmt_ws2812/CMakeLists.txt", "size": 381, "hash": "26a31ebd66ad328361d8b69d7f99b9250685932d077dc300dc96280ff6623bc4"}, {"path": "examples/led_strip_rmt_ws2812/README.md", "size": 1200, "hash": "a5f39b31c5f7cbf548ee31b61ab22e430a6c823404c0ddb113703512bcb3ad3c"}, {"path": "examples/led_strip_spi_ws2812/CMakeLists.txt", "size": 381, "hash": "3096c4f9363c9ccf5733c19542163dcb4497764435fb996156552b81c55c6e14"}, {"path": "examples/led_strip_spi_ws2812/README.md", "size": 1201, "hash": "2c02a29197cd1f2d4af4c4c9cd44677e303b0e168a1773eef9fc3fdb39377d27"}, {"path": "examples/led_strip_spi_ws2812/main/CMakeLists.txt", "size": 99, "hash": "34e7f83d26bca924c629ea2012e6f200b415d486907863fe936d94872ff739eb"}, {"path": "examples/led_strip_spi_ws2812/main/idf_component.yml", "size": 142, "hash": "fe89054a1b7988a7068a2952d01bfc6ae40dc59a33bc7dcc8a98cbb231d472fb"}, {"path": "examples/led_strip_spi_ws2812/main/led_strip_spi_ws2812_main.c", "size": 2462, "hash": "8e052cbfd7e27d5e3382f5f115db23ea884db25f4a73fb69d34ed4867dfbf80a"}, {"path": "examples/led_strip_rmt_ws2812/main/CMakeLists.txt", "size": 99, "hash": "8960b68811805d3aa40e1a7f44ddf7400c0d0731829b6d2b3b1584d8dcd3b392"}, {"path": "examples/led_strip_rmt_ws2812/main/idf_component.yml", "size": 125, "hash": "05a57e3d6808bac9e1a2f41cbcfa26d90b5a3427d518b619a1ff4946e62d791d"}, {"path": "examples/led_strip_rmt_ws2812/main/led_strip_rmt_ws2812_main.c", "size": 2705, "hash": "497f3b88387865c41f7a30c7ab5e0086066a344bf16f250d973bf0af907fa78f"}]} \ No newline at end of file diff --git a/scripts/led-test/managed_components/espressif__led_strip/CMakeLists.txt b/scripts/led-test/managed_components/espressif__led_strip/CMakeLists.txt new file mode 100644 index 0000000..a4e576b --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/CMakeLists.txt @@ -0,0 +1,31 @@ +include($ENV{IDF_PATH}/tools/cmake/version.cmake) + +set(srcs "src/led_strip_api.c") +set(public_requires) + +# Starting from esp-idf v5.x, the RMT driver is rewritten +if("${IDF_VERSION_MAJOR}.${IDF_VERSION_MINOR}" VERSION_GREATER_EQUAL "5.0") + if(CONFIG_SOC_RMT_SUPPORTED) + list(APPEND srcs "src/led_strip_rmt_dev.c" "src/led_strip_rmt_encoder.c") + endif() +else() + list(APPEND srcs "src/led_strip_rmt_dev_idf4.c") +endif() + +# the SPI backend driver relies on some feature that was available in IDF 5.1 +if("${IDF_VERSION_MAJOR}.${IDF_VERSION_MINOR}" VERSION_GREATER_EQUAL "5.1") + if(CONFIG_SOC_GPSPI_SUPPORTED) + list(APPEND srcs "src/led_strip_spi_dev.c") + endif() +endif() + +# Starting from esp-idf v5.3, the RMT and SPI drivers are moved to separate components +if("${IDF_VERSION_MAJOR}.${IDF_VERSION_MINOR}" VERSION_GREATER_EQUAL "5.3") + list(APPEND public_requires "esp_driver_rmt" "esp_driver_spi") +else() + list(APPEND public_requires "driver") +endif() + +idf_component_register(SRCS ${srcs} + INCLUDE_DIRS "include" "interface" + REQUIRES ${public_requires}) diff --git a/scripts/led-test/managed_components/espressif__led_strip/Doxyfile b/scripts/led-test/managed_components/espressif__led_strip/Doxyfile new file mode 100644 index 0000000..285d853 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/Doxyfile @@ -0,0 +1,28 @@ +# Set this to the header file you want +INPUT = \ + include/ \ + interface/ + +# Output goes into doxygen directory, which is added to gitignore +OUTPUT_DIRECTORY = doxygen + +# Warning-related settings, it's recommended to keep them enabled +WARN_IF_UNDOC_ENUM_VAL = YES +WARN_AS_ERROR = YES + +# Other common settings +FULL_PATH_NAMES = YES +ENABLE_PREPROCESSING = YES +MACRO_EXPANSION = YES +OPTIMIZE_OUTPUT_FOR_C = YES +EXPAND_ONLY_PREDEF = YES +EXTRACT_ALL = YES +PREDEFINED = $(ENV_DOXYGEN_DEFINES) +HAVE_DOT = NO +GENERATE_XML = YES +XML_OUTPUT = xml +GENERATE_HTML = NO +HAVE_DOT = NO +GENERATE_LATEX = NO +QUIET = YES +MARKDOWN_SUPPORT = YES \ No newline at end of file diff --git a/scripts/led-test/managed_components/espressif__led_strip/LICENSE b/scripts/led-test/managed_components/espressif__led_strip/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/scripts/led-test/managed_components/espressif__led_strip/README.md b/scripts/led-test/managed_components/espressif__led_strip/README.md new file mode 100644 index 0000000..bb08cca --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/README.md @@ -0,0 +1,97 @@ +# LED Strip Driver + +[![Component Registry](https://components.espressif.com/components/espressif/led_strip/badge.svg)](https://components.espressif.com/components/espressif/led_strip) + +This driver is designed for addressable LEDs like [WS2812](http://www.world-semi.com/Certifications/WS2812B.html), where each LED is controlled by a single data line. + +## Backend Controllers + +### The [RMT](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/rmt.html) Peripheral + +This is the most economical way to drive the LEDs because it only consumes one RMT channel, leaving other channels free to use. However, the memory usage increases dramatically with the number of LEDs. If the RMT hardware can't be assist by DMA, the driver will going into interrupt very frequently, thus result in a high CPU usage. What's worse, if the RMT interrupt is delayed or not serviced in time (e.g. if Wi-Fi interrupt happens on the same CPU core), the RMT transaction will be corrupted and the LEDs will display incorrect colors. If you want to use RMT to drive a large number of LEDs, you'd better to enable the DMA feature if possible [^1]. + +#### Allocate LED Strip Object with RMT Backend + +```c +#define BLINK_GPIO 0 + +led_strip_handle_t led_strip; + +/* LED strip initialization with the GPIO and pixels number*/ +led_strip_config_t strip_config = { + .strip_gpio_num = BLINK_GPIO, // The GPIO that connected to the LED strip's data line + .max_leds = 1, // The number of LEDs in the strip, + .led_pixel_format = LED_PIXEL_FORMAT_GRB, // Pixel format of your LED strip + .led_model = LED_MODEL_WS2812, // LED strip model + .flags.invert_out = false, // whether to invert the output signal (useful when your hardware has a level inverter) +}; + +led_strip_rmt_config_t rmt_config = { +#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0) + .rmt_channel = 0, +#else + .clk_src = RMT_CLK_SRC_DEFAULT, // different clock source can lead to different power consumption + .resolution_hz = 10 * 1000 * 1000, // 10MHz + .flags.with_dma = false, // whether to enable the DMA feature +#endif +}; +ESP_ERROR_CHECK(led_strip_new_rmt_device(&strip_config, &rmt_config, &led_strip)); +``` + +You can create multiple LED strip objects with different GPIOs and pixel numbers. The backend driver will automatically allocate the RMT channel for you if there is more available. + +### The [SPI](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/spi_master.html) Peripheral + +SPI peripheral can also be used to generate the timing required by the LED strip. However this backend is not as economical as the RMT one, because it will take up the whole **bus**, unlike the RMT just takes one **channel**. You **CANT** connect other devices to the same SPI bus if it's been used by the led_strip, because the led_strip doesn't have the concept of "Chip Select". + +Please note, the SPI backend has a dependency of **ESP-IDF >= 5.1** + +#### Allocate LED Strip Object with SPI Backend + +```c +#define BLINK_GPIO 0 + +led_strip_handle_t led_strip; + +/* LED strip initialization with the GPIO and pixels number*/ +led_strip_config_t strip_config = { + .strip_gpio_num = BLINK_GPIO, // The GPIO that connected to the LED strip's data line + .max_leds = 1, // The number of LEDs in the strip, + .led_pixel_format = LED_PIXEL_FORMAT_GRB, // Pixel format of your LED strip + .led_model = LED_MODEL_WS2812, // LED strip model + .flags.invert_out = false, // whether to invert the output signal (useful when your hardware has a level inverter) +}; + +led_strip_spi_config_t spi_config = { + .clk_src = SPI_CLK_SRC_DEFAULT, // different clock source can lead to different power consumption + .flags.with_dma = true, // Using DMA can improve performance and help drive more LEDs + .spi_bus = SPI2_HOST, // SPI bus ID +}; +ESP_ERROR_CHECK(led_strip_new_spi_device(&strip_config, &spi_config, &led_strip)); +``` + +The number of LED strip objects can be created depends on how many free SPI buses are free to use in your project. + +## FAQ + +* Which led_strip backend should I choose? + * It depends on your application requirement and target chip's ability. + + ```mermaid + flowchart LR + A{Is RMT supported?} + A --> |No| B[SPI backend] + B --> C{Does the led strip has \n a larger number of LEDs?} + C --> |No| D[Don't have to enable the DMA of the backend] + C --> |Yes| E[Enable the DMA of the backend] + A --> |Yes| F{Does the led strip has \n a larger number of LEDs?} + F --> |Yes| G{Does RMT support DMA?} + G --> |Yes| E + G --> |No| B + F --> |No| H[RMT backend] --> D + ``` + +* How to set the brightness of the LED strip? + * You can tune the brightness by scaling the value of each R-G-B element with a **same** factor. But pay attention to the overflow of the value. + +[^1]: The RMT DMA feature is not available on all ESP chips. Please check the data sheet before using it. diff --git a/scripts/led-test/managed_components/espressif__led_strip/api.md b/scripts/led-test/managed_components/espressif__led_strip/api.md new file mode 100644 index 0000000..8fc04af --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/api.md @@ -0,0 +1,454 @@ +# API Reference + +## Header files + +- [include/led_strip.h](#file-includeled_striph) +- [include/led_strip_rmt.h](#file-includeled_strip_rmth) +- [include/led_strip_spi.h](#file-includeled_strip_spih) +- [include/led_strip_types.h](#file-includeled_strip_typesh) +- [interface/led_strip_interface.h](#file-interfaceled_strip_interfaceh) + +## File include/led_strip.h + +## Functions + +| Type | Name | +| ---: | :--- | +| esp\_err\_t | [**led\_strip\_clear**](#function-led_strip_clear) ([**led\_strip\_handle\_t**](#typedef-led_strip_handle_t) strip)
_Clear LED strip (turn off all LEDs)_ | +| esp\_err\_t | [**led\_strip\_del**](#function-led_strip_del) ([**led\_strip\_handle\_t**](#typedef-led_strip_handle_t) strip)
_Free LED strip resources._ | +| esp\_err\_t | [**led\_strip\_refresh**](#function-led_strip_refresh) ([**led\_strip\_handle\_t**](#typedef-led_strip_handle_t) strip)
_Refresh memory colors to LEDs._ | +| esp\_err\_t | [**led\_strip\_set\_pixel**](#function-led_strip_set_pixel) ([**led\_strip\_handle\_t**](#typedef-led_strip_handle_t) strip, uint32\_t index, uint32\_t red, uint32\_t green, uint32\_t blue)
_Set RGB for a specific pixel._ | +| esp\_err\_t | [**led\_strip\_set\_pixel\_hsv**](#function-led_strip_set_pixel_hsv) ([**led\_strip\_handle\_t**](#typedef-led_strip_handle_t) strip, uint32\_t index, uint16\_t hue, uint8\_t saturation, uint8\_t value)
_Set HSV for a specific pixel._ | +| esp\_err\_t | [**led\_strip\_set\_pixel\_rgbw**](#function-led_strip_set_pixel_rgbw) ([**led\_strip\_handle\_t**](#typedef-led_strip_handle_t) strip, uint32\_t index, uint32\_t red, uint32\_t green, uint32\_t blue, uint32\_t white)
_Set RGBW for a specific pixel._ | + +## Functions Documentation + +### function `led_strip_clear` + +_Clear LED strip (turn off all LEDs)_ + +```c +esp_err_t led_strip_clear ( + led_strip_handle_t strip +) +``` + +**Parameters:** + +- `strip` LED strip + +**Returns:** + +- ESP\_OK: Clear LEDs successfully +- ESP\_FAIL: Clear LEDs failed because some other error occurred + +### function `led_strip_del` + +_Free LED strip resources._ + +```c +esp_err_t led_strip_del ( + led_strip_handle_t strip +) +``` + +**Parameters:** + +- `strip` LED strip + +**Returns:** + +- ESP\_OK: Free resources successfully +- ESP\_FAIL: Free resources failed because error occurred + +### function `led_strip_refresh` + +_Refresh memory colors to LEDs._ + +```c +esp_err_t led_strip_refresh ( + led_strip_handle_t strip +) +``` + +**Parameters:** + +- `strip` LED strip + +**Returns:** + +- ESP\_OK: Refresh successfully +- ESP\_FAIL: Refresh failed because some other error occurred + +**Note:** + +: After updating the LED colors in the memory, a following invocation of this API is needed to flush colors to strip. + +### function `led_strip_set_pixel` + +_Set RGB for a specific pixel._ + +```c +esp_err_t led_strip_set_pixel ( + led_strip_handle_t strip, + uint32_t index, + uint32_t red, + uint32_t green, + uint32_t blue +) +``` + +**Parameters:** + +- `strip` LED strip +- `index` index of pixel to set +- `red` red part of color +- `green` green part of color +- `blue` blue part of color + +**Returns:** + +- ESP\_OK: Set RGB for a specific pixel successfully +- ESP\_ERR\_INVALID\_ARG: Set RGB for a specific pixel failed because of invalid parameters +- ESP\_FAIL: Set RGB for a specific pixel failed because other error occurred + +### function `led_strip_set_pixel_hsv` + +_Set HSV for a specific pixel._ + +```c +esp_err_t led_strip_set_pixel_hsv ( + led_strip_handle_t strip, + uint32_t index, + uint16_t hue, + uint8_t saturation, + uint8_t value +) +``` + +**Parameters:** + +- `strip` LED strip +- `index` index of pixel to set +- `hue` hue part of color (0 - 360) +- `saturation` saturation part of color (0 - 255, rescaled from 0 - 1. e.g. saturation = 0.5, rescaled to 127) +- `value` value part of color (0 - 255, rescaled from 0 - 1. e.g. value = 0.5, rescaled to 127) + +**Returns:** + +- ESP\_OK: Set HSV color for a specific pixel successfully +- ESP\_ERR\_INVALID\_ARG: Set HSV color for a specific pixel failed because of an invalid argument +- ESP\_FAIL: Set HSV color for a specific pixel failed because other error occurred + +### function `led_strip_set_pixel_rgbw` + +_Set RGBW for a specific pixel._ + +```c +esp_err_t led_strip_set_pixel_rgbw ( + led_strip_handle_t strip, + uint32_t index, + uint32_t red, + uint32_t green, + uint32_t blue, + uint32_t white +) +``` + +**Note:** + +Only call this function if your led strip does have the white component (e.g. SK6812-RGBW) + +**Note:** + +Also see `led_strip_set_pixel` if you only want to specify the RGB part of the color and bypass the white component + +**Parameters:** + +- `strip` LED strip +- `index` index of pixel to set +- `red` red part of color +- `green` green part of color +- `blue` blue part of color +- `white` separate white component + +**Returns:** + +- ESP\_OK: Set RGBW color for a specific pixel successfully +- ESP\_ERR\_INVALID\_ARG: Set RGBW color for a specific pixel failed because of an invalid argument +- ESP\_FAIL: Set RGBW color for a specific pixel failed because other error occurred + +## File include/led_strip_rmt.h + +## Structures and Types + +| Type | Name | +| ---: | :--- | +| struct | [**led\_strip\_rmt\_config\_t**](#struct-led_strip_rmt_config_t)
_LED Strip RMT specific configuration._ | + +## Functions + +| Type | Name | +| ---: | :--- | +| esp\_err\_t | [**led\_strip\_new\_rmt\_device**](#function-led_strip_new_rmt_device) (const [**led\_strip\_config\_t**](#struct-led_strip_config_t) \*led\_config, const [**led\_strip\_rmt\_config\_t**](#struct-led_strip_rmt_config_t) \*rmt\_config, [**led\_strip\_handle\_t**](#typedef-led_strip_handle_t) \*ret\_strip)
_Create LED strip based on RMT TX channel._ | + +## Structures and Types Documentation + +### struct `led_strip_rmt_config_t` + +_LED Strip RMT specific configuration._ + +Variables: + +- rmt\_clock\_source\_t clk_src
RMT clock source + +- struct led\_strip\_rmt\_config\_t::@0 flags
Extra driver flags + +- size\_t mem_block_symbols
How many RMT symbols can one RMT channel hold at one time. Set to 0 will fallback to use the default size. + +- uint32\_t resolution_hz
RMT tick resolution, if set to zero, a default resolution (10MHz) will be applied + +- uint32\_t with_dma
Use DMA to transmit data + +## Functions Documentation + +### function `led_strip_new_rmt_device` + +_Create LED strip based on RMT TX channel._ + +```c +esp_err_t led_strip_new_rmt_device ( + const led_strip_config_t *led_config, + const led_strip_rmt_config_t *rmt_config, + led_strip_handle_t *ret_strip +) +``` + +**Parameters:** + +- `led_config` LED strip configuration +- `rmt_config` RMT specific configuration +- `ret_strip` Returned LED strip handle + +**Returns:** + +- ESP\_OK: create LED strip handle successfully +- ESP\_ERR\_INVALID\_ARG: create LED strip handle failed because of invalid argument +- ESP\_ERR\_NO\_MEM: create LED strip handle failed because of out of memory +- ESP\_FAIL: create LED strip handle failed because some other error + +## File include/led_strip_spi.h + +## Structures and Types + +| Type | Name | +| ---: | :--- | +| struct | [**led\_strip\_spi\_config\_t**](#struct-led_strip_spi_config_t)
_LED Strip SPI specific configuration._ | + +## Functions + +| Type | Name | +| ---: | :--- | +| esp\_err\_t | [**led\_strip\_new\_spi\_device**](#function-led_strip_new_spi_device) (const [**led\_strip\_config\_t**](#struct-led_strip_config_t) \*led\_config, const [**led\_strip\_spi\_config\_t**](#struct-led_strip_spi_config_t) \*spi\_config, [**led\_strip\_handle\_t**](#typedef-led_strip_handle_t) \*ret\_strip)
_Create LED strip based on SPI MOSI channel._ | + +## Structures and Types Documentation + +### struct `led_strip_spi_config_t` + +_LED Strip SPI specific configuration._ + +Variables: + +- spi\_clock\_source\_t clk_src
SPI clock source + +- struct led\_strip\_spi\_config\_t::@1 flags
Extra driver flags + +- spi\_host\_device\_t spi_bus
SPI bus ID. Which buses are available depends on the specific chip + +- uint32\_t with_dma
Use DMA to transmit data + +## Functions Documentation + +### function `led_strip_new_spi_device` + +_Create LED strip based on SPI MOSI channel._ + +```c +esp_err_t led_strip_new_spi_device ( + const led_strip_config_t *led_config, + const led_strip_spi_config_t *spi_config, + led_strip_handle_t *ret_strip +) +``` + +**Note:** + +Although only the MOSI line is used for generating the signal, the whole SPI bus can't be used for other purposes. + +**Parameters:** + +- `led_config` LED strip configuration +- `spi_config` SPI specific configuration +- `ret_strip` Returned LED strip handle + +**Returns:** + +- ESP\_OK: create LED strip handle successfully +- ESP\_ERR\_INVALID\_ARG: create LED strip handle failed because of invalid argument +- ESP\_ERR\_NOT\_SUPPORTED: create LED strip handle failed because of unsupported configuration +- ESP\_ERR\_NO\_MEM: create LED strip handle failed because of out of memory +- ESP\_FAIL: create LED strip handle failed because some other error + +## File include/led_strip_types.h + +## Structures and Types + +| Type | Name | +| ---: | :--- | +| enum | [**led\_model\_t**](#enum-led_model_t)
_LED strip model._ | +| enum | [**led\_pixel\_format\_t**](#enum-led_pixel_format_t)
_LED strip pixel format._ | +| struct | [**led\_strip\_config\_t**](#struct-led_strip_config_t)
_LED Strip Configuration._ | +| typedef struct [**led\_strip\_t**](#struct-led_strip_t) \* | [**led\_strip\_handle\_t**](#typedef-led_strip_handle_t)
_LED strip handle._ | + +## Structures and Types Documentation + +### enum `led_model_t` + +_LED strip model._ + +```c +enum led_model_t { + LED_MODEL_WS2812, + LED_MODEL_SK6812, + LED_MODEL_INVALID +}; +``` + +**Note:** + +Different led model may have different timing parameters, so we need to distinguish them. + +### enum `led_pixel_format_t` + +_LED strip pixel format._ + +```c +enum led_pixel_format_t { + LED_PIXEL_FORMAT_GRB, + LED_PIXEL_FORMAT_GRBW, + LED_PIXEL_FORMAT_INVALID +}; +``` + +### struct `led_strip_config_t` + +_LED Strip Configuration._ + +Variables: + +- struct led\_strip\_config\_t::@2 flags
Extra driver flags + +- uint32\_t invert_out
Invert output signal + +- [**led\_model\_t**](#enum-led_model_t) led_model
LED model + +- [**led\_pixel\_format\_t**](#enum-led_pixel_format_t) led_pixel_format
LED pixel format + +- uint32\_t max_leds
Maximum LEDs in a single strip + +- int strip_gpio_num
GPIO number that used by LED strip + +### typedef `led_strip_handle_t` + +_LED strip handle._ + +```c +typedef struct led_strip_t* led_strip_handle_t; +``` + +## File interface/led_strip_interface.h + +## Structures and Types + +| Type | Name | +| ---: | :--- | +| struct | [**led\_strip\_t**](#struct-led_strip_t)
_LED strip interface definition._ | +| typedef struct [**led\_strip\_t**](#struct-led_strip_t) | [**led\_strip\_t**](#typedef-led_strip_t)
| + +## Structures and Types Documentation + +### struct `led_strip_t` + +_LED strip interface definition._ + +Variables: + +- esp\_err\_t(\* clear
_Clear LED strip (turn off all LEDs)_
**Parameters:** + +- `strip` LED strip +- `timeout_ms` timeout value for clearing task + +**Returns:** + +- ESP\_OK: Clear LEDs successfully +- ESP\_FAIL: Clear LEDs failed because some other error occurred + +- esp\_err\_t(\* del
_Free LED strip resources._
**Parameters:** + +- `strip` LED strip + +**Returns:** + +- ESP\_OK: Free resources successfully +- ESP\_FAIL: Free resources failed because error occurred + +- esp\_err\_t(\* refresh
_Refresh memory colors to LEDs._
**Parameters:** + +- `strip` LED strip +- `timeout_ms` timeout value for refreshing task + +**Returns:** + +- ESP\_OK: Refresh successfully +- ESP\_FAIL: Refresh failed because some other error occurred + +**Note:** + +: After updating the LED colors in the memory, a following invocation of this API is needed to flush colors to strip. + +- esp\_err\_t(\* set_pixel
_Set RGB for a specific pixel._
**Parameters:** + +- `strip` LED strip +- `index` index of pixel to set +- `red` red part of color +- `green` green part of color +- `blue` blue part of color + +**Returns:** + +- ESP\_OK: Set RGB for a specific pixel successfully +- ESP\_ERR\_INVALID\_ARG: Set RGB for a specific pixel failed because of invalid parameters +- ESP\_FAIL: Set RGB for a specific pixel failed because other error occurred + +- esp\_err\_t(\* set_pixel_rgbw
_Set RGBW for a specific pixel. Similar to_ `set_pixel`_but also set the white component._
**Parameters:** + +- `strip` LED strip +- `index` index of pixel to set +- `red` red part of color +- `green` green part of color +- `blue` blue part of color +- `white` separate white component + +**Returns:** + +- ESP\_OK: Set RGBW color for a specific pixel successfully +- ESP\_ERR\_INVALID\_ARG: Set RGBW color for a specific pixel failed because of an invalid argument +- ESP\_FAIL: Set RGBW color for a specific pixel failed because other error occurred + +### typedef `led_strip_t` + +```c +typedef struct led_strip_t led_strip_t; +``` + +Type of LED strip diff --git a/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/CMakeLists.txt b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/CMakeLists.txt new file mode 100644 index 0000000..fc2dfc7 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/CMakeLists.txt @@ -0,0 +1,8 @@ +# For more information about build system see +# https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html +# The following five lines of boilerplate have to be in your project's +# CMakeLists in this exact order for cmake to work correctly +cmake_minimum_required(VERSION 3.16) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(led_strip_rmt_ws2812) diff --git a/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/README.md b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/README.md new file mode 100644 index 0000000..ad52235 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/README.md @@ -0,0 +1,31 @@ +# LED Strip Example (RMT backend + WS2812) + +This example demonstrates how to blink the WS2812 LED using the [led_strip](https://components.espressif.com/component/espressif/led_strip) component. + +## How to Use Example + +### Hardware Required + +* A development board with Espressif SoC +* A USB cable for Power supply and programming +* WS2812 LED strip + +### Configure the Example + +Before project configuration and build, be sure to set the correct chip target using `idf.py set-target `. Then assign the proper GPIO in the [source file](main/led_strip_rmt_ws2812_main.c). If your led strip has multiple LEDs, don't forget update the number. + +### Build and Flash + +Run `idf.py -p PORT build flash monitor` to build, flash and monitor the project. + +(To exit the serial monitor, type ``Ctrl-]``.) + +See the [Getting Started Guide](https://docs.espressif.com/projects/esp-idf/en/latest/get-started/index.html) for full steps to configure and use ESP-IDF to build projects. + +## Example Output + +```text +I (299) gpio: GPIO[8]| InputEn: 0| OutputEn: 1| OpenDrain: 0| Pullup: 1| Pulldown: 0| Intr:0 +I (309) example: Created LED strip object with RMT backend +I (309) example: Start blinking LED strip +``` diff --git a/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/main/CMakeLists.txt b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/main/CMakeLists.txt new file mode 100644 index 0000000..37b9c14 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/main/CMakeLists.txt @@ -0,0 +1,2 @@ +idf_component_register(SRCS "led_strip_rmt_ws2812_main.c" + INCLUDE_DIRS ".") diff --git a/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/main/idf_component.yml b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/main/idf_component.yml new file mode 100644 index 0000000..916c366 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/main/idf_component.yml @@ -0,0 +1,5 @@ +## IDF Component Manager Manifest File +dependencies: + espressif/led_strip: + version: '^2' + override_path: '../../../' diff --git a/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/main/led_strip_rmt_ws2812_main.c b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/main/led_strip_rmt_ws2812_main.c new file mode 100644 index 0000000..5cae3f0 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_rmt_ws2812/main/led_strip_rmt_ws2812_main.c @@ -0,0 +1,75 @@ +/* + * SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ +#include +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "led_strip.h" +#include "esp_log.h" +#include "esp_err.h" + +// GPIO assignment +#define LED_STRIP_BLINK_GPIO 2 +// Numbers of the LED in the strip +#define LED_STRIP_LED_NUMBERS 24 +// 10MHz resolution, 1 tick = 0.1us (led strip needs a high resolution) +#define LED_STRIP_RMT_RES_HZ (10 * 1000 * 1000) + +static const char *TAG = "example"; + +led_strip_handle_t configure_led(void) +{ + // LED strip general initialization, according to your led board design + led_strip_config_t strip_config = { + .strip_gpio_num = LED_STRIP_BLINK_GPIO, // The GPIO that connected to the LED strip's data line + .max_leds = LED_STRIP_LED_NUMBERS, // The number of LEDs in the strip, + .led_pixel_format = LED_PIXEL_FORMAT_GRB, // Pixel format of your LED strip + .led_model = LED_MODEL_WS2812, // LED strip model + .flags.invert_out = false, // whether to invert the output signal + }; + + // LED strip backend configuration: RMT + led_strip_rmt_config_t rmt_config = { +#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0) + .rmt_channel = 0, +#else + .clk_src = RMT_CLK_SRC_DEFAULT, // different clock source can lead to different power consumption + .resolution_hz = LED_STRIP_RMT_RES_HZ, // RMT counter clock frequency + .flags.with_dma = false, // DMA feature is available on ESP target like ESP32-S3 +#endif + }; + + // LED Strip object handle + led_strip_handle_t led_strip; + ESP_ERROR_CHECK(led_strip_new_rmt_device(&strip_config, &rmt_config, &led_strip)); + ESP_LOGI(TAG, "Created LED strip object with RMT backend"); + return led_strip; +} + +void app_main(void) +{ + led_strip_handle_t led_strip = configure_led(); + bool led_on_off = false; + + ESP_LOGI(TAG, "Start blinking LED strip"); + while (1) { + if (led_on_off) { + /* Set the LED pixel using RGB from 0 (0%) to 255 (100%) for each color */ + for (int i = 0; i < LED_STRIP_LED_NUMBERS; i++) { + ESP_ERROR_CHECK(led_strip_set_pixel(led_strip, i, 5, 5, 5)); + } + /* Refresh the strip to send data */ + ESP_ERROR_CHECK(led_strip_refresh(led_strip)); + ESP_LOGI(TAG, "LED ON!"); + } else { + /* Set all LED off to clear all pixels */ + ESP_ERROR_CHECK(led_strip_clear(led_strip)); + ESP_LOGI(TAG, "LED OFF!"); + } + + led_on_off = !led_on_off; + vTaskDelay(pdMS_TO_TICKS(500)); + } +} diff --git a/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/CMakeLists.txt b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/CMakeLists.txt new file mode 100644 index 0000000..7d3af2d --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/CMakeLists.txt @@ -0,0 +1,8 @@ +# For more information about build system see +# https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html +# The following five lines of boilerplate have to be in your project's +# CMakeLists in this exact order for cmake to work correctly +cmake_minimum_required(VERSION 3.16) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(led_strip_spi_ws2812) diff --git a/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/README.md b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/README.md new file mode 100644 index 0000000..c545c84 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/README.md @@ -0,0 +1,31 @@ +# LED Strip Example (SPI backend + WS2812) + +This example demonstrates how to blink the WS2812 LED using the [led_strip](https://components.espressif.com/component/espressif/led_strip) component. + +## How to Use Example + +### Hardware Required + +* A development board with Espressif SoC +* A USB cable for Power supply and programming +* WS2812 LED strip + +### Configure the Example + +Before project configuration and build, be sure to set the correct chip target using `idf.py set-target `. Then assign the proper GPIO in the [source file](main/led_strip_spi_ws2812_main.c). If your led strip has multiple LEDs, don't forget update the number. + +### Build and Flash + +Run `idf.py -p PORT build flash monitor` to build, flash and monitor the project. + +(To exit the serial monitor, type ``Ctrl-]``.) + +See the [Getting Started Guide](https://docs.espressif.com/projects/esp-idf/en/latest/get-started/index.html) for full steps to configure and use ESP-IDF to build projects. + +## Example Output + +```text +I (299) gpio: GPIO[14]| InputEn: 0| OutputEn: 1| OpenDrain: 0| Pullup: 1| Pulldown: 0| Intr:0 +I (309) example: Created LED strip object with SPI backend +I (309) example: Start blinking LED strip +``` diff --git a/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/main/CMakeLists.txt b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/main/CMakeLists.txt new file mode 100644 index 0000000..5ad7dd5 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/main/CMakeLists.txt @@ -0,0 +1,2 @@ +idf_component_register(SRCS "led_strip_spi_ws2812_main.c" + INCLUDE_DIRS ".") diff --git a/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/main/idf_component.yml b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/main/idf_component.yml new file mode 100644 index 0000000..050d8d2 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/main/idf_component.yml @@ -0,0 +1,6 @@ +## IDF Component Manager Manifest File +dependencies: + espressif/led_strip: + version: '^2.4' + override_path: '../../../' + idf: ">=5.1" diff --git a/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/main/led_strip_spi_ws2812_main.c b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/main/led_strip_spi_ws2812_main.c new file mode 100644 index 0000000..69b780c --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/examples/led_strip_spi_ws2812/main/led_strip_spi_ws2812_main.c @@ -0,0 +1,69 @@ +/* + * SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Unlicense OR CC0-1.0 + */ +#include +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "led_strip.h" +#include "esp_log.h" +#include "esp_err.h" + +// GPIO assignment +#define LED_STRIP_BLINK_GPIO 2 +// Numbers of the LED in the strip +#define LED_STRIP_LED_NUMBERS 24 + +static const char *TAG = "example"; + +led_strip_handle_t configure_led(void) +{ + // LED strip general initialization, according to your led board design + led_strip_config_t strip_config = { + .strip_gpio_num = LED_STRIP_BLINK_GPIO, // The GPIO that connected to the LED strip's data line + .max_leds = LED_STRIP_LED_NUMBERS, // The number of LEDs in the strip, + .led_pixel_format = LED_PIXEL_FORMAT_GRB, // Pixel format of your LED strip + .led_model = LED_MODEL_WS2812, // LED strip model + .flags.invert_out = false, // whether to invert the output signal + }; + + // LED strip backend configuration: SPI + led_strip_spi_config_t spi_config = { + .clk_src = SPI_CLK_SRC_DEFAULT, // different clock source can lead to different power consumption + .flags.with_dma = true, // Using DMA can improve performance and help drive more LEDs + .spi_bus = SPI2_HOST, // SPI bus ID + }; + + // LED Strip object handle + led_strip_handle_t led_strip; + ESP_ERROR_CHECK(led_strip_new_spi_device(&strip_config, &spi_config, &led_strip)); + ESP_LOGI(TAG, "Created LED strip object with SPI backend"); + return led_strip; +} + +void app_main(void) +{ + led_strip_handle_t led_strip = configure_led(); + bool led_on_off = false; + + ESP_LOGI(TAG, "Start blinking LED strip"); + while (1) { + if (led_on_off) { + /* Set the LED pixel using RGB from 0 (0%) to 255 (100%) for each color */ + for (int i = 0; i < LED_STRIP_LED_NUMBERS; i++) { + ESP_ERROR_CHECK(led_strip_set_pixel(led_strip, i, 5, 5, 5)); + } + /* Refresh the strip to send data */ + ESP_ERROR_CHECK(led_strip_refresh(led_strip)); + ESP_LOGI(TAG, "LED ON!"); + } else { + /* Set all LED off to clear all pixels */ + ESP_ERROR_CHECK(led_strip_clear(led_strip)); + ESP_LOGI(TAG, "LED OFF!"); + } + + led_on_off = !led_on_off; + vTaskDelay(pdMS_TO_TICKS(500)); + } +} diff --git a/scripts/led-test/managed_components/espressif__led_strip/idf_component.yml b/scripts/led-test/managed_components/espressif__led_strip/idf_component.yml new file mode 100644 index 0000000..a7deca2 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/idf_component.yml @@ -0,0 +1,9 @@ +dependencies: + idf: '>=4.4' +description: Driver for Addressable LED Strip (WS2812, etc) +repository: git://github.com/espressif/idf-extra-components.git +repository_info: + commit_sha: 60c14263f3b69ac6e98ecae79beecbe5c18d5596 + path: led_strip +url: https://github.com/espressif/idf-extra-components/tree/master/led_strip +version: 2.5.5 diff --git a/scripts/led-test/managed_components/espressif__led_strip/include/led_strip.h b/scripts/led-test/managed_components/espressif__led_strip/include/led_strip.h new file mode 100644 index 0000000..a4e9946 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/include/led_strip.h @@ -0,0 +1,111 @@ +/* + * SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include "esp_err.h" +#include "led_strip_rmt.h" +#include "esp_idf_version.h" + +#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0) +#include "led_strip_spi.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Set RGB for a specific pixel + * + * @param strip: LED strip + * @param index: index of pixel to set + * @param red: red part of color + * @param green: green part of color + * @param blue: blue part of color + * + * @return + * - ESP_OK: Set RGB for a specific pixel successfully + * - ESP_ERR_INVALID_ARG: Set RGB for a specific pixel failed because of invalid parameters + * - ESP_FAIL: Set RGB for a specific pixel failed because other error occurred + */ +esp_err_t led_strip_set_pixel(led_strip_handle_t strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue); + +/** + * @brief Set RGBW for a specific pixel + * + * @note Only call this function if your led strip does have the white component (e.g. SK6812-RGBW) + * @note Also see `led_strip_set_pixel` if you only want to specify the RGB part of the color and bypass the white component + * + * @param strip: LED strip + * @param index: index of pixel to set + * @param red: red part of color + * @param green: green part of color + * @param blue: blue part of color + * @param white: separate white component + * + * @return + * - ESP_OK: Set RGBW color for a specific pixel successfully + * - ESP_ERR_INVALID_ARG: Set RGBW color for a specific pixel failed because of an invalid argument + * - ESP_FAIL: Set RGBW color for a specific pixel failed because other error occurred + */ +esp_err_t led_strip_set_pixel_rgbw(led_strip_handle_t strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue, uint32_t white); + +/** + * @brief Set HSV for a specific pixel + * + * @param strip: LED strip + * @param index: index of pixel to set + * @param hue: hue part of color (0 - 360) + * @param saturation: saturation part of color (0 - 255, rescaled from 0 - 1. e.g. saturation = 0.5, rescaled to 127) + * @param value: value part of color (0 - 255, rescaled from 0 - 1. e.g. value = 0.5, rescaled to 127) + * + * @return + * - ESP_OK: Set HSV color for a specific pixel successfully + * - ESP_ERR_INVALID_ARG: Set HSV color for a specific pixel failed because of an invalid argument + * - ESP_FAIL: Set HSV color for a specific pixel failed because other error occurred + */ +esp_err_t led_strip_set_pixel_hsv(led_strip_handle_t strip, uint32_t index, uint16_t hue, uint8_t saturation, uint8_t value); + +/** + * @brief Refresh memory colors to LEDs + * + * @param strip: LED strip + * + * @return + * - ESP_OK: Refresh successfully + * - ESP_FAIL: Refresh failed because some other error occurred + * + * @note: + * After updating the LED colors in the memory, a following invocation of this API is needed to flush colors to strip. + */ +esp_err_t led_strip_refresh(led_strip_handle_t strip); + +/** + * @brief Clear LED strip (turn off all LEDs) + * + * @param strip: LED strip + * + * @return + * - ESP_OK: Clear LEDs successfully + * - ESP_FAIL: Clear LEDs failed because some other error occurred + */ +esp_err_t led_strip_clear(led_strip_handle_t strip); + +/** + * @brief Free LED strip resources + * + * @param strip: LED strip + * + * @return + * - ESP_OK: Free resources successfully + * - ESP_FAIL: Free resources failed because error occurred + */ +esp_err_t led_strip_del(led_strip_handle_t strip); + +#ifdef __cplusplus +} +#endif diff --git a/scripts/led-test/managed_components/espressif__led_strip/include/led_strip_rmt.h b/scripts/led-test/managed_components/espressif__led_strip/include/led_strip_rmt.h new file mode 100644 index 0000000..b575aea --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/include/led_strip_rmt.h @@ -0,0 +1,53 @@ +/* + * SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include "esp_err.h" +#include "led_strip_types.h" +#include "esp_idf_version.h" + +#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0) +#include "driver/rmt_types.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief LED Strip RMT specific configuration + */ +typedef struct { +#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0) + uint8_t rmt_channel; /*!< Specify the channel number, the legacy RMT driver doesn't support channel allocator */ +#else // new driver supports specify the clock source and clock resolution + rmt_clock_source_t clk_src; /*!< RMT clock source */ + uint32_t resolution_hz; /*!< RMT tick resolution, if set to zero, a default resolution (10MHz) will be applied */ +#endif + size_t mem_block_symbols; /*!< How many RMT symbols can one RMT channel hold at one time. Set to 0 will fallback to use the default size. */ + struct { + uint32_t with_dma: 1; /*!< Use DMA to transmit data */ + } flags; /*!< Extra driver flags */ +} led_strip_rmt_config_t; + +/** + * @brief Create LED strip based on RMT TX channel + * + * @param led_config LED strip configuration + * @param rmt_config RMT specific configuration + * @param ret_strip Returned LED strip handle + * @return + * - ESP_OK: create LED strip handle successfully + * - ESP_ERR_INVALID_ARG: create LED strip handle failed because of invalid argument + * - ESP_ERR_NO_MEM: create LED strip handle failed because of out of memory + * - ESP_FAIL: create LED strip handle failed because some other error + */ +esp_err_t led_strip_new_rmt_device(const led_strip_config_t *led_config, const led_strip_rmt_config_t *rmt_config, led_strip_handle_t *ret_strip); + +#ifdef __cplusplus +} +#endif diff --git a/scripts/led-test/managed_components/espressif__led_strip/include/led_strip_spi.h b/scripts/led-test/managed_components/espressif__led_strip/include/led_strip_spi.h new file mode 100644 index 0000000..eb35249 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/include/led_strip_spi.h @@ -0,0 +1,46 @@ +/* + * SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include "esp_err.h" +#include "driver/spi_master.h" +#include "led_strip_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief LED Strip SPI specific configuration + */ +typedef struct { + spi_clock_source_t clk_src; /*!< SPI clock source */ + spi_host_device_t spi_bus; /*!< SPI bus ID. Which buses are available depends on the specific chip */ + struct { + uint32_t with_dma: 1; /*!< Use DMA to transmit data */ + } flags; /*!< Extra driver flags */ +} led_strip_spi_config_t; + +/** + * @brief Create LED strip based on SPI MOSI channel + * @note Although only the MOSI line is used for generating the signal, the whole SPI bus can't be used for other purposes. + * + * @param led_config LED strip configuration + * @param spi_config SPI specific configuration + * @param ret_strip Returned LED strip handle + * @return + * - ESP_OK: create LED strip handle successfully + * - ESP_ERR_INVALID_ARG: create LED strip handle failed because of invalid argument + * - ESP_ERR_NOT_SUPPORTED: create LED strip handle failed because of unsupported configuration + * - ESP_ERR_NO_MEM: create LED strip handle failed because of out of memory + * - ESP_FAIL: create LED strip handle failed because some other error + */ +esp_err_t led_strip_new_spi_device(const led_strip_config_t *led_config, const led_strip_spi_config_t *spi_config, led_strip_handle_t *ret_strip); + +#ifdef __cplusplus +} +#endif diff --git a/scripts/led-test/managed_components/espressif__led_strip/include/led_strip_types.h b/scripts/led-test/managed_components/espressif__led_strip/include/led_strip_types.h new file mode 100644 index 0000000..691f0bc --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/include/led_strip_types.h @@ -0,0 +1,54 @@ +/* + * SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief LED strip pixel format + */ +typedef enum { + LED_PIXEL_FORMAT_GRB, /*!< Pixel format: GRB */ + LED_PIXEL_FORMAT_GRBW, /*!< Pixel format: GRBW */ + LED_PIXEL_FORMAT_INVALID /*!< Invalid pixel format */ +} led_pixel_format_t; + +/** + * @brief LED strip model + * @note Different led model may have different timing parameters, so we need to distinguish them. + */ +typedef enum { + LED_MODEL_WS2812, /*!< LED strip model: WS2812 */ + LED_MODEL_SK6812, /*!< LED strip model: SK6812 */ + LED_MODEL_INVALID /*!< Invalid LED strip model */ +} led_model_t; + +/** + * @brief LED strip handle + */ +typedef struct led_strip_t *led_strip_handle_t; + +/** + * @brief LED Strip Configuration + */ +typedef struct { + int strip_gpio_num; /*!< GPIO number that used by LED strip */ + uint32_t max_leds; /*!< Maximum LEDs in a single strip */ + led_pixel_format_t led_pixel_format; /*!< LED pixel format */ + led_model_t led_model; /*!< LED model */ + + struct { + uint32_t invert_out: 1; /*!< Invert output signal */ + } flags; /*!< Extra driver flags */ +} led_strip_config_t; + +#ifdef __cplusplus +} +#endif diff --git a/scripts/led-test/managed_components/espressif__led_strip/interface/led_strip_interface.h b/scripts/led-test/managed_components/espressif__led_strip/interface/led_strip_interface.h new file mode 100644 index 0000000..3de4c27 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/interface/led_strip_interface.h @@ -0,0 +1,95 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include "esp_err.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct led_strip_t led_strip_t; /*!< Type of LED strip */ + +/** + * @brief LED strip interface definition + */ +struct led_strip_t { + /** + * @brief Set RGB for a specific pixel + * + * @param strip: LED strip + * @param index: index of pixel to set + * @param red: red part of color + * @param green: green part of color + * @param blue: blue part of color + * + * @return + * - ESP_OK: Set RGB for a specific pixel successfully + * - ESP_ERR_INVALID_ARG: Set RGB for a specific pixel failed because of invalid parameters + * - ESP_FAIL: Set RGB for a specific pixel failed because other error occurred + */ + esp_err_t (*set_pixel)(led_strip_t *strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue); + + /** + * @brief Set RGBW for a specific pixel. Similar to `set_pixel` but also set the white component + * + * @param strip: LED strip + * @param index: index of pixel to set + * @param red: red part of color + * @param green: green part of color + * @param blue: blue part of color + * @param white: separate white component + * + * @return + * - ESP_OK: Set RGBW color for a specific pixel successfully + * - ESP_ERR_INVALID_ARG: Set RGBW color for a specific pixel failed because of an invalid argument + * - ESP_FAIL: Set RGBW color for a specific pixel failed because other error occurred + */ + esp_err_t (*set_pixel_rgbw)(led_strip_t *strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue, uint32_t white); + + /** + * @brief Refresh memory colors to LEDs + * + * @param strip: LED strip + * @param timeout_ms: timeout value for refreshing task + * + * @return + * - ESP_OK: Refresh successfully + * - ESP_FAIL: Refresh failed because some other error occurred + * + * @note: + * After updating the LED colors in the memory, a following invocation of this API is needed to flush colors to strip. + */ + esp_err_t (*refresh)(led_strip_t *strip); + + /** + * @brief Clear LED strip (turn off all LEDs) + * + * @param strip: LED strip + * @param timeout_ms: timeout value for clearing task + * + * @return + * - ESP_OK: Clear LEDs successfully + * - ESP_FAIL: Clear LEDs failed because some other error occurred + */ + esp_err_t (*clear)(led_strip_t *strip); + + /** + * @brief Free LED strip resources + * + * @param strip: LED strip + * + * @return + * - ESP_OK: Free resources successfully + * - ESP_FAIL: Free resources failed because error occurred + */ + esp_err_t (*del)(led_strip_t *strip); +}; + +#ifdef __cplusplus +} +#endif diff --git a/scripts/led-test/managed_components/espressif__led_strip/src/led_strip_api.c b/scripts/led-test/managed_components/espressif__led_strip/src/led_strip_api.c new file mode 100644 index 0000000..6eb86b8 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/src/led_strip_api.c @@ -0,0 +1,94 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include "esp_log.h" +#include "esp_check.h" +#include "led_strip.h" +#include "led_strip_interface.h" + +static const char *TAG = "led_strip"; + +esp_err_t led_strip_set_pixel(led_strip_handle_t strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue) +{ + ESP_RETURN_ON_FALSE(strip, ESP_ERR_INVALID_ARG, TAG, "invalid argument"); + return strip->set_pixel(strip, index, red, green, blue); +} + +esp_err_t led_strip_set_pixel_hsv(led_strip_handle_t strip, uint32_t index, uint16_t hue, uint8_t saturation, uint8_t value) +{ + ESP_RETURN_ON_FALSE(strip, ESP_ERR_INVALID_ARG, TAG, "invalid argument"); + + uint32_t red = 0; + uint32_t green = 0; + uint32_t blue = 0; + + uint32_t rgb_max = value; + uint32_t rgb_min = rgb_max * (255 - saturation) / 255.0f; + + uint32_t i = hue / 60; + uint32_t diff = hue % 60; + + // RGB adjustment amount by hue + uint32_t rgb_adj = (rgb_max - rgb_min) * diff / 60; + + switch (i) { + case 0: + red = rgb_max; + green = rgb_min + rgb_adj; + blue = rgb_min; + break; + case 1: + red = rgb_max - rgb_adj; + green = rgb_max; + blue = rgb_min; + break; + case 2: + red = rgb_min; + green = rgb_max; + blue = rgb_min + rgb_adj; + break; + case 3: + red = rgb_min; + green = rgb_max - rgb_adj; + blue = rgb_max; + break; + case 4: + red = rgb_min + rgb_adj; + green = rgb_min; + blue = rgb_max; + break; + default: + red = rgb_max; + green = rgb_min; + blue = rgb_max - rgb_adj; + break; + } + + return strip->set_pixel(strip, index, red, green, blue); +} + +esp_err_t led_strip_set_pixel_rgbw(led_strip_handle_t strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue, uint32_t white) +{ + ESP_RETURN_ON_FALSE(strip, ESP_ERR_INVALID_ARG, TAG, "invalid argument"); + return strip->set_pixel_rgbw(strip, index, red, green, blue, white); +} + +esp_err_t led_strip_refresh(led_strip_handle_t strip) +{ + ESP_RETURN_ON_FALSE(strip, ESP_ERR_INVALID_ARG, TAG, "invalid argument"); + return strip->refresh(strip); +} + +esp_err_t led_strip_clear(led_strip_handle_t strip) +{ + ESP_RETURN_ON_FALSE(strip, ESP_ERR_INVALID_ARG, TAG, "invalid argument"); + return strip->clear(strip); +} + +esp_err_t led_strip_del(led_strip_handle_t strip) +{ + ESP_RETURN_ON_FALSE(strip, ESP_ERR_INVALID_ARG, TAG, "invalid argument"); + return strip->del(strip); +} diff --git a/scripts/led-test/managed_components/espressif__led_strip/src/led_strip_rmt_dev.c b/scripts/led-test/managed_components/espressif__led_strip/src/led_strip_rmt_dev.c new file mode 100644 index 0000000..1cbf0e4 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/src/led_strip_rmt_dev.c @@ -0,0 +1,164 @@ +/* + * SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include +#include +#include "esp_log.h" +#include "esp_check.h" +#include "driver/rmt_tx.h" +#include "led_strip.h" +#include "led_strip_interface.h" +#include "led_strip_rmt_encoder.h" + +#define LED_STRIP_RMT_DEFAULT_RESOLUTION 10000000 // 10MHz resolution +#define LED_STRIP_RMT_DEFAULT_TRANS_QUEUE_SIZE 4 +// the memory size of each RMT channel, in words (4 bytes) +#if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2 +#define LED_STRIP_RMT_DEFAULT_MEM_BLOCK_SYMBOLS 64 +#else +#define LED_STRIP_RMT_DEFAULT_MEM_BLOCK_SYMBOLS 48 +#endif + +static const char *TAG = "led_strip_rmt"; + +typedef struct { + led_strip_t base; + rmt_channel_handle_t rmt_chan; + rmt_encoder_handle_t strip_encoder; + uint32_t strip_len; + uint8_t bytes_per_pixel; + uint8_t pixel_buf[]; +} led_strip_rmt_obj; + +static esp_err_t led_strip_rmt_set_pixel(led_strip_t *strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue) +{ + led_strip_rmt_obj *rmt_strip = __containerof(strip, led_strip_rmt_obj, base); + ESP_RETURN_ON_FALSE(index < rmt_strip->strip_len, ESP_ERR_INVALID_ARG, TAG, "index out of maximum number of LEDs"); + uint32_t start = index * rmt_strip->bytes_per_pixel; + // In thr order of GRB, as LED strip like WS2812 sends out pixels in this order + rmt_strip->pixel_buf[start + 0] = green & 0xFF; + rmt_strip->pixel_buf[start + 1] = red & 0xFF; + rmt_strip->pixel_buf[start + 2] = blue & 0xFF; + if (rmt_strip->bytes_per_pixel > 3) { + rmt_strip->pixel_buf[start + 3] = 0; + } + return ESP_OK; +} + +static esp_err_t led_strip_rmt_set_pixel_rgbw(led_strip_t *strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue, uint32_t white) +{ + led_strip_rmt_obj *rmt_strip = __containerof(strip, led_strip_rmt_obj, base); + ESP_RETURN_ON_FALSE(index < rmt_strip->strip_len, ESP_ERR_INVALID_ARG, TAG, "index out of maximum number of LEDs"); + ESP_RETURN_ON_FALSE(rmt_strip->bytes_per_pixel == 4, ESP_ERR_INVALID_ARG, TAG, "wrong LED pixel format, expected 4 bytes per pixel"); + uint8_t *buf_start = rmt_strip->pixel_buf + index * 4; + // SK6812 component order is GRBW + *buf_start = green & 0xFF; + *++buf_start = red & 0xFF; + *++buf_start = blue & 0xFF; + *++buf_start = white & 0xFF; + return ESP_OK; +} + +static esp_err_t led_strip_rmt_refresh(led_strip_t *strip) +{ + led_strip_rmt_obj *rmt_strip = __containerof(strip, led_strip_rmt_obj, base); + rmt_transmit_config_t tx_conf = { + .loop_count = 0, + }; + + ESP_RETURN_ON_ERROR(rmt_enable(rmt_strip->rmt_chan), TAG, "enable RMT channel failed"); + ESP_RETURN_ON_ERROR(rmt_transmit(rmt_strip->rmt_chan, rmt_strip->strip_encoder, rmt_strip->pixel_buf, + rmt_strip->strip_len * rmt_strip->bytes_per_pixel, &tx_conf), TAG, "transmit pixels by RMT failed"); + ESP_RETURN_ON_ERROR(rmt_tx_wait_all_done(rmt_strip->rmt_chan, -1), TAG, "flush RMT channel failed"); + ESP_RETURN_ON_ERROR(rmt_disable(rmt_strip->rmt_chan), TAG, "disable RMT channel failed"); + return ESP_OK; +} + +static esp_err_t led_strip_rmt_clear(led_strip_t *strip) +{ + led_strip_rmt_obj *rmt_strip = __containerof(strip, led_strip_rmt_obj, base); + // Write zero to turn off all leds + memset(rmt_strip->pixel_buf, 0, rmt_strip->strip_len * rmt_strip->bytes_per_pixel); + return led_strip_rmt_refresh(strip); +} + +static esp_err_t led_strip_rmt_del(led_strip_t *strip) +{ + led_strip_rmt_obj *rmt_strip = __containerof(strip, led_strip_rmt_obj, base); + ESP_RETURN_ON_ERROR(rmt_del_channel(rmt_strip->rmt_chan), TAG, "delete RMT channel failed"); + ESP_RETURN_ON_ERROR(rmt_del_encoder(rmt_strip->strip_encoder), TAG, "delete strip encoder failed"); + free(rmt_strip); + return ESP_OK; +} + +esp_err_t led_strip_new_rmt_device(const led_strip_config_t *led_config, const led_strip_rmt_config_t *rmt_config, led_strip_handle_t *ret_strip) +{ + led_strip_rmt_obj *rmt_strip = NULL; + esp_err_t ret = ESP_OK; + ESP_GOTO_ON_FALSE(led_config && rmt_config && ret_strip, ESP_ERR_INVALID_ARG, err, TAG, "invalid argument"); + ESP_GOTO_ON_FALSE(led_config->led_pixel_format < LED_PIXEL_FORMAT_INVALID, ESP_ERR_INVALID_ARG, err, TAG, "invalid led_pixel_format"); + uint8_t bytes_per_pixel = 3; + if (led_config->led_pixel_format == LED_PIXEL_FORMAT_GRBW) { + bytes_per_pixel = 4; + } else if (led_config->led_pixel_format == LED_PIXEL_FORMAT_GRB) { + bytes_per_pixel = 3; + } else { + assert(false); + } + rmt_strip = calloc(1, sizeof(led_strip_rmt_obj) + led_config->max_leds * bytes_per_pixel); + ESP_GOTO_ON_FALSE(rmt_strip, ESP_ERR_NO_MEM, err, TAG, "no mem for rmt strip"); + uint32_t resolution = rmt_config->resolution_hz ? rmt_config->resolution_hz : LED_STRIP_RMT_DEFAULT_RESOLUTION; + + // for backward compatibility, if the user does not set the clk_src, use the default value + rmt_clock_source_t clk_src = RMT_CLK_SRC_DEFAULT; + if (rmt_config->clk_src) { + clk_src = rmt_config->clk_src; + } + size_t mem_block_symbols = LED_STRIP_RMT_DEFAULT_MEM_BLOCK_SYMBOLS; + // override the default value if the user sets it + if (rmt_config->mem_block_symbols) { + mem_block_symbols = rmt_config->mem_block_symbols; + } + rmt_tx_channel_config_t rmt_chan_config = { + .clk_src = clk_src, + .gpio_num = led_config->strip_gpio_num, + .mem_block_symbols = mem_block_symbols, + .resolution_hz = resolution, + .trans_queue_depth = LED_STRIP_RMT_DEFAULT_TRANS_QUEUE_SIZE, + .flags.with_dma = rmt_config->flags.with_dma, + .flags.invert_out = led_config->flags.invert_out, + }; + ESP_GOTO_ON_ERROR(rmt_new_tx_channel(&rmt_chan_config, &rmt_strip->rmt_chan), err, TAG, "create RMT TX channel failed"); + + led_strip_encoder_config_t strip_encoder_conf = { + .resolution = resolution, + .led_model = led_config->led_model + }; + ESP_GOTO_ON_ERROR(rmt_new_led_strip_encoder(&strip_encoder_conf, &rmt_strip->strip_encoder), err, TAG, "create LED strip encoder failed"); + + + rmt_strip->bytes_per_pixel = bytes_per_pixel; + rmt_strip->strip_len = led_config->max_leds; + rmt_strip->base.set_pixel = led_strip_rmt_set_pixel; + rmt_strip->base.set_pixel_rgbw = led_strip_rmt_set_pixel_rgbw; + rmt_strip->base.refresh = led_strip_rmt_refresh; + rmt_strip->base.clear = led_strip_rmt_clear; + rmt_strip->base.del = led_strip_rmt_del; + + *ret_strip = &rmt_strip->base; + return ESP_OK; +err: + if (rmt_strip) { + if (rmt_strip->rmt_chan) { + rmt_del_channel(rmt_strip->rmt_chan); + } + if (rmt_strip->strip_encoder) { + rmt_del_encoder(rmt_strip->strip_encoder); + } + free(rmt_strip); + } + return ret; +} diff --git a/scripts/led-test/managed_components/espressif__led_strip/src/led_strip_rmt_dev_idf4.c b/scripts/led-test/managed_components/espressif__led_strip/src/led_strip_rmt_dev_idf4.c new file mode 100644 index 0000000..a1067cd --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/src/led_strip_rmt_dev_idf4.c @@ -0,0 +1,194 @@ +/* + * SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include +#include +#include "esp_log.h" +#include "esp_check.h" +#include "driver/rmt.h" +#include "led_strip.h" +#include "led_strip_interface.h" + +static const char *TAG = "led_strip_rmt"; + +#define WS2812_T0H_NS (300) +#define WS2812_T0L_NS (900) +#define WS2812_T1H_NS (900) +#define WS2812_T1L_NS (300) + +#define SK6812_T0H_NS (300) +#define SK6812_T0L_NS (900) +#define SK6812_T1H_NS (600) +#define SK6812_T1L_NS (600) + +#define LED_STRIP_RESET_MS (10) + +// the memory size of each RMT channel, in words (4 bytes) +#if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2 +#define LED_STRIP_RMT_DEFAULT_MEM_BLOCK_SYMBOLS 64 +#else +#define LED_STRIP_RMT_DEFAULT_MEM_BLOCK_SYMBOLS 48 +#endif + +static uint32_t led_t0h_ticks = 0; +static uint32_t led_t1h_ticks = 0; +static uint32_t led_t0l_ticks = 0; +static uint32_t led_t1l_ticks = 0; + +typedef struct { + led_strip_t base; + rmt_channel_t rmt_channel; + uint32_t strip_len; + uint8_t bytes_per_pixel; + uint8_t buffer[0]; +} led_strip_rmt_obj; + +static void IRAM_ATTR ws2812_rmt_adapter(const void *src, rmt_item32_t *dest, size_t src_size, + size_t wanted_num, size_t *translated_size, size_t *item_num) +{ + if (src == NULL || dest == NULL) { + *translated_size = 0; + *item_num = 0; + return; + } + const rmt_item32_t bit0 = {{{ led_t0h_ticks, 1, led_t0l_ticks, 0 }}}; //Logical 0 + const rmt_item32_t bit1 = {{{ led_t1h_ticks, 1, led_t1l_ticks, 0 }}}; //Logical 1 + size_t size = 0; + size_t num = 0; + uint8_t *psrc = (uint8_t *)src; + rmt_item32_t *pdest = dest; + while (size < src_size && num < wanted_num) { + for (int i = 0; i < 8; i++) { + // MSB first + if (*psrc & (1 << (7 - i))) { + pdest->val = bit1.val; + } else { + pdest->val = bit0.val; + } + num++; + pdest++; + } + size++; + psrc++; + } + *translated_size = size; + *item_num = num; +} + +static esp_err_t led_strip_rmt_set_pixel(led_strip_t *strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue) +{ + led_strip_rmt_obj *rmt_strip = __containerof(strip, led_strip_rmt_obj, base); + ESP_RETURN_ON_FALSE(index < rmt_strip->strip_len, ESP_ERR_INVALID_ARG, TAG, "index out of the maximum number of leds"); + uint32_t start = index * rmt_strip->bytes_per_pixel; + // In thr order of GRB + rmt_strip->buffer[start + 0] = green & 0xFF; + rmt_strip->buffer[start + 1] = red & 0xFF; + rmt_strip->buffer[start + 2] = blue & 0xFF; + if (rmt_strip->bytes_per_pixel > 3) { + rmt_strip->buffer[start + 3] = 0; + } + return ESP_OK; +} + +static esp_err_t led_strip_rmt_refresh(led_strip_t *strip) +{ + led_strip_rmt_obj *rmt_strip = __containerof(strip, led_strip_rmt_obj, base); + ESP_RETURN_ON_ERROR(rmt_write_sample(rmt_strip->rmt_channel, rmt_strip->buffer, rmt_strip->strip_len * rmt_strip->bytes_per_pixel, true), TAG, + "transmit RMT samples failed"); + vTaskDelay(pdMS_TO_TICKS(LED_STRIP_RESET_MS)); + return ESP_OK; +} + +static esp_err_t led_strip_rmt_clear(led_strip_t *strip) +{ + led_strip_rmt_obj *rmt_strip = __containerof(strip, led_strip_rmt_obj, base); + // Write zero to turn off all LEDs + memset(rmt_strip->buffer, 0, rmt_strip->strip_len * rmt_strip->bytes_per_pixel); + return led_strip_rmt_refresh(strip); +} + +static esp_err_t led_strip_rmt_del(led_strip_t *strip) +{ + led_strip_rmt_obj *rmt_strip = __containerof(strip, led_strip_rmt_obj, base); + ESP_RETURN_ON_ERROR(rmt_driver_uninstall(rmt_strip->rmt_channel), TAG, "uninstall RMT driver failed"); + free(rmt_strip); + return ESP_OK; +} + +esp_err_t led_strip_new_rmt_device(const led_strip_config_t *led_config, const led_strip_rmt_config_t *dev_config, led_strip_handle_t *ret_strip) +{ + led_strip_rmt_obj *rmt_strip = NULL; + esp_err_t ret = ESP_OK; + ESP_RETURN_ON_FALSE(led_config && dev_config && ret_strip, ESP_ERR_INVALID_ARG, TAG, "invalid argument"); + ESP_RETURN_ON_FALSE(led_config->led_pixel_format < LED_PIXEL_FORMAT_INVALID, ESP_ERR_INVALID_ARG, TAG, "invalid led_pixel_format"); + ESP_RETURN_ON_FALSE(dev_config->flags.with_dma == 0, ESP_ERR_NOT_SUPPORTED, TAG, "DMA is not supported"); + + uint8_t bytes_per_pixel = 3; + if (led_config->led_pixel_format == LED_PIXEL_FORMAT_GRBW) { + bytes_per_pixel = 4; + } else if (led_config->led_pixel_format == LED_PIXEL_FORMAT_GRB) { + bytes_per_pixel = 3; + } else { + assert(false); + } + + // allocate memory for led_strip object + rmt_strip = calloc(1, sizeof(led_strip_rmt_obj) + led_config->max_leds * bytes_per_pixel); + ESP_RETURN_ON_FALSE(rmt_strip, ESP_ERR_NO_MEM, TAG, "request memory for les_strip failed"); + + // install RMT channel driver + rmt_config_t config = RMT_DEFAULT_CONFIG_TX(led_config->strip_gpio_num, dev_config->rmt_channel); + // set the minimal clock division because the LED strip needs a high clock resolution + config.clk_div = 2; + + uint8_t mem_block_num = 2; + // override the default value if the user specify the mem block size + if (dev_config->mem_block_symbols) { + mem_block_num = (dev_config->mem_block_symbols + LED_STRIP_RMT_DEFAULT_MEM_BLOCK_SYMBOLS / 2) / LED_STRIP_RMT_DEFAULT_MEM_BLOCK_SYMBOLS; + } + config.mem_block_num = mem_block_num; + + ESP_GOTO_ON_ERROR(rmt_config(&config), err, TAG, "RMT config failed"); + ESP_GOTO_ON_ERROR(rmt_driver_install(config.channel, 0, 0), err, TAG, "RMT install failed"); + + uint32_t counter_clk_hz = 0; + rmt_get_counter_clock((rmt_channel_t)dev_config->rmt_channel, &counter_clk_hz); + // ns -> ticks + float ratio = (float)counter_clk_hz / 1e9; + if (led_config->led_model == LED_MODEL_WS2812) { + led_t0h_ticks = (uint32_t)(ratio * WS2812_T0H_NS); + led_t0l_ticks = (uint32_t)(ratio * WS2812_T0L_NS); + led_t1h_ticks = (uint32_t)(ratio * WS2812_T1H_NS); + led_t1l_ticks = (uint32_t)(ratio * WS2812_T1L_NS); + } else if (led_config->led_model == LED_MODEL_SK6812) { + led_t0h_ticks = (uint32_t)(ratio * SK6812_T0H_NS); + led_t0l_ticks = (uint32_t)(ratio * SK6812_T0L_NS); + led_t1h_ticks = (uint32_t)(ratio * SK6812_T1H_NS); + led_t1l_ticks = (uint32_t)(ratio * SK6812_T1L_NS); + } else { + assert(false); + } + + // adapter to translates the LES strip date frame into RMT symbols + rmt_translator_init((rmt_channel_t)dev_config->rmt_channel, ws2812_rmt_adapter); + + rmt_strip->bytes_per_pixel = bytes_per_pixel; + rmt_strip->rmt_channel = (rmt_channel_t)dev_config->rmt_channel; + rmt_strip->strip_len = led_config->max_leds; + rmt_strip->base.set_pixel = led_strip_rmt_set_pixel; + rmt_strip->base.refresh = led_strip_rmt_refresh; + rmt_strip->base.clear = led_strip_rmt_clear; + rmt_strip->base.del = led_strip_rmt_del; + + *ret_strip = &rmt_strip->base; + return ESP_OK; + +err: + if (rmt_strip) { + free(rmt_strip); + } + return ret; +} diff --git a/scripts/led-test/managed_components/espressif__led_strip/src/led_strip_rmt_encoder.c b/scripts/led-test/managed_components/espressif__led_strip/src/led_strip_rmt_encoder.c new file mode 100644 index 0000000..2e6f570 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/src/led_strip_rmt_encoder.c @@ -0,0 +1,146 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "esp_check.h" +#include "led_strip_rmt_encoder.h" + +static const char *TAG = "led_rmt_encoder"; + +typedef struct { + rmt_encoder_t base; + rmt_encoder_t *bytes_encoder; + rmt_encoder_t *copy_encoder; + int state; + rmt_symbol_word_t reset_code; +} rmt_led_strip_encoder_t; + +static size_t rmt_encode_led_strip(rmt_encoder_t *encoder, rmt_channel_handle_t channel, const void *primary_data, size_t data_size, rmt_encode_state_t *ret_state) +{ + rmt_led_strip_encoder_t *led_encoder = __containerof(encoder, rmt_led_strip_encoder_t, base); + rmt_encoder_handle_t bytes_encoder = led_encoder->bytes_encoder; + rmt_encoder_handle_t copy_encoder = led_encoder->copy_encoder; + rmt_encode_state_t session_state = 0; + rmt_encode_state_t state = 0; + size_t encoded_symbols = 0; + switch (led_encoder->state) { + case 0: // send RGB data + encoded_symbols += bytes_encoder->encode(bytes_encoder, channel, primary_data, data_size, &session_state); + if (session_state & RMT_ENCODING_COMPLETE) { + led_encoder->state = 1; // switch to next state when current encoding session finished + } + if (session_state & RMT_ENCODING_MEM_FULL) { + state |= RMT_ENCODING_MEM_FULL; + goto out; // yield if there's no free space for encoding artifacts + } + // fall-through + case 1: // send reset code + encoded_symbols += copy_encoder->encode(copy_encoder, channel, &led_encoder->reset_code, + sizeof(led_encoder->reset_code), &session_state); + if (session_state & RMT_ENCODING_COMPLETE) { + led_encoder->state = 0; // back to the initial encoding session + state |= RMT_ENCODING_COMPLETE; + } + if (session_state & RMT_ENCODING_MEM_FULL) { + state |= RMT_ENCODING_MEM_FULL; + goto out; // yield if there's no free space for encoding artifacts + } + } +out: + *ret_state = state; + return encoded_symbols; +} + +static esp_err_t rmt_del_led_strip_encoder(rmt_encoder_t *encoder) +{ + rmt_led_strip_encoder_t *led_encoder = __containerof(encoder, rmt_led_strip_encoder_t, base); + rmt_del_encoder(led_encoder->bytes_encoder); + rmt_del_encoder(led_encoder->copy_encoder); + free(led_encoder); + return ESP_OK; +} + +static esp_err_t rmt_led_strip_encoder_reset(rmt_encoder_t *encoder) +{ + rmt_led_strip_encoder_t *led_encoder = __containerof(encoder, rmt_led_strip_encoder_t, base); + rmt_encoder_reset(led_encoder->bytes_encoder); + rmt_encoder_reset(led_encoder->copy_encoder); + led_encoder->state = 0; + return ESP_OK; +} + +esp_err_t rmt_new_led_strip_encoder(const led_strip_encoder_config_t *config, rmt_encoder_handle_t *ret_encoder) +{ + esp_err_t ret = ESP_OK; + rmt_led_strip_encoder_t *led_encoder = NULL; + ESP_GOTO_ON_FALSE(config && ret_encoder, ESP_ERR_INVALID_ARG, err, TAG, "invalid argument"); + ESP_GOTO_ON_FALSE(config->led_model < LED_MODEL_INVALID, ESP_ERR_INVALID_ARG, err, TAG, "invalid led model"); + led_encoder = calloc(1, sizeof(rmt_led_strip_encoder_t)); + ESP_GOTO_ON_FALSE(led_encoder, ESP_ERR_NO_MEM, err, TAG, "no mem for led strip encoder"); + led_encoder->base.encode = rmt_encode_led_strip; + led_encoder->base.del = rmt_del_led_strip_encoder; + led_encoder->base.reset = rmt_led_strip_encoder_reset; + rmt_bytes_encoder_config_t bytes_encoder_config; + if (config->led_model == LED_MODEL_SK6812) { + bytes_encoder_config = (rmt_bytes_encoder_config_t) { + .bit0 = { + .level0 = 1, + .duration0 = 0.3 * config->resolution / 1000000, // T0H=0.3us + .level1 = 0, + .duration1 = 0.9 * config->resolution / 1000000, // T0L=0.9us + }, + .bit1 = { + .level0 = 1, + .duration0 = 0.6 * config->resolution / 1000000, // T1H=0.6us + .level1 = 0, + .duration1 = 0.6 * config->resolution / 1000000, // T1L=0.6us + }, + .flags.msb_first = 1 // SK6812 transfer bit order: G7...G0R7...R0B7...B0(W7...W0) + }; + } else if (config->led_model == LED_MODEL_WS2812) { + // different led strip might have its own timing requirements, following parameter is for WS2812 + bytes_encoder_config = (rmt_bytes_encoder_config_t) { + .bit0 = { + .level0 = 1, + .duration0 = 0.3 * config->resolution / 1000000, // T0H=0.3us + .level1 = 0, + .duration1 = 0.9 * config->resolution / 1000000, // T0L=0.9us + }, + .bit1 = { + .level0 = 1, + .duration0 = 0.9 * config->resolution / 1000000, // T1H=0.9us + .level1 = 0, + .duration1 = 0.3 * config->resolution / 1000000, // T1L=0.3us + }, + .flags.msb_first = 1 // WS2812 transfer bit order: G7...G0R7...R0B7...B0 + }; + } else { + assert(false); + } + ESP_GOTO_ON_ERROR(rmt_new_bytes_encoder(&bytes_encoder_config, &led_encoder->bytes_encoder), err, TAG, "create bytes encoder failed"); + rmt_copy_encoder_config_t copy_encoder_config = {}; + ESP_GOTO_ON_ERROR(rmt_new_copy_encoder(©_encoder_config, &led_encoder->copy_encoder), err, TAG, "create copy encoder failed"); + + uint32_t reset_ticks = config->resolution / 1000000 * 280 / 2; // reset code duration defaults to 280us to accomodate WS2812B-V5 + led_encoder->reset_code = (rmt_symbol_word_t) { + .level0 = 0, + .duration0 = reset_ticks, + .level1 = 0, + .duration1 = reset_ticks, + }; + *ret_encoder = &led_encoder->base; + return ESP_OK; +err: + if (led_encoder) { + if (led_encoder->bytes_encoder) { + rmt_del_encoder(led_encoder->bytes_encoder); + } + if (led_encoder->copy_encoder) { + rmt_del_encoder(led_encoder->copy_encoder); + } + free(led_encoder); + } + return ret; +} diff --git a/scripts/led-test/managed_components/espressif__led_strip/src/led_strip_rmt_encoder.h b/scripts/led-test/managed_components/espressif__led_strip/src/led_strip_rmt_encoder.h new file mode 100644 index 0000000..ba71e60 --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/src/led_strip_rmt_encoder.h @@ -0,0 +1,38 @@ +/* + * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#pragma once + +#include +#include "driver/rmt_encoder.h" +#include "led_strip_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Type of led strip encoder configuration + */ +typedef struct { + uint32_t resolution; /*!< Encoder resolution, in Hz */ + led_model_t led_model; /*!< LED model */ +} led_strip_encoder_config_t; + +/** + * @brief Create RMT encoder for encoding LED strip pixels into RMT symbols + * + * @param[in] config Encoder configuration + * @param[out] ret_encoder Returned encoder handle + * @return + * - ESP_ERR_INVALID_ARG for any invalid arguments + * - ESP_ERR_NO_MEM out of memory when creating led strip encoder + * - ESP_OK if creating encoder successfully + */ +esp_err_t rmt_new_led_strip_encoder(const led_strip_encoder_config_t *config, rmt_encoder_handle_t *ret_encoder); + +#ifdef __cplusplus +} +#endif diff --git a/scripts/led-test/managed_components/espressif__led_strip/src/led_strip_spi_dev.c b/scripts/led-test/managed_components/espressif__led_strip/src/led_strip_spi_dev.c new file mode 100644 index 0000000..6c66d7e --- /dev/null +++ b/scripts/led-test/managed_components/espressif__led_strip/src/led_strip_spi_dev.c @@ -0,0 +1,211 @@ +/* + * SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +#include +#include +#include +#include "esp_log.h" +#include "esp_check.h" +#include "esp_rom_gpio.h" +#include "soc/spi_periph.h" +#include "led_strip.h" +#include "led_strip_interface.h" +#include "hal/spi_hal.h" + +#define LED_STRIP_SPI_DEFAULT_RESOLUTION (2.5 * 1000 * 1000) // 2.5MHz resolution +#define LED_STRIP_SPI_DEFAULT_TRANS_QUEUE_SIZE 4 + +#define SPI_BYTES_PER_COLOR_BYTE 3 +#define SPI_BITS_PER_COLOR_BYTE (SPI_BYTES_PER_COLOR_BYTE * 8) + +static const char *TAG = "led_strip_spi"; + +typedef struct { + led_strip_t base; + spi_host_device_t spi_host; + spi_device_handle_t spi_device; + uint32_t strip_len; + uint8_t bytes_per_pixel; + uint8_t pixel_buf[]; +} led_strip_spi_obj; + +// please make sure to zero-initialize the buf before calling this function +static void __led_strip_spi_bit(uint8_t data, uint8_t *buf) +{ + // Each color of 1 bit is represented by 3 bits of SPI, low_level:100 ,high_level:110 + // So a color byte occupies 3 bytes of SPI. + *(buf + 2) |= data & BIT(0) ? BIT(2) | BIT(1) : BIT(2); + *(buf + 2) |= data & BIT(1) ? BIT(5) | BIT(4) : BIT(5); + *(buf + 2) |= data & BIT(2) ? BIT(7) : 0x00; + *(buf + 1) |= BIT(0); + *(buf + 1) |= data & BIT(3) ? BIT(3) | BIT(2) : BIT(3); + *(buf + 1) |= data & BIT(4) ? BIT(6) | BIT(5) : BIT(6); + *(buf + 0) |= data & BIT(5) ? BIT(1) | BIT(0) : BIT(1); + *(buf + 0) |= data & BIT(6) ? BIT(4) | BIT(3) : BIT(4); + *(buf + 0) |= data & BIT(7) ? BIT(7) | BIT(6) : BIT(7); +} + +static esp_err_t led_strip_spi_set_pixel(led_strip_t *strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue) +{ + led_strip_spi_obj *spi_strip = __containerof(strip, led_strip_spi_obj, base); + ESP_RETURN_ON_FALSE(index < spi_strip->strip_len, ESP_ERR_INVALID_ARG, TAG, "index out of maximum number of LEDs"); + // LED_PIXEL_FORMAT_GRB takes 72bits(9bytes) + uint32_t start = index * spi_strip->bytes_per_pixel * SPI_BYTES_PER_COLOR_BYTE; + memset(spi_strip->pixel_buf + start, 0, spi_strip->bytes_per_pixel * SPI_BYTES_PER_COLOR_BYTE); + __led_strip_spi_bit(green, &spi_strip->pixel_buf[start]); + __led_strip_spi_bit(red, &spi_strip->pixel_buf[start + SPI_BYTES_PER_COLOR_BYTE]); + __led_strip_spi_bit(blue, &spi_strip->pixel_buf[start + SPI_BYTES_PER_COLOR_BYTE * 2]); + if (spi_strip->bytes_per_pixel > 3) { + __led_strip_spi_bit(0, &spi_strip->pixel_buf[start + SPI_BYTES_PER_COLOR_BYTE * 3]); + } + return ESP_OK; +} + +static esp_err_t led_strip_spi_set_pixel_rgbw(led_strip_t *strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue, uint32_t white) +{ + led_strip_spi_obj *spi_strip = __containerof(strip, led_strip_spi_obj, base); + ESP_RETURN_ON_FALSE(index < spi_strip->strip_len, ESP_ERR_INVALID_ARG, TAG, "index out of maximum number of LEDs"); + ESP_RETURN_ON_FALSE(spi_strip->bytes_per_pixel == 4, ESP_ERR_INVALID_ARG, TAG, "wrong LED pixel format, expected 4 bytes per pixel"); + // LED_PIXEL_FORMAT_GRBW takes 96bits(12bytes) + uint32_t start = index * spi_strip->bytes_per_pixel * SPI_BYTES_PER_COLOR_BYTE; + // SK6812 component order is GRBW + memset(spi_strip->pixel_buf + start, 0, spi_strip->bytes_per_pixel * SPI_BYTES_PER_COLOR_BYTE); + __led_strip_spi_bit(green, &spi_strip->pixel_buf[start]); + __led_strip_spi_bit(red, &spi_strip->pixel_buf[start + SPI_BYTES_PER_COLOR_BYTE]); + __led_strip_spi_bit(blue, &spi_strip->pixel_buf[start + SPI_BYTES_PER_COLOR_BYTE * 2]); + __led_strip_spi_bit(white, &spi_strip->pixel_buf[start + SPI_BYTES_PER_COLOR_BYTE * 3]); + + return ESP_OK; +} + +static esp_err_t led_strip_spi_refresh(led_strip_t *strip) +{ + led_strip_spi_obj *spi_strip = __containerof(strip, led_strip_spi_obj, base); + spi_transaction_t tx_conf; + memset(&tx_conf, 0, sizeof(tx_conf)); + + tx_conf.length = spi_strip->strip_len * spi_strip->bytes_per_pixel * SPI_BITS_PER_COLOR_BYTE; + tx_conf.tx_buffer = spi_strip->pixel_buf; + tx_conf.rx_buffer = NULL; + ESP_RETURN_ON_ERROR(spi_device_transmit(spi_strip->spi_device, &tx_conf), TAG, "transmit pixels by SPI failed"); + + return ESP_OK; +} + +static esp_err_t led_strip_spi_clear(led_strip_t *strip) +{ + led_strip_spi_obj *spi_strip = __containerof(strip, led_strip_spi_obj, base); + //Write zero to turn off all leds + memset(spi_strip->pixel_buf, 0, spi_strip->strip_len * spi_strip->bytes_per_pixel * SPI_BYTES_PER_COLOR_BYTE); + uint8_t *buf = spi_strip->pixel_buf; + for (int index = 0; index < spi_strip->strip_len * spi_strip->bytes_per_pixel; index++) { + __led_strip_spi_bit(0, buf); + buf += SPI_BYTES_PER_COLOR_BYTE; + } + + return led_strip_spi_refresh(strip); +} + +static esp_err_t led_strip_spi_del(led_strip_t *strip) +{ + led_strip_spi_obj *spi_strip = __containerof(strip, led_strip_spi_obj, base); + + ESP_RETURN_ON_ERROR(spi_bus_remove_device(spi_strip->spi_device), TAG, "delete spi device failed"); + ESP_RETURN_ON_ERROR(spi_bus_free(spi_strip->spi_host), TAG, "free spi bus failed"); + + free(spi_strip); + return ESP_OK; +} + +esp_err_t led_strip_new_spi_device(const led_strip_config_t *led_config, const led_strip_spi_config_t *spi_config, led_strip_handle_t *ret_strip) +{ + led_strip_spi_obj *spi_strip = NULL; + esp_err_t ret = ESP_OK; + ESP_GOTO_ON_FALSE(led_config && spi_config && ret_strip, ESP_ERR_INVALID_ARG, err, TAG, "invalid argument"); + ESP_GOTO_ON_FALSE(led_config->led_pixel_format < LED_PIXEL_FORMAT_INVALID, ESP_ERR_INVALID_ARG, err, TAG, "invalid led_pixel_format"); + uint8_t bytes_per_pixel = 3; + if (led_config->led_pixel_format == LED_PIXEL_FORMAT_GRBW) { + bytes_per_pixel = 4; + } else if (led_config->led_pixel_format == LED_PIXEL_FORMAT_GRB) { + bytes_per_pixel = 3; + } else { + assert(false); + } + uint32_t mem_caps = MALLOC_CAP_DEFAULT; + if (spi_config->flags.with_dma) { + // DMA buffer must be placed in internal SRAM + mem_caps |= MALLOC_CAP_INTERNAL | MALLOC_CAP_DMA; + } + spi_strip = heap_caps_calloc(1, sizeof(led_strip_spi_obj) + led_config->max_leds * bytes_per_pixel * SPI_BYTES_PER_COLOR_BYTE, mem_caps); + + ESP_GOTO_ON_FALSE(spi_strip, ESP_ERR_NO_MEM, err, TAG, "no mem for spi strip"); + + spi_strip->spi_host = spi_config->spi_bus; + // for backward compatibility, if the user does not set the clk_src, use the default value + spi_clock_source_t clk_src = SPI_CLK_SRC_DEFAULT; + if (spi_config->clk_src) { + clk_src = spi_config->clk_src; + } + + spi_bus_config_t spi_bus_cfg = { + .mosi_io_num = led_config->strip_gpio_num, + //Only use MOSI to generate the signal, set -1 when other pins are not used. + .miso_io_num = -1, + .sclk_io_num = -1, + .quadwp_io_num = -1, + .quadhd_io_num = -1, + .max_transfer_sz = led_config->max_leds * bytes_per_pixel * SPI_BYTES_PER_COLOR_BYTE, + }; + ESP_GOTO_ON_ERROR(spi_bus_initialize(spi_strip->spi_host, &spi_bus_cfg, spi_config->flags.with_dma ? SPI_DMA_CH_AUTO : SPI_DMA_DISABLED), err, TAG, "create SPI bus failed"); + + if (led_config->flags.invert_out == true) { + esp_rom_gpio_connect_out_signal(led_config->strip_gpio_num, spi_periph_signal[spi_strip->spi_host].spid_out, true, false); + } + + spi_device_interface_config_t spi_dev_cfg = { + .clock_source = clk_src, + .command_bits = 0, + .address_bits = 0, + .dummy_bits = 0, + .clock_speed_hz = LED_STRIP_SPI_DEFAULT_RESOLUTION, + .mode = 0, + //set -1 when CS is not used + .spics_io_num = -1, + .queue_size = LED_STRIP_SPI_DEFAULT_TRANS_QUEUE_SIZE, + }; + + ESP_GOTO_ON_ERROR(spi_bus_add_device(spi_strip->spi_host, &spi_dev_cfg, &spi_strip->spi_device), err, TAG, "Failed to add spi device"); + //ensure the reset time is enough + esp_rom_delay_us(10); + int clock_resolution_khz = 0; + spi_device_get_actual_freq(spi_strip->spi_device, &clock_resolution_khz); + // TODO: ideally we should decide the SPI_BYTES_PER_COLOR_BYTE by the real clock resolution + // But now, let's fixed the resolution, the downside is, we don't support a clock source whose frequency is not multiple of LED_STRIP_SPI_DEFAULT_RESOLUTION + // clock_resolution between 2.2MHz to 2.8MHz is supported + ESP_GOTO_ON_FALSE((clock_resolution_khz < LED_STRIP_SPI_DEFAULT_RESOLUTION / 1000 + 300) && (clock_resolution_khz > LED_STRIP_SPI_DEFAULT_RESOLUTION / 1000 - 300), ESP_ERR_NOT_SUPPORTED, err, + TAG, "unsupported clock resolution:%dKHz", clock_resolution_khz); + + spi_strip->bytes_per_pixel = bytes_per_pixel; + spi_strip->strip_len = led_config->max_leds; + spi_strip->base.set_pixel = led_strip_spi_set_pixel; + spi_strip->base.set_pixel_rgbw = led_strip_spi_set_pixel_rgbw; + spi_strip->base.refresh = led_strip_spi_refresh; + spi_strip->base.clear = led_strip_spi_clear; + spi_strip->base.del = led_strip_spi_del; + + *ret_strip = &spi_strip->base; + return ESP_OK; +err: + if (spi_strip) { + if (spi_strip->spi_device) { + spi_bus_remove_device(spi_strip->spi_device); + } + if (spi_strip->spi_host) { + spi_bus_free(spi_strip->spi_host); + } + free(spi_strip); + } + return ret; +} diff --git a/scripts/led-test/sdkconfig b/scripts/led-test/sdkconfig new file mode 100644 index 0000000..105bc8c --- /dev/null +++ b/scripts/led-test/sdkconfig @@ -0,0 +1,2202 @@ +# +# Automatically generated file. DO NOT EDIT. +# Espressif IoT Development Framework (ESP-IDF) 5.5.5 Project Configuration +# +CONFIG_SOC_ADC_SUPPORTED=y +CONFIG_SOC_DEDICATED_GPIO_SUPPORTED=y +CONFIG_SOC_UART_SUPPORTED=y +CONFIG_SOC_GDMA_SUPPORTED=y +CONFIG_SOC_UHCI_SUPPORTED=y +CONFIG_SOC_AHB_GDMA_SUPPORTED=y +CONFIG_SOC_GPTIMER_SUPPORTED=y +CONFIG_SOC_TWAI_SUPPORTED=y +CONFIG_SOC_BT_SUPPORTED=y +CONFIG_SOC_ASYNC_MEMCPY_SUPPORTED=y +CONFIG_SOC_USB_SERIAL_JTAG_SUPPORTED=y +CONFIG_SOC_TEMP_SENSOR_SUPPORTED=y +CONFIG_SOC_XT_WDT_SUPPORTED=y +CONFIG_SOC_PHY_SUPPORTED=y +CONFIG_SOC_WIFI_SUPPORTED=y +CONFIG_SOC_SUPPORTS_SECURE_DL_MODE=y +CONFIG_SOC_EFUSE_KEY_PURPOSE_FIELD=y +CONFIG_SOC_EFUSE_HAS_EFUSE_RST_BUG=y +CONFIG_SOC_EFUSE_SUPPORTED=y +CONFIG_SOC_RTC_FAST_MEM_SUPPORTED=y +CONFIG_SOC_RTC_MEM_SUPPORTED=y +CONFIG_SOC_I2S_SUPPORTED=y +CONFIG_SOC_RMT_SUPPORTED=y +CONFIG_SOC_SDM_SUPPORTED=y +CONFIG_SOC_GPSPI_SUPPORTED=y +CONFIG_SOC_LEDC_SUPPORTED=y +CONFIG_SOC_I2C_SUPPORTED=y +CONFIG_SOC_SYSTIMER_SUPPORTED=y +CONFIG_SOC_SUPPORT_COEXISTENCE=y +CONFIG_SOC_AES_SUPPORTED=y +CONFIG_SOC_MPI_SUPPORTED=y +CONFIG_SOC_SHA_SUPPORTED=y +CONFIG_SOC_HMAC_SUPPORTED=y +CONFIG_SOC_DIG_SIGN_SUPPORTED=y +CONFIG_SOC_FLASH_ENC_SUPPORTED=y +CONFIG_SOC_SECURE_BOOT_SUPPORTED=y +CONFIG_SOC_MEMPROT_SUPPORTED=y +CONFIG_SOC_BOD_SUPPORTED=y +CONFIG_SOC_CLK_TREE_SUPPORTED=y +CONFIG_SOC_ASSIST_DEBUG_SUPPORTED=y +CONFIG_SOC_WDT_SUPPORTED=y +CONFIG_SOC_SPI_FLASH_SUPPORTED=y +CONFIG_SOC_RNG_SUPPORTED=y +CONFIG_SOC_LIGHT_SLEEP_SUPPORTED=y +CONFIG_SOC_DEEP_SLEEP_SUPPORTED=y +CONFIG_SOC_LP_PERIPH_SHARE_INTERRUPT=y +CONFIG_SOC_PM_SUPPORTED=y +CONFIG_SOC_XTAL_SUPPORT_40M=y +CONFIG_SOC_AES_SUPPORT_DMA=y +CONFIG_SOC_AES_GDMA=y +CONFIG_SOC_AES_SUPPORT_AES_128=y +CONFIG_SOC_AES_SUPPORT_AES_256=y +CONFIG_SOC_ADC_DIG_CTRL_SUPPORTED=y +CONFIG_SOC_ADC_ARBITER_SUPPORTED=y +CONFIG_SOC_ADC_DIG_IIR_FILTER_SUPPORTED=y +CONFIG_SOC_ADC_MONITOR_SUPPORTED=y +CONFIG_SOC_ADC_DMA_SUPPORTED=y +CONFIG_SOC_ADC_PERIPH_NUM=2 +CONFIG_SOC_ADC_MAX_CHANNEL_NUM=5 +CONFIG_SOC_ADC_ATTEN_NUM=4 +CONFIG_SOC_ADC_DIGI_CONTROLLER_NUM=1 +CONFIG_SOC_ADC_PATT_LEN_MAX=8 +CONFIG_SOC_ADC_DIGI_MIN_BITWIDTH=12 +CONFIG_SOC_ADC_DIGI_MAX_BITWIDTH=12 +CONFIG_SOC_ADC_DIGI_RESULT_BYTES=4 +CONFIG_SOC_ADC_DIGI_DATA_BYTES_PER_CONV=4 +CONFIG_SOC_ADC_DIGI_IIR_FILTER_NUM=2 +CONFIG_SOC_ADC_DIGI_MONITOR_NUM=2 +CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_HIGH=83333 +CONFIG_SOC_ADC_SAMPLE_FREQ_THRES_LOW=611 +CONFIG_SOC_ADC_RTC_MIN_BITWIDTH=12 +CONFIG_SOC_ADC_RTC_MAX_BITWIDTH=12 +CONFIG_SOC_ADC_CALIBRATION_V1_SUPPORTED=y +CONFIG_SOC_ADC_SELF_HW_CALI_SUPPORTED=y +CONFIG_SOC_ADC_SHARED_POWER=y +CONFIG_SOC_APB_BACKUP_DMA=y +CONFIG_SOC_BROWNOUT_RESET_SUPPORTED=y +CONFIG_SOC_SHARED_IDCACHE_SUPPORTED=y +CONFIG_SOC_CACHE_FREEZE_SUPPORTED=y +CONFIG_SOC_CACHE_MEMORY_IBANK_SIZE=0x4000 +CONFIG_SOC_CPU_CORES_NUM=1 +CONFIG_SOC_CPU_INTR_NUM=32 +CONFIG_SOC_CPU_HAS_FLEXIBLE_INTC=y +CONFIG_SOC_CPU_HAS_CSR_PC=y +CONFIG_SOC_CPU_BREAKPOINTS_NUM=8 +CONFIG_SOC_CPU_WATCHPOINTS_NUM=8 +CONFIG_SOC_CPU_WATCHPOINT_MAX_REGION_SIZE=0x80000000 +CONFIG_SOC_CPU_MISALIGNED_ACCESS_ON_PMP_MISMATCH_ISSUE=y +CONFIG_SOC_DS_SIGNATURE_MAX_BIT_LEN=3072 +CONFIG_SOC_DS_KEY_PARAM_MD_IV_LENGTH=16 +CONFIG_SOC_DS_KEY_CHECK_MAX_WAIT_US=1100 +CONFIG_SOC_AHB_GDMA_VERSION=1 +CONFIG_SOC_GDMA_NUM_GROUPS_MAX=1 +CONFIG_SOC_GDMA_PAIRS_PER_GROUP_MAX=3 +CONFIG_SOC_GPIO_PORT=1 +CONFIG_SOC_GPIO_PIN_COUNT=22 +CONFIG_SOC_GPIO_SUPPORT_PIN_GLITCH_FILTER=y +CONFIG_SOC_GPIO_FILTER_CLK_SUPPORT_APB=y +CONFIG_SOC_GPIO_SUPPORT_FORCE_HOLD=y +CONFIG_SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP=y +CONFIG_SOC_GPIO_IN_RANGE_MAX=21 +CONFIG_SOC_GPIO_OUT_RANGE_MAX=21 +CONFIG_SOC_GPIO_DEEP_SLEEP_WAKE_VALID_GPIO_MASK=0 +CONFIG_SOC_GPIO_DEEP_SLEEP_WAKE_SUPPORTED_PIN_CNT=6 +CONFIG_SOC_GPIO_VALID_DIGITAL_IO_PAD_MASK=0x00000000003FFFC0 +CONFIG_SOC_GPIO_CLOCKOUT_BY_GPIO_MATRIX=y +CONFIG_SOC_GPIO_CLOCKOUT_CHANNEL_NUM=3 +CONFIG_SOC_DEDIC_GPIO_OUT_CHANNELS_NUM=8 +CONFIG_SOC_DEDIC_GPIO_IN_CHANNELS_NUM=8 +CONFIG_SOC_DEDIC_PERIPH_ALWAYS_ENABLE=y +CONFIG_SOC_I2C_NUM=1 +CONFIG_SOC_HP_I2C_NUM=1 +CONFIG_SOC_I2C_FIFO_LEN=32 +CONFIG_SOC_I2C_CMD_REG_NUM=8 +CONFIG_SOC_I2C_SUPPORT_SLAVE=y +CONFIG_SOC_I2C_SUPPORT_HW_CLR_BUS=y +CONFIG_SOC_I2C_SUPPORT_XTAL=y +CONFIG_SOC_I2C_SUPPORT_RTC=y +CONFIG_SOC_I2C_SUPPORT_10BIT_ADDR=y +CONFIG_SOC_I2C_SLAVE_SUPPORT_BROADCAST=y +CONFIG_SOC_I2C_SLAVE_CAN_GET_STRETCH_CAUSE=y +CONFIG_SOC_I2C_SLAVE_SUPPORT_I2CRAM_ACCESS=y +CONFIG_SOC_I2S_NUM=1 +CONFIG_SOC_I2S_HW_VERSION_2=y +CONFIG_SOC_I2S_SUPPORTS_XTAL=y +CONFIG_SOC_I2S_SUPPORTS_PLL_F160M=y +CONFIG_SOC_I2S_SUPPORTS_PCM=y +CONFIG_SOC_I2S_SUPPORTS_PDM=y +CONFIG_SOC_I2S_SUPPORTS_PDM_TX=y +CONFIG_SOC_I2S_SUPPORTS_PCM2PDM=y +CONFIG_SOC_I2S_SUPPORTS_PDM_RX=y +CONFIG_SOC_I2S_PDM_MAX_TX_LINES=2 +CONFIG_SOC_I2S_PDM_MAX_RX_LINES=1 +CONFIG_SOC_I2S_SUPPORTS_TDM=y +CONFIG_SOC_LEDC_SUPPORT_APB_CLOCK=y +CONFIG_SOC_LEDC_SUPPORT_XTAL_CLOCK=y +CONFIG_SOC_LEDC_TIMER_NUM=4 +CONFIG_SOC_LEDC_CHANNEL_NUM=6 +CONFIG_SOC_LEDC_TIMER_BIT_WIDTH=14 +CONFIG_SOC_LEDC_SUPPORT_FADE_STOP=y +CONFIG_SOC_MMU_LINEAR_ADDRESS_REGION_NUM=1 +CONFIG_SOC_MMU_PERIPH_NUM=1 +CONFIG_SOC_MPU_MIN_REGION_SIZE=0x20000000 +CONFIG_SOC_MPU_REGIONS_MAX_NUM=8 +CONFIG_SOC_RMT_GROUPS=1 +CONFIG_SOC_RMT_TX_CANDIDATES_PER_GROUP=2 +CONFIG_SOC_RMT_RX_CANDIDATES_PER_GROUP=2 +CONFIG_SOC_RMT_CHANNELS_PER_GROUP=4 +CONFIG_SOC_RMT_MEM_WORDS_PER_CHANNEL=48 +CONFIG_SOC_RMT_SUPPORT_RX_PINGPONG=y +CONFIG_SOC_RMT_SUPPORT_RX_DEMODULATION=y +CONFIG_SOC_RMT_SUPPORT_ASYNC_STOP=y +CONFIG_SOC_RMT_SUPPORT_TX_LOOP_COUNT=y +CONFIG_SOC_RMT_SUPPORT_TX_SYNCHRO=y +CONFIG_SOC_RMT_SUPPORT_TX_CARRIER_DATA_ONLY=y +CONFIG_SOC_RMT_SUPPORT_XTAL=y +CONFIG_SOC_RMT_SUPPORT_APB=y +CONFIG_SOC_RMT_SUPPORT_RC_FAST=y +CONFIG_SOC_RTC_CNTL_CPU_PD_DMA_BUS_WIDTH=128 +CONFIG_SOC_RTC_CNTL_CPU_PD_REG_FILE_NUM=108 +CONFIG_SOC_RTC_CNTL_NEEDS_ATOMIC_ACCESS=y +CONFIG_SOC_SLEEP_SYSTIMER_STALL_WORKAROUND=y +CONFIG_SOC_SLEEP_TGWDT_STOP_WORKAROUND=y +CONFIG_SOC_RTCIO_PIN_COUNT=0 +CONFIG_SOC_MPI_MEM_BLOCKS_NUM=4 +CONFIG_SOC_MPI_OPERATIONS_NUM=3 +CONFIG_SOC_RSA_MAX_BIT_LEN=3072 +CONFIG_SOC_SHA_DMA_MAX_BUFFER_SIZE=3968 +CONFIG_SOC_SHA_SUPPORT_DMA=y +CONFIG_SOC_SHA_SUPPORT_RESUME=y +CONFIG_SOC_SHA_GDMA=y +CONFIG_SOC_SHA_SUPPORT_SHA1=y +CONFIG_SOC_SHA_SUPPORT_SHA224=y +CONFIG_SOC_SHA_SUPPORT_SHA256=y +CONFIG_SOC_SDM_GROUPS=1 +CONFIG_SOC_SDM_CHANNELS_PER_GROUP=4 +CONFIG_SOC_SDM_CLK_SUPPORT_APB=y +CONFIG_SOC_SPI_PERIPH_NUM=2 +CONFIG_SOC_SPI_MAX_CS_NUM=6 +CONFIG_SOC_SPI_MAXIMUM_BUFFER_SIZE=64 +CONFIG_SOC_SPI_SUPPORT_DDRCLK=y +CONFIG_SOC_SPI_SLAVE_SUPPORT_SEG_TRANS=y +CONFIG_SOC_SPI_SUPPORT_CD_SIG=y +CONFIG_SOC_SPI_SUPPORT_CONTINUOUS_TRANS=y +CONFIG_SOC_SPI_SUPPORT_SLAVE_HD_VER2=y +CONFIG_SOC_SPI_SUPPORT_CLK_APB=y +CONFIG_SOC_SPI_SUPPORT_CLK_XTAL=y +CONFIG_SOC_SPI_PERIPH_SUPPORT_CONTROL_DUMMY_OUT=y +CONFIG_SOC_SPI_SCT_SUPPORTED=y +CONFIG_SOC_SPI_SCT_REG_NUM=14 +CONFIG_SOC_SPI_SCT_BUFFER_NUM_MAX=y +CONFIG_SOC_SPI_SCT_CONF_BITLEN_MAX=0x3FFFA +CONFIG_SOC_MEMSPI_IS_INDEPENDENT=y +CONFIG_SOC_SPI_MAX_PRE_DIVIDER=16 +CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_WAIT_IDLE=y +CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_SUSPEND=y +CONFIG_SOC_SPI_MEM_SUPPORT_AUTO_RESUME=y +CONFIG_SOC_SPI_MEM_SUPPORT_IDLE_INTR=y +CONFIG_SOC_SPI_MEM_SUPPORT_SW_SUSPEND=y +CONFIG_SOC_SPI_MEM_SUPPORT_CHECK_SUS=y +CONFIG_SOC_SPI_MEM_SUPPORT_CONFIG_GPIO_BY_EFUSE=y +CONFIG_SOC_SPI_MEM_SUPPORT_WRAP=y +CONFIG_SOC_MEMSPI_ENCRYPTION_ALIGNMENT=16 +CONFIG_SOC_SYSTIMER_COUNTER_NUM=2 +CONFIG_SOC_SYSTIMER_ALARM_NUM=3 +CONFIG_SOC_SYSTIMER_BIT_WIDTH_LO=32 +CONFIG_SOC_SYSTIMER_BIT_WIDTH_HI=20 +CONFIG_SOC_SYSTIMER_FIXED_DIVIDER=y +CONFIG_SOC_SYSTIMER_INT_LEVEL=y +CONFIG_SOC_SYSTIMER_ALARM_MISS_COMPENSATE=y +CONFIG_SOC_TIMER_GROUPS=2 +CONFIG_SOC_TIMER_GROUP_TIMERS_PER_GROUP=1 +CONFIG_SOC_TIMER_GROUP_COUNTER_BIT_WIDTH=54 +CONFIG_SOC_TIMER_GROUP_SUPPORT_XTAL=y +CONFIG_SOC_TIMER_GROUP_SUPPORT_APB=y +CONFIG_SOC_TIMER_GROUP_TOTAL_TIMERS=2 +CONFIG_SOC_LP_TIMER_BIT_WIDTH_LO=32 +CONFIG_SOC_LP_TIMER_BIT_WIDTH_HI=16 +CONFIG_SOC_MWDT_SUPPORT_XTAL=y +CONFIG_SOC_TWAI_CONTROLLER_NUM=1 +CONFIG_SOC_TWAI_MASK_FILTER_NUM=1 +CONFIG_SOC_TWAI_CLK_SUPPORT_APB=y +CONFIG_SOC_TWAI_BRP_MIN=2 +CONFIG_SOC_TWAI_BRP_MAX=16384 +CONFIG_SOC_TWAI_SUPPORTS_RX_STATUS=y +CONFIG_SOC_EFUSE_DIS_DOWNLOAD_ICACHE=y +CONFIG_SOC_EFUSE_DIS_PAD_JTAG=y +CONFIG_SOC_EFUSE_DIS_USB_JTAG=y +CONFIG_SOC_EFUSE_DIS_DIRECT_BOOT=y +CONFIG_SOC_EFUSE_SOFT_DIS_JTAG=y +CONFIG_SOC_EFUSE_DIS_ICACHE=y +CONFIG_SOC_EFUSE_BLOCK9_KEY_PURPOSE_QUIRK=y +CONFIG_SOC_SECURE_BOOT_V2_RSA=y +CONFIG_SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS=3 +CONFIG_SOC_EFUSE_REVOKE_BOOT_KEY_DIGESTS=y +CONFIG_SOC_SUPPORT_SECURE_BOOT_REVOKE_KEY=y +CONFIG_SOC_FLASH_ENCRYPTED_XTS_AES_BLOCK_MAX=32 +CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES=y +CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_128=y +CONFIG_SOC_MEMPROT_CPU_PREFETCH_PAD_SIZE=16 +CONFIG_SOC_MEMPROT_MEM_ALIGN_SIZE=512 +CONFIG_SOC_UART_NUM=2 +CONFIG_SOC_UART_HP_NUM=2 +CONFIG_SOC_UART_FIFO_LEN=128 +CONFIG_SOC_UART_BITRATE_MAX=5000000 +CONFIG_SOC_UART_SUPPORT_APB_CLK=y +CONFIG_SOC_UART_SUPPORT_RTC_CLK=y +CONFIG_SOC_UART_SUPPORT_XTAL_CLK=y +CONFIG_SOC_UART_SUPPORT_WAKEUP_INT=y +CONFIG_SOC_UART_SUPPORT_FSM_TX_WAIT_SEND=y +CONFIG_SOC_UART_WAKEUP_SUPPORT_ACTIVE_THRESH_MODE=y +CONFIG_SOC_UHCI_NUM=1 +CONFIG_SOC_COEX_HW_PTI=y +CONFIG_SOC_PHY_DIG_REGS_MEM_SIZE=21 +CONFIG_SOC_MAC_BB_PD_MEM_SIZE=192 +CONFIG_SOC_WIFI_LIGHT_SLEEP_CLK_WIDTH=12 +CONFIG_SOC_PM_SUPPORT_WIFI_WAKEUP=y +CONFIG_SOC_PM_SUPPORT_BT_WAKEUP=y +CONFIG_SOC_PM_SUPPORT_CPU_PD=y +CONFIG_SOC_PM_SUPPORT_WIFI_PD=y +CONFIG_SOC_PM_SUPPORT_BT_PD=y +CONFIG_SOC_PM_SUPPORT_RC_FAST_PD=y +CONFIG_SOC_PM_SUPPORT_VDDSDIO_PD=y +CONFIG_SOC_PM_SUPPORT_MAC_BB_PD=y +CONFIG_SOC_PM_CPU_RETENTION_BY_RTCCNTL=y +CONFIG_SOC_PM_MODEM_RETENTION_BY_BACKUPDMA=y +CONFIG_SOC_PM_MODEM_PD_BY_SW=y +CONFIG_SOC_CLK_RC_FAST_D256_SUPPORTED=y +CONFIG_SOC_RTC_SLOW_CLK_SUPPORT_RC_FAST_D256=y +CONFIG_SOC_CLK_RC_FAST_SUPPORT_CALIBRATION=y +CONFIG_SOC_CLK_XTAL32K_SUPPORTED=y +CONFIG_SOC_CLK_LP_FAST_SUPPORT_XTAL_D2=y +CONFIG_SOC_TEMPERATURE_SENSOR_SUPPORT_FAST_RC=y +CONFIG_SOC_TEMPERATURE_SENSOR_SUPPORT_XTAL=y +CONFIG_SOC_WIFI_HW_TSF=y +CONFIG_SOC_WIFI_FTM_SUPPORT=y +CONFIG_SOC_WIFI_GCMP_SUPPORT=y +CONFIG_SOC_WIFI_WAPI_SUPPORT=y +CONFIG_SOC_WIFI_TXOP_SUPPORT=y +CONFIG_SOC_WIFI_CSI_SUPPORT=y +CONFIG_SOC_WIFI_MESH_SUPPORT=y +CONFIG_SOC_WIFI_SUPPORT_VARIABLE_BEACON_WINDOW=y +CONFIG_SOC_WIFI_PHY_NEEDS_USB_WORKAROUND=y +CONFIG_SOC_BLE_SUPPORTED=y +CONFIG_SOC_BLE_MESH_SUPPORTED=y +CONFIG_SOC_BLE_50_SUPPORTED=y +CONFIG_SOC_BLE_DEVICE_PRIVACY_SUPPORTED=y +CONFIG_SOC_BLUFI_SUPPORTED=y +CONFIG_SOC_PHY_COMBO_MODULE=y +CONFIG_IDF_CMAKE=y +CONFIG_IDF_TOOLCHAIN="gcc" +CONFIG_IDF_TOOLCHAIN_GCC=y +CONFIG_IDF_TARGET_ARCH_RISCV=y +CONFIG_IDF_TARGET_ARCH="riscv" +CONFIG_IDF_TARGET="esp32c3" +CONFIG_IDF_INIT_VERSION="5.5.5" +CONFIG_IDF_TARGET_ESP32C3=y +CONFIG_IDF_FIRMWARE_CHIP_ID=0x0005 + +# +# Build type +# +CONFIG_APP_BUILD_TYPE_APP_2NDBOOT=y +# CONFIG_APP_BUILD_TYPE_RAM is not set +CONFIG_APP_BUILD_GENERATE_BINARIES=y +CONFIG_APP_BUILD_BOOTLOADER=y +CONFIG_APP_BUILD_USE_FLASH_SECTIONS=y +# CONFIG_APP_REPRODUCIBLE_BUILD is not set +# CONFIG_APP_NO_BLOBS is not set +# end of Build type + +# +# Bootloader config +# + +# +# Bootloader manager +# +CONFIG_BOOTLOADER_COMPILE_TIME_DATE=y +CONFIG_BOOTLOADER_PROJECT_VER=1 +# end of Bootloader manager + +# +# Application Rollback +# +# CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE is not set +# end of Application Rollback + +# +# Recovery Bootloader and Rollback +# +# end of Recovery Bootloader and Rollback + +CONFIG_BOOTLOADER_OFFSET_IN_FLASH=0x0 +CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_SIZE=y +# CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_DEBUG is not set +# CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_PERF is not set +# CONFIG_BOOTLOADER_COMPILER_OPTIMIZATION_NONE is not set + +# +# Log +# +CONFIG_BOOTLOADER_LOG_VERSION_1=y +CONFIG_BOOTLOADER_LOG_VERSION=1 +# CONFIG_BOOTLOADER_LOG_LEVEL_NONE is not set +# CONFIG_BOOTLOADER_LOG_LEVEL_ERROR is not set +# CONFIG_BOOTLOADER_LOG_LEVEL_WARN is not set +CONFIG_BOOTLOADER_LOG_LEVEL_INFO=y +# CONFIG_BOOTLOADER_LOG_LEVEL_DEBUG is not set +# CONFIG_BOOTLOADER_LOG_LEVEL_VERBOSE is not set +CONFIG_BOOTLOADER_LOG_LEVEL=3 + +# +# Format +# +# CONFIG_BOOTLOADER_LOG_COLORS is not set +CONFIG_BOOTLOADER_LOG_TIMESTAMP_SOURCE_CPU_TICKS=y +# end of Format + +# +# Settings +# +CONFIG_BOOTLOADER_LOG_MODE_TEXT_EN=y +CONFIG_BOOTLOADER_LOG_MODE_TEXT=y +# end of Settings +# end of Log + +# +# Serial Flash Configurations +# +# CONFIG_BOOTLOADER_FLASH_DC_AWARE is not set +CONFIG_BOOTLOADER_FLASH_XMC_SUPPORT=y +# end of Serial Flash Configurations + +# CONFIG_BOOTLOADER_FACTORY_RESET is not set +# CONFIG_BOOTLOADER_APP_TEST is not set +CONFIG_BOOTLOADER_REGION_PROTECTION_ENABLE=y +CONFIG_BOOTLOADER_WDT_ENABLE=y +# CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE is not set +CONFIG_BOOTLOADER_WDT_TIME_MS=9000 +# CONFIG_BOOTLOADER_SKIP_VALIDATE_IN_DEEP_SLEEP is not set +# CONFIG_BOOTLOADER_SKIP_VALIDATE_ON_POWER_ON is not set +# CONFIG_BOOTLOADER_SKIP_VALIDATE_ALWAYS is not set +CONFIG_BOOTLOADER_RESERVE_RTC_SIZE=0 +# CONFIG_BOOTLOADER_CUSTOM_RESERVE_RTC is not set +# end of Bootloader config + +# +# Security features +# +CONFIG_SECURE_BOOT_V2_RSA_SUPPORTED=y +CONFIG_SECURE_BOOT_V2_PREFERRED=y +# CONFIG_SECURE_SIGNED_APPS_NO_SECURE_BOOT is not set +# CONFIG_SECURE_BOOT is not set +# CONFIG_SECURE_FLASH_ENC_ENABLED is not set +CONFIG_SECURE_ROM_DL_MODE_ENABLED=y +# end of Security features + +# +# Application manager +# +CONFIG_APP_COMPILE_TIME_DATE=y +# CONFIG_APP_EXCLUDE_PROJECT_VER_VAR is not set +# CONFIG_APP_EXCLUDE_PROJECT_NAME_VAR is not set +# CONFIG_APP_PROJECT_VER_FROM_CONFIG is not set +CONFIG_APP_RETRIEVE_LEN_ELF_SHA=9 +# end of Application manager + +CONFIG_ESP_ROM_HAS_CRC_LE=y +CONFIG_ESP_ROM_HAS_CRC_BE=y +CONFIG_ESP_ROM_HAS_MZ_CRC32=y +CONFIG_ESP_ROM_HAS_JPEG_DECODE=y +CONFIG_ESP_ROM_UART_CLK_IS_XTAL=y +CONFIG_ESP_ROM_USB_SERIAL_DEVICE_NUM=3 +CONFIG_ESP_ROM_HAS_RETARGETABLE_LOCKING=y +CONFIG_ESP_ROM_HAS_ERASE_0_REGION_BUG=y +CONFIG_ESP_ROM_HAS_ENCRYPTED_WRITES_USING_LEGACY_DRV=y +CONFIG_ESP_ROM_GET_CLK_FREQ=y +CONFIG_ESP_ROM_NEEDS_SWSETUP_WORKAROUND=y +CONFIG_ESP_ROM_HAS_LAYOUT_TABLE=y +CONFIG_ESP_ROM_HAS_SPI_FLASH=y +CONFIG_ESP_ROM_HAS_SPI_FLASH_MMAP=y +CONFIG_ESP_ROM_HAS_ETS_PRINTF_BUG=y +CONFIG_ESP_ROM_HAS_NEWLIB=y +CONFIG_ESP_ROM_HAS_NEWLIB_NANO_FORMAT=y +CONFIG_ESP_ROM_HAS_NEWLIB_32BIT_TIME=y +CONFIG_ESP_ROM_NEEDS_SET_CACHE_MMU_SIZE=y +CONFIG_ESP_ROM_RAM_APP_NEEDS_MMU_INIT=y +CONFIG_ESP_ROM_HAS_SW_FLOAT=y +CONFIG_ESP_ROM_USB_OTG_NUM=-1 +CONFIG_ESP_ROM_HAS_VERSION=y +CONFIG_ESP_ROM_SUPPORT_DEEP_SLEEP_WAKEUP_STUB=y +CONFIG_ESP_ROM_CONSOLE_OUTPUT_SECONDARY=y +CONFIG_ESP_ROM_HAS_SUBOPTIMAL_NEWLIB_ON_MISALIGNED_MEMORY=y + +# +# Boot ROM Behavior +# +CONFIG_BOOT_ROM_LOG_ALWAYS_ON=y +# CONFIG_BOOT_ROM_LOG_ALWAYS_OFF is not set +# CONFIG_BOOT_ROM_LOG_ON_GPIO_HIGH is not set +# CONFIG_BOOT_ROM_LOG_ON_GPIO_LOW is not set +# end of Boot ROM Behavior + +# +# Serial flasher config +# +# CONFIG_ESPTOOLPY_NO_STUB is not set +# CONFIG_ESPTOOLPY_FLASHMODE_QIO is not set +# CONFIG_ESPTOOLPY_FLASHMODE_QOUT is not set +CONFIG_ESPTOOLPY_FLASHMODE_DIO=y +# CONFIG_ESPTOOLPY_FLASHMODE_DOUT is not set +CONFIG_ESPTOOLPY_FLASH_SAMPLE_MODE_STR=y +CONFIG_ESPTOOLPY_FLASHMODE="dio" +CONFIG_ESPTOOLPY_FLASHFREQ_80M=y +# CONFIG_ESPTOOLPY_FLASHFREQ_40M is not set +# CONFIG_ESPTOOLPY_FLASHFREQ_26M is not set +# CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set +CONFIG_ESPTOOLPY_FLASHFREQ="80m" +# CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set +CONFIG_ESPTOOLPY_FLASHSIZE_2MB=y +# CONFIG_ESPTOOLPY_FLASHSIZE_4MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_16MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set +CONFIG_ESPTOOLPY_FLASHSIZE="2MB" +# CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set +CONFIG_ESPTOOLPY_BEFORE_RESET=y +# CONFIG_ESPTOOLPY_BEFORE_NORESET is not set +CONFIG_ESPTOOLPY_BEFORE="default_reset" +CONFIG_ESPTOOLPY_AFTER_RESET=y +# CONFIG_ESPTOOLPY_AFTER_NORESET is not set +CONFIG_ESPTOOLPY_AFTER="hard_reset" +CONFIG_ESPTOOLPY_MONITOR_BAUD=115200 +# end of Serial flasher config + +# +# Partition Table +# +CONFIG_PARTITION_TABLE_SINGLE_APP=y +# CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE is not set +# CONFIG_PARTITION_TABLE_TWO_OTA is not set +# CONFIG_PARTITION_TABLE_TWO_OTA_LARGE is not set +# CONFIG_PARTITION_TABLE_CUSTOM is not set +CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" +CONFIG_PARTITION_TABLE_FILENAME="partitions_singleapp.csv" +CONFIG_PARTITION_TABLE_OFFSET=0x8000 +CONFIG_PARTITION_TABLE_MD5=y +# end of Partition Table + +# +# Compiler options +# +CONFIG_COMPILER_OPTIMIZATION_DEBUG=y +# CONFIG_COMPILER_OPTIMIZATION_SIZE is not set +# CONFIG_COMPILER_OPTIMIZATION_PERF is not set +# CONFIG_COMPILER_OPTIMIZATION_NONE is not set +CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE=y +# CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT is not set +# CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_DISABLE is not set +CONFIG_COMPILER_ASSERT_NDEBUG_EVALUATE=y +CONFIG_COMPILER_FLOAT_LIB_FROM_GCCLIB=y +CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL=2 +# CONFIG_COMPILER_OPTIMIZATION_CHECKS_SILENT is not set +CONFIG_COMPILER_HIDE_PATHS_MACROS=y +# CONFIG_COMPILER_CXX_EXCEPTIONS is not set +# CONFIG_COMPILER_CXX_RTTI is not set +CONFIG_COMPILER_STACK_CHECK_MODE_NONE=y +# CONFIG_COMPILER_STACK_CHECK_MODE_NORM is not set +# CONFIG_COMPILER_STACK_CHECK_MODE_STRONG is not set +# CONFIG_COMPILER_STACK_CHECK_MODE_ALL is not set +# CONFIG_COMPILER_NO_MERGE_CONSTANTS is not set +# CONFIG_COMPILER_WARN_WRITE_STRINGS is not set +# CONFIG_COMPILER_SAVE_RESTORE_LIBCALLS is not set +CONFIG_COMPILER_DISABLE_DEFAULT_ERRORS=y +# CONFIG_COMPILER_DISABLE_GCC12_WARNINGS is not set +# CONFIG_COMPILER_DISABLE_GCC13_WARNINGS is not set +# CONFIG_COMPILER_DISABLE_GCC14_WARNINGS is not set +# CONFIG_COMPILER_DUMP_RTL_FILES is not set +CONFIG_COMPILER_RT_LIB_GCCLIB=y +CONFIG_COMPILER_RT_LIB_NAME="gcc" +CONFIG_COMPILER_ORPHAN_SECTIONS_WARNING=y +# CONFIG_COMPILER_ORPHAN_SECTIONS_PLACE is not set +# CONFIG_COMPILER_STATIC_ANALYZER is not set +# end of Compiler options + +# +# Component config +# + +# +# Application Level Tracing +# +# CONFIG_APPTRACE_DEST_JTAG is not set +CONFIG_APPTRACE_DEST_NONE=y +# CONFIG_APPTRACE_DEST_UART0 is not set +# CONFIG_APPTRACE_DEST_UART1 is not set +# CONFIG_APPTRACE_DEST_USB_CDC is not set +CONFIG_APPTRACE_DEST_UART_NONE=y +CONFIG_APPTRACE_UART_TASK_PRIO=1 +CONFIG_APPTRACE_LOCK_ENABLE=y +# end of Application Level Tracing + +# +# Bluetooth +# +# CONFIG_BT_ENABLED is not set + +# +# Common Options +# + +# +# BT Logs +# + +# +# Log Sources +# +# end of Log Sources + +# CONFIG_BT_LOG_CRITICAL_ONLY is not set +# CONFIG_BLE_LOG_ENABLED is not set + +# +# Legacy SPI Log Output (Deprecated - use BT Log Async Output instead) +# +# CONFIG_BT_BLE_LOG_SPI_OUT_ENABLED is not set +# end of Legacy SPI Log Output (Deprecated - use BT Log Async Output instead) +# end of BT Logs + +# CONFIG_BT_LE_USED_MEM_STATISTICS_ENABLED is not set +# end of Common Options +# end of Bluetooth + +# +# Console Library +# +# CONFIG_CONSOLE_SORTED_HELP is not set +# end of Console Library + +# +# Driver Configurations +# + +# +# Legacy TWAI Driver Configurations +# +# CONFIG_TWAI_SKIP_LEGACY_CONFLICT_CHECK is not set +CONFIG_TWAI_ERRATA_FIX_LISTEN_ONLY_DOM=y +# end of Legacy TWAI Driver Configurations + +# +# Legacy ADC Driver Configuration +# +# CONFIG_ADC_SUPPRESS_DEPRECATE_WARN is not set +# CONFIG_ADC_SKIP_LEGACY_CONFLICT_CHECK is not set + +# +# Legacy ADC Calibration Configuration +# +# CONFIG_ADC_CALI_SUPPRESS_DEPRECATE_WARN is not set +# end of Legacy ADC Calibration Configuration +# end of Legacy ADC Driver Configuration + +# +# Legacy Timer Group Driver Configurations +# +# CONFIG_GPTIMER_SUPPRESS_DEPRECATE_WARN is not set +# CONFIG_GPTIMER_SKIP_LEGACY_CONFLICT_CHECK is not set +# end of Legacy Timer Group Driver Configurations + +# +# Legacy RMT Driver Configurations +# +# CONFIG_RMT_SUPPRESS_DEPRECATE_WARN is not set +# CONFIG_RMT_SKIP_LEGACY_CONFLICT_CHECK is not set +# end of Legacy RMT Driver Configurations + +# +# Legacy I2S Driver Configurations +# +# CONFIG_I2S_SUPPRESS_DEPRECATE_WARN is not set +# CONFIG_I2S_SKIP_LEGACY_CONFLICT_CHECK is not set +# end of Legacy I2S Driver Configurations + +# +# Legacy I2C Driver Configurations +# +# CONFIG_I2C_SKIP_LEGACY_CONFLICT_CHECK is not set +# end of Legacy I2C Driver Configurations + +# +# Legacy SDM Driver Configurations +# +# CONFIG_SDM_SUPPRESS_DEPRECATE_WARN is not set +# CONFIG_SDM_SKIP_LEGACY_CONFLICT_CHECK is not set +# end of Legacy SDM Driver Configurations + +# +# Legacy Temperature Sensor Driver Configurations +# +# CONFIG_TEMP_SENSOR_SUPPRESS_DEPRECATE_WARN is not set +# CONFIG_TEMP_SENSOR_SKIP_LEGACY_CONFLICT_CHECK is not set +# end of Legacy Temperature Sensor Driver Configurations +# end of Driver Configurations + +# +# eFuse Bit Manager +# +# CONFIG_EFUSE_CUSTOM_TABLE is not set +# CONFIG_EFUSE_VIRTUAL is not set +CONFIG_EFUSE_MAX_BLK_LEN=256 +# end of eFuse Bit Manager + +# +# ESP-TLS +# +CONFIG_ESP_TLS_USING_MBEDTLS=y +# CONFIG_ESP_TLS_USE_SECURE_ELEMENT is not set +CONFIG_ESP_TLS_USE_DS_PERIPHERAL=y +# CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS is not set +# CONFIG_ESP_TLS_SERVER_SESSION_TICKETS is not set +# CONFIG_ESP_TLS_SERVER_CERT_SELECT_HOOK is not set +# CONFIG_ESP_TLS_SERVER_MIN_AUTH_MODE_OPTIONAL is not set +# CONFIG_ESP_TLS_PSK_VERIFICATION is not set +# CONFIG_ESP_TLS_INSECURE is not set +CONFIG_ESP_TLS_DYN_BUF_STRATEGY_SUPPORTED=y +# end of ESP-TLS + +# +# ADC and ADC Calibration +# +# CONFIG_ADC_ONESHOT_CTRL_FUNC_IN_IRAM is not set +# CONFIG_ADC_CONTINUOUS_ISR_IRAM_SAFE is not set +# CONFIG_ADC_CONTINUOUS_FORCE_USE_ADC2_ON_C3_S3 is not set +# CONFIG_ADC_ONESHOT_FORCE_USE_ADC2_ON_C3 is not set +# CONFIG_ADC_ENABLE_DEBUG_LOG is not set +# end of ADC and ADC Calibration + +# +# Wireless Coexistence +# +CONFIG_ESP_COEX_ENABLED=y +# CONFIG_ESP_COEX_EXTERNAL_COEXIST_ENABLE is not set +# CONFIG_ESP_COEX_GPIO_DEBUG is not set +# end of Wireless Coexistence + +# +# Common ESP-related +# +CONFIG_ESP_ERR_TO_NAME_LOOKUP=y +# end of Common ESP-related + +# +# ESP-Driver:GPIO Configurations +# +# CONFIG_GPIO_CTRL_FUNC_IN_IRAM is not set +# end of ESP-Driver:GPIO Configurations + +# +# ESP-Driver:GPTimer Configurations +# +CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y +# CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is not set +# CONFIG_GPTIMER_ISR_CACHE_SAFE is not set +CONFIG_GPTIMER_OBJ_CACHE_SAFE=y +# CONFIG_GPTIMER_ENABLE_DEBUG_LOG is not set +# end of ESP-Driver:GPTimer Configurations + +# +# ESP-Driver:I2C Configurations +# +# CONFIG_I2C_ISR_IRAM_SAFE is not set +# CONFIG_I2C_ENABLE_DEBUG_LOG is not set +# CONFIG_I2C_ENABLE_SLAVE_DRIVER_VERSION_2 is not set +CONFIG_I2C_MASTER_ISR_HANDLER_IN_IRAM=y +# end of ESP-Driver:I2C Configurations + +# +# ESP-Driver:I2S Configurations +# +# CONFIG_I2S_ISR_IRAM_SAFE is not set +# CONFIG_I2S_ENABLE_DEBUG_LOG is not set +# end of ESP-Driver:I2S Configurations + +# +# ESP-Driver:LEDC Configurations +# +# CONFIG_LEDC_CTRL_FUNC_IN_IRAM is not set +# end of ESP-Driver:LEDC Configurations + +# +# ESP-Driver:RMT Configurations +# +CONFIG_RMT_ENCODER_FUNC_IN_IRAM=y +CONFIG_RMT_TX_ISR_HANDLER_IN_IRAM=y +CONFIG_RMT_RX_ISR_HANDLER_IN_IRAM=y +# CONFIG_RMT_RECV_FUNC_IN_IRAM is not set +# CONFIG_RMT_TX_ISR_CACHE_SAFE is not set +# CONFIG_RMT_RX_ISR_CACHE_SAFE is not set +CONFIG_RMT_OBJ_CACHE_SAFE=y +# CONFIG_RMT_ENABLE_DEBUG_LOG is not set +# CONFIG_RMT_ISR_IRAM_SAFE is not set +# end of ESP-Driver:RMT Configurations + +# +# ESP-Driver:Sigma Delta Modulator Configurations +# +# CONFIG_SDM_CTRL_FUNC_IN_IRAM is not set +# CONFIG_SDM_ENABLE_DEBUG_LOG is not set +# end of ESP-Driver:Sigma Delta Modulator Configurations + +# +# ESP-Driver:SPI Configurations +# +# CONFIG_SPI_MASTER_IN_IRAM is not set +CONFIG_SPI_MASTER_ISR_IN_IRAM=y +# CONFIG_SPI_SLAVE_IN_IRAM is not set +CONFIG_SPI_SLAVE_ISR_IN_IRAM=y +# end of ESP-Driver:SPI Configurations + +# +# ESP-Driver:Temperature Sensor Configurations +# +# CONFIG_TEMP_SENSOR_ENABLE_DEBUG_LOG is not set +# end of ESP-Driver:Temperature Sensor Configurations + +# +# ESP-Driver:TWAI Configurations +# +# CONFIG_TWAI_ISR_IN_IRAM is not set +# CONFIG_TWAI_IO_FUNC_IN_IRAM is not set +# CONFIG_TWAI_ISR_CACHE_SAFE is not set +# CONFIG_TWAI_ENABLE_DEBUG_LOG is not set +# end of ESP-Driver:TWAI Configurations + +# +# ESP-Driver:UART Configurations +# +# CONFIG_UART_ISR_IN_IRAM is not set +# end of ESP-Driver:UART Configurations + +# +# ESP-Driver:UHCI Configurations +# +# CONFIG_UHCI_ISR_HANDLER_IN_IRAM is not set +# CONFIG_UHCI_ISR_CACHE_SAFE is not set +# CONFIG_UHCI_ENABLE_DEBUG_LOG is not set +# end of ESP-Driver:UHCI Configurations + +# +# ESP-Driver:USB Serial/JTAG Configuration +# +CONFIG_USJ_ENABLE_USB_SERIAL_JTAG=y +# end of ESP-Driver:USB Serial/JTAG Configuration + +# +# Ethernet +# +CONFIG_ETH_ENABLED=y +CONFIG_ETH_USE_SPI_ETHERNET=y +# CONFIG_ETH_SPI_ETHERNET_DM9051 is not set +# CONFIG_ETH_SPI_ETHERNET_W5500 is not set +# CONFIG_ETH_SPI_ETHERNET_KSZ8851SNL is not set +# CONFIG_ETH_USE_OPENETH is not set +# CONFIG_ETH_TRANSMIT_MUTEX is not set +# end of Ethernet + +# +# Event Loop Library +# +# CONFIG_ESP_EVENT_LOOP_PROFILING is not set +CONFIG_ESP_EVENT_POST_FROM_ISR=y +CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR=y +# end of Event Loop Library + +# +# GDB Stub +# +CONFIG_ESP_GDBSTUB_ENABLED=y +# CONFIG_ESP_SYSTEM_GDBSTUB_RUNTIME is not set +CONFIG_ESP_GDBSTUB_SUPPORT_TASKS=y +CONFIG_ESP_GDBSTUB_MAX_TASKS=32 +# end of GDB Stub + +# +# ESP HID +# +CONFIG_ESPHID_TASK_SIZE_BT=2048 +CONFIG_ESPHID_TASK_SIZE_BLE=4096 +# end of ESP HID + +# +# ESP HTTP client +# +CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS=y +# CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH is not set +# CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH is not set +# CONFIG_ESP_HTTP_CLIENT_ENABLE_CUSTOM_TRANSPORT is not set +CONFIG_ESP_HTTP_CLIENT_EVENT_POST_TIMEOUT=2000 +# end of ESP HTTP client + +# +# HTTP Server +# +CONFIG_HTTPD_MAX_REQ_HDR_LEN=1024 +CONFIG_HTTPD_MAX_URI_LEN=512 +CONFIG_HTTPD_ERR_RESP_NO_DELAY=y +CONFIG_HTTPD_PURGE_BUF_LEN=32 +# CONFIG_HTTPD_LOG_PURGE_DATA is not set +# CONFIG_HTTPD_WS_SUPPORT is not set +# CONFIG_HTTPD_QUEUE_WORK_BLOCKING is not set +CONFIG_HTTPD_SERVER_EVENT_POST_TIMEOUT=2000 +# end of HTTP Server + +# +# ESP HTTPS OTA +# +# CONFIG_ESP_HTTPS_OTA_DECRYPT_CB is not set +# CONFIG_ESP_HTTPS_OTA_ALLOW_HTTP is not set +CONFIG_ESP_HTTPS_OTA_EVENT_POST_TIMEOUT=2000 +# end of ESP HTTPS OTA + +# +# ESP HTTPS server +# +# CONFIG_ESP_HTTPS_SERVER_ENABLE is not set +CONFIG_ESP_HTTPS_SERVER_EVENT_POST_TIMEOUT=2000 +# CONFIG_ESP_HTTPS_SERVER_CERT_SELECT_HOOK is not set +# end of ESP HTTPS server + +# +# Hardware Settings +# +CONFIG_ESP_HW_SUPPORT_FUNC_IN_IRAM=y + +# +# Chip revision +# +# CONFIG_ESP32C3_REV_MIN_0 is not set +# CONFIG_ESP32C3_REV_MIN_1 is not set +# CONFIG_ESP32C3_REV_MIN_2 is not set +CONFIG_ESP32C3_REV_MIN_3=y +# CONFIG_ESP32C3_REV_MIN_4 is not set +# CONFIG_ESP32C3_REV_MIN_101 is not set +CONFIG_ESP32C3_REV_MIN_FULL=3 +CONFIG_ESP_REV_MIN_FULL=3 + +# +# Maximum Supported ESP32-C3 Revision (Rev v1.99) +# +CONFIG_ESP32C3_REV_MAX_FULL=199 +CONFIG_ESP_REV_MAX_FULL=199 +CONFIG_ESP_EFUSE_BLOCK_REV_MIN_FULL=0 +CONFIG_ESP_EFUSE_BLOCK_REV_MAX_FULL=199 + +# +# Maximum Supported ESP32-C3 eFuse Block Revision (eFuse Block Rev v1.99) +# +# end of Chip revision + +# +# MAC Config +# +CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_STA=y +CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_AP=y +CONFIG_ESP_MAC_ADDR_UNIVERSE_BT=y +CONFIG_ESP_MAC_ADDR_UNIVERSE_ETH=y +CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES_FOUR=y +CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES=4 +# CONFIG_ESP32C3_UNIVERSAL_MAC_ADDRESSES_TWO is not set +CONFIG_ESP32C3_UNIVERSAL_MAC_ADDRESSES_FOUR=y +CONFIG_ESP32C3_UNIVERSAL_MAC_ADDRESSES=4 +# CONFIG_ESP_MAC_USE_CUSTOM_MAC_AS_BASE_MAC is not set +# end of MAC Config + +# +# Sleep Config +# +# CONFIG_ESP_SLEEP_POWER_DOWN_FLASH is not set +CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND=y +# CONFIG_ESP_SLEEP_MSPI_NEED_ALL_IO_PU is not set +CONFIG_ESP_SLEEP_GPIO_RESET_WORKAROUND=y +CONFIG_ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY=0 +# CONFIG_ESP_SLEEP_CACHE_SAFE_ASSERTION is not set +# CONFIG_ESP_SLEEP_DEBUG is not set +CONFIG_ESP_SLEEP_GPIO_ENABLE_INTERNAL_RESISTORS=y +# end of Sleep Config + +# +# RTC Clock Config +# +CONFIG_RTC_CLK_SRC_INT_RC=y +# CONFIG_RTC_CLK_SRC_EXT_CRYS is not set +# CONFIG_RTC_CLK_SRC_EXT_OSC is not set +# CONFIG_RTC_CLK_SRC_INT_8MD256 is not set +CONFIG_RTC_CLK_CAL_CYCLES=1024 +CONFIG_RTC_CLK_FUNC_IN_IRAM=y +CONFIG_RTC_TIME_FUNC_IN_IRAM=y +# end of RTC Clock Config + +# +# Peripheral Control +# +CONFIG_ESP_PERIPH_CTRL_FUNC_IN_IRAM=y +CONFIG_ESP_REGI2C_CTRL_FUNC_IN_IRAM=y +# end of Peripheral Control + +# +# GDMA Configurations +# +CONFIG_GDMA_CTRL_FUNC_IN_IRAM=y +CONFIG_GDMA_ISR_HANDLER_IN_IRAM=y +CONFIG_GDMA_OBJ_DRAM_SAFE=y +# CONFIG_GDMA_ENABLE_DEBUG_LOG is not set +# CONFIG_GDMA_ISR_IRAM_SAFE is not set +# end of GDMA Configurations + +# +# Main XTAL Config +# +CONFIG_XTAL_FREQ_40=y +CONFIG_XTAL_FREQ=40 +# end of Main XTAL Config + +# +# Power Supplier +# + +# +# Brownout Detector +# +CONFIG_ESP_BROWNOUT_DET=y +CONFIG_ESP_BROWNOUT_DET_LVL_SEL_7=y +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_6 is not set +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_5 is not set +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_4 is not set +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_3 is not set +# CONFIG_ESP_BROWNOUT_DET_LVL_SEL_2 is not set +CONFIG_ESP_BROWNOUT_DET_LVL=7 +CONFIG_ESP_BROWNOUT_USE_INTR=y +# end of Brownout Detector +# end of Power Supplier + +CONFIG_ESP_SPI_BUS_LOCK_ISR_FUNCS_IN_IRAM=y +CONFIG_ESP_INTR_IN_IRAM=y +# end of Hardware Settings + +# +# ESP-Driver:LCD Controller Configurations +# +# CONFIG_LCD_ENABLE_DEBUG_LOG is not set +# end of ESP-Driver:LCD Controller Configurations + +# +# ESP-MM: Memory Management Configurations +# +# end of ESP-MM: Memory Management Configurations + +# +# ESP NETIF Adapter +# +CONFIG_ESP_NETIF_IP_LOST_TIMER_INTERVAL=120 +# CONFIG_ESP_NETIF_PROVIDE_CUSTOM_IMPLEMENTATION is not set +CONFIG_ESP_NETIF_TCPIP_LWIP=y +# CONFIG_ESP_NETIF_LOOPBACK is not set +CONFIG_ESP_NETIF_USES_TCPIP_WITH_BSD_API=y +CONFIG_ESP_NETIF_REPORT_DATA_TRAFFIC=y +# CONFIG_ESP_NETIF_RECEIVE_REPORT_ERRORS is not set +# CONFIG_ESP_NETIF_L2_TAP is not set +# CONFIG_ESP_NETIF_BRIDGE_EN is not set +# CONFIG_ESP_NETIF_SET_DNS_PER_DEFAULT_NETIF is not set +# end of ESP NETIF Adapter + +# +# Partition API Configuration +# +# end of Partition API Configuration + +# +# PHY +# +CONFIG_ESP_PHY_ENABLED=y +CONFIG_ESP_PHY_CALIBRATION_AND_DATA_STORAGE=y +# CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION is not set +CONFIG_ESP_PHY_MAX_WIFI_TX_POWER=20 +CONFIG_ESP_PHY_MAX_TX_POWER=20 +# CONFIG_ESP_PHY_REDUCE_TX_POWER is not set +CONFIG_ESP_PHY_ENABLE_USB=y +# CONFIG_ESP_PHY_ENABLE_CERT_TEST is not set +CONFIG_ESP_PHY_RF_CAL_PARTIAL=y +# CONFIG_ESP_PHY_RF_CAL_NONE is not set +# CONFIG_ESP_PHY_RF_CAL_FULL is not set +CONFIG_ESP_PHY_CALIBRATION_MODE=0 +CONFIG_ESP_PHY_PLL_TRACK_PERIOD_MS=1000 +# CONFIG_ESP_PHY_PLL_TRACK_DEBUG is not set +# CONFIG_ESP_PHY_RECORD_USED_TIME is not set +CONFIG_ESP_PHY_IRAM_OPT=y +# CONFIG_ESP_PHY_DEBUG is not set +CONFIG_ESP_PHY_ENABLE_VERSION_PRINT=y +# end of PHY + +# +# Power Management +# +# CONFIG_PM_SLEEP_FUNC_IN_IRAM is not set +# CONFIG_PM_ENABLE is not set +# CONFIG_PM_SLP_IRAM_OPT is not set +CONFIG_PM_POWER_DOWN_CPU_IN_LIGHT_SLEEP=y +# end of Power Management + +# +# ESP PSRAM +# + +# +# ESP Ringbuf +# +# CONFIG_RINGBUF_PLACE_FUNCTIONS_INTO_FLASH is not set +# end of ESP Ringbuf + +# +# ESP-ROM +# +CONFIG_ESP_ROM_PRINT_IN_IRAM=y +# end of ESP-ROM + +# +# ESP Security Specific +# +# end of ESP Security Specific + +# +# ESP System Settings +# +# CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_80 is not set +CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_160=y +CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=160 +CONFIG_ESP_SYSTEM_IN_IRAM=y +# CONFIG_ESP_SYSTEM_PANIC_PRINT_HALT is not set +CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT=y +# CONFIG_ESP_SYSTEM_PANIC_SILENT_REBOOT is not set +# CONFIG_ESP_SYSTEM_PANIC_GDBSTUB is not set +CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS=0 +CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE=y +CONFIG_ESP_SYSTEM_RTC_FAST_MEM_AS_HEAP_DEPCHECK=y +CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP=y +CONFIG_ESP_SYSTEM_NO_BACKTRACE=y +# CONFIG_ESP_SYSTEM_USE_EH_FRAME is not set +# CONFIG_ESP_SYSTEM_USE_FRAME_POINTER is not set + +# +# Memory protection +# +CONFIG_ESP_SYSTEM_MEMPROT_FEATURE=y +CONFIG_ESP_SYSTEM_MEMPROT_FEATURE_LOCK=y +# end of Memory protection + +CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE=32 +CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE=2304 +CONFIG_ESP_MAIN_TASK_STACK_SIZE=3584 +CONFIG_ESP_MAIN_TASK_AFFINITY_CPU0=y +# CONFIG_ESP_MAIN_TASK_AFFINITY_NO_AFFINITY is not set +CONFIG_ESP_MAIN_TASK_AFFINITY=0x0 +CONFIG_ESP_MINIMAL_SHARED_STACK_SIZE=2048 +# CONFIG_ESP_CONSOLE_UART_DEFAULT is not set +CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y +# CONFIG_ESP_CONSOLE_UART_CUSTOM is not set +# CONFIG_ESP_CONSOLE_NONE is not set +CONFIG_ESP_CONSOLE_SECONDARY_NONE=y +CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED=y +CONFIG_ESP_CONSOLE_UART_NUM=-1 +CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM=3 +CONFIG_ESP_INT_WDT=y +CONFIG_ESP_INT_WDT_TIMEOUT_MS=300 +CONFIG_ESP_TASK_WDT_EN=y +CONFIG_ESP_TASK_WDT_INIT=y +# CONFIG_ESP_TASK_WDT_PANIC is not set +CONFIG_ESP_TASK_WDT_TIMEOUT_S=5 +CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0=y +# CONFIG_ESP_PANIC_HANDLER_IRAM is not set +# CONFIG_ESP_DEBUG_STUBS_ENABLE is not set +CONFIG_ESP_DEBUG_OCDAWARE=y +CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL_4=y +CONFIG_ESP_SYSTEM_HW_STACK_GUARD=y +CONFIG_ESP_SYSTEM_HW_PC_RECORD=y +# end of ESP System Settings + +# +# IPC (Inter-Processor Call) +# +CONFIG_ESP_IPC_TASK_STACK_SIZE=1024 +# end of IPC (Inter-Processor Call) + +# +# ESP Timer (High Resolution Timer) +# +CONFIG_ESP_TIMER_IN_IRAM=y +# CONFIG_ESP_TIMER_PROFILING is not set +CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER=y +CONFIG_ESP_TIME_FUNCS_USE_ESP_TIMER=y +CONFIG_ESP_TIMER_TASK_STACK_SIZE=3584 +CONFIG_ESP_TIMER_INTERRUPT_LEVEL=1 +# CONFIG_ESP_TIMER_SHOW_EXPERIMENTAL is not set +CONFIG_ESP_TIMER_TASK_AFFINITY=0x0 +CONFIG_ESP_TIMER_TASK_AFFINITY_CPU0=y +CONFIG_ESP_TIMER_ISR_AFFINITY_CPU0=y +# CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD is not set +CONFIG_ESP_TIMER_IMPL_SYSTIMER=y +# end of ESP Timer (High Resolution Timer) + +# +# Wi-Fi +# +CONFIG_ESP_WIFI_ENABLED=y +CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=10 +CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=32 +# CONFIG_ESP_WIFI_STATIC_TX_BUFFER is not set +CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER=y +CONFIG_ESP_WIFI_TX_BUFFER_TYPE=1 +CONFIG_ESP_WIFI_DYNAMIC_TX_BUFFER_NUM=32 +CONFIG_ESP_WIFI_STATIC_RX_MGMT_BUFFER=y +# CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUFFER is not set +CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUF=0 +CONFIG_ESP_WIFI_RX_MGMT_BUF_NUM_DEF=5 +# CONFIG_ESP_WIFI_CSI_ENABLED is not set +CONFIG_ESP_WIFI_AMPDU_TX_ENABLED=y +CONFIG_ESP_WIFI_TX_BA_WIN=6 +CONFIG_ESP_WIFI_AMPDU_RX_ENABLED=y +CONFIG_ESP_WIFI_RX_BA_WIN=6 +CONFIG_ESP_WIFI_NVS_ENABLED=y +CONFIG_ESP_WIFI_SOFTAP_BEACON_MAX_LEN=752 +CONFIG_ESP_WIFI_MGMT_SBUF_NUM=32 +CONFIG_ESP_WIFI_IRAM_OPT=y +# CONFIG_ESP_WIFI_EXTRA_IRAM_OPT is not set +CONFIG_ESP_WIFI_RX_IRAM_OPT=y +CONFIG_ESP_WIFI_ENABLE_WPA3_SAE=y +CONFIG_ESP_WIFI_ENABLE_SAE_PK=y +CONFIG_ESP_WIFI_ENABLE_SAE_H2E=y +CONFIG_ESP_WIFI_SOFTAP_SAE_SUPPORT=y +CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA=y +# CONFIG_ESP_WIFI_SLP_IRAM_OPT is not set +CONFIG_ESP_WIFI_SLP_DEFAULT_MIN_ACTIVE_TIME=50 +# CONFIG_ESP_WIFI_BSS_MAX_IDLE_SUPPORT is not set +CONFIG_ESP_WIFI_SLP_DEFAULT_MAX_ACTIVE_TIME=10 +CONFIG_ESP_WIFI_SLP_DEFAULT_WAIT_BROADCAST_DATA_TIME=15 +# CONFIG_ESP_WIFI_FTM_ENABLE is not set +CONFIG_ESP_WIFI_STA_DISCONNECTED_PM_ENABLE=y +# CONFIG_ESP_WIFI_GCMP_SUPPORT is not set +CONFIG_ESP_WIFI_GMAC_SUPPORT=y +CONFIG_ESP_WIFI_SOFTAP_SUPPORT=y +# CONFIG_ESP_WIFI_SLP_BEACON_LOST_OPT is not set +CONFIG_ESP_WIFI_ESPNOW_MAX_ENCRYPT_NUM=7 +CONFIG_ESP_WIFI_MBEDTLS_CRYPTO=y +CONFIG_ESP_WIFI_MBEDTLS_TLS_CLIENT=y +# CONFIG_ESP_WIFI_WAPI_PSK is not set +# CONFIG_ESP_WIFI_SUITE_B_192 is not set +# CONFIG_ESP_WIFI_11KV_SUPPORT is not set +# CONFIG_ESP_WIFI_MBO_SUPPORT is not set +# CONFIG_ESP_WIFI_DPP_SUPPORT is not set +# CONFIG_ESP_WIFI_P256_ACCEL is not set +# CONFIG_ESP_WIFI_11R_SUPPORT is not set +# CONFIG_ESP_WIFI_WPS_SOFTAP_REGISTRAR is not set + +# +# WPS Configuration Options +# +# CONFIG_ESP_WIFI_WPS_STRICT is not set +# CONFIG_ESP_WIFI_WPS_PASSPHRASE is not set +# CONFIG_ESP_WIFI_WPS_RECONNECT_ON_FAIL is not set +# end of WPS Configuration Options + +# CONFIG_ESP_WIFI_DEBUG_PRINT is not set +CONFIG_ESP_WIFI_ENTERPRISE_SUPPORT=y +# CONFIG_ESP_WIFI_ENT_FREE_DYNAMIC_BUFFER is not set +# CONFIG_ESP_WIFI_PASSIVE_HIDDEN_AP_SUPPORT is not set +# end of Wi-Fi + +# +# Core dump +# +# CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH is not set +# CONFIG_ESP_COREDUMP_ENABLE_TO_UART is not set +CONFIG_ESP_COREDUMP_ENABLE_TO_NONE=y +# end of Core dump + +# +# FAT Filesystem support +# +CONFIG_FATFS_VOLUME_COUNT=2 +CONFIG_FATFS_LFN_NONE=y +# CONFIG_FATFS_LFN_HEAP is not set +# CONFIG_FATFS_LFN_STACK is not set +# CONFIG_FATFS_SECTOR_512 is not set +CONFIG_FATFS_SECTOR_4096=y +# CONFIG_FATFS_CODEPAGE_DYNAMIC is not set +CONFIG_FATFS_CODEPAGE_437=y +# CONFIG_FATFS_CODEPAGE_720 is not set +# CONFIG_FATFS_CODEPAGE_737 is not set +# CONFIG_FATFS_CODEPAGE_771 is not set +# CONFIG_FATFS_CODEPAGE_775 is not set +# CONFIG_FATFS_CODEPAGE_850 is not set +# CONFIG_FATFS_CODEPAGE_852 is not set +# CONFIG_FATFS_CODEPAGE_855 is not set +# CONFIG_FATFS_CODEPAGE_857 is not set +# CONFIG_FATFS_CODEPAGE_860 is not set +# CONFIG_FATFS_CODEPAGE_861 is not set +# CONFIG_FATFS_CODEPAGE_862 is not set +# CONFIG_FATFS_CODEPAGE_863 is not set +# CONFIG_FATFS_CODEPAGE_864 is not set +# CONFIG_FATFS_CODEPAGE_865 is not set +# CONFIG_FATFS_CODEPAGE_866 is not set +# CONFIG_FATFS_CODEPAGE_869 is not set +# CONFIG_FATFS_CODEPAGE_932 is not set +# CONFIG_FATFS_CODEPAGE_936 is not set +# CONFIG_FATFS_CODEPAGE_949 is not set +# CONFIG_FATFS_CODEPAGE_950 is not set +CONFIG_FATFS_CODEPAGE=437 +CONFIG_FATFS_FS_LOCK=0 +CONFIG_FATFS_TIMEOUT_MS=10000 +CONFIG_FATFS_PER_FILE_CACHE=y +# CONFIG_FATFS_USE_FASTSEEK is not set +CONFIG_FATFS_USE_STRFUNC_NONE=y +# CONFIG_FATFS_USE_STRFUNC_WITHOUT_CRLF_CONV is not set +# CONFIG_FATFS_USE_STRFUNC_WITH_CRLF_CONV is not set +CONFIG_FATFS_VFS_FSTAT_BLKSIZE=0 +# CONFIG_FATFS_IMMEDIATE_FSYNC is not set +# CONFIG_FATFS_USE_LABEL is not set +CONFIG_FATFS_LINK_LOCK=y +# CONFIG_FATFS_USE_DYN_BUFFERS is not set + +# +# File system free space calculation behavior +# +CONFIG_FATFS_DONT_TRUST_FREE_CLUSTER_CNT=0 +CONFIG_FATFS_DONT_TRUST_LAST_ALLOC=0 +# end of File system free space calculation behavior +# end of FAT Filesystem support + +# +# FreeRTOS +# + +# +# Kernel +# +# CONFIG_FREERTOS_SMP is not set +CONFIG_FREERTOS_UNICORE=y +CONFIG_FREERTOS_HZ=100 +CONFIG_FREERTOS_OPTIMIZED_SCHEDULER=y +# CONFIG_FREERTOS_CHECK_STACKOVERFLOW_NONE is not set +# CONFIG_FREERTOS_CHECK_STACKOVERFLOW_PTRVAL is not set +CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY=y +CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS=1 +CONFIG_FREERTOS_IDLE_TASK_STACKSIZE=1536 +# CONFIG_FREERTOS_USE_IDLE_HOOK is not set +# CONFIG_FREERTOS_USE_TICK_HOOK is not set +CONFIG_FREERTOS_MAX_TASK_NAME_LEN=16 +# CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY is not set +CONFIG_FREERTOS_USE_TIMERS=y +CONFIG_FREERTOS_TIMER_SERVICE_TASK_NAME="Tmr Svc" +# CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU0 is not set +CONFIG_FREERTOS_TIMER_TASK_NO_AFFINITY=y +CONFIG_FREERTOS_TIMER_SERVICE_TASK_CORE_AFFINITY=0x7FFFFFFF +CONFIG_FREERTOS_TIMER_TASK_PRIORITY=1 +CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=2048 +CONFIG_FREERTOS_TIMER_QUEUE_LENGTH=10 +CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE=0 +CONFIG_FREERTOS_TASK_NOTIFICATION_ARRAY_ENTRIES=1 +# CONFIG_FREERTOS_USE_TRACE_FACILITY is not set +# CONFIG_FREERTOS_USE_LIST_DATA_INTEGRITY_CHECK_BYTES is not set +# CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS is not set +# CONFIG_FREERTOS_USE_APPLICATION_TASK_TAG is not set +# end of Kernel + +# +# Port +# +CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER=y +# CONFIG_FREERTOS_WATCHPOINT_END_OF_STACK is not set +CONFIG_FREERTOS_TLSP_DELETION_CALLBACKS=y +# CONFIG_FREERTOS_TASK_PRE_DELETION_HOOK is not set +# CONFIG_FREERTOS_ENABLE_STATIC_TASK_CLEAN_UP is not set +CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER=y +CONFIG_FREERTOS_ISR_STACKSIZE=1536 +CONFIG_FREERTOS_INTERRUPT_BACKTRACE=y +CONFIG_FREERTOS_TICK_SUPPORT_SYSTIMER=y +CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL1=y +# CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL3 is not set +CONFIG_FREERTOS_SYSTICK_USES_SYSTIMER=y +# CONFIG_FREERTOS_PLACE_FUNCTIONS_INTO_FLASH is not set +# CONFIG_FREERTOS_CHECK_PORT_CRITICAL_COMPLIANCE is not set +# end of Port + +# +# Extra +# +# end of Extra + +CONFIG_FREERTOS_PORT=y +CONFIG_FREERTOS_NO_AFFINITY=0x7FFFFFFF +CONFIG_FREERTOS_SUPPORT_STATIC_ALLOCATION=y +CONFIG_FREERTOS_DEBUG_OCDAWARE=y +CONFIG_FREERTOS_ENABLE_TASK_SNAPSHOT=y +CONFIG_FREERTOS_PLACE_SNAPSHOT_FUNS_INTO_FLASH=y +CONFIG_FREERTOS_NUMBER_OF_CORES=1 +CONFIG_FREERTOS_IN_IRAM=y +# end of FreeRTOS + +# +# Hardware Abstraction Layer (HAL) and Low Level (LL) +# +CONFIG_HAL_ASSERTION_EQUALS_SYSTEM=y +# CONFIG_HAL_ASSERTION_DISABLE is not set +# CONFIG_HAL_ASSERTION_SILENT is not set +# CONFIG_HAL_ASSERTION_ENABLE is not set +CONFIG_HAL_DEFAULT_ASSERTION_LEVEL=2 +# end of Hardware Abstraction Layer (HAL) and Low Level (LL) + +# +# Heap memory debugging +# +CONFIG_HEAP_POISONING_DISABLED=y +# CONFIG_HEAP_POISONING_LIGHT is not set +# CONFIG_HEAP_POISONING_COMPREHENSIVE is not set +CONFIG_HEAP_TRACING_OFF=y +# CONFIG_HEAP_TRACING_STANDALONE is not set +# CONFIG_HEAP_TRACING_TOHOST is not set +# CONFIG_HEAP_USE_HOOKS is not set +# CONFIG_HEAP_TASK_TRACKING is not set +# CONFIG_HEAP_ABORT_WHEN_ALLOCATION_FAILS is not set +# CONFIG_HEAP_PLACE_FUNCTION_INTO_FLASH is not set +# end of Heap memory debugging + +# +# Log +# +CONFIG_LOG_VERSION_1=y +# CONFIG_LOG_VERSION_2 is not set +CONFIG_LOG_VERSION=1 + +# +# Log Level +# +# CONFIG_LOG_DEFAULT_LEVEL_NONE is not set +# CONFIG_LOG_DEFAULT_LEVEL_ERROR is not set +# CONFIG_LOG_DEFAULT_LEVEL_WARN is not set +CONFIG_LOG_DEFAULT_LEVEL_INFO=y +# CONFIG_LOG_DEFAULT_LEVEL_DEBUG is not set +# CONFIG_LOG_DEFAULT_LEVEL_VERBOSE is not set +CONFIG_LOG_DEFAULT_LEVEL=3 +CONFIG_LOG_MAXIMUM_EQUALS_DEFAULT=y +# CONFIG_LOG_MAXIMUM_LEVEL_DEBUG is not set +# CONFIG_LOG_MAXIMUM_LEVEL_VERBOSE is not set +CONFIG_LOG_MAXIMUM_LEVEL=3 + +# +# Level Settings +# +# CONFIG_LOG_MASTER_LEVEL is not set +CONFIG_LOG_DYNAMIC_LEVEL_CONTROL=y +# CONFIG_LOG_TAG_LEVEL_IMPL_NONE is not set +# CONFIG_LOG_TAG_LEVEL_IMPL_LINKED_LIST is not set +CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_AND_LINKED_LIST=y +# CONFIG_LOG_TAG_LEVEL_CACHE_ARRAY is not set +CONFIG_LOG_TAG_LEVEL_CACHE_BINARY_MIN_HEAP=y +CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_SIZE=31 +# end of Level Settings +# end of Log Level + +# +# Format +# +# CONFIG_LOG_COLORS is not set +CONFIG_LOG_TIMESTAMP_SOURCE_RTOS=y +# CONFIG_LOG_TIMESTAMP_SOURCE_SYSTEM is not set +# end of Format + +# +# Settings +# +CONFIG_LOG_MODE_TEXT_EN=y +CONFIG_LOG_MODE_TEXT=y +# end of Settings + +CONFIG_LOG_IN_IRAM=y +# end of Log + +# +# LWIP +# +CONFIG_LWIP_ENABLE=y +CONFIG_LWIP_LOCAL_HOSTNAME="espressif" +CONFIG_LWIP_TCPIP_TASK_PRIO=18 +# CONFIG_LWIP_TCPIP_CORE_LOCKING is not set +# CONFIG_LWIP_CHECK_THREAD_SAFETY is not set +CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES=y +# CONFIG_LWIP_L2_TO_L3_COPY is not set +# CONFIG_LWIP_IRAM_OPTIMIZATION is not set +# CONFIG_LWIP_EXTRA_IRAM_OPTIMIZATION is not set +CONFIG_LWIP_TIMERS_ONDEMAND=y +CONFIG_LWIP_ND6=y +# CONFIG_LWIP_FORCE_ROUTER_FORWARDING is not set +CONFIG_LWIP_MAX_SOCKETS=10 +# CONFIG_LWIP_USE_ONLY_LWIP_SELECT is not set +# CONFIG_LWIP_SO_LINGER is not set +CONFIG_LWIP_SO_REUSE=y +CONFIG_LWIP_SO_REUSE_RXTOALL=y +# CONFIG_LWIP_SO_RCVBUF is not set +# CONFIG_LWIP_NETBUF_RECVINFO is not set +CONFIG_LWIP_IP_DEFAULT_TTL=64 +CONFIG_LWIP_IP4_FRAG=y +CONFIG_LWIP_IP6_FRAG=y +# CONFIG_LWIP_IP4_REASSEMBLY is not set +# CONFIG_LWIP_IP6_REASSEMBLY is not set +CONFIG_LWIP_IP_REASS_MAX_PBUFS=10 +# CONFIG_LWIP_IP_FORWARD is not set +# CONFIG_LWIP_STATS is not set +CONFIG_LWIP_ESP_GRATUITOUS_ARP=y +CONFIG_LWIP_GARP_TMR_INTERVAL=60 +CONFIG_LWIP_ESP_MLDV6_REPORT=y +CONFIG_LWIP_MLDV6_TMR_INTERVAL=40 +CONFIG_LWIP_TCPIP_RECVMBOX_SIZE=32 +CONFIG_LWIP_DHCP_DOES_ARP_CHECK=y +# CONFIG_LWIP_DHCP_DOES_ACD_CHECK is not set +# CONFIG_LWIP_DHCP_DOES_NOT_CHECK_OFFERED_IP is not set +# CONFIG_LWIP_DHCP_DISABLE_CLIENT_ID is not set +CONFIG_LWIP_DHCP_DISABLE_VENDOR_CLASS_ID=y +# CONFIG_LWIP_DHCP_RESTORE_LAST_IP is not set +CONFIG_LWIP_DHCP_OPTIONS_LEN=69 +CONFIG_LWIP_NUM_NETIF_CLIENT_DATA=0 +CONFIG_LWIP_DHCP_COARSE_TIMER_SECS=1 + +# +# DHCP server +# +CONFIG_LWIP_DHCPS=y +CONFIG_LWIP_DHCPS_LEASE_UNIT=60 +CONFIG_LWIP_DHCPS_MAX_STATION_NUM=8 +CONFIG_LWIP_DHCPS_STATIC_ENTRIES=y +CONFIG_LWIP_DHCPS_ADD_DNS=y +# end of DHCP server + +# CONFIG_LWIP_AUTOIP is not set +CONFIG_LWIP_IPV4=y +CONFIG_LWIP_IPV6=y +# CONFIG_LWIP_IPV6_AUTOCONFIG is not set +CONFIG_LWIP_IPV6_NUM_ADDRESSES=3 +# CONFIG_LWIP_IPV6_FORWARD is not set +# CONFIG_LWIP_NETIF_STATUS_CALLBACK is not set +CONFIG_LWIP_NETIF_LOOPBACK=y +CONFIG_LWIP_LOOPBACK_MAX_PBUFS=8 + +# +# TCP +# +CONFIG_LWIP_MAX_ACTIVE_TCP=16 +CONFIG_LWIP_MAX_LISTENING_TCP=16 +CONFIG_LWIP_TCP_HIGH_SPEED_RETRANSMISSION=y +CONFIG_LWIP_TCP_MAXRTX=12 +CONFIG_LWIP_TCP_SYNMAXRTX=12 +CONFIG_LWIP_TCP_MSS=1440 +CONFIG_LWIP_TCP_TMR_INTERVAL=250 +CONFIG_LWIP_TCP_MSL=60000 +CONFIG_LWIP_TCP_FIN_WAIT_TIMEOUT=20000 +CONFIG_LWIP_TCP_SND_BUF_DEFAULT=5760 +CONFIG_LWIP_TCP_WND_DEFAULT=5760 +CONFIG_LWIP_TCP_RECVMBOX_SIZE=6 +CONFIG_LWIP_TCP_ACCEPTMBOX_SIZE=6 +CONFIG_LWIP_TCP_QUEUE_OOSEQ=y +CONFIG_LWIP_TCP_OOSEQ_TIMEOUT=6 +CONFIG_LWIP_TCP_OOSEQ_MAX_PBUFS=4 +# CONFIG_LWIP_TCP_SACK_OUT is not set +CONFIG_LWIP_TCP_OVERSIZE_MSS=y +# CONFIG_LWIP_TCP_OVERSIZE_QUARTER_MSS is not set +# CONFIG_LWIP_TCP_OVERSIZE_DISABLE is not set +CONFIG_LWIP_TCP_RTO_TIME=1500 +# end of TCP + +# +# UDP +# +CONFIG_LWIP_MAX_UDP_PCBS=16 +CONFIG_LWIP_UDP_RECVMBOX_SIZE=6 +# end of UDP + +# +# Checksums +# +# CONFIG_LWIP_CHECKSUM_CHECK_IP is not set +# CONFIG_LWIP_CHECKSUM_CHECK_UDP is not set +CONFIG_LWIP_CHECKSUM_CHECK_ICMP=y +# end of Checksums + +CONFIG_LWIP_TCPIP_TASK_STACK_SIZE=3072 +CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY=y +# CONFIG_LWIP_TCPIP_TASK_AFFINITY_CPU0 is not set +CONFIG_LWIP_TCPIP_TASK_AFFINITY=0x7FFFFFFF +CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE=3 +CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS=5 +CONFIG_LWIP_IPV6_ND6_NUM_PREFIXES=5 +CONFIG_LWIP_IPV6_ND6_NUM_ROUTERS=3 +CONFIG_LWIP_IPV6_ND6_NUM_DESTINATIONS=10 +# CONFIG_LWIP_IPV6_ND6_ROUTE_INFO_OPTION_SUPPORT is not set +# CONFIG_LWIP_PPP_SUPPORT is not set +# CONFIG_LWIP_SLIP_SUPPORT is not set + +# +# ICMP +# +CONFIG_LWIP_ICMP=y +# CONFIG_LWIP_MULTICAST_PING is not set +# CONFIG_LWIP_BROADCAST_PING is not set +# end of ICMP + +# +# LWIP RAW API +# +CONFIG_LWIP_MAX_RAW_PCBS=16 +# end of LWIP RAW API + +# +# SNTP +# +CONFIG_LWIP_SNTP_MAX_SERVERS=1 +# CONFIG_LWIP_DHCP_GET_NTP_SRV is not set +CONFIG_LWIP_SNTP_UPDATE_DELAY=3600000 +CONFIG_LWIP_SNTP_STARTUP_DELAY=y +CONFIG_LWIP_SNTP_MAXIMUM_STARTUP_DELAY=5000 +# end of SNTP + +# +# DNS +# +CONFIG_LWIP_DNS_MAX_HOST_IP=1 +CONFIG_LWIP_DNS_MAX_SERVERS=3 +# CONFIG_LWIP_FALLBACK_DNS_SERVER_SUPPORT is not set +# CONFIG_LWIP_DNS_SETSERVER_WITH_NETIF is not set +# CONFIG_LWIP_USE_ESP_GETADDRINFO is not set +# end of DNS + +CONFIG_LWIP_BRIDGEIF_MAX_PORTS=7 +CONFIG_LWIP_ESP_LWIP_ASSERT=y + +# +# Hooks +# +# CONFIG_LWIP_HOOK_TCP_ISN_NONE is not set +CONFIG_LWIP_HOOK_TCP_ISN_DEFAULT=y +# CONFIG_LWIP_HOOK_TCP_ISN_CUSTOM is not set +CONFIG_LWIP_HOOK_IP6_ROUTE_NONE=y +# CONFIG_LWIP_HOOK_IP6_ROUTE_DEFAULT is not set +# CONFIG_LWIP_HOOK_IP6_ROUTE_CUSTOM is not set +CONFIG_LWIP_HOOK_ND6_GET_GW_NONE=y +# CONFIG_LWIP_HOOK_ND6_GET_GW_DEFAULT is not set +# CONFIG_LWIP_HOOK_ND6_GET_GW_CUSTOM is not set +CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_NONE=y +# CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_DEFAULT is not set +# CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_CUSTOM is not set +CONFIG_LWIP_HOOK_DHCP_EXTRA_OPTION_NONE=y +# CONFIG_LWIP_HOOK_DHCP_EXTRA_OPTION_DEFAULT is not set +# CONFIG_LWIP_HOOK_DHCP_EXTRA_OPTION_CUSTOM is not set +CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE=y +# CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_DEFAULT is not set +# CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_CUSTOM is not set +CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_NONE=y +# CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_CUSTOM is not set +# CONFIG_LWIP_HOOK_IP6_INPUT_NONE is not set +CONFIG_LWIP_HOOK_IP6_INPUT_DEFAULT=y +# CONFIG_LWIP_HOOK_IP6_INPUT_CUSTOM is not set +# end of Hooks + +# CONFIG_LWIP_DEBUG is not set +# end of LWIP + +# +# mbedTLS +# +CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC=y +# CONFIG_MBEDTLS_DEFAULT_MEM_ALLOC is not set +# CONFIG_MBEDTLS_CUSTOM_MEM_ALLOC is not set +CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN=y +CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN=16384 +CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN=4096 +# CONFIG_MBEDTLS_DYNAMIC_BUFFER is not set +# CONFIG_MBEDTLS_DEBUG is not set + +# +# mbedTLS v3.x related +# +# CONFIG_MBEDTLS_SSL_PROTO_TLS1_3 is not set +# CONFIG_MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH is not set +# CONFIG_MBEDTLS_X509_TRUSTED_CERT_CALLBACK is not set +# CONFIG_MBEDTLS_SSL_CONTEXT_SERIALIZATION is not set +CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE=y +# CONFIG_MBEDTLS_SSL_KEYING_MATERIAL_EXPORT is not set +CONFIG_MBEDTLS_PKCS7_C=y +# end of mbedTLS v3.x related + +# +# Certificate Bundle +# +CONFIG_MBEDTLS_CERTIFICATE_BUNDLE=y +CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL=y +# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_CMN is not set +# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE is not set +# CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE is not set +# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEPRECATED_LIST is not set +CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS=200 +# end of Certificate Bundle + +# CONFIG_MBEDTLS_ECP_RESTARTABLE is not set +CONFIG_MBEDTLS_CMAC_C=y +CONFIG_MBEDTLS_HARDWARE_AES=y +CONFIG_MBEDTLS_AES_USE_INTERRUPT=y +CONFIG_MBEDTLS_AES_INTERRUPT_LEVEL=0 +CONFIG_MBEDTLS_GCM_SUPPORT_NON_AES_CIPHER=y +CONFIG_MBEDTLS_HARDWARE_MPI=y +CONFIG_MBEDTLS_LARGE_KEY_SOFTWARE_MPI=y +CONFIG_MBEDTLS_MPI_USE_INTERRUPT=y +CONFIG_MBEDTLS_MPI_INTERRUPT_LEVEL=0 +CONFIG_MBEDTLS_HARDWARE_SHA=y +CONFIG_MBEDTLS_ROM_MD5=y +# CONFIG_MBEDTLS_ATCA_HW_ECDSA_SIGN is not set +# CONFIG_MBEDTLS_ATCA_HW_ECDSA_VERIFY is not set +CONFIG_MBEDTLS_HAVE_TIME=y +# CONFIG_MBEDTLS_PLATFORM_TIME_ALT is not set +# CONFIG_MBEDTLS_HAVE_TIME_DATE is not set +CONFIG_MBEDTLS_ECDSA_DETERMINISTIC=y +CONFIG_MBEDTLS_SHA1_C=y +CONFIG_MBEDTLS_SHA512_C=y +# CONFIG_MBEDTLS_SHA3_C is not set +CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT=y +# CONFIG_MBEDTLS_TLS_SERVER_ONLY is not set +# CONFIG_MBEDTLS_TLS_CLIENT_ONLY is not set +# CONFIG_MBEDTLS_TLS_DISABLED is not set +CONFIG_MBEDTLS_TLS_SERVER=y +CONFIG_MBEDTLS_TLS_CLIENT=y +CONFIG_MBEDTLS_TLS_ENABLED=y + +# +# TLS Key Exchange Methods +# +# CONFIG_MBEDTLS_PSK_MODES is not set +CONFIG_MBEDTLS_KEY_EXCHANGE_RSA=y +CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE=y +CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA=y +CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA=y +CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA=y +CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA=y +# end of TLS Key Exchange Methods + +CONFIG_MBEDTLS_SSL_RENEGOTIATION=y +CONFIG_MBEDTLS_SSL_PROTO_TLS1_2=y +# CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1 is not set +# CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set +CONFIG_MBEDTLS_SSL_ALPN=y +CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS=y +CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS=y + +# +# Symmetric Ciphers +# +CONFIG_MBEDTLS_AES_C=y +# CONFIG_MBEDTLS_CAMELLIA_C is not set +# CONFIG_MBEDTLS_DES_C is not set +# CONFIG_MBEDTLS_BLOWFISH_C is not set +# CONFIG_MBEDTLS_XTEA_C is not set +CONFIG_MBEDTLS_CCM_C=y +CONFIG_MBEDTLS_GCM_C=y +# CONFIG_MBEDTLS_NIST_KW_C is not set +# end of Symmetric Ciphers + +# CONFIG_MBEDTLS_RIPEMD160_C is not set + +# +# Certificates +# +CONFIG_MBEDTLS_PEM_PARSE_C=y +CONFIG_MBEDTLS_PEM_WRITE_C=y +CONFIG_MBEDTLS_X509_CRL_PARSE_C=y +CONFIG_MBEDTLS_X509_CSR_PARSE_C=y +# end of Certificates + +CONFIG_MBEDTLS_ECP_C=y +CONFIG_MBEDTLS_PK_PARSE_EC_EXTENDED=y +CONFIG_MBEDTLS_PK_PARSE_EC_COMPRESSED=y +# CONFIG_MBEDTLS_DHM_C is not set +CONFIG_MBEDTLS_ECDH_C=y +CONFIG_MBEDTLS_ECDSA_C=y +# CONFIG_MBEDTLS_ECJPAKE_C is not set +CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED=y +CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED=y +CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED=y +CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED=y +CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED=y +CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED=y +CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED=y +CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED=y +CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED=y +CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED=y +CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED=y +CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED=y +CONFIG_MBEDTLS_ECP_NIST_OPTIM=y +# CONFIG_MBEDTLS_ECP_FIXED_POINT_OPTIM is not set +# CONFIG_MBEDTLS_POLY1305_C is not set +# CONFIG_MBEDTLS_CHACHA20_C is not set +# CONFIG_MBEDTLS_HKDF_C is not set +# CONFIG_MBEDTLS_THREADING_C is not set +CONFIG_MBEDTLS_ERROR_STRINGS=y +CONFIG_MBEDTLS_FS_IO=y +# CONFIG_MBEDTLS_ALLOW_WEAK_CERTIFICATE_VERIFICATION is not set +# end of mbedTLS + +# +# ESP-MQTT Configurations +# +CONFIG_MQTT_PROTOCOL_311=y +# CONFIG_MQTT_PROTOCOL_5 is not set +CONFIG_MQTT_TRANSPORT_SSL=y +CONFIG_MQTT_TRANSPORT_WEBSOCKET=y +CONFIG_MQTT_TRANSPORT_WEBSOCKET_SECURE=y +# CONFIG_MQTT_MSG_ID_INCREMENTAL is not set +# CONFIG_MQTT_SKIP_PUBLISH_IF_DISCONNECTED is not set +# CONFIG_MQTT_REPORT_DELETED_MESSAGES is not set +# CONFIG_MQTT_USE_CUSTOM_CONFIG is not set +# CONFIG_MQTT_TASK_CORE_SELECTION_ENABLED is not set +# CONFIG_MQTT_CUSTOM_OUTBOX is not set +# end of ESP-MQTT Configurations + +# +# LibC +# +CONFIG_LIBC_NEWLIB=y +# CONFIG_LIBC_PICOLIBC is not set +CONFIG_LIBC_MISC_IN_IRAM=y +CONFIG_LIBC_LOCKS_PLACE_IN_IRAM=y +CONFIG_LIBC_STDOUT_LINE_ENDING_CRLF=y +# CONFIG_LIBC_STDOUT_LINE_ENDING_LF is not set +# CONFIG_LIBC_STDOUT_LINE_ENDING_CR is not set +# CONFIG_LIBC_STDIN_LINE_ENDING_CRLF is not set +# CONFIG_LIBC_STDIN_LINE_ENDING_LF is not set +CONFIG_LIBC_STDIN_LINE_ENDING_CR=y +# CONFIG_LIBC_NEWLIB_NANO_FORMAT is not set +CONFIG_LIBC_TIME_SYSCALL_USE_RTC_HRT=y +# CONFIG_LIBC_TIME_SYSCALL_USE_RTC is not set +# CONFIG_LIBC_TIME_SYSCALL_USE_HRT is not set +# CONFIG_LIBC_TIME_SYSCALL_USE_NONE is not set +CONFIG_LIBC_OPTIMIZED_MISALIGNED_ACCESS=y +CONFIG_LIBC_ASSERT_BUFFER_SIZE=200 +# end of LibC + +# +# NVS +# +# CONFIG_NVS_ENCRYPTION is not set +# CONFIG_NVS_ASSERT_ERROR_CHECK is not set +# CONFIG_NVS_LEGACY_DUP_KEYS_COMPATIBILITY is not set +# end of NVS + +# +# OpenThread +# +# CONFIG_OPENTHREAD_ENABLED is not set + +# +# OpenThread Spinel +# +# CONFIG_OPENTHREAD_SPINEL_ONLY is not set +# end of OpenThread Spinel + +# CONFIG_OPENTHREAD_DEBUG is not set +# end of OpenThread + +# +# Protocomm +# +CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_0=y +CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_1=y +CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_VERSION_2=y +CONFIG_ESP_PROTOCOMM_SUPPORT_SECURITY_PATCH_VERSION=y +# end of Protocomm + +# +# PThreads +# +CONFIG_PTHREAD_TASK_PRIO_DEFAULT=5 +CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072 +CONFIG_PTHREAD_STACK_MIN=768 +CONFIG_PTHREAD_TASK_CORE_DEFAULT=-1 +CONFIG_PTHREAD_TASK_NAME_DEFAULT="pthread" +# end of PThreads + +# +# MMU Config +# +CONFIG_MMU_PAGE_SIZE_64KB=y +CONFIG_MMU_PAGE_MODE="64KB" +CONFIG_MMU_PAGE_SIZE=0x10000 +# end of MMU Config + +# +# Main Flash configuration +# + +# +# SPI Flash behavior when brownout +# +CONFIG_SPI_FLASH_BROWNOUT_RESET_XMC=y +CONFIG_SPI_FLASH_BROWNOUT_RESET=y +# end of SPI Flash behavior when brownout + +# +# Optional and Experimental Features (READ DOCS FIRST) +# + +# +# Features here require specific hardware (READ DOCS FIRST!) +# +# CONFIG_SPI_FLASH_AUTO_SUSPEND is not set +CONFIG_SPI_FLASH_SUSPEND_TSUS_VAL_US=50 +# CONFIG_SPI_FLASH_FORCE_ENABLE_XMC_C_SUSPEND is not set +# CONFIG_SPI_FLASH_FORCE_ENABLE_C6_H2_SUSPEND is not set +CONFIG_SPI_FLASH_PLACE_FUNCTIONS_IN_IRAM=y +# end of Optional and Experimental Features (READ DOCS FIRST) +# end of Main Flash configuration + +# +# SPI Flash driver +# +# CONFIG_SPI_FLASH_VERIFY_WRITE is not set +# CONFIG_SPI_FLASH_ENABLE_COUNTERS is not set +CONFIG_SPI_FLASH_ROM_DRIVER_PATCH=y +# CONFIG_SPI_FLASH_ROM_IMPL is not set +CONFIG_SPI_FLASH_DANGEROUS_WRITE_ABORTS=y +# CONFIG_SPI_FLASH_DANGEROUS_WRITE_FAILS is not set +# CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED is not set +# CONFIG_SPI_FLASH_BYPASS_BLOCK_ERASE is not set +CONFIG_SPI_FLASH_YIELD_DURING_ERASE=y +CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS=20 +CONFIG_SPI_FLASH_ERASE_YIELD_TICKS=1 +CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE=8192 +# CONFIG_SPI_FLASH_SIZE_OVERRIDE is not set +# CONFIG_SPI_FLASH_CHECK_ERASE_TIMEOUT_DISABLED is not set +# CONFIG_SPI_FLASH_OVERRIDE_CHIP_DRIVER_LIST is not set + +# +# Auto-detect flash chips +# +CONFIG_SPI_FLASH_VENDOR_XMC_SUPPORT_ENABLED=y +CONFIG_SPI_FLASH_VENDOR_GD_SUPPORT_ENABLED=y +CONFIG_SPI_FLASH_VENDOR_ISSI_SUPPORT_ENABLED=y +CONFIG_SPI_FLASH_VENDOR_MXIC_SUPPORT_ENABLED=y +CONFIG_SPI_FLASH_VENDOR_WINBOND_SUPPORT_ENABLED=y +CONFIG_SPI_FLASH_VENDOR_BOYA_SUPPORT_ENABLED=y +CONFIG_SPI_FLASH_VENDOR_TH_SUPPORT_ENABLED=y +CONFIG_SPI_FLASH_SUPPORT_ISSI_CHIP=y +CONFIG_SPI_FLASH_SUPPORT_MXIC_CHIP=y +CONFIG_SPI_FLASH_SUPPORT_GD_CHIP=y +CONFIG_SPI_FLASH_SUPPORT_WINBOND_CHIP=y +CONFIG_SPI_FLASH_SUPPORT_BOYA_CHIP=y +CONFIG_SPI_FLASH_SUPPORT_TH_CHIP=y +# end of Auto-detect flash chips + +CONFIG_SPI_FLASH_ENABLE_ENCRYPTED_READ_WRITE=y +# end of SPI Flash driver + +# +# SPIFFS Configuration +# +CONFIG_SPIFFS_MAX_PARTITIONS=3 + +# +# SPIFFS Cache Configuration +# +CONFIG_SPIFFS_CACHE=y +CONFIG_SPIFFS_CACHE_WR=y +# CONFIG_SPIFFS_CACHE_STATS is not set +# end of SPIFFS Cache Configuration + +CONFIG_SPIFFS_PAGE_CHECK=y +CONFIG_SPIFFS_GC_MAX_RUNS=10 +# CONFIG_SPIFFS_GC_STATS is not set +CONFIG_SPIFFS_PAGE_SIZE=256 +CONFIG_SPIFFS_OBJ_NAME_LEN=32 +# CONFIG_SPIFFS_FOLLOW_SYMLINKS is not set +CONFIG_SPIFFS_USE_MAGIC=y +CONFIG_SPIFFS_USE_MAGIC_LENGTH=y +CONFIG_SPIFFS_META_LENGTH=4 +CONFIG_SPIFFS_USE_MTIME=y + +# +# Debug Configuration +# +# CONFIG_SPIFFS_DBG is not set +# CONFIG_SPIFFS_API_DBG is not set +# CONFIG_SPIFFS_GC_DBG is not set +# CONFIG_SPIFFS_CACHE_DBG is not set +# CONFIG_SPIFFS_CHECK_DBG is not set +# CONFIG_SPIFFS_TEST_VISUALISATION is not set +# end of Debug Configuration +# end of SPIFFS Configuration + +# +# TCP Transport +# + +# +# Websocket +# +CONFIG_WS_TRANSPORT=y +CONFIG_WS_BUFFER_SIZE=1024 +# CONFIG_WS_DYNAMIC_BUFFER is not set +# end of Websocket +# end of TCP Transport + +# +# Unity unit testing library +# +CONFIG_UNITY_ENABLE_FLOAT=y +CONFIG_UNITY_ENABLE_DOUBLE=y +# CONFIG_UNITY_ENABLE_64BIT is not set +# CONFIG_UNITY_ENABLE_COLOR is not set +CONFIG_UNITY_ENABLE_IDF_TEST_RUNNER=y +# CONFIG_UNITY_ENABLE_FIXTURE is not set +# CONFIG_UNITY_ENABLE_BACKTRACE_ON_FAIL is not set +# CONFIG_UNITY_TEST_ORDER_BY_FILE_PATH_AND_LINE is not set +# end of Unity unit testing library + +# +# Virtual file system +# +CONFIG_VFS_SUPPORT_IO=y +CONFIG_VFS_SUPPORT_DIR=y +CONFIG_VFS_SUPPORT_SELECT=y +CONFIG_VFS_SUPPRESS_SELECT_DEBUG_OUTPUT=y +# CONFIG_VFS_SELECT_IN_RAM is not set +CONFIG_VFS_SUPPORT_TERMIOS=y +CONFIG_VFS_MAX_COUNT=8 + +# +# Host File System I/O (Semihosting) +# +CONFIG_VFS_SEMIHOSTFS_MAX_MOUNT_POINTS=1 +# end of Host File System I/O (Semihosting) + +CONFIG_VFS_INITIALIZE_DEV_NULL=y +# end of Virtual file system + +# +# Wear Levelling +# +# CONFIG_WL_SECTOR_SIZE_512 is not set +CONFIG_WL_SECTOR_SIZE_4096=y +CONFIG_WL_SECTOR_SIZE=4096 +# end of Wear Levelling + +# +# Wi-Fi Provisioning Manager +# +CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES=16 +CONFIG_WIFI_PROV_AUTOSTOP_TIMEOUT=30 +CONFIG_WIFI_PROV_STA_ALL_CHANNEL_SCAN=y +# CONFIG_WIFI_PROV_STA_FAST_SCAN is not set +# end of Wi-Fi Provisioning Manager +# end of Component config + +# CONFIG_IDF_EXPERIMENTAL_FEATURES is not set + +# Deprecated options for backward compatibility +# CONFIG_APP_BUILD_TYPE_ELF_RAM is not set +# CONFIG_NO_BLOBS is not set +# CONFIG_APP_ROLLBACK_ENABLE is not set +# CONFIG_LOG_BOOTLOADER_LEVEL_NONE is not set +# CONFIG_LOG_BOOTLOADER_LEVEL_ERROR is not set +# CONFIG_LOG_BOOTLOADER_LEVEL_WARN is not set +CONFIG_LOG_BOOTLOADER_LEVEL_INFO=y +# CONFIG_LOG_BOOTLOADER_LEVEL_DEBUG is not set +# CONFIG_LOG_BOOTLOADER_LEVEL_VERBOSE is not set +CONFIG_LOG_BOOTLOADER_LEVEL=3 +# CONFIG_FLASH_ENCRYPTION_ENABLED is not set +# CONFIG_FLASHMODE_QIO is not set +# CONFIG_FLASHMODE_QOUT is not set +CONFIG_FLASHMODE_DIO=y +# CONFIG_FLASHMODE_DOUT is not set +CONFIG_MONITOR_BAUD=115200 +CONFIG_OPTIMIZATION_LEVEL_DEBUG=y +CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG=y +CONFIG_COMPILER_OPTIMIZATION_DEFAULT=y +# CONFIG_OPTIMIZATION_LEVEL_RELEASE is not set +# CONFIG_COMPILER_OPTIMIZATION_LEVEL_RELEASE is not set +CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED=y +# CONFIG_OPTIMIZATION_ASSERTIONS_SILENT is not set +# CONFIG_OPTIMIZATION_ASSERTIONS_DISABLED is not set +CONFIG_OPTIMIZATION_ASSERTION_LEVEL=2 +# CONFIG_CXX_EXCEPTIONS is not set +CONFIG_STACK_CHECK_NONE=y +# CONFIG_STACK_CHECK_NORM is not set +# CONFIG_STACK_CHECK_STRONG is not set +# CONFIG_STACK_CHECK_ALL is not set +# CONFIG_WARN_WRITE_STRINGS is not set +# CONFIG_ESP32_APPTRACE_DEST_TRAX is not set +CONFIG_ESP32_APPTRACE_DEST_NONE=y +CONFIG_ESP32_APPTRACE_LOCK_ENABLE=y +# CONFIG_EXTERNAL_COEX_ENABLE is not set +# CONFIG_ESP_WIFI_EXTERNAL_COEXIST_ENABLE is not set +# CONFIG_GPTIMER_ISR_IRAM_SAFE is not set +# CONFIG_EVENT_LOOP_PROFILING is not set +CONFIG_POST_EVENTS_FROM_ISR=y +CONFIG_POST_EVENTS_FROM_IRAM_ISR=y +CONFIG_GDBSTUB_SUPPORT_TASKS=y +CONFIG_GDBSTUB_MAX_TASKS=32 +# CONFIG_OTA_ALLOW_HTTP is not set +# CONFIG_ESP_SYSTEM_PD_FLASH is not set +CONFIG_ESP32C3_LIGHTSLEEP_GPIO_RESET_WORKAROUND=y +CONFIG_ESP32C3_RTC_CLK_SRC_INT_RC=y +# CONFIG_ESP32C3_RTC_CLK_SRC_EXT_CRYS is not set +# CONFIG_ESP32C3_RTC_CLK_SRC_EXT_OSC is not set +# CONFIG_ESP32C3_RTC_CLK_SRC_INT_8MD256 is not set +CONFIG_ESP32C3_RTC_CLK_CAL_CYCLES=1024 +CONFIG_PERIPH_CTRL_FUNC_IN_IRAM=y +CONFIG_BROWNOUT_DET=y +CONFIG_ESP32C3_BROWNOUT_DET=y +CONFIG_BROWNOUT_DET_LVL_SEL_7=y +CONFIG_ESP32C3_BROWNOUT_DET_LVL_SEL_7=y +# CONFIG_BROWNOUT_DET_LVL_SEL_6 is not set +# CONFIG_ESP32C3_BROWNOUT_DET_LVL_SEL_6 is not set +# CONFIG_BROWNOUT_DET_LVL_SEL_5 is not set +# CONFIG_ESP32C3_BROWNOUT_DET_LVL_SEL_5 is not set +# CONFIG_BROWNOUT_DET_LVL_SEL_4 is not set +# CONFIG_ESP32C3_BROWNOUT_DET_LVL_SEL_4 is not set +# CONFIG_BROWNOUT_DET_LVL_SEL_3 is not set +# CONFIG_ESP32C3_BROWNOUT_DET_LVL_SEL_3 is not set +# CONFIG_BROWNOUT_DET_LVL_SEL_2 is not set +# CONFIG_ESP32C3_BROWNOUT_DET_LVL_SEL_2 is not set +CONFIG_BROWNOUT_DET_LVL=7 +CONFIG_ESP32C3_BROWNOUT_DET_LVL=7 +CONFIG_ESP_SYSTEM_BROWNOUT_INTR=y +CONFIG_ESP32_PHY_CALIBRATION_AND_DATA_STORAGE=y +# CONFIG_ESP32_PHY_INIT_DATA_IN_PARTITION is not set +CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER=20 +CONFIG_ESP32_PHY_MAX_TX_POWER=20 +# CONFIG_REDUCE_PHY_TX_POWER is not set +# CONFIG_ESP32_REDUCE_PHY_TX_POWER is not set +CONFIG_ESP_SYSTEM_PM_POWER_DOWN_CPU=y +# CONFIG_ESP32C3_DEFAULT_CPU_FREQ_80 is not set +CONFIG_ESP32C3_DEFAULT_CPU_FREQ_160=y +CONFIG_ESP32C3_DEFAULT_CPU_FREQ_MHZ=160 +CONFIG_ESP32C3_MEMPROT_FEATURE=y +CONFIG_ESP32C3_MEMPROT_FEATURE_LOCK=y +CONFIG_SYSTEM_EVENT_QUEUE_SIZE=32 +CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE=2304 +CONFIG_MAIN_TASK_STACK_SIZE=3584 +# CONFIG_CONSOLE_UART_DEFAULT is not set +# CONFIG_CONSOLE_UART_CUSTOM is not set +# CONFIG_CONSOLE_UART_NONE is not set +# CONFIG_ESP_CONSOLE_UART_NONE is not set +CONFIG_CONSOLE_UART_NUM=-1 +CONFIG_INT_WDT=y +CONFIG_INT_WDT_TIMEOUT_MS=300 +CONFIG_TASK_WDT=y +CONFIG_ESP_TASK_WDT=y +# CONFIG_TASK_WDT_PANIC is not set +CONFIG_TASK_WDT_TIMEOUT_S=5 +CONFIG_TASK_WDT_CHECK_IDLE_TASK_CPU0=y +# CONFIG_ESP32_DEBUG_STUBS_ENABLE is not set +CONFIG_ESP32C3_DEBUG_OCDAWARE=y +CONFIG_IPC_TASK_STACK_SIZE=1024 +CONFIG_TIMER_TASK_STACK_SIZE=3584 +CONFIG_ESP32_WIFI_ENABLED=y +CONFIG_ESP32_WIFI_STATIC_RX_BUFFER_NUM=10 +CONFIG_ESP32_WIFI_DYNAMIC_RX_BUFFER_NUM=32 +# CONFIG_ESP32_WIFI_STATIC_TX_BUFFER is not set +CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER=y +CONFIG_ESP32_WIFI_TX_BUFFER_TYPE=1 +CONFIG_ESP32_WIFI_DYNAMIC_TX_BUFFER_NUM=32 +# CONFIG_ESP32_WIFI_CSI_ENABLED is not set +CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED=y +CONFIG_ESP32_WIFI_TX_BA_WIN=6 +CONFIG_ESP32_WIFI_AMPDU_RX_ENABLED=y +CONFIG_ESP32_WIFI_RX_BA_WIN=6 +CONFIG_ESP32_WIFI_NVS_ENABLED=y +CONFIG_ESP32_WIFI_SOFTAP_BEACON_MAX_LEN=752 +CONFIG_ESP32_WIFI_MGMT_SBUF_NUM=32 +CONFIG_ESP32_WIFI_IRAM_OPT=y +CONFIG_ESP32_WIFI_RX_IRAM_OPT=y +CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE=y +CONFIG_ESP32_WIFI_ENABLE_WPA3_OWE_STA=y +CONFIG_WPA_MBEDTLS_CRYPTO=y +CONFIG_WPA_MBEDTLS_TLS_CLIENT=y +# CONFIG_WPA_WAPI_PSK is not set +# CONFIG_WPA_SUITE_B_192 is not set +# CONFIG_WPA_11KV_SUPPORT is not set +# CONFIG_WPA_MBO_SUPPORT is not set +# CONFIG_WPA_DPP_SUPPORT is not set +# CONFIG_WPA_11R_SUPPORT is not set +# CONFIG_WPA_WPS_SOFTAP_REGISTRAR is not set +# CONFIG_WPA_WPS_STRICT is not set +# CONFIG_WPA_DEBUG_PRINT is not set +# CONFIG_ESP32_ENABLE_COREDUMP_TO_FLASH is not set +# CONFIG_ESP32_ENABLE_COREDUMP_TO_UART is not set +CONFIG_ESP32_ENABLE_COREDUMP_TO_NONE=y +CONFIG_TIMER_TASK_PRIORITY=1 +CONFIG_TIMER_TASK_STACK_DEPTH=2048 +CONFIG_TIMER_QUEUE_LENGTH=10 +# CONFIG_ENABLE_STATIC_TASK_CLEAN_UP_HOOK is not set +# CONFIG_HAL_ASSERTION_SILIENT is not set +# CONFIG_L2_TO_L3_COPY is not set +CONFIG_ESP_GRATUITOUS_ARP=y +CONFIG_GARP_TMR_INTERVAL=60 +CONFIG_TCPIP_RECVMBOX_SIZE=32 +CONFIG_TCP_MAXRTX=12 +CONFIG_TCP_SYNMAXRTX=12 +CONFIG_TCP_MSS=1440 +CONFIG_TCP_MSL=60000 +CONFIG_TCP_SND_BUF_DEFAULT=5760 +CONFIG_TCP_WND_DEFAULT=5760 +CONFIG_TCP_RECVMBOX_SIZE=6 +CONFIG_TCP_QUEUE_OOSEQ=y +CONFIG_TCP_OVERSIZE_MSS=y +# CONFIG_TCP_OVERSIZE_QUARTER_MSS is not set +# CONFIG_TCP_OVERSIZE_DISABLE is not set +CONFIG_UDP_RECVMBOX_SIZE=6 +CONFIG_TCPIP_TASK_STACK_SIZE=3072 +CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY=y +# CONFIG_TCPIP_TASK_AFFINITY_CPU0 is not set +CONFIG_TCPIP_TASK_AFFINITY=0x7FFFFFFF +# CONFIG_PPP_SUPPORT is not set +CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF=y +# CONFIG_NEWLIB_STDOUT_LINE_ENDING_LF is not set +# CONFIG_NEWLIB_STDOUT_LINE_ENDING_CR is not set +# CONFIG_NEWLIB_STDIN_LINE_ENDING_CRLF is not set +# CONFIG_NEWLIB_STDIN_LINE_ENDING_LF is not set +CONFIG_NEWLIB_STDIN_LINE_ENDING_CR=y +# CONFIG_NEWLIB_NANO_FORMAT is not set +CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC_HRT=y +CONFIG_ESP32C3_TIME_SYSCALL_USE_RTC_SYSTIMER=y +# CONFIG_NEWLIB_TIME_SYSCALL_USE_RTC is not set +# CONFIG_ESP32C3_TIME_SYSCALL_USE_RTC is not set +# CONFIG_NEWLIB_TIME_SYSCALL_USE_HRT is not set +# CONFIG_ESP32C3_TIME_SYSCALL_USE_SYSTIMER is not set +# CONFIG_NEWLIB_TIME_SYSCALL_USE_NONE is not set +# CONFIG_ESP32C3_TIME_SYSCALL_USE_NONE is not set +CONFIG_ESP32_PTHREAD_TASK_PRIO_DEFAULT=5 +CONFIG_ESP32_PTHREAD_TASK_STACK_SIZE_DEFAULT=3072 +CONFIG_ESP32_PTHREAD_STACK_MIN=768 +CONFIG_ESP32_PTHREAD_TASK_CORE_DEFAULT=-1 +CONFIG_ESP32_PTHREAD_TASK_NAME_DEFAULT="pthread" +CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS=y +# CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_FAILS is not set +# CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ALLOWED is not set +CONFIG_SUPPRESS_SELECT_DEBUG_OUTPUT=y +CONFIG_SUPPORT_TERMIOS=y +CONFIG_SEMIHOSTFS_MAX_MOUNT_POINTS=1 +# End of deprecated options diff --git a/scripts/led-test/sdkconfig.defaults b/scripts/led-test/sdkconfig.defaults new file mode 100644 index 0000000..5e9f8e2 --- /dev/null +++ b/scripts/led-test/sdkconfig.defaults @@ -0,0 +1 @@ +CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y diff --git a/scripts/setup-port80.sh b/scripts/setup-port80.sh deleted file mode 100755 index cfb5a75..0000000 --- a/scripts/setup-port80.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env bash -# Allow the app to bind to port 80 without root. -# Run once: sudo scripts/setup-port80.sh (from repo root) -# Or: scripts/setup-port80.sh (will prompt for sudo only for setcap) - -set -e -cd "$(dirname "$0")/.." -REPO_ROOT="$(pwd)" -# If run under sudo, use the invoking user's pipenv so the venv is found -if [ -n "$SUDO_USER" ]; then - VENV="$(sudo -u "$SUDO_USER" bash -c "cd '$REPO_ROOT' && pipenv --venv" 2>/dev/null)" || true -else - VENV="$(pipenv --venv 2>/dev/null)" || true -fi -if [ -z "$VENV" ]; then - echo "Run 'pipenv install' first, then run this script again." - exit 1 -fi -PYTHON="${VENV}/bin/python3" -if [ ! -f "$PYTHON" ]; then - PYTHON="${VENV}/bin/python" -fi -if [ ! -f "$PYTHON" ]; then - echo "Python not found in venv: $VENV" - exit 1 -fi -# Use the real binary (setcap can fail on symlinks or some filesystems) -REAL_PYTHON="$(readlink -f "$PYTHON" 2>/dev/null)" || REAL_PYTHON="$PYTHON" -if sudo setcap 'cap_net_bind_service=+ep' "$REAL_PYTHON" 2>/dev/null; then - echo "OK: port 80 enabled for $REAL_PYTHON" - echo "Start the app with: pipenv run run" -else - echo "setcap failed on $REAL_PYTHON" - exit 1 -fi diff --git a/scripts/setup-vpn-autoconnect.sh b/scripts/setup-vpn-autoconnect.sh new file mode 100755 index 0000000..aa19a0f --- /dev/null +++ b/scripts/setup-vpn-autoconnect.sh @@ -0,0 +1,82 @@ +#!/usr/bin/env bash +# Enable VPN at boot on Raspberry Pi OS (NetworkManager or WireGuard). +# +# NetworkManager (import VPN in nm-connection-editor or nmcli first): +# sudo ./scripts/setup-vpn-autoconnect.sh nm "My VPN connection name" +# +# WireGuard (/etc/wireguard/wg0.conf must exist; interface name without .conf): +# sudo ./scripts/setup-vpn-autoconnect.sh wg wg0 +# +# OpenVPN single file (needs network-manager-openvpn): +# sudo ./scripts/setup-vpn-autoconnect.sh import-openvpn /home/pi/OpenVPN-Config.ovpn +# sudo ./scripts/setup-vpn-autoconnect.sh nm OpenVPN-Config +# +set -euo pipefail + +usage() { + sed -n '2,17p' "$0" | sed 's/^# \{0,1\}//' + exit 1 +} + +if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then + usage +fi + +case "${1:-}" in + import-openvpn|import-ovpn) + FILE="${2:-}" + if [ -z "$FILE" ] || [ ! -f "$FILE" ]; then + echo "Usage: $0 import-openvpn /path/to/profile.ovpn" >&2 + exit 1 + fi + if ! command -v nmcli >/dev/null 2>&1; then + echo "nmcli not found." >&2 + exit 1 + fi + ABS="$(readlink -f "$FILE")" + nmcli connection import type openvpn file "$ABS" + NM_NAME="$(basename "$FILE" .ovpn)" + nmcli connection modify "$NM_NAME" connection.autoconnect yes + nmcli connection modify "$NM_NAME" connection.autoconnect-priority 20 + echo "Imported as NM connection: $NM_NAME (autoconnect on)" + echo "Connect now: sudo nmcli connection up \"$NM_NAME\"" + ;; + nm|network-manager) + NAME="${2:-}" + if [ -z "$NAME" ]; then + echo "Usage: $0 nm \"Connection name\"" >&2 + exit 1 + fi + if ! command -v nmcli >/dev/null 2>&1; then + echo "nmcli not found. Install NetworkManager." >&2 + exit 1 + fi + if ! nmcli -t -f NAME connection show "$NAME" >/dev/null 2>&1; then + echo "No NetworkManager connection named: $NAME" >&2 + echo "List: nmcli -f NAME,TYPE connection" >&2 + exit 1 + fi + nmcli connection modify "$NAME" connection.autoconnect yes + nmcli connection modify "$NAME" connection.autoconnect-priority 10 + echo "Enabled autoconnect for NM profile: $NAME" + echo "Reconnect now: sudo nmcli connection up \"$NAME\"" + ;; + wg|wireguard) + IFACE="${2:-}" + if [ -z "$IFACE" ]; then + echo "Usage: $0 wg wg0 (config must be /etc/wireguard/\${IFACE}.conf)" >&2 + exit 1 + fi + CFG="/etc/wireguard/${IFACE}.conf" + if [ ! -f "$CFG" ]; then + echo "Missing $CFG — create it first (e.g. copy from your VPN provider)." >&2 + exit 1 + fi + systemctl enable "wg-quick@${IFACE}.service" + echo "Enabled: wg-quick@${IFACE}.service (starts at boot)" + echo "Start now: sudo systemctl start wg-quick@${IFACE}" + ;; + *) + usage + ;; +esac diff --git a/scripts/start.sh b/scripts/start.sh deleted file mode 100755 index 370fd51..0000000 --- a/scripts/start.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env bash -# Start the LED controller web server (port 80 by default). -# 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}" -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 diff --git a/scripts/test-port80.sh b/scripts/test-port80.sh deleted file mode 100755 index 4e559bb..0000000 --- a/scripts/test-port80.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env bash -# Test the app on port 80. Run after: sudo scripts/setup-port80.sh -# Usage: ./scripts/test-port80.sh - -set -e -cd "$(dirname "$0")/.." -APP_URL="${APP_URL:-http://127.0.0.1:80}" - -echo "Starting app on port 80 in background..." -pipenv run run & -PID=$! -trap "kill $PID 2>/dev/null; exit" EXIT - -echo "Waiting for server to start..." -for i in 1 2 3 4 5 6 7 8 9 10; do - if curl -s -o /dev/null -w "%{http_code}" "$APP_URL/" 2>/dev/null | grep -q 200; then - echo "Server is up." - break - fi - sleep 1 -done - -echo "Requesting $APP_URL/ ..." -CODE=$(curl -s -o /dev/null -w "%{http_code}" "$APP_URL/") -if [ "$CODE" = "200" ]; then - echo "OK: GET / returned HTTP $CODE" - curl -s "$APP_URL/" | head -5 - echo "..." - exit 0 -else - echo "FAIL: GET / returned HTTP $CODE (expected 200)" - exit 1 -fi diff --git a/src/boot.py b/src/boot.py deleted file mode 100644 index 0cc6e07..0000000 --- a/src/boot.py +++ /dev/null @@ -1,6 +0,0 @@ -# Boot script (ESP only; no-op on Pi) -import settings # noqa: F401 -from settings import Settings - -s = Settings() -# AP setup was here when running on ESP; Pi uses system networking. diff --git a/src/controllers/__init__.py b/src/controllers/__init__.py deleted file mode 100644 index 5fe28c2..0000000 --- a/src/controllers/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# Controllers package diff --git a/src/controllers/device.py b/src/controllers/device.py deleted file mode 100644 index cafc75a..0000000 --- a/src/controllers/device.py +++ /dev/null @@ -1,393 +0,0 @@ -from microdot import Microdot -from models.device import ( - Device, - derive_device_mac, - validate_device_transport, - validate_device_type, -) -from models.transport import get_current_sender -from models.wifi_ws_clients import ( - normalize_tcp_peer_ip, - send_json_line_to_ip, - tcp_client_connected, -) -from util.driver_patterns import driver_patterns_dir -from util.espnow_message import build_message -import asyncio -import json -import os -import socket -from urllib.parse import quote - -# Ephemeral driver preset name (never written to Pi preset store; ``save`` not set on wire). -_IDENTIFY_PRESET_KEY = "__identify" - -# Short-key payload: 10 Hz full cycle = 50 ms on + 50 ms off (driver ``blink`` toggles each ``d`` ms). -_IDENTIFY_DRIVER_PRESET = { - "p": "blink", - "c": ["#ff0000"], - "d": 50, - "b": 128, - "a": True, - "n1": 0, - "n2": 0, - "n3": 0, - "n4": 0, - "n5": 0, - "n6": 0, -} - - -def _compact_v1_json(*, presets=None, select=None, save=False): - """Single-line v1 object; compact so serial/ESP-NOW stays small.""" - body = {"v": "1"} - if presets is not None: - body["presets"] = presets - if save: - body["save"] = True - if select is not None: - body["select"] = select - return json.dumps(body, separators=(",", ":")) - -# Seconds after identify blink before selecting built-in ``off`` (tests may monkeypatch). -IDENTIFY_OFF_DELAY_S = 2.0 - -controller = Microdot() -devices = Device() - - -def _device_live_connected(dev_dict): - """ - Wi-Fi: whether the controller has an outbound WebSocket to this device's IP. - ESP-NOW: None (no Wi-Fi session on the Pi for that transport). - """ - tr = (dev_dict.get("transport") or "espnow").strip().lower() - if tr != "wifi": - return None - ip = normalize_tcp_peer_ip(dev_dict.get("address") or "") - if not ip: - return False - return tcp_client_connected(ip) - - -def _device_json_with_live_status(dev_dict): - row = dict(dev_dict) - row["connected"] = _device_live_connected(dev_dict) - return row - - -def _safe_pattern_filename(name): - if not isinstance(name, str): - return False - if not name.endswith(".py"): - return False - if "/" in name or "\\" in name or ".." in name: - return False - return True - - -def _http_post_pattern_source(ip, filename, code_text, reload_patterns=True, timeout_s=10.0): - """POST source to driver /patterns/upload?name=...&reload=...; return True on 2xx.""" - if not isinstance(ip, str) or not ip.strip(): - return False - if not isinstance(filename, str) or not filename: - return False - if not isinstance(code_text, str): - return False - - name_q = quote(filename, safe="") - reload_q = "1" if reload_patterns else "0" - path = "/patterns/upload?name=%s&reload=%s" % (name_q, reload_q) - body = code_text.encode("utf-8") - req = ( - "POST %s HTTP/1.1\r\n" - "Host: %s\r\n" - "Content-Type: text/plain; charset=utf-8\r\n" - "Content-Length: %d\r\n" - "Connection: close\r\n" - "\r\n" % (path, ip, len(body)) - ).encode("utf-8") + body - - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - try: - sock.settimeout(timeout_s) - sock.connect((ip.strip(), 80)) - sock.sendall(req) - data = b"" - while True: - chunk = sock.recv(1024) - if not chunk: - break - data += chunk - except OSError: - return False - finally: - try: - sock.close() - except Exception: - pass - - first_line = data.split(b"\r\n", 1)[0] if data else b"" - return b" 2" in first_line - - -async def _identify_send_off_after_delay(sender, transport, wifi_ip, dev_id, name): - try: - await asyncio.sleep(IDENTIFY_OFF_DELAY_S) - off_msg = build_message(select={name: ["off"]}) - if transport == "wifi": - await send_json_line_to_ip(wifi_ip, off_msg) - else: - await sender.send(off_msg, addr=dev_id) - except Exception: - pass - - -@controller.get("") -async def list_devices(request): - """List all devices (includes ``connected`` for live Wi-Fi WebSocket presence).""" - devices_data = {} - for dev_id in devices.list(): - d = devices.read(dev_id) - if d: - devices_data[dev_id] = _device_json_with_live_status(d) - return json.dumps(devices_data), 200, {"Content-Type": "application/json"} - - -@controller.get("/") -async def get_device(request, id): - """Get a device by ID (includes ``connected`` for live Wi-Fi WebSocket presence).""" - dev = devices.read(id) - if dev: - return json.dumps(_device_json_with_live_status(dev)), 200, { - "Content-Type": "application/json", - } - return json.dumps({"error": "Device not found"}), 404, { - "Content-Type": "application/json", - } - - -@controller.post("") -async def create_device(request): - """Create a new device.""" - try: - data = request.json or {} - name = data.get("name", "").strip() - if not name: - return json.dumps({"error": "name is required"}), 400, { - "Content-Type": "application/json", - } - try: - device_type = validate_device_type(data.get("type", "led")) - transport = validate_device_transport(data.get("transport", "espnow")) - except ValueError as e: - return json.dumps({"error": str(e)}), 400, { - "Content-Type": "application/json", - } - address = data.get("address") - mac = data.get("mac") - if derive_device_mac(mac=mac, address=address, transport=transport) is None: - return json.dumps( - { - "error": "mac is required (12 hex digits); for Wi-Fi include mac plus IP in address" - } - ), 400, {"Content-Type": "application/json"} - default_pattern = data.get("default_pattern") - zl = data.get("zones") - if isinstance(zl, list): - zl = [str(t) for t in zl] - else: - zl = [] - dev_id = devices.create( - name=name, - address=address, - mac=mac, - default_pattern=default_pattern, - zones=zl, - device_type=device_type, - transport=transport, - ) - dev = devices.read(dev_id) - return json.dumps({dev_id: dev}), 201, {"Content-Type": "application/json"} - except ValueError as e: - msg = str(e) - code = 409 if "already exists" in msg.lower() else 400 - return json.dumps({"error": msg}), code, {"Content-Type": "application/json"} - except Exception as e: - return json.dumps({"error": str(e)}), 400, {"Content-Type": "application/json"} - - -@controller.put("/") -async def update_device(request, id): - """Update a device.""" - try: - raw = request.json or {} - data = dict(raw) - data.pop("id", None) - data.pop("addresses", None) - data.pop("connected", None) - if "name" in data: - n = (data.get("name") or "").strip() - if not n: - return json.dumps({"error": "name cannot be empty"}), 400, { - "Content-Type": "application/json", - } - data["name"] = n - if "type" in data: - data["type"] = validate_device_type(data.get("type")) - if "transport" in data: - data["transport"] = validate_device_transport(data.get("transport")) - if "zones" in data and isinstance(data["zones"], list): - data["zones"] = [str(t) for t in data["zones"]] - if devices.update(id, data): - return json.dumps(devices.read(id)), 200, {"Content-Type": "application/json"} - return json.dumps({"error": "Device not found"}), 404, { - "Content-Type": "application/json", - } - except ValueError as e: - return json.dumps({"error": str(e)}), 400, {"Content-Type": "application/json"} - except Exception as e: - return json.dumps({"error": str(e)}), 400, {"Content-Type": "application/json"} - - -@controller.delete("/") -async def delete_device(request, id): - """Delete a device.""" - if devices.delete(id): - return ( - json.dumps({"message": "Device deleted successfully"}), - 200, - {"Content-Type": "application/json"}, - ) - return json.dumps({"error": "Device not found"}), 404, { - "Content-Type": "application/json", - } - - -@controller.post("//identify") -async def identify_device(request, id): - """ - One v1 JSON object: ``presets.__identify`` (``d``=50 ms → 10 Hz blink) plus ``select`` for - this device name — same combined shape as profile sends the driver already accepts over TCP - / ESP-NOW. No ``save``. After ``IDENTIFY_OFF_DELAY_S``, a background task selects ``off``. - """ - dev = devices.read(id) - if not dev: - return json.dumps({"error": "Device not found"}), 404, { - "Content-Type": "application/json", - } - sender = get_current_sender() - if not sender: - return json.dumps({"error": "Transport not configured"}), 503, { - "Content-Type": "application/json", - } - name = str(dev.get("name") or "").strip() - if not name: - return json.dumps({"error": "Device must have a name to identify"}), 400, { - "Content-Type": "application/json", - } - - transport = dev.get("transport") or "espnow" - wifi_ip = None - if transport == "wifi": - wifi_ip = dev.get("address") - if not wifi_ip: - return json.dumps({"error": "Device has no IP address"}), 400, { - "Content-Type": "application/json", - } - - try: - msg = _compact_v1_json( - presets={_IDENTIFY_PRESET_KEY: dict(_IDENTIFY_DRIVER_PRESET)}, - select={name: [_IDENTIFY_PRESET_KEY]}, - ) - if transport == "wifi": - ok = await send_json_line_to_ip(wifi_ip, msg) - if not ok: - return json.dumps({"error": "Wi-Fi driver not connected"}), 503, { - "Content-Type": "application/json", - } - else: - await sender.send(msg, addr=id) - - asyncio.create_task( - _identify_send_off_after_delay(sender, transport, wifi_ip, id, name) - ) - except Exception as e: - return json.dumps({"error": str(e)}), 503, {"Content-Type": "application/json"} - return json.dumps({"message": "Identify sent"}), 200, { - "Content-Type": "application/json", - } - - -@controller.post("//patterns/push") -async def push_patterns_ota(request, id): - """ - Push all local pattern files directly to a Wi-Fi LED driver over HTTP upload. - """ - dev = devices.read(id) - if not dev: - return json.dumps({"error": "Device not found"}), 404, { - "Content-Type": "application/json", - } - if (dev.get("transport") or "").lower() != "wifi": - return json.dumps({"error": "Pattern OTA push is only supported for Wi-Fi devices"}), 400, { - "Content-Type": "application/json", - } - wifi_ip = str(dev.get("address") or "").strip() - if not wifi_ip: - return json.dumps({"error": "Device has no IP address"}), 400, { - "Content-Type": "application/json", - } - - base_dir = driver_patterns_dir() - try: - names = sorted(os.listdir(base_dir)) - except OSError as e: - return json.dumps({"error": str(e)}), 500, { - "Content-Type": "application/json", - } - - files = [n for n in names if _safe_pattern_filename(n) and n != "__init__.py"] - if not files: - return json.dumps({"error": "No pattern files found"}), 404, { - "Content-Type": "application/json", - } - - sent = [] - failed = [] - total = len(files) - for idx, filename in enumerate(files): - path = os.path.join(base_dir, filename) - try: - with open(path, "r") as f: - code = f.read() - except OSError: - failed.append(filename) - continue - reload_patterns = idx == (total - 1) - ok = _http_post_pattern_source( - wifi_ip, - filename, - code, - reload_patterns=reload_patterns, - timeout_s=10.0, - ) - if ok: - sent.append(filename) - else: - failed.append(filename) - - if not sent: - return json.dumps({"error": "Wi-Fi driver did not accept pattern uploads", "failed": failed}), 503, { - "Content-Type": "application/json", - } - - return json.dumps({ - "message": "Pattern files uploaded", - "sent_count": len(sent), - "sent": sent, - "failed": failed, - }), 200, { - "Content-Type": "application/json", - } diff --git a/src/controllers/group.py b/src/controllers/group.py deleted file mode 100644 index d033492..0000000 --- a/src/controllers/group.py +++ /dev/null @@ -1,50 +0,0 @@ -from microdot import Microdot -from models.group import Group -import json - -controller = Microdot() -groups = Group() - -@controller.get('') -async def list_groups(request): - """List all groups.""" - return json.dumps(groups), 200, {'Content-Type': 'application/json'} - -@controller.get('/') -async def get_group(request, id): - """Get a specific group by ID.""" - group = groups.read(id) - if group: - return json.dumps(group), 200, {'Content-Type': 'application/json'} - return json.dumps({"error": "Group not found"}), 404 - -@controller.post('') -async def create_group(request): - """Create a new group.""" - try: - data = request.json or {} - name = data.get("name", "") - group_id = groups.create(name) - if data: - groups.update(group_id, data) - return json.dumps(groups.read(group_id)), 201, {'Content-Type': 'application/json'} - except Exception as e: - return json.dumps({"error": str(e)}), 400 - -@controller.put('/') -async def update_group(request, id): - """Update an existing group.""" - try: - data = request.json - if groups.update(id, data): - return json.dumps(groups.read(id)), 200, {'Content-Type': 'application/json'} - return json.dumps({"error": "Group not found"}), 404 - except Exception as e: - return json.dumps({"error": str(e)}), 400 - -@controller.delete('/') -async def delete_group(request, id): - """Delete a group.""" - if groups.delete(id): - return json.dumps({"message": "Group deleted successfully"}), 200 - return json.dumps({"error": "Group not found"}), 404 diff --git a/src/controllers/led_tool.py b/src/controllers/led_tool.py deleted file mode 100644 index d39cdfe..0000000 --- a/src/controllers/led_tool.py +++ /dev/null @@ -1,189 +0,0 @@ -import json -import os -import subprocess -import sys - -from microdot import Microdot -from serial.tools import list_ports - -controller = Microdot() - - -def _repo_root() -> str: - return os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) - - -def _led_cli_path() -> str: - return os.path.join(_repo_root(), "led-tool", "cli.py") - - -def _build_led_cli_command(port: str, payload: dict): - cmd = [sys.executable, _led_cli_path(), "--port", port] - - flag_map = ( - ("name", "--name"), - ("led_pin", "--pin"), - ("num_leds", "--leds"), - ("brightness", "--brightness"), - ("transport", "--transport"), - ("ssid", "--ssid"), - ("password", "--wifi-password"), - ("wifi_channel", "--wifi-channel"), - ("default", "--default"), - ) - - for key, flag in flag_map: - value = payload.get(key) - if value is None: - continue - value_str = str(value).strip() - if value_str == "": - continue - cmd.extend([flag, value_str]) - - return cmd - - -def _run_led_cli_command(cmd, cli_path: str, timeout_s=180): - try: - result = subprocess.run( - cmd, - capture_output=True, - text=True, - timeout=timeout_s, - cwd=os.path.dirname(cli_path), - ) - except subprocess.TimeoutExpired: - return ( - json.dumps({"error": "led-tool command timed out after 180 seconds"}), - 504, - {"Content-Type": "application/json"}, - ) - except Exception as exc: - return ( - json.dumps({"error": str(exc)}), - 500, - {"Content-Type": "application/json"}, - ) - - return ( - json.dumps( - { - "ok": result.returncode == 0, - "returncode": result.returncode, - "stdout": result.stdout, - "stderr": result.stderr, - "command": cmd, - } - ), - 200, - {"Content-Type": "application/json"}, - ) - - -def _extract_settings_from_stdout(stdout: str): - text = (stdout or "").strip() - if not text: - return None - try: - parsed = json.loads(text) - return parsed if isinstance(parsed, dict) else None - except Exception: - return None - - -@controller.get("/ports") -async def list_serial_ports(request): - ports = [] - for info in list_ports.comports(): - ports.append( - { - "device": info.device, - "description": info.description, - "hwid": info.hwid, - } - ) - return ( - json.dumps( - { - "ports": ports, - "led_cli_exists": os.path.exists(_led_cli_path()), - } - ), - 200, - {"Content-Type": "application/json"}, - ) - - -@controller.post("/settings") -async def apply_settings(request): - data = request.json or {} - port = str(data.get("port") or "").strip() - if not port: - return ( - json.dumps({"error": "port is required"}), - 400, - {"Content-Type": "application/json"}, - ) - - cli_path = _led_cli_path() - if not os.path.exists(cli_path): - return ( - json.dumps({"error": "led-tool/cli.py not found"}), - 500, - {"Content-Type": "application/json"}, - ) - - cmd = _build_led_cli_command(port, data) + ["--follow"] - return _run_led_cli_command(cmd, cli_path, timeout_s=None) - - -@controller.post("/reset") -@controller.post("/reset/") -async def reset_device(request): - data = request.json or {} - port = str(data.get("port") or "").strip() - if not port: - return ( - json.dumps({"error": "port is required"}), - 400, - {"Content-Type": "application/json"}, - ) - - cli_path = _led_cli_path() - if not os.path.exists(cli_path): - return ( - json.dumps({"error": "led-tool/cli.py not found"}), - 500, - {"Content-Type": "application/json"}, - ) - - cmd = [sys.executable, cli_path, "--port", port, "--reset", "--follow"] - return _run_led_cli_command(cmd, cli_path, timeout_s=None) - - -@controller.get("/settings") -async def read_settings(request): - port = str(request.args.get("port") or "").strip() - if not port: - return ( - json.dumps({"error": "port is required"}), - 400, - {"Content-Type": "application/json"}, - ) - - cli_path = _led_cli_path() - if not os.path.exists(cli_path): - return ( - json.dumps({"error": "led-tool/cli.py not found"}), - 500, - {"Content-Type": "application/json"}, - ) - - cmd = [sys.executable, cli_path, "--port", port, "--show"] - body, status, headers = _run_led_cli_command(cmd, cli_path) - if status != 200: - return body, status, headers - data = json.loads(body) - data["settings"] = _extract_settings_from_stdout(data.get("stdout") or "") - return json.dumps(data), status, headers diff --git a/src/controllers/output.py b/src/controllers/output.py deleted file mode 100644 index 190f0ea..0000000 --- a/src/controllers/output.py +++ /dev/null @@ -1,85 +0,0 @@ -from microdot import Microdot -from models.output import Output -from engine.outputs import open_output -import asyncio -import json - -controller = Microdot() -outputs = Output() - -_JSON = {'Content-Type': 'application/json'} - -TEST_COLORS = ((255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255)) - - -async def run_output_test(out, step_s=1.0): - """Red, green, blue, white for ``step_s`` each, then black.""" - await out.open() - try: - for color in TEST_COLORS: - frame = bytes(color) * out.pixel_count - end = asyncio.get_running_loop().time() + step_s - while asyncio.get_running_loop().time() < end: - await out.send(frame) - await asyncio.sleep(1.0 / out.fps) - finally: - await out.close() - return out.status() - - -@controller.get('') -async def list_outputs(request): - """List all pixel outputs.""" - return json.dumps(outputs), 200, _JSON - - -@controller.get('/') -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('/') -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('/') -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('//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 diff --git a/src/controllers/palette.py b/src/controllers/palette.py deleted file mode 100644 index 8a42218..0000000 --- a/src/controllers/palette.py +++ /dev/null @@ -1,58 +0,0 @@ -from microdot import Microdot -from models.pallet import Palette -import json - -controller = Microdot() -palettes = Palette() - -@controller.get('') -async def list_palettes(request): - """List all palettes.""" - data = {} - for pid in palettes.list(): - colors = palettes.read(pid) - data[pid] = colors - return json.dumps(data), 200, {'Content-Type': 'application/json'} - -@controller.get('/') -async def get_palette(request, id): - """Get a specific palette by ID.""" - if str(id) in palettes: - palette = palettes.read(id) - return json.dumps({"colors": palette or [], "id": str(id)}), 200, {'Content-Type': 'application/json'} - return json.dumps({"error": "Palette not found"}), 404 - -@controller.post('') -async def create_palette(request): - """Create a new palette.""" - try: - data = request.json or {} - colors = data.get("colors", None) - # Palette no longer needs a name; only colors are stored. - palette_id = palettes.create("", colors) - created_colors = palettes.read(palette_id) or [] - return json.dumps({"id": str(palette_id), "colors": created_colors}), 201, {'Content-Type': 'application/json'} - except Exception as e: - return json.dumps({"error": str(e)}), 400 - -@controller.put('/') -async def update_palette(request, id): - """Update an existing palette.""" - try: - data = request.json or {} - # Ignore any name field; only colors are relevant. - if "name" in data: - data.pop("name", None) - if palettes.update(id, data): - colors = palettes.read(id) or [] - return json.dumps({"id": str(id), "colors": colors}), 200, {'Content-Type': 'application/json'} - return json.dumps({"error": "Palette not found"}), 404 - except Exception as e: - return json.dumps({"error": str(e)}), 400 - -@controller.delete('/') -async def delete_palette(request, id): - """Delete a palette.""" - if palettes.delete(id): - return json.dumps({"message": "Palette deleted successfully"}), 200 - return json.dumps({"error": "Palette not found"}), 404 diff --git a/src/controllers/pattern.py b/src/controllers/pattern.py deleted file mode 100644 index 8d25199..0000000 --- a/src/controllers/pattern.py +++ /dev/null @@ -1,500 +0,0 @@ -from microdot import Microdot -from models.pattern import Pattern -from models.device import Device -from util.driver_patterns import ( - driver_patterns_dir, - is_firmware_builtin_pattern_module, - normalize_pattern_py_filename, -) -import json -import re -import os -import socket -from urllib.parse import quote - -controller = Microdot() -patterns = Pattern() - - -def _project_root(): - """Project root (parent of ``src/``). CWD is often ``src/`` when running ``main.py``.""" - here = os.path.dirname(os.path.abspath(__file__)) - return os.path.abspath(os.path.join(here, "..", "..")) - - -def _safe_pattern_filename(name): - if not isinstance(name, str): - return False - if not name.endswith(".py"): - return False - if "/" in name or "\\" in name or ".." in name: - return False - return True - - -_PATTERN_KEY_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]{0,63}$") - - -def _normalize_pattern_key(raw): - """Pattern id / module basename (no .py).""" - if not isinstance(raw, str): - return "" - s = raw.strip() - if s.lower().endswith(".py"): - s = s[:-3].strip() - return s - - -def _valid_pattern_key(key): - return bool(key and _PATTERN_KEY_RE.match(key)) - - -def _http_post_pattern_source(ip, filename, code_text, reload_patterns=True, timeout_s=10.0): - """POST source to driver /patterns/upload?name=...&reload=...; return True on 2xx.""" - if not isinstance(ip, str) or not ip.strip(): - return False - if not isinstance(filename, str) or not filename: - return False - if not isinstance(code_text, str): - return False - - name_q = quote(filename, safe="") - reload_q = "1" if reload_patterns else "0" - path = "/patterns/upload?name=%s&reload=%s" % (name_q, reload_q) - body = code_text.encode("utf-8") - req = ( - "POST %s HTTP/1.1\r\n" - "Host: %s\r\n" - "Content-Type: text/plain; charset=utf-8\r\n" - "Content-Length: %d\r\n" - "Connection: close\r\n" - "\r\n" % (path, ip, len(body)) - ).encode("utf-8") + body - - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - try: - sock.settimeout(timeout_s) - sock.connect((ip.strip(), 80)) - sock.sendall(req) - data = b"" - while True: - chunk = sock.recv(1024) - if not chunk: - break - data += chunk - except OSError: - return False - finally: - try: - sock.close() - except Exception: - pass - - first_line = data.split(b"\r\n", 1)[0] if data else b"" - # Accept any 2xx status. - return b" 2" in first_line - -def load_pattern_definitions(): - """Load pattern definitions from pattern.json file.""" - try: - root = _project_root() - paths = [ - os.path.join(root, "db", "pattern.json"), - os.path.join(root, "pattern.json"), - "db/pattern.json", - "pattern.json", - "/db/pattern.json", - ] - for path in paths: - try: - with open(path, "r") as f: - return json.load(f) - except OSError: - continue - return {} - except Exception as e: - print(f"Error loading pattern.json: {e}") - return {} - - -def load_driver_pattern_names(): - """List available pattern module names from led-driver/src/patterns.""" - try: - names = [] - for filename in os.listdir(driver_patterns_dir()): - if not _safe_pattern_filename(filename) or filename == "__init__.py": - continue - names.append(filename[:-3]) - names.sort() - return names - except OSError: - return [] - - -def build_runtime_pattern_map(): - """ - Runtime pattern map for UI menus. - Keep pattern DB metadata as primary, then add any local driver pattern files - missing from the DB so new OTA files still appear in menus. - """ - definitions = load_pattern_definitions() - available = load_driver_pattern_names() - result = {} - for name, meta in definitions.items(): - result[name] = dict(meta) if isinstance(meta, dict) else {} - for name in available: - if name not in result: - result[name] = {} - return result - -@controller.get('/definitions') -async def get_pattern_definitions(request): - """Get definitions for patterns currently available on the driver.""" - definitions = build_runtime_pattern_map() - return json.dumps(definitions), 200, {'Content-Type': 'application/json'} - - -@controller.get('/ota/manifest') -async def ota_manifest(request): - """Manifest of driver pattern source files for OTA pulls.""" - base_dir = driver_patterns_dir() - host = request.headers.get("Host", "") - if not host: - return json.dumps({"error": "Missing Host header"}), 400, { - "Content-Type": "application/json" - } - try: - names = sorted(os.listdir(base_dir)) - except OSError as e: - return json.dumps({"error": str(e)}), 500, {"Content-Type": "application/json"} - - files = [] - for name in names: - if not _safe_pattern_filename(name) or name == "__init__.py": - continue - files.append({ - "name": name, - "url": "http://%s/patterns/ota/file/%s" % (host, name), - }) - - return json.dumps({"files": files}), 200, {"Content-Type": "application/json"} - - -@controller.get('/ota/file/') -async def ota_pattern_file(request, name): - """Serve one driver pattern source file for OTA pulls.""" - fname = normalize_pattern_py_filename(name) - if not fname or not _safe_pattern_filename(fname) or fname == "__init__.py": - return json.dumps({"error": "Invalid filename"}), 400, { - "Content-Type": "application/json" - } - if is_firmware_builtin_pattern_module(fname): - return json.dumps( - { - "error": "on and off are built into the driver firmware; there is no module file to serve.", - } - ), 400, { - "Content-Type": "application/json" - } - base = driver_patterns_dir() - path = os.path.join(base, fname) - try: - with open(path, "r") as f: - content = f.read() - except OSError: - return json.dumps( - { - "error": "Pattern file not found", - "path": path, - "hint": "Ensure led-driver is present or set LED_CONTROLLER_PATTERNS_DIR.", - } - ), 404, { - "Content-Type": "application/json" - } - return content, 200, {"Content-Type": "text/plain; charset=utf-8"} - - -@controller.post('//send') -async def send_pattern_to_device(request, name): - """Push one pattern source file directly to Wi-Fi driver(s) over HTTP.""" - if not isinstance(name, str): - return json.dumps({"error": "Invalid pattern name"}), 400, { - "Content-Type": "application/json" - } - filename = normalize_pattern_py_filename(name) - if not filename or not _safe_pattern_filename(filename) or filename == "__init__.py": - return json.dumps({"error": "Invalid pattern filename"}), 400, { - "Content-Type": "application/json" - } - if is_firmware_builtin_pattern_module(filename): - return json.dumps( - { - "error": "on and off are built into the driver firmware; send does not apply.", - } - ), 400, { - "Content-Type": "application/json" - } - - devices = Device() - body = request.json or {} - requested_device_id = str(body.get("device_id") or "").strip() - - base = driver_patterns_dir() - path = os.path.join(base, filename) - if not os.path.exists(path): - return json.dumps( - { - "error": "Pattern file not found", - "path": path, - "hint": "Ensure led-driver is present or set LED_CONTROLLER_PATTERNS_DIR.", - } - ), 404, { - "Content-Type": "application/json" - } - - try: - with open(path, "r") as f: - source = f.read() - except OSError as e: - return json.dumps({"error": str(e)}), 500, {"Content-Type": "application/json"} - target_ids = [] - if requested_device_id: - dev = devices.read(requested_device_id) - if not dev: - return json.dumps({"error": "Device not found"}), 404, { - "Content-Type": "application/json" - } - if (dev.get("transport") or "").lower() != "wifi": - return json.dumps({"error": "Pattern send is only supported for Wi-Fi devices"}), 400, { - "Content-Type": "application/json" - } - target_ids = [requested_device_id] - else: - for did in devices.list(): - dev = devices.read(did) or {} - if (dev.get("transport") or "").lower() == "wifi": - target_ids.append(str(did)) - if not target_ids: - return json.dumps({"error": "No Wi-Fi devices found"}), 404, { - "Content-Type": "application/json" - } - - sent_ids = [] - for did in target_ids: - dev = devices.read(did) or {} - ip = str(dev.get("address") or "").strip() - if not ip: - continue - ok = _http_post_pattern_source(ip, filename, source, reload_patterns=True, timeout_s=10.0) - if ok: - sent_ids.append(did) - - if not sent_ids: - return json.dumps({"error": "No Wi-Fi drivers accepted pattern upload"}), 503, { - "Content-Type": "application/json" - } - return json.dumps({"message": "Pattern sent", "pattern": filename, "device_ids": sent_ids, "sent_count": len(sent_ids)}), 200, { - "Content-Type": "application/json" - } - - -@controller.post('/upload') -async def upload_pattern_file(request): - """ - Upload a pattern source file to led-controller local storage. - - Body JSON: - { - "name": "sparkle.py" | "sparkle", - "code": "class Sparkle: ...", - "overwrite": true | false # optional, default true - } - """ - data = request.json or {} - raw_name = data.get("name") or data.get("filename") - code = data.get("code") - overwrite = data.get("overwrite", True) - overwrite = bool(overwrite) - - if not isinstance(raw_name, str) or not raw_name.strip(): - return json.dumps({"error": "name is required"}), 400, { - "Content-Type": "application/json" - } - filename = raw_name.strip() - if not filename.endswith(".py"): - filename += ".py" - if not _safe_pattern_filename(filename) or filename == "__init__.py": - return json.dumps({"error": "invalid pattern filename"}), 400, { - "Content-Type": "application/json" - } - if is_firmware_builtin_pattern_module(filename): - return json.dumps( - {"error": "on and off are built into the driver firmware; use a different pattern name."} - ), 400, { - "Content-Type": "application/json" - } - if not isinstance(code, str) or not code.strip(): - return json.dumps({"error": "code is required"}), 400, { - "Content-Type": "application/json" - } - - path = os.path.join(driver_patterns_dir(), filename) - exists = os.path.exists(path) - if exists and not overwrite: - return json.dumps({"error": "pattern file already exists", "name": filename}), 409, { - "Content-Type": "application/json" - } - - try: - with open(path, "w") as f: - f.write(code) - except OSError as e: - return json.dumps({"error": str(e)}), 500, {"Content-Type": "application/json"} - - return json.dumps({ - "message": "Pattern uploaded", - "name": filename, - "overwrote": bool(exists), - }), 201, {"Content-Type": "application/json"} - - -@controller.post('/driver') -async def create_driver_pattern(request): - """ - Create a driver pattern: save ``.py`` under led-driver/src/patterns and - metadata in db/pattern.json (Pattern model). - - Body JSON: - name, code (required), - min_delay, max_delay, max_colors (optional numbers), - n1..n8 (optional string labels), - overwrite (optional, default true). - """ - data = request.json or {} - key = _normalize_pattern_key(data.get("name") or "") - if not _valid_pattern_key(key): - return json.dumps({ - "error": "name must be a valid Python identifier (e.g. sparkle, my_pattern)", - }), 400, {"Content-Type": "application/json"} - if is_firmware_builtin_pattern_module(key): - return json.dumps( - {"error": "on and off are built into the driver firmware; use a different pattern name."} - ), 400, { - "Content-Type": "application/json" - } - - code = data.get("code") - if not isinstance(code, str) or not code.strip(): - return json.dumps({"error": "code is required (upload a .py file or paste source)"}), 400, { - "Content-Type": "application/json" - } - - overwrite = bool(data.get("overwrite", True)) - - filename = key + ".py" - py_path = os.path.join(driver_patterns_dir(), filename) - if os.path.exists(py_path) and not overwrite: - return json.dumps({"error": "pattern file already exists", "name": filename}), 409, { - "Content-Type": "application/json" - } - - meta = {} - for fld in ("min_delay", "max_delay", "max_colors"): - if fld not in data: - continue - try: - meta[fld] = int(data[fld]) - except (TypeError, ValueError): - return json.dumps({"error": "%s must be an integer" % fld}), 400, { - "Content-Type": "application/json" - } - - for i in range(1, 9): - nk = "n%d" % i - if nk not in data: - continue - lab = data[nk] - if lab is None: - continue - s = str(lab).strip() - if s: - meta[nk] = s - - try: - with open(py_path, "w") as f: - f.write(code) - except OSError as e: - return json.dumps({"error": str(e)}), 500, {"Content-Type": "application/json"} - - if patterns.read(key): - patterns.update(key, meta) - else: - patterns.create(key, meta) - - return json.dumps({ - "message": "Pattern created", - "name": key, - "file": filename, - "metadata": patterns.read(key), - }), 201, {"Content-Type": "application/json"} - - -@controller.get('') -async def list_patterns(request): - """List patterns for UI (DB metadata + local driver additions).""" - return json.dumps(build_runtime_pattern_map()), 200, {'Content-Type': 'application/json'} - - -@controller.get('/') -async def get_pattern(request, id): - """Get a specific pattern by ID.""" - pattern = patterns.read(id) - if pattern is not None: - return json.dumps(pattern), 200, {'Content-Type': 'application/json'} - return json.dumps({"error": "Pattern not found"}), 404 - - -@controller.post('') -async def create_pattern(request): - """Create a new pattern.""" - try: - payload = request.json or {} - name = payload.get("name", "") - pattern_data = payload.get("data", {}) - - # IMPORTANT: - # `patterns.create()` stores `pattern_data` as the underlying dict value. - # If we then call `patterns.update(pattern_id, payload)` with the full - # request object, it may assign `payload["data"]` back onto that same - # dict object, creating a circular reference (json.dumps fails). - pattern_id = patterns.create(name, pattern_data) - - # Only merge "extra" metadata fields (anything except name/data). - extra = dict(payload) - extra.pop("name", None) - extra.pop("data", None) - if extra: - patterns.update(pattern_id, extra) - return json.dumps(patterns.read(pattern_id)), 201, {'Content-Type': 'application/json'} - except Exception as e: - return json.dumps({"error": str(e)}), 400 - - -@controller.put('/') -async def update_pattern(request, id): - """Update an existing pattern.""" - try: - data = request.json - if patterns.update(id, data): - return json.dumps(patterns.read(id)), 200, {'Content-Type': 'application/json'} - return json.dumps({"error": "Pattern not found"}), 404 - except Exception as e: - return json.dumps({"error": str(e)}), 400 - - -@controller.delete('/') -async def delete_pattern(request, id): - """Delete a pattern.""" - if patterns.delete(id): - return json.dumps({"message": "Pattern deleted successfully"}), 200 - return json.dumps({"error": "Pattern not found"}), 404 diff --git a/src/controllers/preset.py b/src/controllers/preset.py deleted file mode 100644 index 599f976..0000000 --- a/src/controllers/preset.py +++ /dev/null @@ -1,322 +0,0 @@ -from microdot import Microdot -from microdot.session import with_session -from models.preset import Preset -from models.profile import Profile -from models.device import Device, normalize_mac -from models.transport import get_current_sender -from util.driver_delivery import deliver_json_messages, deliver_preset_broadcast_then_per_device -from util.espnow_message import build_message, build_preset_dict -import json - -controller = Microdot() -presets = Preset() -profiles = Profile() - -def get_current_profile_id(session=None): - """Get the current active profile ID from session or fallback to first.""" - profile_list = profiles.list() - session_profile = None - if session is not None: - session_profile = session.get('current_profile') - if session_profile and session_profile in profile_list: - return session_profile - if profile_list: - return profile_list[0] - return None - -@controller.get('') -@with_session -async def list_presets(request, session): - """List presets for the current profile.""" - current_profile_id = get_current_profile_id(session) - if not current_profile_id: - return json.dumps({}), 200, {'Content-Type': 'application/json'} - scoped = { - pid: pdata for pid, pdata in presets.items() - if isinstance(pdata, dict) and str(pdata.get("profile_id")) == str(current_profile_id) - } - return json.dumps(scoped), 200, {'Content-Type': 'application/json'} - -@controller.get('/') -@with_session -async def get_preset(request, session, preset_id): - """Get a specific preset by ID (current profile only).""" - preset = presets.read(preset_id) - current_profile_id = get_current_profile_id(session) - if preset and str(preset.get("profile_id")) == str(current_profile_id): - return json.dumps(preset), 200, {'Content-Type': 'application/json'} - return json.dumps({"error": "Preset not found"}), 404 - -@controller.post('') -@with_session -async def create_preset(request, session): - """Create a new preset for the current profile.""" - try: - try: - data = request.json or {} - except Exception: - return json.dumps({"error": "Invalid JSON"}), 400, {'Content-Type': 'application/json'} - current_profile_id = get_current_profile_id(session) - if not current_profile_id: - return json.dumps({"error": "No profile available"}), 404 - preset_id = presets.create(current_profile_id) - if not isinstance(data, dict): - data = {} - data = dict(data) - data["profile_id"] = str(current_profile_id) - if presets.update(preset_id, data): - preset_data = presets.read(preset_id) - return json.dumps({preset_id: preset_data}), 201, {'Content-Type': 'application/json'} - return json.dumps({"error": "Failed to create preset"}), 400 - except Exception as e: - return json.dumps({"error": str(e)}), 400 - -@controller.put('/') -@with_session -async def update_preset(request, session, preset_id): - """Update an existing preset (current profile only).""" - try: - preset = presets.read(preset_id) - current_profile_id = get_current_profile_id(session) - if not preset or str(preset.get("profile_id")) != str(current_profile_id): - return json.dumps({"error": "Preset not found"}), 404 - try: - data = request.json or {} - except Exception: - return json.dumps({"error": "Invalid JSON"}), 400, {'Content-Type': 'application/json'} - if not isinstance(data, dict): - data = {} - data = dict(data) - data["profile_id"] = str(current_profile_id) - if presets.update(preset_id, data): - return json.dumps(presets.read(preset_id)), 200, {'Content-Type': 'application/json'} - return json.dumps({"error": "Preset not found"}), 404 - except Exception as e: - return json.dumps({"error": str(e)}), 400 - -@controller.delete('/') -@with_session -async def delete_preset(request, *args, **kwargs): - """Delete a preset (current profile only).""" - # Be tolerant of wrapper/arg-order variations. - session = None - preset_id = None - if len(args) > 0: - session = args[0] - if len(args) > 1: - preset_id = args[1] - if 'session' in kwargs and kwargs.get('session') is not None: - session = kwargs.get('session') - if 'preset_id' in kwargs and kwargs.get('preset_id') is not None: - preset_id = kwargs.get('preset_id') - if 'id' in kwargs and kwargs.get('id') is not None and preset_id is None: - preset_id = kwargs.get('id') - if preset_id is None: - return json.dumps({"error": "Preset ID is required"}), 400 - preset = presets.read(preset_id) - current_profile_id = get_current_profile_id(session) - if not preset or str(preset.get("profile_id")) != str(current_profile_id): - return json.dumps({"error": "Preset not found"}), 404 - if presets.delete(preset_id): - return json.dumps({"message": "Preset deleted successfully"}), 200 - return json.dumps({"error": "Preset not found"}), 404 - - -@controller.post('/send') -@with_session -async def send_presets(request, session): - """ - Send one or more presets to LED drivers (serial/ESP-NOW and/or TCP Wi-Fi clients). - - Body JSON: - {"preset_ids": ["1", "2", ...]} or {"ids": ["1", "2", ...]} - Optional "targets": ["aabbccddeeff", ...] — registry MACs. When set: preset - chunks are ESP-NOW broadcast once each; Wi-Fi drivers get the same chunks - over TCP; if "default" is set, each target then gets a unicast default - message (serial or TCP) with that device name in "targets". - Omit targets for broadcast-only serial (legacy). - - Optional "destination_mac" / "to": single MAC when targets is omitted. - """ - try: - data = request.json or {} - except Exception: - return json.dumps({"error": "Invalid JSON"}), 400, {'Content-Type': 'application/json'} - - preset_ids = data.get('preset_ids') or data.get('ids') - if not isinstance(preset_ids, list) or not preset_ids: - return json.dumps({"error": "preset_ids must be a non-empty list"}), 400, {'Content-Type': 'application/json'} - save_flag = data.get('save', True) - save_flag = bool(save_flag) - default_id = data.get('default') - destination_mac = data.get('destination_mac') or data.get('to') - - # Build API-compliant preset map keyed by preset ID, include name - current_profile_id = get_current_profile_id(session) - presets_by_name = {} - for pid in preset_ids: - preset_data = presets.read(str(pid)) - if not preset_data: - continue - if str(preset_data.get("profile_id")) != str(current_profile_id): - continue - preset_key = str(pid) - preset_payload = build_preset_dict(preset_data) - preset_payload["name"] = preset_data.get("name", "") - presets_by_name[preset_key] = preset_payload - - if not presets_by_name: - return json.dumps({"error": "No matching presets found"}), 404, {'Content-Type': 'application/json'} - - if default_id is not None and str(default_id) not in presets_by_name: - default_id = None - - sender = get_current_sender() - if not sender: - return json.dumps({"error": "Transport not configured"}), 503, {'Content-Type': 'application/json'} - - MAX_BYTES = 240 - send_delay_s = 0.1 - entries = list(presets_by_name.items()) - total_presets = len(entries) - - batch = {} - chunk_messages = [] - for name, preset_obj in entries: - test_batch = dict(batch) - test_batch[name] = preset_obj - test_msg = build_message(presets=test_batch, save=save_flag, default=default_id) - size = len(test_msg) - - if size <= MAX_BYTES or not batch: - batch = test_batch - else: - chunk_messages.append( - build_message( - presets=dict(batch), - save=False, - default=None, - ) - ) - batch = {name: preset_obj} - - if batch: - chunk_messages.append( - build_message( - presets=dict(batch), - save=save_flag, - default=default_id, - ) - ) - - target_list = None - raw_targets = data.get("targets") - if isinstance(raw_targets, list) and raw_targets: - target_list = [] - for t in raw_targets: - m = normalize_mac(str(t)) - if m: - target_list.append(m) - target_list = list(dict.fromkeys(target_list)) - if not target_list: - target_list = None - elif destination_mac: - dm = normalize_mac(str(destination_mac)) - target_list = [dm] if dm else None - - try: - if target_list: - deliveries = await deliver_preset_broadcast_then_per_device( - sender, - chunk_messages, - target_list, - Device(), - str(default_id) if default_id is not None else None, - delay_s=send_delay_s, - ) - else: - deliveries, _chunks = await deliver_json_messages( - sender, - chunk_messages, - None, - Device(), - delay_s=send_delay_s, - ) - except Exception: - return json.dumps({"error": "Send failed"}), 503, {'Content-Type': 'application/json'} - - return json.dumps({ - "message": "Presets sent", - "presets_sent": total_presets, - "messages_sent": deliveries, - }), 200, {'Content-Type': 'application/json'} - - -@controller.post('/push') -@with_session -async def push_driver_messages(request, session): - """ - Deliver one or more raw v1 JSON objects to devices (ESP-NOW and/or TCP). - - Body: - {"sequence": [{ "v": "1", ... }, ...], "targets": ["mac", ...]} - or a single {"payload": {...}, "targets": [...]}. - """ - try: - data = request.json or {} - except Exception: - return json.dumps({"error": "Invalid JSON"}), 400, {'Content-Type': 'application/json'} - - seq = data.get("sequence") - if not seq and data.get("payload") is not None: - seq = [data["payload"]] - if not isinstance(seq, list) or not seq: - return json.dumps({"error": "sequence or payload required"}), 400, {'Content-Type': 'application/json'} - - raw_targets = data.get("targets") - target_list = None - if isinstance(raw_targets, list) and raw_targets: - target_list = [] - for t in raw_targets: - m = normalize_mac(str(t)) - if m: - target_list.append(m) - target_list = list(dict.fromkeys(target_list)) - if not target_list: - target_list = None - - sender = get_current_sender() - if not sender: - return json.dumps({"error": "Transport not configured"}), 503, {'Content-Type': 'application/json'} - - messages = [] - for item in seq: - if isinstance(item, dict): - messages.append(json.dumps(item)) - elif isinstance(item, str): - messages.append(item) - else: - return json.dumps({"error": "sequence items must be objects or strings"}), 400, {'Content-Type': 'application/json'} - - delay_s = data.get("delay_s", 0.05) - try: - delay_s = float(delay_s) - except (TypeError, ValueError): - delay_s = 0.05 - - try: - deliveries, _chunks = await deliver_json_messages( - sender, - messages, - target_list, - Device(), - delay_s=delay_s, - ) - except Exception: - return json.dumps({"error": "Send failed"}), 503, {'Content-Type': 'application/json'} - - return json.dumps({ - "message": "Delivered", - "deliveries": deliveries, - }), 200, {'Content-Type': 'application/json'} - diff --git a/src/controllers/profile.py b/src/controllers/profile.py deleted file mode 100644 index 675dd3f..0000000 --- a/src/controllers/profile.py +++ /dev/null @@ -1,390 +0,0 @@ -from microdot import Microdot -from microdot.session import with_session -from models.profile import Profile -from models.zone import Zone -from models.preset import Preset -import json - -controller = Microdot() -profiles = Profile() -zones = Zone() -presets = Preset() - -@controller.get('') -@with_session -async def list_profiles(request, session): - """List all profiles with current profile info.""" - profile_list = profiles.list() - current_id = session.get('current_profile') - if current_id and current_id not in profile_list: - current_id = None - - # If no current profile in session, use first one - if not current_id and profile_list: - current_id = profile_list[0] - session['current_profile'] = str(current_id) - session.save() - - # Build profiles object - profiles_data = {} - for profile_id in profile_list: - profile_data = profiles.read(profile_id) - if profile_data: - profiles_data[profile_id] = profile_data - - return json.dumps({ - "profiles": profiles_data, - "current_profile_id": current_id - }), 200, {'Content-Type': 'application/json'} - -@controller.get('/current') -@with_session -async def get_current_profile(request, session): - """Get the current profile ID from session (or fallback).""" - profile_list = profiles.list() - current_id = session.get('current_profile') - if current_id and current_id not in profile_list: - current_id = None - if not current_id and profile_list: - current_id = profile_list[0] - session['current_profile'] = str(current_id) - session.save() - if current_id: - profile = profiles.read(current_id) - return json.dumps({"id": current_id, "profile": profile}), 200, {'Content-Type': 'application/json'} - return json.dumps({"error": "No profile available"}), 404 - -@controller.get('/') -@with_session -async def get_profile(request, id, session): - """Get a specific profile by ID.""" - # Handle 'current' as a special case - if id == 'current': - return await get_current_profile(request, session) - - profile = profiles.read(id) - if profile: - return json.dumps(profile), 200, {'Content-Type': 'application/json'} - return json.dumps({"error": "Profile not found"}), 404 - -@controller.post('//apply') -@with_session -async def apply_profile(request, session, id): - """Apply a profile by saving it to session.""" - if not profiles.read(id): - return json.dumps({"error": "Profile not found"}), 404 - session['current_profile'] = str(id) - session.save() - return json.dumps({"message": "Profile applied", "id": str(id)}), 200, {'Content-Type': 'application/json'} - -@controller.post('') -async def create_profile(request): - """Create a new profile.""" - try: - data = dict(request.json or {}) - name = data.get("name", "") - seed_raw = data.get("seed_dj_zone", False) - if isinstance(seed_raw, str): - seed_dj_zone = seed_raw.strip().lower() in ("1", "true", "yes", "on") - else: - seed_dj_zone = bool(seed_raw) - # Request-only flag: do not persist on profile records. - data.pop("seed_dj_zone", None) - profile_id = profiles.create(name) - # Avoid persisting request-only fields. - data.pop("name", None) - if data: - profiles.update(profile_id, data) - - # New profiles always start with a default zone pre-populated with starter presets. - default_preset_ids = [] - default_preset_defs = [ - { - "name": "on", - "pattern": "on", - "colors": ["#FFFFFF"], - "brightness": 255, - "delay": 100, - "auto": True, - }, - { - "name": "off", - "pattern": "off", - "colors": [], - "brightness": 0, - "delay": 100, - "auto": True, - }, - { - "name": "rainbow", - "pattern": "rainbow", - "colors": [], - "brightness": 255, - "delay": 100, - "auto": True, - "n1": 2, - }, - { - "name": "Colour Cycle", - "pattern": "colour_cycle", - "colors": ["#FF0000", "#00FF00", "#0000FF"], - "brightness": 255, - "delay": 100, - "auto": True, - "n1": 1, - }, - { - "name": "transition", - "pattern": "transition", - "colors": ["#FF0000", "#00FF00", "#0000FF"], - "brightness": 255, - "delay": 500, - "auto": True, - }, - { - "name": "flicker", - "pattern": "flicker", - "colors": ["#FFB84D"], - "brightness": 255, - "delay": 80, - "auto": True, - "n1": 30, - }, - { - "name": "flame", - "pattern": "flame", - "colors": [], - "brightness": 255, - "delay": 50, - "auto": True, - "n1": 35, - "n2": 2600, - "n3": 0, - "n4": 0, - }, - { - "name": "twinkle", - "pattern": "twinkle", - "colors": ["#78C8FF", "#508CFF", "#B478FF", "#64DCE8", "#A0C8FF"], - "brightness": 255, - "delay": 55, - "auto": True, - "n1": 72, - "n2": 140, - "n3": 2, - "n4": 6, - }, - ] - - for preset_data in default_preset_defs: - pid = presets.create(profile_id) - presets.update(pid, preset_data) - default_preset_ids.append(str(pid)) - - default_tab_id = zones.create(name="default", names=["1"], presets=[default_preset_ids]) - zones.update(default_tab_id, { - "presets_flat": default_preset_ids, - "default_preset": default_preset_ids[0] if default_preset_ids else None, - }) - - profile = profiles.read(profile_id) or {} - profile_tabs = profile.get("zones", []) if isinstance(profile.get("zones", []), list) else [] - profile_tabs.append(str(default_tab_id)) - - if seed_dj_zone: - # Seed a DJ-focused zone with three starter presets. - seeded_preset_ids = [] - preset_defs = [ - { - "name": "DJ Rainbow", - "pattern": "rainbow", - "colors": [], - "brightness": 220, - "delay": 60, - "n1": 12, - }, - { - "name": "DJ Single Color", - "pattern": "on", - "colors": ["#ff00ff"], - "brightness": 220, - "delay": 100, - }, - { - "name": "DJ Transition", - "pattern": "transition", - "colors": ["#ff0000", "#00ff00", "#0000ff"], - "brightness": 220, - "delay": 250, - }, - ] - - for preset_data in preset_defs: - pid = presets.create(profile_id) - presets.update(pid, preset_data) - seeded_preset_ids.append(str(pid)) - - dj_tab_id = zones.create(name="dj", names=["dj"], presets=[seeded_preset_ids]) - zones.update(dj_tab_id, { - "presets_flat": seeded_preset_ids, - "default_preset": seeded_preset_ids[0] if seeded_preset_ids else None, - }) - - profile_tabs.append(str(dj_tab_id)) - - profiles.update(profile_id, {"zones": profile_tabs}) - - profile_data = profiles.read(profile_id) - return json.dumps({profile_id: profile_data}), 201, {'Content-Type': 'application/json'} - except Exception as e: - return json.dumps({"error": str(e)}), 400 - -@controller.post('//clone') -async def clone_profile(request, id): - """Clone an existing profile along with its tabs and palette.""" - try: - source = profiles.read(id) - if not source: - return json.dumps({"error": "Profile not found"}), 404 - - data = request.json or {} - source_name = source.get("name") or f"Profile {id}" - new_name = data.get("name") or source_name - profile_type = source.get("type", "zones") - - def allocate_id(model, cache): - if "next" not in cache: - max_id = max((int(k) for k in model.keys() if str(k).isdigit()), default=0) - cache["next"] = max_id + 1 - next_id = str(cache["next"]) - cache["next"] += 1 - return next_id - - def map_preset_container(value, id_map, preset_cache, new_profile_id, new_presets): - if isinstance(value, list): - return [map_preset_container(v, id_map, preset_cache, new_profile_id, new_presets) for v in value] - if value is None: - return None - preset_id = str(value) - if preset_id in id_map: - return id_map[preset_id] - preset_data = presets.read(preset_id) - if not preset_data: - return None - new_preset_id = allocate_id(presets, preset_cache) - clone_data = dict(preset_data) - clone_data["profile_id"] = str(new_profile_id) - new_presets[new_preset_id] = clone_data - id_map[preset_id] = new_preset_id - return new_preset_id - - # Prepare new IDs without writing until everything is ready. - profile_cache = {} - palette_cache = {} - tab_cache = {} - preset_cache = {} - - new_profile_id = allocate_id(profiles, profile_cache) - new_palette_id = allocate_id(profiles._palette_model, palette_cache) - - # Clone palette colors into the new profile's palette - src_palette_id = source.get("palette_id") - palette_colors = [] - if src_palette_id: - try: - palette_colors = profiles._palette_model.read(src_palette_id) - except Exception: - palette_colors = [] - - # Clone tabs and presets used by those tabs - source_tabs = source.get("zones") - if not isinstance(source_tabs, list) or len(source_tabs) == 0: - source_tabs = source.get("zone_order", []) - source_tabs = source_tabs or [] - cloned_tab_ids = [] - preset_id_map = {} - new_tabs = {} - new_presets = {} - for zone_id in source_tabs: - zone = zones.read(zone_id) - if not zone: - continue - tab_name = zone.get("name") or f"Zone {zone_id}" - clone_name = tab_name - mapped_presets = map_preset_container(zone.get("presets"), preset_id_map, preset_cache, new_profile_id, new_presets) - clone_id = allocate_id(zones, tab_cache) - clone_data = { - "name": clone_name, - "names": zone.get("names") or [], - "presets": mapped_presets if mapped_presets is not None else [] - } - extra = {k: v for k, v in zone.items() if k not in ("name", "names", "presets")} - if "presets_flat" in extra: - extra["presets_flat"] = map_preset_container(extra.get("presets_flat"), preset_id_map, preset_cache, new_profile_id, new_presets) - if extra: - clone_data.update(extra) - new_tabs[clone_id] = clone_data - cloned_tab_ids.append(clone_id) - - new_profile_data = { - "name": new_name, - "type": profile_type, - "zones": cloned_tab_ids, - "scenes": list(source.get("scenes", [])) if isinstance(source.get("scenes", []), list) else [], - "palette_id": str(new_palette_id), - } - - # Commit all changes and save once per model. - profiles._palette_model[str(new_palette_id)] = list(palette_colors) if palette_colors else [] - for pid, pdata in new_presets.items(): - presets[pid] = pdata - for tid, tdata in new_tabs.items(): - zones[tid] = tdata - profiles[str(new_profile_id)] = new_profile_data - - profiles._palette_model.save() - presets.save() - zones.save() - profiles.save() - - return json.dumps({new_profile_id: new_profile_data}), 201, {'Content-Type': 'application/json'} - except Exception as e: - return json.dumps({"error": str(e)}), 400 - -@controller.put('/current') -@with_session -async def update_current_profile(request, session): - """Update the current profile using session (or fallback).""" - try: - data = request.json or {} - profile_list = profiles.list() - current_id = session.get('current_profile') - if not current_id and profile_list: - current_id = profile_list[0] - session['current_profile'] = str(current_id) - session.save() - if not current_id: - return json.dumps({"error": "No profile available"}), 404 - if profiles.update(current_id, data): - return json.dumps(profiles.read(current_id)), 200, {'Content-Type': 'application/json'} - return json.dumps({"error": "Profile not found"}), 404 - except Exception as e: - return json.dumps({"error": str(e)}), 400 - -@controller.put('/') -async def update_profile(request, id): - """Update an existing profile.""" - try: - data = request.json - if profiles.update(id, data): - return json.dumps(profiles.read(id)), 200, {'Content-Type': 'application/json'} - return json.dumps({"error": "Profile not found"}), 404 - except Exception as e: - return json.dumps({"error": str(e)}), 400 - -@controller.delete('/') -async def delete_profile(request, id): - """Delete a profile.""" - if profiles.delete(id): - return json.dumps({"message": "Profile deleted successfully"}), 200 - return json.dumps({"error": "Profile not found"}), 404 diff --git a/src/controllers/scene.py b/src/controllers/scene.py deleted file mode 100644 index 018f93e..0000000 --- a/src/controllers/scene.py +++ /dev/null @@ -1,83 +0,0 @@ -from microdot import Microdot -from models.scene import Scene -import json - -controller = Microdot() -scenes = Scene() - -@controller.get('') -async def list_scenes(request): - """List all scenes.""" - return json.dumps(scenes), 200, {'Content-Type': 'application/json'} - -@controller.get('/') -async def get_scene(request, id): - """Get a specific scene by ID.""" - scene = scenes.read(id) - if scene: - return json.dumps(scene), 200, {'Content-Type': 'application/json'} - return json.dumps({"error": "Scene not found"}), 404 - -@controller.post('') -async def create_scene(request): - """Create a new scene.""" - try: - data = request.json - scene_id = scenes.create() - if scenes.update(scene_id, data): - return json.dumps(scenes.read(scene_id)), 201, {'Content-Type': 'application/json'} - return json.dumps({"error": "Failed to create scene"}), 400 - except Exception as e: - return json.dumps({"error": str(e)}), 400 - -@controller.put('/') -async def update_scene(request, id): - """Update an existing scene.""" - try: - data = request.json - if scenes.update(id, data): - return json.dumps(scenes.read(id)), 200, {'Content-Type': 'application/json'} - return json.dumps({"error": "Scene not found"}), 404 - except Exception as e: - return json.dumps({"error": str(e)}), 400 - -@controller.delete('/') -async def delete_scene(request, id): - """Delete a scene.""" - if scenes.delete(id): - return json.dumps({"message": "Scene deleted successfully"}), 200 - return json.dumps({"error": "Scene not found"}), 404 - - -@controller.post('//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('//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'} diff --git a/src/controllers/sequence.py b/src/controllers/sequence.py deleted file mode 100644 index 4d4b6a6..0000000 --- a/src/controllers/sequence.py +++ /dev/null @@ -1,78 +0,0 @@ -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, _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('/') -async def get_sequence(request, id): - """Get a specific sequence by ID.""" - sequence = sequences.read(id) - if sequence: - return json.dumps(sequence), 200, _JSON - return json.dumps({"error": "Sequence not found"}), 404, _JSON - - -@controller.post('') -async def create_sequence(request): - """Create a sequence: {name, zone_id, loop, repeat_count, steps: [{preset_id, duration_s}]}.""" - try: - 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('/') -async def update_sequence(request, id): - """Update an existing sequence.""" - try: - 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('/') -async def delete_sequence(request, id): - """Delete a sequence (stops it first if running).""" - await get_engine().sequences.stop(id) - if sequences.delete(id): - return json.dumps({"message": "Sequence deleted successfully"}), 200, _JSON - return json.dumps({"error": "Sequence not found"}), 404, _JSON - - -@controller.post('//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('//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 diff --git a/src/controllers/settings.py b/src/controllers/settings.py deleted file mode 100644 index 9bfdb79..0000000 --- a/src/controllers/settings.py +++ /dev/null @@ -1,110 +0,0 @@ -import asyncio -import json - -from microdot import Microdot, send_file - -from models import wifi_ws_clients -from settings import Settings - -controller = Microdot() -settings = Settings() - -@controller.get('') -async def get_settings(request): - """Get all settings.""" - # Settings is already a dict subclass; avoid dict() wrapper which can - # trigger MicroPython's "dict update sequence has wrong length" quirk. - return json.dumps(settings), 200, {'Content-Type': 'application/json'} - -@controller.get('/wifi/ap') -async def get_ap_config(request): - """Get saved AP configuration (Pi: no in-device AP).""" - config = { - 'saved_ssid': settings.get('wifi_ap_ssid'), - 'saved_password': settings.get('wifi_ap_password'), - 'saved_channel': settings.get('wifi_ap_channel'), - 'active': False, - } - return json.dumps(config), 200, {'Content-Type': 'application/json'} - -@controller.post('/wifi/ap') -async def configure_ap(request): - """Save AP configuration to settings (Pi: no in-device AP).""" - try: - data = request.json - ssid = data.get('ssid') - password = data.get('password', '') - channel = data.get('channel') - - if not ssid: - return json.dumps({"error": "SSID is required"}), 400 - - # Validate channel (1-11 for 2.4GHz) - if channel is not None: - channel = int(channel) - if channel < 1 or channel > 11: - return json.dumps({"error": "Channel must be between 1 and 11"}), 400 - - settings['wifi_ap_ssid'] = ssid - settings['wifi_ap_password'] = password - if channel is not None: - settings['wifi_ap_channel'] = channel - settings.save() - - return json.dumps({ - "message": "AP settings saved", - "ssid": ssid, - "channel": channel - }), 200, {'Content-Type': 'application/json'} - except Exception as e: - return json.dumps({"error": str(e)}), 500 - -def _validate_wifi_channel(value): - """Return int 1–11 or raise ValueError.""" - ch = int(value) - if ch < 1 or ch > 11: - raise ValueError("wifi_channel must be between 1 and 11") - 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 - except Exception as e: - return json.dumps({"error": str(e)}), 500 - -@controller.get('/page') -async def settings_page(request): - """Serve the settings page.""" - return send_file('templates/settings.html') - diff --git a/src/controllers/zone.py b/src/controllers/zone.py deleted file mode 100644 index fdc71e2..0000000 --- a/src/controllers/zone.py +++ /dev/null @@ -1,400 +0,0 @@ -from microdot import Microdot, send_file -from microdot.session import with_session -from models.zone import Zone -from models.profile import Profile -import json - -controller = Microdot() -zones = Zone() -profiles = Profile() - - -def get_current_profile_id(session=None): - """Get the current active profile ID from session or fallback to first.""" - profile_list = profiles.list() - session_profile = None - if session is not None: - session_profile = session.get("current_profile") - if session_profile and session_profile in profile_list: - return session_profile - if profile_list: - return profile_list[0] - return None - - -def _profile_zone_id_list(profile): - """Ordered zone ids for a profile (``zones``, legacy ``tabs``, or ``zone_order``).""" - if not profile or not isinstance(profile, dict): - return [] - z = profile.get("zones") - if isinstance(z, list) and z: - return list(z) - t = profile.get("zones") - if isinstance(t, list) and t: - return list(t) - o = profile.get("zone_order") - if isinstance(o, list) and o: - return list(o) - return [] - - -def get_profile_zone_order(profile_id): - if not profile_id: - return [] - profile = profiles.read(profile_id) - return _profile_zone_id_list(profile) - - -def _set_profile_zone_order(profile, ids): - profile["zones"] = list(ids) - profile.pop("tabs", None) - profile.pop("zone_order", None) - - -def get_current_zone_id(request, session=None): - """Cookie ``current_zone``, legacy ``current_zone``, then first zone in profile.""" - z = request.cookies.get("current_zone") or request.cookies.get("current_zone") - if z: - return z - profile_id = get_current_profile_id(session) - if profile_id: - profile = profiles.read(profile_id) - order = _profile_zone_id_list(profile) - if order: - return order[0] - return None - - -def _render_zones_list_fragment(request, session): - """Render zone strip HTML for HTMX / JS.""" - profile_id = get_current_profile_id(session) - if not profile_id: - return ( - '
No profile selected
', - 200, - {"Content-Type": "text/html"}, - ) - - zone_order = get_profile_zone_order(profile_id) - current_zone_id = get_current_zone_id(request, session) - - html = '
' - for zid in zone_order: - zdata = zones.read(zid) - if zdata: - active_class = "active" if str(zid) == str(current_zone_id) else "" - zname = zdata.get("name", "Zone " + str(zid)) - html += ( - '" - ) - html += "
" - return html, 200, {"Content-Type": "text/html"} - - -def _render_zone_content_fragment(request, session, id): - if id == "current": - current_zone_id = get_current_zone_id(request, session) - if not current_zone_id: - accept_header = request.headers.get("Accept", "") - wants_html = "text/html" in accept_header - if wants_html: - return ( - '
No current zone set
', - 404, - {"Content-Type": "text/html"}, - ) - return json.dumps({"error": "No current zone set"}), 404 - id = current_zone_id - - z = zones.read(id) - if not z: - return '
Zone not found
', 404, {"Content-Type": "text/html"} - - session["current_zone"] = str(id) - session.save() - - if not request.headers.get("HX-Request"): - return send_file("templates/index.html") - - html = ( - '
' - "

Presets

" - '
' - '
' - "" - "
" - "
" - ) - return html, 200, {"Content-Type": "text/html"} - - -@controller.get("//content-fragment") -@with_session -async def zone_content_fragment(request, session, id): - return _render_zone_content_fragment(request, session, id) - - -@controller.get("") -@with_session -async def list_zones(request, session): - profile_id = get_current_profile_id(session) - current_zone_id = get_current_zone_id(request, session) - zone_order = get_profile_zone_order(profile_id) if profile_id else [] - - zones_data = {} - for zid in zones.list(): - zdata = zones.read(zid) - if zdata: - zones_data[zid] = zdata - - return ( - json.dumps( - { - "zones": zones_data, - "zone_order": zone_order, - "current_zone_id": current_zone_id, - "profile_id": profile_id, - } - ), - 200, - {"Content-Type": "application/json"}, - ) - - -@controller.get("/current") -@with_session -async def get_current_zone(request, session): - current_zone_id = get_current_zone_id(request, session) - if not current_zone_id: - return ( - json.dumps({"error": "No current zone set", "zone": None, "zone_id": None}), - 404, - ) - - z = zones.read(current_zone_id) - if z: - return ( - json.dumps({"zone": z, "zone_id": current_zone_id}), - 200, - {"Content-Type": "application/json"}, - ) - return ( - json.dumps({"error": "Zone not found", "zone": None, "zone_id": None}), - 404, - ) - - -@controller.post("//set-current") -async def set_current_zone(request, id): - z = zones.read(id) - if not z: - return json.dumps({"error": "Zone not found"}), 404 - - response_data = json.dumps({"message": "Current zone set", "zone_id": id}) - return ( - response_data, - 200, - { - "Content-Type": "application/json", - "Set-Cookie": ( - f"current_zone={id}; Path=/; Max-Age=31536000; SameSite=Lax" - ), - }, - ) - - -@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("//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("//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("/") -async def get_zone(request, id): - z = zones.read(id) - if z: - return json.dumps(z), 200, {"Content-Type": "application/json"} - return json.dumps({"error": "Zone not found"}), 404 - - -@controller.put("/") -async def update_zone(request, id): - try: - data = request.json - if zones.update(id, data): - return json.dumps(zones.read(id)), 200, {"Content-Type": "application/json"} - return json.dumps({"error": "Zone not found"}), 404 - except Exception as e: - return json.dumps({"error": str(e)}), 400 - - -@controller.delete("/") -@with_session -async def delete_zone(request, session, id): - try: - if id == "current": - current_zone_id = get_current_zone_id(request, session) - if current_zone_id: - id = current_zone_id - else: - return json.dumps({"error": "No current zone to delete"}), 404 - - if zones.delete(id): - profile_id = get_current_profile_id(session) - if profile_id: - profile = profiles.read(profile_id) - if profile: - zlist = _profile_zone_id_list(profile) - if id in zlist: - zlist.remove(id) - _set_profile_zone_order(profile, zlist) - profiles.update(profile_id, profile) - - current_zone_id = get_current_zone_id(request, session) - if current_zone_id == id: - response_data = json.dumps({"message": "Zone deleted successfully"}) - return ( - response_data, - 200, - { - "Content-Type": "application/json", - "Set-Cookie": ( - "current_zone=; Path=/; Max-Age=0; SameSite=Lax" - ), - }, - ) - - return json.dumps({"message": "Zone deleted successfully"}), 200, { - "Content-Type": "application/json" - } - - return json.dumps({"error": "Zone not found"}), 404 - except Exception as e: - import sys - - try: - sys.print_exception(e) - except Exception: - pass - return json.dumps({"error": str(e)}), 500, {"Content-Type": "application/json"} - - -@controller.post("") -@with_session -async def create_zone(request, session): - try: - if request.form: - name = request.form.get("name", "").strip() - ids_str = request.form.get("ids", "1").strip() - names = [i.strip() for i in ids_str.split(",") if i.strip()] - preset_ids = None - else: - data = request.json or {} - name = data.get("name", "") - names = data.get("names") - if names is None: - names = data.get("ids") - preset_ids = data.get("presets", None) - - if not name: - return json.dumps({"error": "Zone name cannot be empty"}), 400 - - zid = zones.create(name, names, preset_ids) - - profile_id = get_current_profile_id(session) - if profile_id: - profile = profiles.read(profile_id) - if profile: - zlist = _profile_zone_id_list(profile) - if zid not in zlist: - zlist.append(zid) - _set_profile_zone_order(profile, zlist) - profiles.update(profile_id, profile) - - zdata = zones.read(zid) - return json.dumps({zid: zdata}), 201, {"Content-Type": "application/json"} - except Exception as e: - import sys - - sys.print_exception(e) - return json.dumps({"error": str(e)}), 400 - - -@controller.post("//clone") -@with_session -async def clone_zone(request, session, id): - try: - source = zones.read(id) - if not source: - return json.dumps({"error": "Zone not found"}), 404 - - data = request.json or {} - source_name = source.get("name") or f"Zone {id}" - new_name = data.get("name") or f"{source_name} Copy" - clone_id = zones.create(new_name, source.get("names"), source.get("presets")) - extra = {k: v for k, v in source.items() if k not in ("name", "names", "presets")} - if extra: - zones.update(clone_id, extra) - - profile_id = get_current_profile_id(session) - if profile_id: - profile = profiles.read(profile_id) - if profile: - zlist = _profile_zone_id_list(profile) - if clone_id not in zlist: - zlist.append(clone_id) - _set_profile_zone_order(profile, zlist) - profiles.update(profile_id, profile) - - zdata = zones.read(clone_id) - return json.dumps({clone_id: zdata}), 201, {"Content-Type": "application/json"} - except Exception as e: - import sys - - try: - sys.print_exception(e) - except Exception: - pass - return json.dumps({"error": str(e)}), 400 - diff --git a/src/engine/__init__.py b/src/engine/__init__.py deleted file mode 100644 index f8294b1..0000000 --- a/src/engine/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -"""Pi-side animation engine. - -* ``engine.outputs`` — protocol drivers (DDP, Art-Net, sACN, USB-DMX, ESP32 presets) -* ``engine.renderer`` — runs unchanged led-driver patterns under CPython -* ``engine.player`` — per-zone frame streaming -* ``engine.sequence_runner`` — timed preset chains - -``get_engine()`` returns the process-wide Engine (created on first use). -""" - -_engine = None - - -def get_engine(): - global _engine - if _engine is None: - from engine.core import Engine - _engine = Engine() - return _engine - - -def set_engine(engine): - global _engine - _engine = engine - return engine diff --git a/src/engine/cli.py b/src/engine/cli.py deleted file mode 100644 index f7c4246..0000000 --- a/src/engine/cli.py +++ /dev/null @@ -1,148 +0,0 @@ -"""Engine CLI (run from ``src/``) — portal's ``run_cli`` equivalent. - - python -m engine.cli --output ddp://10.0.0.5?pixels=300 --test - python -m engine.cli --output artnet://10.0.0.6?universe=0&pixels=170 --color ff0000 - python -m engine.cli --output sacn://?universe=1&pixels=170 --preset 16 - python -m engine.cli --pattern rainbow --n1 2 --leds 60 # stdout preview - python -m engine.cli --output dmx_serial:///dev/ttyUSB0?pixels=10 --pattern pulse \\ - --colors ff0000,0000ff --n1 300 --n2 200 --n3 300 -""" - -import argparse -import asyncio -import sys - -from engine.outputs import parse_output_url -from engine.outputs.base import FrameOutput -from engine.player import ZonePlayer -from engine.zone_targets import ZoneTargets - - -class StdoutOutput(FrameOutput): - """Truecolour terminal strip, one line redrawn per frame.""" - - protocol = "stdout" - - async def _send_prepared(self, payload): - cells = [] - for i in range(0, len(payload), 3): - r, g, b = payload[i], payload[i + 1], payload[i + 2] - cells.append(f"\x1b[48;2;{r};{g};{b}m ") - sys.stdout.write("\r" + "".join(cells) + "\x1b[0m") - sys.stdout.flush() - self.stats.packets += 1 - - -def _output_factory(cfg): - if cfg.get("protocol") == "stdout": - return StdoutOutput(cfg) - from engine.outputs import open_output - return open_output(cfg) - - -def build_parser(): - p = argparse.ArgumentParser(prog="python -m engine.cli", description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - p.add_argument("--output", action="append", default=[], - help="ddp://, artnet://, sacn://, dmx_serial:// URL (repeatable); default stdout") - p.add_argument("--leds", type=int, default=None, help="pixel count (default: from output URL, else 60)") - p.add_argument("--fps", type=int, default=None, help="output fps cap") - p.add_argument("--global-brightness", type=int, default=255, help="0-255, applied at send") - p.add_argument("--duration", type=float, default=None, help="seconds to run (default: until Ctrl-C)") - what = p.add_mutually_exclusive_group() - what.add_argument("--test", action="store_true", help="red, green, blue, white, then black") - what.add_argument("--color", help="solid colour hex, e.g. ff0000") - what.add_argument("--preset", help="preset id from db/preset.json") - what.add_argument("--pattern", help="driver pattern name, e.g. rainbow") - p.add_argument("--colors", default="ffffff", help="comma-separated hex colours for --pattern") - p.add_argument("--delay", type=int, default=100) - p.add_argument("--brightness", type=int, default=255, help="preset brightness 0-255") - p.add_argument("--no-auto", action="store_true", help="manual (beat) mode: auto=false") - for i in range(1, 7): - p.add_argument(f"--n{i}", type=int, default=0) - return p - - -def _frame_cfgs(args): - urls = args.output or ["stdout://"] - cfgs = [] - for url in urls: - cfg = {"protocol": "stdout", "name": "stdout"} if url.startswith("stdout") else parse_output_url(url) - if args.leds is not None: - cfg["pixel_count"] = args.leds - cfg.setdefault("pixel_count", 60) - if args.fps is not None: - cfg["fps"] = args.fps - elif cfg["protocol"] == "stdout": - cfg.setdefault("fps", 20) - cfgs.append(cfg) - return cfgs - - -def _payload_from_args(args): - if args.preset: - from engine.presets import preset_payload - payload = preset_payload(args.preset) - if payload is None: - raise SystemExit(f"preset {args.preset!r} not found") - return args.preset, payload - if args.color: - return "cli", {"p": "on", "c": ["#" + args.color.lstrip("#")], "b": args.brightness} - payload = { - "p": args.pattern or "rainbow", - "c": ["#" + c.strip().lstrip("#") for c in args.colors.split(",") if c.strip()], - "d": args.delay, - "b": args.brightness, - "a": not args.no_auto, - } - for i in range(1, 7): - payload[f"n{i}"] = getattr(args, f"n{i}") - return "cli", payload - - -async def _run_test(player, step_s=1.0): - for color in ((255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255)): - await player.apply("cli", {"p": "on", "c": [color], "b": 255}) - await asyncio.sleep(step_s) - - -async def run(args): - from engine.pattern_loader import get_library - - library = get_library() - if library.errors: - print(f"pattern load errors: {library.errors}", file=sys.stderr) - targets = ZoneTargets("cli", _frame_cfgs(args), []) - player = ZonePlayer(targets, library, lambda: args.global_brightness, output_factory=_output_factory) - await player.start() - try: - if args.test: - await _run_test(player) - return - preset_id, payload = _payload_from_args(args) - if payload.get("p") not in library.ids(): - raise SystemExit(f"unknown pattern {payload.get('p')!r}; available: {', '.join(library.ids())}") - await player.apply(preset_id, payload) - if args.duration: - await asyncio.sleep(args.duration) - else: - while True: - await asyncio.sleep(3600) - finally: - await player.stop() - print() - for st in player.status()["outputs"]: - print(f"{st['name']}: frames={st['frames']} packets={st['packets']} errors={st['errors']}" - + (f" last_error={st['last_error']}" if st["last_error"] else "")) - - -def main(argv=None): - args = build_parser().parse_args(argv) - try: - asyncio.run(run(args)) - except KeyboardInterrupt: - pass - - -if __name__ == "__main__": - main() diff --git a/src/engine/core.py b/src/engine/core.py deleted file mode 100644 index 8954f6a..0000000 --- a/src/engine/core.py +++ /dev/null @@ -1,89 +0,0 @@ -"""Engine: one ZonePlayer per zone + the preset sequencer on top.""" - -import asyncio - -from engine.pattern_loader import get_library -from engine.player import ZonePlayer -from engine.presets import preset_payload -from engine.sequence_runner import SequenceRunner -from engine.zone_targets import resolve_zone - - -class EngineError(Exception): - def __init__(self, message, status=400): - super().__init__(message) - self.status = status - - -class Engine: - def __init__(self, library=None, brightness_getter=None, zone_resolver=None, - payload_resolver=None, player_factory=None, sequences_model=None): - self._library = library - self.brightness_getter = brightness_getter or (lambda: 255) - self._resolve_zone = zone_resolver or resolve_zone - self._payload = payload_resolver or preset_payload - self._player_factory = player_factory or ZonePlayer - self.players = {} - self._lock = None - self.sequences = SequenceRunner(self, sequences_model=sequences_model) - - @property - def library(self): - if self._library is None: - self._library = get_library() - return self._library - - def _get_lock(self): - if self._lock is None: - self._lock = asyncio.Lock() - return self._lock - - async def play(self, zone_id, preset_id, source="manual", drivers=True): - """Run ``preset_id`` on every target of ``zone_id`` (pixel outputs + ESP32s). - - ``source="manual"`` (UI pick) stops any sequence running on the zone. - ``drivers=False`` leaves the ESP32s alone (the UI already sent to them). - """ - zone_id = str(zone_id) - if source == "manual": - await self.sequences.stop_zone(zone_id) - targets = self._resolve_zone(zone_id) - if targets is None: - raise EngineError("Zone not found", 404) - payload = self._payload(str(preset_id)) - if payload is None: - raise EngineError("Preset not found", 404) - async with self._get_lock(): - player = self.players.get(zone_id) - if player is not None and player.targets.signature() != targets.signature(): - await player.stop() - player = None - if player is None: - player = self._player_factory(targets, self.library, self.brightness_getter) - await player.start() - self.players[zone_id] = player - await player.apply(str(preset_id), payload, drivers=drivers) - return player.status() - - async def stop(self, zone_id): - """Stop the zone's sequence and Pi rendering (pixel outputs go black).""" - zone_id = str(zone_id) - await self.sequences.stop_zone(zone_id) - async with self._get_lock(): - player = self.players.pop(zone_id, None) - if player is not None: - await player.stop() - return player is not None - - async def stop_all(self, persist=False): - await self.sequences.stop_all(persist=persist) - async with self._get_lock(): - players, self.players = list(self.players.values()), {} - for player in players: - await player.stop() - - def status(self): - return { - "zones": {zid: p.status() for zid, p in self.players.items()}, - "sequences": self.sequences.status(), - } diff --git a/src/engine/frame_driver.py b/src/engine/frame_driver.py deleted file mode 100644 index 635298b..0000000 --- a/src/engine/frame_driver.py +++ /dev/null @@ -1,68 +0,0 @@ -"""Stand-in for the led-driver ``Presets`` object that patterns draw into. - -Same surface the patterns use on the ESP32 (``n[i]``, ``n.write()``, -``n.fill``, ``num_leds``, ``step``, ``fill``, ``off``, ``on``, -``apply_brightness``), but ``write()`` hands the frame to a callback instead -of a NeoPixel strip. -""" - - -class PixelBuffer: - """NeoPixel-compatible buffer of RGB tuples.""" - - def __init__(self, num_leds, on_write=None): - self.n = int(num_leds) - self._px = [(0, 0, 0)] * self.n - self.on_write = on_write - - def __len__(self): - return self.n - - def __setitem__(self, i, color): - self._px[i] = (int(color[0]) & 0xFF, int(color[1]) & 0xFF, int(color[2]) & 0xFF) - - def __getitem__(self, i): - return self._px[i] - - def fill(self, color): - c = (int(color[0]) & 0xFF, int(color[1]) & 0xFF, int(color[2]) & 0xFF) - self._px = [c] * self.n - - def to_bytes(self): - out = bytearray(self.n * 3) - for i, (r, g, b) in enumerate(self._px): - j = i * 3 - out[j] = r - out[j + 1] = g - out[j + 2] = b - return bytes(out) - - def write(self): - if self.on_write is not None: - self.on_write(self.to_bytes()) - - -class FrameDriver: - def __init__(self, num_leds, on_write=None): - self.num_leds = int(num_leds) - self.n = PixelBuffer(self.num_leds, on_write) - self.step = 0 - # Global brightness is applied per output at send time, not here. - self.b = 255 - - def apply_brightness(self, color, brightness_override=None): - local = brightness_override if brightness_override is not None else 255 - effective_brightness = int(local * self.b / 255) - return tuple(int(c * effective_brightness / 255) for c in color) - - def fill(self, color=None): - self.n.fill(color if color is not None else (0, 0, 0)) - self.n.write() - - def off(self, preset=None): - self.fill((0, 0, 0)) - - def on(self, preset): - colors = preset.c - color = colors[0] if colors else (255, 255, 255) - self.fill(self.apply_brightness(color, preset.b)) diff --git a/src/engine/mpcompat.py b/src/engine/mpcompat.py deleted file mode 100644 index 0131838..0000000 --- a/src/engine/mpcompat.py +++ /dev/null @@ -1,86 +0,0 @@ -"""MicroPython compatibility for running led-driver patterns under CPython. - -Installs a ``utime`` module whose clock is chosen per thread: - -* ``RealClock`` — monotonic wall clock, ``sleep_ms`` really sleeps (render threads). -* ``VirtualClock`` — manual time; ``sleep_ms`` just advances it (tests, offline render). - -Patterns only use ``ticks_ms``/``ticks_diff``/``ticks_add``/``sleep_ms``; tick -values never wrap here, so the diff/add helpers are plain arithmetic. -""" - -import sys -import threading -import time -import types - - -class RealClock: - def __init__(self): - self._t0 = time.monotonic() - - def ticks_ms(self): - return int((time.monotonic() - self._t0) * 1000) - - def ticks_us(self): - return int((time.monotonic() - self._t0) * 1000000) - - def sleep_ms(self, ms): - if ms > 0: - time.sleep(ms / 1000.0) - - -class VirtualClock: - def __init__(self, start_ms=0): - self.now_us = int(start_ms) * 1000 - - def ticks_ms(self): - return self.now_us // 1000 - - def ticks_us(self): - return self.now_us - - def advance_ms(self, ms): - self.now_us += int(ms * 1000) - - def sleep_ms(self, ms): - if ms > 0: - self.advance_ms(ms) - - -_local = threading.local() -_default_clock = RealClock() - - -def current_clock(): - return getattr(_local, "clock", None) or _default_clock - - -def set_thread_clock(clock): - """Use ``clock`` for ``utime`` calls made on the current thread (None = real).""" - _local.clock = clock - - -def _build_utime(): - mod = types.ModuleType("utime") - mod.ticks_ms = lambda: current_clock().ticks_ms() - mod.ticks_us = lambda: current_clock().ticks_us() - mod.ticks_cpu = mod.ticks_us - mod.ticks_diff = lambda a, b: a - b - mod.ticks_add = lambda a, b: a + b - mod.sleep_ms = lambda ms: current_clock().sleep_ms(ms) - mod.sleep_us = lambda us: current_clock().sleep_ms(us / 1000.0) - mod.sleep = lambda s: current_clock().sleep_ms(s * 1000.0) - mod.time = time.time - mod.__led_controller_shim__ = True - return mod - - -def install(): - """Register the shim as ``utime`` (idempotent; never replaces a real utime).""" - existing = sys.modules.get("utime") - if existing is not None: - return existing - mod = _build_utime() - sys.modules["utime"] = mod - return mod diff --git a/src/engine/outputs/__init__.py b/src/engine/outputs/__init__.py deleted file mode 100644 index 7df3f1a..0000000 --- a/src/engine/outputs/__init__.py +++ /dev/null @@ -1,72 +0,0 @@ -"""Engine output drivers and the factory that builds them from config.""" - -from urllib.parse import parse_qs, urlparse - -from engine.outputs.artnet import ArtNetOutput -from engine.outputs.base import FrameOutput, PresetOutput -from engine.outputs.ddp import DdpOutput -from engine.outputs.dmx_serial import DmxSerialOutput -from engine.outputs.sacn import SacnOutput - -FRAME_PROTOCOLS = { - "ddp": DdpOutput, - "artnet": ArtNetOutput, - "sacn": SacnOutput, - "dmx_serial": DmxSerialOutput, -} - -_URL_ALIASES = {"e131": "sacn", "dmx": "dmx_serial", "art-net": "artnet"} -_QUERY_KEYS = { - "pixels": "pixel_count", - "order": "color_order", - "offset": "pixel_offset", - "mode": "dmx_mode", -} - - -def open_output(cfg): - """Build a FrameOutput from an output record (``protocol`` selects the driver).""" - protocol = str((cfg or {}).get("protocol") or "").lower() - protocol = _URL_ALIASES.get(protocol, protocol) - cls = FRAME_PROTOCOLS.get(protocol) - if cls is None: - raise ValueError(f"unknown output protocol: {protocol!r}") - return cls(cfg) - - -def parse_output_url(url): - """``ddp://10.0.0.5:4048?pixels=300&order=grb`` → output config dict. - - ``dmx_serial:///dev/ttyUSB0?mode=open_dmx&channel=1`` for serial DMX. - """ - # urlparse rejects "_" in schemes (dmx_serial://), so split the scheme off first. - scheme, sep, rest = str(url).partition("://") - if not sep: - raise ValueError(f"output URL needs a scheme, e.g. ddp://host: {url!r}") - scheme = scheme.strip().lower() - protocol = _URL_ALIASES.get(scheme, scheme) - parsed = urlparse("udp://" + rest) - cfg = {"protocol": protocol, "name": url} - if protocol == "dmx_serial": - cfg["serial_port"] = parsed.path or parsed.netloc - else: - if parsed.hostname: - cfg["host"] = parsed.hostname - if parsed.port: - cfg["port"] = parsed.port - for key, values in parse_qs(parsed.query).items(): - cfg[_QUERY_KEYS.get(key, key)] = values[-1] - return cfg - - -__all__ = [ - "FrameOutput", - "PresetOutput", - "DdpOutput", - "ArtNetOutput", - "SacnOutput", - "DmxSerialOutput", - "FRAME_PROTOCOLS", - "open_output", - "parse_output_url", -] diff --git a/src/engine/outputs/artnet.py b/src/engine/outputs/artnet.py deleted file mode 100644 index 2401ed6..0000000 --- a/src/engine/outputs/artnet.py +++ /dev/null @@ -1,78 +0,0 @@ -"""Art-Net (ArtDMX) output — UDP 6454. - -ArtDMX packet: - 0 "Art-Net\\0" - 8 OpCode 0x5000 (little-endian) - 10 ProtVer 14 (big-endian) - 12 Sequence 1..255 (0 disables re-ordering) - 13 Physical 0 - 14 Port-Address: SubUni (low byte), Net (high 7 bits) - 16 Length (big-endian, even, 2..512) - 18 DMX data - -170 RGB pixels per universe; consecutive universes from ``universe``. -Optional ArtSync (OpCode 0x5200) after each frame when ``sync`` is set. -""" - -import struct - -from engine.outputs.base import UdpFrameOutput, _bool, _int, split_universes - -ARTNET_PORT = 6454 -ARTNET_ID = b"Art-Net\x00" -OP_DMX = 0x5000 -OP_SYNC = 0x5200 -PROT_VER = 14 - - -def build_artdmx(universe, data, sequence=0, physical=0): - data = bytes(data[:512]) - if len(data) % 2: - data += b"\x00" - if len(data) < 2: - data = data + bytes(2 - len(data)) - universe &= 0x7FFF - return ( - ARTNET_ID - + struct.pack("H", 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", 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) diff --git a/src/engine/outputs/base.py b/src/engine/outputs/base.py deleted file mode 100644 index 9be87be..0000000 --- a/src/engine/outputs/base.py +++ /dev/null @@ -1,254 +0,0 @@ -"""Common output-driver interface and helpers. - -Two kinds of output: - -* ``FrameOutput`` — the Pi renders pixels and streams raw RGB frames - (DDP, Art-Net, sACN, USB-DMX). -* ``PresetOutput`` — the device renders itself; the engine only tells it which - preset to run (our ESP32 led-drivers over Wi-Fi / ESP-NOW). -""" - -import asyncio -import functools -import socket - -COLOR_ORDERS = { - "rgb": (0, 1, 2), - "rbg": (0, 2, 1), - "grb": (1, 0, 2), - "gbr": (1, 2, 0), - "brg": (2, 0, 1), - "bgr": (2, 1, 0), -} - -DEFAULT_FPS = 40 - - -def _int(value, default, lo=None, hi=None): - try: - v = int(value) - except (TypeError, ValueError): - v = default - if lo is not None: - v = max(lo, v) - if hi is not None: - v = min(hi, v) - return v - - -def _bool(value, default=False): - if isinstance(value, bool): - return value - if isinstance(value, (int, float)): - return bool(value) - if isinstance(value, str): - s = value.strip().lower() - if s in ("1", "true", "yes", "on"): - return True - if s in ("0", "false", "no", "off"): - return False - return default - - -class OutputStats: - def __init__(self): - self.frames = 0 - self.packets = 0 - self.bytes = 0 - self.errors = 0 - self.last_error = None - - def error(self, exc): - self.errors += 1 - self.last_error = repr(exc) - - def to_dict(self): - return { - "frames": self.frames, - "packets": self.packets, - "bytes": self.bytes, - "errors": self.errors, - "last_error": self.last_error, - } - - -class FrameOutput: - """Base class for pixel-streaming outputs.""" - - kind = "frame" - protocol = "" - # Resend the last frame this often when the pattern is static, so receivers - # don't time out (sACN drops a source after 2.5 s; DMX expects a steady stream). - keepalive_s = 1.0 - - def __init__(self, cfg): - cfg = dict(cfg or {}) - self.cfg = cfg - self.name = str(cfg.get("name") or cfg.get("id") or self.protocol) - self.pixel_count = _int(cfg.get("pixel_count"), 60, 1, 100000) - self.pixel_offset = _int(cfg.get("pixel_offset"), 0, 0) - order = str(cfg.get("color_order") or "rgb").lower() - self.color_order = order if order in COLOR_ORDERS else "rgb" - self.reverse = _bool(cfg.get("reverse"), False) - self.brightness = _int(cfg.get("brightness"), 255, 0, 255) - self.fps = _int(cfg.get("fps"), DEFAULT_FPS, 1, 120) - self.stats = OutputStats() - self._index_map = self._build_index_map() - - # -- frame preparation ------------------------------------------------- - - def _build_index_map(self): - """Byte index map: out[i] = src[map[i]] (colour order + reverse).""" - order = COLOR_ORDERS[self.color_order] - n = self.pixel_count - idx = [] - for p in range(n): - src_px = (n - 1 - p) if self.reverse else p - base = src_px * 3 - idx.extend((base + order[0], base + order[1], base + order[2])) - return idx - - @staticmethod - @functools.lru_cache(maxsize=64) - def brightness_table(level): - level = max(0, min(255, int(level))) - return bytes((v * level + 127) // 255 for v in range(256)) - - def prepare(self, rgb, global_brightness=255): - """Pad/truncate, apply brightness, colour order and reverse.""" - need = self.pixel_count * 3 - data = bytes(rgb[:need]) - if len(data) < need: - data = data + bytes(need - len(data)) - level = (self.brightness * max(0, min(255, int(global_brightness))) + 127) // 255 - if level < 255: - data = data.translate(self.brightness_table(level)) - if self.color_order == "rgb" and not self.reverse: - return data - m = self._index_map - return bytes(data[i] for i in m) - - # -- lifecycle ----------------------------------------------------------- - - async def open(self): - pass - - async def send(self, rgb, global_brightness=255): - """Send one frame of logical RGB (pixel_count*3 bytes).""" - try: - payload = self.prepare(rgb, global_brightness) - await self._send_prepared(payload) - self.stats.frames += 1 - except Exception as e: - self.stats.error(e) - - async def _send_prepared(self, payload): - raise NotImplementedError - - async def blackout(self): - await self.send(bytes(self.pixel_count * 3)) - - async def close(self): - try: - await self.blackout() - except Exception: - pass - - def status(self): - return { - "name": self.name, - "protocol": self.protocol, - "kind": self.kind, - "pixel_count": self.pixel_count, - **self.stats.to_dict(), - } - - -class _DatagramSink(asyncio.DatagramProtocol): - def __init__(self, owner): - self.owner = owner - - def error_received(self, exc): - self.owner.stats.error(exc) - - -class UdpFrameOutput(FrameOutput): - """FrameOutput that sends UDP datagrams to one host:port.""" - - default_port = 0 - - def __init__(self, cfg): - super().__init__(cfg) - self.host = str(self.cfg.get("host") or "").strip() - self.port = _int(self.cfg.get("port"), self.default_port, 1, 65535) - self.broadcast = _bool(self.cfg.get("broadcast"), False) - self._transport = None - - def destination(self): - return (self.host, self.port) - - def _make_socket(self): - sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - sock.setblocking(False) - if self.broadcast or self.host.endswith(".255"): - sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) - return sock - - async def open(self): - if self._transport is not None: - return - loop = asyncio.get_running_loop() - self._transport, _ = await loop.create_datagram_endpoint( - lambda: _DatagramSink(self), sock=self._make_socket() - ) - - def sendto(self, packet, addr=None): - if self._transport is None: - raise RuntimeError("output not open") - self._transport.sendto(packet, addr or self.destination()) - self.stats.packets += 1 - self.stats.bytes += len(packet) - - async def send(self, rgb, global_brightness=255): - if self._transport is None: - try: - await self.open() - except Exception as e: - self.stats.error(e) - return - await super().send(rgb, global_brightness) - - async def close(self): - await super().close() - if self._transport is not None: - self._transport.close() - self._transport = None - - -class PresetOutput: - """Base class for outputs that render presets on the device itself.""" - - kind = "preset" - protocol = "" - - def __init__(self, cfg=None): - self.cfg = dict(cfg or {}) - self.name = str(self.cfg.get("name") or self.protocol) - self.stats = OutputStats() - - async def open(self): - pass - - async def apply(self, preset_id, preset_payload): - raise NotImplementedError - - async def close(self): - pass - - def status(self): - return {"name": self.name, "protocol": self.protocol, "kind": self.kind, **self.stats.to_dict()} - - -def split_universes(data, channels_per_universe=510): - """Split RGB bytes into DMX-universe sized chunks (170 RGB px = 510 ch).""" - return [data[i:i + channels_per_universe] for i in range(0, len(data), channels_per_universe)] or [b""] diff --git a/src/engine/outputs/ddp.py b/src/engine/outputs/ddp.py deleted file mode 100644 index c60ddff..0000000 --- a/src/engine/outputs/ddp.py +++ /dev/null @@ -1,61 +0,0 @@ -"""DDP (Distributed Display Protocol) output — UDP 4048. - -Header (10 bytes, big-endian): - 0 flags 0x40 = version 1, | 0x01 = PUSH (last packet of a frame) - 1 sequence 1..15 (0 = sequence numbers unused) - 2 data type 0x0B = RGB, 8 bits per channel - 3 dest id 0x01 = default output device - 4 offset uint32 byte offset into the frame - 8 length uint16 payload length -""" - -import struct - -from engine.outputs.base import UdpFrameOutput, _int - -DDP_PORT = 4048 -DDP_FLAG_VER1 = 0x40 -DDP_FLAG_PUSH = 0x01 -DDP_TYPE_RGB8 = 0x0B -DDP_ID_DISPLAY = 0x01 -DDP_MAX_DATA = 1440 # 480 RGB pixels; fits a 1500-byte MTU - - -def build_ddp_packets(data, sequence, max_data=DDP_MAX_DATA, dest_id=DDP_ID_DISPLAY): - """Split one frame into DDP packets; PUSH set on the last.""" - packets = [] - total = len(data) - offset = 0 - while True: - chunk = data[offset:offset + max_data] - last = offset + len(chunk) >= total - flags = DDP_FLAG_VER1 | (DDP_FLAG_PUSH if last else 0) - header = struct.pack( - ">BBBBIH", flags, sequence & 0x0F, DDP_TYPE_RGB8, dest_id, offset, len(chunk) - ) - packets.append(header + bytes(chunk)) - offset += len(chunk) - if last: - break - return packets - - -class DdpOutput(UdpFrameOutput): - protocol = "ddp" - default_port = DDP_PORT - - def __init__(self, cfg): - super().__init__(cfg) - self.dest_id = _int(self.cfg.get("dest_id"), DDP_ID_DISPLAY, 0, 255) - self._sequence = 0 - - def next_sequence(self): - self._sequence = (self._sequence % 15) + 1 - return self._sequence - - def packets_for(self, payload): - return build_ddp_packets(payload, self.next_sequence(), dest_id=self.dest_id) - - async def _send_prepared(self, payload): - for packet in self.packets_for(payload): - self.sendto(packet) diff --git a/src/engine/outputs/dmx_serial.py b/src/engine/outputs/dmx_serial.py deleted file mode 100644 index 88431f1..0000000 --- a/src/engine/outputs/dmx_serial.py +++ /dev/null @@ -1,97 +0,0 @@ -"""USB-DMX output via pyserial (one universe, 512 channels). - -Modes: - enttec_pro Enttec DMX USB Pro: 0x7E, label 6, len LE, start code + data, 0xE7 - open_dmx FTDI "Open DMX": 250000 baud 8N2, break, MAB, start code + 512 slots - -Pixels start at DMX channel ``channel`` (1-based). Max 170 RGB pixels. -""" - -import asyncio -import struct -import time - -from engine.outputs.base import FrameOutput, _int - -ENTTEC_SOM = 0x7E -ENTTEC_EOM = 0xE7 -ENTTEC_LABEL_SEND_DMX = 6 -DMX_CHANNELS = 512 - - -def dmx_universe(payload, channel=1): - """512-slot universe with ``payload`` starting at 1-based ``channel``.""" - start = max(1, int(channel)) - 1 - universe = bytearray(DMX_CHANNELS) - data = bytes(payload[: max(0, DMX_CHANNELS - start)]) - universe[start:start + len(data)] = data - return bytes(universe) - - -def build_enttec_pro(universe): - body = b"\x00" + bytes(universe) # start code 0 - return bytes((ENTTEC_SOM, ENTTEC_LABEL_SEND_DMX)) + struct.pack("= 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 diff --git a/src/engine/outputs/driver.py b/src/engine/outputs/driver.py deleted file mode 100644 index 6995c63..0000000 --- a/src/engine/outputs/driver.py +++ /dev/null @@ -1,75 +0,0 @@ -"""Preset output for our own ESP32 led-drivers (Wi-Fi and ESP-NOW). - -The firmware renders patterns itself, so the engine only sends the preset -definition followed by a ``select`` for the zone's device names — the same -two-message sequence the UI posts to ``/presets/push`` today. -""" - -import json - -from engine.outputs.base import PresetOutput -from models.device import Device -from models.transport import get_current_sender -from util.driver_delivery import deliver_json_messages - - -def resolve_device_macs(names, devices=None): - """Zone device names → MACs, one distinct device per repeated name (as zones.js).""" - devices = devices if devices is not None else Device() - used = set() - rows = [] - for raw in names or []: - name = str(raw or "").strip() - if not name: - continue - for mac, doc in devices.items(): - if mac in used or not isinstance(doc, dict): - continue - if str(doc.get("name") or "").strip() == name: - used.add(mac) - rows.append((name, mac)) - break - return rows - - -class DriverOutput(PresetOutput): - protocol = "driver" - - def __init__(self, names, cfg=None, sender_getter=None, devices=None, save=False, delay_s=0.05): - super().__init__(cfg) - self.names = [str(n).strip() for n in (names or []) if str(n or "").strip()] - self.name = self.cfg.get("name") or ",".join(self.names) or "driver" - self._sender_getter = sender_getter or get_current_sender - self._devices = devices - self.save = bool(save) - self.delay_s = delay_s - - def messages_for(self, preset_id, preset_payload): - pid = str(preset_id) - preset_msg = {"v": "1", "presets": {pid: preset_payload}} - if self.save: - preset_msg["save"] = True - messages = [json.dumps(preset_msg)] - names = list(dict.fromkeys(self.names)) - if names: - messages.append(json.dumps({"v": "1", "select": {n: [pid] for n in names}})) - return messages - - async def apply(self, preset_id, preset_payload): - sender = self._sender_getter() - if sender is None: - self.stats.error(RuntimeError("transport not configured")) - return 0 - devices = self._devices if self._devices is not None else Device() - macs = [mac for _name, mac in resolve_device_macs(self.names, devices)] - try: - delivered, _ = await deliver_json_messages( - sender, self.messages_for(preset_id, preset_payload), macs or None, devices, - delay_s=self.delay_s, - ) - self.stats.frames += 1 - self.stats.packets += delivered - return delivered - except Exception as e: - self.stats.error(e) - return 0 diff --git a/src/engine/outputs/sacn.py b/src/engine/outputs/sacn.py deleted file mode 100644 index 37eb983..0000000 --- a/src/engine/outputs/sacn.py +++ /dev/null @@ -1,92 +0,0 @@ -"""sACN / E1.31 output — UDP 5568, multicast 239.255.. 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) diff --git a/src/engine/pattern_loader.py b/src/engine/pattern_loader.py deleted file mode 100644 index a601939..0000000 --- a/src/engine/pattern_loader.py +++ /dev/null @@ -1,116 +0,0 @@ -"""Load the led-driver pattern modules (and its Preset class) for Pi-side rendering. - -Mirrors ``Presets._load_dynamic_patterns`` in ``led-driver/src/presets.py``: -every ``*.py`` in the patterns dir except ``__init__.py``/``main.py``, using -the first class in the module that has ``run()``. -""" - -import importlib.util -import os -import threading - -from engine import mpcompat -from util.driver_patterns import driver_patterns_dir - -_MODULE_PREFIX = "led_driver_patterns." - - -def _load_module(name, path): - spec = importlib.util.spec_from_file_location(name, path) - module = importlib.util.module_from_spec(spec) - spec.loader.exec_module(module) - return module - - -class _FallbackPreset: - """Used only when led-driver/src/preset.py is not deployed next to the patterns.""" - - _aliases = {"pattern": "p", "colors": "c", "delay": "d", "brightness": "b", "auto": "a"} - - def __init__(self, data): - self.p, self.d, self.b, self.c, self.a = "off", 100, 127, [(255, 255, 255)], True - self.n1 = self.n2 = self.n3 = self.n4 = self.n5 = self.n6 = 0 - self.edit(data) - - def edit(self, data=None): - for key, value in (data or {}).items(): - key = self._aliases.get(key, key) - if key in ("d", "b", "n1", "n2", "n3", "n4", "n5", "n6"): - try: - value = max(0, int(value)) - except (TypeError, ValueError): - continue - if key == "b": - value = min(255, value) - elif key == "a": - value = bool(value) - elif key not in ("p", "c"): - continue - setattr(self, key, value) - return True - - -class PatternLibrary: - def __init__(self, patterns_dir=None): - self.patterns_dir = patterns_dir or driver_patterns_dir() - self._lock = threading.Lock() - self.classes = {} - self.errors = {} - self.preset_class = _FallbackPreset - self.load() - - def load(self): - mpcompat.install() - classes, errors = {}, {} - try: - files = sorted(os.listdir(self.patterns_dir)) - except OSError as e: - files = [] - errors["*"] = repr(e) - for filename in files: - if not filename.endswith(".py") or filename in ("__init__.py", "main.py"): - continue - base = filename[:-3] - try: - module = _load_module(_MODULE_PREFIX + base, os.path.join(self.patterns_dir, filename)) - except Exception as e: - errors[base] = repr(e) - continue - for attr_name in dir(module): - attr = getattr(module, attr_name) - if isinstance(attr, type) and hasattr(attr, "run"): - classes[base] = attr - break - preset_cls = _FallbackPreset - preset_path = os.path.join(os.path.dirname(self.patterns_dir), "preset.py") - if os.path.isfile(preset_path): - try: - preset_cls = _load_module("led_driver_preset", preset_path).Preset - except Exception as e: - errors["preset.py"] = repr(e) - with self._lock: - self.classes = classes - self.errors = errors - self.preset_class = preset_cls - return self - - reload = load - - def ids(self): - return sorted(set(self.classes) | {"on", "off"}) - - def get(self, pattern_id): - return self.classes.get(pattern_id) - - def make_preset(self, payload): - return self.preset_class(dict(payload or {})) - - -_library = None - - -def get_library(): - global _library - if _library is None: - _library = PatternLibrary() - return _library diff --git a/src/engine/player.py b/src/engine/player.py deleted file mode 100644 index 679c254..0000000 --- a/src/engine/player.py +++ /dev/null @@ -1,148 +0,0 @@ -"""Per-zone player: render on a thread, stream frames to pixel outputs. - -Modelled on portal's ``PatternPlayer``: the asyncio side only ships frames. -The render thread runs the driver pattern exactly like the ESP32 main loop, -and each ``n.write()`` wakes the sender, which pushes the newest frame to -every output (coalescing writes faster than the outputs' fps). -""" - -import asyncio -import time - -from engine.outputs import open_output -from engine.renderer import Renderer, RenderThread - -SEND_TIMEOUT_S = 0.05 - - -def _default_driver_output(names): - from engine.outputs.driver import DriverOutput # pulls in the Wi-Fi/serial stack - - return DriverOutput(names) - - -class ZonePlayer: - def __init__(self, targets, library, brightness_getter=None, output_factory=None, - driver_factory=None): - self.targets = targets - self.zone_id = targets.zone_id - self.library = library - self._brightness = brightness_getter or (lambda: 255) - make_output = output_factory or open_output - self.frame_outputs = [make_output(cfg) for cfg in targets.frame_cfgs] - make_driver = driver_factory or _default_driver_output - self.driver_output = make_driver(targets.driver_names) if targets.driver_names else None - self.preset_id = None - self.started_at = None - self._loop = None - self._latest = None - self._frame_event = None - self._sender_task = None - self._render = None - self.renderer = None - - @property - def fps(self): - return min((o.fps for o in self.frame_outputs), default=0) - - async def start(self): - self._loop = asyncio.get_running_loop() - if not self.frame_outputs: - return - for out in self.frame_outputs: - try: - await out.open() - except Exception as e: - out.stats.error(e) - self._frame_event = asyncio.Event() - self.renderer = Renderer(self.library, self.targets.frame_length, on_frame=self._on_frame_thread) - self._render = RenderThread(self.renderer, name=f"engine-zone-{self.zone_id}").start() - self._sender_task = asyncio.create_task(self._send_loop(), name=f"engine-send-{self.zone_id}") - - def _on_frame_thread(self, frame): - loop = self._loop - if loop is None or loop.is_closed(): - return - try: - loop.call_soon_threadsafe(self._frame_ready, frame) - except RuntimeError: - pass - - def _frame_ready(self, frame): - self._latest = frame - if self._frame_event is not None: - self._frame_event.set() - - async def send_frame(self, frame): - level = self._brightness() - tasks = [] - for out in self.frame_outputs: - start = out.pixel_offset * 3 - tasks.append(asyncio.ensure_future(out.send(frame[start:start + out.pixel_count * 3], level))) - if not tasks: - return - _done, pending = await asyncio.wait(tasks, timeout=SEND_TIMEOUT_S) - for t in pending: - t.cancel() - - @property - def keepalive_s(self): - return min((o.keepalive_s for o in self.frame_outputs), default=1.0) - - async def _send_loop(self): - interval = 1.0 / max(1, self.fps) - keepalive = self.keepalive_s - while True: - try: - await asyncio.wait_for(self._frame_event.wait(), timeout=keepalive) - except asyncio.TimeoutError: - pass # no new frame: resend the last one - self._frame_event.clear() - started = time.monotonic() - frame = self._latest - if frame is not None: - await self.send_frame(frame) - rest = interval - (time.monotonic() - started) - if rest > 0: - await asyncio.sleep(rest) - - async def apply(self, preset_id, payload, drivers=True): - self.preset_id = str(preset_id) - self.started_at = time.time() - if self._render is not None: - self._render.apply(preset_id, payload) - if drivers and self.driver_output is not None: - await self.driver_output.apply(preset_id, payload) - - async def stop(self): - if self._render is not None: - self._render.stop() - self._render = None - if self._sender_task is not None: - self._sender_task.cancel() - try: - await self._sender_task - except (asyncio.CancelledError, Exception): - pass - self._sender_task = None - for out in self.frame_outputs: - try: - await out.close() - except Exception: - pass - if self.driver_output is not None: - await self.driver_output.close() - - def status(self): - r = self.renderer - return { - "zone_id": self.zone_id, - "preset_id": self.preset_id, - "pattern": r.pattern_id if r else None, - "error": r.error if r else None, - "started_at": self.started_at, - "frame_length": self.targets.frame_length, - "fps": self.fps, - "outputs": [o.status() for o in self.frame_outputs] - + ([self.driver_output.status()] if self.driver_output else []), - } diff --git a/src/engine/presets.py b/src/engine/presets.py deleted file mode 100644 index 46c3042..0000000 --- a/src/engine/presets.py +++ /dev/null @@ -1,61 +0,0 @@ -"""Resolve stored presets into driver payloads (short keys, palette refs applied).""" - -from models.pallet import Palette -from models.preset import Preset as PresetModel -from models.profile import Profile -from util.espnow_message import build_preset_dict - - -def resolve_palette_colors(colors, palette_refs, palette): - """Same rule as presets.js ``resolveColorsWithPaletteRefs``.""" - base = list(colors) if isinstance(colors, list) else [] - refs = palette_refs if isinstance(palette_refs, list) else [] - pal = palette if isinstance(palette, list) else [] - out = [] - for idx, color in enumerate(base): - ref = refs[idx] if idx < len(refs) else None - try: - ref = int(ref) - except (TypeError, ValueError): - ref = None - if ref is not None and 0 <= ref < len(pal) and pal[ref]: - out.append(pal[ref]) - else: - out.append(color) - return out - - -def profile_palette(profile_id): - if profile_id is None: - return [] - profile = Profile().read(profile_id) or {} - palette_id = profile.get("palette_id") - if palette_id is None: - return [] - return Palette().read(palette_id) - - -def preset_payload(preset_id, preset_data=None): - """Driver payload (``p``, ``c``, ``d``, ``b``, ``a``, ``n1``..) for a stored preset.""" - data = preset_data if preset_data is not None else PresetModel().read(preset_id) - if not data: - return None - data = dict(data) - refs = data.get("palette_refs") - if refs: - data["colors"] = resolve_palette_colors( - data.get("colors") or [], refs, profile_palette(data.get("profile_id")) - ) - return build_preset_dict(data) - - -def hex_to_rgb(color): - if isinstance(color, (list, tuple)) and len(color) >= 3: - return tuple(max(0, min(255, int(c))) for c in color[:3]) - s = str(color or "").strip().lstrip("#") - if len(s) == 3: - s = "".join(ch * 2 for ch in s) - try: - return (int(s[0:2], 16), int(s[2:4], 16), int(s[4:6], 16)) - except (ValueError, IndexError): - return (255, 255, 255) diff --git a/src/engine/renderer.py b/src/engine/renderer.py deleted file mode 100644 index 1186e5b..0000000 --- a/src/engine/renderer.py +++ /dev/null @@ -1,157 +0,0 @@ -"""Run one led-driver pattern generator and collect the frames it writes. - -``Renderer`` is synchronous and clock-agnostic (tests drive it with a -``VirtualClock``). ``RenderThread`` runs a Renderer on its own thread with the -real clock, the way the ESP32 main loop calls ``Presets.tick()``: patterns may -block in ``utime.sleep_ms`` between writes and every ``n.write()`` becomes a frame. -""" - -import threading -import time -import traceback -import types - -from engine import mpcompat -from engine.frame_driver import FrameDriver -from engine.presets import hex_to_rgb - -BUILTIN_PATTERNS = ("on", "off") - - -class Renderer: - def __init__(self, library, num_leds, on_frame=None): - self.library = library - self.on_frame = on_frame - self.driver = FrameDriver(num_leds, on_write=self._frame_written) - self.preset = None - self.preset_id = None - self.pattern_id = None - self.generator = None - self.last_frame = bytes(self.driver.num_leds * 3) - self.frame_count = 0 - self.error = None - - def _frame_written(self, frame): - self.last_frame = frame - self.frame_count += 1 - if self.on_frame is not None: - self.on_frame(frame) - - def set_preset(self, preset_id, payload): - """Select a preset, mirroring ``Presets.select`` (step reset rules included).""" - data = dict(payload or {}) - colors = data.get("c", data.get("colors")) - if isinstance(colors, list): - data["c"] = [hex_to_rgb(c) for c in colors] - data.pop("colors", None) - preset = self.library.make_preset(data) - pid = str(preset_id) - if preset.p == "off" or pid != self.preset_id: - self.driver.step = 0 - self.preset = preset - self.preset_id = pid - self.pattern_id = preset.p - self.error = None - self.generator = None - - if preset.p in BUILTIN_PATTERNS: - getattr(self.driver, preset.p)(preset) - return True - cls = self.library.get(preset.p) - if cls is None: - self.error = f"pattern not found: {preset.p}" - self.driver.off() - return False - try: - result = cls(self.driver).run(preset) - except Exception as e: - self.error = repr(e) - return False - if isinstance(result, types.GeneratorType): - self.generator = result - return True - - def tick(self): - """Advance the pattern by one generator step (one device tick).""" - gen = self.generator - if gen is None: - return False - try: - next(gen) - return True - except StopIteration: - self.generator = None - except Exception as e: - self.error = repr(e) - print(f"[engine] pattern {self.pattern_id!r} error: {e!r}") - self.generator = None - return False - - def render_virtual(self, preset_id, payload, ticks, tick_ms=1, clock=None): - """Offline render with a virtual clock; returns the list of frames written.""" - frames = [] - prev_cb = self.on_frame - self.on_frame = frames.append - clock = clock or mpcompat.VirtualClock() - mpcompat.set_thread_clock(clock) - try: - self.set_preset(preset_id, payload) - for _ in range(int(ticks)): - self.tick() - clock.advance_ms(tick_ms) - finally: - mpcompat.set_thread_clock(None) - self.on_frame = prev_cb - return frames - - -class RenderThread: - """Ticks a Renderer on a daemon thread; ``apply`` hot-swaps presets thread-safely.""" - - def __init__(self, renderer, tick_s=0.001, name="engine-render"): - self.renderer = renderer - self.tick_s = tick_s - self._pending = None - self._lock = threading.Lock() - self._wake = threading.Event() - self._stop = threading.Event() - self._thread = threading.Thread(target=self._run, name=name, daemon=True) - - def start(self): - self._thread.start() - return self - - def apply(self, preset_id, payload): - with self._lock: - self._pending = (preset_id, payload) - self._wake.set() - - def stop(self, timeout=1.0): - self._stop.set() - self._wake.set() - if self._thread.is_alive() and threading.current_thread() is not self._thread: - self._thread.join(timeout) - - def _take_pending(self): - with self._lock: - pending, self._pending = self._pending, None - return pending - - def _run(self): - mpcompat.set_thread_clock(mpcompat.RealClock()) - r = self.renderer - while not self._stop.is_set(): - pending = self._take_pending() - if pending is not None: - try: - r.set_preset(*pending) - except Exception: - traceback.print_exc() - if r.generator is None: - # Static frame (on/off/finished): sleep until the next preset. - self._wake.wait() - self._wake.clear() - continue - r.tick() - if self.tick_s: - time.sleep(self.tick_s) diff --git a/src/engine/sequence_runner.py b/src/engine/sequence_runner.py deleted file mode 100644 index ae673c0..0000000 --- a/src/engine/sequence_runner.py +++ /dev/null @@ -1,161 +0,0 @@ -"""Preset sequencer — timed chains of presets per zone (portal's SequenceRunner). - -Each running sequence is an asyncio task: ``engine.play(zone, step)``, -``notify()``, ``sleep(duration_s)``, next step; loop / repeat_count decide -when it ends. Cuts are hard. At most one sequence runs per zone. -""" - -import asyncio -import time - - -class SequenceRunner: - def __init__(self, engine, sequences_model=None, notify=None): - self.engine = engine - self._model = sequences_model - self.notify = notify - self._tasks = {} # zone_id -> (sequence_id, task) - self._state = {} # sequence_id -> status dict - - @property - def model(self): - if self._model is None: - from models.squence import Sequence - self._model = Sequence() - return self._model - - def zone_for(self, sequence_id): - for zone_id, (sid, _task) in self._tasks.items(): - if sid == str(sequence_id): - return zone_id - return None - - async def play(self, sequence_id): - from engine.core import EngineError - - sid = str(sequence_id) - seq = self.model.read(sid) - if not seq: - raise EngineError("Sequence not found", 404) - zone_id = seq.get("zone_id") - if zone_id in (None, ""): - raise EngineError("Sequence has no zone_id", 400) - if not seq.get("steps"): - raise EngineError("Sequence has no steps", 400) - zone_id = str(zone_id) - await self.stop_zone(zone_id) - current = self.zone_for(sid) - if current is not None: - await self.stop_zone(current) - self.model.update(sid, {"active": True}) - self._state[sid] = { - "sequence_id": sid, - "zone_id": zone_id, - "step_index": 0, - "pass": 0, - "preset_id": None, - "started_at": time.time(), - "next_at": None, - "running": True, - } - task = asyncio.create_task(self._run(sid, zone_id), name=f"sequence-{sid}") - self._tasks[zone_id] = (sid, task) - return self._state[sid] - - async def _run(self, sid, zone_id): - state = self._state[sid] - passes = 0 - loop = asyncio.get_running_loop() - # Steps are scheduled on absolute deadlines so send latency doesn't drift the timing. - deadline = loop.time() - try: - while True: - seq = self.model.read(sid) or {} - steps = seq.get("steps") or [] - if not steps: - break - for index, step in enumerate(steps): - duration = float(step.get("duration_s") or 5) - state.update(step_index=index, preset_id=str(step.get("preset_id")), - next_at=time.time() + duration) - try: - await self.engine.play(zone_id, step.get("preset_id"), source="sequence") - except Exception as e: - state["error"] = str(e) - print(f"[sequence {sid}] step {index} failed: {e}") - self._notify(state) - deadline += duration - await asyncio.sleep(max(0.0, deadline - loop.time())) - passes += 1 - state["pass"] = passes - if not seq.get("loop", True): - break - repeat = int(seq.get("repeat_count") or 0) - if repeat and passes >= repeat: - break - except asyncio.CancelledError: - raise - finally: - state.update(running=False, next_at=None) - entry = self._tasks.get(zone_id) - if entry is not None and entry[0] == sid and entry[1] is asyncio.current_task(): - self._tasks.pop(zone_id, None) - # Finished on its own (not cancelled): no longer active. - self.model.update(sid, {"active": False}) - self._notify(state) - - def _notify(self, state): - if self.notify is not None: - try: - self.notify(dict(state)) - except Exception: - pass - - async def _cancel(self, zone_id, persist): - entry = self._tasks.pop(str(zone_id), None) - if entry is None: - return None - sid, task = entry - task.cancel() - try: - await task - except (asyncio.CancelledError, Exception): - pass - if persist: - self.model.update(sid, {"active": False}) - state = self._state.get(sid) - if state is not None: - state.update(running=False, next_at=None) - return sid - - async def stop(self, sequence_id): - zone_id = self.zone_for(sequence_id) - if zone_id is None: - self.model.update(str(sequence_id), {"active": False}) - return False - await self._cancel(zone_id, persist=True) - return True - - async def stop_zone(self, zone_id): - return await self._cancel(zone_id, persist=True) - - async def stop_all(self, persist=False): - """Cancel every sequence; ``persist=False`` keeps ``active`` so they resume on restart.""" - for zone_id in list(self._tasks): - await self._cancel(zone_id, persist=persist) - - async def resume_active(self): - started = [] - for sid in list(self.model.list()): - seq = self.model.read(sid) or {} - if seq.get("active"): - try: - await self.play(sid) - started.append(sid) - except Exception as e: - print(f"[sequence {sid}] resume failed: {e}") - self.model.update(sid, {"active": False}) - return started - - def status(self): - return {sid: dict(s) for sid, s in self._state.items()} diff --git a/src/engine/zone_targets.py b/src/engine/zone_targets.py deleted file mode 100644 index 89af2d6..0000000 --- a/src/engine/zone_targets.py +++ /dev/null @@ -1,56 +0,0 @@ -"""Resolve a zone's ``names`` into pixel outputs and ESP32 driver names. - -A name that matches an enabled record in ``db/output.json`` becomes a frame -output (the Pi renders for it); every other name is treated as an led-driver -device name and gets presets + ``select`` as today. -""" - -import json - -from models.output import Output -from models.zone import Zone - - -class ZoneTargets: - def __init__(self, zone_id, frame_cfgs, driver_names): - self.zone_id = str(zone_id) - self.frame_cfgs = frame_cfgs - self.driver_names = driver_names - - @property - def frame_length(self): - """Pixels the renderer must produce: outputs at offset 0 mirror the frame start.""" - return max( - (int(c.get("pixel_offset") or 0) + int(c.get("pixel_count") or 0) for c in self.frame_cfgs), - default=0, - ) - - def signature(self): - return json.dumps( - {"frames": self.frame_cfgs, "drivers": self.driver_names}, sort_keys=True - ) - - -def zone_names(zone): - names = zone.get("names") if isinstance(zone, dict) else None - return [str(n).strip() for n in (names or []) if str(n or "").strip()] - - -def resolve_zone(zone_id, zones=None, outputs=None): - zones = zones if zones is not None else Zone() - outputs = outputs if outputs is not None else Output() - zone = zones.read(zone_id) - if not zone: - return None - frame_cfgs, driver_names, seen = [], [], set() - for name in zone_names(zone): - matches = [o for o in outputs.by_name(name) if o.get("enabled", True)] - if matches: - for cfg in matches: - oid = str(cfg.get("id")) - if oid not in seen: - seen.add(oid) - frame_cfgs.append(dict(cfg)) - else: - driver_names.append(name) - return ZoneTargets(zone_id, frame_cfgs, driver_names) diff --git a/src/main.py b/src/main.py deleted file mode 100644 index ed29abc..0000000 --- a/src/main.py +++ /dev/null @@ -1,431 +0,0 @@ -import asyncio -import errno -import json -import os -import signal -import socket -import threading -import traceback -from microdot import Microdot, send_file -from microdot.websocket import with_websocket -from microdot.session import Session -from settings import Settings - -import controllers.preset as preset -import controllers.profile as profile -import controllers.group as group -import controllers.sequence as sequence -import controllers.zone as zone -import controllers.palette as palette -import controllers.scene as scene -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 -from util.device_status_broadcaster import ( - broadcast_device_tcp_snapshot_to, - broadcast_device_tcp_status, - register_device_status_ws, - unregister_device_status_ws, -) - -_tcp_device_lock = threading.Lock() - -DISCOVERY_UDP_PORT = 8766 - - -def _register_udp_device_sync( - device_name: str, peer_ip: str, mac, device_type=None -) -> None: - with _tcp_device_lock: - try: - d = Device() - did, persisted = d.upsert_wifi_tcp_client( - device_name, peer_ip, mac, device_type=device_type - ) - if did and persisted: - print( - f"UDP device registered: mac={did} name={device_name!r} ip={peer_ip!r}" - ) - except Exception as e: - print(f"UDP device registry failed: {e}") - traceback.print_exception(type(e), e, e.__traceback__) - - -async def _handle_udp_discovery(sock, udp_holder=None) -> None: - while True: - try: - data, addr = await asyncio.get_running_loop().sock_recvfrom(sock, 2048) - except asyncio.CancelledError: - raise - except OSError as e: - if udp_holder and udp_holder.get("closing"): - break - print(f"[UDP] recv failed: {e!r}") - continue - except Exception as e: - print(f"[UDP] recv failed: {e!r}") - continue - peer_ip = addr[0] if addr else "" - line = data.split(b"\n", 1)[0].strip() - if line: - try: - parsed = json.loads(line.decode("utf-8")) - if isinstance(parsed, dict): - dns = str(parsed.get("device_name") or "").strip() - mac = parsed.get("mac") or parsed.get("device_mac") or parsed.get( - "sta_mac" - ) - device_type = parsed.get("type") or parsed.get("device_type") - if dns and normalize_mac(mac): - _register_udp_device_sync(dns, peer_ip, mac, device_type) - if str(parsed.get("v") or "") == "1": - tcp_client_registry.ensure_driver_connection(peer_ip) - except (UnicodeError, ValueError, TypeError): - pass - try: - await asyncio.get_running_loop().sock_sendto(sock, data, addr) - except Exception as e: - print(f"[UDP] echo send failed: {e!r}") - - -def _prime_wifi_outbound_driver_connections() -> None: - """ - For each Wi‑Fi device in the registry with a usable IPv4, start (or keep) the - outbound WebSocket task. The client loop reconnects automatically if the link - drops. Presets are not pushed automatically; use Send Presets / profile apply. - """ - n = 0 - try: - dev = Device() - for mac_key, doc in list(dev.items()): - if not isinstance(doc, dict): - continue - if doc.get("transport") != "wifi": - continue - ip = _ipv4_address(str(doc.get("address") or "")) - if not ip: - continue - tcp_client_registry.ensure_driver_connection(ip) - n += 1 - except Exception as e: - print(f"[startup] Wi-Fi driver connection prime failed: {e!r}") - traceback.print_exception(type(e), e, e.__traceback__) - return - if n: - print(f"[startup] primed outbound WebSocket for {n} Wi-Fi driver(s)") - - -def _ipv4_address(addr: str) -> str | None: - """Return dotted IPv4 string or None (hostnames skipped for UDP nudge).""" - s = (addr or "").strip() - if not s: - return None - parts = s.split(".") - if len(parts) != 4: - return None - try: - nums = [int(p) for p in parts] - except ValueError: - return None - if not all(0 <= n <= 255 for n in nums): - return None - return s - - -async def _periodic_wifi_driver_hello_loop(settings, udp_holder) -> None: - """ - While a registered Wi-Fi driver has no outbound WebSocket, send a short JSON hello on - UDP discovery port so the device can announce itself and we can reconnect. - """ - try: - interval = float(settings.get("wifi_driver_hello_interval_s", 10.0)) - except (TypeError, ValueError): - interval = 10.0 - if interval <= 0: - return - - sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - sock.setblocking(False) - loop = asyncio.get_running_loop() - try: - while True: - await asyncio.sleep(interval) - if udp_holder.get("closing"): - break - try: - dev = Device() - except Exception as e: - print(f"[hello] device list failed: {e!r}") - continue - for _mac_key, doc in list(dev.items()): - if not isinstance(doc, dict): - continue - if doc.get("transport") != "wifi": - continue - ip = _ipv4_address(str(doc.get("address") or "")) - if not ip: - continue - if tcp_client_registry.tcp_client_connected(ip): - continue - name = (doc.get("name") or "").strip() - mac = normalize_mac(doc.get("id") or _mac_key) - if not name or not mac: - continue - line = ( - json.dumps( - {"m": "hello", "device_name": name, "mac": mac}, - separators=(",", ":"), - ) - + "\n" - ) - try: - await loop.sock_sendto( - sock, line.encode("utf-8"), (ip, DISCOVERY_UDP_PORT) - ) - except OSError as e: - print(f"[hello] UDP to {ip!r} failed: {e!r}") - finally: - try: - sock.close() - except OSError: - pass - - -async def _run_udp_discovery_server(udp_holder=None) -> None: - sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - sock.setblocking(False) - try: - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - except (AttributeError, OSError): - pass - try: - sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) - except (AttributeError, OSError): - pass - sock.bind(("0.0.0.0", DISCOVERY_UDP_PORT)) - if udp_holder is not None: - udp_holder["sock"] = sock - print(f"UDP discovery listening on 0.0.0.0:{DISCOVERY_UDP_PORT}") - try: - await _handle_udp_discovery(sock, udp_holder) - finally: - if udp_holder is not None: - udp_holder.pop("sock", None) - try: - sock.close() - except Exception: - pass - - -async def _send_bridge_wifi_channel(settings, sender): - """Tell the serial ESP32 bridge to set STA channel (settings wifi_channel); not forwarded as ESP-NOW.""" - try: - ch = int(settings.get("wifi_channel", 6)) - except (TypeError, ValueError): - ch = 6 - ch = max(1, min(11, ch)) - payload = json.dumps({"m": "bridge", "ch": ch}, separators=(",", ":")) - try: - await sender.send(payload, addr="ffffffffffff") - print(f"[startup] bridge Wi-Fi channel -> {ch}") - except Exception as e: - print(f"[startup] bridge channel message failed: {e}") - - -async def main(port=80): - settings = Settings() - print(settings) - print("Starting") - - # Initialize transport (serial to ESP32 bridge) - sender = get_sender(settings) - set_sender(sender) - - app = Microdot() - - # Initialize sessions with a secret key from settings - secret_key = settings.get('session_secret_key', 'led-controller-secret-key-change-in-production') - Session(app, secret_key=secret_key) - - # Mount model controllers as subroutes - # Verify controllers are Microdot instances before mounting - controllers_to_mount = [ - ('/presets', preset, 'preset'), - ('/profiles', profile, 'profile'), - ('/groups', group, 'group'), - ('/sequences', sequence, 'sequence'), - ('/zones', zone, 'zone'), - ('/palettes', palette, 'palette'), - ('/scenes', scene, 'scene'), - ('/outputs', output_controller, 'output'), - ] - - # Mount model controllers as subroutes - app.mount(preset.controller, '/presets') - app.mount(profile.controller, '/profiles') - app.mount(group.controller, '/groups') - app.mount(sequence.controller, '/sequences') - app.mount(zone.controller, '/zones') - app.mount(palette.controller, '/palettes') - app.mount(scene.controller, '/scenes') - app.mount(pattern.controller, '/patterns') - 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) - - # Serve index.html at root (cwd is src/ when run via pipenv run run) - @app.route('/') - def index(request): - """Serve the main web UI.""" - return send_file('templates/index.html') - - # Favicon: avoid 404 in browser console (no file needed) - @app.route('/favicon.ico') - def favicon(request): - return '', 204 - - # Static file route - @app.route("/static/") - def static_handler(request, path): - """Serve static files.""" - if '..' in path: - # Directory traversal is not allowed - return 'Not found', 404 - return send_file('static/' + path) - - @app.route('/ws') - @with_websocket - async def ws(request, ws): - await register_device_status_ws(ws) - await broadcast_device_tcp_snapshot_to(ws) - try: - while True: - data = await ws.receive() - print(data) - if data: - try: - parsed = json.loads(data) - print("WS received JSON:", parsed) - # Optional "to": 12-char hex MAC; rest is payload (sent with that address). - addr = parsed.pop("to", None) - payload = json.dumps(parsed) if parsed else data - await sender.send(payload, addr=addr) - except json.JSONDecodeError: - # Not JSON: send raw with default address - try: - await sender.send(data) - except Exception: - try: - await ws.send(json.dumps({"error": "Send failed"})) - except Exception: - pass - except Exception: - try: - await ws.send(json.dumps({"error": "Send failed"})) - except Exception: - pass - else: - break - finally: - await unregister_device_status_ws(ws) - - - - # Touch Device singleton early so db/device.json exists before first UDP hello. - Device() - 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() - - def _graceful_shutdown(*_args): - print("[server] shutting down...") - udp_holder["closing"] = True - u = udp_holder.get("sock") - if u is not None: - try: - u.close() - except OSError: - pass - tcp_client_registry.cancel_all_driver_tasks() - if getattr(app, "server", None) is not None: - app.shutdown() - - shutdown_handlers_registered = False - try: - try: - for sig in (signal.SIGINT, signal.SIGTERM): - loop.add_signal_handler(sig, _graceful_shutdown) - shutdown_handlers_registered = True - except (NotImplementedError, RuntimeError): - pass - - # Await HTTP + UDP discovery; bind failures (e.g. port 80 in use) surface here. - try: - await asyncio.gather( - app.start_server(host="0.0.0.0", port=port), - _run_udp_discovery_server(udp_holder), - _periodic_wifi_driver_hello_loop(settings, udp_holder), - ) - except OSError as e: - if e.errno == errno.EADDRINUSE: - print( - f"[server] bind failed (address already in use): {e!s}\n" - f"[server] HTTP is configured for port {port} (env PORT). " - f"Stop the other process or use a free port, e.g. PORT=8080 pipenv run run" - ) - 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: - srv.close() - await srv.wait_closed() - except Exception: - pass - try: - app.server = None - except Exception: - pass - if shutdown_handlers_registered: - for sig in (signal.SIGINT, signal.SIGTERM): - try: - loop.remove_signal_handler(sig) - except (NotImplementedError, OSError, ValueError): - pass - -if __name__ == "__main__": - import os - port = int(os.environ.get("PORT", 80)) - asyncio.run(main(port=port)) diff --git a/src/models/__init__.py b/src/models/__init__.py deleted file mode 100644 index f3d9f4b..0000000 --- a/src/models/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# Models package diff --git a/src/models/device.py b/src/models/device.py deleted file mode 100644 index 156d16e..0000000 --- a/src/models/device.py +++ /dev/null @@ -1,285 +0,0 @@ -""" -LED driver registry persisted in ``db/device.json``. - -Storage key and **id** field are the device **MAC**: 12 lowercase hex characters -(no colons). **name** is for ``select`` / zones (not unique). **address** is the -reachability hint: same as MAC for ESP-NOW, or IP/hostname for Wi-Fi. -""" - -from models.model import Model - -DEVICE_TYPES = frozenset({"led"}) -DEVICE_TRANSPORTS = frozenset({"wifi", "espnow"}) - - -def validate_device_type(value): - t = (value or "led").strip().lower() - if t not in DEVICE_TYPES: - raise ValueError(f"type must be one of: {', '.join(sorted(DEVICE_TYPES))}") - return t - - -def validate_device_transport(value): - tr = (value or "espnow").strip().lower() - if tr not in DEVICE_TRANSPORTS: - raise ValueError( - f"transport must be one of: {', '.join(sorted(DEVICE_TRANSPORTS))}" - ) - return tr - - -def normalize_mac(mac): - """Normalise to 12-char lowercase hex or None.""" - if mac is None: - return None - s = str(mac).strip().lower().replace(":", "").replace("-", "") - if len(s) == 12 and all(c in "0123456789abcdef" for c in s): - return s - return None - - -def derive_device_mac(mac=None, address=None, transport="espnow"): - """ - Resolve the device MAC used as storage id. - - Explicit ``mac`` wins. For ESP-NOW, ``address`` is the peer MAC. For Wi-Fi, - ``mac`` must be supplied (``address`` is typically an IP). - """ - m = normalize_mac(mac) - if m: - return m - tr = validate_device_transport(transport) - if tr == "espnow": - return normalize_mac(address) - return None - - -def normalize_address_for_transport(addr, transport): - """ESP-NOW → 12 hex or None; Wi-Fi → trimmed string or None.""" - tr = validate_device_transport(transport) - if tr == "espnow": - return normalize_mac(addr) - if addr is None: - return None - s = str(addr).strip() - return s if s else None - - -class Device(Model): - def __init__(self): - super().__init__() - - def load(self): - super().load() - changed = False - for sid, doc in list(self.items()): - if not isinstance(doc, dict): - continue - if self._migrate_record(str(sid), doc): - changed = True - if self._rekey_legacy_ids(): - changed = True - if changed: - self.save() - - def _migrate_record(self, storage_id, doc): - changed = False - if doc.get("type") not in DEVICE_TYPES: - doc["type"] = "led" - changed = True - if doc.get("transport") not in DEVICE_TRANSPORTS: - doc["transport"] = "espnow" - changed = True - raw_list = doc.get("addresses") - if isinstance(raw_list, list) and raw_list: - picked = None - for item in raw_list: - n = normalize_mac(item) - if n: - picked = n - break - if picked: - doc["address"] = picked - del doc["addresses"] - changed = True - elif "addresses" in doc: - del doc["addresses"] - changed = True - tr = doc["transport"] - norm = normalize_address_for_transport(doc.get("address"), tr) - if doc.get("address") != norm: - doc["address"] = norm - changed = True - mac_key = normalize_mac(storage_id) - if mac_key and mac_key == storage_id and str(doc.get("id") or "") != mac_key: - doc["id"] = mac_key - changed = True - elif str(doc.get("id") or "").strip() != storage_id: - doc["id"] = storage_id - changed = True - doc.pop("mac", None) - return changed - - def _rekey_legacy_ids(self): - """Move numeric-keyed rows to MAC keys when ESP-NOW MAC is known.""" - changed = False - moves = [] - for sid in list(self.keys()): - doc = self.get(sid) - if not isinstance(doc, dict): - continue - if normalize_mac(sid) == sid: - continue - if not str(sid).isdigit(): - continue - tr = doc.get("transport", "espnow") - cand = None - if tr == "espnow": - cand = normalize_mac(doc.get("address")) - if not cand: - continue - moves.append((sid, cand)) - for old, mac in moves: - if old not in self: - continue - doc = self.pop(old) - if mac in self: - existing = dict(self[mac]) - for k, v in doc.items(): - if k not in existing or existing[k] in (None, "", []): - existing[k] = v - doc = existing - doc["id"] = mac - self[mac] = doc - changed = True - return changed - - def create( - self, - name="", - address=None, - mac=None, - default_pattern=None, - zones=None, - device_type="led", - transport="espnow", - ): - dt = validate_device_type(device_type) - tr = validate_device_transport(transport) - mac_hex = derive_device_mac(mac=mac, address=address, transport=tr) - if not mac_hex: - raise ValueError( - "mac is required (12 hex characters); for Wi-Fi pass mac separately from IP address" - ) - if mac_hex in self: - raise ValueError("device with this mac already exists") - addr = normalize_address_for_transport(address, tr) - if tr == "espnow": - addr = mac_hex - self[mac_hex] = { - "id": mac_hex, - "name": name, - "type": dt, - "transport": tr, - "address": addr, - "default_pattern": default_pattern if default_pattern else None, - "zones": list(zones) if zones else [], - } - self.save() - return mac_hex - - def read(self, id): - m = normalize_mac(id) - if m is not None and m in self: - return self.get(m) - return self.get(str(id), None) - - def update(self, id, data): - id_str = normalize_mac(id) - if id_str is None: - id_str = str(id) - if id_str not in self: - return False - incoming = dict(data) - incoming.pop("id", None) - incoming.pop("addresses", None) - in_mac = normalize_mac(incoming.get("mac")) - if in_mac is not None and in_mac != id_str: - raise ValueError("cannot change device mac; delete and re-add") - incoming.pop("mac", None) - merged = dict(self[id_str]) - merged.update(incoming) - merged["type"] = validate_device_type(merged.get("type")) - merged["transport"] = validate_device_transport(merged.get("transport")) - tr = merged["transport"] - merged["address"] = normalize_address_for_transport(merged.get("address"), tr) - if tr == "espnow": - merged["address"] = id_str - merged["id"] = id_str - self[id_str] = merged - self.save() - return True - - def delete(self, id): - id_str = normalize_mac(id) - if id_str is None: - 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 upsert_wifi_tcp_client(self, device_name, peer_ip, mac, device_type=None): - """ - Register or update a Wi-Fi client by **MAC** (storage id). Updates **name**, - **address** (peer IP), and optionally **type** from the client hello when valid. - - Returns ``(mac_hex | None, persisted)`` where **persisted** is True iff ``save()`` - ran (new row or field changes). Duplicate hellos with identical data are no-ops. - """ - mac_hex = normalize_mac(mac) - if not mac_hex: - return None, False - name = (device_name or "").strip() - if not name: - return None, False - ip = normalize_address_for_transport(peer_ip, "wifi") - if not ip: - return None, False - resolved_type = None - if device_type is not None: - try: - resolved_type = validate_device_type(device_type) - except ValueError: - resolved_type = None - if mac_hex in self: - prev = self[mac_hex] - merged = dict(prev) - merged["name"] = name - if resolved_type is not None: - merged["type"] = resolved_type - else: - merged["type"] = validate_device_type(merged.get("type")) - merged["transport"] = "wifi" - merged["address"] = ip - merged["id"] = mac_hex - if merged == prev: - return mac_hex, False - self[mac_hex] = merged - self.save() - return mac_hex, True - self[mac_hex] = { - "id": mac_hex, - "name": name, - "type": resolved_type or "led", - "transport": "wifi", - "address": ip, - "default_pattern": None, - "zones": [], - } - self.save() - return mac_hex, True diff --git a/src/models/group.py b/src/models/group.py deleted file mode 100644 index 06bec27..0000000 --- a/src/models/group.py +++ /dev/null @@ -1,51 +0,0 @@ -from models.model import Model - -class Group(Model): - def __init__(self): - super().__init__() - - def create(self, name=""): - next_id = self.get_next_id() - self[next_id] = { - "name": name, - "devices": [], - "pattern": "on", - "colors": ["000000", "FF0000"], - "brightness": 100, - "delay": 100, - "step_offset": 0, - "step_increment": 1, - "n1": 0, - "n2": 0, - "n3": 0, - "n4": 0, - "n5": 0, - "n6": 0, - "n7": 0, - "n8": 0 - } - 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) - 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()) diff --git a/src/models/http_driver.py b/src/models/http_driver.py deleted file mode 100644 index 423154e..0000000 --- a/src/models/http_driver.py +++ /dev/null @@ -1,125 +0,0 @@ -"""Wi-Fi LED drivers over HTTP long-poll (same port as the web UI). - -Drivers POST /driver/v1/poll; the controller responds with queued JSON lines. -Presence: last poll within DRIVER_HTTP_SEEN_S counts as connected. -""" - -import asyncio -import time - -from models.wifi_peer import normalize_wifi_peer_ip - -# Must exceed max ``wait_s`` (60) on /driver/v1/poll so sessions are not pruned mid-wait. -DRIVER_HTTP_SEEN_S = 90.0 -_QUEUE_MAX = 64 - -_queues: dict[str, asyncio.Queue] = {} -_last_poll: dict[str, float] = {} -_connected_flag: set[str] = set() -_status_broadcast = None - - -def set_wifi_driver_status_broadcaster(coro) -> None: - global _status_broadcast - _status_broadcast = coro - - -def _schedule_status(ip: str, connected: bool) -> None: - fn = _status_broadcast - if not fn: - return - try: - loop = asyncio.get_running_loop() - except RuntimeError: - return - try: - loop.create_task(fn(ip, connected)) - except Exception: - pass - - -def _get_queue(ip: str) -> asyncio.Queue: - q = _queues.get(ip) - if q is None: - q = asyncio.Queue(maxsize=_QUEUE_MAX) - _queues[ip] = q - return q - - -def prune_stale_http_sessions() -> None: - """Drop timed-out sessions, clear queues, broadcast disconnect.""" - now = time.monotonic() - for ip in list(_last_poll.keys()): - if now - _last_poll[ip] <= DRIVER_HTTP_SEEN_S: - continue - _last_poll.pop(ip, None) - _queues.pop(ip, None) - if ip in _connected_flag: - _connected_flag.discard(ip) - _schedule_status(ip, False) - print(f"[HTTP driver] session timed out: {ip}") - - -def touch_http_session(ip: str) -> None: - ip = normalize_wifi_peer_ip(ip) - if not ip: - return - prune_stale_http_sessions() - now = time.monotonic() - _last_poll[ip] = now - if ip not in _connected_flag: - _connected_flag.add(ip) - _schedule_status(ip, True) - - -def wifi_driver_connected(ip: str) -> bool: - prune_stale_http_sessions() - key = normalize_wifi_peer_ip(ip) - return bool(key and key in _connected_flag) - - -def list_connected_driver_ips(): - prune_stale_http_sessions() - return list(_connected_flag) - - -async def enqueue_json_line(ip: str, json_str: str) -> bool: - ip = normalize_wifi_peer_ip(ip) - if not ip: - return False - line = json_str[:-1] if json_str.endswith("\n") else json_str - q = _get_queue(ip) - while True: - try: - q.put_nowait(line) - return True - except asyncio.QueueFull: - try: - q.get_nowait() - except asyncio.QueueEmpty: - pass - - -async def send_json_line_to_ip(ip: str, json_str: str) -> bool: - """Queue one JSON line for the driver to receive on the next long-poll.""" - return await enqueue_json_line(ip, json_str) - - -async def collect_lines_after_touch(ip: str, wait_s: float) -> list[str]: - """Wait up to wait_s for first line, then drain the rest (non-blocking).""" - ip = normalize_wifi_peer_ip(ip) - if not ip: - return [] - q = _get_queue(ip) - lines: list[str] = [] - try: - first = await asyncio.wait_for(q.get(), timeout=wait_s) - lines.append(first) - while True: - try: - lines.append(q.get_nowait()) - except asyncio.QueueEmpty: - break - except asyncio.TimeoutError: - pass - return lines diff --git a/src/models/model.py b/src/models/model.py deleted file mode 100644 index 43aa625..0000000 --- a/src/models/model.py +++ /dev/null @@ -1,113 +0,0 @@ -import json -import os -import traceback - -# DB directory: project root / db (writable without root) -def _db_dir(): - try: - # src/models/model.py -> project root - base = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - return os.path.join(base, "db") - except Exception: - return "db" - -class Model(dict): - def __new__(cls, *args, **kwargs): - # Singleton pattern: return existing instance if it exists - if not hasattr(cls, '_instance'): - cls._instance = super().__new__(cls) - return cls._instance - - def __init__(self): - # Only initialize once (check if already initialized) - if hasattr(self, '_initialized'): - return - - db_dir = _db_dir() - try: - os.makedirs(db_dir, exist_ok=True) - except OSError: - pass - self.class_name = self.__class__.__name__ - self.file = os.path.join(db_dir, f"{self.class_name.lower()}.json") - super().__init__() - - self.load() # Load settings from file during initialization - self._initialized = True - - def set_defaults(self): - self.clear() - - def get_next_id(self): - """Get the next available ID for creating a new record.""" - if not self: - return "1" - max_id = max((int(k) for k in self.keys() if k.isdigit()), default=0) - return str(max_id + 1) - - def save(self): - try: - db_dir = os.path.dirname(self.file) - try: - os.makedirs(db_dir, exist_ok=True) - except OSError: - pass - j = json.dumps(self) - with open(self.file, 'w') as file: - file.write(j) - file.flush() # Ensure data is written to buffer - # Try to sync filesystem if available (MicroPython) - try: - os.sync() - except (AttributeError, OSError): - pass # os.sync() not available on all platforms - print(f"{self.class_name} saved successfully to {self.file}") - except Exception as e: - print(f"Error saving {self.class_name} to {self.file}: {e}") - traceback.print_exception(type(e), e, e.__traceback__) - - def load(self): - try: - # Check if file exists first - try: - with open(self.file, 'r') as file: - content = file.read().strip() - except OSError: - # File doesn't exist - raise - - if not content: - # Empty file - loaded_settings = {} - else: - # Parse JSON content - loaded_settings = json.loads(content) - - # Verify it's a dictionary - if not isinstance(loaded_settings, dict): - raise ValueError(f"File does not contain a dictionary, got {type(loaded_settings)}") - - # Clear and update with loaded data - # Clear first - self.clear() - # Manually copy items to avoid any update() method issues - for key, value in loaded_settings.items(): - self[key] = value - print(f"{self.class_name} loaded successfully.") - except OSError as e: - # File doesn't exist yet - this is normal on first run - # Create an empty file with defaults - self.set_defaults() - self.save() - print(f"{self.class_name} initialized (new file created).") - except ValueError: - # JSON parsing error - file exists but is corrupted - # Note: MicroPython uses ValueError for JSON errors, not JSONDecodeError - print(f"Error loading {self.class_name}: Invalid JSON format. Resetting to defaults.") - self.set_defaults() - self.save() - except Exception: - # Other unexpected errors - avoid trying to format exception to prevent further errors - print(f"Error loading {self.class_name}. Resetting to defaults.") - self.set_defaults() - self.save() diff --git a/src/models/output.py b/src/models/output.py deleted file mode 100644 index 7914bad..0000000 --- a/src/models/output.py +++ /dev/null @@ -1,138 +0,0 @@ -""" -Pixel-output registry persisted in ``db/output.json``. - -Network / DMX fixtures that the Pi renders frames for (DDP, Art-Net, sACN, -USB-DMX). Our own ESP32 led-drivers stay in ``db/device.json``. **name** is -matched against zone ``names`` the same way device names are. -""" - -from models.model import Model - -OUTPUT_PROTOCOLS = ("ddp", "artnet", "sacn", "dmx_serial") -COLOR_ORDERS = ("rgb", "rbg", "grb", "gbr", "brg", "bgr") -DMX_MODES = ("enttec_pro", "open_dmx") - -_DEFAULTS = { - "name": "", - "protocol": "ddp", - "host": "", - "port": None, - "universe": None, - "channel": 1, - "serial_port": "", - "dmx_mode": "enttec_pro", - "pixel_count": 60, - "pixel_offset": 0, - "color_order": "rgb", - "reverse": False, - "brightness": 255, - "fps": 40, - "enabled": True, -} - - -def _int_field(doc, key, lo, hi, allow_none=False): - value = doc.get(key) - if value is None or value == "": - if allow_none: - doc[key] = None - return - raise ValueError(f"{key} is required") - try: - value = int(value) - except (TypeError, ValueError): - raise ValueError(f"{key} must be an integer") - if value < lo or value > hi: - raise ValueError(f"{key} must be between {lo} and {hi}") - doc[key] = value - - -def validate_output(data): - """Return a normalised output record or raise ValueError.""" - doc = dict(_DEFAULTS) - doc.update({k: v for k, v in (data or {}).items() if k != "id"}) - doc["name"] = str(doc.get("name") or "").strip() - if not doc["name"]: - raise ValueError("name is required") - protocol = str(doc.get("protocol") or "").strip().lower() - if protocol not in OUTPUT_PROTOCOLS: - raise ValueError(f"protocol must be one of: {', '.join(OUTPUT_PROTOCOLS)}") - doc["protocol"] = protocol - doc["host"] = str(doc.get("host") or "").strip() - doc["serial_port"] = str(doc.get("serial_port") or "").strip() - - if protocol == "ddp" and not doc["host"]: - raise ValueError("host is required for ddp") - if protocol == "dmx_serial": - if not doc["serial_port"]: - raise ValueError("serial_port is required for dmx_serial") - mode = str(doc.get("dmx_mode") or "enttec_pro").lower() - if mode not in DMX_MODES: - raise ValueError(f"dmx_mode must be one of: {', '.join(DMX_MODES)}") - doc["dmx_mode"] = mode - - _int_field(doc, "port", 1, 65535, allow_none=True) - if protocol == "sacn": - _int_field(doc, "universe", 1, 63999, allow_none=True) - else: - _int_field(doc, "universe", 0, 0x7FFF, allow_none=True) - _int_field(doc, "channel", 1, 512) - _int_field(doc, "pixel_count", 1, 100000) - _int_field(doc, "pixel_offset", 0, 100000) - _int_field(doc, "brightness", 0, 255) - _int_field(doc, "fps", 1, 120) - if protocol == "dmx_serial": - max_px = (512 - doc["channel"] + 1) // 3 - if doc["pixel_count"] > max_px: - raise ValueError(f"pixel_count must be at most {max_px} for one DMX universe from channel {doc['channel']}") - - order = str(doc.get("color_order") or "rgb").lower() - if order not in COLOR_ORDERS: - raise ValueError(f"color_order must be one of: {', '.join(COLOR_ORDERS)}") - doc["color_order"] = order - doc["reverse"] = bool(doc.get("reverse")) - doc["enabled"] = bool(doc.get("enabled", True)) - return doc - - -class Output(Model): - def __init__(self): - super().__init__() - - def create(self, data): - doc = validate_output(data) - next_id = self.get_next_id() - doc["id"] = next_id - self[next_id] = doc - self.save() - return next_id - - def read(self, id): - return self.get(str(id), None) - - def update(self, id, data): - id_str = str(id) - if id_str not in self: - return False - merged = dict(self[id_str]) - merged.update(data or {}) - doc = validate_output(merged) - doc["id"] = id_str - self[id_str] = doc - self.save() - return True - - def delete(self, id): - id_str = str(id) - if id_str not in self: - return False - self.pop(id_str) - self.save() - return True - - def list(self): - return list(self.keys()) - - def by_name(self, name): - n = str(name or "").strip() - return [doc for doc in self.values() if isinstance(doc, dict) and doc.get("name") == n] diff --git a/src/models/pallet.py b/src/models/pallet.py deleted file mode 100644 index 56de198..0000000 --- a/src/models/pallet.py +++ /dev/null @@ -1,45 +0,0 @@ -from models.model import Model - -class Palette(Model): - def __init__(self): - super().__init__() - - def create(self, name="", colors=None): - next_id = self.get_next_id() - # Store palette as a simple list of colors; name is ignored. - self[next_id] = list(colors) if colors else [] - self.save() - return next_id - - def read(self, id): - id_str = str(id) - value = self.get(id_str, None) - # Backwards compatibility: if stored as {"colors": [...]}, unwrap. - if isinstance(value, dict) and "colors" in value: - return value.get("colors") or [] - # Otherwise, expect a list of colors. - return value or [] - - def update(self, id, data): - id_str = str(id) - if id_str not in self: - return False - # Accept either {"colors": [...]} or a raw list. - if isinstance(data, dict): - colors = data.get("colors", []) - else: - colors = data - self[id_str] = list(colors) if colors else [] - 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()) diff --git a/src/models/pattern.py b/src/models/pattern.py deleted file mode 100644 index 6ea0f76..0000000 --- a/src/models/pattern.py +++ /dev/null @@ -1,38 +0,0 @@ -from models.model import Model - - -class Pattern(Model): - def __init__(self): - super().__init__() - - def create(self, name="", data=None): - pattern_name = str(name).strip() - if not pattern_name: - pattern_name = self.get_next_id() - self[pattern_name] = data if isinstance(data, dict) else {} - self.save() - return pattern_name - - def read(self, id): - id_str = str(id) - return self.get(id_str, None) - - def update(self, id, data): - id_str = str(id) - if id_str not in self: - return False - if isinstance(data, dict): - self[id_str].update(data) - self.save() - return True - - def delete(self, id): - id_str = str(id) - if id_str not in self: - return False - self.pop(id_str) - self.save() - return True - - def list(self): - return list(self.keys()) diff --git a/src/models/preset.py b/src/models/preset.py deleted file mode 100644 index 78be827..0000000 --- a/src/models/preset.py +++ /dev/null @@ -1,69 +0,0 @@ -from models.model import Model -from models.profile import Profile - -class Preset(Model): - def __init__(self): - super().__init__() - # Backfill profile ownership for existing presets. - try: - profiles = Profile() - profile_list = profiles.list() - default_profile_id = profile_list[0] if profile_list else None - changed = False - for preset_id, preset_data in list(self.items()): - if isinstance(preset_data, dict) and "profile_id" not in preset_data: - if default_profile_id is not None: - preset_data["profile_id"] = str(default_profile_id) - changed = True - if changed: - self.save() - except Exception: - pass - - def create(self, profile_id=None): - next_id = self.get_next_id() - self[next_id] = { - "name": "", - "pattern": "", - "colors": [], - "brightness": 0, - "delay": 0, - "n1": 0, - "n2": 0, - "n3": 0, - "n4": 0, - "n5": 0, - "n6": 0, - "n7": 0, - "n8": 0, - "profile_id": str(profile_id) if profile_id is not None else None, - } - self.save() - return next_id - - - def read(self, id): - id_str = str(id) - if id_str not in self: - return None - return self[id_str] - - def update(self, id, data): - id_str = str(id) - if id_str not in self: - return False - self[id_str].update(data) - self.save() - return True - - def delete(self, id): - id_str = str(id) - if id_str not in self: - return False - self.pop(id_str) - self.save() - return True - - def list(self): - return list(self.keys()) - \ No newline at end of file diff --git a/src/models/profile.py b/src/models/profile.py deleted file mode 100644 index 62d53a3..0000000 --- a/src/models/profile.py +++ /dev/null @@ -1,69 +0,0 @@ -from models.model import Model -from models.pallet import Palette - - -class Profile(Model): - def __init__(self): - """Profile model. - - Each profile owns a single, unique palette stored in the Palette model. - The profile stores a `palette_id` that points to its palette; any legacy - inline `palette` arrays are migrated to a dedicated Palette entry. - """ - super().__init__() - self._palette_model = Palette() - - # Migrate legacy inline palettes to separate Palette entries. - changed = False - for pid, pdata in list(self.items()): - if isinstance(pdata, dict): - if "palette" in pdata and "palette_id" not in pdata: - colors = pdata.get("palette") or [] - palette_id = self._palette_model.create(colors=colors) - pdata.pop("palette", None) - pdata["palette_id"] = str(palette_id) - changed = True - if changed: - self.save() - - def create(self, name="", profile_type="zones"): - """Create a new profile and its own empty palette. - - profile_type: "zones" or "scenes" (ignoring scenes for now) - """ - next_id = self.get_next_id() - # Create a unique palette for this profile. - palette_id = self._palette_model.create(colors=[]) - self[next_id] = { - "name": name, - "type": profile_type, # "zones" or "scenes" - "zones": [], # Array of zone IDs - "scenes": [], # Array of scene IDs (for future use) - "palette_id": str(palette_id), - } - 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) - 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()) - \ No newline at end of file diff --git a/src/models/scene.py b/src/models/scene.py deleted file mode 100644 index 64cf2e4..0000000 --- a/src/models/scene.py +++ /dev/null @@ -1,38 +0,0 @@ -from models.model import Model - -class Scene(Model): - def __init__(self): - super().__init__() - - def create(self, name="", sequences=None, groups=None): - next_id = self.get_next_id() - self[next_id] = { - "name": name, - "sequences": sequences if sequences else [], - "groups": groups if groups else [] - } - 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) - 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()) diff --git a/src/models/serial.py b/src/models/serial.py deleted file mode 100644 index 2517c27..0000000 --- a/src/models/serial.py +++ /dev/null @@ -1,12 +0,0 @@ -class Serial: - def __init__(self, port, baudrate): - self.port = port - self.baudrate = baudrate - self.uart = UART(1, baudrate, tx=Pin(21), rx=Pin(6)) - - def send(self, data): - self.uart.write(data) - - def receive(self): - return self.uart.read() - \ No newline at end of file diff --git a/src/models/squence.py b/src/models/squence.py deleted file mode 100644 index c6c57ef..0000000 --- a/src/models/squence.py +++ /dev/null @@ -1,112 +0,0 @@ -from models.model import Model - -DURATION_MIN_S = 0.5 -DURATION_MAX_S = 600.0 -DURATION_DEFAULT_S = 5.0 - -_LEGACY_KEYS = ( - "group_name", "presets", "sequence_duration", "sequence_transition", "sequence_loop", - "sequence_repeat_count", "sequence_active", "sequence_index", "sequence_start_time", -) - - -def _normalize_step(step): - """``{"preset_id", "duration_s"}`` with duration clamped to 0.5–600 s (default 5).""" - if not isinstance(step, dict): - step = {"preset_id": step} - preset_id = step.get("preset_id") - if preset_id in (None, ""): - raise ValueError("each step needs a preset_id") - try: - duration = float(step.get("duration_s", DURATION_DEFAULT_S)) - except (TypeError, ValueError): - duration = DURATION_DEFAULT_S - duration = max(DURATION_MIN_S, min(DURATION_MAX_S, duration)) - return {"preset_id": str(preset_id), "duration_s": duration} - - -def _normalize(data): - doc = dict(data or {}) - doc["name"] = str(doc.get("name") or "").strip() - zone_id = doc.get("zone_id") - doc["zone_id"] = None if zone_id in (None, "") else str(zone_id) - doc["loop"] = bool(doc.get("loop", True)) - try: - doc["repeat_count"] = max(0, int(doc.get("repeat_count") or 0)) - except (TypeError, ValueError): - raise ValueError("repeat_count must be an integer") - steps = doc.get("steps") or [] - if not isinstance(steps, list): - raise ValueError("steps must be a list") - doc["steps"] = [_normalize_step(s) for s in steps] - doc["active"] = bool(doc.get("active", False)) - for key in _LEGACY_KEYS: - doc.pop(key, None) - return doc - - -def migrate_legacy(doc): - """Old ``presets`` + ``sequence_duration`` (ms) records → ``steps`` shape.""" - if not isinstance(doc, dict) or "steps" in doc: - return doc, False - try: - duration_s = float(doc.get("sequence_duration", 3000)) / 1000.0 - except (TypeError, ValueError): - duration_s = DURATION_DEFAULT_S - migrated = { - "name": doc.get("name") or doc.get("group_name") or "", - "zone_id": doc.get("zone_id"), - "loop": bool(doc.get("sequence_loop", True)), - "repeat_count": doc.get("sequence_repeat_count") or 0, - "steps": [{"preset_id": p, "duration_s": duration_s} for p in (doc.get("presets") or [])], - "active": False, - } - return _normalize(migrated), True - - -class Sequence(Model): - def __init__(self): - super().__init__() - - def load(self): - super().load() - changed = False - for key in list(self.keys()): - doc, migrated = migrate_legacy(self[key]) - if migrated: - self[key] = doc - changed = True - if changed: - self.save() - - def create(self, data=None): - doc = _normalize(data) - next_id = self.get_next_id() - self[next_id] = doc - self.save() - return next_id - - def read(self, id): - id_str = str(id) - return self.get(id_str, None) - - def update(self, id, data): - id_str = str(id) - if id_str not in self: - return False - merged = dict(self[id_str]) - merged.update(data or {}) - self[id_str] = _normalize(merged) - self.save() - return True - - def delete(self, id): - id_str = str(id) - if id_str not in self: - return False - self.pop(id_str) - self.save() - return True - - def list(self): - return list(self.keys()) diff --git a/src/models/transport.py b/src/models/transport.py deleted file mode 100644 index 236bee6..0000000 --- a/src/models/transport.py +++ /dev/null @@ -1,90 +0,0 @@ -import asyncio -import json - - -# Default: broadcast (6 bytes). Pi always sends 6-byte address + payload to ESP32. -BROADCAST_MAC = bytes.fromhex("ffffffffffff") - - -def _encode_payload(data): - if isinstance(data, str): - return data.encode() - if isinstance(data, dict): - return json.dumps(data).encode() - return data - - -def _parse_mac(addr): - """Convert 12-char hex string or 6-byte bytes to 6-byte MAC.""" - if addr is None or addr == b"": - return BROADCAST_MAC - if isinstance(addr, bytes) and len(addr) == 6: - return addr - if isinstance(addr, str) and len(addr) == 12: - return bytes.fromhex(addr) - return BROADCAST_MAC - - -async def _to_thread(func, *args): - to_thread = getattr(asyncio, "to_thread", None) - if to_thread: - return await to_thread(func, *args) - loop = asyncio.get_event_loop() - 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 - - self._serial = serial.Serial(port, baudrate=baudrate, timeout=1) - self._default_addr = _parse_mac(default_addr) - self._write_lock = asyncio.Lock() - - async def send(self, data, addr=None): - mac = _parse_mac(addr) if addr is not None else self._default_addr - payload = _encode_payload(data) - async with self._write_lock: - await _to_thread(self._serial.write, mac + payload) - return True - - -_current_sender = None - - -def set_sender(sender): - global _current_sender - _current_sender = sender - - -def get_current_sender(): - return _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") - 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() diff --git a/src/models/wifi_peer.py b/src/models/wifi_peer.py deleted file mode 100644 index ccdff94..0000000 --- a/src/models/wifi_peer.py +++ /dev/null @@ -1,8 +0,0 @@ -"""Normalise Wi-Fi client addresses (strip IPv4-mapped IPv6 prefix).""" - - -def normalize_wifi_peer_ip(ip: str) -> str: - s = str(ip).strip() - if s.lower().startswith("::ffff:"): - s = s[7:] - return s diff --git a/src/models/wifi_ws_clients.py b/src/models/wifi_ws_clients.py deleted file mode 100644 index 8ecd7d2..0000000 --- a/src/models/wifi_ws_clients.py +++ /dev/null @@ -1,365 +0,0 @@ -"""Outbound WebSocket clients to Wi-Fi LED drivers (firmware serves ``/ws`` on device).""" - -from __future__ import annotations - -import asyncio -import errno -import json -import traceback - -import websockets -from websockets.exceptions import ConnectionClosed - -_connections: dict[str, object] = {} -_send_locks: dict[str, asyncio.Lock] = {} -_tasks: dict[str, asyncio.Task] = {} -_unreachable_counts: dict[str, int] = {} -_settings = None - -_tcp_status_broadcast = None - - -def set_settings(settings) -> None: - global _settings - _settings = settings - - -def set_tcp_status_broadcaster(coro) -> None: - global _tcp_status_broadcast - _tcp_status_broadcast = coro - - -def _schedule_status_broadcast(ip: str, connected: bool) -> None: - fn = _tcp_status_broadcast - if not fn: - return - try: - loop = asyncio.get_running_loop() - except RuntimeError: - return - try: - loop.create_task(fn(ip, connected)) - except Exception: - pass - - -def _benign_ws_connect_failure(exc: BaseException) -> bool: - """True for common \"driver down / no route\" errors while dialling the WebSocket.""" - if isinstance(exc, (asyncio.TimeoutError, TimeoutError)): - return True - if isinstance(exc, ConnectionRefusedError): - return True - if not isinstance(exc, OSError): - return False - en = exc.errno - if en is None: - return False - codes = {errno.ECONNREFUSED, errno.ETIMEDOUT} - for name in ("EHOSTUNREACH", "ENETUNREACH", "ENETDOWN", "EADDRNOTAVAIL"): - if hasattr(errno, name): - codes.add(getattr(errno, name)) - return en in codes - - -def normalize_tcp_peer_ip(ip: str) -> str: - """Match peer addresses to registry IPs (strip IPv4-mapped IPv6 prefix).""" - s = str(ip).strip() - if s.lower().startswith("::ffff:"): - s = s[7:] - return s - - -def _ws_open(ws) -> bool: - try: - return ws.close_code is None - except Exception: - return False - - -def prune_stale_tcp_writers() -> None: - """Drop closed WebSocket entries (name kept for callers).""" - stale = [ip for ip, ws in list(_connections.items()) if not _ws_open(ws)] - for ip in stale: - _connections.pop(ip, 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: - return - _connections[key] = ws - _unreachable_counts.pop(key, None) - if key not in _send_locks: - _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: - """ - Remove the WebSocket for peer_ip. If ``ws`` is given, only pop when it is still - the registered instance. - - Returns ``removed``, ``noop``, or ``superseded`` (same contract as former TCP registry). - """ - if not peer_ip: - return "noop" - key = normalize_tcp_peer_ip(peer_ip) - if not key: - return "noop" - current = _connections.get(key) - if ws is not None: - if current is None: - return "noop" - if current is not ws: - return "superseded" - had = key in _connections - if had: - _connections.pop(key, None) - _schedule_status_broadcast(key, False) - print(f"[WS] driver disconnected: {key}") - return "removed" - return "noop" - - -def list_connected_ips(): - """IPs with an active outbound WebSocket to the driver.""" - prune_stale_tcp_writers() - return list(_connections.keys()) - - -def tcp_client_connected(ip: str) -> bool: - """True if the controller has an outbound WebSocket to this driver IP.""" - prune_stale_tcp_writers() - key = normalize_tcp_peer_ip(ip) - return bool(key and key in _connections) - - -async def send_json_line_to_ip(ip: str, json_str: str) -> bool: - """Send one JSON text frame (v1 line; trailing newline stripped for WebSocket).""" - ip = normalize_tcp_peer_ip(ip) - ws = _connections.get(ip) - if ws is None or not _ws_open(ws): - return False - text = json_str.rstrip("\n") - lock = _send_locks.setdefault(ip, asyncio.Lock()) - try: - async with lock: - await ws.send(text) - return True - except Exception as exc: - print(f"[WS] send to {ip} failed: {exc}") - unregister_tcp_writer(ip, ws) - return False - - -async def _recv_forward_loop(ip: str, ws) -> None: - from models.transport import get_current_sender - - sender = get_current_sender() - async for message in ws: - if isinstance(message, bytes): - try: - text = message.decode("utf-8") - except UnicodeDecodeError: - print(f"[WS] recv {ip} (non-UTF-8, {len(message)} bytes)") - continue - else: - text = message - text = text.strip() - if not text: - continue - print(f"[WS] recv {ip}: {text}") - if not sender: - continue - try: - parsed = json.loads(text) - except json.JSONDecodeError: - try: - await sender.send(text) - except Exception: - pass - continue - if isinstance(parsed, dict): - addr = parsed.pop("to", None) - payload = json.dumps(parsed) if parsed else "{}" - try: - await sender.send(payload, addr=addr) - except Exception as e: - print(f"[WS] forward to bridge failed: {e}") - else: - try: - await sender.send(text) - except Exception: - 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: - return - port = int(_settings.get("wifi_driver_ws_port", 80)) - path = str(_settings.get("wifi_driver_ws_path", "/ws")) - if not path.startswith("/"): - path = "/" + path - uri = f"ws://{ip}:{port}{path}" - 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 = loop.time() - if not connected_once and now >= deadline: - print( - f"[WS] driver {ip} still unreachable after {int(retry_window_s)}s " - f"(initial window); stopping until next UDP hello / registry prime" - ) - break - try: - print(f"[WS] connecting to {uri!r}") - async with websockets.connect( - uri, - ping_interval=20, - ping_timeout=15, - open_timeout=open_timeout, - ) as ws: - connected_once = True - _register_ws(ip, ws) - try: - await _recv_forward_loop(ip, ws) - finally: - unregister_tcp_writer(ip, ws) - except asyncio.CancelledError: - raise - except ConnectionClosed as e: - print(f"[WS] driver {ip} closed: {e}") - unregister_tcp_writer(ip, None) - except Exception as e: - if _benign_ws_connect_failure(e): - 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 {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__) - _unreachable_counts.pop(ip, None) - unregister_tcp_writer(ip, None) - await asyncio.sleep(retry_interval_s) - except asyncio.CancelledError: - unregister_tcp_writer(ip, None) - raise - finally: - _tasks.pop(ip, None) - - -def ensure_driver_connection(peer_ip: str) -> None: - """Start (or keep) a background task that maintains ``ws://:port/ws``.""" - key = normalize_tcp_peer_ip(peer_ip) - if not key: - return - t = _tasks.get(key) - if t is not None and not t.done(): - return - try: - loop = asyncio.get_running_loop() - except RuntimeError: - return - _tasks[key] = loop.create_task(_driver_connection_loop(key)) - - -def cancel_all_driver_tasks() -> None: - """Signal shutdown: cancel outbound driver connection tasks.""" - for _ip, t in list(_tasks.items()): - if not t.done(): - t.cancel() - _tasks.clear() - for ip in list(_connections.keys()): - _schedule_status_broadcast(ip, False) - _connections.clear() - _send_locks.clear() - _unreachable_counts.clear() diff --git a/src/models/zone.py b/src/models/zone.py deleted file mode 100644 index fb8f099..0000000 --- a/src/models/zone.py +++ /dev/null @@ -1,62 +0,0 @@ -import os -import shutil - -from models.model import Model - - -def _maybe_migrate_tab_json_to_zone(): - """One-time copy ``db/tab.json`` → ``db/zone.json`` when upgrading.""" - try: - base = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - db_dir = os.path.join(base, "db") - zone_path = os.path.join(db_dir, "zone.json") - tab_path = os.path.join(db_dir, "tab.json") - if not os.path.exists(zone_path) and os.path.exists(tab_path): - shutil.copy2(tab_path, zone_path) - print("Migrated db/tab.json -> db/zone.json") - except OSError: - pass - - -class Zone(Model): - """Preset layout row (stored in ``db/zone.json``); legacy storage was ``tab.json`` / Tab.""" - - def __init__(self): - if not getattr(Zone, "_migration_checked", False): - _maybe_migrate_tab_json_to_zone() - Zone._migration_checked = True - super().__init__() - - def create(self, name="", names=None, presets=None): - next_id = self.get_next_id() - self[next_id] = { - "name": name, - "names": names if names else [], - "presets": presets if presets else [], - "default_preset": None, - } - 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) - 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()) diff --git a/src/profile.py b/src/profile.py deleted file mode 100644 index e69de29..0000000 diff --git a/src/settings.py b/src/settings.py deleted file mode 100644 index c28a894..0000000 --- a/src/settings.py +++ /dev/null @@ -1,105 +0,0 @@ -import json -import os -import binascii - - -def _settings_path(): - """Path to settings.json in project root (writable without root).""" - try: - base = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - return os.path.join(base, "settings.json") - except Exception: - return "settings.json" - - -class Settings(dict): - SETTINGS_FILE = None # Set in __init__ from _settings_path() - - def __init__(self): - super().__init__() - if Settings.SETTINGS_FILE is None: - Settings.SETTINGS_FILE = _settings_path() - self.load() # Load settings from file during initialization - - def generate_secret_key(self): - """Generate a random secret key for session signing.""" - try: - # Try to use os.urandom for secure random bytes - random_bytes = os.urandom(32) - return binascii.hexlify(random_bytes).decode('utf-8') - except (AttributeError, NotImplementedError): - # Fallback for MicroPython or systems without os.urandom - try: - import secrets - return secrets.token_hex(32) - except ImportError: - # Last resort: use a combination of time and random - import time - import random - random.seed(time.time()) - return binascii.hexlify(bytes([random.randint(0, 255) for _ in range(32)])).decode('utf-8') - - def set_defaults(self): - """Set default settings if they don't exist.""" - if 'session_secret_key' not in self: - self['session_secret_key'] = self.generate_secret_key() - # Save immediately when generating a new key - self.save() - # ESP-NOW STA channel (2.4 GHz) for LED drivers / bridge alignment; 1–11 - if 'wifi_channel' not in self: - self['wifi_channel'] = 6 - # Wi-Fi LED drivers: controller opens WebSocket to device (firmware serves /ws) - if 'wifi_driver_ws_port' not in self: - self['wifi_driver_ws_port'] = 80 - if 'wifi_driver_ws_path' not in self: - self['wifi_driver_ws_path'] = '/ws' - # Seconds between UDP discovery nudges when a Wi-Fi driver WebSocket is - # 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: - j = json.dumps(self) - with open(self.SETTINGS_FILE, 'w') as file: - file.write(j) - print("Settings saved successfully.") - except Exception as e: - print(f"Error saving settings: {e}") - - def load(self): - loaded_from_file = False - try: - with open(self.SETTINGS_FILE, 'r') as file: - loaded_settings = json.load(file) - self.update(loaded_settings) - loaded_from_file = True - print("Settings loaded successfully.") - except Exception as e: - print(f"Error loading settings") - self.clear() - finally: - # Ensure defaults are set even if file exists but is missing keys - self.set_defaults() - # Only save if file didn't exist or was invalid - if not loaded_from_file: - self.save() diff --git a/src/static/app.js b/src/static/app.js deleted file mode 100644 index 4af1d43..0000000 --- a/src/static/app.js +++ /dev/null @@ -1,1734 +0,0 @@ -// Lighting Controller Web App -class LightingController { - constructor() { - this.currentTab = null; - this.state = { - lights: {}, - patterns: {}, - zone_order: [], - presets: {} - }; - this.selectedColorIndex = 0; - this.updateTimeouts = {}; - this.quickPaletteContext = null; - - this.init(); - } - - async init() { - await this.loadState(); - this.setupEventListeners(); - this.renderTabs(); - if (this.state.zone_order.length > 0) { - this.selectTab(this.state.zone_order[0]); - } - } - - async loadState() { - try { - // Load presets and profiles separately since /api/state doesn't exist - const presetsResponse = await fetch('/presets'); - const presets = await presetsResponse.json(); - this.state.presets = presets || {}; - - const patternsResponse = await fetch('/patterns'); - if (patternsResponse.ok) { - const patterns = await patternsResponse.json(); - this.state.patterns = patterns || {}; - } - - // Load profiles - const profilesResponse = await fetch('/profiles'); - const profiles = await profilesResponse.json(); - - // Update current profile display - this.updateCurrentProfileDisplay(); - // Update current profile display if profiles modal is open - if (document.getElementById('profiles-modal').classList.contains('active')) { - await this.loadProfiles(); - await this.loadProfilePalette(); - } - } catch (error) { - console.error('Failed to load state:', error); - } - } - - updateCurrentProfileDisplay() { - const currentProfileName = document.getElementById('current-profile-name'); - if (currentProfileName) { - const profile = this.state.current_profile || 'None'; - currentProfileName.textContent = profile; - } - } - - setupEventListeners() { - // Zone management - document.getElementById('add-zone-btn').addEventListener('click', () => this.showAddTabModal()); - document.getElementById('edit-zone-btn').addEventListener('click', () => this.showEditTabModal()); - document.getElementById('delete-zone-btn').addEventListener('click', () => this.deleteCurrentTab()); - document.getElementById('color-palette-btn').addEventListener('click', () => this.showColorPalette()); - document.getElementById('presets-btn').addEventListener('click', () => this.showPresets()); - document.getElementById('profiles-btn').addEventListener('click', () => this.showProfiles()); - - // Modal actions - document.getElementById('add-zone-confirm').addEventListener('click', () => this.createTab()); - document.getElementById('add-zone-cancel').addEventListener('click', () => this.hideModal('add-zone-modal')); - document.getElementById('edit-zone-confirm').addEventListener('click', () => this.updateTab()); - document.getElementById('edit-zone-cancel').addEventListener('click', () => this.hideModal('edit-zone-modal')); - document.getElementById('profiles-close-btn').addEventListener('click', () => this.hideModal('profiles-modal')); - document.getElementById('color-palette-close-btn').addEventListener('click', () => this.hideModal('color-palette-modal')); - document.getElementById('presets-close-btn').addEventListener('click', () => this.hideModal('presets-modal')); - document.getElementById('create-preset-btn').addEventListener('click', () => this.showPresetEditor()); - document.getElementById('preset-editor-save-btn').addEventListener('click', () => this.savePreset()); - document.getElementById('preset-editor-cancel-btn').addEventListener('click', () => this.hideModal('preset-editor-modal')); - document.getElementById('preset-add-color-btn').addEventListener('click', () => this.addPresetColor()); - document.getElementById('preset-remove-color-btn').addEventListener('click', () => this.removePresetColor()); - document.getElementById('preset-editor-from-current-btn').addEventListener('click', () => this.loadCurrentTabToPresetEditor()); - document.getElementById('preset-brightness-slider').addEventListener('input', (e) => { - document.getElementById('preset-brightness-value').textContent = e.target.value; - }); - document.getElementById('quick-palette-close-btn').addEventListener('click', () => this.hideQuickPaletteModal()); - document.getElementById('quick-palette-use-picker-btn').addEventListener('click', () => this.useColorPickerFromQuickPalette()); - document.getElementById('create-profile-btn').addEventListener('click', () => this.createProfile()); - document.getElementById('add-palette-color-btn').addEventListener('click', () => this.addPaletteColor()); - document.getElementById('palette-add-color-btn').addEventListener('click', () => this.addPaletteColorFromModal()); - document.getElementById('toggle-left-panel').addEventListener('click', () => this.toggleLeftPanel()); - - // Enter key for new profile name - document.getElementById('new-profile-name').addEventListener('keypress', (e) => { - if (e.key === 'Enter') { - this.createProfile(); - } - }); - - // Brightness and delay sliders - document.getElementById('brightness-slider').addEventListener('input', (e) => { - document.getElementById('brightness-value').textContent = e.target.value; - this.debounceUpdate('brightness', () => this.updateBrightness()); - }); - document.getElementById('delay-slider').addEventListener('input', (e) => { - this.updateDelayValue(e.target.value); - this.debounceUpdate('delay', () => this.updateDelay()); - }); - - // N parameters - for (let i = 1; i <= 8; i++) { - document.getElementById(`n${i}-input`).addEventListener('input', (e) => { - this.debounceUpdate('nparams', () => this.updateNParams()); - }); - } - - // Color palette - document.getElementById('add-color-btn').addEventListener('click', () => this.addColorToPalette()); - document.getElementById('remove-color-btn').addEventListener('click', () => this.removeSelectedColor()); - - } - - renderTabs() { - const tabsList = document.getElementById('zones-list'); - tabsList.innerHTML = ''; - - this.state.zone_order.forEach(tabName => { - const tabButton = document.createElement('button'); - tabButton.className = 'zone-button'; - tabButton.textContent = tabName; - tabButton.addEventListener('click', () => this.selectTab(tabName)); - if (tabName === this.currentTab) { - tabButton.classList.add('active'); - } - tabsList.appendChild(tabButton); - }); - } - - toggleLeftPanel() { - const leftPanel = document.querySelector('.left-panel'); - if (!leftPanel) return; - leftPanel.classList.toggle('collapsed'); - } - - async selectTab(tabName) { - if (!this.state.lights[tabName]) return; - - this.currentTab = tabName; - this.renderTabs(); - await this.loadTabContent(tabName); - } - - async loadTabContent(tabName) { - const light = this.state.lights[tabName]; - if (!light) { - return; - } - const settings = light.settings; - const pattern = settings.pattern || 'on'; - - // Get pattern-specific settings - const patternSettings = this.getPatternSettings(tabName, pattern); - - // Update IDs display - document.getElementById('current-ids').textContent = light.names.join(', '); - - // Load and render colors in the palette - const colors = patternSettings.colors || ['#000000']; - this.renderColorPalette(tabName, colors); - - // Update brightness slider - const brightness = settings.brightness || 127; - document.getElementById('brightness-slider').value = brightness; - document.getElementById('brightness-value').textContent = brightness; - - // Update delay slider - const patternConfig = this.state.patterns[pattern] || {}; - const minDelay = patternConfig.min_delay || 10; - const maxDelay = patternConfig.max_delay || 10000; - const delaySliderPos = this.delayToSlider(patternSettings.delay, minDelay, maxDelay); - document.getElementById('delay-slider').value = delaySliderPos; - this.updateDelayValue(delaySliderPos, minDelay, maxDelay); - - // Update n parameters - for (let i = 1; i <= 8; i++) { - document.getElementById(`n${i}-input`).value = patternSettings[`n${i}`] || 10; - } - this.updateNParamLabels(pattern); - - // Render presets - this.renderPresets(tabName); - } - - updateNParamLabels(patternName) { - const defaultLabels = {}; - for (let i = 1; i <= 8; i++) { - defaultLabels[`n${i}`] = `n${i}:`; - } - const patternConfig = this.state.patterns ? this.state.patterns[patternName] : null; - if (patternConfig && typeof patternConfig === 'object') { - Object.entries(patternConfig).forEach(([label, key]) => { - if (typeof key === 'string' && key.startsWith('n')) { - defaultLabels[key] = `${label}:`; - } - }); - } - for (let i = 1; i <= 8; i++) { - const labelEl = document.getElementById(`n${i}-label`); - if (labelEl) { - labelEl.textContent = defaultLabels[`n${i}`]; - } - } - } - - renderPresets(tabName) { - const presetsList = document.getElementById('presets-list-zone'); - presetsList.innerHTML = ''; - - const presets = this.state.presets || {}; - const presetNames = Object.keys(presets); - - // Get current zone's settings for comparison - const currentSettings = this.getCurrentTabSettings(tabName); - - // Always include "on" and "off" presets - const defaultPresets = { - 'on': { - pattern: 'on', - colors: ['#FFFFFF'], - brightness: 255, - delay: 100, - n1: 10, - n2: 10, - n3: 10, - n4: 10, - n5: 10, - n6: 10, - n7: 10, - n8: 10 - }, - 'off': { - pattern: 'off', - colors: ['#000000'], - brightness: 0, - delay: 100, - n1: 10, - n2: 10, - n3: 10, - n4: 10, - n5: 10, - n6: 10, - n7: 10, - n8: 10 - } - }; - - // Create a combined list with default presets first, then user presets - const allPresets = { ...defaultPresets, ...presets }; - const allPresetNames = ['on', 'off', ...presetNames.filter(name => name !== 'on' && name !== 'off')]; - - allPresetNames.forEach(presetName => { - const preset = allPresets[presetName]; - const presetButton = document.createElement('button'); - presetButton.className = 'pattern-button'; - - // Check if this preset matches the current zone's settings - const isActive = this.presetMatchesSettings(preset, currentSettings); - if (isActive) { - presetButton.classList.add('active'); - } - - // Mark default presets (on/off) with a special indicator - const isDefault = presetName === 'on' || presetName === 'off'; - if (isDefault) { - presetButton.classList.add('default-preset'); - } - - // Create preset info display - const presetInfo = document.createElement('div'); - presetInfo.style.cssText = 'display: flex; flex-direction: column; align-items: flex-start; width: 100%;'; - - const presetNameLabel = document.createElement('span'); - presetNameLabel.textContent = presetName; - presetNameLabel.style.fontWeight = 'bold'; - presetNameLabel.style.marginBottom = '0.25rem'; - - const presetDetails = document.createElement('span'); - presetDetails.style.fontSize = '0.85em'; - presetDetails.style.color = '#aaa'; - presetDetails.textContent = `${preset.pattern} • ${preset.colors.length} color${preset.colors.length !== 1 ? 's' : ''}`; - - presetInfo.appendChild(presetNameLabel); - presetInfo.appendChild(presetDetails); - presetButton.appendChild(presetInfo); - - presetButton.addEventListener('click', () => { - if (isDefault && !presets[presetName]) { - // Apply default preset directly - this.applyDefaultPreset(tabName, presetName, preset); - } else { - // Apply regular preset - this.applyPresetToTab(tabName, presetName); - } - }); - presetsList.appendChild(presetButton); - }); - } - - async applyDefaultPreset(tabName, presetName, preset) { - // Apply default preset by setting pattern and parameters directly - try { - // First set the pattern - const patternResponse = await fetch('/api/pattern', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - tab_name: tabName, - pattern: preset.pattern, - delay: preset.delay, - colors: preset.colors, - n1: preset.n1, - n2: preset.n2, - n3: preset.n3, - n4: preset.n4, - n5: preset.n5, - n6: preset.n6, - n7: preset.n7, - n8: preset.n8 - }) - }); - - if (patternResponse.ok) { - // Then update brightness - await fetch('/api/parameters', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - tab_name: tabName, - brightness: preset.brightness - }) - }); - - // Reload state and zone content - await this.loadState(); - await this.loadTabContent(tabName); - } else { - const error = await patternResponse.json(); - alert(`Failed to apply preset: ${error.error || 'Unknown error'}`); - } - } catch (error) { - console.error('Failed to apply default preset:', error); - alert('Failed to apply preset'); - } - } - - getCurrentTabSettings(tabName) { - if (!this.state.lights[tabName]) { - return null; - } - - const light = this.state.lights[tabName]; - const settings = light.settings; - const pattern = settings.pattern || 'on'; - const patternSettings = this.getPatternSettings(tabName, pattern); - - return { - pattern: pattern, - brightness: settings.brightness || 127, - delay: patternSettings.delay || 100, - colors: patternSettings.colors || ['#000000'], - n1: patternSettings.n1 || 10, - n2: patternSettings.n2 || 10, - n3: patternSettings.n3 || 10, - n4: patternSettings.n4 || 10, - n5: patternSettings.n5 || 10, - n6: patternSettings.n6 || 10, - n7: patternSettings.n7 || 10, - n8: patternSettings.n8 || 10 - }; - } - - presetMatchesSettings(preset, currentSettings) { - if (!currentSettings) { - return false; - } - - // Compare all settings - if (preset.pattern !== currentSettings.pattern) { - return false; - } - - if (preset.brightness !== currentSettings.brightness) { - return false; - } - - if (preset.delay !== currentSettings.delay) { - return false; - } - - // Compare n values - for (let i = 1; i <= 8; i++) { - if (preset[`n${i}`] !== currentSettings[`n${i}`]) { - return false; - } - } - - // Compare colors (order matters for presets) - if (preset.colors.length !== currentSettings.colors.length) { - return false; - } - - for (let i = 0; i < preset.colors.length; i++) { - // Normalize color format (uppercase, no spaces) - const presetColor = preset.colors[i].toUpperCase().trim(); - const currentColor = currentSettings.colors[i].toUpperCase().trim(); - if (presetColor !== currentColor) { - return false; - } - } - - return true; - } - - async applyPresetToTab(tabName, presetName) { - try { - const preset = this.state.presets[presetName]; - if (!preset) { - alert('Preset not found'); - return; - } - - // Apply preset using the apply endpoint - const response = await fetch(`/api/presets/${presetName}/apply`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ - tab_name: tabName - }) - }); - - if (response.ok) { - await this.loadState(); - await this.loadTabContent(tabName); - } else { - const error = await response.json(); - alert(`Failed to apply preset: ${error.error || 'Unknown error'}`); - } - } catch (error) { - console.error('Failed to apply preset:', error); - alert('Failed to apply preset'); - } - } - - renderColorPalette(tabName, colors) { - const palette = document.getElementById('color-palette'); - if (!palette) { - return; - } - palette.innerHTML = ''; - - colors.forEach((hexColor, index) => { - const swatch = document.createElement('div'); - swatch.className = 'color-swatch'; - if (index === this.selectedColorIndex) { - swatch.classList.add('selected'); - } - - const preview = document.createElement('div'); - preview.className = 'color-swatch-preview'; - preview.style.backgroundColor = hexColor; - - const label = document.createElement('span'); - label.className = 'color-swatch-label'; - label.textContent = `Color ${index + 1}`; - - // Color picker input with palette quick-select - const colorPickerWrapper = document.createElement('div'); - colorPickerWrapper.style.cssText = 'position: relative; display: inline-block;'; - - const colorPicker = document.createElement('input'); - colorPicker.type = 'color'; - colorPicker.value = hexColor; - colorPicker.className = 'color-picker-input'; - colorPicker.dataset.tabName = tabName; - colorPicker.dataset.colorIndex = index; - colorPicker.addEventListener('change', (e) => { - const newColor = e.target.value; - this.updateColorInPalette(tabName, index, newColor); - }); - - // Show quick palette on click, prevent native picker if palette has colors - const clickHandler = (e) => { - e.stopPropagation(); - const palette = this.state.color_palette || []; - // Check if we're allowing native picker (set by "Use Color Picker" button) - if (palette.length > 0 && !colorPicker.dataset.allowNative) { - e.preventDefault(); - this.showPaletteQuickSelect(colorPickerWrapper, tabName, index, colorPicker); - } - // If no palette colors or allowNative is set, let native picker open - }; - colorPicker.addEventListener('click', clickHandler); - // Store handler reference for later removal if needed - colorPicker._clickHandler = clickHandler; - - colorPickerWrapper.appendChild(colorPicker); - - swatch.appendChild(preview); - swatch.appendChild(label); - swatch.appendChild(colorPickerWrapper); - swatch.addEventListener('click', (e) => { - // Don't trigger selection if clicking on the color picker - if (e.target !== colorPicker && !colorPicker.contains(e.target)) { - this.selectColor(tabName, index, hexColor); - } - }); - - palette.appendChild(swatch); - }); - } - - getPatternSettings(tabName, patternName) { - const light = this.state.lights[tabName]; - if (!light) return { - colors: ['#000000'], - delay: 100, - n1: 10, - n2: 10, - n3: 10, - n4: 10, - n5: 10, - n6: 10, - n7: 10, - n8: 10 - }; - - const lightSettings = light.settings; - if (!lightSettings.patterns) lightSettings.patterns = {}; - if (!lightSettings.patterns[patternName]) lightSettings.patterns[patternName] = {}; - - const patternSettings = lightSettings.patterns[patternName]; - // Fall back to global colors if pattern-specific colors don't exist - const globalColors = lightSettings.colors || ['#000000']; - return { - colors: patternSettings.colors || globalColors, - delay: patternSettings.delay || lightSettings.delay || 100, - n1: patternSettings.n1 || lightSettings.n1 || 10, - n2: patternSettings.n2 || lightSettings.n2 || 10, - n3: patternSettings.n3 || lightSettings.n3 || 10, - n4: patternSettings.n4 || lightSettings.n4 || 10, - n5: patternSettings.n5 || lightSettings.n5 || 10, - n6: patternSettings.n6 || lightSettings.n6 || 10, - n7: patternSettings.n7 || lightSettings.n7 || 10, - n8: patternSettings.n8 || lightSettings.n8 || 10 - }; - } - - async setPattern(tabName, patternName) { - const patternSettings = this.getPatternSettings(tabName, patternName); - - try { - const response = await fetch('/api/pattern', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - tab_name: tabName, - pattern: patternName, - delay: patternSettings.delay, - colors: patternSettings.colors, - n1: patternSettings.n1, - n2: patternSettings.n2, - n3: patternSettings.n3, - n4: patternSettings.n4, - n5: patternSettings.n5, - n6: patternSettings.n6, - n7: patternSettings.n7, - n8: patternSettings.n8 - }) - }); - - if (response.ok) { - // Update the pattern immediately in the state - if (this.state.lights[tabName]) { - this.state.lights[tabName].settings.pattern = patternName; - } - // Reload state from server to ensure consistency - await this.loadState(); - // Reload zone content to update UI - await this.loadTabContent(tabName); - } else { - const errorText = await response.text(); - console.error('Failed to set pattern:', errorText); - alert(`Failed to set pattern: ${errorText}`); - } - } catch (error) { - console.error('Failed to set pattern:', error); - } - } - - selectColor(tabName, index, hexColor) { - this.selectedColorIndex = index; - if (this.state.lights[tabName]) { - const pattern = this.state.lights[tabName].settings.pattern; - const patternSettings = this.getPatternSettings(tabName, pattern); - this.renderColorPalette(tabName, patternSettings.colors); - } - } - - async updateColorInPalette(tabName, index, hexColor) { - if (!this.currentTab || tabName !== this.currentTab) return; - - const pattern = this.state.lights[tabName].settings.pattern; - const patternSettings = this.getPatternSettings(tabName, pattern); - patternSettings.colors[index] = hexColor; - - // Update the preview - const palette = document.getElementById('color-palette'); - if (palette && palette.children[index]) { - const preview = palette.children[index].querySelector('.color-swatch-preview'); - if (preview) { - preview.style.backgroundColor = hexColor; - } - } - - // Send update to backend to persist changes - const rgb = this.hexToRgb(hexColor); - try { - const response = await fetch('/api/parameters', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - tab_name: this.currentTab, - red: rgb.r, - green: rgb.g, - blue: rgb.b, - color_index: index - }) - }); - - if (response.ok) { - // Reload state to ensure persistence - await this.loadState(); - // Re-render palette to reflect persisted state - const updatedPatternSettings = this.getPatternSettings(tabName, pattern); - this.renderColorPalette(tabName, updatedPatternSettings.colors); - } - } catch (error) { - console.error('Failed to update color:', error); - } - } - - - async updateBrightness() { - if (!this.currentTab) return; - - const brightness = parseInt(document.getElementById('brightness-slider').value) || 0; - - try { - await fetch('/api/parameters', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - tab_name: this.currentTab, - brightness: brightness - }) - }); - } catch (error) { - console.error('Failed to update brightness:', error); - } - } - - async updateDelay() { - if (!this.currentTab) return; - - const sliderValue = parseInt(document.getElementById('delay-slider').value); - const pattern = this.state.lights[this.currentTab].settings.pattern; - const patternConfig = this.state.patterns[pattern] || {}; - const minDelay = patternConfig.min_delay || 10; - const maxDelay = patternConfig.max_delay || 10000; - - try { - await fetch('/api/parameters', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - tab_name: this.currentTab, - delay_slider: sliderValue - }) - }); - } catch (error) { - console.error('Failed to update delay:', error); - } - } - - async updateNParams() { - if (!this.currentTab) return; - - const nParams = {}; - for (let i = 1; i <= 8; i++) { - nParams[`n${i}`] = parseInt(document.getElementById(`n${i}-input`).value) || 0; - } - - try { - await fetch('/api/parameters', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - tab_name: this.currentTab, - ...nParams - }) - }); - } catch (error) { - console.error('Failed to update n params:', error); - } - } - - debounceUpdate(key, callback) { - if (this.updateTimeouts[key]) { - clearTimeout(this.updateTimeouts[key]); - } - this.updateTimeouts[key] = setTimeout(callback, 100); - } - - delayToSlider(delayMs, minDelay = 10, maxDelay = 10000) { - if (delayMs <= minDelay) return 0; - if (delayMs >= maxDelay) return 1000; - if (minDelay === maxDelay) return 0; - return Math.floor(1000 * Math.log(delayMs / minDelay) / Math.log(maxDelay / minDelay)); - } - - sliderToDelay(sliderValue, minDelay = 10, maxDelay = 10000) { - if (sliderValue <= 0) return minDelay; - if (sliderValue >= 1000) return maxDelay; - if (minDelay === maxDelay) return minDelay; - return Math.floor(minDelay * Math.pow(maxDelay / minDelay, sliderValue / 1000)); - } - - updateDelayValue(sliderValue, minDelay, maxDelay) { - if (!minDelay || !maxDelay) { - const pattern = this.currentTab ? this.state.lights[this.currentTab]?.settings?.pattern : 'on'; - const patternConfig = this.state.patterns[pattern] || {}; - minDelay = patternConfig.min_delay || 10; - maxDelay = patternConfig.max_delay || 10000; - } - const delay = this.sliderToDelay(parseInt(sliderValue), minDelay, maxDelay); - document.getElementById('delay-value').textContent = `${delay} ms`; - } - - hexToRgb(hex) { - const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); - return result ? { - r: parseInt(result[1], 16), - g: parseInt(result[2], 16), - b: parseInt(result[3], 16) - } : { r: 0, g: 0, b: 0 }; - } - - rgbToHex(r, g, b) { - return `#${[r, g, b].map(x => { - const hex = x.toString(16); - return hex.length === 1 ? '0' + hex : hex; - }).join('')}`; - } - - showAddTabModal() { - document.getElementById('new-zone-name').value = ''; - document.getElementById('new-zone-ids').value = '1'; - document.getElementById('add-zone-modal').classList.add('active'); - } - - async createTab() { - const name = document.getElementById('new-zone-name').value.trim(); - const idsStr = document.getElementById('new-zone-ids').value.trim(); - const ids = idsStr.split(',').map(id => id.trim()).filter(id => id); - - if (!name) { - alert('Zone name cannot be empty'); - return; - } - - try { - const response = await fetch('/zones', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ name, ids }) - }); - - if (response.ok) { - await this.loadState(); - this.renderTabs(); - this.selectTab(name); - this.hideModal('add-zone-modal'); - } else { - const error = await response.json(); - alert(error.error || 'Failed to create zone'); - } - } catch (error) { - console.error('Failed to create zone:', error); - alert('Failed to create zone'); - } - } - - showEditTabModal() { - if (!this.currentTab) { - alert('Please select a zone first'); - return; - } - - const light = this.state.lights[this.currentTab]; - document.getElementById('edit-zone-name').value = this.currentTab; - document.getElementById('edit-zone-ids').value = light.names.join(', '); - document.getElementById('edit-zone-modal').classList.add('active'); - } - - async updateTab() { - const newName = document.getElementById('edit-zone-name').value.trim(); - const idsStr = document.getElementById('edit-zone-ids').value.trim(); - const ids = idsStr.split(',').map(id => id.trim()).filter(id => id); - - if (!newName) { - alert('Zone name cannot be empty'); - return; - } - - try { - const response = await fetch(`/zones/${this.currentTab}`, { - method: 'PUT', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ name: newName, ids }) - }); - - if (response.ok) { - await this.loadState(); - this.renderTabs(); - this.selectTab(newName); - this.hideModal('edit-zone-modal'); - } else { - const error = await response.json(); - alert(error.error || 'Failed to update zone'); - } - } catch (error) { - console.error('Failed to update zone:', error); - alert('Failed to update zone'); - } - } - - async deleteCurrentTab() { - if (!this.currentTab) { - alert('Please select a zone first'); - return; - } - - if (!confirm(`Are you sure you want to delete the zone '${this.currentTab}'?`)) { - return; - } - - try { - const response = await fetch(`/zones/${this.currentTab}`, { - method: 'DELETE' - }); - - if (response.ok) { - await this.loadState(); - this.renderTabs(); - if (this.state.zone_order.length > 0) { - this.selectTab(this.state.zone_order[0]); - } else { - this.currentTab = null; - document.getElementById('zone-content').innerHTML = '

No tabs available. Create a new zone to get started.

'; - } - } - } catch (error) { - console.error('Failed to delete zone:', error); - alert('Failed to delete zone'); - } - } - - async addColorToPalette() { - if (!this.currentTab) return; - - const pattern = this.state.lights[this.currentTab].settings.pattern; - const patternSettings = this.getPatternSettings(this.currentTab, pattern); - patternSettings.colors.push('#000000'); - this.selectedColorIndex = patternSettings.colors.length - 1; - this.renderColorPalette(this.currentTab, patternSettings.colors); - } - - async removeSelectedColor() { - if (!this.currentTab) return; - - const pattern = this.state.lights[this.currentTab].settings.pattern; - const patternSettings = this.getPatternSettings(this.currentTab, pattern); - - if (patternSettings.colors.length <= 1) { - alert('There must be at least one color in the palette'); - return; - } - - patternSettings.colors.splice(this.selectedColorIndex, 1); - if (this.selectedColorIndex >= patternSettings.colors.length) { - this.selectedColorIndex = patternSettings.colors.length - 1; - } - this.renderColorPalette(this.currentTab, patternSettings.colors); - } - - async showColorPalette() { - const modal = document.getElementById('color-palette-modal'); - modal.classList.add('active'); - // Update current profile display in palette modal - const profileNameDisplay = document.getElementById('palette-current-profile-name'); - if (profileNameDisplay) { - profileNameDisplay.textContent = this.state.current_profile || 'None'; - } - await this.loadProfilePalette(); - } - - async showProfiles() { - const modal = document.getElementById('profiles-modal'); - modal.classList.add('active'); - - await this.loadProfiles(); - await this.loadProfilePalette(); - } - - async loadProfiles() { - try { - const response = await fetch('/profiles'); - const profiles = await response.json(); - - const profilesList = document.getElementById('profiles-list'); - profilesList.innerHTML = ''; - - // Controllers return dict with IDs as keys, convert to array of names - const profileNames = Object.keys(profiles || {}); - const profileData = Object.values(profiles || {}); - - // Find current profile (first one or from settings) - const currentProfile = profileNames.length > 0 ? profileNames[0] : ''; - this.state.current_profile = currentProfile; - if (currentProfile && profiles[currentProfile]) { - this.state.color_palette = profiles[currentProfile].color_palette || []; - } - this.updateCurrentProfileDisplay(); - - if (profileNames.length === 0) { - profilesList.innerHTML = '

No profiles found

'; - } else { - profileNames.forEach(profileId => { - const profile = profiles[profileId]; - const profileName = profile.name || profileId; - const profileItem = document.createElement('div'); - profileItem.style.cssText = 'display: flex; align-items: center; justify-content: space-between; padding: 0.75rem; background-color: #3a3a3a; border-radius: 4px; margin-bottom: 0.5rem;'; - - const profileLabel = document.createElement('span'); - profileLabel.textContent = profileName; - if (profileId === currentProfile || profileName === currentProfile) { - profileLabel.textContent = `✓ ${profileName}`; - profileLabel.style.fontWeight = 'bold'; - profileLabel.style.color = '#FFD700'; - } - - const actionsContainer = document.createElement('div'); - actionsContainer.style.cssText = 'display: flex; gap: 0.5rem;'; - - const loadButton = document.createElement('button'); - loadButton.className = 'btn btn-small'; - loadButton.textContent = 'Load'; - loadButton.addEventListener('click', () => this.loadProfile(profileId)); - - const deleteButton = document.createElement('button'); - deleteButton.className = 'btn btn-small btn-danger'; - deleteButton.textContent = 'Delete'; - deleteButton.addEventListener('click', () => this.deleteProfile(profileId)); - - actionsContainer.appendChild(loadButton); - actionsContainer.appendChild(deleteButton); - - profileItem.appendChild(profileLabel); - profileItem.appendChild(actionsContainer); - profilesList.appendChild(profileItem); - }); - } - } catch (error) { - console.error('Failed to load profiles:', error); - alert('Failed to load profiles'); - } - } - - async deleteProfile(profileName) { - if (!confirm(`Delete profile '${profileName}'? This cannot be undone.`)) { - return; - } - - try { - const response = await fetch(`/profiles/${profileName}`, { - method: 'DELETE' - }); - - if (response.ok) { - await this.loadProfiles(); - // If the current profile was deleted, clear current state tabs - if (this.state.current_profile === profileName) { - this.state.current_profile = ''; - this.state.lights = {}; - this.state.zone_order = []; - this.renderTabs(); - document.getElementById('zone-content').innerHTML = '

No tabs available. Create a new zone to get started.

'; - this.updateCurrentProfileDisplay(); - } - } else { - const error = await response.json(); - alert(error.error || 'Failed to delete profile'); - } - } catch (error) { - console.error('Failed to delete profile:', error); - alert('Failed to delete profile'); - } - } - - async loadProfile(profileName) { - try { - const response = await fetch(`/profiles/${profileName}`, { - method: 'POST' - }); - - if (response.ok) { - await this.loadState(); - this.renderTabs(); - if (this.state.zone_order.length > 0) { - this.selectTab(this.state.zone_order[0]); - } else { - this.currentTab = null; - } - await this.loadProfiles(); // Refresh the profiles list - } else { - const error = await response.json(); - alert(error.error || 'Failed to load profile'); - } - } catch (error) { - console.error('Failed to load profile:', error); - alert('Failed to load profile'); - } - } - - async createProfile() { - const nameInput = document.getElementById('new-profile-name'); - const profileName = nameInput.value.trim(); - - if (!profileName) { - alert('Profile name cannot be empty'); - return; - } - - try { - const response = await fetch('/profiles', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ name: profileName }) - }); - - if (response.ok) { - nameInput.value = ''; - await this.loadProfiles(); - alert(`Profile '${profileName}' created successfully`); - } else { - const error = await response.json(); - alert(error.error || 'Failed to create profile'); - } - } catch (error) { - console.error('Failed to create profile:', error); - alert('Failed to create profile'); - } - } - - async loadProfilePalette() { - const currentProfile = this.state.current_profile; - if (!currentProfile) { - this.renderProfilePalette([]); - return; - } - - try { - // TODO: /profiles//palette endpoint doesn't exist, load profile and extract palette - const profileResponse = await fetch(`/profiles/${currentProfile}`); - const profile = await profileResponse.json(); - const response = { json: async () => ({ color_palette: profile.color_palette || [] }) }; - if (response.ok) { - const data = await response.json(); - this.renderProfilePalette(data.color_palette || []); - } else { - this.renderProfilePalette([]); - } - } catch (error) { - console.error('Failed to load profile palette:', error); - this.renderProfilePalette([]); - } - } - - renderProfilePalette(colors) { - // Render in profiles modal - const container = document.getElementById('profile-palette-container'); - if (container) { - container.innerHTML = ''; - colors.forEach((color, index) => { - const swatch = this.createPaletteSwatch(color, index); - container.appendChild(swatch); - }); - } - - // Render in color palette modal - const paletteContainer = document.getElementById('palette-container'); - if (paletteContainer) { - paletteContainer.innerHTML = ''; - colors.forEach((color, index) => { - const swatch = this.createPaletteSwatch(color, index); - paletteContainer.appendChild(swatch); - }); - } - } - - createPaletteSwatch(color, index) { - const swatch = document.createElement('div'); - swatch.style.cssText = 'width: 40px; height: 40px; background-color: ' + color + '; border: 2px solid #4a4a4a; border-radius: 4px; cursor: pointer; position: relative;'; - swatch.title = `Click to apply ${color} to selected color`; - - // Click to apply color to currently selected color in active zone - swatch.addEventListener('click', (e) => { - // Only apply if not clicking the remove button - if (e.target === swatch || !e.target.closest('button')) { - this.applyPaletteColorToSelected(color); - } - }); - - const removeBtn = document.createElement('button'); - removeBtn.textContent = '×'; - removeBtn.style.cssText = 'position: absolute; top: -8px; right: -8px; width: 20px; height: 20px; border-radius: 50%; background-color: #ff4444; color: white; border: none; cursor: pointer; font-size: 14px; line-height: 1; display: flex; align-items: center; justify-content: center; z-index: 10;'; - removeBtn.addEventListener('click', (e) => { - e.stopPropagation(); - this.removePaletteColor(index); - }); - - swatch.appendChild(removeBtn); - return swatch; - } - - applyPaletteColorToSelected(paletteColor) { - if (!this.currentTab) { - alert('No zone selected. Please select a zone first.'); - return; - } - - const pattern = this.state.lights[this.currentTab].settings.pattern; - const patternSettings = this.getPatternSettings(this.currentTab, pattern); - - if (patternSettings.colors.length === 0) { - alert('No colors in the current pattern. Add a color first.'); - return; - } - - // Apply the palette color to the currently selected color index - const selectedIndex = this.selectedColorIndex; - if (selectedIndex >= 0 && selectedIndex < patternSettings.colors.length) { - this.updateColorInPalette(this.currentTab, selectedIndex, paletteColor); - } else { - // If no color is selected, apply to the first color - this.updateColorInPalette(this.currentTab, 0, paletteColor); - } - } - - async addPaletteColor() { - const colorInput = document.getElementById('new-palette-color'); - if (!colorInput) return; - await this.addPaletteColorFromInput(colorInput); - } - - async addPaletteColorFromModal() { - const colorInput = document.getElementById('palette-new-color'); - if (!colorInput) return; - await this.addPaletteColorFromInput(colorInput); - } - - async addPaletteColorFromInput(colorInput) { - const color = colorInput.value; - const currentProfile = this.state.current_profile; - - if (!currentProfile) { - alert('No profile selected'); - return; - } - - try { - const currentPalette = this.state.color_palette || []; - if (currentPalette.includes(color)) { - alert('Color already in palette'); - return; - } - - const newPalette = [...currentPalette, color]; - // TODO: /profiles//palette endpoint doesn't exist, update profile directly - const profileResponse = await fetch(`/profiles/${currentProfile}`); - const profile = await profileResponse.json(); - profile.color_palette = colorPalette; - const response = await fetch(`/profiles/${currentProfile}`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ color_palette: newPalette }) - }); - - if (response.ok) { - this.state.color_palette = newPalette; - await this.loadProfilePalette(); - } else { - alert('Failed to add color to palette'); - } - } catch (error) { - console.error('Failed to add palette color:', error); - alert('Failed to add color to palette'); - } - } - - async removePaletteColor(index) { - const currentProfile = this.state.current_profile; - - if (!currentProfile) { - alert('No profile selected'); - return; - } - - try { - const currentPalette = this.state.color_palette || []; - const newPalette = currentPalette.filter((_, i) => i !== index); - - // TODO: /profiles//palette endpoint doesn't exist, update profile directly - const profileResponse = await fetch(`/profiles/${currentProfile}`); - const profile = await profileResponse.json(); - profile.color_palette = colorPalette; - const response = await fetch(`/profiles/${currentProfile}`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ color_palette: newPalette }) - }); - - if (response.ok) { - this.state.color_palette = newPalette; - await this.loadProfilePalette(); - } else { - alert('Failed to remove color from palette'); - } - } catch (error) { - console.error('Failed to remove palette color:', error); - alert('Failed to remove color from palette'); - } - } - - showPaletteQuickSelect(wrapper, tabName, colorIndex, colorPickerInput) { - const palette = this.state.color_palette || []; - if (palette.length === 0) { - // No palette colors, allow native picker to open - return; - } - - // Store context for the modal - this.quickPaletteContext = { - tabName: tabName, - colorIndex: colorIndex, - colorPickerInput: colorPickerInput - }; - - // Show the modal - const modal = document.getElementById('quick-palette-modal'); - modal.classList.add('active'); - - // Render palette colors in the modal - this.renderQuickPalette(palette); - } - - renderQuickPalette(palette) { - const container = document.getElementById('quick-palette-container'); - if (!container) return; - - container.innerHTML = ''; - - if (palette.length === 0) { - container.innerHTML = '

No colors in palette

'; - return; - } - - palette.forEach((color) => { - const colorBtn = document.createElement('div'); - colorBtn.style.cssText = `width: 80px; height: 80px; background-color: ${color}; border: 3px solid #4a4a4a; border-radius: 8px; cursor: pointer; flex-shrink: 0; position: relative; transition: transform 0.2s, border-color 0.2s;`; - colorBtn.title = color; - - // Add color hex label - const label = document.createElement('div'); - label.style.cssText = 'position: absolute; bottom: -20px; left: 0; right: 0; text-align: center; font-size: 0.7rem; color: #aaa;'; - label.textContent = color; - colorBtn.appendChild(label); - - colorBtn.addEventListener('mouseenter', () => { - colorBtn.style.transform = 'scale(1.1)'; - colorBtn.style.borderColor = '#6a5acd'; - }); - colorBtn.addEventListener('mouseleave', () => { - colorBtn.style.transform = 'scale(1)'; - colorBtn.style.borderColor = '#4a4a4a'; - }); - - colorBtn.addEventListener('click', () => { - if (this.quickPaletteContext) { - const { tabName, colorIndex, colorPickerInput } = this.quickPaletteContext; - this.updateColorInPalette(tabName, colorIndex, color); - colorPickerInput.value = color; - } - this.hideQuickPaletteModal(); - }); - - container.appendChild(colorBtn); - }); - } - - hideQuickPaletteModal() { - const modal = document.getElementById('quick-palette-modal'); - modal.classList.remove('active'); - this.quickPaletteContext = null; - } - - useColorPickerFromQuickPalette() { - if (this.quickPaletteContext && this.quickPaletteContext.colorPickerInput) { - const colorPickerInput = this.quickPaletteContext.colorPickerInput; - // Mark that we want to allow native picker - colorPickerInput.dataset.allowNative = 'true'; - // Temporarily remove the click handler - if (colorPickerInput._clickHandler) { - colorPickerInput.removeEventListener('click', colorPickerInput._clickHandler); - } - this.hideQuickPaletteModal(); - // Trigger native color picker after closing modal - setTimeout(() => { - // Try using showPicker() if available (modern browsers) - if (colorPickerInput.showPicker) { - colorPickerInput.showPicker().catch(() => { - // Fallback to click if showPicker fails - colorPickerInput.click(); - }); - } else { - // Fallback to click for older browsers - colorPickerInput.click(); - } - // Restore the click handler after a moment - setTimeout(() => { - if (colorPickerInput._clickHandler) { - colorPickerInput.addEventListener('click', colorPickerInput._clickHandler); - } - delete colorPickerInput.dataset.allowNative; - }, 500); - }, 200); - } - } - - async showPresets() { - const modal = document.getElementById('presets-modal'); - modal.classList.add('active'); - await this.loadPresets(); - } - - async loadPresets() { - try { - const response = await fetch('/presets'); - const data = await response.json(); - - // Controllers return the full dict, so use it directly - this.state.presets = data || {}; - - const presetsList = document.getElementById('presets-list'); - presetsList.innerHTML = ''; - - const presetNames = Object.keys(this.state.presets); - if (presetNames.length === 0) { - presetsList.innerHTML = '

No presets found. Create one to get started.

'; - } else { - presetNames.forEach(presetName => { - const preset = this.state.presets[presetName]; - const presetItem = document.createElement('div'); - presetItem.style.cssText = 'display: flex; align-items: center; justify-content: space-between; padding: 0.75rem; background-color: #3a3a3a; border-radius: 4px; margin-bottom: 0.5rem;'; - - const presetInfo = document.createElement('div'); - presetInfo.style.cssText = 'display: flex; flex-direction: column; gap: 0.25rem; flex: 1;'; - - const presetNameLabel = document.createElement('span'); - presetNameLabel.textContent = presetName; - presetNameLabel.style.fontWeight = 'bold'; - - const presetDetails = document.createElement('span'); - presetDetails.style.fontSize = '0.9em'; - presetDetails.style.color = '#aaa'; - presetDetails.textContent = `Pattern: ${preset.pattern} | Brightness: ${preset.brightness} | Delay: ${preset.delay}ms | Colors: ${preset.colors.length}`; - - presetInfo.appendChild(presetNameLabel); - presetInfo.appendChild(presetDetails); - - const actionsContainer = document.createElement('div'); - actionsContainer.style.cssText = 'display: flex; gap: 0.5rem;'; - - const applyButton = document.createElement('button'); - applyButton.className = 'btn btn-small btn-primary'; - applyButton.textContent = 'Apply'; - applyButton.addEventListener('click', () => this.applyPreset(presetName)); - - const editButton = document.createElement('button'); - editButton.className = 'btn btn-small'; - editButton.textContent = 'Edit'; - editButton.addEventListener('click', () => this.showPresetEditor(presetName)); - - const deleteButton = document.createElement('button'); - deleteButton.className = 'btn btn-small btn-danger'; - deleteButton.textContent = 'Delete'; - deleteButton.addEventListener('click', () => this.deletePreset(presetName)); - - actionsContainer.appendChild(applyButton); - actionsContainer.appendChild(editButton); - actionsContainer.appendChild(deleteButton); - - presetItem.appendChild(presetInfo); - presetItem.appendChild(actionsContainer); - presetsList.appendChild(presetItem); - }); - } - } catch (error) { - console.error('Failed to load presets:', error); - alert('Failed to load presets'); - } - } - - async applyPreset(presetName) { - if (!this.currentTab) { - alert('Please select a zone first'); - return; - } - - try { - // TODO: /presets//apply endpoint doesn't exist, using pattern/parameters directly - const preset = this.state.presets[presetName]; - if (!preset) { - alert('Preset not found'); - return; - } - - // Apply preset using the apply endpoint - const response = await fetch(`/api/presets/${presetName}/apply`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ - tab_name: this.currentTab - }) - }); - - if (response.ok) { - await this.loadState(); - await this.loadTabContent(this.currentTab); - this.hideModal('presets-modal'); - } else { - const error = await response.json(); - alert(`Failed to apply preset: ${error.error || 'Unknown error'}`); - } - } catch (error) { - console.error('Failed to apply preset:', error); - alert('Failed to apply preset'); - } - } - - async deletePreset(presetName) { - if (!confirm(`Delete preset '${presetName}'? This cannot be undone.`)) { - return; - } - - try { - const response = await fetch(`/presets/${presetName}`, { - method: 'DELETE' - }); - - if (response.ok) { - await this.loadPresets(); - } else { - const error = await response.json(); - alert(`Failed to delete preset: ${error.error || 'Unknown error'}`); - } - } catch (error) { - console.error('Failed to delete preset:', error); - alert('Failed to delete preset'); - } - } - - showPresetEditor(presetName = null) { - const modal = document.getElementById('preset-editor-modal'); - const title = document.getElementById('preset-editor-title'); - const nameInput = document.getElementById('preset-name-input'); - const patternSelect = document.getElementById('preset-pattern-select'); - const brightnessSlider = document.getElementById('preset-brightness-slider'); - const brightnessValue = document.getElementById('preset-brightness-value'); - const delayInput = document.getElementById('preset-delay-input'); - const n1Input = document.getElementById('preset-n1-input'); - const n2Input = document.getElementById('preset-n2-input'); - const n3Input = document.getElementById('preset-n3-input'); - const n4Input = document.getElementById('preset-n4-input'); - - // Store editing preset name - this.editingPresetName = presetName; - - // Populate pattern select - patternSelect.innerHTML = ''; - const patterns = Object.keys(this.state.patterns || {}); - patterns.forEach(pattern => { - const option = document.createElement('option'); - option.value = pattern; - option.textContent = pattern; - patternSelect.appendChild(option); - }); - - if (presetName && this.state.presets[presetName]) { - // Editing existing preset - title.textContent = 'Edit Preset'; - const preset = this.state.presets[presetName]; - nameInput.value = presetName; - nameInput.disabled = false; - patternSelect.value = preset.pattern; - brightnessSlider.value = preset.brightness; - brightnessValue.textContent = preset.brightness; - delayInput.value = preset.delay; - n1Input.value = preset.n1; - n2Input.value = preset.n2; - n3Input.value = preset.n3; - n4Input.value = preset.n4; - this.renderPresetColors(preset.colors); - } else { - // Creating new preset - title.textContent = 'Create Preset'; - nameInput.value = ''; - nameInput.disabled = false; - patternSelect.value = patterns[0] || 'on'; - brightnessSlider.value = 127; - brightnessValue.textContent = 127; - delayInput.value = 100; - n1Input.value = 10; - n2Input.value = 10; - n3Input.value = 10; - n4Input.value = 10; - this.renderPresetColors(['#000000']); - } - - this.selectedPresetColorIndex = 0; - modal.classList.add('active'); - } - - renderPresetColors(colors) { - const container = document.getElementById('preset-colors-container'); - container.innerHTML = ''; - - colors.forEach((color, index) => { - const colorWrapper = document.createElement('div'); - colorWrapper.style.cssText = 'position: relative;'; - - const colorSwatch = document.createElement('div'); - colorSwatch.style.cssText = `width: 50px; height: 50px; background-color: ${color}; border: 2px solid ${index === this.selectedPresetColorIndex ? '#FFD700' : '#4a4a4a'}; border-radius: 4px; cursor: pointer; position: relative;`; - colorSwatch.dataset.index = index; - colorSwatch.addEventListener('click', () => { - this.selectedPresetColorIndex = index; - this.renderPresetColors(colors); - }); - - const colorPicker = document.createElement('input'); - colorPicker.type = 'color'; - colorPicker.value = color; - colorPicker.style.cssText = 'position: absolute; top: 0; left: 0; width: 50px; height: 50px; opacity: 0; cursor: pointer;'; - colorPicker.addEventListener('change', (e) => { - colors[index] = e.target.value; - this.renderPresetColors(colors); - }); - - colorWrapper.appendChild(colorSwatch); - colorWrapper.appendChild(colorPicker); - container.appendChild(colorWrapper); - }); - - this.presetColors = colors; - } - - addPresetColor() { - const colorInput = document.getElementById('preset-new-color'); - const color = colorInput.value; - - if (!this.presetColors) { - this.presetColors = []; - } - - this.presetColors.push(color); - this.selectedPresetColorIndex = this.presetColors.length - 1; - this.renderPresetColors(this.presetColors); - } - - removePresetColor() { - if (!this.presetColors || this.presetColors.length === 0) { - return; - } - - if (this.selectedPresetColorIndex >= 0 && this.selectedPresetColorIndex < this.presetColors.length) { - this.presetColors.splice(this.selectedPresetColorIndex, 1); - if (this.selectedPresetColorIndex >= this.presetColors.length) { - this.selectedPresetColorIndex = Math.max(0, this.presetColors.length - 1); - } - this.renderPresetColors(this.presetColors); - } - } - - loadCurrentTabToPresetEditor() { - if (!this.currentTab || !this.state.lights[this.currentTab]) { - alert('Please select a zone first'); - return; - } - - const light = this.state.lights[this.currentTab]; - const settings = light.settings; - const pattern = settings.pattern || 'on'; - - // Get pattern-specific settings - const patternSettings = this.getPatternSettings(this.currentTab, pattern); - - const patternSelect = document.getElementById('preset-pattern-select'); - const brightnessSlider = document.getElementById('preset-brightness-slider'); - const brightnessValue = document.getElementById('preset-brightness-value'); - const delayInput = document.getElementById('preset-delay-input'); - const n1Input = document.getElementById('preset-n1-input'); - const n2Input = document.getElementById('preset-n2-input'); - const n3Input = document.getElementById('preset-n3-input'); - const n4Input = document.getElementById('preset-n4-input'); - - patternSelect.value = pattern; - brightnessSlider.value = settings.brightness || 127; - brightnessValue.textContent = settings.brightness || 127; - delayInput.value = patternSettings.delay || 100; - n1Input.value = patternSettings.n1 || 10; - n2Input.value = patternSettings.n2 || 10; - n3Input.value = patternSettings.n3 || 10; - n4Input.value = patternSettings.n4 || 10; - - this.renderPresetColors(patternSettings.colors || ['#000000']); - } - - async savePreset() { - const nameInput = document.getElementById('preset-name-input'); - const patternSelect = document.getElementById('preset-pattern-select'); - const brightnessSlider = document.getElementById('preset-brightness-slider'); - const delayInput = document.getElementById('preset-delay-input'); - const n1Input = document.getElementById('preset-n1-input'); - const n2Input = document.getElementById('preset-n2-input'); - const n3Input = document.getElementById('preset-n3-input'); - const n4Input = document.getElementById('preset-n4-input'); - - const presetName = nameInput.value.trim(); - if (!presetName) { - alert('Please enter a preset name'); - return; - } - - if (!this.presetColors || this.presetColors.length === 0) { - alert('Please add at least one color'); - return; - } - - const presetData = { - name: presetName, - pattern: patternSelect.value, - brightness: parseInt(brightnessSlider.value), - delay: parseInt(delayInput.value), - n1: parseInt(n1Input.value), - n2: parseInt(n2Input.value), - n3: parseInt(n3Input.value), - n4: parseInt(n4Input.value), - colors: this.presetColors - }; - - try { - let response; - if (this.editingPresetName) { - // Update existing preset - response = await fetch(`/presets/${this.editingPresetName}`, { - method: 'PUT', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(presetData) - }); - } else { - // Create new preset - response = await fetch('/presets', { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(presetData) - }); - } - - if (response.ok) { - await this.loadPresets(); - this.hideModal('preset-editor-modal'); - this.editingPresetName = null; - } else { - const error = await response.json(); - alert(`Failed to save preset: ${error.error || 'Unknown error'}`); - } - } catch (error) { - console.error('Failed to save preset:', error); - alert('Failed to save preset'); - } - } - - hideModal(modalId) { - document.getElementById(modalId).classList.remove('active'); - } -} - -// Initialize app when DOM is ready -document.addEventListener('DOMContentLoaded', () => { - new LightingController(); -}); - diff --git a/src/static/main.js b/src/static/main.js deleted file mode 100644 index 66b0287..0000000 --- a/src/static/main.js +++ /dev/null @@ -1,81 +0,0 @@ -import "./rgb-slider.js"; - -const ws = new WebSocket("ws://localhost:8000/ws"); - -ws.onopen = () => { - console.log("WebSocket connection established"); -}; - -ws.onclose = () => { - console.log("WebSocket connection closed"); -}; - -ws.onerror = (error) => { - console.error("WebSocket error:", error); -}; - -// Number of sliders (tabs) you want to create -const numTabs = 3; - -// Select the container for tabs and content -const tabsContainer = document.querySelector(".tabs"); -const tabContentContainer = document.querySelector(".zone-content"); - -// Create tabs dynamically -for (let i = 1; i <= numTabs; i++) { - // Create the zone button - const tabButton = document.createElement("button"); - tabButton.classList.add("zone"); - tabButton.id = `zone${i}`; - tabButton.textContent = `Zone ${i}`; - - // Add the zone button to the container - tabsContainer.appendChild(tabButton); - - // Create the corresponding zone content (RGB slider) - const tabContent = document.createElement("div"); - tabContent.classList.add("zone-pane"); - tabContent.id = `content${i}`; - const slider = document.createElement("rgb-slider"); - slider.id = i; - tabContent.appendChild(slider); - - // Add the zone content to the container - tabContentContainer.appendChild(tabContent); - - // Listen for color change on each RGB slider - slider.addEventListener("color-change", (e) => { - const { r, g, b } = e.detail; - console.log(`Color changed in zone ${i}:`, e.detail); - // Send RGB data to WebSocket server - if (ws.readyState === WebSocket.OPEN) { - const colorData = { r, g, b }; - ws.send(JSON.stringify(colorData)); - } - }); -} - -// Function to switch tabs -function switchTab(zoneId) { - const tabs = document.querySelectorAll(".zone"); - const tabContents = document.querySelectorAll(".zone-pane"); - - zones.forEach((zone) => zone.classList.remove("active")); - tabContents.forEach((content) => content.classList.remove("active")); - - // Activate the clicked zone and corresponding content - document.getElementById(zoneId).classList.add("active"); - document - .getElementById("content" + zoneId.replace("zone", "")) - .classList.add("active"); -} - -// Add event listeners to tabs -tabsContainer.addEventListener("click", (e) => { - if (e.target.classList.contains("zone")) { - switchTab(e.target.id); - } -}); - -// Initially set the first zone as active -switchTab("tab1"); diff --git a/src/static/rgb-slider.js b/src/static/rgb-slider.js deleted file mode 100644 index 0c986df..0000000 --- a/src/static/rgb-slider.js +++ /dev/null @@ -1,195 +0,0 @@ -// rgb-slider.js - -export class RGBSlider extends HTMLElement { - constructor() { - super(); - const shadow = this.attachShadow({ mode: "open" }); - - shadow.innerHTML = ` - - - -
-
- -
-
- - -
-
- - -
-
- - -
-
- -
-
- - -
-
- - -
-
- - -
-
-
- `; - - const get = (id) => shadow.querySelector(id); - this.r = get("#r"); - this.g = get("#g"); - this.b = get("#b"); - this.rInput = get("#rInput"); - this.gInput = get("#gInput"); - this.bInput = get("#bInput"); - this.preview = get("#preview"); - - const updateColor = (r, g, b) => { - this.preview.style.backgroundColor = `rgb(${r}, ${g}, ${b})`; - this.rInput.value = r; - this.gInput.value = g; - this.bInput.value = b; - this.dispatchEvent( - new CustomEvent("color-change", { - detail: { r, g, b }, - bubbles: true, - composed: true, - }), - ); - }; - - const syncFromSliders = () => { - const r = +this.r.value; - const g = +this.g.value; - const b = +this.b.value; - updateColor(r, g, b); - }; - - const syncFromInputs = () => { - const r = Math.min(255, Math.max(0, +this.rInput.value)); - const g = Math.min(255, Math.max(0, +this.gInput.value)); - const b = Math.min(255, Math.max(0, +this.bInput.value)); - this.r.value = r; - this.g.value = g; - this.b.value = b; - updateColor(r, g, b); - }; - - this.r.addEventListener("input", syncFromSliders); - this.g.addEventListener("input", syncFromSliders); - this.b.addEventListener("input", syncFromSliders); - - this.rInput.addEventListener("change", syncFromInputs); - this.gInput.addEventListener("change", syncFromInputs); - this.bInput.addEventListener("change", syncFromInputs); - } -} - -customElements.define("rgb-slider", RGBSlider); diff --git a/src/static/styles.css b/src/static/styles.css deleted file mode 100644 index 470677a..0000000 --- a/src/static/styles.css +++ /dev/null @@ -1,37 +0,0 @@ -/* General zone styles */ -.tabs { - display: flex; - justify-content: center; - margin-bottom: 20px; -} - -.zone { - padding: 10px 20px; - margin: 0 10px; - cursor: pointer; - background-color: #f1f1f1; - border: 1px solid #ccc; - border-radius: 4px; - transition: background-color 0.3s ease; -} - -.zone:hover { - background-color: #ddd; -} - -.zone.active { - background-color: #ccc; -} - -.zone-content { - display: flex; - justify-content: center; -} - -.zone-pane { - display: none; -} - -.zone-pane.active { - display: block; -} diff --git a/src/util/README.md b/src/util/README.md deleted file mode 100644 index 12d0020..0000000 --- a/src/util/README.md +++ /dev/null @@ -1,80 +0,0 @@ -# Driver message builder (`espnow_message`) - -This utility builds **v1** JSON payloads for LED drivers (serial/ESP-NOW bridge and Wi-Fi TCP). See **`docs/API.md`** for the full wire format. - -## Usage - -### Basic Message Building - -```python -from util.espnow_message import build_message, build_preset_dict, build_select_dict - -# Build a message with presets and select -presets = { - "red_blink": build_preset_dict({ - "pattern": "blink", - "colors": ["#FF0000"], - "delay": 200, - "brightness": 255, - "auto": True - }) -} - -select = build_select_dict({ - "device1": "red_blink" -}) - -message = build_message(presets=presets, select=select) -# Result: {"v": "1", "presets": {...}, "select": {...}} -``` - -### Building Select Messages with Step Synchronization - -```python -from util.espnow_message import build_message, build_select_dict - -# Select with step for synchronization -select = build_select_dict( - {"device1": "rainbow_preset", "device2": "rainbow_preset"}, - step_mapping={"device1": 10, "device2": 10} -) - -message = build_message(select=select) -# Result: {"v": "1", "select": {"device1": ["rainbow_preset", 10], "device2": ["rainbow_preset", 10]}} -``` - -### Converting Presets - -```python -from util.espnow_message import build_preset_dict, build_presets_dict - -# Single preset -preset = build_preset_dict({ - "name": "my_preset", - "pattern": "rainbow", - "colors": ["#FF0000", "#00FF00"], # Can be hex strings or RGB tuples - "delay": 100, - "brightness": 127, - "auto": False, - "n1": 2 -}) - -# Multiple presets -presets_data = { - "preset1": {"pattern": "on", "colors": ["#FF0000"]}, - "preset2": {"pattern": "blink", "colors": ["#00FF00"]} -} -presets = build_presets_dict(presets_data) -``` - -## API Specification - -See **`docs/API.md`** for REST routes, session scoping, and the compact preset keys on the wire. - -## Key Features - -- **Version Field**: All messages include `"v": "1"` for version tracking -- **Preset Format**: Presets use hex colour strings (`#RRGGBB`), not RGB tuples -- **Select Format**: Select values are always lists: `["preset_name"]` or `["preset_name", step]` -- **Colour Conversion**: Automatically converts RGB tuples to hex strings -- **Default Values**: Provides sensible defaults for missing fields diff --git a/src/util/device_status_broadcaster.py b/src/util/device_status_broadcaster.py deleted file mode 100644 index b6d5d4a..0000000 --- a/src/util/device_status_broadcaster.py +++ /dev/null @@ -1,52 +0,0 @@ -"""Push Wi-Fi driver connect/disconnect updates to browser WebSocket clients.""" - -import json -import threading -from typing import Any, Set - -# Threading lock: safe across asyncio tasks and avoids binding asyncio.Lock to the wrong loop. -_clients_lock = threading.Lock() -_clients: Set[Any] = set() - - -async def register_device_status_ws(ws: Any) -> None: - with _clients_lock: - _clients.add(ws) - - -async def unregister_device_status_ws(ws: Any) -> None: - with _clients_lock: - _clients.discard(ws) - - -async def broadcast_device_tcp_status(ip: str, connected: bool) -> None: - from models.wifi_ws_clients import normalize_tcp_peer_ip - - ip = normalize_tcp_peer_ip(ip) - if not ip: - return - msg = json.dumps({"type": "device_tcp", "ip": ip, "connected": bool(connected)}) - with _clients_lock: - targets = list(_clients) - dead = [] - for ws in targets: - try: - await ws.send(msg) - except Exception as exc: - dead.append(ws) - print(f"[device_status_broadcaster] ws.send failed: {exc!r}") - if dead: - with _clients_lock: - for ws in dead: - _clients.discard(ws) - - -async def broadcast_device_tcp_snapshot_to(ws: Any) -> None: - from models import wifi_ws_clients as tcp - - ips = tcp.list_connected_ips() - msg = json.dumps({"type": "device_tcp_snapshot", "connected_ips": ips}) - try: - await ws.send(msg) - except Exception as exc: - print(f"[device_status_broadcaster] snapshot send failed: {exc!r}") diff --git a/src/util/driver_delivery.py b/src/util/driver_delivery.py deleted file mode 100644 index a02eb64..0000000 --- a/src/util/driver_delivery.py +++ /dev/null @@ -1,224 +0,0 @@ -"""Deliver driver JSON messages over serial (ESP-NOW) and/or WebSocket (Wi-Fi drivers).""" - -import asyncio -import json - -from models.device import normalize_mac -from models.wifi_ws_clients import send_json_line_to_ip - -# Serial bridge (ESP32): broadcast MAC + this envelope → firmware unicasts ``body`` to each peer. -_SPLIT_MODE = "split" -_BROADCAST_MAC_HEX = "ffffffffffff" - - -def _split_serial_envelope(inner_json_str, peer_hex_list): - """One UART frame: broadcast dest + JSON {m:split, peers:[hex,...], body:}.""" - body = json.loads(inner_json_str) - env = {"m": _SPLIT_MODE, "peers": list(peer_hex_list), "body": body} - return json.dumps(env, separators=(",", ":")) - - -def _wifi_message_for_device(msg, device_name): - """ - For Wi-Fi WebSocket fanout, narrow a v1 select map to a single device name. - Returns the original message when no narrowing applies. - """ - if not device_name: - return msg - try: - body = json.loads(msg) - except Exception: - return msg - if not isinstance(body, dict): - return msg - select = body.get("select") - if not isinstance(select, dict): - return msg - if device_name not in select: - return msg - body["select"] = {device_name: select[device_name]} - return json.dumps(body, separators=(",", ":")) - - -def _combine_preset_chunks_for_wifi(chunk_messages): - """Merge chunked v1 preset messages into one v1 JSON string for Wi-Fi.""" - merged_presets = {} - save_flag = False - default_id = None - for msg in chunk_messages: - try: - body = json.loads(msg) - except Exception: - continue - if not isinstance(body, dict): - continue - presets = body.get("presets") - if isinstance(presets, dict): - merged_presets.update(presets) - if body.get("save"): - save_flag = True - if body.get("default") is not None: - default_id = body.get("default") - out = {"v": "1", "presets": merged_presets} - if save_flag: - out["save"] = True - if default_id is not None: - out["default"] = default_id - return json.dumps(out, separators=(",", ":")) - - -async def deliver_preset_broadcast_then_per_device( - sender, - chunk_messages, - target_macs, - devices_model, - default_id, - delay_s=0.1, -): - """ - Send preset definition chunks: ESP-NOW broadcast once per chunk; same chunk to each - Wi-Fi driver over WebSocket. If default_id is set, send a per-target default message - (unicast serial or WebSocket) with targets=[device name] for each registry entry. - """ - if not chunk_messages: - return 0 - - seen = set() - ordered = [] - for raw in target_macs: - m = normalize_mac(str(raw)) if raw else None - if not m or m in seen: - continue - seen.add(m) - ordered.append(m) - - wifi_ips = [] - for mac in ordered: - doc = devices_model.read(mac) - if doc and doc.get("transport") == "wifi" and doc.get("address"): - wifi_ips.append(str(doc["address"]).strip()) - - deliveries = 0 - wifi_combined_msg = _combine_preset_chunks_for_wifi(chunk_messages) - for msg in chunk_messages: - tasks = [sender.send(msg, addr=_BROADCAST_MAC_HEX)] - results = await asyncio.gather(*tasks, return_exceptions=True) - if results and results[0] is True: - deliveries += 1 - await asyncio.sleep(delay_s) - - for ip in wifi_ips: - if not ip: - continue - try: - if await send_json_line_to_ip(ip, wifi_combined_msg): - deliveries += 1 - except Exception as e: - print(f"[driver_delivery] Wi-Fi preset send failed: {e!r}") - await asyncio.sleep(delay_s) - - if default_id: - did = str(default_id) - for mac in ordered: - doc = devices_model.read(mac) or {} - name = str(doc.get("name") or "").strip() or mac - body = {"v": "1", "default": did, "save": True, "targets": [name]} - out = json.dumps(body, separators=(",", ":")) - if doc.get("transport") == "wifi" and doc.get("address"): - ip = str(doc["address"]).strip() - try: - if await send_json_line_to_ip(ip, out): - deliveries += 1 - except Exception as e: - print(f"[driver_delivery] default Wi-Fi send failed: {e!r}") - else: - try: - await sender.send(out, addr=mac) - deliveries += 1 - except Exception as e: - print(f"[driver_delivery] default serial failed: {e!r}") - await asyncio.sleep(delay_s) - - return deliveries - - -async def deliver_json_messages(sender, messages, target_macs, devices_model, delay_s=0.1): - """ - Send each message string to the bridge and/or Wi-Fi WebSocket clients. - - If target_macs is None or empty: one serial send per message (default/broadcast address). - Otherwise: Wi-Fi uses WebSocket in parallel. Multiple ESP-NOW peers are sent in **one** serial - write to the ESP32 (broadcast + split envelope); the bridge unicasts ``body`` to each - peer. A single ESP-NOW peer still uses one unicast serial frame. Wi-Fi and serial - tasks run together in one asyncio.gather. - - Returns (delivery_count, chunk_count) where chunk_count is len(messages). - """ - if not messages: - return 0, 0 - - if not target_macs: - deliveries = 0 - for msg in messages: - await sender.send(msg) - deliveries += 1 - await asyncio.sleep(delay_s) - return deliveries, len(messages) - - seen = set() - ordered_macs = [] - for raw in target_macs: - m = normalize_mac(str(raw)) if raw else None - if not m or m in seen: - continue - seen.add(m) - ordered_macs.append(m) - - deliveries = 0 - for msg in messages: - wifi_tasks = [] - espnow_hex = [] - for mac in ordered_macs: - doc = devices_model.read(mac) - if doc and doc.get("transport") == "wifi": - ip = doc.get("address") - if ip: - name = str(doc.get("name") or "").strip() - wifi_msg = _wifi_message_for_device(msg, name) - wifi_tasks.append(send_json_line_to_ip(ip, wifi_msg)) - else: - espnow_hex.append(mac) - - tasks = [] - espnow_peer_count = 0 - if len(espnow_hex) > 1: - tasks.append( - sender.send( - _split_serial_envelope(msg, espnow_hex), - addr=_BROADCAST_MAC_HEX, - ) - ) - espnow_peer_count = len(espnow_hex) - elif len(espnow_hex) == 1: - tasks.append(sender.send(msg, addr=espnow_hex[0])) - espnow_peer_count = 1 - - tasks.extend(wifi_tasks) - - if tasks: - results = await asyncio.gather(*tasks, return_exceptions=True) - n_serial = len(tasks) - len(wifi_tasks) - for i, r in enumerate(results): - if i < n_serial: - if r is True: - deliveries += espnow_peer_count - elif isinstance(r, Exception): - print(f"[driver_delivery] serial delivery failed: {r!r}") - else: - if r is True: - deliveries += 1 - elif isinstance(r, Exception): - print(f"[driver_delivery] Wi-Fi delivery failed: {r!r}") - - await asyncio.sleep(delay_s) - return deliveries, len(messages) diff --git a/src/util/driver_patterns.py b/src/util/driver_patterns.py deleted file mode 100644 index 80f76a4..0000000 --- a/src/util/driver_patterns.py +++ /dev/null @@ -1,53 +0,0 @@ -import os - -_ENV_PATTERNS_DIR = "LED_CONTROLLER_PATTERNS_DIR" - -def driver_patterns_dir(): - """Absolute path to driver pattern ``.py`` modules. - - If ``LED_CONTROLLER_PATTERNS_DIR`` is set to an existing directory, that wins - (for installs where ``led-driver`` is not next to this repo). Otherwise uses - ``/led-driver/src/patterns``. - """ - env = (os.environ.get(_ENV_PATTERNS_DIR) or "").strip() - if env and os.path.isdir(env): - return os.path.abspath(env) - here = os.path.dirname(os.path.abspath(__file__)) - root = os.path.abspath(os.path.join(here, "..", "..")) - return os.path.join(root, "led-driver", "src", "patterns") - - -def normalize_pattern_py_filename(name): - """Return a single ``*.py`` basename (no paths), or ``\"\"`` if invalid. - - Strips repeated ``.py`` suffixes so ``blink.py.py`` becomes ``blink.py``. - """ - if not isinstance(name, str): - return "" - s = name.strip() - if not s: - return "" - lower = s.lower() - while lower.endswith(".py"): - s = s[:-3] - s = s.strip() - lower = s.lower() - if not s: - return "" - if "/" in s or "\\" in s or ".." in s: - return "" - return s + ".py" - - -# Implemented in led-driver ``presets.py`` only — no separate ``patterns/*.py``. -FIRMWARE_BUILTIN_PATTERN_IDS = frozenset({"on", "off"}) - - -def is_firmware_builtin_pattern_module(name): - """True for ``on`` / ``off``, with or without a ``.py`` suffix.""" - if not isinstance(name, str): - return False - s = name.strip().lower() - while s.endswith(".py"): - s = s[:-3].strip() - return s in FIRMWARE_BUILTIN_PATTERN_IDS diff --git a/src/util/espnow_message.py b/src/util/espnow_message.py deleted file mode 100644 index c7176cc..0000000 --- a/src/util/espnow_message.py +++ /dev/null @@ -1,194 +0,0 @@ -""" -Message builder for LED driver API communication. - -Builds JSON messages according to the LED driver API specification -for sending presets and select commands over the transport (e.g. serial). -""" - -import json - - -def build_message(presets=None, select=None, save=False, default=None): - """ - Build an API message (presets and/or select) as a JSON string. - - Args: - presets: Dictionary mapping preset names to preset objects, or None - select: Dictionary mapping device names to select lists, or None - - Returns: - JSON string ready to send over the transport - - Example: - message = build_message( - presets={ - "red_blink": { - "pattern": "blink", - "colors": ["#FF0000"], - "delay": 200, - "brightness": 255, - "auto": True - } - }, - select={ - "device1": ["red_blink"] - } - ) - """ - message = { - "v": "1" - } - - if presets: - message["presets"] = presets - # When sending presets, optionally include a save flag so the - # led-driver can persist them. - if save: - message["save"] = True - - if select: - message["select"] = select - - if default is not None: - message["default"] = default - - return json.dumps(message) - - -def build_select_message(device_name, preset_name, step=None): - """ - Build a select message for a single device. - - Args: - device_name: Name of the device - preset_name: Name of the preset to select - step: Optional step value for synchronization - - Returns: - Dictionary with select field ready to use in build_message - - Example: - select = build_select_message("device1", "rainbow_preset", step=10) - message = build_message(select=select) - """ - select_list = [preset_name] - if step is not None: - select_list.append(step) - - return {device_name: select_list} - - -def build_preset_dict(preset_data): - """ - Convert preset data to API-compliant format. - - Args: - preset_data: Dictionary with preset fields (may include name, pattern, colors, etc.) - - Returns: - Dictionary with preset in API-compliant format (without name field) - - Example: - preset = build_preset_dict({ - "name": "red_blink", - "pattern": "blink", - "colors": ["#FF0000"], - "delay": 200, - "brightness": 255, - "auto": True, - "n1": 0, - "n2": 0, - "n3": 0, - "n4": 0, - "n5": 0, - "n6": 0 - }) - """ - # Ensure colors are in hex format - colors = preset_data.get("colors", preset_data.get("c", ["#FFFFFF"])) - if colors: - # Convert RGB tuples to hex strings if needed - if isinstance(colors[0], list) and len(colors[0]) == 3: - # RGB tuple format [r, g, b] - colors = [f"#{r:02x}{g:02x}{b:02x}" for r, g, b in colors] - elif not isinstance(colors[0], str): - # Handle other formats - convert to hex - colors = ["#FFFFFF"] - # Ensure all colors start with # - colors = [c if c.startswith("#") else f"#{c}" for c in colors] - else: - colors = ["#FFFFFF"] - - # Build payload using the short keys expected by led-driver - preset = { - "p": preset_data.get("pattern", preset_data.get("p", "off")), - "c": colors, - "d": preset_data.get("delay", preset_data.get("d", 100)), - "b": preset_data.get("brightness", preset_data.get("b", preset_data.get("br", 127))), - "a": preset_data.get("auto", preset_data.get("a", True)), - "n1": preset_data.get("n1", 0), - "n2": preset_data.get("n2", 0), - "n3": preset_data.get("n3", 0), - "n4": preset_data.get("n4", 0), - "n5": preset_data.get("n5", 0), - "n6": preset_data.get("n6", 0) - } - - return preset - - -def build_presets_dict(presets_data): - """ - Convert multiple presets to API-compliant format. - - Args: - presets_data: Dictionary mapping preset names to preset data - - Returns: - Dictionary mapping preset names to API-compliant preset objects - - Example: - presets = build_presets_dict({ - "red_blink": { - "pattern": "blink", - "colors": ["#FF0000"], - "delay": 200 - }, - "blue_pulse": { - "pattern": "pulse", - "colors": ["#0000FF"], - "delay": 100 - } - }) - """ - result = {} - for preset_name, preset_data in presets_data.items(): - result[preset_name] = build_preset_dict(preset_data) - return result - - -def build_select_dict(device_preset_mapping, step_mapping=None): - """ - Build a select dictionary mapping device names to select lists. - - Args: - device_preset_mapping: Dictionary mapping device names to preset names - step_mapping: Optional dictionary mapping device names to step values - - Returns: - Dictionary with select field ready to use in build_message - - Example: - select = build_select_dict( - {"device1": "rainbow_preset", "device2": "pulse_preset"}, - step_mapping={"device1": 10} - ) - message = build_message(select=select) - """ - select = {} - for device_name, preset_name in device_preset_mapping.items(): - select_list = [preset_name] - if step_mapping and device_name in step_mapping: - select_list.append(step_mapping[device_name]) - select[device_name] = select_list - return select diff --git a/src/util/message.py b/src/util/message.py deleted file mode 100644 index 7df8c38..0000000 --- a/src/util/message.py +++ /dev/null @@ -1,25 +0,0 @@ -"""JSON wire representation for controller messages (binary packing can replace later).""" - -from __future__ import annotations - -import json -from typing import Any, Dict, Union - - -class Message: - """Round-trip API dicts as compact UTF-8 JSON.""" - - def encode(self, data: Dict[str, Any]) -> bytes: - """Encode a JSON-serialisable mapping (typically a v1 API dict) to bytes.""" - return json.dumps(data, separators=(",", ":")).encode("utf-8") - - def decode(self, payload: Union[str, bytes, bytearray]) -> Dict[str, Any]: - """Decode UTF-8 JSON bytes or string into a dict.""" - if isinstance(payload, (bytes, bytearray)): - text = payload.decode("utf-8") - else: - text = payload - obj = json.loads(text) - if not isinstance(obj, dict): - raise TypeError("JSON root must be an object") - return obj diff --git a/tests/README.md b/tests/README.md deleted file mode 100644 index ec04e87..0000000 --- a/tests/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# Tests - -Tests for the LED Controller project live under **`tests/`** (pytest + legacy scripts). - -## Layout - -| Path | Role | -|------|------| -| `test_endpoints.py` | HTTP endpoint checks (**`LED_CONTROLLER_RUN_DEVICE_ENDPOINT_TESTS=1`**); **`test_zones`** / **`test_zone_edit_workflow`** hit **`/zones`** | -| `test_endpoints_pytest.py` | Pytest-style endpoint coverage | -| `test_browser.py` | Selenium UI flows (set **`LED_CONTROLLER_RUN_BROWSER_TESTS=1`** to run; uses **`test_zones_ui`** and legacy **`tabsManager`** JS aliases) | -| `test_pattern_ota_send.py` | Pattern OTA / Wi-Fi send helpers | -| `tcp_test_server.py`, `async_tcp_server.py` | TCP test doubles for driver protocol | -| `udp_server.py` | UDP discovery / hello test listener (port **8766**) | -| `ws.py` | WebSocket client checks | -| `p2p.py` | ESP-NOW–related helpers / experiments | -| `web.py` | Local dev static server (not the main app) | -| `conftest.py` | Pytest fixtures | -| `models/` | Model unit tests (`run_all.py`, `test_zone.py`, …) | - -## Running tests - -### Pytest (recommended) - -From the project root (with dev dependencies installed): - -```bash -pipenv run pytest tests/ -q -``` - -### Browser tests (real browser) - -```bash -python tests/test_browser.py -``` - -Requires **Selenium**, Chrome/Chromium, and a matching **ChromeDriver**. - -### Model tests only - -```bash -python tests/models/run_all.py -``` - -### Local static server - -`tests/web.py` serves files for quick UI experiments; it is **not** the Microdot app. For the real server use **`pipenv run run`** from the repo root. diff --git a/tests/async_tcp_server.py b/tests/async_tcp_server.py deleted file mode 100644 index 4ad99c5..0000000 --- a/tests/async_tcp_server.py +++ /dev/null @@ -1,182 +0,0 @@ -#!/usr/bin/env python3 -# Standalone async TCP server (stdlib only). Multiple simultaneous clients. -# No watchdog: runs on a full host (e.g. Raspberry Pi); ESP32 clients may use WDT. -# For RTT latency, clients may send lines like ``rtt 12345`` (ticks); they are echoed back. -# -# Run from anywhere (default: all IPv4 interfaces, port 9000): -# python3 async_tcp_server.py -# python3 async_tcp_server.py --port 9000 -# Localhost only: -# python3 async_tcp_server.py --host 127.0.0.1 -# -# Or from this directory: -# chmod +x async_tcp_server.py && ./async_tcp_server.py - -import argparse -import asyncio -import time - - -class _ClientRegistry: - """Track writers and broadcast newline-terminated lines to all clients.""" - - def __init__(self) -> None: - self._writers: set[asyncio.StreamWriter] = set() - - def add(self, writer: asyncio.StreamWriter) -> None: - self._writers.add(writer) - - def remove(self, writer: asyncio.StreamWriter) -> None: - self._writers.discard(writer) - - def count(self) -> int: - return len(self._writers) - - async def broadcast_line(self, line: str) -> None: - data = (line.rstrip("\r\n") + "\n").encode("utf-8") - for writer in list(self._writers): - try: - writer.write(data) - await writer.drain() - except Exception as e: - print(f"[tcp] broadcast failed, dropping client: {e}") - self._writers.discard(writer) - try: - writer.close() - await writer.wait_closed() - except Exception: - pass - - -async def _periodic_broadcast( - registry: _ClientRegistry, - interval_sec: float, - message: str, -) -> None: - while True: - await asyncio.sleep(interval_sec) - if registry.count() == 0: - continue - line = message.format(t=time.time()) - print(f"[tcp] broadcast to {registry.count()} client(s): {line!r}") - await registry.broadcast_line(line) - - -async def _handle_client( - reader: asyncio.StreamReader, - writer: asyncio.StreamWriter, - registry: _ClientRegistry, -) -> None: - peer = writer.get_extra_info("peername") - print(f"[tcp] connected: {peer}") - registry.add(writer) - try: - while not reader.at_eof(): - data = await reader.readline() - if not data: - break - message = data.decode("utf-8", errors="replace").rstrip("\r\n") - # Echo newline-delimited lines (simple test harness behaviour). - # Clients may send ``rtt `` for round-trip timing; echo unchanged. - t0 = time.perf_counter() - writer.write((message + "\n").encode("utf-8")) - await writer.drain() - if message.startswith("rtt "): - server_ms = (time.perf_counter() - t0) * 1000.0 - print( - f"[tcp] echoed rtt from {peer} " - f"(host write+drain ~{server_ms:.2f} ms)" - ) - finally: - registry.remove(writer) - writer.close() - await writer.wait_closed() - print(f"[tcp] disconnected: {peer}") - - -def _make_client_handler(registry: _ClientRegistry): - async def _handler( - reader: asyncio.StreamReader, - writer: asyncio.StreamWriter, - ) -> None: - await _handle_client(reader, writer, registry) - - return _handler - - -async def _run( - host: str, - port: int, - broadcast_interval: float | None, - broadcast_message: str, -) -> None: - registry = _ClientRegistry() - handler = _make_client_handler(registry) - server = await asyncio.start_server(handler, host, port) - print(f"[tcp] listening on {host}:{port} (Ctrl+C to stop)") - if broadcast_interval is not None and broadcast_interval > 0: - print( - f"[tcp] periodic broadcast every {broadcast_interval}s " - f"(use {{t}} in --message for unix time)" - ) - async with server: - tasks = [] - if broadcast_interval is not None and broadcast_interval > 0: - tasks.append( - asyncio.create_task( - _periodic_broadcast(registry, broadcast_interval, broadcast_message), - name="broadcast", - ) - ) - try: - if tasks: - await asyncio.gather(server.serve_forever(), *tasks) - else: - await server.serve_forever() - finally: - for t in tasks: - t.cancel() - for t in tasks: - try: - await t - except asyncio.CancelledError: - pass - - -def main() -> None: - parser = argparse.ArgumentParser( - description="Standalone asyncio TCP server (multiple connections).", - ) - parser.add_argument( - "--host", - default="0.0.0.0", - help="bind address (default: all IPv4 interfaces)", - ) - parser.add_argument("--port", type=int, default=9000, help="bind port") - parser.add_argument( - "--interval", - type=float, - default=5.0, - metavar="SEC", - help="seconds between broadcast lines to all clients (default: 5)", - ) - parser.add_argument( - "--message", - default="ping {t:.0f}", - help='broadcast line (newline added); use "{t}" for time.time() (default: %(default)s)', - ) - parser.add_argument( - "--no-broadcast", - action="store_true", - help="disable periodic broadcast (echo-only)", - ) - args = parser.parse_args() - interval = None if args.no_broadcast else args.interval - try: - asyncio.run(_run(args.host, args.port, interval, args.message)) - except KeyboardInterrupt: - print("\n[tcp] stopped") - - -if __name__ == "__main__": - main() diff --git a/tests/conftest.py b/tests/conftest.py deleted file mode 100644 index 7e71963..0000000 --- a/tests/conftest.py +++ /dev/null @@ -1,14 +0,0 @@ -from pathlib import Path -import sys - -PROJECT_ROOT = Path(__file__).resolve().parents[1] -SRC_PATH = PROJECT_ROOT / "src" -LIB_PATH = PROJECT_ROOT / "lib" - -# Last insert(0) wins: order must be (root, lib, src) so src/models wins over -# tests/models (same package name "models" on sys.path when pytest imports tests). -for p in (str(PROJECT_ROOT), str(LIB_PATH), str(SRC_PATH)): - if p in sys.path: - sys.path.remove(p) - sys.path.insert(0, p) - diff --git a/tests/device_ws_cycle.py b/tests/device_ws_cycle.py deleted file mode 100644 index 42f3b9c..0000000 --- a/tests/device_ws_cycle.py +++ /dev/null @@ -1,300 +0,0 @@ -#!/usr/bin/env python3 -"""Discover a Wi‑Fi LED driver via UDP hello, then drive it over WebSocket. - -1. Listens on UDP (default port 8766) for the same JSON line the firmware sends - (``v``, ``device_name``, ``mac``, ``type``: ``led``). -2. Opens ``ws://:/ws``. -3. Pushes a few test presets (``v``: ``"1"``) and cycles ``select`` for the - reported ``device_name``. - -The firmware sends UDP hello about one second **after** HTTP is listening, so -this script retries the WebSocket handshake by default. - -The device ``settings.json`` ``name`` must match ``device_name`` in the hello -(and in each ``select`` map). - -Examples:: - - pipenv install --dev - pipenv run python tests/device_ws_cycle.py - - pipenv run python tests/device_ws_cycle.py --timeout 60 --cycle-s 4 - - # Skip UDP; connect directly (set ``--device-name`` to the device's ``name``):: - pipenv run python tests/device_ws_cycle.py --host 192.168.1.42 --device-name a -""" - -from __future__ import annotations - -import argparse -import asyncio -import json -import socket -import sys - - -def _parse_hello_line(data: bytes) -> tuple[dict | None, bytes]: - line = data.split(b"\n", 1)[0].strip() - if not line: - return None, line - try: - obj = json.loads(line.decode("utf-8")) - except (UnicodeError, ValueError, TypeError): - return None, line - if not isinstance(obj, dict): - return None, line - return obj, line - - -def wait_for_udp_hello( - bind: str, - port: int, - timeout_s: float, - echo: bool, -) -> tuple[str, str, dict]: - """Block until a valid hello arrives. Returns (device_ip, device_name, hello_dict).""" - sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - try: - try: - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - except OSError: - pass - try: - sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) - except OSError: - pass - sock.bind((bind, port)) - sock.settimeout(timeout_s) - print( - f"UDP listening on {bind}:{port} (timeout {timeout_s}s) — " - "power the device or wait for hello…", - ) - while True: - try: - data, addr = sock.recvfrom(2048) - except socket.timeout as e: - raise SystemExit(f"No UDP hello before timeout: {e}") from e - peer_ip = addr[0] - parsed, raw_line = _parse_hello_line(data) - if parsed is None: - print(f"Ignored datagram from {peer_ip!r}: {raw_line!r}") - continue - if str(parsed.get("v") or "") != "1": - print(f"Ignored v={parsed.get('v')!r} from {peer_ip!r}") - continue - dev_type = parsed.get("type") or parsed.get("device_type") - if dev_type is not None and dev_type != "led": - print(f"Ignored type={dev_type!r} from {peer_ip!r}") - continue - name = str(parsed.get("device_name") or "").strip() - mac = parsed.get("mac") - if not name or not mac: - print( - f"Ignored hello without device_name/mac from {peer_ip!r}: {parsed!r}", - ) - continue - print( - f"Heard hello: ip={peer_ip!r} device_name={name!r} mac={mac!r}", - ) - if echo: - try: - sock.sendto(data, addr) - except OSError as e: - print(f"UDP echo to {addr} failed: {e!r}") - return peer_ip, name, parsed - finally: - try: - sock.close() - except OSError: - pass - - -PRESETS = { - "_test_on": {"p": "on", "c": [(0, 80, 200)]}, - "_test_blink": {"p": "blink", "d": 120, "b": 200, "c": [(255, 40, 0), (0, 40, 255)]}, - "_test_rainbow": {"p": "rainbow", "d": 12, "n1": 2, "a": True}, -} - -PRESET_ORDER = ["_test_on", "_test_blink", "_test_rainbow"] - - -async def cycle_presets( - host: str, - device_name: str, - ws_port: int, - ws_path: str, - cycle_s: float, - passes: int, - *, - ws_open_timeout_s: float, - ws_connect_retries: int, - ws_connect_retry_delay_s: float, -) -> None: - try: - import websockets - except ImportError as e: - raise SystemExit( - "Install websockets: pipenv install websockets (or: pip install websockets)" - ) from e - - path = ws_path if ws_path.startswith("/") else "/" + ws_path - uri = f"ws://{host}:{ws_port}{path}" - print(f"WebSocket connect {uri!r} …") - - n = max(1, ws_connect_retries) - last_err: BaseException | None = None - for attempt in range(n): - try: - async with websockets.connect( - uri, - open_timeout=ws_open_timeout_s, - ) as ws: - print("Connected.") - push = json.dumps({"v": "1", "presets": PRESETS}) - await ws.send(push) - print(f"Sent presets: {list(PRESETS.keys())}") - await asyncio.sleep(0.25) - - for p in range(passes): - print(f"--- pass {p + 1}/{passes} ---") - for pname in PRESET_ORDER: - sel = json.dumps({"v": "1", "select": {device_name: [pname]}}) - await ws.send(sel) - print(f" select {pname!r}") - await asyncio.sleep(cycle_s) - - print("Done.") - return - except (TimeoutError, OSError, ConnectionError) as e: - last_err = e - if attempt + 1 < n: - print( - f" connect failed ({e!r}), retry {attempt + 2}/{n} in " - f"{ws_connect_retry_delay_s}s …", - ) - await asyncio.sleep(ws_connect_retry_delay_s) - - raise TimeoutError( - f"WebSocket handshake failed after {n} attempts: {last_err!r}", - ) from last_err - - -def main() -> int: - parser = argparse.ArgumentParser( - description="UDP hello discovery + WebSocket preset cycle (led-driver)", - ) - parser.add_argument( - "--bind", - default="0.0.0.0", - help="UDP bind address (default 0.0.0.0)", - ) - parser.add_argument( - "-p", - "--udp-port", - type=int, - default=8766, - help="UDP listen port (default 8766)", - ) - parser.add_argument( - "--timeout", - type=float, - default=120.0, - help="Seconds to wait for first hello (default 120)", - ) - parser.add_argument( - "--no-echo", - action="store_true", - help="Do not echo the datagram back (firmware often uses wait_reply=False)", - ) - parser.add_argument( - "--host", - default="", - metavar="IP", - help="Skip UDP and use this device IP", - ) - parser.add_argument( - "--device-name", - default="", - metavar="NAME", - help="Device settings name for select map (required with --host if not default)", - ) - parser.add_argument( - "--ws-port", - type=int, - default=80, - help="Device WebSocket port (default 80)", - ) - parser.add_argument( - "--ws-path", - default="/ws", - help="WebSocket path (default /ws)", - ) - parser.add_argument( - "--cycle-s", - type=float, - default=3.0, - help="Seconds between select commands (default 3)", - ) - parser.add_argument( - "--passes", - type=int, - default=2, - help="How many full cycles through all test presets (default 2)", - ) - parser.add_argument( - "--ws-open-timeout", - type=float, - default=30.0, - help="Per-attempt WebSocket handshake timeout in seconds (default 30)", - ) - parser.add_argument( - "--ws-retries", - type=int, - default=15, - help="WebSocket connect attempts (default 15; use with device hello after HTTP)", - ) - parser.add_argument( - "--ws-retry-delay", - type=float, - default=1.0, - help="Seconds between WebSocket retries (default 1)", - ) - args = parser.parse_args() - - if args.host: - host = args.host.strip() - device_name = (args.device_name or "a").strip() - if not device_name: - print("--device-name is required when using a generic --host", file=sys.stderr) - return 1 - print(f"Using host {host!r} device_name {device_name!r} (no UDP)") - else: - host, device_name, _hello = wait_for_udp_hello( - args.bind, - args.udp_port, - args.timeout, - echo=not args.no_echo, - ) - - try: - asyncio.run( - cycle_presets( - host=host, - device_name=device_name, - ws_port=args.ws_port, - ws_path=args.ws_path, - cycle_s=args.cycle_s, - passes=max(1, args.passes), - ws_open_timeout_s=args.ws_open_timeout, - ws_connect_retries=args.ws_retries, - ws_connect_retry_delay_s=args.ws_retry_delay, - ) - ) - except KeyboardInterrupt: - print("\nInterrupted.") - return 130 - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tests/engine_tests/test_output_model.py b/tests/engine_tests/test_output_model.py deleted file mode 100644 index ed04ba2..0000000 --- a/tests/engine_tests/test_output_model.py +++ /dev/null @@ -1,37 +0,0 @@ -"""Output registry validation.""" - -import pytest - -from models.output import validate_output - - -def test_valid_records_are_normalised(): - doc = validate_output({"name": " wall ", "protocol": "DDP", "host": "10.0.0.5", "pixel_count": "300", - "color_order": "GRB"}) - assert doc["name"] == "wall" and doc["protocol"] == "ddp" and doc["pixel_count"] == 300 - assert doc["color_order"] == "grb" and doc["enabled"] is True and doc["port"] is None - art = validate_output({"name": "a", "protocol": "artnet", "universe": 0, "pixel_count": 170}) - assert art["universe"] == 0 and art["host"] == "" - sacn = validate_output({"name": "s", "protocol": "sacn", "universe": 5}) - assert sacn["universe"] == 5 - dmx = validate_output({"name": "d", "protocol": "dmx_serial", "serial_port": "/dev/ttyUSB0", - "channel": 1, "pixel_count": 170}) - assert dmx["dmx_mode"] == "enttec_pro" - - -@pytest.mark.parametrize("data,message", [ - ({"protocol": "ddp", "host": "x"}, "name"), - ({"name": "a", "protocol": "foo"}, "protocol"), - ({"name": "a", "protocol": "ddp"}, "host"), - ({"name": "a", "protocol": "dmx_serial"}, "serial_port"), - ({"name": "a", "protocol": "dmx_serial", "serial_port": "/dev/x", "dmx_mode": "bad"}, "dmx_mode"), - ({"name": "a", "protocol": "dmx_serial", "serial_port": "/dev/x", "channel": 500, "pixel_count": 10}, "pixel_count"), - ({"name": "a", "protocol": "sacn", "universe": 0}, "universe"), - ({"name": "a", "protocol": "artnet", "pixel_count": 0}, "pixel_count"), - ({"name": "a", "protocol": "artnet", "brightness": 300}, "brightness"), - ({"name": "a", "protocol": "artnet", "color_order": "rgbw"}, "color_order"), - ({"name": "a", "protocol": "ddp", "host": "h", "port": "abc"}, "port"), -]) -def test_invalid_records(data, message): - with pytest.raises(ValueError, match=message): - validate_output(data) diff --git a/tests/engine_tests/test_outputs.py b/tests/engine_tests/test_outputs.py deleted file mode 100644 index 7d6a84f..0000000 --- a/tests/engine_tests/test_outputs.py +++ /dev/null @@ -1,303 +0,0 @@ -"""Protocol driver tests: packet layout, universe splitting, frame prep, UDP, DMX, ESP32.""" - -import asyncio -import json -import socket -import struct - -import pytest - -from engine.outputs import open_output, parse_output_url -from engine.outputs.artnet import ArtNetOutput, build_artdmx, build_artsync -from engine.outputs.base import FrameOutput -from engine.outputs.ddp import DdpOutput, build_ddp_packets -from engine.outputs.dmx_serial import DmxSerialOutput, build_enttec_pro, dmx_universe -from engine.outputs.sacn import SacnOutput, build_e131, multicast_address - - -def frame(pixels, value=None): - if value is None: - return bytes(i % 256 for i in range(pixels * 3)) - return bytes(value) * pixels - - -# -- base ------------------------------------------------------------------- - -def test_prepare_pads_truncates_and_scales(): - out = FrameOutput({"pixel_count": 2}) - assert out.prepare(b"\x10\x20\x30") == b"\x10\x20\x30\x00\x00\x00" - assert out.prepare(bytes(range(9))) == bytes(range(6)) - half = FrameOutput({"pixel_count": 1, "brightness": 128}) - assert half.prepare(b"\xff\x80\x00") == bytes((128, 64, 0)) - assert out.prepare(b"\xff\xff\xff\xff\xff\xff", global_brightness=0) == bytes(6) - - -@pytest.mark.parametrize("order,expected", [ - ("rgb", b"\x01\x02\x03"), ("grb", b"\x02\x01\x03"), ("bgr", b"\x03\x02\x01"), - ("brg", b"\x03\x01\x02"), ("rbg", b"\x01\x03\x02"), ("gbr", b"\x02\x03\x01"), -]) -def test_color_order(order, expected): - assert FrameOutput({"pixel_count": 1, "color_order": order}).prepare(b"\x01\x02\x03") == expected - - -def test_reverse(): - out = FrameOutput({"pixel_count": 2, "reverse": True, "color_order": "grb"}) - assert out.prepare(b"\x01\x02\x03\x04\x05\x06") == b"\x05\x04\x06\x02\x01\x03" - - -def test_parse_output_url(): - cfg = parse_output_url("ddp://10.0.0.5:4049?pixels=300&order=grb") - assert cfg["protocol"] == "ddp" and cfg["host"] == "10.0.0.5" and cfg["port"] == 4049 - assert cfg["pixel_count"] == "300" and cfg["color_order"] == "grb" - out = open_output(cfg) - assert isinstance(out, DdpOutput) and out.pixel_count == 300 and out.port == 4049 - dmx = parse_output_url("dmx_serial:///dev/ttyUSB1?mode=open_dmx&channel=4") - assert dmx["serial_port"] == "/dev/ttyUSB1" and dmx["dmx_mode"] == "open_dmx" - assert isinstance(open_output(parse_output_url("e131://?universe=2")), SacnOutput) - with pytest.raises(ValueError): - open_output({"protocol": "nope"}) - - -# -- DDP -------------------------------------------------------------------- - -def test_ddp_packets_split_and_push(): - data = frame(600) # 1800 bytes -> 1440 + 360 - packets = build_ddp_packets(data, sequence=3) - assert len(packets) == 2 - for pkt, (offset, length, push) in zip(packets, [(0, 1440, False), (1440, 360, True)]): - flags, seq, dtype, dest, off, ln = struct.unpack(">BBBBIH", pkt[:10]) - assert flags & 0x40 and bool(flags & 0x01) == push - assert seq == 3 and dtype == 0x0B and dest == 1 - assert off == offset and ln == length == len(pkt) - 10 - assert b"".join(p[10:] for p in packets) == data - - -def test_ddp_three_packets_and_sequence_wraps(): - out = DdpOutput({"host": "127.0.0.1", "pixel_count": 1000}) - pkts = out.packets_for(frame(1000)) # 3000 bytes -> 3 packets - assert [struct.unpack(">I", p[4:8])[0] for p in pkts] == [0, 1440, 2880] - assert [p[0] & 0x01 for p in pkts] == [0, 0, 1] - seqs = [out.next_sequence() for _ in range(16)] - assert seqs[0] == 2 and 0 not in seqs and max(seqs) == 15 and seqs[-1] == 2 - - -# -- Art-Net ---------------------------------------------------------------- - -def test_artdmx_header(): - pkt = build_artdmx(0x1234, b"\x01\x02\x03", sequence=7) - assert pkt[:8] == b"Art-Net\x00" - assert struct.unpack("H", pkt[10:12])[0] == 14 - assert pkt[12] == 7 and pkt[13] == 0 - assert pkt[14] == 0x34 and pkt[15] == 0x12 # SubUni, Net - assert struct.unpack(">H", pkt[16:18])[0] == 4 # padded to even - assert pkt[18:] == b"\x01\x02\x03\x00" - - -def test_artnet_universe_split(): - out = ArtNetOutput({"host": "127.0.0.1", "universe": 3, "pixel_count": 400}) - pkts = out.packets_for(out.prepare(frame(400))) - assert [p[14] for p in pkts] == [3, 4, 5] - assert [struct.unpack(">H", p[16:18])[0] for p in pkts] == [510, 510, 180] - assert len({p[12] for p in pkts}) == 1 - - -def test_artnet_sequence_wrap_and_sync(): - out = ArtNetOutput({"host": "127.0.0.1", "sync": True, "pixel_count": 1}) - seqs = [out.next_sequence() for _ in range(256)] - assert seqs[0] == 1 and seqs[254] == 255 and seqs[255] == 1 - pkts = out.packets_for(out.prepare(frame(1))) - assert pkts[-1] == build_artsync() - assert struct.unpack("H", pkt[16:18])[0] - assert root_fl >> 12 == 0x7 and root_fl & 0x0FFF == len(pkt) - 16 - assert struct.unpack(">I", pkt[18:22])[0] == 4 - assert pkt[22:38] == cid - framing_fl = struct.unpack(">H", pkt[38:40])[0] - assert framing_fl & 0x0FFF == len(pkt) - 38 - assert struct.unpack(">I", pkt[40:44])[0] == 2 - assert pkt[44:48] == b"test" - assert pkt[108] == 100 # priority - assert pkt[111] == 9 # sequence - assert struct.unpack(">H", pkt[113:115])[0] == 300 - dmp_fl = struct.unpack(">H", pkt[115:117])[0] - assert dmp_fl & 0x0FFF == len(pkt) - 115 - assert pkt[117] == 0x02 and pkt[118] == 0xA1 - assert struct.unpack(">H", pkt[123:125])[0] == 4 # start code + 3 slots - assert pkt[125] == 0 and pkt[126:] == b"\x0a\x0b\x0c" - - -def test_sacn_multicast_split_and_stable_cid(): - assert multicast_address(1) == "239.255.0.1" - assert multicast_address(300) == "239.255.1.44" - out = SacnOutput({"name": "roof", "universe": 1, "pixel_count": 200}) - pkts = out.packets_for(out.prepare(frame(200))) - assert [addr for _p, addr in pkts] == [("239.255.0.1", 5568), ("239.255.0.2", 5568)] - again = SacnOutput({"name": "roof", "universe": 1, "pixel_count": 200}) - assert out.cid == again.cid and len(out.cid) == 16 - pkts2 = out.packets_for(out.prepare(frame(200))) - assert pkts2[0][0][111] == (pkts[0][0][111] + 1) & 0xFF - uni = SacnOutput({"host": "10.0.0.9", "universe": 5, "pixel_count": 1}) - assert uni.packets_for(uni.prepare(frame(1)))[0][1] == ("10.0.0.9", 5568) - - -# -- UDP round trip --------------------------------------------------------- - -def _udp_receiver(): - sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - sock.bind(("127.0.0.1", 0)) - sock.settimeout(2.0) - return sock - - -@pytest.mark.parametrize("cls,pixels,expected_packets", [(DdpOutput, 600, 2), (ArtNetOutput, 400, 3)]) -def test_udp_round_trip(cls, pixels, expected_packets): - recv = _udp_receiver() - port = recv.getsockname()[1] - - async def go(): - out = cls({"host": "127.0.0.1", "port": port, "pixel_count": pixels}) - await out.send(frame(pixels)) - await asyncio.sleep(0.05) - if out._transport: - out._transport.close() - return out - - out = asyncio.run(go()) - got = [recv.recvfrom(2048)[0] for _ in range(expected_packets)] - recv.close() - assert out.stats.frames == 1 and out.stats.packets == expected_packets and out.stats.errors == 0 - if cls is DdpOutput: - assert b"".join(p[10:] for p in got) == frame(pixels) - else: - assert got[0][:8] == b"Art-Net\x00" - - -# -- USB-DMX ---------------------------------------------------------------- - -class FakeSerial: - def __init__(self, output): - self.writes = [] - self.breaks = [] - self.closed = False - self._bc = False - - @property - def break_condition(self): - return self._bc - - @break_condition.setter - def break_condition(self, value): - self._bc = value - self.breaks.append(value) - - def write(self, data): - self.writes.append(bytes(data)) - - def close(self): - self.closed = True - - -def test_dmx_universe_channel_offset(): - u = dmx_universe(b"\x01\x02\x03", channel=10) - assert len(u) == 512 and u[9:12] == b"\x01\x02\x03" and u[:9] == bytes(9) - assert dmx_universe(bytes(600), channel=1) == bytes(512) - - -def test_enttec_pro_framing(): - pkt = build_enttec_pro(bytes(512)) - assert pkt[0] == 0x7E and pkt[1] == 6 - assert struct.unpack("= 512 # close() sends black - - -# -- ESP32 preset output -------------------------------------------------------- - -class FakeSender: - def __init__(self): - self.sent = [] - - async def send(self, data, addr=None): - self.sent.append((data, addr)) - return True - - -class FakeDevices(dict): - def read(self, mac): - return self.get(mac) - - -def test_driver_output_matches_presets_push(): - from engine.outputs.driver import DriverOutput, resolve_device_macs - - devices = FakeDevices({ - "aaaaaaaaaaaa": {"name": "roof", "transport": "espnow", "address": "aaaaaaaaaaaa"}, - "bbbbbbbbbbbb": {"name": "roof", "transport": "espnow", "address": "bbbbbbbbbbbb"}, - "cccccccccccc": {"name": "dj", "transport": "espnow", "address": "cccccccccccc"}, - }) - assert resolve_device_macs(["roof", "roof", "nobody"], devices) == [ - ("roof", "aaaaaaaaaaaa"), ("roof", "bbbbbbbbbbbb")] - - sender = FakeSender() - out = DriverOutput(["dj"], sender_getter=lambda: sender, devices=devices, delay_s=0) - payload = {"p": "rainbow", "c": ["#FF0000"], "d": 100, "b": 32, "a": True, - "n1": 2, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0} - delivered = asyncio.run(out.apply("3", payload)) - assert delivered == 2 - msgs = [json.loads(d) for d, _a in sender.sent] - assert [a for _d, a in sender.sent] == ["cccccccccccc", "cccccccccccc"] - # Same two-message sequence presets.js sends via /presets/push (without save). - assert msgs[0] == {"v": "1", "presets": {"3": payload}} - assert msgs[1] == {"v": "1", "select": {"dj": ["3"]}} - - -def test_driver_output_without_sender_records_error(): - from engine.outputs.driver import DriverOutput - - out = DriverOutput(["dj"], sender_getter=lambda: None, devices=FakeDevices()) - assert asyncio.run(out.apply("1", {"p": "on"})) == 0 - assert out.stats.errors == 1 diff --git a/tests/engine_tests/test_player.py b/tests/engine_tests/test_player.py deleted file mode 100644 index f40ab23..0000000 --- a/tests/engine_tests/test_player.py +++ /dev/null @@ -1,242 +0,0 @@ -"""ZonePlayer + Engine: frames reach pixel outputs, presets reach ESP32 drivers.""" - -import asyncio - -import pytest - -from engine.core import Engine, EngineError -from engine.outputs.base import FrameOutput -from engine.pattern_loader import PatternLibrary -from engine.player import ZonePlayer -from engine.zone_targets import ZoneTargets, resolve_zone - -LIB = PatternLibrary() - - -class RecordingOutput(FrameOutput): - protocol = "test" - keepalive_s = 0.2 - - def __init__(self, cfg): - super().__init__(cfg) - self.sent = [] - self.levels = [] - self.closed = False - - async def send(self, rgb, global_brightness=255): - self.levels.append(global_brightness) - await super().send(rgb, global_brightness) - - async def _send_prepared(self, payload): - self.sent.append(payload) - - async def close(self): - await super().close() - self.closed = True - - -class RecordingDriver: - kind = "preset" - - def __init__(self, names): - self.names = names - self.applied = [] - self.closed = False - - async def apply(self, preset_id, payload): - self.applied.append((preset_id, payload)) - - async def close(self): - self.closed = True - - def status(self): - return {"name": ",".join(self.names), "kind": "preset", "frames": len(self.applied), - "packets": 0, "errors": 0, "last_error": None} - - -def make_player(cfgs, drivers=(), brightness=255): - made = {"outputs": [], "driver": None} - - def output_factory(cfg): - out = RecordingOutput(cfg) - made["outputs"].append(out) - return out - - def driver_factory(names): - made["driver"] = RecordingDriver(names) - return made["driver"] - - targets = ZoneTargets("z1", cfgs, list(drivers)) - player = ZonePlayer(targets, LIB, lambda: brightness, output_factory=output_factory, - driver_factory=driver_factory) - return player, made - - -def test_frames_split_per_output_offset_and_brightness(): - async def go(): - player, made = make_player( - [{"name": "a", "pixel_count": 2, "fps": 60}, - {"name": "b", "pixel_count": 1, "pixel_offset": 2, "color_order": "grb", "fps": 60}], - brightness=128, - ) - assert player.targets.frame_length == 3 - await player.start() - await player.apply("1", {"p": "on", "c": ["#ff8000"], "b": 255}) - await asyncio.sleep(0.15) - await player.stop() - return made - - made = asyncio.run(go()) - a, b = made["outputs"] - assert a.sent[0] == bytes((128, 64, 0)) * 2 - assert b.sent[0] == bytes((64, 128, 0)) # grb - assert set(a.levels[:-1]) == {128} # last send is the black frame from close() - assert a.closed and b.closed and a.sent[-1] == bytes(6) # black on stop - - -def test_animated_pattern_streams_and_keepalive_resends_static(): - async def go(): - player, made = make_player([{"name": "a", "pixel_count": 8, "fps": 60}]) - await player.start() - await player.apply("1", {"p": "rainbow", "c": [], "d": 10, "b": 255, "n1": 8}) - await asyncio.sleep(0.4) - rainbow_frames = len(made["outputs"][0].sent) - await player.apply("2", {"p": "on", "c": ["#00ff00"], "b": 255}) - await asyncio.sleep(0.1) - before = len(made["outputs"][0].sent) - await asyncio.sleep(0.5) # static frame -> keepalive resends (0.2 s) - after = len(made["outputs"][0].sent) - await player.stop() - return rainbow_frames, before, after, made - - rainbow_frames, before, after, made = asyncio.run(go()) - assert rainbow_frames >= 10 - assert after - before >= 2 - assert made["outputs"][0].sent[before] == bytes((0, 255, 0)) * 8 - - -def test_mixed_zone_drives_esp32_and_pixels_together(): - async def go(): - player, made = make_player([{"name": "ddp", "pixel_count": 4}], drivers=["dj"]) - await player.start() - await player.apply("7", {"p": "on", "c": ["#ffffff"], "b": 255}) - await asyncio.sleep(0.1) - status = player.status() - await player.stop() - return made, status - - made, status = asyncio.run(go()) - assert made["driver"].applied == [("7", {"p": "on", "c": ["#ffffff"], "b": 255})] - assert made["outputs"][0].sent - assert status["preset_id"] == "7" and len(status["outputs"]) == 2 - assert made["driver"].closed - - -def test_drivers_false_skips_esp32(): - async def go(): - player, made = make_player([{"name": "ddp", "pixel_count": 1}], drivers=["dj"]) - await player.start() - await player.apply("1", {"p": "on", "c": ["#ffffff"], "b": 255}, drivers=False) - await asyncio.sleep(0.05) - await player.stop() - return made - - made = asyncio.run(go()) - assert made["driver"].applied == [] and made["outputs"][0].sent - - -def test_driver_only_zone_has_no_render_thread(): - async def go(): - player, made = make_player([], drivers=["roof"]) - await player.start() - await player.apply("1", {"p": "rainbow"}) - await player.stop() - return player, made - - player, made = asyncio.run(go()) - assert player.renderer is None and made["driver"].applied - - -# -- Engine -------------------------------------------------------------------- - -class FakeZones(dict): - def read(self, id): - return self.get(str(id)) - - -class FakeOutputs(dict): - def by_name(self, name): - return [o for o in self.values() if o.get("name") == name] - - -def test_resolve_zone_splits_outputs_and_drivers(): - zones = FakeZones({"1": {"names": ["roof", "wall", "wall", "dj"]}}) - outputs = FakeOutputs({ - "1": {"id": "1", "name": "wall", "pixel_count": 100, "enabled": True}, - "2": {"id": "2", "name": "wall", "pixel_count": 50, "pixel_offset": 100, "enabled": True}, - "3": {"id": "3", "name": "dj", "pixel_count": 10, "enabled": False}, - }) - t = resolve_zone("1", zones, outputs) - assert [c["id"] for c in t.frame_cfgs] == ["1", "2"] - assert t.driver_names == ["roof", "dj"] # disabled output falls back to device name - assert t.frame_length == 150 - assert resolve_zone("9", zones, outputs) is None - - -def make_engine(targets_by_zone, payloads): - created = [] - - def factory(targets, library, brightness): - player, made = make_player(targets.frame_cfgs, targets.driver_names) - created.append((player, made)) - return player - - eng = Engine( - library=LIB, - zone_resolver=lambda zid: targets_by_zone.get(zid), - payload_resolver=lambda pid: payloads.get(pid), - player_factory=factory, - sequences_model=FakeSequences(), - ) - return eng, created - - -class FakeSequences(dict): - def read(self, id): - return self.get(str(id)) - - def update(self, id, data): - if str(id) not in self: - return False - self[str(id)].update(data) - return True - - def list(self): - return list(self.keys()) - - -def test_engine_play_reuses_player_and_rebuilds_on_target_change(): - targets = {"1": ZoneTargets("1", [{"name": "a", "pixel_count": 2}], ["dj"])} - payloads = {"10": {"p": "on", "c": ["#ff0000"]}, "11": {"p": "off"}} - - async def go(): - eng, created = make_engine(targets, payloads) - await eng.play("1", "10") - await eng.play("1", "11") - assert len(created) == 1 - targets["1"] = ZoneTargets("1", [{"name": "a", "pixel_count": 3}], ["dj"]) - await eng.play("1", "10") - assert len(created) == 2 and created[0][1]["outputs"][0].closed - with pytest.raises(EngineError): - await eng.play("1", "missing") - with pytest.raises(EngineError): - await eng.play("nozone", "10") - status = eng.status() - assert status["zones"]["1"]["preset_id"] == "10" - assert await eng.stop("1") is True - assert eng.status()["zones"] == {} - await eng.stop_all() - return created - - created = asyncio.run(go()) - assert [p for p, _ in created[0][1]["driver"].applied] == ["10", "11"] diff --git a/tests/engine_tests/test_renderer.py b/tests/engine_tests/test_renderer.py deleted file mode 100644 index caa1b8a..0000000 --- a/tests/engine_tests/test_renderer.py +++ /dev/null @@ -1,119 +0,0 @@ -"""The unchanged led-driver patterns run under the CPython shim.""" - -import threading -import time - -import pytest - -from engine import mpcompat -from engine.pattern_loader import PatternLibrary -from engine.renderer import Renderer, RenderThread - -LIB = PatternLibrary() -NUM_LEDS = 24 - - -def payload(pattern, **kw): - base = {"p": pattern, "c": ["#ff0000", "#00ff00", "#0000ff"], "d": 40, "b": 255, "a": True, - "n1": 5, "n2": 5, "n3": 5, "n4": 5, "n5": 0, "n6": 0} - base.update(kw) - return base - - -def test_library_loads_every_driver_pattern(): - assert LIB.errors == {} - assert LIB.preset_class.__module__ == "led_driver_preset" - assert len(LIB.classes) >= 30 - assert {"rainbow", "pulse", "chase", "on", "off"} <= set(LIB.ids()) - - -@pytest.mark.parametrize("pattern", sorted(LIB.classes)) -def test_pattern_renders(pattern): - r = Renderer(LIB, NUM_LEDS) - frames = r.render_virtual("1", payload(pattern), ticks=200, tick_ms=5) - assert r.error is None - assert frames, f"{pattern} wrote no frames" - assert all(len(f) == NUM_LEDS * 3 for f in frames) - - -@pytest.mark.parametrize("pattern", ["rainbow", "colour_cycle", "plasma", "aurora", "scanner", "transition"]) -def test_animated_patterns_change(pattern): - frames = Renderer(LIB, NUM_LEDS).render_virtual("1", payload(pattern), ticks=400, tick_ms=5) - assert len(set(frames)) > 3 - - -def test_on_and_off_builtins(): - r = Renderer(LIB, 3) - frames = r.render_virtual("1", {"p": "on", "c": ["#ff8000"], "b": 255}, ticks=5) - assert frames == [bytes((255, 128, 0)) * 3] and r.generator is None - frames = r.render_virtual("2", {"p": "off"}, ticks=5) - assert frames == [bytes(9)] - - -def test_preset_brightness_applies_like_device(): - frames = Renderer(LIB, 1).render_virtual("1", {"p": "on", "c": ["#ffffff"], "b": 128}, ticks=1) - assert frames[-1] == bytes((128, 128, 128)) - - -def test_step_reset_rules_match_presets_select(): - r = Renderer(LIB, 4) - r.render_virtual("1", payload("rainbow", n1=10), ticks=100, tick_ms=50) - assert r.driver.step != 0 - kept = r.driver.step - r.set_preset("1", payload("rainbow", n1=10)) # same preset again = beat, keeps step - assert r.driver.step == kept - r.set_preset("2", payload("rainbow")) # different preset resets - assert r.driver.step == 0 - - -def test_unknown_pattern_goes_dark(): - r = Renderer(LIB, 2) - frames = r.render_virtual("1", {"p": "does_not_exist"}, ticks=3) - assert r.error and frames == [bytes(6)] - - -def test_virtual_clock_sleep_does_not_block(): - started = time.monotonic() - frames = Renderer(LIB, 4).render_virtual("1", payload("heartbeat", d=500), ticks=50) - assert time.monotonic() - started < 2.0 - assert len(frames) > 10 - - -def test_render_thread_real_clock_and_hot_swap(): - got = [] - lock = threading.Lock() - - def on_frame(f): - with lock: - got.append(f) - - r = Renderer(LIB, 4, on_frame=on_frame) - t = RenderThread(r).start() - try: - t.apply("1", payload("rainbow", d=10, n1=8)) - time.sleep(0.3) - with lock: - n_rainbow = len(got) - assert n_rainbow >= 5 - t.apply("2", {"p": "on", "c": ["#0000ff"], "b": 255}) - time.sleep(0.1) - with lock: - assert got[-1] == bytes((0, 0, 255)) * 4 - assert r.pattern_id == "on" - finally: - t.stop() - assert not t._thread.is_alive() - - -def test_shim_installed_as_utime(): - import sys - assert getattr(sys.modules["utime"], "__led_controller_shim__", False) - clock = mpcompat.VirtualClock(1000) - mpcompat.set_thread_clock(clock) - try: - import utime - assert utime.ticks_ms() == 1000 - utime.sleep_ms(250) - assert utime.ticks_diff(utime.ticks_ms(), 1000) == 250 - finally: - mpcompat.set_thread_clock(None) diff --git a/tests/engine_tests/test_sequences.py b/tests/engine_tests/test_sequences.py deleted file mode 100644 index 99ebe6f..0000000 --- a/tests/engine_tests/test_sequences.py +++ /dev/null @@ -1,214 +0,0 @@ -"""Sequence model normalisation/migration and the SequenceRunner.""" - -import asyncio - -import pytest - -from engine.core import EngineError -from engine.sequence_runner import SequenceRunner -from models.squence import _normalize, migrate_legacy - - -class FakeSequences(dict): - def read(self, id): - return self.get(str(id)) - - def update(self, id, data): - if str(id) not in self: - return False - self[str(id)].update(data) - return True - - def list(self): - return list(self.keys()) - - -class FakeEngine: - def __init__(self): - self.plays = [] - - async def play(self, zone_id, preset_id, source="manual"): - self.plays.append((zone_id, str(preset_id), source)) - - -def seq(zone="1", steps=("a", "b"), duration=0.02, **kw): - doc = {"name": "s", "zone_id": zone, "loop": True, "repeat_count": 0, "active": False, - "steps": [{"preset_id": p, "duration_s": duration} for p in steps]} - doc.update(kw) - return doc - - -# -- model ---------------------------------------------------------------------- - -def test_normalize_clamps_and_defaults(): - doc = _normalize({"name": " x ", "zone_id": 2, "steps": [ - {"preset_id": 1, "duration_s": 0.01}, {"preset_id": "2", "duration_s": 9999}, {"preset_id": "3"}]}) - assert doc["name"] == "x" and doc["zone_id"] == "2" and doc["loop"] is True - assert [s["duration_s"] for s in doc["steps"]] == [0.5, 600.0, 5.0] - assert doc["steps"][0]["preset_id"] == "1" - with pytest.raises(ValueError): - _normalize({"steps": [{"duration_s": 3}]}) - - -def test_migrate_legacy_record(): - legacy = {"group_name": "Main Group", "presets": ["1", "2"], "sequence_duration": 3000, - "sequence_transition": 500, "sequence_loop": False, "sequence_repeat_count": 2, - "sequence_active": True, "sequence_index": 1, "sequence_start_time": 0} - doc, migrated = migrate_legacy(legacy) - assert migrated - assert doc == {"name": "Main Group", "zone_id": None, "loop": False, "repeat_count": 2, - "steps": [{"preset_id": "1", "duration_s": 3.0}, {"preset_id": "2", "duration_s": 3.0}], - "active": False} - same, migrated = migrate_legacy(doc) - assert not migrated and same is doc - - -# -- runner --------------------------------------------------------------------- - -def test_steps_play_in_order_and_repeat_count_ends(): - async def go(): - model = FakeSequences({"1": seq(steps=("a", "b", "c"), repeat_count=2)}) - eng = FakeEngine() - runner = SequenceRunner(eng, sequences_model=model) - await runner.play("1") - assert model["1"]["active"] is True - await asyncio.sleep(0.4) - return eng, model, runner - - eng, model, runner = asyncio.run(go()) - assert [p for _z, p, _s in eng.plays] == ["a", "b", "c", "a", "b", "c"] - assert all(s == "sequence" for _z, _p, s in eng.plays) - assert model["1"]["active"] is False - st = runner.status()["1"] - assert st["running"] is False and st["pass"] == 2 - - -def test_no_loop_plays_once(): - async def go(): - model = FakeSequences({"1": seq(loop=False)}) - eng = FakeEngine() - await SequenceRunner(eng, sequences_model=model).play("1") - await asyncio.sleep(0.2) - return eng - - assert [p for _z, p, _s in asyncio.run(go()).plays] == ["a", "b"] - - -def test_infinite_loop_until_stop(): - async def go(): - model = FakeSequences({"1": seq()}) - eng = FakeEngine() - runner = SequenceRunner(eng, sequences_model=model) - await runner.play("1") - await asyncio.sleep(0.25) - assert await runner.stop("1") is True - n = len(eng.plays) - await asyncio.sleep(0.1) - return eng, n, model - - eng, n, model = asyncio.run(go()) - assert n >= 6 and len(eng.plays) == n - assert model["1"]["active"] is False - - -def test_new_sequence_replaces_old_on_same_zone(): - async def go(): - model = FakeSequences({"1": seq(steps=("a",)), "2": seq(steps=("z",))}) - eng = FakeEngine() - runner = SequenceRunner(eng, sequences_model=model) - await runner.play("1") - await asyncio.sleep(0.05) - await runner.play("2") - await asyncio.sleep(0.05) - plays_after_switch = list(eng.plays) - await runner.stop_all() - return plays_after_switch, model, runner - - plays, model, runner = asyncio.run(go()) - switch = plays.index(("1", "z", "sequence")) - assert all(p == "z" for _z, p, _s in plays[switch:]) - assert model["1"]["active"] is False - assert runner.status()["1"]["running"] is False - - -def test_stop_all_keeps_active_for_resume(): - async def go(): - model = FakeSequences({"1": seq(), "2": seq(zone="2")}) - eng = FakeEngine() - runner = SequenceRunner(eng, sequences_model=model) - await runner.play("1") - await runner.play("2") - await runner.stop_all(persist=False) - assert model["1"]["active"] and model["2"]["active"] - fresh = SequenceRunner(FakeEngine(), sequences_model=model) - resumed = await fresh.resume_active() - await fresh.stop_all() - return resumed - - assert sorted(asyncio.run(go())) == ["1", "2"] - - -def test_play_errors(): - async def go(): - model = FakeSequences({"nozone": seq(zone=None), "empty": seq(steps=())}) - runner = SequenceRunner(FakeEngine(), sequences_model=model) - for sid in ("missing", "nozone", "empty"): - with pytest.raises(EngineError): - await runner.play(sid) - - asyncio.run(go()) - - -def test_failing_step_does_not_kill_sequence(): - class Flaky(FakeEngine): - async def play(self, zone_id, preset_id, source="manual"): - await super().play(zone_id, preset_id, source) - if preset_id == "a": - raise EngineError("Preset not found", 404) - - async def go(): - model = FakeSequences({"1": seq(loop=False)}) - eng = Flaky() - runner = SequenceRunner(eng, sequences_model=model) - await runner.play("1") - await asyncio.sleep(0.2) - return eng, runner - - eng, runner = asyncio.run(go()) - assert [p for _z, p, _s in eng.plays] == ["a", "b"] - assert runner.status()["1"]["error"] == "Preset not found" - - -def test_manual_engine_play_stops_zone_sequence(): - from engine.core import Engine - from engine.zone_targets import ZoneTargets - - class NullPlayer: - def __init__(self, targets, library, brightness): - self.targets = targets - - async def start(self): - pass - - async def apply(self, preset_id, payload, drivers=True): - pass - - async def stop(self): - pass - - def status(self): - return {} - - async def go(): - model = FakeSequences({"1": seq(zone="5", steps=("a", "b"))}) - eng = Engine(library=object(), zone_resolver=lambda z: ZoneTargets(z, [], ["dj"]), - payload_resolver=lambda p: {"p": "on"}, player_factory=NullPlayer, - sequences_model=model) - await eng.sequences.play("1") - await asyncio.sleep(0.03) - await eng.play("5", "x") # manual pick - return eng, model - - eng, model = asyncio.run(go()) - assert eng.sequences.zone_for("1") is None - assert model["1"]["active"] is False diff --git a/tests/models/__init__.py b/tests/models/__init__.py deleted file mode 100644 index 0e78f7e..0000000 --- a/tests/models/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# Model tests package diff --git a/tests/models/run_all.py b/tests/models/run_all.py deleted file mode 100644 index 6c736e0..0000000 --- a/tests/models/run_all.py +++ /dev/null @@ -1,62 +0,0 @@ -"""Run all model tests.""" -import sys -import os - -# Add src to path -sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../src')) - -from test_model import test_model -from test_preset import test_preset -from test_profile import test_profile -from test_group import test_group -from test_sequence import test_sequence -from test_zone import test_zone -from test_palette import test_palette -from test_device import test_device - -def run_all_tests(): - """Run all model tests.""" - print("=" * 60) - print("Running Model Tests") - print("=" * 60) - - tests = [ - ("Base Model", test_model), - ("Preset", test_preset), - ("Profile", test_profile), - ("Group", test_group), - ("Sequence", test_sequence), - ("Zone", test_zone), - ("Palette", test_palette), - ("Device", test_device), - ] - - passed = 0 - failed = 0 - - for name, test_func in tests: - print(f"\n{'=' * 60}") - print(f"Testing {name}") - print('=' * 60) - try: - test_func() - print(f"\n✓ {name} tests passed!") - passed += 1 - except AssertionError as e: - print(f"\n✗ {name} tests failed: {e}") - failed += 1 - except Exception as e: - print(f"\n✗ {name} tests error: {e}") - import traceback - traceback.print_exc() - failed += 1 - - print(f"\n{'=' * 60}") - print(f"Test Summary: {passed} passed, {failed} failed") - print('=' * 60) - - return failed == 0 - -if __name__ == '__main__': - success = run_all_tests() - sys.exit(0 if success else 1) diff --git a/tests/models/test_device.py b/tests/models/test_device.py deleted file mode 100644 index b3aadbd..0000000 --- a/tests/models/test_device.py +++ /dev/null @@ -1,168 +0,0 @@ -import os -import sys -from pathlib import Path - -# Prefer src/models; pytest may have registered tests/models as top-level ``models``. -_src = Path(__file__).resolve().parents[2] / "src" -_sp = str(_src) -if _sp in sys.path: - sys.path.remove(_sp) -sys.path.insert(0, _sp) -_m = sys.modules.get("models") -if _m is not None: - mf = (getattr(_m, "__file__", "") or "").replace("\\", "/") - if "/tests/models" in mf: - del sys.modules["models"] - -from models.device import Device - - -def _fresh_device(): - """New empty device DB and new Device singleton (tests only).""" - db_dir = os.path.join( - os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "db" - ) - device_file = os.path.join(db_dir, "device.json") - if os.path.exists(device_file): - os.remove(device_file) - if hasattr(Device, "_instance"): - del Device._instance - return Device() - - -def test_device(): - """Test Device model CRUD operations (id = MAC).""" - devices = _fresh_device() - - mac = "aabbccddeeff" - print("Testing create device") - device_id = devices.create("Test Device", address="aa:bb:cc:dd:ee:ff", default_pattern="on", zones=["1", "2"]) - print(f"Created device with ID: {device_id}") - assert device_id == mac - assert device_id in devices - - print("\nTesting read device") - device = devices.read(device_id) - print(f"Read: {device}") - assert device is not None - assert device["id"] == mac - assert device["name"] == "Test Device" - assert device["type"] == "led" - assert device["transport"] == "espnow" - assert device["address"] == mac - assert device["default_pattern"] == "on" - assert device["zones"] == ["1", "2"] - - print("\nTesting read by colon MAC") - assert devices.read("aa:bb:cc:dd:ee:ff")["id"] == mac - - print("\nTesting address normalization on update (espnow keeps MAC as address)") - devices.update(device_id, {"address": "11:22:33:44:55:66"}) - updated = devices.read(device_id) - assert updated["address"] == mac - - print("\nTesting update device fields") - update_data = { - "name": "Updated Device", - "default_pattern": "rainbow", - "zones": ["1", "2", "3"], - } - result = devices.update(device_id, update_data) - assert result is True - updated = devices.read(device_id) - assert updated["name"] == "Updated Device" - assert updated["default_pattern"] == "rainbow" - assert len(updated["zones"]) == 3 - - print("\nTesting list devices") - device_list = devices.list() - print(f"Device list: {device_list}") - assert mac in device_list - - print("\nTesting delete device") - deleted = devices.delete(device_id) - assert deleted is True - assert mac not in devices - - print("\nTesting read after delete") - device = devices.read(device_id) - assert device is None - - print("\nAll device tests passed!") - - -def test_upsert_wifi_tcp_client(): - devices = _fresh_device() - assert devices.upsert_wifi_tcp_client("", "192.168.1.10", None) == (None, False) - assert devices.upsert_wifi_tcp_client("kitchen", "192.168.1.20", "bad") == ( - None, - False, - ) - - m1 = "001122334455" - m2 = "001122334466" - i1, p1 = devices.upsert_wifi_tcp_client("kitchen", "192.168.1.20", m1) - assert i1 == m1 and p1 is True - d = devices.read(i1) - assert d["name"] == "kitchen" - assert d["type"] == "led" - assert d["transport"] == "wifi" - assert d["address"] == "192.168.1.20" - - noop_mac, noop_p = devices.upsert_wifi_tcp_client("kitchen", "192.168.1.20", m1) - assert noop_mac == m1 and noop_p is False - - i2, p2 = devices.upsert_wifi_tcp_client("kitchen", "192.168.1.21", m2) - assert i2 == m2 and p2 is True - assert devices.read(m1)["address"] == "192.168.1.20" - assert devices.read(m2)["address"] == "192.168.1.21" - assert devices.read(m1)["name"] == devices.read(m2)["name"] == "kitchen" - - again, p_again = devices.upsert_wifi_tcp_client("kitchen", "192.168.1.99", m1) - assert again == m1 and p_again is True - assert devices.read(m1)["address"] == "192.168.1.99" - - bogus_mac, bogus_p = devices.upsert_wifi_tcp_client( - "kitchen", "192.168.1.100", m1, device_type="bogus" - ) - assert bogus_mac == m1 and bogus_p is True - assert devices.read(m1)["type"] == "led" - - i3, p3 = devices.upsert_wifi_tcp_client("hall", "10.0.0.5", "deadbeefcafe") - assert i3 == "deadbeefcafe" and p3 is True - assert len(devices.list()) == 3 - - -def test_device_can_change_address(): - devices = _fresh_device() - m = "feedfacec0de" - did = devices.create("mover", mac=m, address="192.168.1.1", transport="wifi") - assert did == m - devices.update(did, {"address": "10.0.0.99"}) - assert devices.read(did)["address"] == "10.0.0.99" - - -def test_device_duplicate_names_allowed(): - devices = _fresh_device() - a1 = devices.create("alpha", address="aa:bb:cc:dd:ee:ff") - a2 = devices.create("alpha", address="11:22:33:44:55:66") - assert a1 != a2 - assert devices.read(a1)["name"] == devices.read(a2)["name"] == "alpha" - - -def test_device_duplicate_mac_rejected(): - devices = _fresh_device() - devices.create("one", address="aa:bb:cc:dd:ee:ff") - try: - devices.create("two", address="aa-bb-cc-dd-ee-ff") - assert False, "expected ValueError" - except ValueError as e: - assert "already exists" in str(e).lower() - - -if __name__ == "__main__": - test_device() - test_upsert_wifi_tcp_client() - test_device_can_change_address() - test_device_duplicate_names_allowed() - test_device_duplicate_mac_rejected() diff --git a/tests/models/test_group.py b/tests/models/test_group.py deleted file mode 100644 index 3b9090b..0000000 --- a/tests/models/test_group.py +++ /dev/null @@ -1,61 +0,0 @@ -from models.group import Group -import os - -def test_group(): - """Test Group model CRUD operations.""" - # Clean up any existing test file - if os.path.exists("Group.json"): - os.remove("Group.json") - - groups = Group() - - print("Testing create group") - group_id = groups.create("test_group") - print(f"Created group with ID: {group_id}") - assert group_id is not None - assert group_id in groups - - print("\nTesting read group") - group = groups.read(group_id) - print(f"Read: {group}") - assert group is not None - assert group["name"] == "test_group" - assert "devices" in group - assert "pattern" in group - assert "colors" in group - - print("\nTesting update group") - update_data = { - "name": "updated_group", - "devices": ["device1", "device2"], - "pattern": "rainbow", - "colors": ["#FF0000", "#00FF00", "#0000FF"], - "brightness": 80, - "delay": 50 - } - result = groups.update(group_id, update_data) - assert result is True - updated = groups.read(group_id) - assert updated["name"] == "updated_group" - assert len(updated["devices"]) == 2 - assert updated["pattern"] == "rainbow" - - print("\nTesting list groups") - group_list = groups.list() - print(f"Group list: {group_list}") - assert group_id in group_list - - print("\nTesting delete group") - deleted = groups.delete(group_id) - assert deleted is True - assert group_id not in groups - - print("\nTesting read after delete") - group = groups.read(group_id) - assert group is None - - print("\nAll group tests passed!") - - -if __name__ == '__main__': - test_group() diff --git a/tests/models/test_model.py b/tests/models/test_model.py deleted file mode 100644 index f6a0ad9..0000000 --- a/tests/models/test_model.py +++ /dev/null @@ -1,55 +0,0 @@ -from models.model import Model -import os - -def test_model(): - """Test base Model class functionality.""" - # Create a test model class - class TestModel(Model): - pass - - # Clean up any existing test file (model uses db/.json) - db_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "db") - testmodel_file = os.path.join(db_dir, "testmodel.json") - if os.path.exists(testmodel_file): - os.remove(testmodel_file) - - model = TestModel() - - print("Testing get_next_id with empty model") - next_id = model.get_next_id() - assert next_id == "1" - print(f"Next ID: {next_id}") - - print("\nTesting get_next_id with existing entries") - model["1"] = {"data": "test1"} - model["2"] = {"data": "test2"} - model["5"] = {"data": "test5"} - next_id = model.get_next_id() - assert next_id == "6" - print(f"Next ID: {next_id}") - - print("\nTesting save and load") - model.save() - - # Create new instance to test load - model2 = TestModel() - assert "1" in model2 - assert "2" in model2 - assert "5" in model2 - assert model2["1"]["data"] == "test1" - - print("\nTesting set_defaults") - model2.set_defaults() - # Note: set_defaults currently doesn't work as expected (self = {} doesn't modify the dict) - # But we can test that the method exists and doesn't crash - assert hasattr(model2, 'set_defaults') - - # Clean up - if os.path.exists(testmodel_file): - os.remove(testmodel_file) - - print("\nAll model base class tests passed!") - - -if __name__ == '__main__': - test_model() diff --git a/tests/models/test_palette.py b/tests/models/test_palette.py deleted file mode 100644 index 65844a1..0000000 --- a/tests/models/test_palette.py +++ /dev/null @@ -1,64 +0,0 @@ -from models.pallet import Palette -import os - -def test_palette(): - """Test Palette model CRUD operations. - Palette stores a list of colors per ID; read() returns that list (or unwraps from dict). - """ - # Clean up any existing test file (model uses db/palette.json from project root) - db_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "db") - palette_file = os.path.join(db_dir, "palette.json") - if os.path.exists(palette_file): - os.remove(palette_file) - - palettes = Palette() - - print("Testing create palette") - colors = ["#FF0000", "#00FF00", "#0000FF", "#FFFF00"] - palette_id = palettes.create("test_palette", colors) - print(f"Created palette with ID: {palette_id}") - assert palette_id is not None - assert palette_id in palettes - - print("\nTesting read palette") - palette = palettes.read(palette_id) - print(f"Read: {palette}") - # read() returns list of colors (name is not stored) - assert palette is not None - assert isinstance(palette, list) or (isinstance(palette, dict) and "colors" in palette) - colors_read = palette if isinstance(palette, list) else palette.get("colors", []) - assert len(colors_read) == 4 - assert "#FF0000" in colors_read - - print("\nTesting update palette") - update_data = { - "name": "updated_palette", - "colors": ["#FF00FF", "#00FFFF", "#FFA500"] - } - result = palettes.update(palette_id, update_data) - assert result is True - updated = palettes.read(palette_id) - updated_colors = updated if isinstance(updated, list) else (updated.get("colors") or []) - assert len(updated_colors) == 3 - assert "#FF00FF" in updated_colors - - print("\nTesting list palettes") - palette_list = palettes.list() - print(f"Palette list: {palette_list}") - assert palette_id in palette_list - - print("\nTesting delete palette") - deleted = palettes.delete(palette_id) - assert deleted is True - assert palette_id not in palettes - - print("\nTesting read after delete") - palette = palettes.read(palette_id) - # read() returns [] when id is missing (value or []) - assert palette == [] or palette is None - - print("\nAll palette tests passed!") - - -if __name__ == '__main__': - test_palette() diff --git a/tests/models/test_preset.py b/tests/models/test_preset.py deleted file mode 100644 index b0bc68a..0000000 --- a/tests/models/test_preset.py +++ /dev/null @@ -1,60 +0,0 @@ -from models.preset import Preset -import os - -def test_preset(): - """Test Preset model CRUD operations.""" - # Clean up any existing test file - if os.path.exists("Preset.json"): - os.remove("Preset.json") - - presets = Preset() - - print("Testing create preset") - preset_id = presets.create() - print(f"Created preset with ID: {preset_id}") - assert preset_id is not None - assert preset_id in presets - - print("\nTesting read preset") - preset = presets.read(preset_id) - print(f"Read: {preset}") - assert preset is not None - assert preset["name"] == "" - assert preset["pattern"] == "" - - print("\nTesting update preset") - update_data = { - "name": "test_preset", - "pattern": "on", - "colors": ["#FF0000", "#00FF00"], - "delay": 100, - "brightness": 127, - "n1": 10, - "n2": 20 - } - result = presets.update(preset_id, update_data) - assert result is True - updated = presets.read(preset_id) - assert updated["name"] == "test_preset" - assert updated["pattern"] == "on" - assert updated["delay"] == 100 - - print("\nTesting list presets") - preset_list = presets.list() - print(f"Preset list: {preset_list}") - assert preset_id in preset_list - - print("\nTesting delete preset") - deleted = presets.delete(preset_id) - assert deleted is True - assert preset_id not in presets - - print("\nTesting read after delete") - preset = presets.read(preset_id) - assert preset is None - - print("\nAll preset tests passed!") - - -if __name__ == '__main__': - test_preset() diff --git a/tests/models/test_profile.py b/tests/models/test_profile.py deleted file mode 100644 index 22ea973..0000000 --- a/tests/models/test_profile.py +++ /dev/null @@ -1,60 +0,0 @@ -from models.profile import Profile -import os - -def test_profile(): - """Test Profile model CRUD operations. - Profile create() sets name, type, zones (list of zone IDs), scenes, palette_id. - """ - # Clean up any existing test file (model uses db/profile.json from project root) - db_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "db") - profile_file = os.path.join(db_dir, "profile.json") - if os.path.exists(profile_file): - os.remove(profile_file) - - profiles = Profile() - - print("Testing create profile") - profile_id = profiles.create("test_profile") - print(f"Created profile with ID: {profile_id}") - assert profile_id is not None - assert profile_id in profiles - - print("\nTesting read profile") - profile = profiles.read(profile_id) - print(f"Read: {profile}") - assert profile is not None - assert profile["name"] == "test_profile" - assert "zones" in profile - assert "palette_id" in profile - assert "type" in profile - - print("\nTesting update profile") - update_data = { - "name": "updated_profile", - "zones": ["tab1"], - } - result = profiles.update(profile_id, update_data) - assert result is True - updated = profiles.read(profile_id) - assert updated["name"] == "updated_profile" - assert "tab1" in updated["zones"] - - print("\nTesting list profiles") - profile_list = profiles.list() - print(f"Profile list: {profile_list}") - assert profile_id in profile_list - - print("\nTesting delete profile") - deleted = profiles.delete(profile_id) - assert deleted is True - assert profile_id not in profiles - - print("\nTesting read after delete") - profile = profiles.read(profile_id) - assert profile is None - - print("\nAll profile tests passed!") - - -if __name__ == '__main__': - test_profile() diff --git a/tests/models/test_sequence.py b/tests/models/test_sequence.py deleted file mode 100644 index 8661228..0000000 --- a/tests/models/test_sequence.py +++ /dev/null @@ -1,62 +0,0 @@ -from models.squence import Sequence - - -def test_sequence(): - """Test Sequence model CRUD operations.""" - sequences = Sequence() - - print("Testing create sequence") - sequence_id = sequences.create({ - "name": "test_sequence", - "zone_id": "1", - "steps": [{"preset_id": "preset1", "duration_s": 3}, {"preset_id": "preset2"}], - }) - print(f"Created sequence with ID: {sequence_id}") - assert sequence_id is not None - assert sequence_id in sequences - - print("\nTesting read sequence") - sequence = sequences.read(sequence_id) - print(f"Read: {sequence}") - assert sequence is not None - assert sequence["name"] == "test_sequence" - assert sequence["zone_id"] == "1" - assert [s["preset_id"] for s in sequence["steps"]] == ["preset1", "preset2"] - assert sequence["steps"][1]["duration_s"] == 5.0 - assert sequence["loop"] is True - assert sequence["active"] is False - - print("\nTesting update sequence") - update_data = { - "name": "updated_sequence", - "steps": [{"preset_id": p, "duration_s": 2} for p in ("preset3", "preset4", "preset5")], - "loop": False, - "repeat_count": 3, - } - result = sequences.update(sequence_id, update_data) - assert result is True - updated = sequences.read(sequence_id) - assert updated["name"] == "updated_sequence" - assert len(updated["steps"]) == 3 - assert updated["loop"] is False - assert updated["repeat_count"] == 3 - - print("\nTesting list sequences") - sequence_list = sequences.list() - print(f"Sequence list: {sequence_list}") - assert sequence_id in sequence_list - - print("\nTesting delete sequence") - deleted = sequences.delete(sequence_id) - assert deleted is True - assert sequence_id not in sequences - - print("\nTesting read after delete") - sequence = sequences.read(sequence_id) - assert sequence is None - - print("\nAll sequence tests passed!") - - -if __name__ == '__main__': - test_sequence() diff --git a/tests/models/test_zone.py b/tests/models/test_zone.py deleted file mode 100644 index 5436457..0000000 --- a/tests/models/test_zone.py +++ /dev/null @@ -1,57 +0,0 @@ -from models.zone import Zone -import os - - -def test_zone(): - """Test Zone model CRUD operations.""" - if os.path.exists("Zone.json"): - os.remove("Zone.json") - - zones = Zone() - - print("Testing create zone") - zone_id = zones.create("test_zone", ["1", "2", "3"], ["preset1", "preset2"]) - print(f"Created zone with ID: {zone_id}") - assert zone_id is not None - assert zone_id in zones - - print("\nTesting read zone") - zone = zones.read(zone_id) - print(f"Read: {zone}") - assert zone is not None - assert zone["name"] == "test_zone" - assert len(zone["names"]) == 3 - assert len(zone["presets"]) == 2 - - print("\nTesting update zone") - update_data = { - "name": "updated_zone", - "names": ["4", "5"], - "presets": ["preset3"], - } - result = zones.update(zone_id, update_data) - assert result is True - updated = zones.read(zone_id) - assert updated["name"] == "updated_zone" - assert len(updated["names"]) == 2 - assert len(updated["presets"]) == 1 - - print("\nTesting list zones") - zone_list = zones.list() - print(f"Zone list: {zone_list}") - assert zone_id in zone_list - - print("\nTesting delete zone") - deleted = zones.delete(zone_id) - assert deleted is True - assert zone_id not in zones - - print("\nTesting read after delete") - zone = zones.read(zone_id) - assert zone is None - - print("\nAll zone tests passed!") - - -if __name__ == "__main__": - test_zone() diff --git a/tests/p2p.py b/tests/p2p.py deleted file mode 100644 index 4b9b16e..0000000 --- a/tests/p2p.py +++ /dev/null @@ -1,105 +0,0 @@ -#!/usr/bin/env python3 -# MicroPython script to test LED bar patterns over ESP-NOW (no WebSocket) - -import json -import uasyncio as asyncio - -# Import P2P from src/p2p.py -# Note: When running on device, ensure src/p2p.py is in the path -try: - from p2p import P2P -except ImportError: - # Fallback: import from src directory - import sys - sys.path.insert(0, 'src') - from p2p import P2P - -async def main(): - p2p = P2P() - - # Test cases following msg.json format: - # {"g": {"df": {...}, "group_name": {...}}, "sv": true, "st": 0} - # Note: led-bar device must have matching group in settings["groups"] - tests = [ - # Example 1: Default format with df defaults and dj group (matches msg.json) - { - "g": { - "df": { - "pt": "on", - "cl": ["#ff0000"], - "br": 200, - "n1": 10, - "n2": 10, - "n3": 10, - "n4": 10, - "n5": 10, - "n6": 10, - "dl": 100 - }, - "dj": { - "pt": "blink", - "cl": ["#00ff00"], - "dl": 500 - } - }, - "sv": True, - "st": 0 - }, - # Example 2: Different group with df defaults - { - "g": { - "df": { - "pt": "on", - "br": 150, - "dl": 100 - }, - "group1": { - "pt": "rainbow", - "dl": 50 - } - }, - "sv": False - }, - # Example 3: Multiple groups - { - "g": { - "df": { - "br": 200, - "dl": 100 - }, - "group1": { - "pt": "on", - "cl": ["#0000ff"] - }, - "group2": { - "pt": "blink", - "cl": ["#ff00ff"], - "dl": 300 - } - }, - "sv": True, - "st": 1 - }, - # Example 4: Single group without df - { - "g": { - "dj": { - "pt": "off" - } - }, - "sv": False - } - ] - - for i, test in enumerate(tests, 1): - print(f"\n{'='*50}") - print(f"Test {i}/{len(tests)}") - print(f"Sending: {json.dumps(test, indent=2)}") - await p2p.send(json.dumps(test)) - await asyncio.sleep_ms(2000) - - print(f"\n{'='*50}") - print("All tests completed") - -if __name__ == "__main__": - asyncio.run(main()) \ No newline at end of file diff --git a/tests/tcp_test_server.py b/tests/tcp_test_server.py deleted file mode 100644 index d321b06..0000000 --- a/tests/tcp_test_server.py +++ /dev/null @@ -1,216 +0,0 @@ -#!/usr/bin/env python3 -""" -Simple TCP test server for led-controller. - -Listens on the same TCP port used by led-driver WiFi transport and -every 5 seconds sends a newline-delimited JSON message with v="1". - -Clients talking to the real Pi registry should send a first line JSON object -that includes device_name, mac (12 hex), and type (e.g. led) so the controller -can register the device by MAC. -""" - -import asyncio -import contextlib -import json -import os -import sys -from typing import Dict, Set - - -CLIENTS: Set[asyncio.StreamWriter] = set() -# Map each client writer to the device_name it reported. -CLIENT_DEVICE: Dict[asyncio.StreamWriter, str] = {} - - -async def _send_off_to_all(): - """Best-effort send an 'off' message to all connected devices.""" - if not CLIENTS: - return - print("[TCP TEST] Sending 'off' to all clients before shutdown") - dead = [] - for w in CLIENTS: - device_name = CLIENT_DEVICE.get(w) - if not device_name: - continue - payload = { - "v": "1", - "select": {device_name: ["off"]}, - } - line = json.dumps(payload) + "\n" - data = line.encode("utf-8") - try: - w.write(data) - await w.drain() - except Exception as e: - peer = w.get_extra_info("peername") - print(f"[TCP TEST] Error sending 'off' to {peer}: {e}") - dead.append(w) - for w in dead: - CLIENTS.discard(w) - CLIENT_DEVICE.pop(w, None) - - -async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter): - peer = writer.get_extra_info("peername") - print(f"[TCP TEST] Client connected: {peer}") - CLIENTS.add(writer) - buf = b"" - try: - # Wait for client to send its device_name JSON, then send presets once. - sent_presets = False - while True: - data = await reader.read(100) - if not data: - break - buf += data - print(f"[TCP TEST] From client {peer}: {data!r}") - - # Handle newline-delimited JSON from client. - while b"\n" in buf: - line, buf = buf.split(b"\n", 1) - line = line.strip() - if not line: - continue - try: - msg = json.loads(line.decode("utf-8")) - except Exception: - continue - - if isinstance(msg, dict) and "device_name" in msg: - device_name = str(msg.get("device_name") or "") - CLIENT_DEVICE[writer] = device_name - print(f"[TCP TEST] Registered device_name {device_name!r} for {peer}") - - if not sent_presets and device_name: - hello_payload = { - "v": "1", - "presets": { - "solid_red": { - "p": "on", - "c": ["#ff0000"], - "d": 100, - }, - "solid_blue": { - "p": "on", - "c": ["#0000ff"], - "d": 100, - }, - }, - "select": { - device_name: ["solid_red"], - }, - "b": 32, - } - try: - writer.write((json.dumps(hello_payload) + "\n").encode("utf-8")) - await writer.drain() - sent_presets = True - print( - f"[TCP TEST] Sent initial presets/select for device " - f"{device_name!r} to {peer}" - ) - except Exception as e: - print(f"[TCP TEST] Failed to send initial presets/select to {peer}: {e}") - except Exception as e: - print(f"[TCP TEST] Client error: {peer} {e}") - finally: - print(f"[TCP TEST] Client disconnected: {peer}") - CLIENTS.discard(writer) - CLIENT_DEVICE.pop(writer, None) - try: - writer.close() - await writer.wait_closed() - except Exception: - pass - - -async def broadcaster(port: int): - """Broadcast preset selection / brightness changes every 5 seconds.""" - counter = 0 - while True: - await asyncio.sleep(5) - counter += 1 - - # Toggle between two presets and brightness levels. - if CLIENTS: - print(f"[TCP TEST] Broadcasting to {len(CLIENTS)} client(s)") - - dead = [] - for w in CLIENTS: - device_name = CLIENT_DEVICE.get(w) - if not device_name: - continue - - if counter % 2 == 0: - preset_name = "solid_red" - payload = { - "v": "1", - "select": {device_name: [preset_name]}, - } - else: - preset_name = "solid_blue" - payload = { - "v": "1", - "select": {device_name: [preset_name]}, - } - - line = json.dumps(payload) + "\n" - data = line.encode("utf-8") - - try: - w.write(data) - await w.drain() - peer = w.get_extra_info("peername") - print( - f"[TCP TEST] Sent preset {preset_name!r} to device {device_name!r} " - f"for client {peer}" - ) - except Exception as e: - peer = w.get_extra_info("peername") - print(f"[TCP TEST] Error writing to {peer}: {e}") - dead.append(w) - - for w in dead: - CLIENTS.discard(w) - CLIENT_DEVICE.pop(w, None) - - -async def main(): - port = int(os.environ.get("PORT", os.environ.get("TCP_PORT", "8765"))) - host = "0.0.0.0" - print(f"[TCP TEST] Starting TCP test server on {host}:{port}") - - try: - server = await asyncio.start_server(handle_client, host=host, port=port) - except OSError as e: - if e.errno == 98: # EADDRINUSE - print( - f"[TCP TEST] Port {port} is already in use.\n" - f" If led-controller.service is enabled, it binds this port for ESP TCP " - f"transport after boot. Stop it for a standalone mock:\n" - f" sudo systemctl stop led-controller\n" - f" Or keep the main app and use another port for this mock:\n" - f" TCP_PORT=8766 pipenv run tcp-test\n" - f" (point test clients at that port). See also: sudo ss -tlnp | grep {port}", - file=sys.stderr, - ) - raise - async with server: - broadcaster_task = asyncio.create_task(broadcaster(port)) - try: - await server.serve_forever() - finally: - # On shutdown, try to turn all connected devices off. - await _send_off_to_all() - broadcaster_task.cancel() - with contextlib.suppress(Exception): - await broadcaster_task - - -if __name__ == "__main__": - try: - asyncio.run(main()) - except KeyboardInterrupt: - print("\n[TCP TEST] Shutting down.") - diff --git a/tests/test_binary_envelope.py b/tests/test_binary_envelope.py deleted file mode 100644 index aeaf7d3..0000000 --- a/tests/test_binary_envelope.py +++ /dev/null @@ -1,93 +0,0 @@ -"""Tests for compact binary controller envelopes (host util).""" - -import sys -from pathlib import Path - -PROJECT_ROOT = Path(__file__).resolve().parents[1] -sys.path.insert(0, str(PROJECT_ROOT / "src")) - -from util.binary_envelope import ( # noqa: E402 - BINARY_ENVELOPE_VERSION_2, - brightness_wire_from_0_255, - brightness_0_255_from_wire, - pack_binary_envelope_v2, - parse_binary_envelope, - parse_binary_envelope_v2, - parse_binary_envelope_v1, -) - - -def test_brightness_round_trip_extremes(): - assert brightness_0_255_from_wire(brightness_wire_from_0_255(0)) == 0 - assert brightness_0_255_from_wire(brightness_wire_from_0_255(255)) == 255 - - -def test_pack_parse_v2_brightness_only(): - raw = pack_binary_envelope_v2(brightness_0_255=128) - assert raw[0] == BINARY_ENVELOPE_VERSION_2 - data = parse_binary_envelope_v2(raw) - assert data == {"v": "1", "b": 128} - - -def test_pack_parse_v2_full(): - raw = pack_binary_envelope_v2( - presets={ - "a": { - "p": "on", - "c": ["#ffffff"], - "d": 10, - "b": 255, - "a": True, - "n1": 1, - "n2": -2, - "n3": 3, - "n4": 4, - "n5": 5, - "n6": 6, - } - }, - select={"dev": ["a"]}, - default="a", - default_targets=["dev"], - brightness_0_255=64, - ) - assert len(raw) <= 250 - data = parse_binary_envelope_v2(raw) - assert data["v"] == "1" - assert data["b"] == 64 - assert data["presets"]["a"]["p"] == "on" - assert data["presets"]["a"]["n2"] == -2 - assert data["select"]["dev"] == ["a"] - assert data["default"] == "a" - assert data["targets"] == ["dev"] - - merged = parse_binary_envelope(raw) - assert merged == data - - -def test_v2_wire_not_utf8_json(): - raw = pack_binary_envelope_v2( - presets={"x": {"p": "blink", "c": ["#112233"]}}, - brightness_0_255=None, - ) - assert raw[0] == BINARY_ENVELOPE_VERSION_2 - assert parse_binary_envelope_v1(raw) is None - - -def test_dont_change_brightness_v2(): - raw = pack_binary_envelope_v2(brightness_0_255=None) - data = parse_binary_envelope_v2(raw) - assert "b" not in data - - -def test_json_wire_not_v2(): - assert parse_binary_envelope_v2(b'{"v":"1"}') is None - - -def test_legacy_v1_parse_via_dispatcher(): - import json - - inner = json.dumps({"x": {"p": "on"}}, separators=(",", ":")).encode() - raw = bytes([1, 255, len(inner), 0, 0]) + inner - d = parse_binary_envelope(raw) - assert d["presets"]["x"]["p"] == "on" diff --git a/tests/test_browser.py b/tests/test_browser.py deleted file mode 100644 index f0c0a34..0000000 --- a/tests/test_browser.py +++ /dev/null @@ -1,1131 +0,0 @@ -#!/usr/bin/env python3 -""" -Browser automation tests using Selenium. -Tests run against the device in an actual browser. Target host defaults to -``192.168.4.1``; override with ``LED_CONTROLLER_DEVICE_IP`` (IP or hostname, -or a full ``http://`` / ``https://`` base URL). - -Fixed delays between UI steps use ``LED_CONTROLLER_BROWSER_SLEEP_SCALE`` -(default ``0.5``, i.e. half the nominal pause). Set to ``1`` for the old pacing, -or ``0`` to skip fixed sleeps (may flake). Driver implicit wait defaults to -``2`` seconds; override with ``LED_CONTROLLER_BROWSER_IMPLICIT_WAIT``. - -On Pi OS Lite (no desktop) these tests are skipped unless headless Chromium -and chromedriver are installed (e.g. chromium-browser chromium-chromedriver). -""" - -import os -import sys - -import pytest - -if os.environ.get("LED_CONTROLLER_RUN_BROWSER_TESTS") != "1": - # pytest catches Skipped; plain `python tests/test_browser.py` does not. - if __name__ == "__main__": - print( - "Browser tests are disabled by default. " - "Set LED_CONTROLLER_RUN_BROWSER_TESTS=1 to run.", - file=sys.stderr, - ) - raise SystemExit(0) - pytest.skip( - "Legacy device browser automation script; enable explicitly to run.", - allow_module_level=True, - ) -import time -import requests -from typing import Optional, List - -from selenium import webdriver -from selenium.webdriver.common.by import By -from selenium.webdriver.support.ui import WebDriverWait -from selenium.webdriver.support import expected_conditions as EC -from selenium.webdriver.chrome.options import Options as ChromeOptions -from selenium.webdriver.firefox.options import Options as FirefoxOptions -from selenium.webdriver.common.action_chains import ActionChains -from selenium.common.exceptions import ( - TimeoutException, - NoSuchElementException, - ElementNotInteractableException, -) - -_DEFAULT_DEVICE_HOST = "192.168.4.1" - - -def _device_base_url() -> str: - raw = os.environ.get("LED_CONTROLLER_DEVICE_IP", _DEFAULT_DEVICE_HOST).strip() - if not raw: - raw = _DEFAULT_DEVICE_HOST - if raw.startswith(("http://", "https://")): - return raw.rstrip("/") - return f"http://{raw}" - - -# Base URL for the device -BASE_URL = _device_base_url() - - -def _browser_sleep(seconds: float) -> None: - """Scale fixed UI pauses via LED_CONTROLLER_BROWSER_SLEEP_SCALE (default 0.5).""" - try: - scale = float(os.environ.get("LED_CONTROLLER_BROWSER_SLEEP_SCALE", "0.5")) - except ValueError: - scale = 0.5 - if scale <= 0: - return - time.sleep(max(0.0, float(seconds)) * scale) - - -def _implicit_wait_s() -> int: - try: - v = float(os.environ.get("LED_CONTROLLER_BROWSER_IMPLICIT_WAIT", "2")) - except ValueError: - v = 2.0 - return int(max(0, min(60, round(v)))) - - -class BrowserTest: - """Browser automation test class.""" - - def __init__(self, base_url: str = BASE_URL, headless: bool = False): - self.base_url = base_url - self.driver = None - self.headless = headless - self.created_zones: List[str] = [] - self.created_profiles: List[str] = [] - self.created_presets: List[str] = [] - - def setup(self): - """Set up the browser driver. Tries Chrome first, then Firefox.""" - err_chrome, err_firefox = None, None - # Try Chrome first - try: - opts = ChromeOptions() - if self.headless: - opts.add_argument('--headless') - opts.add_argument('--no-sandbox') - opts.add_argument('--disable-dev-shm-usage') - opts.add_argument('--disable-gpu') - opts.add_argument('--window-size=1920,1080') - self.driver = webdriver.Chrome(options=opts) - self.driver.implicitly_wait(_implicit_wait_s()) - print("✓ Browser started (Chrome)") - return True - except Exception as e: - err_chrome = e - # Fallback to Firefox - try: - opts = FirefoxOptions() - if self.headless: - opts.add_argument('--headless') - self.driver = webdriver.Firefox(options=opts) - self.driver.implicitly_wait(_implicit_wait_s()) - print("✓ Browser started (Firefox)") - return True - except Exception as e: - err_firefox = e - print("✗ Failed to start browser.") - if err_chrome: - print(f" Chrome: {err_chrome}") - if err_firefox: - print(f" Firefox: {err_firefox}") - print(" On Raspberry Pi (aarch64), install: chromium-browser and chromium-chromedriver") - return False - - def teardown(self): - """Close the browser.""" - if self.driver: - self.driver.quit() - print("✓ Browser closed") - - def navigate(self, path: str = '/'): - """Navigate to a URL.""" - url = f"{self.base_url}{path}" - try: - self.driver.get(url) - _browser_sleep(1) # Wait for page load - return True - except Exception as e: - print(f"✗ Failed to navigate to {url}: {e}") - return False - - def wait_for_element(self, by, value, timeout=10): - """Wait for an element to appear.""" - try: - element = WebDriverWait(self.driver, timeout).until( - EC.presence_of_element_located((by, value)) - ) - return element - except TimeoutException: - return None - - def _scroll_into_view(self, element) -> None: - self.driver.execute_script( - "arguments[0].scrollIntoView({block: 'center', inline: 'nearest'});", - element, - ) - - def click_element(self, by, value, timeout=10, use_js=False): - """Click an element.""" - try: - element = self.wait_for_element(by, value, timeout) - if element: - self._scroll_into_view(element) - if use_js: - # Use JavaScript click for elements that might be intercepted - self.driver.execute_script("arguments[0].click();", element) - else: - # Try normal click first, fall back to JS if it fails - try: - element.click() - except Exception: - self.driver.execute_script("arguments[0].click();", element) - _browser_sleep(0.5) # Wait for action - return True - return False - except Exception as e: - print(f"✗ Failed to click {value}: {e}") - return False - - def handle_alert(self, accept=True, timeout=2): - """Handle an alert dialog.""" - try: - alert = WebDriverWait(self.driver, timeout).until(EC.alert_is_present()) - if accept: - alert.accept() - else: - alert.dismiss() - _browser_sleep(0.3) - return True - except TimeoutException: - return False - except Exception as e: - print(f"✗ Failed to handle alert: {e}") - return False - - def cleanup_test_data(self): - """Clean up test data created during tests.""" - print("\n Cleaning up test data...") - try: - # Use requests to make API calls for cleanup - session = requests.Session() - - # Delete created presets by ID - for preset_id in self.created_presets: - try: - response = session.delete(f"{self.base_url}/presets/{preset_id}") - if response.status_code == 200: - print(f" ✓ Cleaned up preset: {preset_id}") - except Exception as e: - print(f" ⚠ Failed to cleanup preset {preset_id}: {e}") - - # Delete created zones by ID - for zone_id in self.created_zones: - try: - response = session.delete(f"{self.base_url}/zones/{zone_id}") - if response.status_code == 200: - print(f" ✓ Cleaned up zone: {zone_id}") - except Exception as e: - print(f" ⚠ Failed to cleanup zone {zone_id}: {e}") - - # Delete created profiles by ID - for profile_id in self.created_profiles: - try: - response = session.delete(f"{self.base_url}/profiles/{profile_id}") - if response.status_code == 200: - print(f" ✓ Cleaned up profile: {profile_id}") - except Exception as e: - print(f" ⚠ Failed to cleanup profile {profile_id}: {e}") - - # Also try to cleanup by name pattern (in case IDs weren't tracked) - test_names = ['Browser Test Zone', 'Browser Test Profile', 'Browser Test Preset', - 'Preset 1', 'Preset 2', 'Preset 3', 'Edited Browser Zone'] - - # Cleanup zones by name - try: - zones_response = session.get(f"{self.base_url}/zones") - if zones_response.status_code == 200: - zones_data = zones_response.json() - zones_map = zones_data.get('zones', {}) - for zone_id, zone_row in zones_map.items(): - if isinstance(zone_row, dict) and zone_row.get('name') in test_names: - try: - session.delete(f"{self.base_url}/zones/{zone_id}") - print(f" ✓ Cleaned up zone by name: {zone_row.get('name')}") - except: - pass - except: - pass - - # Cleanup profiles by name - try: - profiles_response = session.get(f"{self.base_url}/profiles") - if profiles_response.status_code == 200: - profiles_data = profiles_response.json() - profiles = profiles_data.get('profiles', {}) - for profile_id, profile_data in profiles.items(): - if isinstance(profile_data, dict) and profile_data.get('name') in test_names: - try: - session.delete(f"{self.base_url}/profiles/{profile_id}") - print(f" ✓ Cleaned up profile by name: {profile_data.get('name')}") - except: - pass - except: - pass - - # Cleanup presets by name - try: - presets_response = session.get(f"{self.base_url}/presets") - if presets_response.status_code == 200: - presets_data = presets_response.json() - presets = presets_data.get('presets', {}) if isinstance(presets_data, dict) else presets_data - for preset_id, preset_data in presets.items(): - if isinstance(preset_data, dict) and preset_data.get('name') in test_names: - try: - session.delete(f"{self.base_url}/presets/{preset_id}") - print(f" ✓ Cleaned up preset by name: {preset_data.get('name')}") - except: - pass - except: - pass - - # Clear the lists - self.created_zones.clear() - self.created_profiles.clear() - self.created_presets.clear() - except Exception as e: - print(f" ⚠ Cleanup error: {e}") - - def fill_input(self, by, value, text, timeout=10): - """Fill an input field.""" - try: - element = self.wait_for_element(by, value, timeout) - if element: - self._scroll_into_view(element) - # Chrome often reports as not interactable for clear/send_keys. - if (element.get_attribute("type") or "").lower() == "color": - hex_v = text.strip() - if hex_v and not hex_v.startswith("#"): - hex_v = "#" + hex_v - self.driver.execute_script( - """ - var el = arguments[0], v = arguments[1]; - el.value = v; - el.dispatchEvent(new Event('input', {bubbles: true})); - el.dispatchEvent(new Event('change', {bubbles: true})); - """, - element, - hex_v, - ) - return True - element.clear() - try: - element.send_keys(text) - except ElementNotInteractableException: - self.driver.execute_script( - "arguments[0].value = arguments[1];" - "arguments[0].dispatchEvent(new Event('input', {bubbles: true}));" - "arguments[0].dispatchEvent(new Event('change', {bubbles: true}));", - element, - text, - ) - return True - return False - except Exception as e: - print(f"✗ Failed to fill {value}: {e}") - return False - - def get_text(self, by, value, timeout=10): - """Get text from an element.""" - try: - element = self.wait_for_element(by, value, timeout) - if element: - return element.text - return None - except Exception as e: - return None - - def get_cookie(self, name: str): - """Get a cookie value.""" - try: - return self.driver.get_cookie(name) - except: - return None - - def drag_and_drop(self, source_element, target_element): - """Perform drag and drop operation.""" - try: - actions = ActionChains(self.driver) - actions.drag_and_drop(source_element, target_element).perform() - _browser_sleep(0.5) # Wait for drop to complete - return True - except Exception as e: - print(f"✗ Drag and drop failed: {e}") - return False - - def drag_and_drop_by_offset(self, element, x_offset, y_offset): - """Perform drag and drop by offset.""" - try: - actions = ActionChains(self.driver) - actions.drag_and_drop_by_offset(element, x_offset, y_offset).perform() - _browser_sleep(0.5) - return True - except Exception as e: - print(f"✗ Drag and drop by offset failed: {e}") - return False - - -@pytest.fixture -def browser() -> BrowserTest: - return BrowserTest() - - -def test_browser_connection(browser: BrowserTest) -> bool: - """Test basic browser connection.""" - print("Testing browser connection...") - if not browser.setup(): - return False - - try: - if browser.navigate('/'): - print("✓ Successfully loaded page") - title = browser.driver.title - print(f" Page title: {title}") - return True - else: - print("✗ Failed to load page") - return False - finally: - browser.teardown() - -def test_zones_ui(browser: BrowserTest) -> bool: - """Test zones UI in browser.""" - print("\n=== Testing Zones UI in Browser ===") - passed = 0 - total = 0 - - if not browser.setup(): - return False - - try: - # Test 1: Load page - total += 1 - if browser.navigate('/'): - print("✓ Loaded main page") - passed += 1 - else: - print("✗ Failed to load main page") - browser.teardown() - return False - - # Test 2: Open zones modal - total += 1 - if browser.click_element(By.ID, 'zones-btn'): - print("✓ Clicked Zones button") - # Wait for modal to appear - _browser_sleep(0.5) - modal = browser.wait_for_element(By.ID, 'zones-modal') - if modal and 'active' in modal.get_attribute('class'): - print("✓ Zones modal opened") - passed += 1 - else: - print("✗ Zones modal didn't open") - else: - print("✗ Failed to click Zones button") - - # Test 3: Create a zone via UI - total += 1 - try: - # Fill in zone name - if browser.fill_input(By.ID, 'new-zone-name', 'Browser Test Zone'): - print(" ✓ Filled zone name") - # Devices default from registry or placeholder name "1" - # Click create button - if browser.click_element(By.ID, 'create-zone-btn'): - print(" ✓ Clicked create button") - _browser_sleep(1) # Wait for creation - # Check if zone appears in list and extract ID - tabs_list = browser.wait_for_element(By.ID, 'zones-list-modal') - if tabs_list: - list_text = tabs_list.text - if 'Browser Test Zone' in list_text: - print("✓ Created zone via UI") - # Try to extract zone ID from the list (look for data-zone-id attribute) - try: - tab_rows = browser.driver.find_elements(By.CSS_SELECTOR, '#zones-list-modal .profiles-row') - for row in tab_rows: - if 'Browser Test Zone' in row.text: - zone_id = row.get_attribute('data-zone-id') - if zone_id: - browser.created_zones.append(zone_id) - break - except: - pass # If we can't extract ID, cleanup will try by name - passed += 1 - else: - print("✗ Zone not found in list after creation") - else: - print("✗ Zones list not found") - else: - print("✗ Failed to click create button") - except Exception as e: - print(f"✗ Failed to create zone via UI: {e}") - - # Test 4: Edit a zone via UI (right-click in zones list) - total += 1 - try: - # First, close and reopen modal to refresh - browser.click_element(By.ID, 'zones-close-btn') - _browser_sleep(0.5) - browser.click_element(By.ID, 'zones-btn') - _browser_sleep(0.5) - - # Right-click the row corresponding to 'Browser Test Zone' - try: - tab_row = browser.driver.find_element( - By.XPATH, - "//div[@id='zones-list-modal']//div[contains(@class,'profiles-row')][.//span[contains(text(), 'Browser Test Zone')]]" - ) - except Exception: - tab_row = None - - if tab_row: - actions = ActionChains(browser.driver) - actions.context_click(tab_row).perform() - _browser_sleep(0.5) - - # Check if edit modal opened - edit_modal = browser.wait_for_element(By.ID, 'edit-zone-modal') - if edit_modal: - print("✓ Edit modal opened via right-click") - # Fill in new name - if browser.fill_input(By.ID, 'edit-zone-name', 'Edited Browser Zone'): - print(" ✓ Filled new zone name") - # Submit form - edit_form = browser.wait_for_element(By.ID, 'edit-zone-form') - if edit_form: - browser.driver.execute_script("arguments[0].submit();", edit_form) - _browser_sleep(1) # Wait for update - print("✓ Submitted edit form") - passed += 1 - else: - print("✗ Edit form not found") - else: - print("✗ Edit modal didn't open after right-click") - else: - print("✗ Could not find zone row for 'Browser Test Zone'") - except Exception as e: - print(f"✗ Failed to edit zone via UI: {e}") - import traceback - traceback.print_exc() - - # Test 5: Check current zone cookie - total += 1 - cookie = browser.get_cookie('current_zone') - if cookie: - print(f"✓ Found current_zone cookie: {cookie.get('value')}") - passed += 1 - else: - print("⚠ No current_zone cookie found (might be normal if no zone selected)") - passed += 1 # Not a failure, just informational - - # Close modal - browser.click_element(By.ID, 'zones-close-btn') - - except Exception as e: - print(f"✗ Browser test error: {e}") - import traceback - traceback.print_exc() - finally: - browser.cleanup_test_data() - browser.teardown() - - print(f"\nBrowser zones UI tests: {passed}/{total} passed") - return passed == total - -def test_profiles_ui(browser: BrowserTest) -> bool: - """Test profiles UI in browser.""" - print("\n=== Testing Profiles UI in Browser ===") - passed = 0 - total = 0 - - if not browser.setup(): - return False - - try: - # Test 1: Load page - total += 1 - if browser.navigate('/'): - print("✓ Loaded main page") - passed += 1 - else: - browser.teardown() - return False - - # Test 2: Open profiles modal - total += 1 - if browser.click_element(By.ID, 'profiles-btn'): - print("✓ Clicked Profiles button") - _browser_sleep(0.5) - modal = browser.wait_for_element(By.ID, 'profiles-modal') - if modal: - print("✓ Profiles modal opened") - passed += 1 - else: - print("✗ Profiles modal didn't open") - - # Test 3: Create profile via UI - total += 1 - try: - if browser.fill_input(By.ID, 'new-profile-name', 'Browser Test Profile'): - print(" ✓ Filled profile name") - if browser.click_element(By.ID, 'create-profile-btn'): - print(" ✓ Clicked create button") - _browser_sleep(1) - # Check if profile appears - profiles_list = browser.wait_for_element(By.ID, 'profiles-list') - if profiles_list and 'Browser Test Profile' in profiles_list.text: - print("✓ Created profile via UI") - passed += 1 - else: - print("✗ Profile not found in list") - except Exception as e: - print(f"✗ Failed to create profile: {e}") - - # Close modal - browser.click_element(By.ID, 'profiles-close-btn') - - except Exception as e: - print(f"✗ Browser test error: {e}") - import traceback - traceback.print_exc() - finally: - browser.cleanup_test_data() - browser.teardown() - - print(f"\nBrowser profiles UI tests: {passed}/{total} passed") - return passed == total - - -def test_mobile_tab_presets_two_columns(): - """ - Verify that the zone preset selecting area shows roughly two preset tiles per row - on a phone-sized viewport. - """ - bt = BrowserTest(base_url=BASE_URL, headless=True) - if not bt.setup(): - assert False, "Failed to start browser" - - try: - # Simulate a mobile viewport - bt.driver.set_window_size(400, 800) - assert bt.navigate('/'), "Failed to load main page" - - # Click the first zone button to load presets for that zone - first_tab = bt.wait_for_element(By.CSS_SELECTOR, '.zone-button', timeout=10) - assert first_tab is not None, "No zone buttons found" - first_tab.click() - _browser_sleep(1) - - container = bt.wait_for_element(By.ID, 'presets-list-zone', timeout=10) - assert container is not None, "presets-list-zone not found" - - tiles = bt.driver.find_elements(By.CSS_SELECTOR, '#presets-list-zone .preset-tile-row') - # Need at least 2 presets to make this meaningful - assert len(tiles) >= 2, "Fewer than 2 presets found for zone" - - container_width = container.size['width'] - first_width = tiles[0].size['width'] - - # Each tile should be about half the container width (tolerate some margin) - assert 0.4 * container_width <= first_width <= 0.6 * container_width, ( - f"Preset tile width {first_width} not ~half of container {container_width}" - ) - finally: - bt.teardown() - -def test_presets_ui(browser: BrowserTest) -> bool: - """Test presets UI in browser.""" - print("\n=== Testing Presets UI in Browser ===") - passed = 0 - total = 0 - - if not browser.setup(): - return False - - try: - # Test 1: Load page - total += 1 - if browser.navigate('/'): - print("✓ Loaded main page") - passed += 1 - else: - browser.teardown() - return False - - # Test 2: Open presets modal - total += 1 - if browser.click_element(By.ID, 'presets-btn'): - print("✓ Clicked Presets button") - _browser_sleep(0.5) - modal = browser.wait_for_element(By.ID, 'presets-modal') - if modal: - print("✓ Presets modal opened") - passed += 1 - else: - print("✗ Presets modal didn't open") - - # Test 3: Click Add button to open preset editor - total += 1 - try: - if browser.click_element(By.ID, 'preset-add-btn'): - print(" ✓ Clicked Add Preset button") - _browser_sleep(0.5) - editor_modal = browser.wait_for_element(By.ID, 'preset-editor-modal') - if editor_modal: - print("✓ Preset editor modal opened") - passed += 1 - else: - print("✗ Preset editor modal didn't open") - else: - print("✗ Failed to click Add Preset button") - except Exception as e: - print(f"✗ Failed to open preset editor: {e}") - - # Test 4: Create a preset via UI - total += 1 - try: - # Fill preset name - if browser.fill_input(By.ID, 'preset-name-input', 'Browser Test Preset'): - print(" ✓ Filled preset name") - # Select a pattern - pattern_select = browser.wait_for_element(By.ID, 'preset-pattern-input') - if pattern_select: - # Try to select first available pattern - from selenium.webdriver.support.ui import Select - select = Select(pattern_select) - if len(select.options) > 1: # More than just the placeholder - select.select_by_index(1) # Select first real pattern - print(" ✓ Selected pattern") - # Add a color - if browser.fill_input(By.ID, 'preset-new-color', '#ff0000'): - print(" ✓ Set color") - if browser.click_element(By.ID, 'preset-add-color-btn'): - print(" ✓ Added color") - # Set brightness - if browser.fill_input(By.ID, 'preset-brightness-input', '200'): - print(" ✓ Set brightness") - # Save preset - if browser.click_element(By.ID, 'preset-save-btn'): - print(" ✓ Clicked save button") - _browser_sleep(1) - # Check if preset appears in list - presets_list = browser.wait_for_element(By.ID, 'presets-list') - if presets_list and 'Browser Test Preset' in presets_list.text: - print("✓ Created preset via UI") - passed += 1 - else: - print("✗ Preset not found in list after creation") - else: - print("✗ Failed to click save button") - except Exception as e: - print(f"✗ Failed to create preset: {e}") - import traceback - traceback.print_exc() - - # Close editor modal - browser.click_element(By.ID, 'preset-editor-close-btn', use_js=True) - _browser_sleep(0.5) - # Close presets modal - browser.click_element(By.ID, 'presets-close-btn', use_js=True) - - except Exception as e: - print(f"✗ Browser test error: {e}") - import traceback - traceback.print_exc() - finally: - browser.cleanup_test_data() - browser.teardown() - - print(f"\nBrowser presets UI tests: {passed}/{total} passed") - return passed == total - -def test_color_palette_ui(browser: BrowserTest) -> bool: - """Test color palette UI in browser.""" - print("\n=== Testing Color Palette UI in Browser ===") - passed = 0 - total = 0 - - if not browser.setup(): - return False - - try: - # Test 1: Load page - total += 1 - if browser.navigate('/'): - print("✓ Loaded main page") - passed += 1 - else: - browser.teardown() - return False - - # Test 2: Open color palette modal - total += 1 - if browser.click_element(By.ID, 'color-palette-btn'): - print("✓ Clicked Color Palette button") - _browser_sleep(0.5) - modal = browser.wait_for_element(By.ID, 'color-palette-modal') - if modal: - print("✓ Color palette modal opened") - passed += 1 - else: - print("✗ Color palette modal didn't open") - - # Test 3: Add a color to palette - total += 1 - try: - # Set color picker - use a unique color that's likely not in palette - color_input = browser.wait_for_element(By.ID, 'palette-new-color') - if color_input: - # Use a unique color (purple) that's less likely to be in palette - browser.driver.execute_script("arguments[0].value = '#9b59b6'; arguments[0].dispatchEvent(new Event('input'));", color_input) - print(" ✓ Set color to #9b59b6") - # Click add color button - if browser.click_element(By.ID, 'palette-add-color-btn'): - print(" ✓ Clicked Add Color button") - _browser_sleep(0.5) - # Handle alert if color already exists - browser.handle_alert(accept=True, timeout=1) - # Check if color appears in palette - palette_container = browser.wait_for_element(By.ID, 'palette-container') - if palette_container: - # Look for color swatches - color_swatches = browser.driver.find_elements(By.CSS_SELECTOR, '#palette-container .draggable-color-swatch, #palette-container [style*="background-color"]') - if color_swatches: - print("✓ Added color to palette") - passed += 1 - else: - print("✗ Color not found in palette after adding") - else: - print("✗ Palette container not found") - else: - print("✗ Failed to click Add Color button") - except Exception as e: - print(f"✗ Failed to add color: {e}") - import traceback - traceback.print_exc() - - # Test 4: Test drag and drop colors (if multiple colors exist) - total += 1 - try: - color_swatches = browser.driver.find_elements(By.CSS_SELECTOR, '#palette-container .draggable-color-swatch, #palette-container [draggable="true"]') - if len(color_swatches) >= 2: - # Drag first color to second position - source = color_swatches[0] - target = color_swatches[1] - if browser.drag_and_drop(source, target): - print("✓ Dragged color to reorder") - _browser_sleep(0.5) - passed += 1 - else: - print("✗ Drag and drop failed") - else: - print("⚠ Not enough colors to test drag and drop (need at least 2)") - passed += 1 # Not a failure - except Exception as e: - print(f"✗ Drag and drop test error: {e}") - - # Close modal - browser.click_element(By.ID, 'color-palette-close-btn', use_js=True) - - except Exception as e: - print(f"✗ Browser test error: {e}") - import traceback - traceback.print_exc() - finally: - browser.cleanup_test_data() - browser.teardown() - - print(f"\nBrowser color palette UI tests: {passed}/{total} passed") - return passed >= total - 1 # Allow one failure (alert handling might be flaky) - -def test_preset_drag_and_drop(browser: BrowserTest) -> bool: - """Test dragging presets around in a zone.""" - print("\n=== Testing Preset Drag and Drop in Zone ===") - passed = 0 - total = 0 - - if not browser.setup(): - return False - - try: - # Test 1: Load page and ensure we have a zone - total += 1 - if browser.navigate('/'): - print("✓ Loaded main page") - passed += 1 - else: - browser.teardown() - return False - - # Test 2: Open zones modal and create/select a zone - total += 1 - browser.click_element(By.ID, 'zones-btn') - _browser_sleep(0.5) - - # Check if we have zones, if not create one - tabs_list = browser.wait_for_element(By.ID, 'zones-list-modal') - if tabs_list and 'No zones found' in tabs_list.text: - # Create a zone - browser.fill_input(By.ID, 'new-zone-name', 'Drag Test Zone') - browser.click_element(By.ID, 'create-zone-btn') - _browser_sleep(1) - - # Select first zone (or the one we just created) - select_buttons = browser.driver.find_elements(By.XPATH, "//button[contains(text(), 'Select')]") - if select_buttons: - select_buttons[0].click() - _browser_sleep(1) - print("✓ Selected a zone") - passed += 1 - else: - print("✗ No zones available to select") - browser.click_element(By.ID, 'zones-close-btn') - browser.teardown() - return False - - browser.click_element(By.ID, 'zones-close-btn', use_js=True) - _browser_sleep(0.5) - - # Test 3: Open presets modal and create presets - total += 1 - browser.click_element(By.ID, 'presets-btn') - _browser_sleep(0.5) - - # Create first preset - browser.click_element(By.ID, 'preset-add-btn') - _browser_sleep(0.5) - browser.fill_input(By.ID, 'preset-name-input', 'Preset 1') - browser.fill_input(By.ID, 'preset-new-color', '#ff0000') - browser.click_element(By.ID, 'preset-add-color-btn') - browser.click_element(By.ID, 'preset-save-btn') - _browser_sleep(1) - - # Create second preset - browser.click_element(By.ID, 'preset-add-btn') - _browser_sleep(0.5) - browser.fill_input(By.ID, 'preset-name-input', 'Preset 2') - browser.fill_input(By.ID, 'preset-new-color', '#00ff00') - browser.click_element(By.ID, 'preset-add-color-btn') - browser.click_element(By.ID, 'preset-save-btn') - _browser_sleep(1) - - # Create third preset - browser.click_element(By.ID, 'preset-add-btn') - _browser_sleep(0.5) - browser.fill_input(By.ID, 'preset-name-input', 'Preset 3') - browser.fill_input(By.ID, 'preset-new-color', '#0000ff') - browser.click_element(By.ID, 'preset-add-color-btn') - browser.click_element(By.ID, 'preset-save-btn') - _browser_sleep(1) - - browser.click_element(By.ID, 'presets-close-btn', use_js=True) - _browser_sleep(0.5) - - print("✓ Created 3 presets for drag test") - passed += 1 - - # Test 4: Add presets to the zone (via Edit Zone modal – Add buttons in list) - total += 1 - try: - zone_id = browser.driver.execute_script( - "return (window.tabsManager && window.tabsManager.getCurrentTabId && window.tabsManager.getCurrentTabId()) || null;" - ) - if not zone_id: - print("✗ Could not get current zone id") - else: - browser.driver.execute_script( - "if (window.tabsManager && window.tabsManager.openEditTabModal) { window.tabsManager.openEditTabModal(arguments[0], null); }", - zone_id - ) - _browser_sleep(1) - list_el = browser.wait_for_element(By.ID, 'edit-zone-presets-list', timeout=5) - if list_el: - select_buttons = browser.driver.find_elements(By.XPATH, "//div[@id='edit-zone-presets-list']//button[text()='Add']") - if len(select_buttons) >= 2: - browser.driver.execute_script("arguments[0].click();", select_buttons[0]) - _browser_sleep(1.5) - browser.handle_alert(accept=True, timeout=1) - select_buttons = browser.driver.find_elements(By.XPATH, "//div[@id='edit-zone-presets-list']//button[text()='Add']") - if len(select_buttons) >= 1: - browser.driver.execute_script("arguments[0].click();", select_buttons[0]) - _browser_sleep(1.5) - browser.handle_alert(accept=True, timeout=1) - print(" ✓ Added 2 presets to zone") - passed += 1 - elif len(select_buttons) == 1: - browser.driver.execute_script("arguments[0].click();", select_buttons[0]) - _browser_sleep(1.5) - browser.handle_alert(accept=True, timeout=1) - print(" ✓ Added 1 preset to zone") - passed += 1 - else: - print(" ⚠ No presets available to add (all already in zone)") - else: - print("✗ Edit zone presets list not found") - except Exception as e: - print(f"✗ Failed to add presets to zone: {e}") - import traceback - traceback.print_exc() - - # Test 5: Find presets in zone and test drag and drop (Edit mode only) - total += 1 - try: - # Wait for presets to load in the zone - presets_list_tab = browser.wait_for_element(By.ID, 'presets-list-zone', timeout=5) - if presets_list_tab: - _browser_sleep(1) # Wait for presets to render - - # Reordering is only available in Edit mode (tiles get .draggable-preset) - mode_toggle = browser.wait_for_element(By.CSS_SELECTOR, '.ui-mode-toggle', timeout=5) - if mode_toggle and mode_toggle.get_attribute('aria-pressed') == 'false': - mode_toggle.click() - _browser_sleep(0.5) - - # Find draggable preset elements - wait a bit more for rendering - _browser_sleep(1) - draggable_presets = browser.driver.find_elements(By.CSS_SELECTOR, '#presets-list-zone .draggable-preset') - if len(draggable_presets) >= 2: - print(f" ✓ Found {len(draggable_presets)} draggable presets") - - # Get initial order - initial_order = [p.text for p in draggable_presets] - print(f" Initial order: {initial_order[:3]}") # Show first 3 - - # Drag first preset down - source = draggable_presets[0] - target = draggable_presets[1] - - # Use ActionChains for drag and drop - actions = ActionChains(browser.driver) - actions.click_and_hold(source).move_to_element(target).release().perform() - _browser_sleep(1) # Wait for reorder to complete - - # Check if order changed - draggable_presets_after = browser.driver.find_elements(By.CSS_SELECTOR, '#presets-list-zone .draggable-preset') - if len(draggable_presets_after) >= 2: - new_order = [p.text for p in draggable_presets_after] - print(f" New order: {new_order[:3]}") - - if initial_order != new_order: - print("✓ Preset drag and drop worked - order changed") - passed += 1 - else: - print("⚠ Order didn't change (might need to verify with API)") - passed += 1 # Not necessarily a failure - else: - print("✗ Presets disappeared after drag") - elif len(draggable_presets) == 1: - print(f"⚠ Only 1 preset found in zone (need 2 for drag test). Preset: {draggable_presets[0].text}") - zone_id = browser.driver.execute_script( - "return (window.tabsManager && window.tabsManager.getCurrentTabId && window.tabsManager.getCurrentTabId()) || null;" - ) - if zone_id: - browser.driver.execute_script( - "if (window.tabsManager && window.tabsManager.openEditTabModal) { window.tabsManager.openEditTabModal(arguments[0], null); }", - zone_id - ) - _browser_sleep(1) - select_buttons = browser.driver.find_elements(By.XPATH, "//div[@id='edit-zone-presets-list']//button[text()='Add']") - if select_buttons: - print(" Attempting to add another preset...") - browser.driver.execute_script("arguments[0].click();", select_buttons[0]) - _browser_sleep(1.5) - browser.handle_alert(accept=True, timeout=1) - try: - browser.driver.execute_script("document.getElementById('edit-zone-modal').classList.remove('active');") - except Exception: - pass - _browser_sleep(1) - draggable_presets = browser.driver.find_elements(By.CSS_SELECTOR, '#presets-list-zone .draggable-preset') - if len(draggable_presets) >= 2: - print(" ✓ Added another preset, now testing drag...") - source = draggable_presets[0] - target = draggable_presets[1] - actions = ActionChains(browser.driver) - actions.click_and_hold(source).move_to_element(target).release().perform() - _browser_sleep(1) - print("✓ Performed drag and drop") - passed += 1 - else: - print(f" ✗ Still only {len(draggable_presets)} preset(s) after adding") - else: - print(" ✗ No Add buttons found in Edit Zone modal") - else: - print(f"✗ No presets found in zone (found {len(draggable_presets)})") - else: - print("✗ Presets list in zone not found") - except Exception as e: - print(f"✗ Drag and drop test error: {e}") - import traceback - traceback.print_exc() - - except Exception as e: - print(f"✗ Browser test error: {e}") - import traceback - traceback.print_exc() - finally: - browser.cleanup_test_data() - browser.teardown() - - print(f"\nBrowser preset drag and drop tests: {passed}/{total} passed") - return passed >= total - 2 # Allow up to 2 failures (drag test and adding presets can be flaky) - -def main(): - """Run all browser tests.""" - print("=" * 60) - print("LED Controller Browser Tests") - print(f"Testing against: {BASE_URL}") - print("=" * 60) - - # On Pi OS Lite there is no browser by default; skip with exit 0 instead of failing - browser = BrowserTest(headless=True) - if not browser.setup(): - print("\nSkipped (Pi OS Lite / no browser). Install chromium-browser and") - print("chromium-chromedriver to run browser tests, or run on Pi OS with desktop.") - sys.exit(0) - browser.teardown() - - browser = BrowserTest(headless=False) # Set to True for headless mode - - results = [] - - # Run browser tests - results.append(("Browser Connection", test_browser_connection(browser))) - results.append(("Zones UI", test_zones_ui(browser))) - results.append(("Profiles UI", test_profiles_ui(browser))) - results.append(("Presets UI", test_presets_ui(browser))) - results.append(("Color Palette UI", test_color_palette_ui(browser))) - results.append(("Preset Drag and Drop", test_preset_drag_and_drop(browser))) - - # Summary - print("\n" + "=" * 60) - print("Browser Test Summary") - print("=" * 60) - all_passed = True - for name, passed in results: - status = "✓ PASS" if passed else "✗ FAIL" - print(f"{status} - {name}") - if not passed: - all_passed = False - - print("=" * 60) - if all_passed: - print("✓ All browser tests passed!") - sys.exit(0) - else: - print("✗ Some browser tests failed") - sys.exit(1) - -if __name__ == "__main__": - main() diff --git a/tests/test_endpoints.py b/tests/test_endpoints.py deleted file mode 100644 index cba77a9..0000000 --- a/tests/test_endpoints.py +++ /dev/null @@ -1,596 +0,0 @@ -#!/usr/bin/env python3 -""" -Endpoint tests that mimic web browser requests. -Tests run against the device at 192.168.4.1 -""" - -import os -import pytest - -if os.environ.get("LED_CONTROLLER_RUN_DEVICE_ENDPOINT_TESTS") != "1": - pytest.skip( - "Legacy device integration endpoint tests; enable explicitly to run.", - allow_module_level=True, - ) - -import requests -import json -import sys -from typing import Dict, Optional - -# Base URL for the device -BASE_URL = "http://192.168.4.1" - -class TestClient: - """HTTP client that mimics a web browser with cookie support.""" - - def __init__(self, base_url: str = BASE_URL): - self.base_url = base_url - self.session = requests.Session() - self.session.headers.update({ - 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36', - 'Accept': 'application/json', - 'Accept-Language': 'en-US,en;q=0.9', - }) - - def get(self, path: str, **kwargs) -> requests.Response: - """GET request.""" - url = f"{self.base_url}{path}" - return self.session.get(url, **kwargs) - - def post(self, path: str, data: Optional[Dict] = None, json_data: Optional[Dict] = None, **kwargs) -> requests.Response: - """POST request.""" - url = f"{self.base_url}{path}" - if json_data: - return self.session.post(url, json=json_data, **kwargs) - return self.session.post(url, data=data, **kwargs) - - def put(self, path: str, json_data: Optional[Dict] = None, **kwargs) -> requests.Response: - """PUT request.""" - url = f"{self.base_url}{path}" - return self.session.put(url, json=json_data, **kwargs) - - def delete(self, path: str, **kwargs) -> requests.Response: - """DELETE request.""" - url = f"{self.base_url}{path}" - return self.session.delete(url, **kwargs) - - def set_cookie(self, name: str, value: str): - """Set a cookie manually.""" - self.session.cookies.set(name, value, domain='192.168.4.1', path='/') - - def get_cookie(self, name: str) -> Optional[str]: - """Get a cookie value.""" - return self.session.cookies.get(name) - -def test_connection(client: TestClient) -> bool: - """Test basic connection to the server.""" - print("Testing connection...") - try: - response = client.get('/') - if response.status_code == 200: - print("✓ Connection successful") - return True - else: - print(f"✗ Connection failed: {response.status_code}") - return False - except requests.exceptions.ConnectionError: - print(f"✗ Cannot connect to {BASE_URL}") - print(" Make sure the device is running and accessible at 192.168.4.1") - return False - except Exception as e: - print(f"✗ Connection error: {e}") - return False - -def test_zones(client: TestClient) -> bool: - """Test zones endpoints.""" - print("\n=== Testing Zones Endpoints ===") - passed = 0 - total = 0 - - # Test 1: List zones - total += 1 - try: - response = client.get('/zones') - if response.status_code == 200: - data = response.json() - print(f"✓ GET /zones - Found {len(data.get('zones', {}))} zones") - passed += 1 - else: - print(f"✗ GET /zones - Status: {response.status_code}") - except Exception as e: - print(f"✗ GET /zones - Error: {e}") - - # Test 2: Create zone - total += 1 - try: - zone_data = { - "name": "Test Zone", - "names": ["1", "2"] - } - response = client.post('/zones', json_data=zone_data) - if response.status_code == 201: - created_zone = response.json() - # Response format: {zone_id: {zone object}} - if isinstance(created_zone, dict): - # Get the first key which should be the zone ID - zone_id = next(iter(created_zone.keys())) if created_zone else None - else: - zone_id = None - print(f"✓ POST /zones - Created zone: {zone_id}") - passed += 1 - - # Test 3: Get specific zone - if zone_id: - total += 1 - response = client.get(f'/zones/{zone_id}') - if response.status_code == 200: - print(f"✓ GET /zones/{zone_id} - Retrieved zone") - passed += 1 - else: - print(f"✗ GET /zones/{zone_id} - Status: {response.status_code}") - - # Test 4: Set current zone - total += 1 - response = client.post(f'/zones/{zone_id}/set-current') - if response.status_code == 200: - print(f"✓ POST /zones/{zone_id}/set-current - Set current zone") - # Check cookie was set - cookie = client.get_cookie('current_zone') - if cookie == zone_id: - print(f" ✓ Cookie 'current_zone' set to {zone_id}") - passed += 1 - else: - print(f"✗ POST /zones/{zone_id}/set-current - Status: {response.status_code}") - - # Test 5: Get current zone - total += 1 - response = client.get('/zones/current') - if response.status_code == 200: - data = response.json() - if data.get('zone_id') == zone_id: - print(f"✓ GET /zones/current - Current zone is {zone_id}") - passed += 1 - else: - print(f"✗ GET /zones/current - Wrong zone ID") - else: - print(f"✗ GET /zones/current - Status: {response.status_code}") - - # Test 6: Update zone (edit functionality) - total += 1 - update_data = { - "name": "Updated Test Zone", - "names": ["1", "2", "3"] # Update device IDs too - } - response = client.put(f'/zones/{zone_id}', json_data=update_data) - if response.status_code == 200: - updated = response.json() - if updated.get('name') == "Updated Test Zone" and updated.get('names') == ["1", "2", "3"]: - print(f"✓ PUT /zones/{zone_id} - Updated zone (name and device IDs)") - passed += 1 - else: - print(f"✗ PUT /zones/{zone_id} - Update didn't work correctly") - print(f" Expected name='Updated Test Zone', got '{updated.get('name')}'") - print(f" Expected names=['1','2','3'], got {updated.get('names')}") - else: - print(f"✗ PUT /zones/{zone_id} - Status: {response.status_code}, Response: {response.text}") - - # Test 6b: Verify update persisted - total += 1 - response = client.get(f'/zones/{zone_id}') - if response.status_code == 200: - verified = response.json() - if verified.get('name') == "Updated Test Zone": - print(f"✓ GET /zones/{zone_id} - Verified update persisted") - passed += 1 - else: - print(f"✗ GET /zones/{zone_id} - Update didn't persist") - else: - print(f"✗ GET /zones/{zone_id} - Status: {response.status_code}") - - # Test 7: Delete zone - total += 1 - response = client.delete(f'/zones/{zone_id}') - if response.status_code == 200: - print(f"✓ DELETE /zones/{zone_id} - Deleted zone") - passed += 1 - else: - print(f"✗ DELETE /zones/{zone_id} - Status: {response.status_code}") - else: - print(f"✗ POST /zones - Status: {response.status_code}, Response: {response.text}") - except Exception as e: - print(f"✗ POST /zones - Error: {e}") - import traceback - traceback.print_exc() - - print(f"\nZones tests: {passed}/{total} passed") - return passed == total - -def test_profiles(client: TestClient) -> bool: - """Test profiles endpoints.""" - print("\n=== Testing Profiles Endpoints ===") - passed = 0 - total = 0 - - # Test 1: List profiles - total += 1 - try: - response = client.get('/profiles') - if response.status_code == 200: - data = response.json() - profiles = data.get('profiles', {}) - current_id = data.get('current_profile_id') - print(f"✓ GET /profiles - Found {len(profiles)} profiles, current: {current_id}") - passed += 1 - else: - print(f"✗ GET /profiles - Status: {response.status_code}") - except Exception as e: - print(f"✗ GET /profiles - Error: {e}") - - # Test 2: Get current profile - total += 1 - try: - response = client.get('/profiles/current') - if response.status_code == 200: - data = response.json() - print(f"✓ GET /profiles/current - Current profile: {data.get('id')}") - passed += 1 - else: - print(f"✗ GET /profiles/current - Status: {response.status_code}") - except Exception as e: - print(f"✗ GET /profiles/current - Error: {e}") - - # Test 3: Create profile - total += 1 - try: - profile_data = {"name": "Test Profile"} - response = client.post('/profiles', json_data=profile_data) - if response.status_code == 201: - created = response.json() - # Response format: {profile_id: {profile_data}} - if isinstance(created, dict): - profile_id = next(iter(created.keys())) if created else None - else: - profile_id = None - print(f"✓ POST /profiles - Created profile: {profile_id}") - passed += 1 - - # Test 4: Apply profile - if profile_id: - total += 1 - response = client.post(f'/profiles/{profile_id}/apply') - if response.status_code == 200: - print(f"✓ POST /profiles/{profile_id}/apply - Applied profile") - passed += 1 - else: - print(f"✗ POST /profiles/{profile_id}/apply - Status: {response.status_code}") - - # Test 5: Delete profile - total += 1 - response = client.delete(f'/profiles/{profile_id}') - if response.status_code == 200: - print(f"✓ DELETE /profiles/{profile_id} - Deleted profile") - passed += 1 - else: - print(f"✗ DELETE /profiles/{profile_id} - Status: {response.status_code}") - else: - print(f"✗ POST /profiles - Status: {response.status_code}") - except Exception as e: - print(f"✗ POST /profiles - Error: {e}") - - print(f"\nProfiles tests: {passed}/{total} passed") - return passed == total - -def test_presets(client: TestClient) -> bool: - """Test presets endpoints.""" - print("\n=== Testing Presets Endpoints ===") - passed = 0 - total = 0 - - # Test 1: List presets - total += 1 - try: - response = client.get('/presets') - if response.status_code == 200: - data = response.json() - preset_count = len(data) if isinstance(data, dict) else 0 - print(f"✓ GET /presets - Found {preset_count} presets") - passed += 1 - else: - print(f"✗ GET /presets - Status: {response.status_code}") - except Exception as e: - print(f"✗ GET /presets - Error: {e}") - - # Test 2: Create preset - total += 1 - try: - preset_data = { - "name": "Test Preset", - "pattern": "on", - "colors": ["#ff0000"], - "brightness": 200 - } - response = client.post('/presets', json_data=preset_data) - if response.status_code == 201: - created = response.json() - # Response format: {preset_id: {preset_data}} - if isinstance(created, dict): - preset_id = next(iter(created.keys())) if created else None - else: - preset_id = None - print(f"✓ POST /presets - Created preset: {preset_id}") - passed += 1 - - # Test 3: Get specific preset - if preset_id: - total += 1 - response = client.get(f'/presets/{preset_id}') - if response.status_code == 200: - print(f"✓ GET /presets/{preset_id} - Retrieved preset") - passed += 1 - else: - print(f"✗ GET /presets/{preset_id} - Status: {response.status_code}") - - # Test 4: Update preset - total += 1 - update_data = {"brightness": 150} - response = client.put(f'/presets/{preset_id}', json_data=update_data) - if response.status_code == 200: - print(f"✓ PUT /presets/{preset_id} - Updated preset") - passed += 1 - else: - print(f"✗ PUT /presets/{preset_id} - Status: {response.status_code}") - - # Test 5: Send preset via /presets/send - total += 1 - try: - send_body = {"preset_ids": [preset_id]} - response = client.post('/presets/send', json_data=send_body) - if response.status_code == 200: - data = response.json() - sent = data.get('presets_sent') - print(f"✓ POST /presets/send - Sent presets (presets_sent={sent})") - passed += 1 - else: - print(f"✗ POST /presets/send - Status: {response.status_code}, Response: {response.text}") - except Exception as e: - print(f"✗ POST /presets/send - Error: {e}") - - # Test 6: Delete preset - total += 1 - response = client.delete(f'/presets/{preset_id}') - if response.status_code == 200: - print(f"✓ DELETE /presets/{preset_id} - Deleted preset") - passed += 1 - else: - print(f"✗ DELETE /presets/{preset_id} - Status: {response.status_code}") - else: - print(f"✗ POST /presets - Status: {response.status_code}") - except Exception as e: - print(f"✗ POST /presets - Error: {e}") - - print(f"\nPresets tests: {passed}/{total} passed") - return passed == total - -def test_patterns(client: TestClient) -> bool: - """Test patterns endpoints.""" - print("\n=== Testing Patterns Endpoints ===") - passed = 0 - total = 0 - - # Test 1: List patterns - total += 1 - try: - response = client.get('/patterns') - if response.status_code == 200: - data = response.json() - pattern_count = len(data) if isinstance(data, dict) else 0 - print(f"✓ GET /patterns - Found {pattern_count} patterns") - passed += 1 - else: - print(f"✗ GET /patterns - Status: {response.status_code}") - except Exception as e: - print(f"✗ GET /patterns - Error: {e}") - - # Test 2: Get pattern definitions - total += 1 - try: - response = client.get('/patterns/definitions') - if response.status_code == 200: - data = response.json() - print(f"✓ GET /patterns/definitions - Retrieved definitions") - passed += 1 - else: - print(f"✗ GET /patterns/definitions - Status: {response.status_code}") - except Exception as e: - print(f"✗ GET /patterns/definitions - Error: {e}") - - # Test 3: Firmware-only on/off — no OTA file (400 from API). - total += 1 - try: - r = client.get("/patterns/ota/file/on.py") - if r.status_code == 400 and "error" in r.json(): - print("✓ GET /patterns/ota/file/on.py - Rejected as built-in") - passed += 1 - else: - print(f"✗ GET /patterns/ota/file/on.py - Expected 400, got {r.status_code}") - except Exception as e: - print(f"✗ GET /patterns/ota/file/on.py - Error: {e}") - - total += 1 - try: - r = client.post("/patterns/off/send", json_data={}) - if r.status_code == 400 and "error" in r.json(): - print("✓ POST /patterns/off/send - Rejected as built-in") - passed += 1 - else: - print(f"✗ POST /patterns/off/send - Expected 400, got {r.status_code}") - except Exception as e: - print(f"✗ POST /patterns/off/send - Error: {e}") - - print(f"\nPatterns tests: {passed}/{total} passed") - return passed == total - -def test_zone_edit_workflow(client: TestClient) -> bool: - """Test complete zone edit workflow like a browser would.""" - print("\n=== Testing Zone Edit Workflow ===") - passed = 0 - total = 0 - - # Step 1: Create a zone to edit - total += 1 - try: - zone_data = { - "name": "Zone to Edit", - "names": ["1"] - } - response = client.post('/zones', json_data=zone_data) - if response.status_code == 201: - created = response.json() - if isinstance(created, dict): - zone_id = next(iter(created.keys())) if created else None - else: - zone_id = None - - if zone_id: - print(f"✓ Created zone {zone_id} for editing") - passed += 1 - - # Step 2: Get the zone to verify initial state - total += 1 - response = client.get(f'/zones/{zone_id}') - if response.status_code == 200: - original_zone = response.json() - print(f"✓ Retrieved zone - Name: '{original_zone.get('name')}', IDs: {original_zone.get('names')}") - passed += 1 - - # Step 3: Edit the zone (simulate browser edit form submission) - total += 1 - edit_data = { - "name": "Edited Zone Name", - "names": ["2", "3", "4"] - } - response = client.put(f'/zones/{zone_id}', json_data=edit_data) - if response.status_code == 200: - edited = response.json() - if edited.get('name') == "Edited Zone Name" and edited.get('names') == ["2", "3", "4"]: - print(f"✓ PUT /zones/{zone_id} - Successfully edited zone") - print(f" New name: '{edited.get('name')}'") - print(f" New device IDs: {edited.get('names')}") - passed += 1 - else: - print(f"✗ PUT /zones/{zone_id} - Edit didn't work correctly") - print(f" Got: {edited}") - else: - print(f"✗ PUT /zones/{zone_id} - Status: {response.status_code}, Response: {response.text}") - - # Step 4: Verify edit persisted by getting the zone again - total += 1 - response = client.get(f'/zones/{zone_id}') - if response.status_code == 200: - verified = response.json() - if verified.get('name') == "Edited Zone Name" and verified.get('names') == ["2", "3", "4"]: - print(f"✓ GET /zones/{zone_id} - Verified edit persisted") - passed += 1 - else: - print(f"✗ GET /zones/{zone_id} - Edit didn't persist") - print(f" Expected name='Edited Zone Name', got '{verified.get('name')}'") - print(f" Expected names=['2','3','4'], got {verified.get('names')}") - else: - print(f"✗ GET /zones/{zone_id} - Status: {response.status_code}") - - # Step 5: Clean up - delete the test zone - total += 1 - response = client.delete(f'/zones/{zone_id}') - if response.status_code == 200: - print(f"✓ DELETE /zones/{zone_id} - Cleaned up test zone") - passed += 1 - else: - print(f"✗ DELETE /zones/{zone_id} - Status: {response.status_code}") - else: - print(f"✗ Failed to extract zone ID from create response") - else: - print(f"✗ POST /zones - Status: {response.status_code}, Response: {response.text}") - except Exception as e: - print(f"✗ Zone edit workflow - Error: {e}") - import traceback - traceback.print_exc() - - print(f"\nZone edit workflow tests: {passed}/{total} passed") - return passed == total - -def test_static_files(client: TestClient) -> bool: - """Test static file serving.""" - print("\n=== Testing Static Files ===") - passed = 0 - total = 0 - - static_files = [ - '/static/style.css', - '/static/app.js', - '/static/zones.js', - '/static/presets.js', - '/static/profiles.js', - '/static/devices.js', - ] - - for file_path in static_files: - total += 1 - try: - response = client.get(file_path) - if response.status_code == 200: - print(f"✓ GET {file_path} - Retrieved") - passed += 1 - else: - print(f"✗ GET {file_path} - Status: {response.status_code}") - except Exception as e: - print(f"✗ GET {file_path} - Error: {e}") - - print(f"\nStatic files tests: {passed}/{total} passed") - return passed == total - -def main(): - """Run all endpoint tests.""" - print("=" * 60) - print("LED Controller Endpoint Tests") - print(f"Testing against: {BASE_URL}") - print("=" * 60) - - client = TestClient() - - # Test connection first - if not test_connection(client): - print("\n✗ Cannot connect to device. Exiting.") - sys.exit(1) - - results = [] - - # Run all tests - results.append(("Zones", test_zones(client))) - results.append(("Zone Edit Workflow", test_zone_edit_workflow(client))) - results.append(("Profiles", test_profiles(client))) - results.append(("Presets", test_presets(client))) - results.append(("Patterns", test_patterns(client))) - results.append(("Static Files", test_static_files(client))) - - # Summary - print("\n" + "=" * 60) - print("Test Summary") - print("=" * 60) - all_passed = True - for name, passed in results: - status = "✓ PASS" if passed else "✗ FAIL" - print(f"{status} - {name}") - if not passed: - all_passed = False - - print("=" * 60) - if all_passed: - print("✓ All tests passed!") - sys.exit(0) - else: - print("✗ Some tests failed") - sys.exit(1) - -if __name__ == "__main__": - main() diff --git a/tests/test_endpoints_pytest.py b/tests/test_endpoints_pytest.py deleted file mode 100644 index e1c73a6..0000000 --- a/tests/test_endpoints_pytest.py +++ /dev/null @@ -1,859 +0,0 @@ -import asyncio -import builtins -import json -import os -import sys -import threading -import time -import uuid -from pathlib import Path -from typing import Any, Dict, Optional - -import pytest -import requests - -# Ensure imports resolve to the repo's `src/` + `lib/` code. -PROJECT_ROOT = Path(__file__).resolve().parents[1] -SRC_PATH = PROJECT_ROOT / "src" -LIB_PATH = PROJECT_ROOT / "lib" - -for p in (str(SRC_PATH), str(LIB_PATH), str(PROJECT_ROOT)): - if p in sys.path: - sys.path.remove(p) - sys.path.insert(0, p) - -from microdot import Microdot, send_file # noqa: E402 -from microdot.session import Session # noqa: E402 -from microdot.websocket import with_websocket # noqa: E402 - - -class DummySender: - def __init__(self): - self.sent: list[tuple[str, Optional[str]]] = [] - - async def send(self, data: Any, addr: Optional[str] = None): - if isinstance(data, (bytes, bytearray)): - data = bytes(data).decode(errors="ignore") - self.sent.append((data, addr)) - return True - - -def _json(resp: requests.Response) -> Dict[str, Any]: - # Many endpoints already set Content-Type; but be tolerant for now. - return resp.json() # pragma: no cover - - -def _find_id_by_field(list_resp_json: Dict[str, Any], field: str, value: str) -> str: - for obj_id, data in list_resp_json.items(): - if isinstance(data, dict) and data.get(field) == value: - return str(obj_id) - raise AssertionError(f"Could not find id for {field}={value!r}") - - -def _start_microdot_server(app: Microdot, host: str, port: int): - """ - Start Microdot server on a background thread. - Returns (thread, chosen_port). - """ - - def runner(): - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - try: - loop.run_until_complete(app.start_server(host=host, port=port)) - finally: - try: - loop.close() - except Exception: - pass - - thread = threading.Thread(target=runner, daemon=True) - thread.start() - - # Poll until the socket is bound and app.server is available. - chosen_port = None - deadline = time.time() + 5.0 - while time.time() < deadline: - server = getattr(app, "server", None) - if server and getattr(server, "sockets", None): - sockets = server.sockets or [] - if sockets: - chosen_port = sockets[0].getsockname()[1] - break - time.sleep(0.05) - - if chosen_port is None: - raise RuntimeError("Microdot server failed to start in time") - - return thread, chosen_port - - -@pytest.fixture(scope="function") -def server(monkeypatch, tmp_path_factory): - """ - Start the Microdot app in-process and return a test client. - """ - - tmp_root = tmp_path_factory.mktemp("endpoint-tests") - tmp_db_dir = tmp_root / "db" - tmp_settings_file = tmp_root / "settings.json" - - # Be defensive: pytest runners can sometimes alter sys.path ordering. - for p in (str(SRC_PATH), str(LIB_PATH), str(PROJECT_ROOT)): - if p in sys.path: - sys.path.remove(p) - sys.path.insert(0, p) - - # Patch Settings so endpoint tests never touch real `settings.json`. - import settings as settings_mod # noqa: E402 - - settings_mod.Settings.SETTINGS_FILE = str(tmp_settings_file) - - # Patch the Model db directory so endpoint CRUD is isolated. - import models.model as model_mod # noqa: E402 - - monkeypatch.setattr(model_mod, "_db_dir", lambda: str(tmp_db_dir)) - - # Reset model singletons (controllers instantiate model classes at import time). - # Import the classes first so we can delete their `_instance` attribute if present. - import models.preset as models_preset # noqa: E402 - import models.profile as models_profile # noqa: E402 - import models.group as models_group # noqa: E402 - import models.zone as models_zone # noqa: E402 - import models.pallet as models_pallet # noqa: E402 - import models.scene as models_scene # noqa: E402 - import models.pattern as models_pattern # noqa: E402 - import models.squence as models_sequence # noqa: E402 - import models.device as models_device # noqa: E402 - import models.output as models_output # noqa: E402 - import engine as engine_pkg # noqa: E402 - - # Fresh Pi-side engine per test (it caches players and sequence tasks). - engine_pkg.set_engine(None) - - for cls in ( - models_preset.Preset, - models_profile.Profile, - models_group.Group, - models_zone.Zone, - models_pallet.Palette, - models_scene.Scene, - models_pattern.Pattern, - models_sequence.Sequence, - models_device.Device, - models_output.Output, - ): - if hasattr(cls, "_instance"): - delattr(cls, "_instance") - - # Patch open() so pattern definitions work after we `chdir` into src/. - orig_open = builtins.open - - def patched_open(file, *args, **kwargs): - if isinstance(file, str): - # Pattern controller loads definitions from a relative db/ path. - if file in {"db/pattern.json", "pattern.json", "/db/pattern.json"}: - file = str(PROJECT_ROOT / "db" / "pattern.json") - return orig_open(file, *args, **kwargs) - - monkeypatch.setattr(builtins, "open", patched_open) - - old_cwd = os.getcwd() - os.chdir(str(SRC_PATH)) - - dummy_sender = DummySender() - - try: - # Ensure controllers are imported fresh after our patching. - for mod_name in ( - "controllers.preset", - "controllers.profile", - "controllers.group", - "controllers.sequence", - "controllers.zone", - "controllers.palette", - "controllers.scene", - "controllers.pattern", - "controllers.settings", - "controllers.device", - "controllers.output", - ): - sys.modules.pop(mod_name, None) - - # Import controllers after patching db/settings/model singletons. - import controllers.preset as preset_ctl # noqa: E402 - import controllers.profile as profile_ctl # noqa: E402 - import controllers.group as group_ctl # noqa: E402 - import controllers.sequence as sequence_ctl # noqa: E402 - import controllers.zone as zone_ctl # noqa: E402 - import controllers.palette as palette_ctl # noqa: E402 - import controllers.scene as scene_ctl # noqa: E402 - import controllers.pattern as pattern_ctl # noqa: E402 - import controllers.settings as settings_ctl # noqa: E402 - import controllers.device as device_ctl # noqa: E402 - import controllers.output as output_ctl # noqa: E402 - - # Configure transport sender used by /presets/send. - from models.transport import set_sender # noqa: E402 - - set_sender(dummy_sender) - - app = Microdot() - - # Session secret key comes from settings (patched to tmp). - settings = settings_mod.Settings() - secret_key = settings.get( - "session_secret_key", - "led-controller-secret-key-change-in-production", - ) - Session(app, secret_key=secret_key) - - # Mount model controllers under their public prefixes. - app.mount(preset_ctl.controller, "/presets") - app.mount(profile_ctl.controller, "/profiles") - app.mount(group_ctl.controller, "/groups") - app.mount(sequence_ctl.controller, "/sequences") - app.mount(zone_ctl.controller, "/zones") - app.mount(palette_ctl.controller, "/palettes") - app.mount(scene_ctl.controller, "/scenes") - app.mount(pattern_ctl.controller, "/patterns") - app.mount(settings_ctl.controller, "/settings") - app.mount(device_ctl.controller, "/devices") - app.mount(output_ctl.controller, "/outputs") - - @app.route("/") - def index(request): - return send_file("templates/index.html") - - @app.route("/settings") - def settings_page(request): - return send_file("templates/settings.html") - - @app.route("/favicon.ico") - def favicon(request): - return "", 204 - - @app.route("/static/") - def static_handler(request, path): - if ".." in path: - return "Not found", 404 - return send_file("static/" + path) - - @app.route("/ws") - @with_websocket - async def ws(request, ws): - # Minimal websocket handler: forward raw JSON/text payloads to dummy sender. - while True: - data = await ws.receive() - if not data: - break - try: - parsed = json.loads(data) - addr = parsed.pop("to", None) - payload = json.dumps(parsed) if parsed else data - await dummy_sender.send(payload, addr=addr) - except Exception: - await dummy_sender.send(data) - - thread, chosen_port = _start_microdot_server(app, host="127.0.0.1", port=0) - base_url = f"http://127.0.0.1:{chosen_port}" - - client = requests.Session() - client.headers.update( - { - "User-Agent": "pytest/requests", - "Accept": "application/json", - } - ) - - yield { - "base_url": base_url, - "client": client, - "sender": dummy_sender, - "thread": thread, - "app": app, - } - finally: - # Stop server cleanly. - try: - app = locals().get("app") - if app is not None: - app.shutdown() - except Exception: - pass - - # Give it a moment to close sockets. - time.sleep(0.1) - try: - thread = locals().get("thread") - if thread is not None: - thread.join(timeout=5) - except Exception: - pass - - os.chdir(old_cwd) - - -def test_main_routes(server): - c: requests.Session = server["client"] - base_url: str = server["base_url"] - - resp = c.get(f"{base_url}/") - assert resp.status_code == 200 - assert "LED Controller" in resp.text - - resp = c.get(f"{base_url}/favicon.ico") - assert resp.status_code == 204 - - resp = c.get(f"{base_url}/static/style.css") - assert resp.status_code == 200 - - resp = c.get(f"{base_url}/settings/page") - assert resp.status_code == 200 - assert "LED Controller" in resp.text - - resp = c.get(f"{base_url}/ws") - # WebSocket endpoints should reject non-upgraded HTTP requests. - assert resp.status_code != 200 - assert resp.status_code in {400, 401, 403, 404, 405, 426} - - -def test_settings_controller(server): - c: requests.Session = server["client"] - base_url: str = server["base_url"] - - resp = c.get(f"{base_url}/settings") - assert resp.status_code == 200 - data = resp.json() - assert isinstance(data, dict) - assert "wifi_channel" in data - - resp = c.get(f"{base_url}/settings/wifi/ap") - assert resp.status_code == 200 - ap = resp.json() - assert "saved_ssid" in ap - assert "active" in ap - - unique_ssid = f"pytest-ssid-{uuid.uuid4().hex[:8]}" - resp = c.post( - f"{base_url}/settings/wifi/ap", - json={"ssid": unique_ssid, "password": "secret", "channel": 1}, - ) - assert resp.status_code == 200 - msg = resp.json() - assert msg["ssid"] == unique_ssid - assert msg["channel"] == 1 - - resp = c.post( - f"{base_url}/settings/wifi/ap", - json={"ssid": "bad-ssid", "password": "secret", "channel": 12}, - ) - assert resp.status_code == 400 - - resp = c.put(f"{base_url}/settings/settings", json={"wifi_channel": 11}) - assert resp.status_code == 200 - - resp = c.put(f"{base_url}/settings/settings", json={"wifi_channel": 12}) - assert resp.status_code == 400 - - resp = c.put(f"{base_url}/settings/settings", json={"global_brightness": 42}) - assert resp.status_code == 200 - resp = c.get(f"{base_url}/settings") - assert resp.status_code == 200 - assert resp.json().get("global_brightness") == 42 - - resp = c.put(f"{base_url}/settings/settings", json={"global_brightness": 300}) - assert resp.status_code == 400 - - -def test_profiles_presets_zones_endpoints(server, monkeypatch): - c: requests.Session = server["client"] - base_url: str = server["base_url"] - sender: DummySender = server["sender"] - - import controllers.device as device_ctl - - monkeypatch.setattr(device_ctl, "IDENTIFY_OFF_DELAY_S", 0.05) - - unique_profile_name = f"pytest-profile-{uuid.uuid4().hex[:8]}" - - resp = c.post(f"{base_url}/profiles", json={"name": unique_profile_name}) - assert resp.status_code == 201 - created = resp.json() - assert isinstance(created, dict) - profile_id = next(iter(created.keys())) - - resp = c.post(f"{base_url}/profiles/{profile_id}/apply") - assert resp.status_code == 200 - - resp = c.get(f"{base_url}/profiles/current") - assert resp.status_code == 200 - current = resp.json() - assert str(current["id"]) == str(profile_id) - - # Presets CRUD (scoped to current profile session). - resp = c.get(f"{base_url}/presets") - assert resp.status_code == 200 - presets = resp.json() - assert isinstance(presets, dict) - assert presets # seeded presets should exist - - first_preset_id = next(iter(presets.keys())) - resp = c.get(f"{base_url}/presets/{first_preset_id}") - assert resp.status_code == 200 - assert resp.json() # dict - - unique_preset_name = f"pytest-preset-{uuid.uuid4().hex[:8]}" - resp = c.post( - f"{base_url}/presets", - json={ - "name": unique_preset_name, - "pattern": "on", - "colors": ["#ff0000"], - "brightness": 123, - "delay": 100, - }, - ) - assert resp.status_code == 201 - created_preset = resp.json() - new_preset_id = next(iter(created_preset.keys())) - assert created_preset[new_preset_id]["profile_id"] == str(profile_id) - - resp = c.put( - f"{base_url}/presets/{new_preset_id}", - json={"brightness": 77}, - ) - assert resp.status_code == 200 - assert resp.json()["brightness"] == 77 - - sender.sent.clear() - resp = c.post( - f"{base_url}/presets/send", - json={"preset_ids": [new_preset_id], "save": False}, - ) - assert resp.status_code == 200 - sent_result = resp.json() - assert sent_result["presets_sent"] >= 1 - assert len(sender.sent) >= 1 - - resp = c.delete(f"{base_url}/presets/{new_preset_id}") - assert resp.status_code == 200 - resp = c.get(f"{base_url}/presets/{new_preset_id}") - assert resp.status_code == 404 - - # Zones CRUD (scoped to current profile session). - unique_zone_name = f"pytest-zone-{uuid.uuid4().hex[:8]}" - resp = c.post( - f"{base_url}/zones", - json={"name": unique_zone_name, "names": ["1", "2"]}, - ) - assert resp.status_code == 201 - created_zones = resp.json() - zone_id = next(iter(created_zones.keys())) - - resp = c.get(f"{base_url}/zones/{zone_id}") - assert resp.status_code == 200 - assert resp.json()["name"] == unique_zone_name - - resp = c.post(f"{base_url}/zones/{zone_id}/set-current") - assert resp.status_code == 200 - - resp = c.get(f"{base_url}/zones/current") - assert resp.status_code == 200 - assert resp.json()["zone_id"] == str(zone_id) - - resp = c.put( - f"{base_url}/zones/{zone_id}", - json={"name": f"{unique_zone_name}-updated", "names": ["3"]}, - ) - assert resp.status_code == 200 - assert resp.json()["names"] == ["3"] - - resp = c.post(f"{base_url}/zones/{zone_id}/clone", json={"name": "pytest-zone-clone"}) - assert resp.status_code == 201 - clone_payload = resp.json() - clone_id = next(iter(clone_payload.keys())) - - resp = c.get(f"{base_url}/zones/{clone_id}") - assert resp.status_code == 200 - - resp = c.delete(f"{base_url}/zones/{clone_id}") - assert resp.status_code == 200 - - resp = c.delete(f"{base_url}/zones/{zone_id}") - assert resp.status_code == 200 - - # Profile clone + update endpoints. - clone_name = f"pytest-profile-clone-{uuid.uuid4().hex[:8]}" - resp = c.post(f"{base_url}/profiles/{profile_id}/clone", json={"name": clone_name}) - assert resp.status_code == 201 - cloned = resp.json() - clone_profile_id = next(iter(cloned.keys())) - - resp = c.post(f"{base_url}/profiles/{clone_profile_id}/apply") - assert resp.status_code == 200 - - resp = c.put( - f"{base_url}/profiles/current", - json={"name": f"{clone_name}-updated"}, - ) - assert resp.status_code == 200 - - resp = c.put( - f"{base_url}/profiles/{clone_profile_id}", - json={"name": f"{clone_name}-updated-2"}, - ) - assert resp.status_code == 200 - - resp = c.delete(f"{base_url}/profiles/{clone_profile_id}") - assert resp.status_code == 200 - - resp = c.delete(f"{base_url}/profiles/{profile_id}") - assert resp.status_code == 200 - - -def test_groups_sequences_scenes_palettes_patterns_endpoints(server): - c: requests.Session = server["client"] - base_url: str = server["base_url"] - sender: DummySender = server["sender"] - - # Groups. - unique_group_name = f"pytest-group-{uuid.uuid4().hex[:8]}" - resp = c.post(f"{base_url}/groups", json={"name": unique_group_name}) - assert resp.status_code == 201 - groups_list = c.get(f"{base_url}/groups").json() - group_id = _find_id_by_field(groups_list, "name", unique_group_name) - - resp = c.get(f"{base_url}/groups/{group_id}") - assert resp.status_code == 200 - assert resp.json()["name"] == unique_group_name - - resp = c.put(f"{base_url}/groups/{group_id}", json={"brightness": 10}) - assert resp.status_code == 200 - assert resp.json()["brightness"] == 10 - - resp = c.delete(f"{base_url}/groups/{group_id}") - assert resp.status_code == 200 - - # Sequences. - unique_seq_name = f"pytest-seq-{uuid.uuid4().hex[:8]}" - resp = c.post( - f"{base_url}/sequences", - json={"name": unique_seq_name, "steps": [{"preset_id": "1", "duration_s": 2}]}, - ) - assert resp.status_code == 201 - sequences_list = c.get(f"{base_url}/sequences").json() - seq_id = _find_id_by_field(sequences_list, "name", unique_seq_name) - - resp = c.get(f"{base_url}/sequences/{seq_id}") - assert resp.status_code == 200 - assert resp.json()["steps"] == [{"preset_id": "1", "duration_s": 2.0}] - - resp = c.put(f"{base_url}/sequences/{seq_id}", json={"loop": False, "repeat_count": 2}) - assert resp.status_code == 200 - assert resp.json()["loop"] is False and resp.json()["repeat_count"] == 2 - - resp = c.put(f"{base_url}/sequences/{seq_id}", json={"steps": [{"duration_s": 1}]}) - assert resp.status_code == 400 - - # No zone_id -> cannot play. - resp = c.post(f"{base_url}/sequences/{seq_id}/play") - assert resp.status_code == 400 - - resp = c.get(f"{base_url}/sequences/status") - assert resp.status_code == 200 - - resp = c.delete(f"{base_url}/sequences/{seq_id}") - assert resp.status_code == 200 - - # Scenes. - unique_scene_name = f"pytest-scene-{uuid.uuid4().hex[:8]}" - resp = c.post(f"{base_url}/scenes", json={"name": unique_scene_name}) - assert resp.status_code == 201 - scenes_list = c.get(f"{base_url}/scenes").json() - scene_id = _find_id_by_field(scenes_list, "name", unique_scene_name) - - resp = c.get(f"{base_url}/scenes/{scene_id}") - assert resp.status_code == 200 - - resp = c.put(f"{base_url}/scenes/{scene_id}", json={"name": unique_scene_name + "-updated"}) - assert resp.status_code == 200 - assert resp.json()["name"].endswith("-updated") - - resp = c.delete(f"{base_url}/scenes/{scene_id}") - assert resp.status_code == 200 - - # Palettes. - colors = ["#112233", "#445566"] - resp = c.post(f"{base_url}/palettes", json={"colors": colors}) - assert resp.status_code == 201 - palette_payload = resp.json() - palette_id = str(palette_payload["id"]) - - resp = c.get(f"{base_url}/palettes/{palette_id}") - assert resp.status_code == 200 - assert resp.json()["id"] == palette_id - - resp = c.put(f"{base_url}/palettes/{palette_id}", json={"colors": ["#000000"]}) - assert resp.status_code == 200 - assert resp.json()["colors"] == ["#000000"] - - resp = c.delete(f"{base_url}/palettes/{palette_id}") - assert resp.status_code == 200 - - # Devices (LED driver registry). - resp = c.get(f"{base_url}/devices") - assert resp.status_code == 200 - assert resp.json() == {} - - resp = c.post(f"{base_url}/devices", json={}) - assert resp.status_code == 400 - - resp = c.post( - f"{base_url}/devices", - json={"name": "pytest-dev", "address": "aa:bb:cc:dd:ee:ff"}, - ) - assert resp.status_code == 201 - dev_map = resp.json() - dev_id = next(iter(dev_map.keys())) - assert dev_id == "aabbccddeeff" - assert dev_map[dev_id]["name"] == "pytest-dev" - assert dev_map[dev_id]["id"] == dev_id - assert dev_map[dev_id]["type"] == "led" - assert dev_map[dev_id]["transport"] == "espnow" - assert dev_map[dev_id]["address"] == "aabbccddeeff" - - resp = c.get(f"{base_url}/devices/{dev_id}") - assert resp.status_code == 200 - assert resp.json()["name"] == "pytest-dev" - assert resp.json()["type"] == "led" - assert resp.json().get("connected") is None - - resp = c.get(f"{base_url}/devices") - assert resp.status_code == 200 - assert resp.json()[dev_id].get("connected") is None - - sender.sent.clear() - resp = c.post(f"{base_url}/devices/{dev_id}/identify") - assert resp.status_code == 200 - assert resp.json().get("message") - assert len(sender.sent) >= 1 - first = json.loads(sender.sent[0][0]) - assert "presets" in first and "select" in first - assert first["presets"]["__identify"]["p"] == "blink" - assert first["presets"]["__identify"]["d"] == 50 - assert first["select"]["pytest-dev"] == ["__identify"] - deadline = time.monotonic() + 2.0 - while len(sender.sent) < 2 and time.monotonic() < deadline: - time.sleep(0.02) - assert len(sender.sent) >= 2 - second = json.loads(sender.sent[1][0]) - assert second.get("select") == {"pytest-dev": ["off"]} - - resp = c.post( - f"{base_url}/devices", - json={ - "name": "pytest-wifi", - "type": "led", - "transport": "wifi", - "address": "192.168.50.10", - "mac": "102030405060", - }, - ) - assert resp.status_code == 201 - wid = "102030405060" - assert wid in resp.json() - assert resp.json()[wid]["transport"] == "wifi" - assert resp.json()[wid]["address"] == "192.168.50.10" - - resp = c.get(f"{base_url}/devices/{wid}") - assert resp.status_code == 200 - assert resp.json().get("connected") is False - - resp = c.post( - f"{base_url}/devices", - json={ - "name": "pytest-wifi", - "transport": "wifi", - "address": "192.168.50.11", - "mac": "102030405061", - }, - ) - assert resp.status_code == 201 - wid2 = "102030405061" - assert wid2 in resp.json() - assert resp.json()[wid2]["name"] == "pytest-wifi" - - resp = c.post( - f"{base_url}/devices", - json={ - "name": "pytest-wifi-dupmac", - "transport": "wifi", - "address": "192.168.50.99", - "mac": "102030405060", - }, - ) - assert resp.status_code == 409 - - resp = c.post( - f"{base_url}/devices", - json={"name": "no-mac-wifi", "transport": "wifi", "address": "192.168.50.12"}, - ) - assert resp.status_code == 400 - - resp = c.post( - f"{base_url}/devices", - json={"name": "bad-tr", "transport": "serial"}, - ) - assert resp.status_code == 400 - - resp = c.put(f"{base_url}/devices/{dev_id}", json={"name": " "}) - assert resp.status_code == 400 - - resp = c.put(f"{base_url}/devices/{dev_id}", json={"name": "renamed"}) - assert resp.status_code == 200 - assert resp.json()["name"] == "renamed" - - resp = c.put(f"{base_url}/devices/{wid}", json={"name": "renamed"}) - assert resp.status_code == 200 - assert resp.json()["name"] == "renamed" - - resp = c.delete(f"{base_url}/devices/{wid2}") - assert resp.status_code == 200 - - resp = c.delete(f"{base_url}/devices/{wid}") - assert resp.status_code == 200 - - resp = c.delete(f"{base_url}/devices/{dev_id}") - assert resp.status_code == 200 - - # Patterns. - resp = c.get(f"{base_url}/patterns/definitions") - assert resp.status_code == 200 - definitions = resp.json() - assert isinstance(definitions, dict) - - pattern_id = f"pytest_pattern_{uuid.uuid4().hex[:8]}" - resp = c.post( - f"{base_url}/patterns", - json={"name": pattern_id, "data": {"foo": "bar"}}, - ) - assert resp.status_code == 201 - assert resp.json()["foo"] == "bar" - - resp = c.get(f"{base_url}/patterns") - assert resp.status_code == 200 - patterns_list = resp.json() - assert isinstance(patterns_list, dict) - # Runtime list merges repo ``db/pattern.json`` + driver ``.py`` names; test DB - # entries are still exposed on GET /patterns/ after POST. - assert "blink" in patterns_list or len(patterns_list) >= 1 - - resp = c.get(f"{base_url}/patterns/{pattern_id}") - assert resp.status_code == 200 - assert resp.json()["foo"] == "bar" - - resp = c.put(f"{base_url}/patterns/{pattern_id}", json={"baz": 1}) - assert resp.status_code == 200 - assert resp.json()["baz"] == 1 - - resp = c.delete(f"{base_url}/patterns/{pattern_id}") - assert resp.status_code == 200 - - # on/off are firmware-only in presets.py — no OTA file; API rejects serve/send/upload/driver. - resp = c.get(f"{base_url}/patterns/ota/file/on.py") - assert resp.status_code == 400 - assert "error" in resp.json() - - resp = c.post(f"{base_url}/patterns/off/send", json={}) - assert resp.status_code == 400 - assert "error" in resp.json() - - resp = c.post( - f"{base_url}/patterns/upload", - json={"name": "on.py", "code": "class On:\n def run(self, p):\n yield\n"}, - ) - assert resp.status_code == 400 - - resp = c.post( - f"{base_url}/patterns/driver", - json={ - "name": "off", - "code": "class Off:\n def run(self, p):\n yield\n", - }, - ) - assert resp.status_code == 400 - - - -def test_engine_outputs_zone_play_and_sequences(server): - c: requests.Session = server["client"] - base_url: str = server["base_url"] - sender: DummySender = server["sender"] - - # Outputs CRUD + validation. - resp = c.post(f"{base_url}/outputs", json={"name": "wall", "protocol": "ddp"}) - assert resp.status_code == 400 and "host" in resp.json()["error"] - resp = c.post( - f"{base_url}/outputs", - json={"name": "wall", "protocol": "ddp", "host": "127.0.0.1", "port": 9, "pixel_count": 10}, - ) - assert resp.status_code == 201 - output_id = resp.json()["id"] - resp = c.put(f"{base_url}/outputs/{output_id}", json={"color_order": "grb"}) - assert resp.status_code == 200 and resp.json()["color_order"] == "grb" - resp = c.post(f"{base_url}/outputs/{output_id}/test", json={"step_s": 0.1}) - assert resp.status_code == 200 and resp.json()["status"]["frames"] > 0 - - # A profile gives us presets + a zone; add a pixel output and an ESP32 name to it. - resp = c.post(f"{base_url}/profiles", json={"name": f"pytest-engine-{uuid.uuid4().hex[:6]}"}) - assert resp.status_code in (200, 201) - profile_id = str(resp.json().get("id") or next(iter(resp.json()))) - c.post(f"{base_url}/profiles/{profile_id}/apply") - preset = c.post(f"{base_url}/presets", json={"name": "pytest-on", "pattern": "on", "colors": ["#ff0000"]}) - assert preset.status_code == 201 - preset_id = str(next(iter(preset.json()))) - zone = c.post(f"{base_url}/zones", json={"name": "pytest-engine-zone", "names": ["wall", "dj"]}) - assert zone.status_code in (200, 201) - zone_id = str(zone.json().get("id") or next(iter(zone.json()))) - c.put(f"{base_url}/zones/{zone_id}", json={"names": ["wall", "dj"]}) - - resp = c.post(f"{base_url}/zones/{zone_id}/play", json={}) - assert resp.status_code == 400 - resp = c.post(f"{base_url}/zones/{zone_id}/play", json={"preset_id": "nope"}) - assert resp.status_code == 404 - - sender.sent.clear() - resp = c.post(f"{base_url}/zones/{zone_id}/play", json={"preset_id": preset_id}) - assert resp.status_code == 200, resp.text - status = resp.json() - assert status["preset_id"] == preset_id and status["frame_length"] == 10 - kinds = sorted(o["kind"] for o in status["outputs"]) - assert kinds == ["frame", "preset"] - # "dj" has no registered device -> preset + select still broadcast to the bridge. - sent = [json.loads(d) for d, _a in sender.sent] - assert any(m.get("presets", {}).get(preset_id) for m in sent) - assert {"v": "1", "select": {"dj": [preset_id]}} in sent - - resp = c.get(f"{base_url}/zones/engine/status") - assert zone_id in resp.json()["zones"] - - # Sequence on the zone. - resp = c.post( - f"{base_url}/sequences", - json={"name": "pytest-engine-seq", "zone_id": zone_id, "loop": False, - "steps": [{"preset_id": preset_id, "duration_s": 0.5}]}, - ) - seq_id = next(k for k, v in c.get(f"{base_url}/sequences").json().items() - if v.get("name") == "pytest-engine-seq") - resp = c.post(f"{base_url}/sequences/{seq_id}/play") - assert resp.status_code == 200 and resp.json()["zone_id"] == zone_id - assert c.get(f"{base_url}/sequences/{seq_id}").json()["active"] is True - resp = c.post(f"{base_url}/sequences/{seq_id}/stop") - assert resp.json()["stopped"] is True - assert c.get(f"{base_url}/sequences/{seq_id}").json()["active"] is False - - resp = c.post(f"{base_url}/zones/{zone_id}/stop") - assert resp.json()["stopped"] is True - resp = c.delete(f"{base_url}/outputs/{output_id}") - assert resp.status_code == 200 diff --git a/tests/test_main_old.py b/tests/test_main_old.py deleted file mode 100644 index 7c4a6db..0000000 --- a/tests/test_main_old.py +++ /dev/null @@ -1,16 +0,0 @@ -import pytest - -pytest.skip("Legacy manual server script (not a pytest suite).", allow_module_level=True) - -from microdot import Microdot -from src.profile import profile_app - -app = Microdot() - -@app.route('/') -async def index(request): - return 'Hello, world!' - -app.mount(profile_app, url_prefix="/profile") - -app.run(port=8080, debug=True) \ No newline at end of file diff --git a/tests/test_pattern_ota_send.py b/tests/test_pattern_ota_send.py deleted file mode 100644 index b16baa3..0000000 --- a/tests/test_pattern_ota_send.py +++ /dev/null @@ -1,99 +0,0 @@ -#!/usr/bin/env python3 -""" -Manual test helper for pattern OTA send flow. - -Examples: - python tests/test_pattern_ota_send.py --base-url http://led.local --pattern blink - python tests/test_pattern_ota_send.py --base-url http://127.0.0.1:8080 --pattern blink --device-id 102030405060 -""" - -import argparse -import json -import sys -from urllib import request, error - - -def _http_json(method, url, payload=None): - data = None - headers = {"Accept": "application/json"} - if payload is not None: - data = json.dumps(payload).encode("utf-8") - headers["Content-Type"] = "application/json" - req = request.Request(url, data=data, method=method, headers=headers) - try: - with request.urlopen(req, timeout=15) as resp: - body = resp.read().decode("utf-8") - return resp.status, json.loads(body) if body else {} - except error.HTTPError as e: - body = e.read().decode("utf-8") - try: - parsed = json.loads(body) if body else {} - except Exception: - parsed = {"raw": body} - return e.code, parsed - - -def main(): - parser = argparse.ArgumentParser(description="Test /patterns//send OTA flow.") - parser.add_argument( - "--base-url", - default="http://127.0.0.1", - help="Controller base URL (default: http://127.0.0.1)", - ) - parser.add_argument( - "--pattern", - required=True, - help="Pattern name (without .py), e.g. blink", - ) - parser.add_argument( - "--device-id", - default="", - help="Optional device id (MAC). If omitted, sends to all Wi-Fi devices.", - ) - args = parser.parse_args() - - base = args.base_url.rstrip("/") - pattern = args.pattern.strip() - if not pattern: - print("Pattern name is required.") - return 2 - - # Quick visibility before send. - status, patterns = _http_json("GET", f"{base}/patterns") - print(f"GET /patterns -> {status}") - if status != 200: - print(patterns) - return 1 - if pattern not in patterns: - print(f"Pattern {pattern!r} not found in /patterns list.") - return 1 - - status, devices = _http_json("GET", f"{base}/devices") - print(f"GET /devices -> {status}") - if status != 200: - print(devices) - return 1 - wifi_ids = [ - did - for did, d in (devices or {}).items() - if isinstance(d, dict) and str(d.get("transport", "")).lower() == "wifi" - ] - print(f"Wi-Fi devices in registry: {len(wifi_ids)}") - if wifi_ids: - print(" - " + "\n - ".join(wifi_ids)) - - payload = {"device_id": args.device_id} if args.device_id else {} - status, result = _http_json( - "POST", f"{base}/patterns/{pattern}/send", payload=payload - ) - print(f"POST /patterns/{pattern}/send -> {status}") - print(json.dumps(result, indent=2)) - - if status != 200: - return 1 - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) - diff --git a/tests/udp_server.py b/tests/udp_server.py deleted file mode 100644 index 24234d3..0000000 --- a/tests/udp_server.py +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/env python3 -"""UDP echo server for testing the led-driver UDP client (MicroPython ESP32). - -Listens on UDP, prints each datagram (peer + payload), sends the same bytes back. - -Run on the Pi (or any host on the LAN): - - python3 tests/udp_server.py - python3 tests/udp_server.py -p 8766 --bind 0.0.0.0 - -Pair with **`led-driver/tests/udp_client.py`**: the device broadcasts a hello; this server -echoes so the client learns the controller's **unicast IP** from the reply (firmware uses that -for HTTP to the web server only; it is not stored in settings). Some Wi‑Fi APs block broadcast between clients — -prefer a wired listener. -""" - -from __future__ import annotations - -import argparse -import json -import socket -import sys - - -DEFAULT_PORT = 8766 - - -def main() -> int: - parser = argparse.ArgumentParser(description="UDP echo server for led-driver tests") - parser.add_argument( - "--bind", - default="0.0.0.0", - metavar="ADDR", - help="Address to bind (default: all interfaces)", - ) - parser.add_argument( - "-p", - "--port", - type=int, - default=DEFAULT_PORT, - help=f"UDP port (default: {DEFAULT_PORT})", - ) - args = parser.parse_args() - - sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - try: - sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - except (AttributeError, OSError): - pass - try: - sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) - except (AttributeError, OSError): - pass - try: - sock.bind((args.bind, args.port)) - except OSError as e: - print(f"bind {args.bind!r}:{args.port} failed: {e}", file=sys.stderr) - return 1 - - print(f"UDP echo listening on {args.bind}:{args.port} (Ctrl+C to stop)") - while True: - try: - data, addr = sock.recvfrom(2048) - except KeyboardInterrupt: - print("\nStopping.") - return 0 - client_ip, client_port = addr[0], addr[1] - text = data.decode("utf-8", errors="replace") - print(f"client_ip={client_ip} client_udp_port={client_port} ({len(data)} bytes)") - print(f" payload: {text!r}") - line = data.split(b"\n", 1)[0].strip() - if line: - try: - obj = json.loads(line.decode("utf-8")) - if isinstance(obj, dict) and obj.get("type") == "led": - print( - " hello: device_name=%r mac=%r v=%r" - % (obj.get("device_name"), obj.get("mac"), obj.get("v")) - ) - except (UnicodeError, ValueError, TypeError): - pass - try: - sock.sendto(data, addr) - except OSError as e: - print(f" sendto failed: {e}", file=sys.stderr) - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/tests/web.py b/tests/web.py deleted file mode 100755 index c84b52f..0000000 --- a/tests/web.py +++ /dev/null @@ -1,342 +0,0 @@ -#!/usr/bin/env python3 -""" -Local development web server - imports and runs src.main with port 5000 -""" - -import sys -import os -import asyncio -import signal - -# Add project root, src, and lib to path -project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -src_path = os.path.join(project_root, 'src') -lib_path = os.path.join(project_root, 'lib') - -# Add to path in the right order - src must be first so 'models' and 'controllers' can be imported -# This ensures imports like 'from models.preset import Preset' work -sys.path.insert(0, src_path) -sys.path.insert(0, lib_path) -sys.path.insert(0, project_root) - -# Mock MicroPython modules before importing main -class MockMachine: - class WDT: - def __init__(self, timeout): - pass - def feed(self): - pass - -class MockESPNow: - def __init__(self): - self.active_value = False - self.peers = [] - self.websocket_client = None # Store single WebSocket connection - def active(self, value): - self.active_value = value - print(f"[MOCK] ESPNow active: {value}") - def add_peer(self, peer): - self.peers.append(peer) - if hasattr(peer, 'hex'): - print(f"[MOCK] Added peer: {peer.hex()}") - else: - print(f"[MOCK] Added peer: {peer}") - def register_websocket(self, ws): - """Register a WebSocket connection to forward ESPNow data to.""" - self.websocket_client = ws - print(f"[MOCK] Registered WebSocket client") - def unregister_websocket(self, ws): - """Unregister a WebSocket connection.""" - if self.websocket_client == ws: - self.websocket_client = None - print(f"[MOCK] Unregistered WebSocket client") - async def asend(self, peer, data): - if hasattr(peer, 'hex'): - print(f"[MOCK] Would send to {peer.hex()}: {data}") - else: - print(f"[MOCK] Would send to {peer}: {data}") - - # Forward data to the connected WebSocket client - if self.websocket_client: - try: - await self.websocket_client.send(data) - print(f"[MOCK] Forwarded to WebSocket client") - except Exception as e: - print(f"[MOCK] WebSocket client disconnected: {e}") - self.websocket_client = None - -class MockAIOESPNow: - def __init__(self): - self.espnow = MockESPNow() - def active(self, value): - self.espnow.active(value) - return self.espnow - def add_peer(self, peer): - self.espnow.add_peer(peer) - async def asend(self, peer, data): - await self.espnow.asend(peer, data) - - # Store reference to mock instance for WebSocket registration - @property - def mock_instance(self): - return self.espnow - -# Create mock ESPNow instance and store reference for WebSocket registration -mock_espnow_instance = MockESPNow() -mock_aioespnow = MockAIOESPNow() -mock_aioespnow.espnow = mock_espnow_instance # Use the shared instance - -# Create mock ESPNow instance and store reference for WebSocket registration -mock_espnow_instance = MockESPNow() -mock_aioespnow = MockAIOESPNow() -mock_aioespnow.espnow = mock_espnow_instance # Use the shared instance - -# Install mocks in sys.modules before any imports -sys.modules['machine'] = MockMachine() -# Store the mock instance in the module so it can be accessed -aioespnow_module = type('module', (), {'AIOESPNow': MockAIOESPNow, '_mock_instance': mock_espnow_instance})() -sys.modules['aioespnow'] = aioespnow_module -class MockWLAN: - def __init__(self, interface): - self.interface = interface - def active(self, value): - print(f"[MOCK] WLAN({self.interface}) active: {value}") - -sys.modules['network'] = type('module', (), { - 'WLAN': MockWLAN, - 'STA_IF': 0 -})() - -# Mock asyncio.sleep_ms for regular Python -_original_sleep = asyncio.sleep -async def sleep_ms(ms): - await _original_sleep(ms / 1000.0) - -# Patch asyncio.sleep_ms -asyncio.sleep_ms = sleep_ms - -# Patch sys.print_exception for regular Python (MicroPython has this, regular Python doesn't) -if not hasattr(sys, 'print_exception'): - import traceback - sys.print_exception = lambda e, file=None: traceback.print_exception(type(e), e, e.__traceback__, file=file) - -# Patch builtins.open to redirect /db/ paths to project db directory -import builtins -_original_open = builtins.open -def patched_open(file, mode='r', *args, **kwargs): - if isinstance(file, str): - if file.startswith('/db/'): - # Redirect to project db directory - filename = os.path.basename(file) - file = os.path.join(project_root, 'db', filename) - elif not os.path.isabs(file): - # For relative paths starting with templates/ or static/, - # always resolve to src/ directory - if file.startswith('templates/') or file.startswith('static/'): - file = os.path.join(src_path, file) - # For other relative paths, check if they exist in current dir - # If not, try src/ directory - elif not os.path.exists(file): - src_file = os.path.join(src_path, file) - if os.path.exists(src_file): - file = src_file - return _original_open(file, mode, *args, **kwargs) -builtins.open = patched_open - -# Also patch os.mkdir to handle /db path -original_mkdir = os.mkdir -def patched_mkdir(path): - if path == "/db": - # Use project db directory instead - db_path = os.path.join(project_root, "db") - if not os.path.exists(db_path): - os.makedirs(db_path, exist_ok=True) - else: - original_mkdir(path) -os.mkdir = patched_mkdir - -# Create a flag to stop the infinite loop -_stop_flag = False - -# Patch gc.collect to check stop flag -import gc as gc_module -_original_collect = gc_module.collect -def collect(): - global _stop_flag - if _stop_flag: - raise KeyboardInterrupt("Stop requested") - return _original_collect() -gc_module.collect = collect - -# Change to src directory for file paths (where templates and static are) -# main.py expects templates/ and static/ to be relative to the working directory -os.chdir(src_path) - -# Override settings path for local development -# Import settings module and patch the path before main imports it -import importlib.util -spec = importlib.util.spec_from_file_location("settings", os.path.join(src_path, "settings.py")) -settings_module = importlib.util.module_from_spec(spec) -sys.modules['settings'] = settings_module -spec.loader.exec_module(settings_module) -settings_module.Settings.SETTINGS_FILE = os.path.join(project_root, 'settings.json') - -# Patch the Model class file path before importing -# We need to monkey-patch the model.py file's behavior -import importlib.util -model_spec = importlib.util.spec_from_file_location("models.model", os.path.join(src_path, "models", "model.py")) -model_module = importlib.util.module_from_spec(model_spec) - -# Patch os.mkdir in the model module's context -original_mkdir = os.mkdir -def patched_mkdir(path): - if path == "/db": - db_path = os.path.join(project_root, "db") - if not os.path.exists(db_path): - os.makedirs(db_path, exist_ok=True) - else: - original_mkdir(path) - -# Set up the module's namespace with patched os -model_module.__dict__['os'] = type('os', (), {'mkdir': patched_mkdir, 'path': os.path})() -model_spec.loader.exec_module(model_module) -sys.modules['models.model'] = model_module - -# Now patch the Model class to fix file paths -# The issue is that Model.__init__ sets self.file and immediately calls load() -# before we can patch it. We need to replace __init__ completely. -# Also clear any existing singleton instances -Model = model_module.Model -# Clear singleton instances for all Model subclasses -for attr_name in dir(model_module): - attr = getattr(model_module, attr_name) - if isinstance(attr, type) and issubclass(attr, Model) and attr != Model: - if hasattr(attr, '_instance'): - delattr(attr, '_instance') - -original_save = Model.save -original_load = Model.load -original_set_defaults = Model.set_defaults - -def patched_init(self): - # Only initialize once (check if already initialized) - if hasattr(self, '_initialized'): - return - - # Create db directory if it doesn't exist (use project db, not /db) - db_path = os.path.join(project_root, "db") - if not os.path.exists(db_path): - os.makedirs(db_path, exist_ok=True) - - self.class_name = self.__class__.__name__ - # Set file path to project db directory from the start - self.file = os.path.join(project_root, 'db', f"{self.class_name.lower()}.json") - super(Model, self).__init__() - - # Now call load with the correct path already set - # Call the patched load method (defined below) - Model.load(self) - self._initialized = True - -def patched_save(self): - # Ensure file path is correct before saving (this will also fix print statements) - if hasattr(self, 'file') and self.file.startswith('/db/'): - filename = os.path.basename(self.file) - self.file = os.path.join(project_root, 'db', filename) - # Also ensure the directory exists - db_dir = os.path.dirname(self.file) - if not os.path.exists(db_dir): - os.makedirs(db_dir, exist_ok=True) - return original_save(self) - -def patched_load(self): - # Ensure file path is correct before loading - if hasattr(self, 'file') and self.file.startswith('/db/'): - filename = os.path.basename(self.file) - self.file = os.path.join(project_root, 'db', filename) - try: - with open(self.file, 'r') as file: - import json - loaded_settings = json.load(file) - # Use dict.update() directly, not the subclass's update() method - dict.update(self, loaded_settings) - print(f"{self.class_name} loaded successfully.") - except FileNotFoundError: - # File doesn't exist yet - this is normal on first run - print(f"No existing {self.class_name} file found, creating defaults.") - self.set_defaults() - self.save() - except Exception as e: - # Other errors - log and create defaults - print(f"Error loading {self.class_name}: {type(e).__name__}: {e}") - self.set_defaults() - self.save() - -# Apply patches - load must be patched before init uses it -Model.load = patched_load -Model.__init__ = patched_init -Model.save = patched_save - -# Patch with_websocket decorator before importing main to register WebSocket connections -from microdot.websocket import with_websocket as original_with_websocket - -def patched_with_websocket(f): - """Patched with_websocket decorator that registers connections with mock ESPNow.""" - @original_with_websocket - async def wrapped_handler(request, ws): - # Register WebSocket connection with mock ESPNow - mock_espnow_instance.register_websocket(ws) - try: - # Call original handler - await f(request, ws) - finally: - # Unregister when connection closes - mock_espnow_instance.unregister_websocket(ws) - return wrapped_handler - -# Now import main (which will use the patched settings module and model) -# Import as a module file directly to avoid package import issues -main_spec = importlib.util.spec_from_file_location("main", os.path.join(src_path, "main.py")) -main_module = importlib.util.module_from_spec(main_spec) - -# Patch with_websocket in the main module before executing it -main_module.__dict__['with_websocket'] = patched_with_websocket - -main_spec.loader.exec_module(main_module) -main = main_module.main - -def signal_handler(sig, frame): - """Handle Ctrl+C gracefully.""" - global _stop_flag - print("\nShutting down server...") - _stop_flag = True - # Force exit since main has an infinite loop - sys.exit(0) - -async def run_web(): - """Run main with port 5000.""" - print("Starting LED Controller Web Server (Local Development)") - print("=" * 60) - print(f"Server will run on http://localhost:5000") - print("Press Ctrl+C to stop") - print("=" * 60) - - # Set up signal handler - signal.signal(signal.SIGINT, signal_handler) - - try: - # Call main with port 5000 - await main(port=5000) - except KeyboardInterrupt: - print("\nShutting down server...") - except Exception as e: - print(f"Error: {e}") - raise - -if __name__ == "__main__": - try: - asyncio.run(run_web()) - except KeyboardInterrupt: - print("\nExiting...") - except SystemExit: - pass diff --git a/tests/ws.py b/tests/ws.py deleted file mode 100644 index 8b2a6a3..0000000 --- a/tests/ws.py +++ /dev/null @@ -1,193 +0,0 @@ -import asyncio -import websockets -import json -import sys - -async def test_websocket(): - uri = "ws://192.168.4.1:8080/ws" - tests_passed = 0 - tests_total = 0 - - async def run_test(name, test_func): - nonlocal tests_passed, tests_total - tests_total += 1 - try: - result = await test_func() - if result is not False: - print(f"✓ {name}") - tests_passed += 1 - return True - else: - print(f"✗ {name} (failed)") - return False - except Exception as e: - print(f"✗ {name} (error: {e})") - return False - - try: - print(f"Connecting to WebSocket server at {uri}...") - async with websockets.connect(uri) as websocket: - print(f"✓ Connected to WebSocket server\n") - - # Test 1: Empty JSON - print("Test 1: Empty JSON") - await run_test("Send empty JSON", lambda: websocket.send(json.dumps({}))) - await asyncio.sleep(0.3) - - # Test 2: Pattern on with single color - print("\nTest 2: Pattern 'on'") - await run_test("Send on pattern", lambda: websocket.send(json.dumps({ - "settings": {"pattern": "on", "colors": ["#00ff00"], "brightness": 200} - }))) - await asyncio.sleep(0.3) - - # Test 3: Pattern blink - print("\nTest 3: Pattern 'blink'") - await run_test("Send blink pattern", lambda: websocket.send(json.dumps({ - "settings": {"pattern": "blink", "colors": ["#ff0000"], "delay": 500} - }))) - await asyncio.sleep(0.3) - - # Test 4: Pattern rainbow - print("\nTest 4: Pattern 'rainbow'") - await run_test("Send rainbow pattern", lambda: websocket.send(json.dumps({ - "settings": {"pattern": "rainbow", "delay": 100} - }))) - await asyncio.sleep(0.3) - - # Test 5: Pattern off - print("\nTest 5: Pattern 'off'") - await run_test("Send off pattern", lambda: websocket.send(json.dumps({ - "settings": {"pattern": "off"} - }))) - await asyncio.sleep(0.3) - - # Test 6: Multiple colors - print("\nTest 6: Multiple colors") - await run_test("Send multiple colors", lambda: websocket.send(json.dumps({ - "settings": { - "pattern": "color_transition", - "colors": ["#ff0000", "#00ff00", "#0000ff"], - "delay": 100 - } - }))) - await asyncio.sleep(0.3) - - # Test 7: RGB tuple colors (if supported) - print("\nTest 7: RGB tuple colors") - await run_test("Send RGB tuple colors", lambda: websocket.send(json.dumps({ - "settings": { - "pattern": "on", - "colors": [[255, 0, 128], [128, 255, 0]], - "brightness": 150 - } - }))) - await asyncio.sleep(0.3) - - # Test 8: Pattern with all parameters - print("\nTest 8: Pattern with all parameters") - await run_test("Send pattern with all params", lambda: websocket.send(json.dumps({ - "settings": { - "pattern": "flicker", - "colors": ["#ff8800"], - "brightness": 127, - "delay": 80, - "n1": 10, - "n2": 5, - "n3": 1, - "n4": 1 - } - }))) - await asyncio.sleep(0.3) - - # Test 9: Short-key format (df/dj) - print("\nTest 9: Short-key format (df/dj)") - await run_test("Send df/dj format", lambda: websocket.send(json.dumps({ - "df": {"pt": "on", "cl": ["#ff0000"], "br": 200}, - "dj": {"pa": "blink", "cl": ["#00ff00"], "dl": 500}, - "settings": {"pattern": "blink", "colors": ["#00ff00"], "delay": 500, "brightness": 200} - }))) - await asyncio.sleep(0.3) - - # Test 10: Rapid message sending - print("\nTest 10: Rapid message sending") - patterns = ["on", "off", "on", "blink"] - for i, pattern in enumerate(patterns): - p = pattern # Capture in closure - await run_test(f"Rapid send {i+1}/{len(patterns)}", lambda p=p: websocket.send(json.dumps({ - "settings": {"pattern": p, "colors": ["#ffffff"]} - }))) - await asyncio.sleep(0.1) - - # Test 11: Large message - print("\nTest 11: Large message") - large_colors = [f"#{i%256:02x}{i*2%256:02x}{i*3%256:02x}" for i in range(50)] - await run_test("Send large message", lambda: websocket.send(json.dumps({ - "settings": { - "pattern": "color_transition", - "colors": large_colors, - "delay": 50 - } - }))) - await asyncio.sleep(0.3) - - # Test 12: Invalid JSON (should be handled gracefully) - print("\nTest 12: Invalid JSON handling") - try: - await websocket.send("not valid json") - print("⚠ Invalid JSON sent (server should handle gracefully)") - tests_total += 1 - except Exception as e: - print(f"✗ Invalid JSON failed to send: {e}") - tests_total += 1 - - # Test 13: Malformed structure (missing settings) - print("\nTest 13: Malformed structure") - await run_test("Send message without settings", lambda: websocket.send(json.dumps({ - "pattern": "on", - "colors": ["#ff0000"] - }))) - await asyncio.sleep(0.3) - - # Test 14: Just settings key, no pattern - print("\nTest 14: Settings without pattern") - await run_test("Send settings without pattern", lambda: websocket.send(json.dumps({ - "settings": {"colors": ["#0000ff"], "brightness": 100} - }))) - await asyncio.sleep(0.3) - - # Test 15: Empty settings - print("\nTest 15: Empty settings") - await run_test("Send empty settings", lambda: websocket.send(json.dumps({ - "settings": {} - }))) - await asyncio.sleep(0.3) - - print(f"\n{'='*50}") - print(f"Tests completed: {tests_passed}/{tests_total} passed") - if tests_passed == tests_total: - print("✓ All tests passed!") - else: - print(f"⚠ {tests_total - tests_passed} test(s) failed") - print(f"{'='*50}") - - except websockets.exceptions.ConnectionClosedOK: - print("✓ WebSocket connection closed gracefully.") - except websockets.exceptions.ConnectionClosedError as e: - print(f"✗ WebSocket connection closed with error: {e}") - sys.exit(1) - except ConnectionRefusedError: - print(f"✗ Connection refused. Is the server running at {uri}?") - print("Make sure:") - print(" 1. The device is connected to WiFi") - print(" 2. The server is running on the device") - print(" 3. You can reach 192.168.4.1") - sys.exit(1) - except Exception as e: - print(f"✗ An unexpected error occurred: {e}") - import traceback - traceback.print_exc() - sys.exit(1) - -if __name__ == "__main__": - asyncio.run(test_websocket()) diff --git a/v2/dependencies.lock b/v2/dependencies.lock index cb4d42a..61d23c2 100644 --- a/v2/dependencies.lock +++ b/v2/dependencies.lock @@ -1,4 +1,14 @@ dependencies: + espressif/mdns: + component_hash: ef0766474b37459f6ad22461e453a8713e780e831a7c993b16919d817988dff6 + dependencies: + - name: idf + require: private + version: '>=5.0' + source: + registry_url: https://components.espressif.com/ + type: service + version: 1.14.1 idf: source: type: idf @@ -14,7 +24,8 @@ dependencies: type: service version: 1.23.1 direct_dependencies: +- espressif/mdns - joltwallet/littlefs -manifest_hash: 39931b5fd49af3f43a545f2b46eed14a91ad9a530706d1e14335b6dbea19a246 +manifest_hash: ca18d7304afd7b13c5257461792fe9f4b54a044914fa18a550807cfc4eb8cf67 target: esp32s3 version: 2.0.0 diff --git a/v2/docs/BENCH_TEST.md b/v2/docs/BENCH_TEST.md index 24d01fa..652b52e 100644 --- a/v2/docs/BENCH_TEST.md +++ b/v2/docs/BENCH_TEST.md @@ -27,7 +27,7 @@ tools/build_web.sh docker run --rm -v "$PWD":/project -w /project espressif/idf:v5.5.5 idf.py build ``` -Expect `Project build complete`, the app well under its 2 MB slot, and `build/www.bin` present. Fix ownership if Docker left it root-owned: `docker run --rm -v "$PWD":/project espressif/idf:v5.5.5 chown -R 0:0 /project`. +Expect `Project build complete`, the app well under its 2 MB slot, with the web UI embedded (`www_dist/www.pack`). Fix ownership if Docker left it root-owned: `docker run --rm -v "$PWD":/project espressif/idf:v5.5.5 chown -R 0:0 /project`. Flash with the S3 on USB (check which port it is; `ls /dev/ttyACM*`): @@ -35,7 +35,7 @@ Flash with the S3 on USB (check which port it is; `ls /dev/ttyACM*`): docker run --rm --device=/dev/ttyACM0 -v "$PWD":/project -w /project espressif/idf:v5.5.5 idf.py -p /dev/ttyACM0 flash ``` -This writes the bootloader, partition table, app and the web UI image. Watch the log: +This writes the bootloader, partition table and app (the web UI is part of the app). Watch the log: ```bash docker run --rm -it --device=/dev/ttyACM0 -v "$PWD":/project -w /project espressif/idf:v5.5.5 idf.py -p /dev/ttyACM0 monitor @@ -282,7 +282,7 @@ Groups: the controller sends a driver its group list when the driver announces i - **Devices show `last_ack_ms_ago: -1`:** the device record has no usable 12-character MAC in `address` or as its key. - **`beats_sent` rises but `echoes` stays 0:** the driver is not in `bench` mode, or it has not yet heard a controller frame (it learns the controller's MAC from the first data or digest frame; wait a few seconds). - **Resync never triggers:** the driver ignores a digest equal to its own version; confirm with `/status` that `link.ver` changed after the missed play. -- **Web UI is blank:** the `www` image was not built before flashing; run `tools/build_web.sh` and flash again. +- **Web UI is blank:** the web UI was not packed before the build; run `tools/build_web.sh` and build again (`make build` does this). ## 9. Cleanup diff --git a/v2/main/CMakeLists.txt b/v2/main/CMakeLists.txt index 7479c97..484924a 100644 --- a/v2/main/CMakeLists.txt +++ b/v2/main/CMakeLists.txt @@ -2,9 +2,10 @@ idf_component_register(SRCS "main.c" "mic.c" "beat.c" "beat_dsp.c" "espnow_tx.c" INCLUDE_DIRS "." REQUIRES esp_eth esp_netif esp_event esp_driver_spi esp_driver_gpio nvs_flash app_update esp_app_format esp_http_server esp_timer esp_driver_i2s esp_wifi esp_rom json esp_driver_gpio - PRIV_REQUIRES littlefs) + PRIV_REQUIRES littlefs mdns) -# Flash the gzipped web UI into the www partition (run tools/build_web.sh first) -if(EXISTS ${PROJECT_DIR}/www_dist) - littlefs_create_partition_image(www ${PROJECT_DIR}/www_dist FLASH_IN_PROJECT) +# The gzipped web UI is embedded in the app image (run tools/build_web.sh first) +if(NOT EXISTS ${PROJECT_DIR}/www_dist/www.pack) + message(FATAL_ERROR "www_dist/www.pack is missing: run v2/tools/build_web.sh (make build does)") endif() +target_add_binary_data(${COMPONENT_LIB} ${PROJECT_DIR}/www_dist/www.pack BINARY) diff --git a/v2/main/api.c b/v2/main/api.c index 63cc198..84b8f9c 100644 --- a/v2/main/api.c +++ b/v2/main/api.c @@ -198,6 +198,47 @@ static esp_err_t handle_profile_action(httpd_req_t *req, const char *id, const c return not_implemented(req, action); } +// Settings a driver keeps in its own settings.json and takes from a device_config message +static const char *const DEVICE_CONFIG_KEYS[] = { "max_brightness", "num_leds", "color_order", "startup_mode", "reversed" }; + +// The driver settings present in a device update, or NULL when it has none. Caller deletes the result. +static cJSON *device_config_from(const cJSON *body) +{ + cJSON *dc = NULL; + for (size_t i = 0; i < sizeof(DEVICE_CONFIG_KEYS) / sizeof(DEVICE_CONFIG_KEYS[0]); i++) { + const cJSON *v = cJSON_GetObjectItem(body, DEVICE_CONFIG_KEYS[i]); + if (!v || cJSON_IsNull(v)) { + continue; + } + if (!dc) { + dc = cJSON_CreateObject(); + } + cJSON_AddItemToObject(dc, DEVICE_CONFIG_KEYS[i], cJSON_Duplicate(v, true)); + } + return dc; +} + +// Send changed settings to an ESP-NOW driver; takes ownership of dc +static esp_err_t push_device_config(const cJSON *dev, cJSON *dc) +{ + const cJSON *tr = cJSON_GetObjectItem(dev, "transport"), *addr = cJSON_GetObjectItem(dev, "address"); + if (!cJSON_IsString(tr) || strcmp(tr->valuestring, "espnow") || !cJSON_IsString(addr)) { + cJSON_Delete(dc); + return ESP_ERR_INVALID_ARG; + } + cJSON *msg = cJSON_CreateObject(); + cJSON_AddStringToObject(msg, "v", "1"); + cJSON_AddItemToObject(msg, "device_config", dc); + cJSON_AddTrueToObject(msg, "save"); + cJSON *messages = cJSON_CreateArray(), *targets = cJSON_CreateArray(); + cJSON_AddItemToArray(messages, msg); + cJSON_AddItemToArray(targets, cJSON_CreateString(addr->valuestring)); + esp_err_t err = engine_push(messages, targets); + cJSON_Delete(messages); + cJSON_Delete(targets); + return err; +} + static esp_err_t collection_handler_inner(httpd_req_t *req) { char seg[3][64]; @@ -425,9 +466,13 @@ static esp_err_t collection_handler_inner(httpd_req_t *req) if (!body) { return ESP_OK; } + cJSON *dev_cfg = !strcmp(coll, "device") ? device_config_from(body) : NULL; merge(rec, body); cJSON_Delete(body); store_save(coll); + if (dev_cfg) { + push_device_config(rec, dev_cfg); // before the group resend: a second message right behind another may not be delivered + } if (!strcmp(coll, "zone") || !strcmp(coll, "device")) { engine_groups_changed(); } diff --git a/v2/main/idf_component.yml b/v2/main/idf_component.yml index 23b9928..24c8f0d 100644 --- a/v2/main/idf_component.yml +++ b/v2/main/idf_component.yml @@ -1,2 +1,3 @@ dependencies: joltwallet/littlefs: "^1.19.0" + espressif/mdns: "^1.4.0" diff --git a/v2/main/main.c b/v2/main/main.c index 8a30f48..a63fcbb 100644 --- a/v2/main/main.c +++ b/v2/main/main.c @@ -17,6 +17,13 @@ #include "esp_http_server.h" #include "esp_timer.h" #include "esp_system.h" +#include "mdns.h" +#include "lwip/ip4_addr.h" +#include "lwip/etharp.h" +#include "lwip/netif.h" +#include "lwip/sockets.h" +#include "esp_netif_net_stack.h" +#include "cJSON.h" #include "mic.h" #include "beat.h" #include "espnow_tx.h" @@ -71,6 +78,126 @@ static esp_err_t status_get_handler(httpd_req_t *req) return httpd_resp_sendstr(req, buf); } +#define DEFAULT_HOSTNAME "led-controller" + +static const char *settings_str(const char *key) +{ + cJSON *v = cJSON_GetObjectItem(store_settings(), key); + return cJSON_IsString(v) && v->valuestring[0] ? v->valuestring : NULL; +} + +// "static_ips" setting: a list of {ip, netmask, gw, dns} tried in order on every link-up. The first whose +// gateway answers ARP is kept; if none does, the controller falls back to DHCP. +static bool parse_static(cJSON *e, esp_netif_ip_info_t *info, esp_netif_dns_info_t *dns) +{ + const char *ip = NULL, *mask = "255.255.255.0", *gw = NULL, *d = NULL; + cJSON *v; + if (!cJSON_IsObject(e)) return false; + if (cJSON_IsString(v = cJSON_GetObjectItem(e, "ip"))) ip = v->valuestring; + if (cJSON_IsString(v = cJSON_GetObjectItem(e, "netmask"))) mask = v->valuestring; + if (cJSON_IsString(v = cJSON_GetObjectItem(e, "gw"))) gw = v->valuestring; + if (cJSON_IsString(v = cJSON_GetObjectItem(e, "dns"))) d = v->valuestring; + memset(info, 0, sizeof(*info)); + memset(dns, 0, sizeof(*dns)); + if (!ip || esp_netif_str_to_ip4(ip, &info->ip) != ESP_OK || esp_netif_str_to_ip4(mask, &info->netmask) != ESP_OK || + (gw && esp_netif_str_to_ip4(gw, &info->gw) != ESP_OK)) { + return false; + } + if (d && esp_netif_str_to_ip4(d, &dns->ip.u_addr.ip4) == ESP_OK) { + dns->ip.type = ESP_IPADDR_TYPE_V4; + } else if (gw) { + dns->ip.u_addr.ip4 = info->gw; + dns->ip.type = ESP_IPADDR_TYPE_V4; + } + return true; +} + +// Poke the gateway so lwIP ARPs for it, then wait for the entry to show up +static bool gateway_answers(esp_netif_t *netif, const esp_ip4_addr_t *gw) +{ + struct netif *nif = esp_netif_get_netif_impl(netif); + ip4_addr_t g = { .addr = gw->addr }; + int sock = socket(AF_INET, SOCK_DGRAM, 0); + if (!nif || sock < 0) { + if (sock >= 0) close(sock); + return false; + } + struct sockaddr_in to = { .sin_family = AF_INET, .sin_port = htons(9), .sin_addr.s_addr = gw->addr }; + bool ok = false; + for (int i = 0; i < 15 && !ok; i++) { + sendto(sock, "", 0, 0, (struct sockaddr *)&to, sizeof(to)); + vTaskDelay(pdMS_TO_TICKS(100)); + struct eth_addr *eth = NULL; + const ip4_addr_t *ipr = NULL; + ok = etharp_find_addr(nif, &g, ð, &ipr) >= 0; + } + close(sock); + return ok; +} + +static void static_ip_task(void *arg) +{ + static bool running; + if (running) { + vTaskDelete(NULL); + } + running = true; + cJSON *list = cJSON_GetObjectItem(store_settings(), "static_ips"); + esp_netif_dhcpc_stop(s_eth_netif); + bool done = false; + cJSON *e; + cJSON_ArrayForEach(e, list) { + esp_netif_ip_info_t info; + esp_netif_dns_info_t dns; + if (!parse_static(e, &info, &dns)) { + ESP_LOGW(TAG, "static_ips: skipping an invalid entry"); + continue; + } + if (esp_netif_set_ip_info(s_eth_netif, &info) != ESP_OK) { + continue; + } + if (dns.ip.type == ESP_IPADDR_TYPE_V4) { + esp_netif_set_dns_info(s_eth_netif, ESP_NETIF_DNS_MAIN, &dns); + } + if (info.gw.addr == 0 || gateway_answers(s_eth_netif, &info.gw)) { + ESP_LOGI(TAG, "Static IP " IPSTR " (gw " IPSTR ")", IP2STR(&info.ip), IP2STR(&info.gw)); + done = true; + break; + } + ESP_LOGI(TAG, "Static IP " IPSTR ": gateway " IPSTR " did not answer", IP2STR(&info.ip), IP2STR(&info.gw)); + } + if (!done) { + ESP_LOGW(TAG, "No static IP matched this network, using DHCP"); + esp_netif_ip_info_t none = { 0 }; + esp_netif_set_ip_info(s_eth_netif, &none); + esp_netif_dhcpc_start(s_eth_netif); + } + running = false; + vTaskDelete(NULL); +} + +static bool have_static_ips(void) +{ + cJSON *l = cJSON_GetObjectItem(store_settings(), "static_ips"); + return cJSON_IsArray(l) && cJSON_GetArraySize(l) > 0; +} + +static void start_mdns(void) +{ + const char *host = settings_str("hostname"); + if (!host) { + host = DEFAULT_HOSTNAME; + } + if (mdns_init() != ESP_OK) { + ESP_LOGE(TAG, "mDNS init failed"); + return; + } + mdns_hostname_set(host); + mdns_instance_name_set("LED controller"); + mdns_service_add(NULL, "_http", "_tcp", 80, NULL, 0); + ESP_LOGI(TAG, "mDNS: %s.local", host); +} + static void start_webserver(void) { if (s_server) { @@ -108,6 +235,9 @@ static void eth_event_handler(void *arg, esp_event_base_t event_base, esp_eth_ioctl(eth_handle, ETH_CMD_G_SPEED, &speed); esp_eth_ioctl(eth_handle, ETH_CMD_G_DUPLEX_MODE, &duplex); ESP_LOGI(TAG, "Ethernet Link Up, MAC " MACSTR, MAC2STR(mac)); + if (have_static_ips()) { + xTaskCreate(static_ip_task, "static_ip", 4096, NULL, 5, NULL); + } ESP_LOGI(TAG, "%s Mbps %s Duplex", speed == ETH_SPEED_100M ? "100" : "10", duplex == ETH_DUPLEX_FULL ? "Full" : "Half"); @@ -139,6 +269,11 @@ static void got_ip_event_handler(void *arg, esp_event_base_t event_base, // Server binds to all interfaces, so it keeps working across lease changes start_webserver(); + static bool mdns_started; + if (!mdns_started) { + mdns_started = true; + start_mdns(); + } } static esp_err_t w5500_init(esp_eth_handle_t *eth_handle_out) @@ -229,6 +364,9 @@ void app_main(void) s_eth_netif = esp_netif_new(&netif_cfg); ESP_ERROR_CHECK(esp_netif_attach(s_eth_netif, esp_eth_new_netif_glue(eth_handle))); + const char *host = settings_str("hostname"); + esp_netif_set_hostname(s_eth_netif, host ? host : DEFAULT_HOSTNAME); + ESP_ERROR_CHECK(esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, ð_event_handler, NULL)); ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &got_ip_event_handler, NULL)); diff --git a/v2/main/ota.c b/v2/main/ota.c index 8a86399..caa350b 100644 --- a/v2/main/ota.c +++ b/v2/main/ota.c @@ -6,6 +6,7 @@ #include "esp_ota_ops.h" #include "esp_app_format.h" #include "esp_system.h" +#include #include "esp_timer.h" static const char *TAG = "ota"; @@ -140,14 +141,35 @@ static esp_err_t ota_get_handler(httpd_req_t *req) { const esp_partition_t *run = esp_ota_get_running_partition(); const esp_app_desc_t *app = esp_app_get_description(); - char buf[256]; + // The build date is only recompiled with its own file, so the ELF hash is what tells two builds apart + char sha[17]; + for (int i = 0; i < 8; i++) { + snprintf(sha + 2 * i, 3, "%02x", app->app_elf_sha256[i]); + } + char buf[288]; snprintf(buf, sizeof(buf), - "{\"partition\":\"%s\",\"version\":\"%s\",\"built\":\"%s %s\",\"idf\":\"%s\"}", - run ? run->label : "?", app->version, app->date, app->time, app->idf_ver); + "{\"partition\":\"%s\",\"version\":\"%s\",\"built\":\"%s %s\",\"idf\":\"%s\",\"sha\":\"%s\"}", + run ? run->label : "?", app->version, app->date, app->time, app->idf_ver, sha); httpd_resp_set_type(req, "application/json"); return httpd_resp_sendstr(req, buf); } +static esp_err_t reboot_post_handler(httpd_req_t *req) +{ + ESP_LOGI(TAG, "reboot requested"); + httpd_resp_set_type(req, "application/json"); + httpd_resp_sendstr(req, "{\"message\":\"rebooting\"}"); + + static esp_timer_handle_t t; + const esp_timer_create_args_t args = { .callback = reboot_cb, .name = "reboot" }; + if (esp_timer_create(&args, &t) == ESP_OK) { + esp_timer_start_once(t, 500 * 1000); + } else { + esp_restart(); + } + return ESP_OK; +} + esp_err_t ota_register(httpd_handle_t server) { const httpd_uri_t post = { .uri = "/ota", .method = HTTP_POST, .handler = ota_post_handler }; @@ -156,5 +178,9 @@ esp_err_t ota_register(httpd_handle_t server) if (err == ESP_OK) { err = httpd_register_uri_handler(server, &get); } + const httpd_uri_t reboot = { .uri = "/reboot", .method = HTTP_POST, .handler = reboot_post_handler }; + if (err == ESP_OK) { + err = httpd_register_uri_handler(server, &reboot); + } return err; } diff --git a/v2/main/ota.h b/v2/main/ota.h index a55d6bc..69eb9ce 100644 --- a/v2/main/ota.h +++ b/v2/main/ota.h @@ -4,6 +4,8 @@ #include "esp_http_server.h" // Register POST /ota (raw firmware .bin as the body) and GET /ota (running image info). +// The web UI is part of the image, so one upload updates both. +// POST /reboot restarts the board (replies first, reboots after 0.5 s). // A good upload is written to the idle app slot, becomes the boot image and the board reboots. esp_err_t ota_register(httpd_handle_t server); diff --git a/v2/main/store.c b/v2/main/store.c index 3c5dc21..a69c7ec 100644 --- a/v2/main/store.c +++ b/v2/main/store.c @@ -36,6 +36,7 @@ static esp_err_t mount(const char *label, const char *base) .base_path = base, .partition_label = label, .format_if_mount_failed = true, + .grow_on_mount = true, // the db partition spans the rest of the flash; an older, smaller filesystem is extended in place }; return esp_vfs_littlefs_register(&conf); } @@ -71,7 +72,6 @@ esp_err_t store_init(void) { s_lock = xSemaphoreCreateRecursiveMutex(); ESP_RETURN_ON_FALSE(s_lock, ESP_ERR_NO_MEM, TAG, "mutex"); - ESP_RETURN_ON_ERROR(mount("www", "/www"), TAG, "mount www"); ESP_RETURN_ON_ERROR(mount("db", "/db"), TAG, "mount db"); for (size_t i = 0; i < N_COLL; i++) { s_coll[i] = load_file(NAMES[i]); diff --git a/v2/main/store.h b/v2/main/store.h index 968768d..d454187 100644 --- a/v2/main/store.h +++ b/v2/main/store.h @@ -8,7 +8,7 @@ // id -> record, mirroring the Pi's db/*.json. Collections stay in memory and // are written back (via a temp file and rename) whenever they change. -// Mount the www and db partitions and load every collection +// Mount the db partition and load every collection esp_err_t store_init(void); // Borrowed pointer to the collection object (id -> record); never NULL for a known name diff --git a/v2/main/web.c b/v2/main/web.c index 64a6968..37c297d 100644 --- a/v2/main/web.c +++ b/v2/main/web.c @@ -1,14 +1,12 @@ #include "web.h" -#include -#include +#include +#include #include #include "esp_log.h" static const char *TAG = "web"; -#define CHUNK 2048 - static const struct { const char *ext; const char *type; @@ -34,37 +32,57 @@ static const char *mime_for(const char *path) return "application/octet-stream"; } -// path is the URL-relative name, e.g. "static/zones.js"; the file on flash is "/www/.gz" +// The web UI is one blob linked into the app image (www_dist/www.pack, see tools/build_web.sh): +// "WWW1", then per file u16 name length, u32 data length, the name, the gzipped data; a zero name +// length ends it. +extern const uint8_t www_pack_start[] asm("_binary_www_pack_start"); +extern const uint8_t www_pack_end[] asm("_binary_www_pack_end"); + +static bool find_file(const char *path, const uint8_t **data, uint32_t *len) +{ + const uint8_t *p = www_pack_start, *end = www_pack_end; + if (end - p < 6 || memcmp(p, "WWW1", 4) != 0) { + return false; + } + p += 4; + size_t want = strlen(path); + while (end - p >= 2) { + uint16_t nlen; + memcpy(&nlen, p, 2); + if (nlen == 0 || end - p < 6 + nlen) { + return false; + } + uint32_t dlen; + memcpy(&dlen, p + 2, 4); + const uint8_t *name = p + 6, *body = name + nlen; + if (end - body < (ptrdiff_t)dlen) { + return false; + } + if (nlen == want && memcmp(name, path, want) == 0) { + *data = body; + *len = dlen; + return true; + } + p = body + dlen; + } + return false; +} + +// path is the URL-relative name, e.g. "static/zones.js" static esp_err_t send_gz(httpd_req_t *req, const char *path, bool immutable) { - char fs[128]; - if (strstr(path, "..") || snprintf(fs, sizeof(fs), "/www/%s.gz", path) >= (int)sizeof(fs)) { + const uint8_t *data; + uint32_t len; + if (strstr(path, "..")) { return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "bad path"); } - FILE *f = fopen(fs, "rb"); - if (!f) { + if (!find_file(path, &data, &len)) { return httpd_resp_send_404(req); } httpd_resp_set_type(req, mime_for(path)); httpd_resp_set_hdr(req, "Content-Encoding", "gzip"); httpd_resp_set_hdr(req, "Cache-Control", immutable ? "public, max-age=86400" : "no-cache"); - - char *buf = malloc(CHUNK); - if (!buf) { - fclose(f); - return httpd_resp_send_500(req); - } - esp_err_t ret = ESP_OK; - size_t n; - while (ret == ESP_OK && (n = fread(buf, 1, CHUNK, f)) > 0) { - ret = httpd_resp_send_chunk(req, buf, n); - } - if (ret == ESP_OK) { - ret = httpd_resp_send_chunk(req, NULL, 0); - } - free(buf); - fclose(f); - return ret; + return httpd_resp_send(req, (const char *)data, len); } esp_err_t web_send_page(httpd_req_t *req, const char *name) diff --git a/v2/main/web.h b/v2/main/web.h index 533a67d..990a528 100644 --- a/v2/main/web.h +++ b/v2/main/web.h @@ -3,8 +3,8 @@ #include "esp_err.h" #include "esp_http_server.h" -// Register /, /settings/page, /static/* and /favicon.ico. Files come from the -// www partition, stored as .gz and sent with Content-Encoding: gzip. +// Register /, /audio, /static/* and /favicon.ico. Files come from the web UI blob embedded in the +// firmware (gzipped, sent with Content-Encoding: gzip). esp_err_t web_register(httpd_handle_t server); // Send one of the top-level pages (e.g. "settings.html") diff --git a/v2/partitions.csv b/v2/partitions.csv index b6b32d1..c80d6e6 100644 --- a/v2/partitions.csv +++ b/v2/partitions.csv @@ -4,5 +4,4 @@ otadata, data, ota, 0xf000, 0x2000 phy_init, data, phy, 0x11000, 0x1000 ota_0, app, ota_0, 0x20000, 0x200000 ota_1, app, ota_1, 0x220000,0x200000 -www, data, littlefs,0x420000,0x100000 -db, data, littlefs,0x520000,0x100000 +db, data, littlefs,0x520000,0xAE0000 diff --git a/src/util/binary_envelope.py b/v2/test/binary_envelope.py similarity index 100% rename from src/util/binary_envelope.py rename to v2/test/binary_envelope.py diff --git a/v2/test/env_check.py b/v2/test/env_check.py index 57afb3e..8fe8568 100644 --- a/v2/test/env_check.py +++ b/v2/test/env_check.py @@ -1,6 +1,4 @@ -import sys -sys.path.insert(0, "../../src") -from util.binary_envelope import pack_binary_envelope_v2 +from binary_envelope import pack_binary_envelope_v2 p = {"p":"chase","c":["#ff0000","#0f8"],"d":120,"b":200,"a":False,"n1":5,"n2":-3,"n3":0,"n4":7,"n5":0,"n6":300} p2 = {"pattern":"on","colors":["#102030"],"delay":0,"brightness":0,"auto":True} a = pack_binary_envelope_v2(presets={"7":p,"8":p2}, brightness_0_255=128).hex() diff --git a/v2/tools/build_web.sh b/v2/tools/build_web.sh index 168459b..22dfd0b 100755 --- a/v2/tools/build_web.sh +++ b/v2/tools/build_web.sh @@ -1,19 +1,16 @@ #!/usr/bin/env bash -# Minify and gzip the web UI into v2/www_dist for the `www` LittleFS partition. -# Usage: tools/build_web.sh (needs node/npx; WWW_MAX = partition size in bytes) +# Minify and gzip the web UI into v2/www_dist and pack it into www_dist/www.pack, which the +# firmware embeds (main/CMakeLists.txt). Usage: tools/build_web.sh (needs node/npx; WWW_MAX = size limit in bytes) set -euo pipefail cd "$(dirname "$0")/.." -SRC=../src +SRC=web OUT=www_dist -MAX=${WWW_MAX:-1048576} +MAX=${WWW_MAX:-524288} rm -rf "$OUT"; mkdir -p "$OUT/static" -# Legacy files the v2 UI does not load -SKIP=" app.js main.js rgb-slider.js styles.css " - for f in "$SRC"/static/*; do [[ -f $f ]] || continue - b=$(basename "$f"); [[ $SKIP == *" $b "* ]] && continue + b=$(basename "$f") case $b in *.min.js) cp "$f" "$OUT/static/$b" ;; *.js|*.css) npx --yes esbuild@0.25.0 "$f" --minify --target=es2019 --legal-comments=none \ @@ -21,20 +18,10 @@ for f in "$SRC"/static/*; do *) cp "$f" "$OUT/static/$b" ;; esac done -# The Pi does not serve /audio, so the Audio menu entries are added for this build only -# (desktop button row and the mobile dropdown, both just before Help). -tmp=$(mktemp -d) -sed -e "s||\n&|" \ - -e "s||\n&|" \ - "$SRC/templates/index.html" > "$tmp/index.html" -cp "$SRC/templates/settings.html" "$tmp/settings.html" -grep -q 'id="audio-btn"' "$tmp/index.html" && [ "$(grep -c 'audio-btn' "$tmp/index.html")" -eq 2 ] \ - || { echo "ERROR: could not add the Audio menu entries to index.html" >&2; exit 1; } for p in index settings; do npx --yes html-minifier-terser@7.2.0 --collapse-whitespace --remove-comments \ - --minify-css true --minify-js true -o "$OUT/$p.html" "$tmp/$p.html" + --minify-css true --minify-js true -o "$OUT/$p.html" "$SRC/templates/$p.html" done -rm -rf "$tmp" # Live audio and beat page (served at /audio) npx --yes html-minifier-terser@7.2.0 --collapse-whitespace --remove-comments \ @@ -46,4 +33,23 @@ find "$OUT" -name '*.gz' -exec gzip -t {} \; total=$(find "$OUT" -name '*.gz' -printf '%s\n' | paste -sd+ | bc) echo "www_dist: $(find "$OUT" -name '*.gz' | wc -l) files, $total bytes (limit $MAX)" -(( total <= MAX )) || { echo "ERROR: web UI exceeds www partition" >&2; exit 1; } +(( total <= MAX )) || { echo "ERROR: web UI exceeds the size limit" >&2; exit 1; } + +# One blob for the firmware: "WWW1", then per file u16 name length, u32 data length, name (no .gz), +# data; a zero name length ends it. Little-endian, read by main/web.c. +python3 - "$OUT" <<'PY' +import os, struct, sys +root = sys.argv[1] +out = bytearray(b"WWW1") +for dirpath, _, names in sorted(os.walk(root)): + for n in sorted(names): + if not n.endswith(".gz"): + continue + full = os.path.join(dirpath, n) + name = os.path.relpath(full, root)[:-3].encode() + data = open(full, "rb").read() + out += struct.pack(" [build/led_controller_v2.bin] + ota.py [firmware.bin] + +Default is build/led_controller_v2.bin next to this script. The board reboots into the new image. """ import http.client import json import os import sys +import time host = sys.argv[1] if len(sys.argv) > 1 else sys.exit(__doc__) -path = sys.argv[2] if len(sys.argv) > 2 else os.path.join(os.path.dirname(__file__), "..", "build", "led_controller_v2.bin") -size = os.path.getsize(path) +build = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "build") +fw = sys.argv[2] if len(sys.argv) > 2 else os.path.join(build, "led_controller_v2.bin") -conn = http.client.HTTPConnection(host, 80, timeout=60) -conn.request("GET", "/ota") -print("running:", conn.getresponse().read().decode()) -print(f"uploading {path} ({size} bytes)") -with open(path, "rb") as f: - conn.request("POST", "/ota", body=f, headers={"Content-Length": str(size), - "Content-Type": "application/octet-stream"}) - r = conn.getresponse() - body = r.read().decode() -print(r.status, body) -sys.exit(0 if r.status == 200 else 1) +def info(): + try: + c = http.client.HTTPConnection(host, 80, timeout=5) + c.request("GET", "/ota") + r = c.getresponse() + return json.loads(r.read().decode()) if r.status == 200 else None + except (OSError, ValueError): + return None + + +def upload(path, url): + size = os.path.getsize(path) + print(f"uploading {path} ({size} bytes) to {url}") + c = http.client.HTTPConnection(host, 80, timeout=120) + with open(path, "rb") as f: + c.request("POST", url, body=f, headers={"Content-Length": str(size), + "Content-Type": "application/octet-stream"}) + r = c.getresponse() + body = r.read().decode() + print(r.status, body) + if r.status != 200: + sys.exit(1) + time.sleep(3) + for _ in range(30): + i = info() + if i: + print("back up on", i["partition"]) + return + time.sleep(1) + sys.exit("controller did not come back within 30 s") + + +before = info() +print("running:", before) +if before is None: + sys.exit("no OTA endpoint (is this the v2 controller?)") +upload(fw, "/ota") diff --git a/v2/web/static/audio.js b/v2/web/static/audio.js new file mode 100644 index 0000000..8922880 --- /dev/null +++ b/v2/web/static/audio.js @@ -0,0 +1,188 @@ +// Audio modal: live beat indicators and level from the controller's microphone detector, plus a +// simulated beat (a fixed BPM sent to the drivers, with the microphone ignored while it runs). +document.addEventListener('DOMContentLoaded', () => { + const modal = document.getElementById('audio-modal'); + const openBtn = document.getElementById('audio-btn'); + if (!modal || !openBtn) return; + + const el = (id) => document.getElementById(id); + const beatBtn = el('audio-modal-beat-sync'); + const bpmValue = el('audio-bpm-value'); + const beatReadout = el('audio-modal-beat-readout'); + const barPhase = el('audio-bar-phase-value'); + const levelBar = el('audio-input-level-bar'); + const levelReadout = el('audio-level-readout'); + const simInput = el('audio-simulated-bpm'); + const simStatus = el('audio-sim-status'); + const simStart = el('audio-sim-start-btn'); + const simStop = el('audio-sim-stop-btn'); + + const SIM_MIN = 60; + const SIM_MAX = 200; + let events = null; + let pollTimer = null; + let simRunning = false; + let simBpm = 120; + let simTimer = null; + let simTick = 0; + + const clampSim = (n) => Math.max(SIM_MIN, Math.min(SIM_MAX, Math.round(Number(n) || 120))); + + function flash(simulated) { + const cls = simulated ? 'flash-simulated' : 'flash'; + beatBtn.classList.add(cls); + setTimeout(() => beatBtn.classList.remove(cls), 90); + } + + function showBar(bar, meter, sure) { + if (!bar) { + barPhase.textContent = ''; + return; + } + barPhase.textContent = `${bar}/${meter}`; + barPhase.classList.toggle('is-downbeat', bar === 1); + beatBtn.classList.toggle('guess', !sure); + } + + function showBpm(bpm, simulated) { + bpmValue.textContent = bpm ? bpm.toFixed(simulated ? 0 : 1) : '--'; + beatBtn.classList.toggle('audio-simulated', simulated); + } + + // --- detector events ------------------------------------------------------------------- + function openEvents() { + if (events || !window.EventSource) return; + events = new EventSource('/beats'); + events.addEventListener('beat', (e) => { + if (simRunning) return; + const s = JSON.parse(e.data); + flash(false); + showBpm(s.bpm, false); + beatReadout.textContent = `#${s.n}`; + showBar(s.bar, s.meter, s.sure); + }); + events.addEventListener('tempo', (e) => { + if (simRunning) return; + const s = JSON.parse(e.data); + showBpm(s.locked ? s.bpm : 0, false); + }); + } + + function closeEvents() { + if (events) { + events.close(); + events = null; + } + } + + // --- level and simulation state -------------------------------------------------------- + async function poll() { + try { + const s = await (await fetch('/status', { cache: 'no-store' })).json(); + const pct = Math.max(0, Math.min(100, ((s.mic_rms_dbfs + 90) / 90) * 100)); + levelBar.style.width = `${pct}%`; + levelBar.parentElement.setAttribute('aria-valuenow', String(Math.round(pct))); + levelReadout.textContent = `${s.mic_rms_dbfs.toFixed(1)} dBFS · ${s.mic_spl_db.toFixed(0)} dB`; + const t = await (await fetch('/test/beats', { cache: 'no-store' })).json(); + setSimRunning(!!t.running); + } catch (e) { + /* controller briefly unreachable */ + } + if (modal.classList.contains('active')) pollTimer = setTimeout(poll, 500); + } + + function setSimRunning(on) { + if (on === simRunning && (on === (simTimer !== null))) return; + simRunning = on; + simStart.disabled = on; + simStop.disabled = !on; + simStatus.textContent = on ? `Sending ${simBpm} BPM to the drivers; the microphone is ignored.` : ''; + clearInterval(simTimer); + simTimer = null; + if (on) { + // The controller does not echo generated beats back, so the indicator runs on its own clock + simTick = 0; + showBpm(simBpm, true); + simTimer = setInterval(() => { + simTick++; + flash(true); + beatReadout.textContent = `#${simTick}`; + showBar(((simTick - 1) % 4) + 1, 4, true); + }, 60000 / simBpm); + } else { + showBpm(0, false); + beatReadout.textContent = ''; + showBar(0); + } + } + + async function startSim() { + simBpm = clampSim(simInput.value); + simInput.value = simBpm; + simStatus.textContent = ''; + const res = await fetch('/test/beats', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ bpm: simBpm, count: 0 }), + }); + if (!res.ok) { + simStatus.textContent = 'The controller refused that BPM.'; + return; + } + setSimRunning(false); + setSimRunning(true); + fetch('/settings/settings', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ audio_simulated_bpm: simBpm }), + }).catch(() => {}); + } + + async function stopSim() { + await fetch('/test/beats/stop', { method: 'POST' }); + setSimRunning(false); + } + + function tap() { + fetch('/tap', { method: 'POST' }).catch(() => {}); + } + + async function loadSimBpm() { + try { + const s = await (await fetch('/settings', { cache: 'no-store' })).json(); + if (s.audio_simulated_bpm != null) simInput.value = clampSim(s.audio_simulated_bpm); + } catch (e) { + /* keep the default */ + } + } + + // --- open and close -------------------------------------------------------------------- + function open() { + modal.classList.add('active'); + simStop.disabled = true; + loadSimBpm(); + openEvents(); + clearTimeout(pollTimer); + poll(); + } + + function close() { + modal.classList.remove('active'); + closeEvents(); + clearTimeout(pollTimer); + // The simulation keeps running on the controller; only the local indicator stops + clearInterval(simTimer); + simTimer = null; + } + + openBtn.addEventListener('click', open); + el('audio-close-btn').addEventListener('click', close); + simStart.addEventListener('click', startSim); + simStop.addEventListener('click', stopSim); + el('audio-tap-btn').addEventListener('click', tap); + beatBtn.addEventListener('click', tap); + document.addEventListener('keydown', (e) => { + if (!modal.classList.contains('active') || e.repeat) return; + if ((e.key === 't' || e.key === 'T') && !/INPUT|TEXTAREA|SELECT/.test(e.target.tagName)) tap(); + }); +}); diff --git a/src/static/color_palette.js b/v2/web/static/color_palette.js similarity index 100% rename from src/static/color_palette.js rename to v2/web/static/color_palette.js diff --git a/src/static/devices.js b/v2/web/static/devices.js similarity index 93% rename from src/static/devices.js rename to v2/web/static/devices.js index 3bb5b78..a565306 100644 --- a/src/static/devices.js +++ b/v2/web/static/devices.js @@ -325,10 +325,33 @@ function openEditDeviceModal(devId, dev) { applyTransportVisibility(tr); setAddressToBoxes(addressBoxes, tr === 'espnow' ? ((dev && dev.address) || '') : ''); if (wifiInput) wifiInput.value = tr === 'wifi' ? ((dev && dev.address) || '') : ''; + DEVICE_SETTING_FIELDS.forEach((f) => { + const el = document.getElementById(f.id); + if (el) el.value = dev && dev[f.key] != null ? String(dev[f.key]) : ''; + }); modal.classList.add('active'); } -async function updateDevice(devId, name, type, transport, address) { +// Driver settings edited in the device dialog: key on the device record, input id, parser (null = leave unchanged) +const DEVICE_SETTING_FIELDS = [ + { key: 'num_leds', id: 'edit-device-num-leds', parse: (v) => Math.max(1, Math.min(2048, Math.round(Number(v)) || 1)) }, + { key: 'color_order', id: 'edit-device-color-order', parse: (v) => v }, + { key: 'startup_mode', id: 'edit-device-startup-mode', parse: (v) => v }, + { key: 'reversed', id: 'edit-device-reversed', parse: (v) => v === 'true' }, + { key: 'max_brightness', id: 'edit-device-max-brightness', parse: (v) => Math.max(0, Math.min(255, Math.round(Number(v)) || 0)) }, +]; + +function readDeviceSettings() { + const out = {}; + DEVICE_SETTING_FIELDS.forEach((f) => { + const el = document.getElementById(f.id); + const raw = el ? el.value.trim() : ''; + if (raw !== '') out[f.key] = f.parse(raw); + }); + return out; +} + +async function updateDevice(devId, name, type, transport, address, settings) { try { const res = await fetch(`/devices/${encodeURIComponent(devId)}`, { method: 'PUT', @@ -338,6 +361,7 @@ async function updateDevice(devId, name, type, transport, address) { type: type || 'led', transport: transport || 'espnow', address, + ...(settings || {}), }), }); const data = await res.json().catch(() => ({})); @@ -435,7 +459,8 @@ document.addEventListener('DOMContentLoaded', () => { nameInput ? nameInput.value.trim() : '', (typeSel && typeSel.value) || 'led', transport, - address + address, + readDeviceSettings() ); if (ok) editDeviceModal.classList.remove('active'); }); diff --git a/src/static/help.js b/v2/web/static/help.js similarity index 65% rename from src/static/help.js rename to v2/web/static/help.js index 18cf36b..552c825 100644 --- a/src/static/help.js +++ b/v2/web/static/help.js @@ -66,11 +66,76 @@ document.addEventListener('DOMContentLoaded', () => { chInput.value = ch !== undefined && ch !== null && ch !== '' ? String(ch) : '6'; } + const hostInput = document.getElementById('hostname-input'); + if (hostInput && staticIpsList && data && typeof data === 'object') { + hostInput.value = data.hostname || ''; + staticIpsList.innerHTML = ''; + (Array.isArray(data.static_ips) ? data.static_ips : []).forEach(addStaticIpRow); + } } catch (error) { console.error('Error loading device settings:', error); } } + const staticIpsList = document.getElementById('static-ips-list'); + const STATIC_IP_FIELDS = [ + ['ip', 'IP address', '192.168.1.50'], + ['netmask', 'Netmask', '255.255.255.0'], + ['gw', 'Gateway', '192.168.1.1'], + ['dns', 'DNS (optional)', 'gateway'], + ]; + + function addStaticIpRow(entry = {}) { + if (!staticIpsList) return; + const row = document.createElement('div'); + row.className = 'static-ip-row'; + row.style.cssText = 'display:flex;flex-wrap:wrap;gap:0.5rem;margin:0.5rem 0;align-items:center;'; + STATIC_IP_FIELDS.forEach(([key, label, placeholder]) => { + const input = document.createElement('input'); + input.type = 'text'; + input.dataset.key = key; + input.placeholder = `${label} (${placeholder})`; + input.title = label; + input.value = entry[key] || ''; + input.style.cssText = 'flex:1 1 9rem;min-width:0;'; + row.appendChild(input); + }); + const remove = document.createElement('button'); + remove.type = 'button'; + remove.className = 'btn btn-secondary'; + remove.textContent = 'Remove'; + remove.addEventListener('click', () => row.remove()); + row.appendChild(remove); + staticIpsList.appendChild(row); + } + + const IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/; + const validIp = (v) => { + const m = IPV4.exec(v); + return !!m && m.slice(1).every((o) => Number(o) <= 255); + }; + + function readStaticIps() { + const out = []; + for (const row of staticIpsList.querySelectorAll('.static-ip-row')) { + const entry = {}; + row.querySelectorAll('input').forEach((i) => { + const v = i.value.trim(); + if (v) entry[i.dataset.key] = v; + }); + if (!Object.keys(entry).length) continue; + if (!entry.ip) throw new Error('Every static IP needs an IP address'); + for (const [k, v] of Object.entries(entry)) { + if (!validIp(v)) throw new Error(`"${v}" is not a valid ${k} address`); + } + out.push(entry); + } + return out; + } + + const addIpButton = document.getElementById('static-ip-add-btn'); + if (addIpButton) addIpButton.addEventListener('click', () => addStaticIpRow()); + async function loadAPStatus() { try { const response = await fetch('/settings/wifi/ap'); @@ -153,6 +218,39 @@ document.addEventListener('DOMContentLoaded', () => { } }); } + const networkForm = document.getElementById('network-form'); + if (networkForm) { + networkForm.addEventListener('submit', async (e) => { + e.preventDefault(); + const hostname = document.getElementById('hostname-input').value.trim(); + if (hostname && !/^[A-Za-z0-9-]+$/.test(hostname)) { + showSettingsMessage('Hostname may only contain letters, digits and hyphens', 'error'); + return; + } + let staticIps; + try { + staticIps = readStaticIps(); + } catch (error) { + showSettingsMessage(error.message, 'error'); + return; + } + try { + const response = await fetch('/settings/settings', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ hostname, static_ips: staticIps }), + }); + const result = await response.json(); + if (response.ok) { + showSettingsMessage('Network settings saved. Restart the controller to apply them.', 'success'); + } else { + showSettingsMessage(`Error: ${result.error || 'Failed to save network settings'}`, 'error'); + } + } catch (error) { + showSettingsMessage(`Error: ${error.message}`, 'error'); + } + }); + } const apForm = document.getElementById('ap-form'); if (apForm) { apForm.addEventListener('submit', async (e) => { diff --git a/src/static/htmx.min.js b/v2/web/static/htmx.min.js similarity index 100% rename from src/static/htmx.min.js rename to v2/web/static/htmx.min.js diff --git a/src/static/led_tool.js b/v2/web/static/led_tool.js similarity index 100% rename from src/static/led_tool.js rename to v2/web/static/led_tool.js diff --git a/src/static/list_search.js b/v2/web/static/list_search.js similarity index 100% rename from src/static/list_search.js rename to v2/web/static/list_search.js diff --git a/src/static/outputs.js b/v2/web/static/outputs.js similarity index 100% rename from src/static/outputs.js rename to v2/web/static/outputs.js diff --git a/src/static/patterns.js b/v2/web/static/patterns.js similarity index 100% rename from src/static/patterns.js rename to v2/web/static/patterns.js diff --git a/src/static/presets.js b/v2/web/static/presets.js similarity index 96% rename from src/static/presets.js rename to v2/web/static/presets.js index 6076fd2..d4d5fb1 100644 --- a/src/static/presets.js +++ b/v2/web/static/presets.js @@ -1,7 +1,4 @@ -// Shared WebSocket for ESPNow messages (presets + selects) -let espnowSocket = null; -let espnowSocketReady = false; -let espnowPendingMessages = []; +// Sending presets and selects to drivers let currentProfileIdCache = null; const getCurrentProfileId = async () => { @@ -69,80 +66,13 @@ const resolveColorsWithPaletteRefs = (colors, paletteRefs, paletteColors) => { }); }; -const getEspnowSocket = () => { - if (espnowSocket && (espnowSocket.readyState === WebSocket.OPEN || espnowSocket.readyState === WebSocket.CONNECTING)) { - return espnowSocket; - } +// The v2 controller has no /ws endpoint: ESP-NOW goes out through POST /presets/push, and the Wi-Fi +// device presence dots stay as the devices list shows them. Kept so callers need no change. +const getEspnowSocket = () => null; - const wsScheme = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; - const wsUrl = `${wsScheme}//${window.location.host}/ws`; - espnowSocket = new WebSocket(wsUrl); - espnowSocketReady = false; - - espnowSocket.onopen = () => { - espnowSocketReady = true; - window.dispatchEvent(new CustomEvent('deviceTcpWsOpen')); - // Flush any queued messages - espnowPendingMessages.forEach((msg) => { - try { - espnowSocket.send(msg); - } catch (err) { - console.error('Failed to send queued ESPNow message:', err); - } - }); - espnowPendingMessages = []; - }; - - espnowSocket.onmessage = (event) => { - try { - const data = JSON.parse(event.data); - if (data && data.type === 'device_tcp' && typeof data.connected === 'boolean' && data.ip) { - window.dispatchEvent( - new CustomEvent('deviceTcpStatus', { detail: { ip: data.ip, connected: data.connected } }), - ); - return; - } - if (data && data.type === 'device_tcp_snapshot' && Array.isArray(data.connected_ips)) { - window.dispatchEvent( - new CustomEvent('deviceTcpSnapshot', { detail: { connectedIps: data.connected_ips } }), - ); - return; - } - if (data && data.error) { - console.error('ESP-NOW:', data.error); - alert('ESP-NOW send failed. ' + (data.error === 'ESP-NOW send failed' ? 'Check device WiFi/interface.' : data.error)); - } - } catch (_) { - // Ignore non-JSON or non-error messages - } - }; - - espnowSocket.onclose = () => { - espnowSocketReady = false; - espnowSocket = null; - }; - - espnowSocket.onerror = (err) => { - console.error('ESPNow WebSocket error:', err); - }; - - return espnowSocket; -}; - -const sendEspnowMessage = (obj) => { - const json = JSON.stringify(obj); - const ws = getEspnowSocket(); - if (espnowSocketReady && ws.readyState === WebSocket.OPEN) { - try { - ws.send(json); - } catch (err) { - console.error('Failed to send ESPNow message:', err); - } - } else { - // Queue until connection is open - espnowPendingMessages.push(json); - } -}; +const sendEspnowMessage = (obj) => postDriverSequence([obj], [], 0).catch((err) => { + console.error('Failed to send ESPNow message:', err); +}); function tabDeviceNamesFromSection(section) { if (typeof window.parseTabDeviceNames === 'function') { diff --git a/src/static/profiles.js b/v2/web/static/profiles.js similarity index 100% rename from src/static/profiles.js rename to v2/web/static/profiles.js diff --git a/src/static/sequences.js b/v2/web/static/sequences.js similarity index 100% rename from src/static/sequences.js rename to v2/web/static/sequences.js diff --git a/src/static/style.css b/v2/web/static/style.css similarity index 92% rename from src/static/style.css rename to v2/web/static/style.css index ee867e7..bc1d90e 100644 --- a/src/static/style.css +++ b/v2/web/static/style.css @@ -1471,3 +1471,138 @@ body.preset-ui-run .edit-mode-only { .profiles-row.list-search-hidden { display: none !important; } + +/* Audio modal */ +.audio-modal-content { + max-width: 640px; +} + +.audio-beat-sync-btn { + display: inline-flex; + align-items: center; + gap: 0.4rem; + width: 100%; + min-height: 2.25rem; + padding: 0.3rem 0.55rem; + border: 1px solid #4a4a4a; + border-radius: 6px; + background-color: #1a1a1a; + cursor: pointer; + font-family: inherit; + text-align: left; +} + +.audio-beat-sync-btn:hover { + border-color: #6a6a6a; + background-color: #2a2a2a; +} + +.audio-top-indicator-label { + font-size: 0.72rem; + color: #bdbdbd; + letter-spacing: 0.05em; +} + +.audio-top-indicator-value { + font-size: 1rem; + font-weight: 700; + color: #ffd54f; + min-width: 2.4rem; + text-align: right; +} + +.audio-top-beat-readout, +.audio-top-bar-phase { + font-size: 0.75rem; + color: #b0bec5; + line-height: 1.25; + white-space: nowrap; +} + +.audio-top-beat-readout { + flex: 1; + min-width: 2rem; + text-align: right; + overflow: hidden; + text-overflow: ellipsis; +} + +.audio-top-beat-readout:empty, +.audio-top-bar-phase:empty { + display: none; +} + +.audio-top-beat-readout:not(:empty)::before, +.audio-top-bar-phase:not(:empty)::before { + content: "·"; + margin-right: 0.35rem; + color: #757575; +} + +.audio-top-bar-phase.is-downbeat { + color: #ffab91; +} + +.audio-beat-sync-btn.guess .audio-top-bar-phase { + opacity: 0.6; +} + +.audio-beat-sync-btn.flash { + background-color: #ff5252; + border-color: #ff8a80; +} + +.audio-beat-sync-btn.flash-simulated { + background-color: #5a4a00; + border-color: #e6c200; +} + +.audio-beat-sync-btn.audio-simulated .audio-top-indicator-value { + color: #e6c200; +} + +.audio-beat-sync-btn.flash span, +.audio-beat-sync-btn.flash-simulated span { + color: #fff; +} + +.audio-volume-block { + margin-top: 0.5rem; +} + +.audio-volume-header { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 0.75rem; + margin-bottom: 0.5rem; +} + +.audio-volume-header label { + margin: 0; +} + +.audio-volume-readout { + font-size: 0.9rem; + color: #e0e0e0; + white-space: nowrap; +} + +.audio-input-level-meter { + width: 100%; + height: 0.35rem; + border-radius: 2px; + background: #2a2a2a; + overflow: hidden; +} + +.audio-input-level-bar { + height: 100%; + width: 0%; + background: #ff9800; + transition: width 60ms linear; +} + +a.btn { + text-decoration: none; +} diff --git a/src/static/zone_palette.js b/v2/web/static/zone_palette.js similarity index 100% rename from src/static/zone_palette.js rename to v2/web/static/zone_palette.js diff --git a/src/static/zones.js b/v2/web/static/zones.js similarity index 100% rename from src/static/zones.js rename to v2/web/static/zones.js diff --git a/src/templates/index.html b/v2/web/templates/index.html similarity index 86% rename from src/templates/index.html rename to v2/web/templates/index.html index 3009914..e6f77aa 100644 --- a/src/templates/index.html +++ b/v2/web/templates/index.html @@ -29,6 +29,8 @@ + + @@ -50,6 +52,8 @@ + + @@ -160,6 +164,30 @@ +

Driver settings (ESP-NOW drivers; sent when you save, and the driver keeps them). Leave blank to keep the driver's value.

+ + + + + + + + + + + +
+

Network

+
+
+ + + The controller answers at hostname.local. +
+
+ + Tried in order each time the Ethernet link comes up; the first whose gateway answers is used. If none does, or the list is empty, DHCP is used. +
+ +
+
+ +
+ Network changes apply after the controller restarts. +
+
+

WiFi Access Point

@@ -658,9 +708,47 @@
+ + + + diff --git a/src/templates/settings.html b/v2/web/templates/settings.html similarity index 100% rename from src/templates/settings.html rename to v2/web/templates/settings.html