129 Commits
Author SHA1 Message Date
jimmy ff92451a76 feat(profiles): seed twinkle preset defaults
Made-with: Cursor
2026-04-21 20:43:25 +12:00
jimmy 60485bc06a feat(ui): add clear device presets action
Made-with: Cursor
2026-04-21 00:44:38 +12:00
jimmy f6f299c3e5 feat(presets): add radiate pattern defaults
Made-with: Cursor
2026-04-20 23:38:02 +12:00
jimmy 66485f5c59 chore(led-driver): bump submodule for patterns and tests
Made-with: Cursor
2026-04-19 23:28:22 +12:00
jimmy 5f9ff9bcc9 style(ui): presets patterns and layout tweaks
Made-with: Cursor
2026-04-19 23:28:08 +12:00
jimmy 35730b36f0 feat(api): improve pattern deploy and device tcp handling
Made-with: Cursor
2026-04-19 23:28:01 +12:00
jimmy d516833cc3 feat(profiles): seed colour cycle flicker and flame presets
Made-with: Cursor
2026-04-19 23:27:57 +12:00
jimmy 220be64dec feat(db): add flicker flame presets and pattern metadata
Made-with: Cursor
2026-04-19 23:27:49 +12:00
jimmy b433477c64 chore(db): trim device registry
Made-with: Cursor
2026-04-19 23:27:37 +12:00
jimmy 43b7047c57 chore(submodule): bump led-tool for cli upload flags
Made-with: Cursor
2026-04-15 00:46:40 +12:00
jimmy 167417d1ec feat(ui): add web led-tool usb controls
Made-with: Cursor
2026-04-15 00:46:31 +12:00
jimmy fb8141b320 fix(server): close http listener cleanly on shutdown 2026-04-15 00:00:23 +12:00
jimmy 96712dda88 feat(controller): migrate wifi drivers from tcp to websocket clients 2026-04-14 23:13:26 +12:00
jimmy f5a7b42e7c fix(rules): revert unintended submodule changes 2026-04-14 21:54:02 +12:00
jimmy 1b1e9d727e chore(rules): enforce strict user-scoped changes 2026-04-14 21:50:55 +12:00
jimmy 668d29b786 chore(test): move pytest defaults to pyproject.toml
Made-with: Cursor
2026-04-12 02:39:39 +12:00
jimmy e5f42e099e chore: remove esp32 firmware tree and dev mpremote helper
Made-with: Cursor
2026-04-12 02:39:37 +12:00
jimmy a9edda38ef test(browser): fixture, env host and pacing, safer colour inputs
Made-with: Cursor
2026-04-12 02:34:46 +12:00
jimmy edec5ff460 chore(git): ignore pytest cache and ropeproject
Made-with: Cursor
2026-04-12 02:34:44 +12:00
pi 264eb7296f test: fix zone_ctl fixture, pattern assertions, and browser cleanup
Made-with: Cursor
2026-04-12 00:27:43 +12:00
pi fbd4295302 feat(ui): patterns list and create form layout
Made-with: Cursor
2026-04-12 00:13:58 +12:00
pi 7bdb324ebc feat(patterns): driver_patterns helper, on/off ota guard, drop duplicate py tree
Made-with: Cursor
2026-04-12 00:13:56 +12:00
pi 28b19b5219 docs: zones, transports, pattern ota, and submodule readmes
Made-with: Cursor
2026-04-12 00:13:54 +12:00
pi 75ddd559c9 chore(db,led-tool): sync device/zone data and led-tool submodule
Made-with: Cursor
2026-04-11 15:20:26 +12:00
pi 5a1067263a chore: add pattern samples, http driver helpers, OTA/UDP test tools
- patterns/: sample dynamic pattern modules for OTA
- esp32/msg.json: example bridge message shape
- models/http_driver.py, wifi_peer.py: Wi-Fi driver HTTP poll helpers
- tests: pattern OTA send script and UDP discovery echo server
- Submodule led-driver: http_poll and test utilities

Made-with: Cursor
2026-04-11 15:19:15 +12:00
pi e67de6215a feat(patterns,api): pattern OTA, graceful shutdown, driver delivery updates
- Pattern controller/UI and presets patterns tab for OTA to Wi-Fi drivers
- Device controller extensions; driver_delivery chunk handling
- main: SIGINT/SIGTERM shutdown, TCP/UDP server close coordination
- Submodule led-driver: Wi-Fi default transport, lazy espnow import, dynamic patterns

Made-with: Cursor
2026-04-11 15:10:23 +12:00
pi 7179b6531e feat(controller): udp hello discovery and remove tcp registration
Made-with: Cursor
2026-04-06 21:28:13 +12:00
pi fd618d7714 feat(zones): rename tabs to zones across api, ui, and storage
Made-with: Cursor
2026-04-06 18:22:03 +12:00
pi d1ffb857c8 feat(ui): devices tcp status, tabs send, preset websocket hooks
Made-with: Cursor
2026-04-06 00:22:00 +12:00
pi f8eba0ee7e feat(api): tcp driver registry, identify, preset push delivery
- Track Wi-Fi TCP clients, liveness pings, disconnect broadcast, bind errors via gather\n- Device list/get include connected; POST identify with __identify preset\n- Presets push/send delivery helpers; bump led-driver hello type

Made-with: Cursor
2026-04-06 00:21:57 +12:00
pi e6b5bf2cf1 feat(devices): wifi tcp registry, device API/UI, tests; bump led-tool
Made-with: Cursor
2026-04-05 21:13:07 +12:00
pi fbae75b957 chore(cursor): add scoped-fixes rule for minimal changes
Made-with: Cursor
2026-04-05 21:13:03 +12:00
pi 93476655fc test: add tcp mock server with bind conflict hints
Made-with: Cursor
2026-04-05 16:41:23 +12:00
pi 09a87b79d2 docs(ui): update help assets and regenerate help pdf 2026-03-26 00:40:40 +13:00
pi ec39df00fc feat(settings/espnow): validate wifi_channel and wire into firmware 2026-03-26 00:40:21 +13:00
pi 43d494bcb9 fix(api): prevent circular reference in pattern create 2026-03-26 00:40:08 +13:00
pi fed312a397 fix(test/endpoints): add pytest coverage for all Microdot routes 2026-03-26 00:39:41 +13:00
jimmy 63235c7822 fix(ui): enforce save semantics for default and preset chunks 2026-03-22 02:53:34 +13:00
jimmy 5badf17719 refactor(ui): simplify modal interactions and refresh fixtures 2026-03-22 02:00:28 +13:00
jimmy 4597573ac5 fix(ui): update preset send/default behavior in edit mode 2026-03-22 01:47:32 +13:00
jimmy 1550122ced fix(ui): populate preset patterns when definitions are empty
Made-with: Cursor
2026-03-22 00:08:12 +13:00
jimmy b7c45fd72c docs(ui): switch user-facing spelling to colour
Made-with: Cursor
2026-03-22 00:00:12 +13:00
jimmy 9479d0d292 chore(cursor): add commit and spelling rules
Made-with: Cursor
2026-03-21 23:54:33 +13:00
jimmy 3698385af4 feat(ui): help sections, menu order, remove settings, send presets edit-only
Made-with: Cursor
2026-03-21 23:51:02 +13:00
jimmy ef968ebe39 docs: run/edit mode, profiles behavior, send presets
Made-with: Cursor
2026-03-21 23:51:00 +13:00
jimmy a5432db99a feat(ui): gate profile create/clone/delete to edit mode
Made-with: Cursor
2026-03-21 23:50:59 +13:00
jimmy 764d918d5b data: update local db fixtures and browser test expectations
Made-with: Cursor
2026-03-21 23:15:55 +13:00
jimmy edadb40cb6 docs: rewrite API reference for current HTTP and driver flows
Made-with: Cursor
2026-03-21 23:15:44 +13:00
jimmy 9323719a85 feat(ui): add run/edit workflow and improve preset color editing
Made-with: Cursor
2026-03-21 23:15:31 +13:00
jimmy 91de705647 feat(profiles): seed new profiles and refresh tabs on apply
Made-with: Cursor
2026-03-21 23:15:19 +13:00
jimmy 3ee7b74152 fix(api): stabilize palette and preset endpoints
Made-with: Cursor
2026-03-21 23:15:08 +13:00
jimmy 98bbdcbb3d chore: add dev watch command to Pipfile scripts
Made-with: Cursor
2026-03-21 23:15:00 +13:00
jimmy a2abd3e833 data: refresh db JSON fixtures
Made-with: Cursor
2026-03-21 20:17:33 +13:00
jimmy 550217c443 ui: data-bwignore on AP password fields for password managers
Made-with: Cursor
2026-03-21 20:17:33 +13:00
jimmy 2d2032e8b9 esp32: log startup and UART receive for debugging
Made-with: Cursor
2026-03-21 20:17:33 +13:00
jimmy 81bf4dded5 docs: update msg.json example payload
Made-with: Cursor
2026-03-21 20:17:33 +13:00
jimmy a75e27e3d2 feat: device model, API, static UI, and endpoint tests
Made-with: Cursor
2026-03-21 20:17:33 +13:00
jimmy 13538c39a6 tests: skip browser tests when no driver; try Firefox after Chrome
Made-with: Cursor
2026-03-21 20:17:33 +13:00
jimmy 7b724e9ce1 tests: point model tests at db/ and align palette assertions
Made-with: Cursor
2026-03-21 20:17:33 +13:00
jimmy aaca5435e9 chore: gitignore local settings.json (session secret)
Made-with: Cursor
2026-03-21 20:17:33 +13:00
jimmy b64dacc1c3 Stop ignoring esp32; drop esp32 rules from .gitignore
Made-with: Cursor
2026-03-21 20:08:24 +13:00
jimmy 8689bdb6ef Restore esp32 MicroPython sources (main, benchmark_peers)
Adjust .gitignore to ignore esp32/* except *.py so firmware .bin stays untracked.

Made-with: Cursor
2026-03-21 19:59:52 +13:00
jimmy c178e87966 Ignore esp32 folder 2026-03-21 19:53:19 +13:00
jimmy dfe7ae50d2 Add led-tool and led-driver submodules 2026-03-21 19:52:59 +13:00
jimmy 8e87559af6 Add led-tool and led-driver as submodules 2026-03-21 19:52:14 +13:00
jimmy aa3546e9ac Remove obsolete scripts and root config files
Drop clear-debug-log, install, run_web, send_empty_json, esp32 helpers,
and root msg.json/settings.json in favor of current layout.

Made-with: Cursor
2026-03-21 19:47:29 +13:00
jimmy b56af23cbf Add scripts: start, copy ESP32 main, install boot service
Made-with: Cursor
2026-03-15 23:43:27 +13:00
jimmy ac9fca8d4b Pi port: serial transport, addressed ESP-NOW bridge, port 80
- Run app on Raspberry Pi: serial to ESP32 bridge at 912000 baud, /dev/ttyS0
- Remove ESP-NOW/MicroPython-only code from src (espnow, p2p, wifi, machine/Pin)
- Transport: always send 6-byte MAC + payload; optional to/destination_mac in API and WebSocket
- Settings and model DB use project paths (no root); fix sys.print_exception for CPython
- Preset/settings controllers use get_current_sender(); template paths for cwd=src
- Pipfile: run from src, PORT from env; scripts for port 80 (setcap) and test
- ESP32 bridge: receive 6-byte addr + payload, LRU peer management (20 max), handle ESP_ERR_ESPNOW_EXIST
- Add esp32/main.py, esp32/benchmark_peers.py, scripts/setup-port80.sh, scripts/test-port80.sh

Made-with: Cursor
2026-03-15 17:16:07 +13:00
jimmy 0fdc11c0b0 ESP-NOW: STA interface, notify browser on send failure
- Activate STA interface before ESP-NOW to fix ESP_ERR_ESPNOW_IF
- Notify browser on send failure: WebSocket sends error JSON; preset API returns 503
- Use exceptions for failure (not return value) to avoid false errors when send succeeds
- presets.js: handle server error messages in WebSocket onmessage

Made-with: Cursor
2026-03-08 23:47:55 +13:00
jimmyandCursor 91bd78ab31 Add favicon route and minor cleanup
- Add /favicon.ico route (204) to avoid browser 404
- CSS formatting tweaks
- Pipfile trailing newline

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-20 11:49:11 +13:00
jimmyandCursor 2be0640622 Remove WiFi station (client) support
- Drop station connect/status/credentials from wifi util and settings API
- Remove station activation from main
- Remove station UI and JS from index, settings template, and help.js
- Device settings now only configure WiFi Access Point

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-20 11:49:04 +13:00
jimmyandCursor 0e96223bf6 Send tab defaults with presets.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-08 19:40:22 +13:00
jimmyandCursor d8b33923d5 Fix heartbeat LED pin.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-08 19:40:14 +13:00
jimmyandCursor 4ce515be1c Update Python dependencies for device tooling.
This adds ampy support and refreshes lockfile versions.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-08 13:51:28 +13:00
jimmyandCursor f88bf03939 Update browser tests for mobile preset layout.
This keeps UI checks aligned with the new tab/preset flows.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-08 13:51:21 +13:00
jimmyandCursor 7cd4a91350 Add favicon handler and heartbeat LED blink.
This keeps the UI console clean and makes device status visible.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-08 13:51:15 +13:00
jimmyandCursor d907ca37ad Refresh tabs/presets UI and add a mobile menu.
This improves navigation and profile workflows on smaller screens.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-08 13:51:09 +13:00
jimmyandCursor 6c6ed22dbe Scope presets to active profiles and support cloning.
This keeps data isolated per profile while letting users duplicate setups quickly.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-08 13:51:02 +13:00
jimmy 00514f0525 Add in-app settings menu and fix settings API
Move WiFi and device name configuration into a modal menu, reuse existing settings endpoints, and harden settings serialization and startup for MicroPython.
2026-01-29 00:54:20 +13:00
jimmy cf1d831b5a Align controller backend and data with new presets
Update palettes, profiles, tabs, preset sending, and ESPNow message format to match the new preset defaults and driver short-field schema.
2026-01-29 00:04:23 +13:00
jimmy fd37183400 Update frontend for presets, tabs, and help
Align frontend with new preset ID usage and shortened driver fields, improve tab/preset interactions, and refine help and editor UI.
2026-01-28 23:27:50 +13:00
jimmy 5fdeb57b74 Extend endpoint and browser tests for ESPNow and UI
Add coverage for /presets/send and updated tab/preset UI workflows in HTTP and Selenium tests.
2026-01-28 04:44:41 +13:00
jimmy 1576383d09 Update tab UI, presets interactions, and help
Refine tab presets selection and editing, add per-tab removal, improve layout, and provide an in-app help modal.
2026-01-28 04:44:30 +13:00
jimmy 8503315bef Add ESPNow preset send backend support
Implement ESPNow helper model, WebSocket forwarding, and /presets/send endpoint that chunks and broadcasts presets to devices.
2026-01-28 04:43:45 +13:00
jimmy 928263fbd8 Remove Python cache files from version control
- Remove __pycache__ directories that should not be tracked
- These are now ignored via .gitignore
2026-01-27 13:05:22 +13:00
jimmy 7e33f7db6a Add additional configuration and utility files
- Add install script and message configuration
- Add settings controller and templates
- Add ESP-NOW message utility
- Update API documentation
2026-01-27 13:05:09 +13:00
jimmy e74ef6d64f Update main application and dependencies
- Update main.py and run_web.py for local development
- Update microdot session handling
- Update wifi utility
2026-01-27 13:05:07 +13:00
jimmy 3ed435824c Add Selenium dependency for browser tests 2026-01-27 13:05:04 +13:00
jimmy d7fabf58a4 Fix MicroPython compatibility issues in Model class
- Fix JSONDecodeError handling (use ValueError for MicroPython)
- Fix sys.print_exception argument issues
- Improve error handling in load() method
- Add proper file persistence with flush() and os.sync()
2026-01-27 13:05:02 +13:00
jimmy a7e921805a Update controllers to return JSON and fix parameter handling
- Fix decorator parameter order issues with @with_session
- Return JSON responses instead of HTML fragments
- Add proper error handling with JSON error responses
- Fix route parameter conflicts in delete and update endpoints
2026-01-27 13:05:01 +13:00
jimmy c56739c5fa Refactor UI to use JavaScript instead of HTMX
- Replace HTMX with plain JavaScript for tab management
- Consolidate tab UI into single button like profiles
- Add cookie-based current tab storage (client-side)
- Update profiles.js to work with new JSON response format
2026-01-27 13:05:00 +13:00
jimmy fd52e40d17 Add endpoint tests and consolidate test directory
- Add HTTP endpoint tests to mimic browser interactions
- Move old test files from test/ to tests/ directory
- Add comprehensive endpoint tests for tabs, profiles, presets, patterns
- Add README documenting test structure and how to run tests
2026-01-27 13:04:56 +13:00
jimmy f48c8789c7 Add browser automation tests for UI workflows
- Add Selenium-based browser tests for tabs, profiles, presets, and color palette
- Test drag and drop functionality for presets in tabs
- Include cleanup functionality to remove test data after tests
- Tests run against device at 192.168.4.1
2026-01-27 13:04:54 +13:00
jimmy 80ff216e54 Update preset format with n7/n8 parameters
- Add n7 and n8 fields to preset definitions
- Update preset data format
2026-01-17 21:40:38 +13:00
jimmy 1fb3dee942 Update tab storage to 2D grid format
- Change presets from flat array to 2D grid layout
- Add presets_flat array for backward compatibility
- Support 3-column grid layout for preset positioning
2026-01-17 21:40:37 +13:00
jimmy a4502055fb Add test utilities and scripts
- Add test directory with main.py, p2p.py, ws.py
- Add send_empty_json.py WebSocket test script
2026-01-17 21:40:11 +13:00
jimmy 6e61ec8de6 Add P2P communication module
- Implement ESP-NOW async communication
- Support sending string, dict, or bytes data
- Use asend for async broadcast messaging
2026-01-17 21:40:10 +13:00
jimmy 48d02f0e70 Update watch script path in Pipfile
- Fix watch script to use relative paths
2026-01-17 21:40:08 +13:00
jimmy cacaa3505e Add pattern definitions endpoint
- Add /definitions endpoint to pattern controller
- Load pattern.json with fallback paths for local dev and MicroPython
2026-01-17 21:40:07 +13:00
jimmy 97ffc69b12 Add drag-and-drop for presets and colors, max_colors validation, and 2D grid layout
- Add drag-and-drop to reorder presets in tabs (2D grid layout)
- Add drag-and-drop to reorder colors within presets
- Add max_colors field to pattern definitions
- Hide color section when max_colors is 0
- Validate color count against pattern max_colors limit
- Store presets in 2D grid format (3 columns)
- Remove left panel from tab content, show only presets
- Update color palette to show swatches instead of hex codes
- Improve preset editor UI with visual color swatches
2026-01-17 00:58:50 +13:00
jimmy 9f37dbbff0 Add data files and local tooling 2026-01-16 22:31:47 +13:00
jimmy df37f15f73 Update UI for palettes, presets, and patterns 2026-01-16 22:31:36 +13:00
jimmy 9c43a0a22b Update backend models, controllers, and session 2026-01-16 22:31:24 +13:00
jimmy d41faddfca Update static files and templates
- Add htmx library
- Update main.js and styles.css
- Update index.html template
2026-01-11 21:34:19 +13:00
jimmy 9e2409430c Add documentation and utility modules
- Add API specification documentation
- Add system specification document
- Add UI mockups and documentation
- Add utility modules (wifi)
2026-01-11 21:34:18 +13:00
jimmy 5f6e45af09 Clean up obsolete files
- Remove old web.py, wifi.py, patterns.py
- Remove old static files from root
- Remove unused component files
2026-01-11 21:34:17 +13:00
jimmy cccda24448 Add comprehensive model tests
- Add tests for all model CRUD operations
- Add test for base Model class
- Add test runner for all model tests
- Tests include cleanup and validation
2026-01-11 21:34:17 +13:00
jimmy 5cca60d830 Update main.py with controllers and static route
- Mount model controllers as subroutes
- Add static file serving route
- Integrate controllers into main application
2026-01-11 21:34:16 +13:00
jimmy ac750a36e7 Add controllers for models
- Add REST API controllers for all models
- Controllers use Microdot subroutes
- Support CRUD operations via HTTP endpoints
- Controllers: preset, profile, group, sequence, tab, palette
2026-01-11 21:34:15 +13:00
jimmy 01f373f0bd Add model base class and models
- Add Model base class with get_next_id() method
- Add Preset model with CRUD operations
- Add Profile model with tabs and palette support
- Add Group model for device grouping
- Add Sequence model for preset sequencing
- Add Tab model for organizing device controls
- Add Palette model for color collections
2026-01-11 21:34:14 +13:00
jimmy d00d21e2b6 Split up main.js 2025-07-08 18:24:54 +12:00
jimmy deca1b6c37 Add basic draggable item that saves to the server 2025-07-08 17:39:09 +12:00
jimmy 5c35e68ab2 Rename to styles.css 2025-07-07 18:20:11 +12:00
jimmy 8b6bbdeb56 Update wifi.py 2025-05-18 21:31:03 +12:00
jimmy 09bc09cca3 Update web.py 2025-05-18 21:31:00 +12:00
jimmy e57feda131 Delete index_html.py 2025-05-18 21:30:57 +12:00
jimmy 3242aa464b Update index.html 2025-05-18 21:30:50 +12:00
jimmy 72b7ba39ef Update main.js 2025-05-18 21:30:47 +12:00
jimmy c2a0cfaef4 Update main.css 2025-05-18 21:30:44 +12:00
jimmy 4c3337a232 Update settings.py 2025-05-18 21:30:40 +12:00
jimmy 825ae1f637 Update main.py 2025-05-18 21:30:37 +12:00
jimmy 14a70cb024 Update boot.py 2025-05-18 21:30:34 +12:00
jimmy 425511d41f Create Pipfile.lock 2025-05-18 21:30:30 +12:00
jimmy 3e5239f3c6 Create patterns.py 2025-05-18 21:30:24 +12:00
jimmy 2fa02086c9 Add src 2025-05-05 22:19:34 +12:00
jimmy 28fa71b8ad Add dev script and dependencies 2025-05-05 22:18:24 +12:00
jimmy dc691b522b Add libraries 2025-05-05 22:17:47 +12:00
jimmy 29d7a5bcfc Inital slider 2025-05-04 18:06:21 +12:00
jimmy e0a0e083be Initial commit 2025-04-15 10:14:46 +00:00
163 changed files with 30533 additions and 982 deletions
+116
View File
@@ -0,0 +1,116 @@
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434706543}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434706552}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434707852}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434707860}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434708466}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434708474}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/create-form-fragment","targetId":""},"timestamp":1768434709765}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/create-form-fragment","targetId":""},"timestamp":1768434709787}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs","targetId":"tabs-list"},"timestamp":1768434717888}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":201,"responseURL":"http://localhost:5000/tabs","targetId":"tabs-list"},"timestamp":1768434717903}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434717904}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434717913}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434738084}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434738093}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434739031}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434739040}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434746453}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434746496}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/create-form-fragment","targetId":""},"timestamp":1768434748859}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/create-form-fragment","targetId":""},"timestamp":1768434748866}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs","targetId":"tabs-list"},"timestamp":1768434773921}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":201,"responseURL":"http://localhost:5000/tabs","targetId":"tabs-list"},"timestamp":1768434773931}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434773931}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434773940}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/create-form-fragment","targetId":""},"timestamp":1768434810105}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/create-form-fragment","targetId":""},"timestamp":1768434810119}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs","targetId":"tabs-list"},"timestamp":1768434816383}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":201,"responseURL":"http://localhost:5000/tabs","targetId":"tabs-list"},"timestamp":1768434816399}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434816400}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434816414}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434944656}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434944756}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434945369}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434945427}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434946108}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434946162}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434946680}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434946736}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/create-form-fragment","targetId":""},"timestamp":1768434947640}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/create-form-fragment","targetId":""},"timestamp":1768434947656}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs","targetId":"tabs-list"},"timestamp":1768434953064}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":201,"responseURL":"http://localhost:5000/tabs","targetId":"tabs-list"},"timestamp":1768434953079}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434953080}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768434953093}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435103720}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435103776}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435104593}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435104647}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435105158}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435105253}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435275247}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435275315}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435276178}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435276278}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435276945}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435276998}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/create-form-fragment","targetId":""},"timestamp":1768435278150}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/create-form-fragment","targetId":""},"timestamp":1768435278162}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs","targetId":"tabs-list"},"timestamp":1768435281966}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":400,"responseURL":"http://localhost:5000/tabs","targetId":"tabs-list"},"timestamp":1768435281988}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435387623}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435387680}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435388399}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435388454}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/create-form-fragment","targetId":""},"timestamp":1768435389910}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/create-form-fragment","targetId":""},"timestamp":1768435389922}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs","targetId":"tabs-list"},"timestamp":1768435393213}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs","targetId":"tabs-list"},"timestamp":1768435393231}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435393233}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435393245}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/12/content-fragment","targetId":"tab-content"},"timestamp":1768435395729}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/12/content-fragment","targetId":"tab-content"},"timestamp":1768435395748}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/13/content-fragment","targetId":"tab-content"},"timestamp":1768435396771}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/13/content-fragment","targetId":"tab-content"},"timestamp":1768435396788}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/12/content-fragment","targetId":"tab-content"},"timestamp":1768435398656}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/12/content-fragment","targetId":"tab-content"},"timestamp":1768435398674}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/13/content-fragment","targetId":"tab-content"},"timestamp":1768435399748}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/13/content-fragment","targetId":"tab-content"},"timestamp":1768435399774}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435668310}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:DOMContentLoaded","message":"palette elements presence","data":{"hasPaletteButton":true,"hasPaletteModal":false,"hasPaletteContainer":false,"hasLightingController":false},"timestamp":1768435668311}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435668355}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435669841}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:DOMContentLoaded","message":"palette elements presence","data":{"hasPaletteButton":true,"hasPaletteModal":false,"hasPaletteContainer":false,"hasLightingController":false},"timestamp":1768435669842}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435669852}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:color-palette-btn","message":"color palette button clicked","data":{"hasPaletteModal":false,"modalActive":null},"timestamp":1768435672686}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:color-palette-btn","message":"color palette button clicked","data":{"hasPaletteModal":false,"modalActive":null},"timestamp":1768435673713}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:color-palette-btn","message":"color palette button clicked","data":{"hasPaletteModal":false,"modalActive":null},"timestamp":1768435674316}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:color-palette-btn","message":"color palette button clicked","data":{"hasPaletteModal":false,"modalActive":null},"timestamp":1768435674560}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:color-palette-btn","message":"color palette button clicked","data":{"hasPaletteModal":false,"modalActive":null},"timestamp":1768435680419}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:color-palette-btn","message":"color palette button clicked","data":{"hasPaletteModal":false,"modalActive":null},"timestamp":1768435680897}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435814285}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:DOMContentLoaded","message":"palette elements presence","data":{"hasPaletteButton":true,"hasPaletteModal":true,"hasPaletteContainer":false,"hasLightingController":false},"timestamp":1768435814287}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H3","location":"src/static/color_palette.js:DOMContentLoaded","message":"palette script loaded","data":{"hasButton":true,"hasModal":true,"hasClose":true},"timestamp":1768435814287}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435814350}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435815080}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H3","location":"src/static/color_palette.js:DOMContentLoaded","message":"palette script loaded","data":{"hasButton":true,"hasModal":true,"hasClose":true},"timestamp":1768435815081}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:DOMContentLoaded","message":"palette elements presence","data":{"hasPaletteButton":true,"hasPaletteModal":true,"hasPaletteContainer":false,"hasLightingController":false},"timestamp":1768435815082}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435815135}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435815724}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H3","location":"src/static/color_palette.js:DOMContentLoaded","message":"palette script loaded","data":{"hasButton":true,"hasModal":true,"hasClose":true},"timestamp":1768435815725}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:DOMContentLoaded","message":"palette elements presence","data":{"hasPaletteButton":true,"hasPaletteModal":true,"hasPaletteContainer":false,"hasLightingController":false},"timestamp":1768435815725}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435815778}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H4","location":"src/static/color_palette.js:openModal","message":"palette modal opened","data":{"active":true},"timestamp":1768435817104}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:color-palette-btn","message":"color palette button clicked","data":{"hasPaletteModal":true,"modalActive":true},"timestamp":1768435817105}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H4","location":"src/static/color_palette.js:closeModal","message":"palette modal closed","data":{"active":false},"timestamp":1768435820180}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435931118}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:DOMContentLoaded","message":"palette elements presence","data":{"hasPaletteButton":true,"hasPaletteModal":true,"hasPaletteContainer":true,"hasLightingController":false},"timestamp":1768435931120}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H3","location":"src/static/color_palette.js:DOMContentLoaded","message":"palette script loaded","data":{"hasButton":true,"hasModal":true,"hasClose":true,"hasContainer":true,"hasAddButton":true},"timestamp":1768435931119}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435931173}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:htmx:beforeRequest","message":"htmx request","data":{"path":"/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435931791}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H1","location":"src/templates/index.html:DOMContentLoaded","message":"palette elements presence","data":{"hasPaletteButton":true,"hasPaletteModal":true,"hasPaletteContainer":true,"hasLightingController":false},"timestamp":1768435931793}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H3","location":"src/static/color_palette.js:DOMContentLoaded","message":"palette script loaded","data":{"hasButton":true,"hasModal":true,"hasClose":true,"hasContainer":true,"hasAddButton":true},"timestamp":1768435931793}
{"sessionId":"debug-session","runId":"tabs-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:htmx:afterRequest","message":"htmx response","data":{"status":200,"responseURL":"http://localhost:5000/tabs/list-fragment","targetId":"tabs-list"},"timestamp":1768435931895}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H2","location":"src/templates/index.html:color-palette-btn","message":"color palette button clicked","data":{"hasPaletteModal":true,"modalActive":true},"timestamp":1768435933111}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H4","location":"src/static/color_palette.js:openModal","message":"palette modal opened","data":{"active":true},"timestamp":1768435933110}
{"sessionId":"debug-session","runId":"palette-pre-fix","hypothesisId":"H4","location":"src/static/color_palette.js:closeModal","message":"palette modal closed","data":{"active":false},"timestamp":1768435943332}
+26
View File
@@ -0,0 +1,26 @@
---
description: Git commit messages and how to split work into commits
alwaysApply: true
---
# Commits
When preparing commits (especially when the user asks to commit):
1. **Prefer multiple commits** over one large commit when changes span distinct concerns (e.g. UI vs docs vs API). One logical unit per commit.
2. **Message format:** `type(scope): short imperative subject` (lowercase subject after the colon; no trailing period).
- **Types:** `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`, `perf` (use what fits).
- **Scope:** optional but encouraged — e.g. `ui`, `api`, `profiles`, `presets`, `esp32`.
3. **Subject line:** ~50 characters or less; describe *what* changed, not the ticket number alone.
4. **Body:** only when needed (breaking change, non-obvious rationale, or multiple bullets). Otherwise subject is enough.
**Examples**
- `feat(ui): gate profile delete to edit mode`
- `docs: document run vs edit in API`
- `fix(api): resolve preset delete route argument clash`
**Do not**
- Squash unrelated fixes and doc tweaks into one commit unless the user explicitly wants a single commit.
- Use vague messages like `update`, `fixes`, or `wip`.
+45
View File
@@ -0,0 +1,45 @@
---
description: led-driver — MicroPython ESP32: mpremote, imports, layout, I/O, no pycache in src
globs: led-driver/**
alwaysApply: false
---
# led-driver (MicroPython / ESP32)
## Device and tests
1. Validate **MicroPython behaviour** under **`led-driver/`** with **`mpremote connect <PORT> …`** on the chip. Host **`python3`** does **not** prove the firmware build.
2. **Execution target is fixed:** treat **`led-driver/`** code as firmware that runs **only on MicroPython ESP32 devices**. Do **not** run `led-driver/src/main.py` (or other firmware modules) with host CPython as a normal execution path.
3. **Flow:** `mpremote connect <PORT> cp <local> :<on-flash>` then `run <script>.py`. Inline commands only — no **`.sh`** wrappers unless the user asks. Default serial placeholder: **`/dev/ttyACM0`**.
4. Checks that **import and run** code from **`led-driver/src/`** belong in **`led-driver/tests/`** and run with **`mpremote run …`**. **Do not** add **`pytest`** under **`led-controller/tests/`** that **`sys.path`**-loads **`led-driver/src`** and runs those modules on CPython.
## Import layout
4. **No** **`sys.path.insert`**, **`__file__`** path stitching, or other import-path hacks under **`led-driver/`**. Use device flash search path, or host **`PYTHONPATH`** / layout you control.
5. **No** “import fixer” code — fix copy order, flash paths, or env instead.
## Imports (fail loudly)
6. If a dependency does not load, **crash** and fix deployment or filesystem. **Do not** catch **`ImportError`** / **`ModuleNotFoundError`** around **`import`** / **`from … import`** for app/firmware modules (`settings`, `utils`, `network`, `machine`, …).
7. **Allowed — stdlib name pairs only** (MicroPython vs CPython): one **`except ImportError`**, then **one** fallback import, **no** extra logic in **`except`**:
- `uos` → `os`
- `ubinascii` → `binascii`
- `utime` → `time`
Not for “maybe the file exists on flash” — only different **stdlib** names.
8. **No** large inline reimplementations after **`except ImportError`** — deploy the real module.
## I/O
9. Non-blocking **recv** / **accept**: use plain **`except OSError:`** (or **break** on empty). **No** errno / EAGAIN / EWOULDBLOCK tables or **`getattr(errno, …)`** unless fixing a **documented** target bug.
10. Minimal **`try` / `except OSError`** around optional socket options (e.g. **`SO_REUSEADDR`**) is fine.
## Host Python and `src/`
11. **Do not** leave **`__pycache__/`** or **`.pyc`** under **`led-driver/src/`** from host runs. Remove if created; **`.gitignore`** already ignores it. Prefer **`PYTHONDONTWRITEBYTECODE=1`** or **`-B`** when host Python must touch **`led-driver/src/`**.
+18
View File
@@ -0,0 +1,18 @@
---
description: Fix only the issue or task the user gave; no refactors unless requested
alwaysApply: true
---
# Scoped fixes (no overscoping)
1. **Change only what is needed** to satisfy the user’s *current* request (bug, error, feature, or explicit follow-up). Prefer the smallest diff that fixes it.
2. **Refactors:** Do **not** refactor (restructure, rename, extract functions, change abstractions, or “make it nicer”) **unless the user explicitly asked for a refactor**. A bug fix may touch nearby lines only as much as required to correct the bug.
3. **Do not** rename, reformat, or “clean up” unrelated code; do not add extra error handling, logging, or features you were not asked for.
4. **Related issues:** If you spot other problems (missing functions, wrong types elsewhere, style), you may **mention them in prose** — do **not** fix them unless the user explicitly asks.
5. **Tests and docs:** Add or change tests or documentation **only** when the user asked for them or they are strictly required to verify the requested fix.
6. **Multiple distinct fixes:** If the user reported one error (e.g. a single `TypeError`), fix **that** cause first. Offer to tackle follow-ups separately rather than bundling.
+10
View File
@@ -0,0 +1,10 @@
---
description: British spelling for user-facing text; technical identifiers stay as-is
alwaysApply: true
---
# Spelling: colour
- **User-facing strings** (Help modal, button labels, README prose, `docs/`, error messages shown in the UI): use **British English** — **colour**, **favour**, **behaviour**, etc., unless quoting existing product names.
- **Do not rename** existing code for spelling: **identifiers**, file names, URL paths, JSON keys, CSS properties (`color`), HTML attributes (`type="color"`), and API field names stay as they are (`color`, `colors`, `palette`, etc.) so nothing breaks.
- **New** UI copy and docs should follow **colour** in prose; new code symbols may still use `color` when matching surrounding APIs or conventions.
+16
View File
@@ -0,0 +1,16 @@
---
description: enforce strict user-scoped changes only
alwaysApply: true
---
# Strict User Scope
1. Only implement exactly what the user asked for in the current message.
2. Do not add extra refactors, cleanups, renames, architecture changes, or behavioural changes unless the user explicitly asked for them.
3. If a potential improvement is noticed, mention it briefly and ask before changing code.
4. For revert/undo requests, perform the narrowest possible revert and do not modify anything else.
5. Keep edits minimal and local to the requested area.
+34
View File
@@ -0,0 +1,34 @@
# Python
__pycache__/
# led-driver/src is MicroPython source — never keep host __pycache__ there (see .cursor/rules/led-driver.mdc)
led-driver/src/__pycache__/
*.py[cod]
*$py.class
*.so
.Python
# Virtual environments
venv/
env/
ENV/
.venv
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# OS
.DS_Store
Thumbs.db
# Project specific
docs/.help-print.html
settings.json
*.log
*.db
*.sqlite
.pytest_cache/
.ropeproject/
+6
View File
@@ -0,0 +1,6 @@
[submodule "led-driver"]
path = led-driver
url = git@git.technical.kiwi:technicalkiwi/led-driver.git
[submodule "led-tool"]
path = led-tool
url = git@git.technical.kiwi:technicalkiwi/led-tool.git
+235
View File
@@ -0,0 +1,235 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
led-controller
Copyright (C) 2025 technicalkiwi
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
+19 -3
View File
@@ -4,11 +4,27 @@ verify_ssl = true
name = "pypi"
[packages]
fastapi = "*"
uvicorn = "*"
jinja2 = "*"
mpremote = "*"
pyserial = "*"
esptool = "*"
pyjwt = "*"
watchfiles = "*"
requests = "*"
selenium = "*"
adafruit-ampy = "*"
microdot = "*"
websockets = "*"
[dev-packages]
pytest = "*"
[requires]
python_version = "3.12"
[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"
Generated
+952 -215
View File
File diff suppressed because it is too large Load Diff
+43
View File
@@ -0,0 +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:
- **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.
## API docs
- Main API reference: `docs/API.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.
-20
View File
@@ -1,20 +0,0 @@
from pydantic import BaseModel
class ColorUpdate(BaseModel):
barId: str
color: str
class PositionUpdate(BaseModel):
barId: str
x: int
y: int
class CreateBar(BaseModel):
barId: str
url: str
color: str
x: int
y: int
class DeleteBar(BaseModel):
barId: str
-57
View File
@@ -1,57 +0,0 @@
from fastapi import APIRouter, HTTPException
from .models import ColorUpdate, PositionUpdate, CreateBar, DeleteBar
from .settings_manager import SettingsManager
router = APIRouter(prefix="/api")
settings_manager = SettingsManager()
@router.get("/settings")
async def get_settings():
try:
return settings_manager.load_settings()
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error reading settings: {str(e)}")
@router.post("/settings/color")
async def update_color(color_update: ColorUpdate):
try:
settings_manager.update_color(color_update.barId, color_update.color)
return {"success": True, "message": f"Color updated for {color_update.barId}"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error updating settings: {str(e)}")
@router.post("/settings/position")
async def update_position(position_update: PositionUpdate):
try:
settings_manager.update_position(position_update.barId, position_update.x, position_update.y)
return {"success": True, "message": f"Position updated for {position_update.barId}"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error updating settings: {str(e)}")
@router.post("/settings/create")
async def create_bar(create_bar: CreateBar):
try:
if settings_manager.bar_exists(create_bar.barId):
raise HTTPException(status_code=400, detail=f"Bar {create_bar.barId} already exists")
settings_manager.create_bar(
create_bar.barId,
create_bar.url,
create_bar.color,
create_bar.x,
create_bar.y
)
return {"success": True, "message": f"Bar {create_bar.barId} created"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error creating bar: {str(e)}")
@router.delete("/settings/delete")
async def delete_bar(delete_bar: DeleteBar):
try:
if not settings_manager.bar_exists(delete_bar.barId):
raise HTTPException(status_code=404, detail=f"Bar {delete_bar.barId} not found")
settings_manager.delete_bar(delete_bar.barId)
return {"success": True, "message": f"Bar {delete_bar.barId} deleted"}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error deleting bar: {str(e)}")
-51
View File
@@ -1,51 +0,0 @@
import json
import os
from typing import Dict, Any
class SettingsManager:
def __init__(self, settings_file: str = "settings.json"):
self.settings_file = settings_file
def load_settings(self) -> Dict[str, Any]:
try:
with open(self.settings_file, "r") as f:
return json.load(f)
except FileNotFoundError:
return {}
def save_settings(self, settings: Dict[str, Any]) -> None:
with open(self.settings_file, "w") as f:
json.dump(settings, f, indent=2)
def update_color(self, bar_id: str, color: str) -> None:
settings = self.load_settings()
if bar_id in settings:
settings[bar_id]["color"] = color
self.save_settings(settings)
def update_position(self, bar_id: str, x: int, y: int) -> None:
settings = self.load_settings()
if bar_id in settings:
settings[bar_id]["x"] = x
settings[bar_id]["y"] = y
self.save_settings(settings)
def create_bar(self, bar_id: str, url: str, color: str, x: int, y: int) -> None:
settings = self.load_settings()
settings[bar_id] = {
"url": url,
"color": color,
"x": x,
"y": y
}
self.save_settings(settings)
def delete_bar(self, bar_id: str) -> None:
settings = self.load_settings()
if bar_id in settings:
del settings[bar_id]
self.save_settings(settings)
def bar_exists(self, bar_id: str) -> bool:
settings = self.load_settings()
return bar_id in settings
+1
View File
@@ -0,0 +1 @@
{"188b0e1560a8": {"id": "188b0e1560a8", "name": "led-188b0e1560a8", "type": "led", "transport": "wifi", "address": "10.1.1.192", "default_pattern": null, "zones": []}, "f0f5bdfb9d30": {"id": "f0f5bdfb9d30", "name": "led-f0f5bdfb9d30", "type": "led", "transport": "wifi", "address": "10.1.1.232", "default_pattern": null, "zones": []}}
+1
View File
@@ -0,0 +1 @@
{"1": {"name": "Main Group", "devices": ["1", "2", "3"]}, "2": {"name": "Accent Group", "devices": ["4", "5"]}}
+1
View File
@@ -0,0 +1 @@
{"1": ["#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#FF00FF", "#00FFFF", "#FFFFFF", "#000000"], "2": [], "3": [], "4": [], "5": [], "6": [], "7": ["#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#FF00FF", "#00FFFF", "#FFFFFF", "#000000"], "8": [], "9": [], "10": [], "11": [], "12": ["#890b0b", "#0b8935"]}
+92
View File
@@ -0,0 +1,92 @@
{
"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–30 s, -1=off)",
"n4": "Spark gap max (ms)",
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10
},
"twinkle": {
"n1": "Twinkle activity (1–255, higher = more changes)",
"n2": "Density (0–255, higher = more of the strip lit)",
"n3": "Min adjacent LEDs per twinkle (same as max for fixed length)",
"n4": "Max adjacent LEDs per twinkle (same as min for fixed length)",
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10
},
"radiate": {
"n1": "Node spacing (LEDs)",
"n2": "Out time (ms)",
"n3": "In time (ms)",
"min_delay": 10,
"max_delay": 10000,
"max_colors": 2
}
}
+1
View File
File diff suppressed because one or more lines are too long
+1
View File
@@ -0,0 +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"}}
+22
View File
@@ -0,0 +1,22 @@
{
"1": {
"name": "Default Scene",
"sequences": [
"1"
],
"groups": [
"1"
]
},
"2": {
"name": "Party Mode",
"sequences": [
"1",
"2"
],
"groups": [
"1",
"2"
]
}
}
+1
View File
@@ -0,0 +1 @@
{"1": {"group_name": "Main Group", "presets": ["1", "2"], "sequence_duration": 3000, "sequence_transition": 500, "sequence_loop": true, "sequence_repeat_count": 0, "sequence_active": false, "sequence_index": 0, "sequence_start_time": 0}, "2": {"group_name": "Accent Group", "presets": ["2", "3"], "sequence_duration": 2000, "sequence_transition": 300, "sequence_loop": true, "sequence_repeat_count": 0, "sequence_active": false, "sequence_index": 0, "sequence_start_time": 0}}
+1
View File
@@ -0,0 +1 @@
{"1": {"name": "default", "names": ["led-188b0e1560a8", "led-f0f5bdfb9d30"], "presets": [["4", "2", "7"], ["3", "14", "5"], ["8", "9", "1"], ["6", "38", "42"], ["39", "40", "41"]], "presets_flat": ["4", "2", "7", "3", "14", "5", "8", "9", "1", "6", "38", "42", "39", "40", "41"], "default_preset": "4"}, "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}, "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"]}}
+358
View File
@@ -0,0 +1,358 @@
# LED Controller API
This document covers:
1. **HTTP and WebSocket** exposed by the Raspberry Pi app (`src/main.py`) — profiles, zones, presets, transport send, pattern OTA helpers, and related resources.
2. **LED driver JSON** — the compact **v1** message format. It is sent over the **serial → ESP-NOW bridge** to ESP32 peers and as **single JSON text messages** over the **outbound WebSocket** to **Wi-Fi** drivers (same logical fields).
Default HTTP listen address: `0.0.0.0`. Port defaults to **80**; override with the **`PORT`** environment variable (see `pipenv run run`).
**Serial:** UART path and baud come from settings (defaults include `serial_port` such as `/dev/ttyS0` and `serial_baudrate`). **Wi-Fi drivers:** **UDP** on port **8766** is the **discovery** channel: each driver’s JSON hello (**`device_name`**, **MAC**, optional **`type`**) **creates or updates** that device in **`db/device.json`** (keyed by MAC); the Pi echoes the datagram. After a valid hello with **`v`:** **`"1"`**, the Pi also opens an **outbound WebSocket** to that IP (**`wifi_driver_ws_port`**, default **80**; **`wifi_driver_ws_path`**, default **`/ws`**) for v1 commands; presets are not pushed automatically on connect (use **Send Presets** / profile apply). The Pi may send periodic UDP **hello** nudges to known Wi‑Fi device IPs when the WebSocket is down (**`wifi_driver_hello_interval_s`** in settings).
All JSON APIs use `Content-Type: application/json` for bodies and responses unless noted.
---
## UI behavior notes
The main UI has two modes controlled by the mode toggle:
- **Run mode**: optimized for operation (zone/preset selection and profile apply).
- **Edit mode**: shows editing/management controls (zones, presets, patterns, colour palette, send presets, profile management actions, **Devices** registry for LED driver names/MACs, and related tools).
Profiles are available in both modes, but behavior differs:
- **Run mode**: profile **apply** only.
- **Edit mode**: profile **create/clone/delete/apply**.
`POST /presets/send` is wired to the **Send Presets** UI action, which is exposed in Edit mode.
---
## Session and scoping
Several routes use **`@with_session`**: the server stores a **current profile** in the session (cookie). Endpoints that scope data to “the current profile” (notably **`/presets`**) only return or mutate presets whose `profile_id` matches that session value.
Profiles are selected with **`POST /profiles/<id>/apply`**, which sets `current_profile` in the session.
---
## Static pages and assets
| Method | Path | Description |
|--------|------|-------------|
| GET | `/` | Main UI (`templates/index.html`) |
| GET | `/settings` | Settings page (`templates/settings.html`) |
| GET | `/favicon.ico` | Empty response (204) |
| GET | `/static/<path>` | Static files under `src/static/` |
---
## WebSocket: `/ws`
Connect to **`ws://<host>:<port>/ws`**.
- Send **JSON**: the object is forwarded through the **serial sender** (6-byte MAC prefix + payload to the ESP-NOW bridge). Optional key **`to`**: 12-character hex MAC address; if present it is removed from the object and the payload is sent to that peer; otherwise the default destination from settings is used.
- Send **non-JSON text**: forwarded as raw bytes with the default address.
- On send failure, the server may reply with `{"error": "Send failed"}`.
Wi-Fi devices are not targeted by `/ws` directly; use **`POST /presets/send`**, device routes, or **`POST /patterns/<name>/send`** as appropriate.
---
## HTTP API by resource
Below, `<id>` values are string identifiers used by the JSON stores (numeric strings in practice).
### Settings — `/settings`
| Method | Path | Description |
|--------|------|-------------|
| GET | `/settings` | Full settings object (from `settings.json` / `Settings` model). |
| PUT | `/settings/settings` | Merge keys into settings and save. Returns `{"message": "Settings updated successfully"}`. |
| GET | `/settings/wifi/ap` | Saved Wi‑Fi AP fields: `saved_ssid`, `saved_password`, `saved_channel`, `active` (Pi: `active` is always false). |
| POST | `/settings/wifi/ap` | Body: `ssid` (required), `password`, `channel` (1–11). Persists AP-related settings. |
| GET | `/settings/page` | Serves `templates/settings.html` (same page as `GET /settings` from the root app, for convenience). |
### Devices — `/devices`
Registry in `db/device.json`: storage key **`<id>`** (string, e.g. `"1"`) maps to an object that always includes:
| Field | Description |
|-------|-------------|
| **`id`** | Same as the storage key (stable handle for URLs). |
| **`name`** | Shown in the UI and used in `select` keys. |
| **`type`** | `led` (only value today; extensible). |
| **`transport`** | `espnow` or `wifi`. |
| **`address`** | For **`espnow`**: optional 12-character lowercase hex MAC. For **`wifi`**: optional IP or hostname string. |
| **`default_pattern`**, **`zones`** | Optional. Legacy **`tabs`** may still appear in old files and is migrated away on load. |
Existing records without `type` / `transport` / `id` are backfilled on load (`led`, `espnow`, and `id` = key).
| Method | Path | Description |
|--------|------|-------------|
| GET | `/devices` | Map of device id → device object. |
| GET | `/devices/<id>` | One device, 404 if missing. |
| POST | `/devices` | Create. Body: **`name`** (required), **`type`** (default `led`), **`transport`** (default `espnow`), optional **`address`**, **`default_pattern`**, **`zones`**. Returns `{ "<id>": { ... } }`, 201. |
| PUT | `/devices/<id>` | Partial update. **`name`** cannot be cleared. **`id`** in the body is ignored. **`type`** / **`transport`** validated; **`address`** normalised for the resulting transport. |
| DELETE | `/devices/<id>` | Remove device. |
### Profiles — `/profiles`
| Method | Path | Description |
|--------|------|-------------|
| GET | `/profiles` | `{"profiles": {...}, "current_profile_id": "<id>"}`. Ensures a default current profile when possible. |
| GET | `/profiles/current` | `{"id": "...", "profile": {...}}` |
| GET | `/profiles/<id>` | Single profile. If `<id>` is `current`, same as `/profiles/current`. |
| POST | `/profiles` | Create profile. Body may include `name` and other fields. Optional `seed_dj_zone` (request-only) seeds a DJ zone + presets. New profiles always get a populated `default` zone. Returns `{ "<id>": { ... } }` with status 201. |
| POST | `/profiles/<id>/apply` | Sets session current profile to `<id>`. |
| POST | `/profiles/<id>/clone` | Clone profile (zones, palettes, presets). Body may include `name`. |
| PUT | `/profiles/current` | Update the current profile (from session). |
| PUT | `/profiles/<id>` | Update profile by id. |
| DELETE | `/profiles/<id>` | Delete profile. |
### Presets — `/presets`
Scoped to **current profile** in session (see above).
| Method | Path | Description |
|--------|------|-------------|
| GET | `/presets` | Map of preset id → preset object for the current profile only. |
| GET | `/presets/<id>` | One preset, 404 if missing or wrong profile. |
| POST | `/presets` | Create preset; server assigns id and sets `profile_id`. Body fields stored on the preset. Returns `{ "<id>": { ... } }`, 201. |
| PUT | `/presets/<id>` | Update preset (must belong to current profile). |
| DELETE | `/presets/<id>` | Delete preset. |
| POST | `/presets/send` | Push presets to the LED driver over the configured transport (see below). |
**`POST /presets/send` body:**
```json
{
"preset_ids": ["1", "2"],
"save": true,
"default": "1",
"destination_mac": "aabbccddeeff"
}
```
- **`preset_ids`** (or **`ids`**): non-empty list of preset ids to include.
- **`save`**: if true, the outgoing message includes `"save": true` so the driver may persist presets (default true).
- **`default`**: optional preset id string; forwarded as top-level `"default"` in the driver message (startup selection on device).
- **`destination_mac`** (or **`to`**): optional 12-character hex MAC for unicast; omitted uses the transport default (e.g. broadcast).
Response on success includes `presets_sent`, `messages_sent` (chunking splits payloads so each JSON string stays ≤ 240 bytes).
Stored preset records can include:
- `colors`: resolved hex colours for editor/display.
- `palette_refs`: optional array of palette indexes parallel to `colors`. If a slot contains an integer index, the colour is linked to the current profile palette at that index.
### Zones — `/zones`
| Method | Path | Description |
|--------|------|-------------|
| GET | `/zones` | `zones` (map of zone id → zone object), `zone_order`, `current_zone_id`, `profile_id` for the session-backed profile. |
| GET | `/zones/current` | Current zone from cookie/session. |
| POST | `/zones` | Create zone; optional JSON `name`, `names`, `presets`; can append to current profile’s zone list. |
| GET | `/zones/<id>` | Zone JSON. |
| PUT | `/zones/<id>` | Update zone. |
| DELETE | `/zones/<id>` | Delete zone; can delete `current` to remove the active zone; updates profile zone list. |
| POST | `/zones/<id>/set-current` | Sets `current_zone` cookie. |
| POST | `/zones/<id>/clone` | Clone zone into current profile. |
### Palettes — `/palettes`
| Method | Path | Description |
|--------|------|-------------|
| GET | `/palettes` | Map of id → colour list. |
| GET | `/palettes/<id>` | `{"colors": [...], "id": "<id>"}` |
| POST | `/palettes` | Body may include `colors`. Returns palette object with `id`, 201. |
| PUT | `/palettes/<id>` | Update colours (`name` ignored). |
| DELETE | `/palettes/<id>` | Delete palette. |
### Groups — `/groups`
| Method | Path | Description |
|--------|------|-------------|
| GET | `/groups` | All groups. |
| GET | `/groups/<id>` | One group. |
| POST | `/groups` | Create; optional `name` and fields. |
| PUT | `/groups/<id>` | Update. |
| DELETE | `/groups/<id>` | Delete. |
### Scenes — `/scenes`
| Method | Path | Description |
|--------|------|-------------|
| GET | `/scenes` | All scenes. |
| GET | `/scenes/<id>` | One scene. |
| POST | `/scenes` | Create (body JSON stored on scene). |
| PUT | `/scenes/<id>` | Update. |
| DELETE | `/scenes/<id>` | Delete. |
### Sequences — `/sequences`
| Method | Path | Description |
|--------|------|-------------|
| GET | `/sequences` | All sequences. |
| GET | `/sequences/<id>` | One sequence. |
| POST | `/sequences` | Create; may use `group_name`, `presets` in body. |
| PUT | `/sequences/<id>` | Update. |
| DELETE | `/sequences/<id>` | Delete. |
### Patterns — `/patterns`
Pattern metadata lives in **`db/pattern.json`**; driver source files live under **`led-driver/src/patterns/`**. Several routes expose a **runtime map** (metadata merged with on-disk `.py` names so new files appear in menus).
| Method | Path | Description |
|--------|------|-------------|
| GET | `/patterns` | Runtime pattern map (object keyed by pattern id). |
| GET | `/patterns/definitions` | Same runtime map (intended for UI “definitions” clients). |
| GET | `/patterns/ota/manifest` | JSON `{"files":[{"name":"blink.py","url":"http://<Host>/patterns/ota/file/blink.py"},...]}` for OTA pulls. Requires **`Host`** header. |
| GET | `/patterns/ota/file/<name>` | Raw **`.py`** source for one driver pattern (`name` must be a safe filename, e.g. `rainbow.py`). |
| POST | `/patterns/<name>/send` | Push a **manifest** JSON line to **Wi-Fi** devices so they pull one pattern file over HTTP. Body may include **`device_id`** to target one device; otherwise all Wi-Fi devices with an **`address`** are tried. **`<name>`** may be with or without `.py`. |
| POST | `/patterns/upload` | Body JSON: **`name`**, **`code`**, optional **`overwrite`** (default true). Writes **`led-driver/src/patterns/<name>.py`**. |
| POST | `/patterns/driver` | Body JSON: **`name`** (identifier), **`code`**, optional metadata (`min_delay`, `max_delay`, `max_colors`, `n1`…`n8`, **`overwrite`**). Creates/updates both the **`.py`** file and **`db/pattern.json`** via the Pattern model. |
| GET | `/patterns/<id>` | One pattern record from the Pattern model (metadata only). |
| POST | `/patterns` | Create (`name`, optional `data`). |
| PUT | `/patterns/<id>` | Update. |
| DELETE | `/patterns/<id>` | Delete. |
**Devices — pattern OTA push**
| Method | Path | Description |
|--------|------|-------------|
| POST | `/devices/<id>/patterns/push` | Wi-Fi only. Asks the driver at **`address`** to pull pattern files from this server. Optional body **`manifest`**: either a **URL string** pointing at a manifest JSON document, or a **manifest object** (same shape as in driver messages). If omitted, a default manifest is built from the request **`Host`** header. |
---
## LED driver message format (transport / ESP-NOW / Wi-Fi)
Messages are JSON objects. The Pi **`build_message()`** helper (`src/util/espnow_message.py`) produces the same shape sent over serial and forwarded by the ESP32 bridge, and the same logical object can be sent as a **single JSON text message** to a Wi-Fi driver over the **WebSocket**.
### Top-level fields
```json
{
"v": "1",
"presets": { },
"select": { },
"save": true,
"default": "preset_id",
"b": 255
}
```
- **`v`** (required): Must be `"1"` or the driver ignores the message.
- **`presets`**: Map of **preset id** (string) → preset object (see below). Optional **`name`** field on each value is accepted for display; the driver keys presets by map key.
- **`select`**: Map of **device name** (as in device settings) → `[ "preset_id" ]` or `[ "preset_id", step ]`.
- **`save`**: If present (e.g. true), the driver may persist presets to flash after applying.
- **`default`**: Preset id string to use as startup default on the device.
- **`b`**: Optional **global** brightness 0–255 (driver applies this in addition to per-preset brightness).
### Preset object (wire / driver keys)
On the wire, presets use **short keys** (saves space in the ≤240-byte chunks):
| Key | Meaning | Notes |
|-----|---------|--------|
| `p` | Pattern id | `off`, `on`, `blink`, `rainbow`, `pulse`, `transition`, `chase`, `circle` |
| `c` | Colours | Array of `"#RRGGBB"` hex strings; converted to RGB on device |
| `d` | Delay ms | Default 100 |
| `b` | Preset brightness | 0–255; combined with global `b` on the device |
| `a` | Auto | `true`: run continuously; `false`: one step/cycle per “beat” |
| `n1`–`n6` | Pattern parameters | See below |
The HTTP app’s **`POST /presets/send`** path builds this from stored presets via **`build_preset_dict()`** (long names like `pattern` / `colors` in the DB are translated to `p` / `c` / …).
### Pattern-specific parameters (`n1`–`n6`)
#### Rainbow
- **`n1`**: Step increment on the colour wheel per update (default 1).
#### Pulse
- **`n1`**: Attack (fade in) ms
- **`n2`**: Hold ms
- **`n3`**: Decay (fade out) ms
- **`d`**: Off time between pulses ms
#### Transition
- **`d`**: Transition duration ms
#### Chase
- **`n1`**: LEDs with first colour
- **`n2`**: LEDs with second colour
- **`n3`**: Movement on even steps (may be negative)
- **`n4`**: Movement on odd steps (may be negative)
#### Circle
- **`n1`**: Head speed (LEDs/s)
- **`n2`**: Max length
- **`n3`**: Tail speed (LEDs/s)
- **`n4`**: Min length
### Select messages
```json
{
"select": {
"device_name": ["preset_id"],
"other_device": ["preset_id", 10]
}
}
```
- One element: select preset; step behavior follows driver rules (reset on `off`, etc.).
- Two elements: explicit **step** for sync.
### Beat and sync behavior
- Sending **`select`** again with the **same** preset name acts as a **beat** (advances manual patterns / restarts generators per driver logic).
- Choosing **`off`** resets step as a sync point; then selecting a pattern aligns step 0 across devices unless a step is passed explicitly.
### Example (compact preset map)
```json
{
"v": "1",
"save": true,
"presets": {
"1": {
"name": "Red blink",
"p": "blink",
"c": ["#FF0000"],
"d": 200,
"b": 255,
"a": true,
"n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0
}
},
"select": {
"living-room": ["1"]
}
}
```
---
## Processing summary (driver)
1. Reject if `v != "1"`.
2. Apply optional top-level **`b`** (global brightness).
3. For each entry in **`presets`**, normalize colours and upsert preset by id.
4. If this device’s **`name`** appears in **`select`**, run selection (optional step).
5. If **`default`** is set, store startup preset id.
6. If **`save`** is set, persist presets.
---
## Error handling (HTTP)
Controllers typically return JSON with an **`error`** string and 4xx/5xx status codes. Invalid JSON bodies often yield `{"error": "Invalid JSON"}`.
---
## Notes
- **Human-readable preset fields** (`pattern`, `colors`, `delay`, …) are fine in the **web app / database**; the **send path** converts them to **`p` / `c` / `d`** for the driver.
- For a copy of the older long-key reference, see **`led-driver/docs/API.md`** in this repo (conceptually the same behavior; wire format prefers short keys).
File diff suppressed because it is too large Load Diff
+114
View File
@@ -0,0 +1,114 @@
# LED controller — user guide
This page describes the **main web UI** served from the Raspberry Pi app: profiles, **zones**, presets, colour palettes, and sending commands to LED devices. Traffic may go over the **serial → ESP-NOW bridge** or **Wi-Fi** (TCP to drivers on the LAN), depending on each device’s transport.
For HTTP routes and the wire format the driver expects, see **[API.md](API.md)**. For running the app locally, see the project **README**.
Figures below are **schematic** (layout and ideas), not pixel-perfect screenshots.
---
## Run mode and Edit mode
The header has a mode toggle (desktop and mobile menu). The **label on the button is the mode you switch to** when you press it.
![Schematic: zone buttons on the left; Profiles, Zones, Presets, Patterns, and the mode toggle on the right (example shows Edit mode with “Run mode” on the button).](images/help/header-toolbar.svg)
*The active zone is highlighted. Extra management buttons appear only in Edit mode.*
| Mode | Purpose |
|------|--------|
| **Run mode** | Day-to-day control: choose a zone, tap presets, apply profiles. Management buttons are hidden. |
| **Edit mode** | Full setup: zones, presets, patterns, colour palette, **Send Presets**, profile create/clone/delete, preset reordering, and per-tile **Edit** on the strip. |
**Profiles** is available in both modes: in Run mode you can only **apply** a profile; in Edit mode you can also **create**, **clone**, and **delete** profiles.
---
## Zones
- **Select a zone**: click its button in the top bar. The main area shows that zone’s preset strip and controls.
- **Edit mode — open zone settings**: **right-click** a zone button to change its name, **device IDs** (comma-separated), and which presets appear on the zone. Device identifiers are matched to each device’s **name** when the app builds `select` messages for the driver.
- **Zones modal** (Edit mode): create new zones from the header **Zones** button. New zones need a name and device ID list (defaults to `1` if you leave a simple placeholder).
- **Brightness slider** (per zone): adjusts **global** brightness sent to devices (`b` in the driver message), with a short debounce so small drags do not flood the link.
---
## Presets on the zone strip
- **Run and Edit mode**: click the **main part** of a preset tile to **select** that preset on all devices assigned to the current zone (same logical action as a `select` in the driver API).
- **Edit mode only**:
- **Edit** beside a tile opens the preset editor for that preset, scoped to the current zone (so you can **Remove from zone** without deleting the preset from the profile).
- **Drag and drop** tiles to reorder them; order is saved for that zone.
![Schematic: zone title, brightness slider, and a row of preset tiles; Edit mode adds an Edit control and drag handles for reordering.](images/help/zone-preset-strip.svg)
*The slider controls global brightness for the zone’s devices. Click the coloured area of a tile to select that preset.*
The **Presets** header button (Edit mode) opens a **profile-wide** list: **Add** new presets, **Edit**, **Send** (push definition over the transport), and **Delete** (removes the preset from the profile entirely).
---
## Preset editor
- **Pattern**: chosen from the dropdown; optional **n1–n8** fields depend on the pattern (see **Pattern-specific parameters** in [API.md](API.md)).
- **Colours**: choosing a value in the colour picker **adds** a swatch when the picker closes. Swatches can be **reordered** by dragging. Changing a swatch with the picker **clears** palette linkage for that slot.
- **From Palette**: inserts a colour **linked** to the current profile’s palette. Linked slots show a **P** badge; if you change that palette entry later, presets using it update.
- **Brightness (0–255)** and **Delay (ms)**: stored on the preset and sent with the compact preset payload.
- **Try**: sends the current form values to devices on the **current zone**, then selects that preset — **without** `save` on the device (good for auditioning).
- **Default**: updates the zone’s **default preset** and sends a **default** hint for those devices; it does not force the same live selection behaviour as clicking a tile.
- **Save & Send**: writes the preset to the server, then pushes definitions with **save** so devices may persist them. It does **not** auto-select the preset on devices (use the strip or **Try** if you want that).
- **Remove from zone** (when you opened the editor from a zone): removes the preset from **this zone’s list only**; the preset remains in the profile for other zones.
![Schematic: preset editor with name, pattern, colour swatches (one with a P badge for palette-linked), and action buttons.](images/help/preset-editor.svg)
*Try previews without persisting on the device; **Save & Send** stores the preset and pushes definitions with save.*
---
## Profiles
- **Apply**: sets the **current profile** in your session. Zones and presets you see are scoped to that profile.
- **Edit mode — Create**: new profiles always get a populated **default** zone. Optionally tick **DJ zone** to also create a `dj` zone (device name `dj`) with starter DJ-oriented presets.
- **Clone** / **Delete**: available in Edit mode from the profile list.
---
## Send Presets (Edit mode)
**Send Presets** walks **every zone** in the **current profile**, collects each zone’s preset IDs, and calls **`POST /presets/send`** per zone (including each zone’s **default** preset when set). Use this to bulk-push definitions to hardware after editing, without clicking **Send** on every preset individually.
---
## Patterns
The **Patterns** dialog (Edit mode) lists pattern names and typical **delay** ranges from the pattern definitions. Choosing a pattern still happens inside the preset editor.
**Wi-Fi drivers** can install new pattern modules over HTTP: the REST API exposes **`/patterns/ota/*`**, **`POST /patterns/<name>/send`**, **`POST /patterns/upload`**, and **`POST /patterns/driver`** (see [API.md](API.md)). ESP-NOW devices follow the bridge/serial path you configure for preset traffic.
---
## Colour palette
**Colour Palette** (Edit mode) edits the **current profile’s** palette swatches. Those colours are reused by **From Palette** in the preset editor and stay in sync while the **P** link remains.
![Schematic: palette modal with a row of swatches for the current profile.](images/help/colour-palette.svg)
*Add or change swatches here; linked preset colours update automatically.*
---
## Mobile layout
On narrow screens, use **Menu** to reach the same actions as the desktop header (Profiles, Zones, Presets, Help, mode toggle, etc.).
![Schematic: narrow layout with Menu and the same header actions in a dropdown.](images/help/mobile-menu.svg)
*Preset tiles behave the same once a zone is selected.*
---
## Further reading
- **[API.md](API.md)** — REST routes, session scoping, WebSocket `/ws`, and LED driver JSON (`presets`, `select`, `save`, `default`, pattern keys, pattern **manifest**).
- **README** — `pipenv run run`, port 80 setup, and high-level behaviour.
BIN
View File
Binary file not shown.
+14
View File
@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 480 140" width="480" height="140">
<title>Colour Palette modal (concept)</title>
<rect width="480" height="140" fill="#2a2a2a" stroke="#555" stroke-width="1" rx="6"/>
<text x="20" y="28" fill="#fff" font-family="sans-serif" font-size="15" font-weight="600">Colour Palette</text>
<text x="20" y="48" fill="#888" font-family="sans-serif" font-size="10">Profile: current profile name</text>
<rect x="20" y="58" width="44" height="44" rx="4" fill="#e53935" stroke="#333"/>
<rect x="72" y="58" width="44" height="44" rx="4" fill="#fdd835" stroke="#333"/>
<rect x="124" y="58" width="44" height="44" rx="4" fill="#43a047" stroke="#333"/>
<rect x="176" y="58" width="44" height="44" rx="4" fill="#1e88e5" stroke="#333"/>
<rect x="228" y="58" width="44" height="44" rx="4" fill="#8e24aa" stroke="#333"/>
<rect x="280" y="70" width="36" height="28" rx="3" fill="#1a1a1a" stroke="#666"/>
<text x="288" y="88" fill="#ccc" font-family="sans-serif" font-size="10">+</text>
<text x="20" y="122" fill="#aaa" font-family="sans-serif" font-size="10">Swatches belong to the profile; preset editor uses them via From Palette.</text>
</svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

+24
View File
@@ -0,0 +1,24 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 820 108" width="820" height="108">
<title>Header: tab buttons and action bar</title>
<rect width="820" height="108" fill="#1a1a1a"/>
<rect x="0" y="106" width="820" height="2" fill="#4a4a4a"/>
<text x="16" y="28" fill="#888" font-family="sans-serif" font-size="11">Tabs</text>
<rect x="16" y="40" width="72" height="36" rx="4" fill="#333" stroke="#666" stroke-width="1"/>
<text x="34" y="63" fill="#ccc" font-family="sans-serif" font-size="13">default</text>
<rect x="96" y="40" width="88" height="36" rx="4" fill="#2a4a7a" stroke="#5a8fd4" stroke-width="2"/>
<text x="108" y="63" fill="#fff" font-family="sans-serif" font-size="13">lounge</text>
<rect x="192" y="40" width="56" height="36" rx="4" fill="#333" stroke="#666" stroke-width="1"/>
<text x="204" y="63" fill="#ccc" font-family="sans-serif" font-size="13">dj</text>
<text x="380" y="28" fill="#888" font-family="sans-serif" font-size="11">Actions (Edit mode)</text>
<rect x="380" y="40" width="72" height="30" rx="3" fill="#3d3d3d" stroke="#555" stroke-width="1"/>
<text x="396" y="59" fill="#e0e0e0" font-family="sans-serif" font-size="11">Profiles</text>
<rect x="458" y="40" width="52" height="30" rx="3" fill="#3d3d3d" stroke="#555" stroke-width="1"/>
<text x="470" y="59" fill="#e0e0e0" font-family="sans-serif" font-size="11">Tabs</text>
<rect x="516" y="40" width="64" height="30" rx="3" fill="#3d3d3d" stroke="#555" stroke-width="1"/>
<text x="524" y="59" fill="#e0e0e0" font-family="sans-serif" font-size="11">Presets</text>
<rect x="586" y="40" width="78" height="30" rx="3" fill="#3d3d3d" stroke="#555" stroke-width="1"/>
<text x="598" y="59" fill="#e0e0e0" font-family="sans-serif" font-size="11">Patterns</text>
<rect x="670" y="40" width="134" height="30" rx="3" fill="#4a4a6a" stroke="#7a7aaf" stroke-width="1"/>
<text x="688" y="59" fill="#e0e0e0" font-family="sans-serif" font-size="11">Run mode</text>
<text x="16" y="98" fill="#aaa" font-family="sans-serif" font-size="10">Active tab highlighted. Mode button shows the mode you switch to next.</text>
</svg>

After

Width:  |  Height:  |  Size: 2.1 KiB

+26
View File
@@ -0,0 +1,26 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 340" width="300" height="340" role="img" aria-labelledby="t">
<title id="t">Narrow screen: Menu aggregates header actions</title>
<rect width="300" height="340" fill="#2e2e2e"/>
<rect x="0" y="0" width="300" height="52" fill="#1a1a1a"/>
<rect x="12" y="12" width="56" height="28" rx="4" fill="#3d3d3d" stroke="#555" stroke-width="1"/>
<text x="22" y="30" fill="#eee" font-family="DejaVu Sans, Liberation Sans, Arial, sans-serif" font-size="12">Menu �</text>
<rect x="76" y="14" width="52" height="24" rx="4" fill="#333" stroke="#666" stroke-width="1"/>
<text x="86" y="30" fill="#ccc" font-family="DejaVu Sans, Liberation Sans, Arial, sans-serif" font-size="11">tab</text>
<rect x="136" y="14" width="52" height="24" rx="4" fill="#2a4a7a" stroke="#5a8fd4" stroke-width="1"/>
<text x="142" y="30" fill="#fff" font-family="DejaVu Sans, Liberation Sans, Arial, sans-serif" font-size="11">tab</text>
<rect x="12" y="60" width="276" height="168" rx="4" fill="#252525" stroke="#4a4a4a" stroke-width="1"/>
<text x="24" y="84" fill="#888" font-family="DejaVu Sans, Liberation Sans, Arial, sans-serif" font-size="10">Dropdown (same actions as desktop header)</text>
<g font-family="DejaVu Sans, Liberation Sans, Arial, sans-serif" font-size="12" fill="#e8e8e8">
<text x="24" y="108">Run mode</text>
<text x="24" y="132">Profiles</text>
<text x="24" y="156">Tabs</text>
<text x="24" y="180">Presets</text>
<text x="24" y="204">Help</text>
</g>
<rect x="12" y="240" width="276" height="80" rx="6" fill="#222" stroke="#444" stroke-width="1"/>
<text x="24" y="268" fill="#aaa" font-family="DejaVu Sans, Liberation Sans, Arial, sans-serif" font-size="10">Content area  presets as on desktop</text>
<rect x="24" y="278" width="80" height="32" rx="4" fill="#333" stroke="#555"/>
<text x="36" y="298" fill="#ddd" font-family="DejaVu Sans, Liberation Sans, Arial, sans-serif" font-size="11">preset</text>
<rect x="112" y="278" width="80" height="32" rx="4" fill="#333" stroke="#555"/>
<text x="124" y="298" fill="#ddd" font-family="DejaVu Sans, Liberation Sans, Arial, sans-serif" font-size="11">preset</text>
</svg>

After

Width:  |  Height:  |  Size: 2.2 KiB

+31
View File
@@ -0,0 +1,31 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 520 400" width="520" height="400">
<title>Preset editor modal (simplified)</title>
<rect width="520" height="400" fill="#1e1e1e"/>
<rect x="40" y="28" width="440" height="344" rx="8" fill="#2a2a2a" stroke="#555" stroke-width="1"/>
<text x="60" y="58" fill="#fff" font-family="DejaVu Sans,Liberation Sans,Arial,sans-serif" font-size="17" font-weight="600">Preset</text>
<text x="60" y="86" fill="#aaa" font-family="DejaVu Sans,Liberation Sans,Arial,sans-serif" font-size="11">Name</text>
<rect x="60" y="92" width="200" height="28" rx="3" fill="#1a1a1a" stroke="#444" stroke-width="1"/>
<text x="72" y="111" fill="#ddd" font-family="DejaVu Sans,Liberation Sans,Arial,sans-serif" font-size="12">evening glow</text>
<text x="280" y="86" fill="#aaa" font-family="DejaVu Sans,Liberation Sans,Arial,sans-serif" font-size="11">Pattern</text>
<rect x="280" y="92" width="160" height="28" rx="3" fill="#1a1a1a" stroke="#444" stroke-width="1"/>
<text x="292" y="111" fill="#ddd" font-family="DejaVu Sans,Liberation Sans,Arial,sans-serif" font-size="12">pulse</text>
<text x="60" y="148" fill="#aaa" font-family="DejaVu Sans,Liberation Sans,Arial,sans-serif" font-size="11">Colours</text>
<rect x="60" y="156" width="48" height="48" rx="4" fill="#7e57c2" stroke="#333" stroke-width="1"/>
<circle cx="66" cy="162" r="8" fill="#3f51b5" stroke="#fff" stroke-width="1"/>
<text x="63" y="166" fill="#fff" font-family="DejaVu Sans,Liberation Sans,Arial,sans-serif" font-size="7" font-weight="700">P</text>
<rect x="116" y="156" width="48" height="48" rx="4" fill="#26a69a" stroke="#333" stroke-width="1"/>
<text x="176" y="184" fill="#888" font-family="DejaVu Sans,Liberation Sans,Arial,sans-serif" font-size="10">P = palette-linked</text>
<text x="60" y="232" fill="#aaa" font-family="DejaVu Sans,Liberation Sans,Arial,sans-serif" font-size="11">Brightness, delay, n1-n8</text>
<rect x="60" y="238" width="120" height="24" rx="3" fill="#1a1a1a" stroke="#444" stroke-width="1"/>
<text x="68" y="254" fill="#888" font-family="DejaVu Sans,Liberation Sans,Arial,sans-serif" font-size="11">0-255</text>
<text x="60" y="290" fill="#aaa" font-family="DejaVu Sans,Liberation Sans,Arial,sans-serif" font-size="10">Actions</text>
<rect x="60" y="298" width="44" height="26" rx="3" fill="#444" stroke="#666" stroke-width="1"/>
<text x="72" y="315" fill="#eee" font-family="DejaVu Sans,Liberation Sans,Arial,sans-serif" font-size="11">Try</text>
<rect x="112" y="298" width="56" height="26" rx="3" fill="#444" stroke="#666" stroke-width="1"/>
<text x="120" y="315" fill="#eee" font-family="DejaVu Sans,Liberation Sans,Arial,sans-serif" font-size="11">Default</text>
<rect x="176" y="298" width="88" height="26" rx="3" fill="#3d5a80" stroke="#5a7ab8" stroke-width="1"/>
<text x="188" y="315" fill="#fff" font-family="DejaVu Sans,Liberation Sans,Arial,sans-serif" font-size="11">Save+Send</text>
<rect x="272" y="298" width="48" height="26" rx="3" fill="#444" stroke="#666" stroke-width="1"/>
<text x="284" y="315" fill="#eee" font-family="DejaVu Sans,Liberation Sans,Arial,sans-serif" font-size="11">Close</text>
<text x="60" y="352" fill="#888" font-family="DejaVu Sans,Liberation Sans,Arial,sans-serif" font-size="9">Try: preview without device save. Save+Send: store and push with save.</text>
</svg>

After

Width:  |  Height:  |  Size: 3.3 KiB

+35
View File
@@ -0,0 +1,35 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 220" width="800" height="220">
<title>Main area: brightness and preset tiles</title>
<defs>
<linearGradient id="rg1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:#ffd54f"/><stop offset="100%" style="stop-color:#fff8e1"/>
</linearGradient>
<linearGradient id="rg2" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:#e53935"/><stop offset="33%" style="stop-color:#fdd835"/>
<stop offset="66%" style="stop-color:#43a047"/><stop offset="100%" style="stop-color:#1e88e5"/>
</linearGradient>
<linearGradient id="rg3" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:#00897b"/><stop offset="100%" style="stop-color:#4db6ac"/>
</linearGradient>
</defs>
<rect width="800" height="220" fill="#2e2e2e"/>
<text x="20" y="32" fill="#fff" font-family="sans-serif" font-size="16" font-weight="600">lounge</text>
<text x="20" y="56" fill="#aaa" font-family="sans-serif" font-size="11">Brightness (global)</text>
<rect x="20" y="64" width="320" height="8" rx="4" fill="#444"/>
<rect x="20" y="64" width="200" height="8" rx="4" fill="#6a9ee2"/>
<circle cx="220" cy="68" r="10" fill="#ccc" stroke="#333" stroke-width="1"/>
<text x="360" y="74" fill="#888" font-family="sans-serif" font-size="11">drag to adjust</text>
<text x="20" y="108" fill="#aaa" font-family="sans-serif" font-size="11">Click tile body to select on tab devices</text>
<rect x="20" y="118" width="200" height="72" rx="6" fill="#252525" stroke="#555" stroke-width="1"/>
<rect x="28" y="128" width="184" height="36" rx="4" fill="url(#rg1)"/>
<text x="32" y="180" fill="#eee" font-family="sans-serif" font-size="13" font-weight="600">warm white</text>
<rect x="232" y="118" width="200" height="72" rx="6" fill="#252525" stroke="#6a9ee2" stroke-width="2"/>
<rect x="240" y="128" width="184" height="36" rx="4" fill="url(#rg2)"/>
<text x="244" y="180" fill="#eee" font-family="sans-serif" font-size="13" font-weight="600">rainbow</text>
<rect x="444" y="118" width="200" height="72" rx="6" fill="#252525" stroke="#555" stroke-width="1"/>
<rect x="452" y="128" width="184" height="36" rx="4" fill="url(#rg3)"/>
<text x="456" y="180" fill="#eee" font-family="sans-serif" font-size="13" font-weight="600">chase</text>
<rect x="656" y="130" width="56" height="48" rx="4" fill="#3d3d3d" stroke="#555" stroke-width="1"/>
<text x="670" y="158" fill="#ddd" font-family="sans-serif" font-size="11">Edit</text>
<text x="656" y="198" fill="#888" font-family="sans-serif" font-size="10">Edit mode: drag tiles to reorder</text>
</svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

+239
View File
@@ -0,0 +1,239 @@
# Custom Colour Picker Component
A cross-platform, cross-browser colour picker component that provides a consistent user experience across all operating systems and browsers.
## Features
✅ **Consistent UI** - Same appearance and behavior on Windows, macOS, Linux, iOS, and Android
✅ **Browser Support** - Works in Chrome, Firefox, Safari, Edge, Opera, and mobile browsers
✅ **Touch Support** - Full touch/gesture support for mobile devices
✅ **HSB Colour Model** - Uses Hue, Saturation, Brightness for intuitive colour selection
✅ **Multiple Input Methods** - Hex input, RGB inputs, and visual picker
✅ **Accessible** - Keyboard accessible and screen reader friendly
✅ **Customizable** - Easy to style and integrate
## Files
- `color-picker.js` - Main JavaScript component (14KB)
- `color-picker.css` - Stylesheet (4KB)
- `color-picker-demo.html` - Demo page showing usage examples
## Quick Start
### 1. Include the files
```html
<link rel="stylesheet" href="color-picker.css">
<script src="color-picker.js"></script>
```
### 2. Create a container element
```html
<div id="my-color-picker"></div>
```
### 3. Initialize the colour picker
```javascript
const picker = new ColorPicker('#my-color-picker', {
initialColor: '#FF0000',
onColorChange: (color) => {
console.log('Color changed to:', color);
}
});
```
## API
### Constructor
```javascript
new ColorPicker(container, options)
```
**Parameters:**
- `container` (string|HTMLElement) - CSS selector or DOM element
- `options` (object) - Configuration options
**Options:**
- `initialColor` (string) - Initial colour in hex format (default: '#FF0000')
- `onColorChange` (function) - Callback when colour changes (receives hex colour string)
- `showHexInput` (boolean) - Show hex input field (default: true)
### Methods
```javascript
// Get current color
const color = picker.getColor(); // Returns hex string like '#FF0000'
// Set color programmatically
picker.setColor('#00FF00');
// Open the picker panel
picker.open();
// Close the picker panel
picker.close();
// Toggle the picker panel
picker.toggle();
```
## Usage Examples
### Basic Usage
```javascript
const picker = new ColorPicker('#picker1', {
initialColor: '#FF0000'
});
```
### With Callback
```javascript
const picker = new ColorPicker('#picker1', {
initialColor: '#FF0000',
onColorChange: (color) => {
document.body.style.backgroundColor = color;
}
});
```
### Multiple Colour Pickers
```javascript
const colors = ['#FF0000', '#00FF00', '#0000FF'];
const pickers = colors.map((color, index) => {
return new ColorPicker(`#picker-${index}`, {
initialColor: color,
onColorChange: (newColor) => {
colors[index] = newColor;
updateLEDColors(colors);
}
});
});
```
### Dynamic Colour Picker Creation
```javascript
function addColorPicker(containerId, initialColor = '#000000') {
const container = document.createElement('div');
container.id = containerId;
document.getElementById('color-list').appendChild(container);
return new ColorPicker(container, {
initialColor: initialColor,
onColorChange: (color) => {
console.log(`Color ${containerId} changed to ${color}`);
}
});
}
// Add multiple pickers
addColorPicker('color-1', '#FF0000');
addColorPicker('color-2', '#00FF00');
```
## Styling
The colour picker uses CSS classes that can be customized:
- `.color-picker-container` - Main container
- `.color-picker-preview` - Colour preview button
- `.color-picker-panel` - Dropdown panel
- `.color-picker-main` - Main colour area
- `.color-picker-hue` - Hue slider
- `.color-picker-controls` - Controls section
### Custom Styling Example
```css
.color-picker-preview {
width: 80px;
height: 80px;
border-radius: 12px;
}
.color-picker-panel {
background: #2d3748;
border-color: #4a5568;
}
```
## Browser Compatibility
| Browser | Version | Status |
|---------|---------|--------|
| Chrome | 60+ | ✅ Full support |
| Firefox | 55+ | ✅ Full support |
| Safari | 12+ | ✅ Full support |
| Edge | 79+ | ✅ Full support |
| Opera | 47+ | ✅ Full support |
| Mobile Safari | iOS 12+ | ✅ Full support |
| Chrome Mobile | Android 7+ | ✅ Full support |
## Operating System Compatibility
- ✅ Windows 10/11
- ✅ macOS 10.14+
- ✅ Linux (all major distributions)
- ✅ iOS 12+
- ✅ Android 7+
## Colour Format
The colour picker uses **hex colour format** (`#RRGGBB`):
- Always returns uppercase hex strings (e.g., `#FF0000`)
- Accepts both uppercase and lowercase input
- Automatically validates hex format
## Integration with LED Driver Mockups
The colour picker is integrated into:
- `dashboard.html` - Colour selection for patterns
- `presets.html` - Colour selection when creating/editing presets
### Example: Getting Colours from Multiple Pickers
```javascript
const colorPickers = [];
function getSelectedColors() {
return colorPickers.map(picker => picker.getColor());
}
function sendColorsToDevice() {
const colors = getSelectedColors();
// Send to LED device via API
fetch('/api/colors', {
method: 'POST',
body: JSON.stringify({ colors: colors })
});
}
```
## Performance
- Lightweight: ~14KB JavaScript, ~4KB CSS
- Fast rendering: Uses Canvas API for colour gradients
- Smooth interactions: Optimized event handling
- Memory efficient: No external dependencies
## Accessibility
- Keyboard navigation support
- ARIA labels on interactive elements
- High contrast cursor indicators
- Screen reader compatible
## License
Part of the LED Driver project. Use freely in your projects.
## Demo
See `color-picker-demo.html` for a live demonstration of the colour picker component.
+56
View File
@@ -0,0 +1,56 @@
# UI Mockups
This directory contains HTML mockups and generated images for the LED Driver user interface.
## Files
### HTML Mockups
- **index.html** - Navigation page linking to all mockups
- **dashboard.html** - Main control panel for managing LED patterns and devices
- **pattern-selector.html** - Visual pattern selection interface
- **device-management.html** - Device and group management interface
- **settings.html** - Comprehensive settings configuration panel
### Generated Images
Images are automatically generated in the `images/` directory:
- `dashboard.png`
- `pattern-selector.png`
- `device-management.png`
- `settings.png`
- `index.png`
## Generating Images
To generate images from the HTML files, use the provided script:
```bash
# Install dependencies (if not already installed)
pipenv install playwright
pipenv run playwright install chromium
# Generate images
pipenv run python generate_images.py
```
The script will:
1. Check for available screenshot libraries (Playwright, Selenium, or html2image)
2. Generate PNG images from all HTML files
3. Save images to the `images/` directory
### Requirements
The script supports multiple screenshot libraries (in order of preference):
1. **Playwright** (recommended) - `pip install playwright && playwright install chromium`
2. **Selenium** - `pip install selenium` (requires ChromeDriver)
3. **html2image** - `pip install html2image`
## Viewing Mockups
Simply open any HTML file in a web browser to view the mockup. Start with `index.html` for navigation to all mockups.
## Notes
- All mockups are responsive and work on desktop and mobile devices
- The mockups use modern CSS with gradients and smooth animations
- Interactive elements (buttons, sliders, etc.) are functional in the HTML but are mockups (no backend connection)
@@ -0,0 +1,210 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chromium Color Picker Demo</title>
<link rel="stylesheet" href="color-picker-chromium.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&family=Roboto+Mono&display=swap" rel="stylesheet">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Roboto', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 40px 20px;
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
border-radius: 12px;
padding: 40px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
}
h1 {
color: #202124;
margin-bottom: 8px;
font-weight: 400;
font-size: 24px;
}
p {
color: #5f6368;
margin-bottom: 32px;
font-size: 14px;
}
.demo-section {
margin-bottom: 40px;
padding: 24px;
background: #f8f9fa;
border-radius: 8px;
border: 1px solid #e8eaed;
}
.demo-section h2 {
color: #202124;
margin-bottom: 16px;
font-size: 16px;
font-weight: 500;
}
.color-pickers {
display: flex;
gap: 24px;
flex-wrap: wrap;
margin-bottom: 16px;
}
.color-display {
margin-top: 16px;
padding: 12px;
background: white;
border-radius: 6px;
font-family: 'Roboto Mono', 'Courier New', monospace;
font-size: 13px;
border: 1px solid #e8eaed;
}
.color-display strong {
color: #4285f4;
}
.comparison {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 24px;
margin-top: 24px;
}
.comparison-item {
padding: 16px;
background: white;
border-radius: 6px;
border: 1px solid #e8eaed;
}
.comparison-item h3 {
font-size: 14px;
font-weight: 500;
color: #202124;
margin-bottom: 12px;
}
</style>
</head>
<body>
<div class="container">
<h1>Chromium-style Color Picker</h1>
<p>Color picker that matches the native Chromium browser color picker design</p>
<div class="demo-section">
<h2>Single Color Picker</h2>
<div class="color-pickers">
<div id="picker1"></div>
</div>
<div class="color-display">
Selected color: <strong id="color1-display">#FF0000</strong>
</div>
</div>
<div class="demo-section">
<h2>Multiple Color Pickers</h2>
<p style="margin-bottom: 16px; color: #5f6368; font-size: 14px;">Example: Multiple colors for LED patterns</p>
<div class="color-pickers">
<div id="picker2"></div>
<div id="picker3"></div>
<div id="picker4"></div>
</div>
<div class="color-display">
Colors: <strong id="colors-display">#FF0000, #00FF00, #0000FF</strong>
</div>
</div>
<div class="demo-section">
<h2>Features</h2>
<ul style="color: #5f6368; line-height: 1.8; font-size: 14px;">
<li>✅ Matches native Chromium browser color picker design</li>
<li>✅ Clean, minimal interface with native system fonts</li>
<li>✅ RGB number inputs (no sliders) - Chromium style</li>
<li>✅ Hex input with uppercase formatting</li>
<li>✅ HSB (Hue, Saturation, Brightness) color model</li>
<li>✅ Touch support for mobile devices</li>
<li>✅ Keyboard accessible</li>
<li>✅ Dark mode support</li>
</ul>
</div>
<div class="demo-section">
<h2>Design Notes</h2>
<div class="comparison">
<div class="comparison-item">
<h3>Chromium Style</h3>
<ul style="color: #5f6368; line-height: 1.8; font-size: 13px; list-style: none; padding-left: 0;">
<li>• RGB number inputs only</li>
<li>• Compact preview button</li>
<li>• Native system fonts</li>
<li>• Minimal borders and shadows</li>
<li>• Chromium color scheme</li>
</ul>
</div>
<div class="comparison-item">
<h3>Standard Style</h3>
<ul style="color: #5f6368; line-height: 1.8; font-size: 13px; list-style: none; padding-left: 0;">
<li>• RGB sliders + inputs</li>
<li>• Larger preview button</li>
<li>• Custom styling</li>
<li>• Enhanced shadows</li>
<li>• Custom color scheme</li>
</ul>
</div>
</div>
</div>
</div>
<script src="color-picker-chromium.js"></script>
<script>
// Initialize Chromium-style color pickers
const picker1 = new ColorPickerChromium('#picker1', {
initialColor: '#FF0000',
onColorChange: (color) => {
document.getElementById('color1-display').textContent = color;
}
});
const picker2 = new ColorPickerChromium('#picker2', {
initialColor: '#FF0000',
onColorChange: updateColors
});
const picker3 = new ColorPickerChromium('#picker3', {
initialColor: '#00FF00',
onColorChange: updateColors
});
const picker4 = new ColorPickerChromium('#picker4', {
initialColor: '#0000FF',
onColorChange: updateColors
});
function updateColors() {
const colors = [
picker2.getColor(),
picker3.getColor(),
picker4.getColor()
];
document.getElementById('colors-display').textContent = colors.join(', ');
}
</script>
</body>
</html>
+253
View File
@@ -0,0 +1,253 @@
/* Chromium-style Color Picker - Matches native browser color picker dialog */
.color-picker-container {
position: relative;
display: inline-block;
}
/* Preview button - opens the picker */
.color-picker-preview {
width: 40px;
height: 32px;
border: 1px solid #d0d0d0;
border-radius: 4px;
cursor: pointer;
padding: 0;
background: none;
transition: border-color 0.15s;
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
}
.color-picker-preview:hover {
border-color: #8ab4f8;
}
.color-picker-preview:active {
border-color: #4285f4;
}
/* Main picker panel - always visible when open, styled like Chromium dialog */
.color-picker-panel {
position: absolute;
top: calc(100% + 4px);
left: 0;
z-index: 1000;
background: #ffffff;
border: 1px solid #dadce0;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15), 0 4px 16px rgba(0, 0, 0, 0.1);
padding: 16px;
min-width: 260px;
font-family: 'Roboto', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
font-size: 13px;
}
/* Color area - main saturation/brightness square + hue slider */
.color-picker-area {
display: flex;
gap: 12px;
margin-bottom: 16px;
}
/* Main color square - saturation (left-right) and brightness (top-bottom) */
.color-picker-main {
position: relative;
width: 200px;
height: 200px;
border: 1px solid #dadce0;
border-radius: 4px;
overflow: hidden;
cursor: crosshair;
touch-action: none;
background: #ffffff;
flex-shrink: 0;
}
.color-picker-canvas {
display: block;
width: 100%;
height: 100%;
user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
/* Cursor for main color area */
.color-picker-cursor {
position: absolute;
width: 18px;
height: 18px;
border: 2px solid #ffffff;
border-radius: 50%;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2), 0 2px 4px rgba(0, 0, 0, 0.1);
pointer-events: none;
transform: translate(-50%, -50%);
top: 0;
left: 0;
}
/* Hue slider - vertical strip on the right */
.color-picker-hue {
position: relative;
width: 24px;
height: 200px;
border: 1px solid #dadce0;
border-radius: 4px;
overflow: hidden;
cursor: pointer;
touch-action: none;
background: #ffffff;
flex-shrink: 0;
}
/* Hue slider cursor/indicator */
.color-picker-hue-cursor {
position: absolute;
left: 0;
right: 0;
width: 100%;
height: 6px;
border: 2px solid #ffffff;
border-radius: 2px;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2), 0 1px 2px rgba(0, 0, 0, 0.1);
pointer-events: none;
transform: translateY(-50%);
top: 0;
}
/* Controls section - hex and RGB inputs */
.color-picker-controls {
display: flex;
flex-direction: column;
gap: 12px;
}
/* Hex input field */
.color-picker-hex {
width: 100%;
padding: 7px 10px;
border: 1px solid #dadce0;
border-radius: 4px;
font-family: 'Roboto Mono', 'Courier New', monospace;
font-size: 13px;
text-transform: uppercase;
transition: border-color 0.15s, box-shadow 0.15s;
background: #ffffff;
}
.color-picker-hex:focus {
outline: none;
border-color: #4285f4;
box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.2);
}
/* RGB inputs container */
.color-picker-rgb {
display: flex;
gap: 12px;
align-items: flex-end;
}
.color-picker-rgb-item {
flex: 1;
display: flex;
flex-direction: column;
gap: 6px;
}
.color-picker-rgb-item label {
font-size: 11px;
font-weight: 500;
color: #5f6368;
text-align: left;
text-transform: uppercase;
letter-spacing: 0.5px;
}
/* RGB number input fields */
.color-picker-rgb-input {
width: 100%;
padding: 7px 10px;
border: 1px solid #dadce0;
border-radius: 4px;
font-size: 13px;
text-align: left;
transition: border-color 0.15s, box-shadow 0.15s;
background: #ffffff;
font-family: 'Roboto', sans-serif;
-moz-appearance: textfield;
}
.color-picker-rgb-input::-webkit-outer-spin-button,
.color-picker-rgb-input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
.color-picker-rgb-input:focus {
outline: none;
border-color: #4285f4;
box-shadow: 0 0 0 2px rgba(66, 133, 244, 0.2);
}
/* Hide RGB sliders - Chromium uses only number inputs */
.color-picker-rgb-slider {
display: none;
}
/* Responsive adjustments */
@media (max-width: 480px) {
.color-picker-panel {
left: auto;
right: 0;
}
.color-picker-main {
width: 180px;
height: 180px;
}
.color-picker-hue {
height: 180px;
}
}
/* Dark mode support */
@media (prefers-color-scheme: dark) {
.color-picker-panel {
background: #202124;
border-color: #5f6368;
}
.color-picker-preview {
border-color: #5f6368;
}
.color-picker-main,
.color-picker-hue {
border-color: #5f6368;
background: #202124;
}
.color-picker-hex,
.color-picker-rgb-input {
background: #303134;
border-color: #5f6368;
color: #e8eaed;
}
.color-picker-rgb-item label {
color: #9aa0a6;
}
.color-picker-hex:focus,
.color-picker-rgb-input:focus {
border-color: #8ab4f8;
box-shadow: 0 0 0 2px rgba(138, 180, 248, 0.2);
}
.color-picker-preview:hover {
border-color: #8ab4f8;
}
}
+452
View File
@@ -0,0 +1,452 @@
/**
* Chromium-style Color Picker Component
* Matches native Chromium browser color picker design
*/
class ColorPickerChromium {
constructor(container, options = {}) {
this.container = typeof container === 'string' ? document.querySelector(container) : container;
this.options = {
initialColor: options.initialColor || '#FF0000',
onColorChange: options.onColorChange || null,
showHexInput: options.showHexInput !== false,
...options
};
this.currentColor = this.options.initialColor;
this.isOpen = false;
this.init();
}
init() {
this.createPicker();
this.setupEventListeners();
this.updateColor(this.options.initialColor);
}
createPicker() {
this.container.innerHTML = '';
this.container.className = 'color-picker-container';
// Color preview button
this.previewBtn = document.createElement('button');
this.previewBtn.className = 'color-picker-preview';
this.previewBtn.type = 'button';
this.previewBtn.style.backgroundColor = this.currentColor;
this.previewBtn.setAttribute('aria-label', 'Open color picker');
// Dropdown panel
this.panel = document.createElement('div');
this.panel.className = 'color-picker-panel';
this.panel.style.display = 'none';
// Main color area (hue/saturation)
this.mainArea = document.createElement('div');
this.mainArea.className = 'color-picker-main';
this.mainCanvas = document.createElement('canvas');
this.mainCanvas.width = 200;
this.mainCanvas.height = 200;
this.mainCanvas.className = 'color-picker-canvas';
this.mainArea.appendChild(this.mainCanvas);
// Main area cursor
this.mainCursor = document.createElement('div');
this.mainCursor.className = 'color-picker-cursor';
this.mainArea.appendChild(this.mainCursor);
// Hue slider
this.hueArea = document.createElement('div');
this.hueArea.className = 'color-picker-hue';
this.hueCanvas = document.createElement('canvas');
this.hueCanvas.width = 24;
this.hueCanvas.height = 200;
this.hueCanvas.className = 'color-picker-canvas';
this.hueArea.appendChild(this.hueCanvas);
// Hue slider cursor
this.hueCursor = document.createElement('div');
this.hueCursor.className = 'color-picker-hue-cursor';
this.hueArea.appendChild(this.hueCursor);
// Controls section
this.controls = document.createElement('div');
this.controls.className = 'color-picker-controls';
// Hex input
if (this.options.showHexInput) {
this.hexInput = document.createElement('input');
this.hexInput.type = 'text';
this.hexInput.className = 'color-picker-hex';
this.hexInput.placeholder = '#000000';
this.hexInput.maxLength = 7;
this.controls.appendChild(this.hexInput);
}
// RGB inputs (Chromium style - no sliders, just number inputs)
this.rgbContainer = document.createElement('div');
this.rgbContainer.className = 'color-picker-rgb';
['R', 'G', 'B'].forEach((label) => {
const wrapper = document.createElement('div');
wrapper.className = 'color-picker-rgb-item';
wrapper.dataset.channel = label.toLowerCase();
const labelEl = document.createElement('label');
labelEl.textContent = label;
const input = document.createElement('input');
input.type = 'number';
input.className = 'color-picker-rgb-input';
input.min = 0;
input.max = 255;
input.value = 0;
input.dataset.channel = label.toLowerCase();
wrapper.appendChild(labelEl);
wrapper.appendChild(input);
this.rgbContainer.appendChild(wrapper);
this[`rgb${label}`] = input;
});
this.controls.appendChild(this.rgbContainer);
// Assemble panel
const pickerArea = document.createElement('div');
pickerArea.className = 'color-picker-area';
pickerArea.appendChild(this.mainArea);
pickerArea.appendChild(this.hueArea);
this.panel.appendChild(pickerArea);
this.panel.appendChild(this.controls);
// Assemble container
this.container.appendChild(this.previewBtn);
this.container.appendChild(this.panel);
// Draw canvases
this.drawHueCanvas();
this.drawMainCanvas(1.0); // Start with full saturation
}
setupEventListeners() {
// Toggle panel
this.previewBtn.addEventListener('click', (e) => {
e.stopPropagation();
this.toggle();
});
// Close on outside click
document.addEventListener('click', (e) => {
if (!this.container.contains(e.target) && this.isOpen) {
this.close();
}
});
// Main area interaction
let isMainDragging = false;
this.mainCanvas.addEventListener('mousedown', (e) => {
isMainDragging = true;
this.handleMainAreaClick(e);
});
this.mainCanvas.addEventListener('mousemove', (e) => {
if (isMainDragging) {
this.handleMainAreaClick(e);
}
});
document.addEventListener('mouseup', () => {
isMainDragging = false;
});
// Touch support for main area
this.mainCanvas.addEventListener('touchstart', (e) => {
e.preventDefault();
isMainDragging = true;
this.handleMainAreaClick(e.touches[0]);
});
this.mainCanvas.addEventListener('touchmove', (e) => {
e.preventDefault();
if (isMainDragging) {
this.handleMainAreaClick(e.touches[0]);
}
});
this.mainCanvas.addEventListener('touchend', () => {
isMainDragging = false;
});
// Hue slider interaction
let isHueDragging = false;
this.hueCanvas.addEventListener('mousedown', (e) => {
isHueDragging = true;
this.handleHueClick(e);
});
this.hueCanvas.addEventListener('mousemove', (e) => {
if (isHueDragging) {
this.handleHueClick(e);
}
});
document.addEventListener('mouseup', () => {
isHueDragging = false;
});
// Touch support for hue slider
this.hueCanvas.addEventListener('touchstart', (e) => {
e.preventDefault();
isHueDragging = true;
this.handleHueClick(e.touches[0]);
});
this.hueCanvas.addEventListener('touchmove', (e) => {
e.preventDefault();
if (isHueDragging) {
this.handleHueClick(e.touches[0]);
}
});
this.hueCanvas.addEventListener('touchend', () => {
isHueDragging = false;
});
// Hex input
if (this.hexInput) {
this.hexInput.addEventListener('input', (e) => {
const value = e.target.value;
if (/^#[0-9A-Fa-f]{6}$/.test(value)) {
this.updateColor(value);
}
});
this.hexInput.addEventListener('blur', (e) => {
const value = e.target.value;
if (!/^#[0-9A-Fa-f]{6}$/.test(value) && value.length > 0) {
e.target.value = this.currentColor;
}
});
}
// RGB inputs (Chromium style - only number inputs)
['R', 'G', 'B'].forEach(label => {
this[`rgb${label}`].addEventListener('input', (e) => {
let value = parseInt(e.target.value) || 0;
value = Math.max(0, Math.min(255, value)); // Clamp to 0-255
e.target.value = value;
const r = parseInt(this.rgbR.value) || 0;
const g = parseInt(this.rgbG.value) || 0;
const b = parseInt(this.rgbB.value) || 0;
const hex = this.rgbToHex(r, g, b);
this.updateColor(hex, false); // Don't update RGB inputs to avoid loop
});
this[`rgb${label}`].addEventListener('blur', (e) => {
let value = parseInt(e.target.value) || 0;
value = Math.max(0, Math.min(255, value));
e.target.value = value;
});
});
}
drawHueCanvas() {
const ctx = this.hueCanvas.getContext('2d');
const gradient = ctx.createLinearGradient(0, 0, 0, 200);
for (let i = 0; i <= 6; i++) {
const hue = i * 60;
gradient.addColorStop(i / 6, `hsl(${hue}, 100%, 50%)`);
}
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 24, 200);
}
drawMainCanvas(hue) {
const ctx = this.mainCanvas.getContext('2d');
// Saturation gradient (left to right)
const satGradient = ctx.createLinearGradient(0, 0, 200, 0);
satGradient.addColorStop(0, `hsl(${hue}, 0%, 50%)`);
satGradient.addColorStop(1, `hsl(${hue}, 100%, 50%)`);
ctx.fillStyle = satGradient;
ctx.fillRect(0, 0, 200, 200);
// Brightness gradient (top to bottom)
const brightGradient = ctx.createLinearGradient(0, 0, 0, 200);
brightGradient.addColorStop(0, 'rgba(255, 255, 255, 0)');
brightGradient.addColorStop(1, 'rgba(0, 0, 0, 1)');
ctx.fillStyle = brightGradient;
ctx.fillRect(0, 0, 200, 200);
}
handleMainAreaClick(e) {
const rect = this.mainCanvas.getBoundingClientRect();
const x = Math.max(0, Math.min(200, e.clientX - rect.left));
const y = Math.max(0, Math.min(200, e.clientY - rect.top));
const saturation = x / 200;
const brightness = 1 - (y / 200);
this.updateColorFromHSB(this.hue, saturation, brightness);
this.updateCursor(x, y);
}
handleHueClick(e) {
const rect = this.hueCanvas.getBoundingClientRect();
const y = Math.max(0, Math.min(200, e.clientY - rect.top));
const hue = (y / 200) * 360;
this.hue = hue;
this.drawMainCanvas(hue);
this.updateHueCursor(y);
// Recalculate color with new hue
const rect2 = this.mainCanvas.getBoundingClientRect();
const x = parseFloat(this.mainCursor.style.left) || 0;
const y2 = parseFloat(this.mainCursor.style.top) || 0;
const saturation = x / 200;
const brightness = 1 - (y2 / 200);
this.updateColorFromHSB(hue, saturation, brightness);
}
updateColorFromHSB(h, s, v) {
const rgb = this.hsbToRgb(h, s, v);
const hex = this.rgbToHex(rgb.r, rgb.g, rgb.b);
this.updateColor(hex);
}
hsbToRgb(h, s, v) {
h = h / 360;
const i = Math.floor(h * 6);
const f = h * 6 - i;
const p = v * (1 - s);
const q = v * (1 - f * s);
const t = v * (1 - (1 - f) * s);
let r, g, b;
switch (i % 6) {
case 0: r = v; g = t; b = p; break;
case 1: r = q; g = v; b = p; break;
case 2: r = p; g = v; b = t; break;
case 3: r = p; g = q; b = v; break;
case 4: r = t; g = p; b = v; break;
case 5: r = v; g = p; b = q; break;
}
return {
r: Math.round(r * 255),
g: Math.round(g * 255),
b: Math.round(b * 255)
};
}
rgbToHex(r, g, b) {
return '#' + [r, g, b].map(x => {
const hex = x.toString(16);
return hex.length === 1 ? '0' + hex : hex;
}).join('').toUpperCase();
}
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)
} : null;
}
rgbToHsb(r, g, b) {
r /= 255;
g /= 255;
b /= 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const diff = max - min;
let h = 0;
if (diff !== 0) {
if (max === r) {
h = ((g - b) / diff) % 6) * 60;
} else if (max === g) {
h = ((b - r) / diff + 2) * 60;
} else {
h = ((r - g) / diff + 4) * 60;
}
}
if (h < 0) h += 360;
const s = max === 0 ? 0 : diff / max;
const v = max;
return { h, s, v };
}
updateColor(hex, updateInputs = true) {
this.currentColor = hex.toUpperCase();
this.previewBtn.style.backgroundColor = this.currentColor;
const rgb = this.hexToRgb(this.currentColor);
if (!rgb) return;
const hsb = this.rgbToHsb(rgb.r, rgb.g, rgb.b);
this.hue = hsb.h;
// Update main canvas
this.drawMainCanvas(this.hue);
// Update cursors
const x = hsb.s * 200;
const y = (1 - hsb.v) * 200;
this.updateCursor(x, y);
this.updateHueCursor((this.hue / 360) * 200);
// Update inputs
if (updateInputs) {
if (this.hexInput) {
this.hexInput.value = this.currentColor;
}
if (this.rgbR) {
this.rgbR.value = rgb.r;
this.rgbG.value = rgb.g;
this.rgbB.value = rgb.b;
}
}
// Callback
if (this.options.onColorChange) {
this.options.onColorChange(this.currentColor);
}
}
updateCursor(x, y) {
this.mainCursor.style.left = `${x}px`;
this.mainCursor.style.top = `${y}px`;
}
updateHueCursor(y) {
this.hueCursor.style.top = `${y}px`;
}
toggle() {
this.isOpen ? this.close() : this.open();
}
open() {
this.panel.style.display = 'block';
this.isOpen = true;
}
close() {
this.panel.style.display = 'none';
this.isOpen = false;
}
getColor() {
return this.currentColor;
}
setColor(color) {
this.updateColor(color);
}
}
// Export for use in other scripts
if (typeof module !== 'undefined' && module.exports) {
module.exports = ColorPickerChromium;
}
+153
View File
@@ -0,0 +1,153 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Color Picker Demo - Cross-Platform</title>
<link rel="stylesheet" href="color-picker.css">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 40px 20px;
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
border-radius: 12px;
padding: 40px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
}
h1 {
color: #667eea;
margin-bottom: 8px;
}
p {
color: #666;
margin-bottom: 32px;
}
.demo-section {
margin-bottom: 40px;
padding: 24px;
background: #f7fafc;
border-radius: 8px;
}
.demo-section h2 {
color: #333;
margin-bottom: 16px;
font-size: 1.25rem;
}
.color-pickers {
display: flex;
gap: 24px;
flex-wrap: wrap;
margin-bottom: 16px;
}
.color-display {
margin-top: 16px;
padding: 12px;
background: white;
border-radius: 6px;
font-family: 'Courier New', monospace;
font-size: 0.875rem;
}
.color-display strong {
color: #667eea;
}
</style>
</head>
<body>
<div class="container">
<h1>Custom Color Picker</h1>
<p>Consistent color picker that works the same across all operating systems and browsers</p>
<div class="demo-section">
<h2>Single Color Picker</h2>
<div class="color-pickers">
<div id="picker1"></div>
</div>
<div class="color-display">
Selected color: <strong id="color1-display">#FF0000</strong>
</div>
</div>
<div class="demo-section">
<h2>Multiple Color Pickers</h2>
<p style="margin-bottom: 16px;">Example: Multiple colors for LED patterns</p>
<div class="color-pickers">
<div id="picker2"></div>
<div id="picker3"></div>
<div id="picker4"></div>
</div>
<div class="color-display">
Colors: <strong id="colors-display">#FF0000, #00FF00, #0000FF</strong>
</div>
</div>
<div class="demo-section">
<h2>Features</h2>
<ul style="color: #666; line-height: 1.8;">
<li>✅ Consistent UI across Windows, macOS, Linux, iOS, Android</li>
<li>✅ Works in Chrome, Firefox, Safari, Edge, Opera</li>
<li>✅ Touch support for mobile devices</li>
<li>✅ HSB (Hue, Saturation, Brightness) color model</li>
<li>✅ Hex and RGB input support</li>
<li>✅ Keyboard accessible</li>
<li>✅ Customizable styling</li>
</ul>
</div>
</div>
<script src="color-picker.js"></script>
<script>
// Initialize color pickers
const picker1 = new ColorPicker('#picker1', {
initialColor: '#FF0000',
onColorChange: (color) => {
document.getElementById('color1-display').textContent = color;
}
});
const picker2 = new ColorPicker('#picker2', {
initialColor: '#FF0000',
onColorChange: updateColors
});
const picker3 = new ColorPicker('#picker3', {
initialColor: '#00FF00',
onColorChange: updateColors
});
const picker4 = new ColorPicker('#picker4', {
initialColor: '#0000FF',
onColorChange: updateColors
});
function updateColors() {
const colors = [
picker2.getColor(),
picker3.getColor(),
picker4.getColor()
];
document.getElementById('colors-display').textContent = colors.join(', ');
}
</script>
</body>
</html>
+282
View File
@@ -0,0 +1,282 @@
/* Color Picker Styles - Consistent across all browsers and OS */
.color-picker-container {
position: relative;
display: inline-block;
}
.color-picker-preview {
width: 60px;
height: 60px;
border: 2px solid #e0e0e0;
border-radius: 8px;
cursor: pointer;
padding: 0;
background: none;
transition: all 0.2s;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.color-picker-preview:hover {
border-color: #667eea;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
transform: translateY(-1px);
}
.color-picker-preview:active {
transform: translateY(0);
}
.color-picker-panel {
position: absolute;
top: calc(100% + 8px);
left: 0;
z-index: 1000;
background: white;
border: 1px solid #e0e0e0;
border-radius: 12px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
padding: 16px;
min-width: 280px;
}
.color-picker-area {
display: flex;
gap: 12px;
margin-bottom: 16px;
}
.color-picker-main {
position: relative;
width: 200px;
height: 200px;
border: 1px solid #e0e0e0;
border-radius: 8px;
overflow: hidden;
cursor: crosshair;
touch-action: none;
}
.color-picker-canvas {
display: block;
width: 100%;
height: 100%;
user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}
.color-picker-cursor {
position: absolute;
width: 16px;
height: 16px;
border: 2px solid white;
border-radius: 50%;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.3);
pointer-events: none;
transform: translate(-50%, -50%);
top: 0;
left: 0;
}
.color-picker-hue {
position: relative;
width: 20px;
height: 200px;
border: 1px solid #e0e0e0;
border-radius: 8px;
overflow: hidden;
cursor: pointer;
touch-action: none;
}
.color-picker-hue-cursor {
position: absolute;
left: 0;
right: 0;
width: 100%;
height: 4px;
border: 2px solid white;
border-radius: 2px;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.3);
pointer-events: none;
transform: translateY(-50%);
top: 0;
}
.color-picker-controls {
display: flex;
flex-direction: column;
gap: 12px;
}
.color-picker-hex {
width: 100%;
padding: 8px 12px;
border: 1px solid #e0e0e0;
border-radius: 6px;
font-family: 'Courier New', monospace;
font-size: 0.875rem;
text-transform: uppercase;
transition: border-color 0.2s;
}
.color-picker-hex:focus {
outline: none;
border-color: #667eea;
}
.color-picker-rgb {
display: flex;
gap: 8px;
}
.color-picker-rgb-item {
flex: 1;
display: flex;
flex-direction: column;
gap: 6px;
}
.color-picker-rgb-item label {
font-size: 0.75rem;
font-weight: 600;
color: #666;
text-align: center;
}
.color-picker-rgb-slider {
width: 100%;
height: 6px;
border-radius: 3px;
background: #e0e0e0;
outline: none;
-webkit-appearance: none;
cursor: pointer;
}
.color-picker-rgb-slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 16px;
height: 16px;
border-radius: 50%;
background: #667eea;
cursor: pointer;
border: 2px solid white;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2);
transition: all 0.2s;
}
.color-picker-rgb-slider::-webkit-slider-thumb:hover {
transform: scale(1.1);
box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.3);
}
.color-picker-rgb-slider::-moz-range-thumb {
width: 16px;
height: 16px;
border-radius: 50%;
background: #667eea;
cursor: pointer;
border: 2px solid white;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2);
transition: all 0.2s;
}
.color-picker-rgb-slider::-moz-range-thumb:hover {
transform: scale(1.1);
box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.3);
}
/* Color-specific slider backgrounds */
.color-picker-rgb-item[data-channel="r"] .color-picker-rgb-slider {
background: linear-gradient(to right, #000000, #ff0000);
}
.color-picker-rgb-item[data-channel="g"] .color-picker-rgb-slider {
background: linear-gradient(to right, #000000, #00ff00);
}
.color-picker-rgb-item[data-channel="b"] .color-picker-rgb-slider {
background: linear-gradient(to right, #000000, #0000ff);
}
.color-picker-rgb-input {
width: 100%;
padding: 6px 8px;
border: 1px solid #e0e0e0;
border-radius: 6px;
font-size: 0.875rem;
text-align: center;
transition: border-color 0.2s;
-moz-appearance: textfield;
}
.color-picker-rgb-input::-webkit-outer-spin-button,
.color-picker-rgb-input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
.color-picker-rgb-input:focus {
outline: none;
border-color: #667eea;
}
/* Responsive adjustments */
@media (max-width: 480px) {
.color-picker-panel {
left: auto;
right: 0;
}
.color-picker-main {
width: 180px;
height: 180px;
}
.color-picker-hue {
height: 180px;
}
}
/* Dark mode support (optional) */
@media (prefers-color-scheme: dark) {
.color-picker-panel {
background: #2d3748;
border-color: #4a5568;
}
.color-picker-preview {
border-color: #4a5568;
}
.color-picker-main,
.color-picker-hue {
border-color: #4a5568;
}
.color-picker-hex,
.color-picker-rgb-input {
background: #1a202c;
border-color: #4a5568;
color: #e2e8f0;
}
.color-picker-rgb-item label {
color: #a0aec0;
}
.color-picker-rgb-slider {
background: #4a5568 !important;
}
.color-picker-rgb-slider::-webkit-slider-thumb,
.color-picker-rgb-slider::-moz-range-thumb {
background: #667eea;
border-color: #2d3748;
}
}
+474
View File
@@ -0,0 +1,474 @@
/**
* Custom Color Picker Component
* Consistent across all operating systems and browsers
*/
class ColorPicker {
constructor(container, options = {}) {
this.container = typeof container === 'string' ? document.querySelector(container) : container;
this.options = {
initialColor: options.initialColor || '#FF0000',
onColorChange: options.onColorChange || null,
showHexInput: options.showHexInput !== false,
...options
};
this.currentColor = this.options.initialColor;
this.isOpen = false;
this.init();
}
init() {
this.createPicker();
this.setupEventListeners();
this.updateColor(this.options.initialColor);
}
createPicker() {
this.container.innerHTML = '';
this.container.className = 'color-picker-container';
// Color preview button
this.previewBtn = document.createElement('button');
this.previewBtn.className = 'color-picker-preview';
this.previewBtn.type = 'button';
this.previewBtn.style.backgroundColor = this.currentColor;
this.previewBtn.setAttribute('aria-label', 'Open color picker');
// Dropdown panel
this.panel = document.createElement('div');
this.panel.className = 'color-picker-panel';
this.panel.style.display = 'none';
// Main color area (hue/saturation)
this.mainArea = document.createElement('div');
this.mainArea.className = 'color-picker-main';
this.mainCanvas = document.createElement('canvas');
this.mainCanvas.width = 200;
this.mainCanvas.height = 200;
this.mainCanvas.className = 'color-picker-canvas';
this.mainArea.appendChild(this.mainCanvas);
// Main area cursor
this.mainCursor = document.createElement('div');
this.mainCursor.className = 'color-picker-cursor';
this.mainArea.appendChild(this.mainCursor);
// Hue slider
this.hueArea = document.createElement('div');
this.hueArea.className = 'color-picker-hue';
this.hueCanvas = document.createElement('canvas');
this.hueCanvas.width = 20;
this.hueCanvas.height = 200;
this.hueCanvas.className = 'color-picker-canvas';
this.hueArea.appendChild(this.hueCanvas);
// Hue slider cursor
this.hueCursor = document.createElement('div');
this.hueCursor.className = 'color-picker-hue-cursor';
this.hueArea.appendChild(this.hueCursor);
// Controls section
this.controls = document.createElement('div');
this.controls.className = 'color-picker-controls';
// Hex input
if (this.options.showHexInput) {
this.hexInput = document.createElement('input');
this.hexInput.type = 'text';
this.hexInput.className = 'color-picker-hex';
this.hexInput.placeholder = '#000000';
this.hexInput.maxLength = 7;
this.controls.appendChild(this.hexInput);
}
// RGB inputs and sliders
this.rgbContainer = document.createElement('div');
this.rgbContainer.className = 'color-picker-rgb';
['R', 'G', 'B'].forEach((label, index) => {
const wrapper = document.createElement('div');
wrapper.className = 'color-picker-rgb-item';
wrapper.dataset.channel = label.toLowerCase();
const labelEl = document.createElement('label');
labelEl.textContent = label;
const slider = document.createElement('input');
slider.type = 'range';
slider.className = 'color-picker-rgb-slider';
slider.min = 0;
slider.max = 255;
slider.value = 0;
slider.dataset.channel = label.toLowerCase();
const input = document.createElement('input');
input.type = 'number';
input.className = 'color-picker-rgb-input';
input.min = 0;
input.max = 255;
input.value = 0;
input.dataset.channel = label.toLowerCase();
wrapper.appendChild(labelEl);
wrapper.appendChild(slider);
wrapper.appendChild(input);
this.rgbContainer.appendChild(wrapper);
this[`rgb${label}Slider`] = slider;
this[`rgb${label}`] = input;
});
this.controls.appendChild(this.rgbContainer);
// Assemble panel
const pickerArea = document.createElement('div');
pickerArea.className = 'color-picker-area';
pickerArea.appendChild(this.mainArea);
pickerArea.appendChild(this.hueArea);
this.panel.appendChild(pickerArea);
this.panel.appendChild(this.controls);
// Assemble container
this.container.appendChild(this.previewBtn);
this.container.appendChild(this.panel);
// Draw canvases
this.drawHueCanvas();
this.drawMainCanvas(1.0); // Start with full saturation
}
setupEventListeners() {
// Toggle panel
this.previewBtn.addEventListener('click', (e) => {
e.stopPropagation();
this.toggle();
});
// Close on outside click
document.addEventListener('click', (e) => {
if (!this.container.contains(e.target) && this.isOpen) {
this.close();
}
});
// Main area interaction
let isMainDragging = false;
this.mainCanvas.addEventListener('mousedown', (e) => {
isMainDragging = true;
this.handleMainAreaClick(e);
});
this.mainCanvas.addEventListener('mousemove', (e) => {
if (isMainDragging) {
this.handleMainAreaClick(e);
}
});
document.addEventListener('mouseup', () => {
isMainDragging = false;
});
// Touch support for main area
this.mainCanvas.addEventListener('touchstart', (e) => {
e.preventDefault();
isMainDragging = true;
this.handleMainAreaClick(e.touches[0]);
});
this.mainCanvas.addEventListener('touchmove', (e) => {
e.preventDefault();
if (isMainDragging) {
this.handleMainAreaClick(e.touches[0]);
}
});
this.mainCanvas.addEventListener('touchend', () => {
isMainDragging = false;
});
// Hue slider interaction
let isHueDragging = false;
this.hueCanvas.addEventListener('mousedown', (e) => {
isHueDragging = true;
this.handleHueClick(e);
});
this.hueCanvas.addEventListener('mousemove', (e) => {
if (isHueDragging) {
this.handleHueClick(e);
}
});
document.addEventListener('mouseup', () => {
isHueDragging = false;
});
// Touch support for hue slider
this.hueCanvas.addEventListener('touchstart', (e) => {
e.preventDefault();
isHueDragging = true;
this.handleHueClick(e.touches[0]);
});
this.hueCanvas.addEventListener('touchmove', (e) => {
e.preventDefault();
if (isHueDragging) {
this.handleHueClick(e.touches[0]);
}
});
this.hueCanvas.addEventListener('touchend', () => {
isHueDragging = false;
});
// Hex input
if (this.hexInput) {
this.hexInput.addEventListener('input', (e) => {
const value = e.target.value;
if (/^#[0-9A-Fa-f]{6}$/.test(value)) {
this.updateColor(value);
}
});
this.hexInput.addEventListener('blur', (e) => {
const value = e.target.value;
if (!/^#[0-9A-Fa-f]{6}$/.test(value) && value.length > 0) {
e.target.value = this.currentColor;
}
});
}
// RGB inputs and sliders
['R', 'G', 'B'].forEach(label => {
// Slider change
this[`rgb${label}Slider`].addEventListener('input', (e) => {
const value = parseInt(e.target.value) || 0;
this[`rgb${label}`].value = value;
const r = parseInt(this.rgbR.value) || 0;
const g = parseInt(this.rgbG.value) || 0;
const b = parseInt(this.rgbB.value) || 0;
const hex = this.rgbToHex(r, g, b);
this.updateColor(hex, false); // Don't update RGB inputs/sliders to avoid loop
});
// Input change
this[`rgb${label}`].addEventListener('input', (e) => {
let value = parseInt(e.target.value) || 0;
value = Math.max(0, Math.min(255, value)); // Clamp to 0-255
e.target.value = value;
this[`rgb${label}Slider`].value = value;
const r = parseInt(this.rgbR.value) || 0;
const g = parseInt(this.rgbG.value) || 0;
const b = parseInt(this.rgbB.value) || 0;
const hex = this.rgbToHex(r, g, b);
this.updateColor(hex, false); // Don't update RGB inputs/sliders to avoid loop
});
});
}
drawHueCanvas() {
const ctx = this.hueCanvas.getContext('2d');
const gradient = ctx.createLinearGradient(0, 0, 0, 200);
for (let i = 0; i <= 6; i++) {
const hue = i * 60;
gradient.addColorStop(i / 6, `hsl(${hue}, 100%, 50%)`);
}
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 20, 200);
}
drawMainCanvas(hue) {
const ctx = this.mainCanvas.getContext('2d');
// Saturation gradient (left to right)
const satGradient = ctx.createLinearGradient(0, 0, 200, 0);
satGradient.addColorStop(0, `hsl(${hue}, 0%, 50%)`);
satGradient.addColorStop(1, `hsl(${hue}, 100%, 50%)`);
ctx.fillStyle = satGradient;
ctx.fillRect(0, 0, 200, 200);
// Brightness gradient (top to bottom)
const brightGradient = ctx.createLinearGradient(0, 0, 0, 200);
brightGradient.addColorStop(0, 'rgba(255, 255, 255, 0)');
brightGradient.addColorStop(1, 'rgba(0, 0, 0, 1)');
ctx.fillStyle = brightGradient;
ctx.fillRect(0, 0, 200, 200);
}
handleMainAreaClick(e) {
const rect = this.mainCanvas.getBoundingClientRect();
const x = Math.max(0, Math.min(200, e.clientX - rect.left));
const y = Math.max(0, Math.min(200, e.clientY - rect.top));
const saturation = x / 200;
const brightness = 1 - (y / 200);
this.updateColorFromHSB(this.hue, saturation, brightness);
this.updateCursor(x, y);
}
handleHueClick(e) {
const rect = this.hueCanvas.getBoundingClientRect();
const y = Math.max(0, Math.min(200, e.clientY - rect.top));
const hue = (y / 200) * 360;
this.hue = hue;
this.drawMainCanvas(hue);
this.updateHueCursor(y);
// Recalculate color with new hue
const rect2 = this.mainCanvas.getBoundingClientRect();
const x = parseFloat(this.mainCursor.style.left) || 0;
const y2 = parseFloat(this.mainCursor.style.top) || 0;
const saturation = x / 200;
const brightness = 1 - (y2 / 200);
this.updateColorFromHSB(hue, saturation, brightness);
}
updateColorFromHSB(h, s, v) {
const rgb = this.hsbToRgb(h, s, v);
const hex = this.rgbToHex(rgb.r, rgb.g, rgb.b);
this.updateColor(hex);
}
hsbToRgb(h, s, v) {
h = h / 360;
const i = Math.floor(h * 6);
const f = h * 6 - i;
const p = v * (1 - s);
const q = v * (1 - f * s);
const t = v * (1 - (1 - f) * s);
let r, g, b;
switch (i % 6) {
case 0: r = v; g = t; b = p; break;
case 1: r = q; g = v; b = p; break;
case 2: r = p; g = v; b = t; break;
case 3: r = p; g = q; b = v; break;
case 4: r = t; g = p; b = v; break;
case 5: r = v; g = p; b = q; break;
}
return {
r: Math.round(r * 255),
g: Math.round(g * 255),
b: Math.round(b * 255)
};
}
rgbToHex(r, g, b) {
return '#' + [r, g, b].map(x => {
const hex = x.toString(16);
return hex.length === 1 ? '0' + hex : hex;
}).join('').toUpperCase();
}
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)
} : null;
}
rgbToHsb(r, g, b) {
r /= 255;
g /= 255;
b /= 255;
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const diff = max - min;
let h = 0;
if (diff !== 0) {
if (max === r) {
h = ((g - b) / diff) % 6) * 60;
} else if (max === g) {
h = ((b - r) / diff + 2) * 60;
} else {
h = ((r - g) / diff + 4) * 60;
}
}
if (h < 0) h += 360;
const s = max === 0 ? 0 : diff / max;
const v = max;
return { h, s, v };
}
updateColor(hex, updateInputs = true) {
this.currentColor = hex.toUpperCase();
this.previewBtn.style.backgroundColor = this.currentColor;
const rgb = this.hexToRgb(this.currentColor);
if (!rgb) return;
const hsb = this.rgbToHsb(rgb.r, rgb.g, rgb.b);
this.hue = hsb.h;
// Update main canvas
this.drawMainCanvas(this.hue);
// Update cursors
const x = hsb.s * 200;
const y = (1 - hsb.v) * 200;
this.updateCursor(x, y);
this.updateHueCursor((this.hue / 360) * 200);
// Update inputs
if (updateInputs) {
if (this.hexInput) {
this.hexInput.value = this.currentColor;
}
if (this.rgbR) {
this.rgbR.value = rgb.r;
this.rgbG.value = rgb.g;
this.rgbB.value = rgb.b;
}
if (this.rgbRSlider) {
this.rgbRSlider.value = rgb.r;
this.rgbGSlider.value = rgb.g;
this.rgbBSlider.value = rgb.b;
}
}
// Callback
if (this.options.onColorChange) {
this.options.onColorChange(this.currentColor);
}
}
updateCursor(x, y) {
this.mainCursor.style.left = `${x}px`;
this.mainCursor.style.top = `${y}px`;
}
updateHueCursor(y) {
this.hueCursor.style.top = `${y}px`;
}
toggle() {
this.isOpen ? this.close() : this.open();
}
open() {
this.panel.style.display = 'block';
this.isOpen = true;
}
close() {
this.panel.style.display = 'none';
this.isOpen = false;
}
getColor() {
return this.currentColor;
}
setColor(color) {
this.updateColor(color);
}
}
// Export for use in other scripts
if (typeof module !== 'undefined' && module.exports) {
module.exports = ColorPicker;
}
+359
View File
@@ -0,0 +1,359 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LED Driver - Dashboard</title>
<link rel="stylesheet" href="color-picker.css">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
color: #333;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
.header {
background: white;
border-radius: 12px;
padding: 24px;
margin-bottom: 24px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.header h1 {
color: #667eea;
margin-bottom: 8px;
}
.header p {
color: #666;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 24px;
margin-bottom: 24px;
}
.card {
background: white;
border-radius: 12px;
padding: 24px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
transition: transform 0.2s, box-shadow 0.2s;
}
.card:hover {
transform: translateY(-2px);
box-shadow: 0 8px 12px rgba(0, 0, 0, 0.15);
}
.card h2 {
color: #667eea;
margin-bottom: 16px;
font-size: 1.25rem;
}
.pattern-selector {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
gap: 12px;
}
.pattern-btn {
padding: 16px;
border: 2px solid #e0e0e0;
border-radius: 8px;
background: white;
cursor: pointer;
transition: all 0.2s;
text-align: center;
font-weight: 500;
}
.pattern-btn:hover {
border-color: #667eea;
background: #f0f0ff;
}
.pattern-btn.active {
border-color: #667eea;
background: #667eea;
color: white;
}
.slider-group {
margin-bottom: 20px;
}
.slider-group label {
display: block;
margin-bottom: 8px;
font-weight: 500;
color: #333;
}
.slider {
width: 100%;
height: 8px;
border-radius: 4px;
background: #e0e0e0;
outline: none;
-webkit-appearance: none;
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 20px;
height: 20px;
border-radius: 50%;
background: #667eea;
cursor: pointer;
}
.slider::-moz-range-thumb {
width: 20px;
height: 20px;
border-radius: 50%;
background: #667eea;
cursor: pointer;
border: none;
}
.value-display {
display: inline-block;
margin-left: 12px;
font-weight: 600;
color: #667eea;
}
.color-picker-group {
display: flex;
gap: 12px;
flex-wrap: wrap;
}
.color-picker-wrapper {
display: inline-block;
}
.btn {
padding: 12px 24px;
border: none;
border-radius: 8px;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover {
background: #5568d3;
}
.btn-secondary {
background: #e0e0e0;
color: #333;
}
.btn-secondary:hover {
background: #d0d0d0;
}
.device-list {
list-style: none;
}
.device-item {
padding: 12px;
border: 1px solid #e0e0e0;
border-radius: 8px;
margin-bottom: 8px;
display: flex;
justify-content: space-between;
align-items: center;
}
.device-status {
width: 12px;
height: 12px;
border-radius: 50%;
background: #4caf50;
}
.device-status.offline {
background: #f44336;
}
.actions {
display: flex;
gap: 12px;
margin-top: 20px;
}
.btn-full {
width: 100%;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>LED Driver Control Panel</h1>
<p>Manage your LED devices and patterns</p>
</div>
<div class="grid">
<!-- Pattern Selection -->
<div class="card">
<h2>Pattern Selection</h2>
<div class="pattern-selector">
<div class="pattern-btn active">On</div>
<div class="pattern-btn">Off</div>
<div class="pattern-btn">Blink</div>
<div class="pattern-btn">Chase</div>
<div class="pattern-btn">Circle</div>
<div class="pattern-btn">Pulse</div>
<div class="pattern-btn">Rainbow</div>
<div class="pattern-btn">Transition</div>
</div>
</div>
<!-- Brightness & Speed -->
<div class="card">
<h2>Brightness & Speed</h2>
<div class="slider-group">
<label>
Brightness
<span class="value-display" id="brightness-value">100</span>%
</label>
<input type="range" class="slider" id="brightness" min="0" max="100" value="100">
</div>
<div class="slider-group">
<label>
Delay
<span class="value-display" id="delay-value">100</span>ms
</label>
<input type="range" class="slider" id="delay" min="10" max="1000" value="100" step="10">
</div>
</div>
<!-- Color Selection -->
<div class="card">
<h2>Colors</h2>
<div class="color-picker-group">
<input type="color" class="color-input" value="#000000">
<input type="color" class="color-input" value="#FF0000">
<input type="color" class="color-input" value="#00FF00">
<input type="color" class="color-input" value="#0000FF">
</div>
<div class="actions">
<button class="btn btn-secondary btn-full">Add Color</button>
</div>
</div>
<!-- Device Status -->
<div class="card">
<h2>Connected Devices</h2>
<ul class="device-list">
<li class="device-item">
<div>
<strong>led-device1</strong>
<div style="font-size: 0.875rem; color: #666;">Group: group1</div>
</div>
<div class="device-status"></div>
</li>
<li class="device-item">
<div>
<strong>led-device2</strong>
<div style="font-size: 0.875rem; color: #666;">Group: group2</div>
</div>
<div class="device-status"></div>
</li>
<li class="device-item">
<div>
<strong>led-device3</strong>
<div style="font-size: 0.875rem; color: #666;">No group</div>
</div>
<div class="device-status offline"></div>
</li>
</ul>
</div>
</div>
<!-- Action Buttons -->
<div class="card">
<div class="actions">
<button class="btn btn-primary btn-full">Apply Settings</button>
<button class="btn btn-secondary btn-full">Save to Device</button>
</div>
</div>
</div>
<script>
// Brightness slider
document.getElementById('brightness').addEventListener('input', function(e) {
document.getElementById('brightness-value').textContent = e.target.value;
});
// Delay slider
document.getElementById('delay').addEventListener('input', function(e) {
document.getElementById('delay-value').textContent = e.target.value;
});
// Pattern selection
document.querySelectorAll('.pattern-btn').forEach(btn => {
btn.addEventListener('click', function() {
document.querySelectorAll('.pattern-btn').forEach(b => b.classList.remove('active'));
this.classList.add('active');
});
});
// Initialize color pickers
const colorPickers = [];
const initialColors = ['#000000', '#FF0000'];
function addColorPicker(color = '#000000') {
const container = document.createElement('div');
container.className = 'color-picker-wrapper';
document.getElementById('color-pickers').appendChild(container);
const picker = new ColorPicker(container, {
initialColor: color,
onColorChange: (newColor) => {
console.log('Color changed:', newColor);
// Update device colors
}
});
colorPickers.push(picker);
return picker;
}
// Add initial color pickers
initialColors.forEach(color => addColorPicker(color));
</script>
<script src="color-picker.js"></script>
</body>
</html>
+418
View File
@@ -0,0 +1,418 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LED Driver - Device Management</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
.header {
background: white;
border-radius: 12px;
padding: 24px;
margin-bottom: 24px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
display: flex;
justify-content: space-between;
align-items: center;
}
.header h1 {
color: #667eea;
}
.btn {
padding: 12px 24px;
border: none;
border-radius: 8px;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover {
background: #5568d3;
}
.tabs {
display: flex;
gap: 8px;
margin-bottom: 24px;
background: white;
padding: 8px;
border-radius: 12px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.zone {
flex: 1;
padding: 12px 24px;
border: none;
background: transparent;
border-radius: 8px;
cursor: pointer;
font-weight: 500;
transition: all 0.2s;
}
.zone.active {
background: #667eea;
color: white;
}
.zone-content {
display: none;
}
.zone-content.active {
display: block;
}
.card {
background: white;
border-radius: 12px;
padding: 24px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
margin-bottom: 24px;
}
.card h2 {
color: #667eea;
margin-bottom: 20px;
}
.device-item, .group-item {
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 16px;
margin-bottom: 12px;
display: flex;
justify-content: space-between;
align-items: center;
transition: all 0.2s;
}
.device-item:hover, .group-item:hover {
border-color: #667eea;
box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2);
}
.device-info, .group-info {
flex: 1;
}
.device-name, .group-name {
font-weight: 600;
font-size: 1.125rem;
margin-bottom: 4px;
}
.device-details, .group-details {
font-size: 0.875rem;
color: #666;
}
.status-badge {
display: inline-block;
padding: 4px 12px;
border-radius: 12px;
font-size: 0.75rem;
font-weight: 600;
margin-right: 12px;
}
.status-online {
background: #d4edda;
color: #155724;
}
.status-offline {
background: #f8d7da;
color: #721c24;
}
.status-indicator {
width: 12px;
height: 12px;
border-radius: 50%;
background: #4caf50;
margin-right: 8px;
}
.status-indicator.offline {
background: #f44336;
}
.device-actions, .group-actions {
display: flex;
gap: 8px;
}
.btn-icon {
padding: 8px 12px;
border: 1px solid #e0e0e0;
background: white;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s;
}
.btn-icon:hover {
border-color: #667eea;
color: #667eea;
}
.form-group {
margin-bottom: 20px;
}
.form-group label {
display: block;
margin-bottom: 8px;
font-weight: 500;
color: #333;
}
.form-group input, .form-group select {
width: 100%;
padding: 12px;
border: 1px solid #e0e0e0;
border-radius: 8px;
font-size: 1rem;
}
.form-group input:focus, .form-group select:focus {
outline: none;
border-color: #667eea;
}
.form-actions {
display: flex;
gap: 12px;
margin-top: 24px;
}
.btn-secondary {
background: #e0e0e0;
color: #333;
}
.btn-secondary:hover {
background: #d0d0d0;
}
.group-devices {
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid #e0e0e0;
}
.group-device-tag {
display: inline-block;
padding: 4px 8px;
background: #f0f0f0;
border-radius: 4px;
font-size: 0.75rem;
margin-right: 8px;
margin-top: 8px;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Device & Group Management</h1>
<button class="btn btn-primary" onclick="showAddDeviceModal()">+ Add Device</button>
</div>
<div class="tabs">
<button class="zone active" onclick="switchTab('devices')">Devices</button>
<button class="zone" onclick="switchTab('groups')">Groups</button>
</div>
<!-- Devices Zone -->
<div id="devices-zone" class="zone-content active">
<div class="card">
<h2>Connected Devices</h2>
<div class="device-item">
<div class="device-info">
<div class="device-name">
<span class="status-indicator"></span>
led-device1
</div>
<div class="device-details">
<span class="status-badge status-online">Online</span>
MAC: AA:BB:CC:DD:EE:01 | Group: group1 | Pattern: Rainbow
</div>
</div>
<div class="device-actions">
<button class="btn-icon" title="Edit">✏️</button>
<button class="btn-icon" title="Settings">⚙️</button>
<button class="btn-icon" title="Remove">🗑️</button>
</div>
</div>
<div class="device-item">
<div class="device-info">
<div class="device-name">
<span class="status-indicator"></span>
led-device2
</div>
<div class="device-details">
<span class="status-badge status-online">Online</span>
MAC: AA:BB:CC:DD:EE:02 | Group: group2 | Pattern: Chase
</div>
</div>
<div class="device-actions">
<button class="btn-icon" title="Edit">✏️</button>
<button class="btn-icon" title="Settings">⚙️</button>
<button class="btn-icon" title="Remove">🗑️</button>
</div>
</div>
<div class="device-item">
<div class="device-info">
<div class="device-name">
<span class="status-indicator offline"></span>
led-device3
</div>
<div class="device-details">
<span class="status-badge status-offline">Offline</span>
MAC: AA:BB:CC:DD:EE:03 | No group | Pattern: On
</div>
</div>
<div class="device-actions">
<button class="btn-icon" title="Edit">✏️</button>
<button class="btn-icon" title="Settings">⚙️</button>
<button class="btn-icon" title="Remove">🗑️</button>
</div>
</div>
</div>
</div>
<!-- Groups Zone -->
<div id="groups-zone" class="zone-content">
<div class="card">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2>Groups</h2>
<button class="btn btn-primary" onclick="showAddGroupModal()">+ Create Group</button>
</div>
<div class="group-item">
<div class="group-info">
<div class="group-name">group1</div>
<div class="group-details">
Pattern: On | Brightness: 100% | Delay: 100ms
</div>
<div class="group-devices">
<span class="group-device-tag">led-device1</span>
</div>
</div>
<div class="group-actions">
<button class="btn-icon" title="Edit">✏️</button>
<button class="btn-icon" title="Apply">▶️</button>
<button class="btn-icon" title="Delete">🗑️</button>
</div>
</div>
<div class="group-item">
<div class="group-info">
<div class="group-name">group2</div>
<div class="group-details">
Pattern: Chase | Brightness: 75% | Delay: 200ms
</div>
<div class="group-devices">
<span class="group-device-tag">led-device2</span>
</div>
</div>
<div class="group-actions">
<button class="btn-icon" title="Edit">✏️</button>
<button class="btn-icon" title="Apply">▶️</button>
<button class="btn-icon" title="Delete">🗑️</button>
</div>
</div>
</div>
</div>
</div>
<!-- Modal (simplified) -->
<div id="modal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 1000; align-items: center; justify-content: center;">
<div class="card" style="max-width: 500px; margin: 20px;">
<h2 id="modal-title">Add Device</h2>
<div class="form-group">
<label>Device Name</label>
<input type="text" id="device-name" placeholder="led-device4">
</div>
<div class="form-group">
<label>MAC Address</label>
<input type="text" id="device-mac" placeholder="AA:BB:CC:DD:EE:04">
</div>
<div class="form-group">
<label>Group</label>
<select id="device-group">
<option value="">No group</option>
<option value="group1">group1</option>
<option value="group2">group2</option>
</select>
</div>
<div class="form-actions">
<button class="btn btn-secondary" onclick="closeModal()">Cancel</button>
<button class="btn btn-primary" onclick="saveDevice()">Save</button>
</div>
</div>
</div>
<script>
function switchTab(zone) {
document.querySelectorAll('.zone').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.zone-content').forEach(c => c.classList.remove('active'));
event.target.classList.add('active');
document.getElementById(zone + '-zone').classList.add('active');
}
function showAddDeviceModal() {
document.getElementById('modal').style.display = 'flex';
document.getElementById('modal-title').textContent = 'Add Device';
}
function showAddGroupModal() {
document.getElementById('modal').style.display = 'flex';
document.getElementById('modal-title').textContent = 'Create Group';
}
function closeModal() {
document.getElementById('modal').style.display = 'none';
}
function saveDevice() {
alert('Device saved! (This is a mockup)');
closeModal();
}
</script>
</body>
</html>
+155
View File
@@ -0,0 +1,155 @@
#!/usr/bin/env python3
"""
Generate images from HTML mockup files
Uses Playwright to render HTML and take screenshots
"""
import os
import sys
from pathlib import Path
try:
from playwright.sync_api import sync_playwright
PLAYWRIGHT_AVAILABLE = True
except ImportError:
PLAYWRIGHT_AVAILABLE = False
try:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
SELENIUM_AVAILABLE = True
except ImportError:
SELENIUM_AVAILABLE = False
try:
from html2image import Html2Image
HTML2IMAGE_AVAILABLE = True
except ImportError:
HTML2IMAGE_AVAILABLE = False
def generate_with_playwright(html_file, output_file, width=1920, height=1080):
"""Generate image using Playwright"""
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page(viewport={'width': width, 'height': height})
page.goto(f'file://{html_file.absolute()}')
# Wait for page to load
page.wait_for_timeout(1000)
page.screenshot(path=str(output_file), full_page=True)
browser.close()
print(f"✓ Generated {output_file.name} using Playwright")
def generate_with_selenium(html_file, output_file, width=1920, height=1080):
"""Generate image using Selenium"""
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument(f'--window-size={width},{height}')
driver = webdriver.Chrome(options=chrome_options)
try:
driver.get(f'file://{html_file.absolute()}')
# Wait for page to load
import time
time.sleep(2)
driver.save_screenshot(str(output_file))
print(f"✓ Generated {output_file.name} using Selenium")
finally:
driver.quit()
def generate_with_html2image(html_file, output_file, width=1920, height=1080):
"""Generate image using html2image"""
hti = Html2Image(size=(width, height))
hti.screenshot(
html_file=str(html_file),
save_as=output_file.name,
size=(width, height)
)
print(f"✓ Generated {output_file.name} using html2image")
def generate_image(html_file, output_dir, width=1920, height=1080):
"""Generate image from HTML file using available method"""
html_path = Path(html_file)
output_path = output_dir / f"{html_path.stem}.png"
if PLAYWRIGHT_AVAILABLE:
try:
generate_with_playwright(html_path, output_path, width, height)
return True
except Exception as e:
print(f"Playwright failed: {e}, trying alternatives...")
if SELENIUM_AVAILABLE:
try:
generate_with_selenium(html_path, output_path, width, height)
return True
except Exception as e:
print(f"Selenium failed: {e}, trying alternatives...")
if HTML2IMAGE_AVAILABLE:
try:
generate_with_html2image(html_path, output_path, width, height)
return True
except Exception as e:
print(f"html2image failed: {e}")
return False
def main():
"""Main function to generate images from all HTML files"""
script_dir = Path(__file__).parent
output_dir = script_dir / "images"
output_dir.mkdir(exist_ok=True)
html_files = list(script_dir.glob("*.html"))
if not html_files:
print("No HTML files found in mockups directory")
return
print(f"Found {len(html_files)} HTML file(s)")
print(f"Output directory: {output_dir}")
print()
# Check available libraries
if not any([PLAYWRIGHT_AVAILABLE, SELENIUM_AVAILABLE, HTML2IMAGE_AVAILABLE]):
print("ERROR: No screenshot library available!")
print("\nPlease install one of the following:")
print(" pip install playwright && playwright install chromium")
print(" pip install selenium")
print(" pip install html2image")
sys.exit(1)
print("Available screenshot libraries:")
if PLAYWRIGHT_AVAILABLE:
print(" ✓ Playwright")
if SELENIUM_AVAILABLE:
print(" ✓ Selenium")
if HTML2IMAGE_AVAILABLE:
print(" ✓ html2image")
print()
# Generate images
success_count = 0
for html_file in html_files:
print(f"Generating image from {html_file.name}...")
if generate_image(html_file, output_dir):
success_count += 1
else:
print(f"✗ Failed to generate image from {html_file.name}")
print()
print(f"Successfully generated {success_count}/{len(html_files)} images")
print(f"Images saved to: {output_dir}")
if __name__ == "__main__":
main()
Binary file not shown.

After

Width:  |  Height:  |  Size: 625 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 600 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 585 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 714 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 508 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 562 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 904 KiB

+136
View File
@@ -0,0 +1,136 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LED Driver - UI Mockups</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 40px 20px;
display: flex;
align-items: center;
justify-content: center;
}
.container {
max-width: 800px;
width: 100%;
}
.header {
text-align: center;
color: white;
margin-bottom: 40px;
}
.header h1 {
font-size: 3rem;
margin-bottom: 12px;
}
.header p {
font-size: 1.25rem;
opacity: 0.9;
}
.mockups-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 24px;
}
.mockup-card {
background: white;
border-radius: 16px;
padding: 32px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
transition: all 0.3s;
text-decoration: none;
color: inherit;
display: block;
}
.mockup-card:hover {
transform: translateY(-4px);
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.3);
}
.mockup-icon {
font-size: 3rem;
margin-bottom: 16px;
}
.mockup-title {
font-size: 1.5rem;
font-weight: 600;
color: #667eea;
margin-bottom: 8px;
}
.mockup-description {
color: #666;
line-height: 1.6;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>LED Driver UI Mockups</h1>
<p>Example user interfaces for the LED driver system</p>
</div>
<div class="mockups-grid">
<a href="dashboard.html" class="mockup-card">
<div class="mockup-icon">📊</div>
<div class="mockup-title">Dashboard</div>
<div class="mockup-description">
Main control panel for managing LED patterns, brightness, colors, and device status.
</div>
</a>
<a href="pattern-selector.html" class="mockup-card">
<div class="mockup-icon">🎨</div>
<div class="mockup-title">Pattern Selector</div>
<div class="mockup-description">
Visual interface for selecting from available LED patterns: On, Off, Blink, Chase, Circle, Pulse, Rainbow, and Transition.
</div>
</a>
<a href="device-management.html" class="mockup-card">
<div class="mockup-icon">🔧</div>
<div class="mockup-title">Device Management</div>
<div class="mockup-description">
Manage connected LED devices and groups. View device status, assign groups, and configure device settings.
</div>
</a>
<a href="settings.html" class="mockup-card">
<div class="mockup-icon">⚙️</div>
<div class="mockup-title">Settings</div>
<div class="mockup-description">
Comprehensive settings panel for configuring LED pin, color order, pattern parameters, and network settings.
</div>
</a>
<a href="presets.html" class="mockup-card">
<div class="mockup-icon">💾</div>
<div class="mockup-title">Presets</div>
<div class="mockup-description">
Save, load, and manage preset configurations with pattern, colors, delay, and all N1-N8 parameters for quick pattern switching.
</div>
</a>
</div>
</div>
</body>
</html>
+310
View File
@@ -0,0 +1,310 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LED Driver - Pattern Selector</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 1400px;
margin: 0 auto;
}
.header {
text-align: center;
margin-bottom: 40px;
color: #2d3748;
}
.header h1 {
font-size: 2.5rem;
margin-bottom: 8px;
}
.header p {
font-size: 1.125rem;
color: #718096;
}
.patterns-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 24px;
}
.pattern-card {
background: white;
border-radius: 16px;
padding: 24px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
cursor: pointer;
transition: all 0.3s;
border: 3px solid transparent;
}
.pattern-card:hover {
transform: translateY(-4px);
box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
border-color: #667eea;
}
.pattern-card.selected {
border-color: #667eea;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.pattern-icon {
width: 100%;
height: 180px;
border-radius: 12px;
margin-bottom: 16px;
display: flex;
align-items: center;
justify-content: center;
font-size: 3rem;
background: #f7fafc;
position: relative;
overflow: hidden;
}
.pattern-card.selected .pattern-icon {
background: rgba(255, 255, 255, 0.2);
}
.pattern-name {
font-size: 1.5rem;
font-weight: 600;
margin-bottom: 8px;
}
.pattern-description {
font-size: 0.875rem;
color: #718096;
line-height: 1.5;
}
.pattern-card.selected .pattern-description {
color: rgba(255, 255, 255, 0.9);
}
.pattern-preview {
display: flex;
gap: 4px;
margin-top: 12px;
}
.preview-dot {
flex: 1;
height: 8px;
border-radius: 4px;
background: #e2e8f0;
}
.pattern-card.selected .preview-dot {
background: rgba(255, 255, 255, 0.5);
}
.actions {
margin-top: 40px;
text-align: center;
}
.btn {
padding: 16px 48px;
border: none;
border-radius: 12px;
font-size: 1.125rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
margin: 0 12px;
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover {
background: #5568d3;
transform: translateY(-2px);
box-shadow: 0 8px 16px rgba(102, 126, 234, 0.4);
}
.btn-secondary {
background: white;
color: #667eea;
border: 2px solid #667eea;
}
.btn-secondary:hover {
background: #f0f0ff;
}
/* Pattern-specific icons */
.icon-on { background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%); }
.icon-off { background: #2d3748; }
.icon-blink { background: linear-gradient(90deg, #ffd700 25%, #2d3748 25%, #2d3748 50%, #ffd700 50%); }
.icon-chase { background: linear-gradient(90deg, #ff0000 0%, #ff6666 50%, #ff0000 100%); }
.icon-circle { background: radial-gradient(circle, #00ff00 0%, #66ff66 50%, #00ff00 100%); }
.icon-pulse { background: radial-gradient(circle, #0000ff 0%, #6666ff 50%, #0000ff 100%); }
.icon-rainbow { background: linear-gradient(90deg, #ff0000, #ff7f00, #ffff00, #00ff00, #0000ff, #4b0082, #9400d3); }
.icon-transition { background: linear-gradient(135deg, #ff0000 0%, #0000ff 100%); }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Select LED Pattern</h1>
<p>Choose a pattern to display on your LED devices</p>
</div>
<div class="patterns-grid">
<div class="pattern-card" data-pattern="on">
<div class="pattern-icon icon-on">💡</div>
<div class="pattern-name">On</div>
<div class="pattern-description">Solid color display - LEDs stay on with selected color</div>
<div class="pattern-preview">
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
</div>
</div>
<div class="pattern-card" data-pattern="off">
<div class="pattern-icon icon-off">⚫</div>
<div class="pattern-name">Off</div>
<div class="pattern-description">Turn all LEDs off</div>
<div class="pattern-preview">
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
</div>
</div>
<div class="pattern-card" data-pattern="blink">
<div class="pattern-icon icon-blink">✨</div>
<div class="pattern-name">Blink</div>
<div class="pattern-description">All LEDs blink on and off together</div>
<div class="pattern-preview">
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
</div>
</div>
<div class="pattern-card" data-pattern="chase">
<div class="pattern-icon icon-chase">🏃</div>
<div class="pattern-name">Chase</div>
<div class="pattern-description">Light chases along the LED strip</div>
<div class="pattern-preview">
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
</div>
</div>
<div class="pattern-card" data-pattern="circle">
<div class="pattern-icon icon-circle">⭕</div>
<div class="pattern-name">Circle</div>
<div class="pattern-description">Circular pattern that rotates around the strip</div>
<div class="pattern-preview">
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
</div>
</div>
<div class="pattern-card" data-pattern="pulse">
<div class="pattern-icon icon-pulse">💓</div>
<div class="pattern-name">Pulse</div>
<div class="pattern-description">Pulsing effect that fades in and out</div>
<div class="pattern-preview">
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
</div>
</div>
<div class="pattern-card" data-pattern="rainbow">
<div class="pattern-icon icon-rainbow">🌈</div>
<div class="pattern-name">Rainbow</div>
<div class="pattern-description">Smooth rainbow color transition across LEDs</div>
<div class="pattern-preview">
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
</div>
</div>
<div class="pattern-card" data-pattern="transition">
<div class="pattern-icon icon-transition">🔄</div>
<div class="pattern-name">Transition</div>
<div class="pattern-description">Smooth color transition between selected colors</div>
<div class="pattern-preview">
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
<div class="preview-dot"></div>
</div>
</div>
</div>
<div class="actions">
<button class="btn btn-secondary" onclick="window.history.back()">Cancel</button>
<button class="btn btn-primary" id="apply-btn">Apply Pattern</button>
</div>
</div>
<script>
let selectedPattern = null;
document.querySelectorAll('.pattern-card').forEach(card => {
card.addEventListener('click', function() {
document.querySelectorAll('.pattern-card').forEach(c => c.classList.remove('selected'));
this.classList.add('selected');
selectedPattern = this.dataset.pattern;
});
});
document.getElementById('apply-btn').addEventListener('click', function() {
if (selectedPattern) {
alert(`Applying pattern: ${selectedPattern}`);
// In real implementation, this would send the pattern to the device
} else {
alert('Please select a pattern first');
}
});
</script>
</body>
</html>
+968
View File
@@ -0,0 +1,968 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LED Driver - Presets</title>
<link rel="stylesheet" href="color-picker.css">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
color: #333;
}
.container {
max-width: 1400px;
margin: 0 auto;
}
.header {
background: white;
border-radius: 12px;
padding: 24px;
margin-bottom: 24px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
display: flex;
justify-content: space-between;
align-items: center;
}
.header h1 {
color: #667eea;
margin-bottom: 8px;
}
.header p {
color: #666;
}
.controls {
background: white;
border-radius: 12px;
padding: 20px;
margin-bottom: 24px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
display: flex;
gap: 16px;
flex-wrap: wrap;
align-items: center;
}
.search-box {
flex: 1;
min-width: 200px;
padding: 12px;
border: 1px solid #e0e0e0;
border-radius: 8px;
font-size: 1rem;
}
.search-box:focus {
outline: none;
border-color: #667eea;
}
.filter-group {
display: flex;
gap: 12px;
align-items: center;
}
.filter-select {
padding: 12px;
border: 1px solid #e0e0e0;
border-radius: 8px;
font-size: 1rem;
background: white;
cursor: pointer;
}
.filter-select:focus {
outline: none;
border-color: #667eea;
}
.view-toggle {
display: flex;
gap: 8px;
border: 1px solid #e0e0e0;
border-radius: 8px;
overflow: hidden;
}
.view-btn {
padding: 8px 16px;
border: none;
background: white;
cursor: pointer;
transition: all 0.2s;
}
.view-btn.active {
background: #667eea;
color: white;
}
.presets-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 24px;
margin-bottom: 24px;
}
.preset-card {
background: white;
border-radius: 12px;
padding: 24px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
transition: all 0.3s;
cursor: pointer;
border: 3px solid transparent;
}
.preset-card:hover {
transform: translateY(-4px);
box-shadow: 0 12px 24px rgba(0, 0, 0, 0.15);
border-color: #667eea;
}
.preset-card.selected {
border-color: #667eea;
background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
}
.preset-header {
display: flex;
justify-content: space-between;
align-items: start;
margin-bottom: 16px;
}
.preset-name {
font-size: 1.5rem;
font-weight: 600;
color: #333;
margin-bottom: 8px;
}
.pattern-badge {
display: inline-block;
padding: 4px 12px;
border-radius: 12px;
font-size: 0.75rem;
font-weight: 600;
background: #667eea;
color: white;
margin-bottom: 12px;
}
.pattern-badge.on { background: #4caf50; }
.pattern-badge.off { background: #757575; }
.pattern-badge.blink { background: #ff9800; }
.pattern-badge.chase { background: #f44336; }
.pattern-badge.circle { background: #00bcd4; }
.pattern-badge.pulse { background: #e91e63; }
.pattern-badge.rainbow { background: linear-gradient(90deg, #ff0000, #ff7f00, #ffff00, #00ff00, #0000ff, #4b0082, #9400d3); }
.pattern-badge.transition { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.color-preview {
display: flex;
gap: 8px;
margin-bottom: 16px;
flex-wrap: wrap;
}
.color-swatch {
width: 40px;
height: 40px;
border-radius: 8px;
border: 2px solid #e0e0e0;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.preset-info {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin-bottom: 16px;
font-size: 0.875rem;
color: #666;
}
.info-item {
display: flex;
align-items: center;
gap: 8px;
}
.info-label {
font-weight: 500;
}
.info-value {
color: #667eea;
font-weight: 600;
}
.preset-actions {
display: flex;
gap: 8px;
margin-top: 16px;
padding-top: 16px;
border-top: 1px solid #e0e0e0;
}
.btn {
padding: 10px 20px;
border: none;
border-radius: 8px;
font-size: 0.875rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
flex: 1;
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover {
background: #5568d3;
}
.btn-secondary {
background: #e0e0e0;
color: #333;
}
.btn-secondary:hover {
background: #d0d0d0;
}
.btn-danger {
background: #f44336;
color: white;
}
.btn-danger:hover {
background: #d32f2f;
}
.btn-icon {
padding: 8px;
min-width: 40px;
}
.btn-large {
padding: 16px 32px;
font-size: 1rem;
}
/* Modal Styles */
.modal {
display: none;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
z-index: 1000;
align-items: center;
justify-content: center;
padding: 20px;
}
.modal.active {
display: flex;
}
.modal-content {
background: white;
border-radius: 12px;
padding: 32px;
max-width: 600px;
width: 100%;
max-height: 90vh;
overflow-y: auto;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}
.modal-header {
margin-bottom: 24px;
}
.modal-header h2 {
color: #667eea;
margin-bottom: 8px;
}
.form-group {
margin-bottom: 20px;
}
.form-group label {
display: block;
margin-bottom: 8px;
font-weight: 500;
color: #333;
}
.form-group input,
.form-group select {
width: 100%;
padding: 12px;
border: 1px solid #e0e0e0;
border-radius: 8px;
font-size: 1rem;
}
.form-group input:focus,
.form-group select:focus {
outline: none;
border-color: #667eea;
}
.form-group small {
display: block;
margin-top: 4px;
color: #666;
font-size: 0.875rem;
}
.color-inputs {
display: flex;
gap: 12px;
flex-wrap: wrap;
}
.color-input-wrapper {
display: flex;
flex-direction: column;
gap: 8px;
}
.color-input-wrapper {
display: inline-block;
}
.params-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 12px;
}
.n-value-input {
width: 100%;
}
.n-value-input:focus {
border-color: #667eea;
outline: none;
}
.param-input {
display: flex;
flex-direction: column;
}
.param-input label {
font-size: 0.75rem;
margin-bottom: 4px;
}
.param-input input {
padding: 8px;
font-size: 0.875rem;
}
.modal-actions {
display: flex;
gap: 12px;
margin-top: 24px;
padding-top: 24px;
border-top: 1px solid #e0e0e0;
}
.empty-state {
background: white;
border-radius: 12px;
padding: 60px 40px;
text-align: center;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.empty-state-icon {
font-size: 4rem;
margin-bottom: 16px;
}
.empty-state h2 {
color: #667eea;
margin-bottom: 8px;
}
.empty-state p {
color: #666;
margin-bottom: 24px;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<div>
<h1>Preset Management</h1>
<p>Save and manage your favorite LED pattern configurations</p>
</div>
<div style="display: flex; gap: 12px; align-items: center;">
<button class="btn btn-secondary btn-large" onclick="syncPresets()" title="Sync all presets to all devices">🔄 Sync Presets to All Devices</button>
<button class="btn btn-primary btn-large" onclick="showCreateModal()">+ Create Preset</button>
</div>
</div>
<div class="controls">
<input type="text" class="search-box" placeholder="Search presets..." id="search-input">
<div class="filter-group">
<select class="filter-select" id="pattern-filter">
<option value="">All Patterns</option>
<option value="on">On</option>
<option value="off">Off</option>
<option value="blink">Blink</option>
<option value="chase">Chase</option>
<option value="circle">Circle</option>
<option value="pulse">Pulse</option>
<option value="rainbow">Rainbow</option>
<option value="transition">Transition</option>
</select>
<select class="filter-select" id="sort-select">
<option value="name">Sort by Name</option>
<option value="recent">Recently Used</option>
<option value="created">Recently Created</option>
</select>
<div class="view-toggle">
<button class="view-btn active" onclick="setView('grid')" id="view-grid">Grid</button>
<button class="view-btn" onclick="setView('list')" id="view-list">List</button>
</div>
</div>
</div>
<div class="presets-grid" id="presets-container">
<!-- Preset Card 1 -->
<div class="preset-card" data-pattern="rainbow" data-name="Fast Rainbow">
<div class="preset-header">
<div>
<div class="preset-name">Fast Rainbow</div>
<span class="pattern-badge rainbow">Rainbow</span>
</div>
</div>
<div class="color-preview">
<div class="color-swatch" style="background: #FF0000;"></div>
<div class="color-swatch" style="background: #00FF00;"></div>
<div class="color-swatch" style="background: #0000FF;"></div>
</div>
<div class="preset-info">
<div class="info-item">
<span class="info-label">Delay:</span>
<span class="info-value">30ms</span>
</div>
<div class="info-item">
<span class="info-label">N1:</span>
<span class="info-value">10</span>
</div>
</div>
<div class="preset-actions">
<button class="btn btn-primary" onclick="applyPreset('Fast Rainbow')">Apply</button>
<button class="btn btn-secondary btn-icon" onclick="editPreset('Fast Rainbow')" title="Edit">✏️</button>
<button class="btn btn-danger btn-icon" onclick="deletePreset('Fast Rainbow')" title="Delete">🗑️</button>
</div>
</div>
<!-- Preset Card 2 -->
<div class="preset-card" data-pattern="pulse" data-name="Slow Pulse">
<div class="preset-header">
<div>
<div class="preset-name">Slow Pulse</div>
<span class="pattern-badge pulse">Pulse</span>
</div>
</div>
<div class="color-preview">
<div class="color-swatch" style="background: #FF0000;"></div>
<div class="color-swatch" style="background: #0000FF;"></div>
</div>
<div class="preset-info">
<div class="info-item">
<span class="info-label">Delay:</span>
<span class="info-value">200ms</span>
</div>
<div class="info-item">
<span class="info-label">N1:</span>
<span class="info-value">500</span>
</div>
</div>
<div class="preset-actions">
<button class="btn btn-primary" onclick="applyPreset('Slow Pulse')">Apply</button>
<button class="btn btn-secondary btn-icon" onclick="editPreset('Slow Pulse')" title="Edit">✏️</button>
<button class="btn btn-danger btn-icon" onclick="deletePreset('Slow Pulse')" title="Delete">🗑️</button>
</div>
</div>
<!-- Preset Card 3 -->
<div class="preset-card" data-pattern="chase" data-name="Red Blue Chase">
<div class="preset-header">
<div>
<div class="preset-name">Red Blue Chase</div>
<span class="pattern-badge chase">Chase</span>
</div>
</div>
<div class="color-preview">
<div class="color-swatch" style="background: #FF0000;"></div>
<div class="color-swatch" style="background: #0000FF;"></div>
</div>
<div class="preset-info">
<div class="info-item">
<span class="info-label">Delay:</span>
<span class="info-value">100ms</span>
</div>
<div class="info-item">
<span class="info-label">N1:</span>
<span class="info-value">5</span>
</div>
</div>
<div class="preset-actions">
<button class="btn btn-primary" onclick="applyPreset('Red Blue Chase')">Apply</button>
<button class="btn btn-secondary btn-icon" onclick="editPreset('Red Blue Chase')" title="Edit">✏️</button>
<button class="btn btn-danger btn-icon" onclick="deletePreset('Red Blue Chase')" title="Delete">🗑️</button>
</div>
</div>
<!-- Preset Card 4 -->
<div class="preset-card" data-pattern="circle" data-name="Loading Circle">
<div class="preset-header">
<div>
<div class="preset-name">Loading Circle</div>
<span class="pattern-badge circle">Circle</span>
</div>
</div>
<div class="color-preview">
<div class="color-swatch" style="background: #00FF00;"></div>
</div>
<div class="preset-info">
<div class="info-item">
<span class="info-label">Delay:</span>
<span class="info-value">50ms</span>
</div>
<div class="info-item">
<span class="info-label">N1:</span>
<span class="info-value">50</span>
</div>
</div>
<div class="preset-actions">
<button class="btn btn-primary" onclick="applyPreset('Loading Circle')">Apply</button>
<button class="btn btn-secondary btn-icon" onclick="editPreset('Loading Circle')" title="Edit">✏️</button>
<button class="btn btn-danger btn-icon" onclick="deletePreset('Loading Circle')" title="Delete">🗑️</button>
</div>
</div>
<!-- Preset Card 5 -->
<div class="preset-card" data-pattern="blink" data-name="Party Blink">
<div class="preset-header">
<div>
<div class="preset-name">Party Blink</div>
<span class="pattern-badge blink">Blink</span>
</div>
</div>
<div class="color-preview">
<div class="color-swatch" style="background: #FF00FF;"></div>
<div class="color-swatch" style="background: #00FFFF;"></div>
<div class="color-swatch" style="background: #FFFF00;"></div>
</div>
<div class="preset-info">
<div class="info-item">
<span class="info-label">Delay:</span>
<span class="info-value">150ms</span>
</div>
<div class="info-item">
<span class="info-label">N1:</span>
<span class="info-value">0</span>
</div>
</div>
<div class="preset-actions">
<button class="btn btn-primary" onclick="applyPreset('Party Blink')">Apply</button>
<button class="btn btn-secondary btn-icon" onclick="editPreset('Party Blink')" title="Edit">✏️</button>
<button class="btn btn-danger btn-icon" onclick="deletePreset('Party Blink')" title="Delete">🗑️</button>
</div>
</div>
<!-- Preset Card 6 -->
<div class="preset-card" data-pattern="transition" data-name="Smooth Transition">
<div class="preset-header">
<div>
<div class="preset-name">Smooth Transition</div>
<span class="pattern-badge transition">Transition</span>
</div>
</div>
<div class="color-preview">
<div class="color-swatch" style="background: #FF0000;"></div>
<div class="color-swatch" style="background: #00FF00;"></div>
<div class="color-swatch" style="background: #0000FF;"></div>
<div class="color-swatch" style="background: #FFFF00;"></div>
</div>
<div class="preset-info">
<div class="info-item">
<span class="info-label">Delay:</span>
<span class="info-value">100ms</span>
</div>
<div class="info-item">
<span class="info-label">N1:</span>
<span class="info-value">0</span>
</div>
</div>
<div class="preset-actions">
<button class="btn btn-primary" onclick="applyPreset('Smooth Transition')">Apply</button>
<button class="btn btn-secondary btn-icon" onclick="editPreset('Smooth Transition')" title="Edit">✏️</button>
<button class="btn btn-danger btn-icon" onclick="deletePreset('Smooth Transition')" title="Delete">🗑️</button>
</div>
</div>
</div>
</div>
<!-- Create/Edit Preset Modal -->
<div class="modal" id="preset-modal">
<div class="modal-content">
<div class="modal-header">
<h2 id="modal-title">Create Preset</h2>
<p>Configure your preset settings</p>
</div>
<form id="preset-form">
<div class="form-group">
<label for="preset-name">Preset Name *</label>
<input type="text" id="preset-name" required placeholder="Enter preset name">
<small>Unique identifier for this preset</small>
</div>
<div class="form-group">
<label for="preset-pattern">Pattern *</label>
<select id="preset-pattern" required>
<option value="on">On</option>
<option value="off">Off</option>
<option value="blink">Blink</option>
<option value="chase">Chase</option>
<option value="circle">Circle</option>
<option value="pulse">Pulse</option>
<option value="rainbow">Rainbow</option>
<option value="transition">Transition</option>
</select>
</div>
<div class="form-group">
<label>Colors *</label>
<div class="color-inputs" id="color-inputs">
<!-- Color pickers will be added here -->
</div>
<button type="button" class="btn btn-secondary" onclick="addColorPicker()" style="margin-top: 8px;">+ Add Color</button>
<small>Minimum 2 colors required</small>
</div>
<div class="form-group">
<label for="preset-delay">
Delay (ms) *
<span id="delay-value-display" style="margin-left: 12px; color: #667eea; font-weight: 600;">100</span>
</label>
<input type="range" id="preset-delay" min="10" max="1000" value="100" step="10" required>
<small>Animation speed (10-1000 milliseconds)</small>
</div>
<div class="form-group">
<label for="step-offset">Step Offset</label>
<input type="number" id="step-offset" value="0" min="-1000" max="1000">
<small>Step offset for group synchronization. Applied per device when preset is used in a group.</small>
</div>
<div class="form-group">
<label for="step-increment">Step Increment</label>
<input type="number" id="step-increment" value="1" min="1" max="255">
<small>Amount step counter increments per cycle. Controls pattern advancement speed.</small>
</div>
<div class="form-group">
<label>Pattern Parameters (N1-N8)</label>
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
<small style="margin: 0;">Pattern-specific parameters (0-255, varies by pattern)</small>
<button type="button" class="btn btn-secondary" onclick="setAllNValues(0)" style="padding: 6px 12px; font-size: 0.75rem;">Reset All to 0</button>
</div>
<div class="params-grid">
<div class="param-input">
<label>N1</label>
<input type="number" id="n1" min="0" max="255" value="0" class="n-value-input">
</div>
<div class="param-input">
<label>N2</label>
<input type="number" id="n2" min="0" max="255" value="0" class="n-value-input">
</div>
<div class="param-input">
<label>N3</label>
<input type="number" id="n3" min="0" max="255" value="0" class="n-value-input">
</div>
<div class="param-input">
<label>N4</label>
<input type="number" id="n4" min="0" max="255" value="0" class="n-value-input">
</div>
<div class="param-input">
<label>N5</label>
<input type="number" id="n5" min="0" max="255" value="0" class="n-value-input">
</div>
<div class="param-input">
<label>N6</label>
<input type="number" id="n6" min="0" max="255" value="0" class="n-value-input">
</div>
<div class="param-input">
<label>N7</label>
<input type="number" id="n7" min="0" max="255" value="0" class="n-value-input">
</div>
<div class="param-input">
<label>N8</label>
<input type="number" id="n8" min="0" max="255" value="0" class="n-value-input">
</div>
</div>
<div style="margin-top: 12px; display: flex; gap: 8px; flex-wrap: wrap;">
<button type="button" class="btn btn-secondary" onclick="setAllNValues(0)" style="padding: 8px 16px; font-size: 0.875rem;">Set All to 0</button>
<button type="button" class="btn btn-secondary" onclick="copyNValuesFromCurrent()" style="padding: 8px 16px; font-size: 0.875rem;">Copy from Current Settings</button>
<button type="button" class="btn btn-secondary" onclick="showNValueHelp()" style="padding: 8px 16px; font-size: 0.875rem;">ℹ️ Parameter Help</button>
</div>
</div>
<div class="modal-actions">
<button type="button" class="btn btn-secondary" onclick="closeModal()">Cancel</button>
<button type="submit" class="btn btn-primary">Save Preset</button>
</div>
</form>
</div>
</div>
<script>
let currentView = 'grid';
let editingPreset = null;
// Delay slider update
document.getElementById('preset-delay').addEventListener('input', function(e) {
document.getElementById('delay-value-display').textContent = e.target.value;
});
// Search functionality
document.getElementById('search-input').addEventListener('input', function(e) {
filterPresets();
});
// Filter functionality
document.getElementById('pattern-filter').addEventListener('change', function(e) {
filterPresets();
});
// Sort functionality
document.getElementById('sort-select').addEventListener('change', function(e) {
sortPresets(e.target.value);
});
function filterPresets() {
const search = document.getElementById('search-input').value.toLowerCase();
const patternFilter = document.getElementById('pattern-filter').value;
const cards = document.querySelectorAll('.preset-card');
cards.forEach(card => {
const name = card.dataset.name.toLowerCase();
const pattern = card.dataset.pattern;
const matchesSearch = name.includes(search);
const matchesPattern = !patternFilter || pattern === patternFilter;
if (matchesSearch && matchesPattern) {
card.style.display = '';
} else {
card.style.display = 'none';
}
});
}
function sortPresets(sortBy) {
const container = document.getElementById('presets-container');
const cards = Array.from(container.querySelectorAll('.preset-card'));
cards.sort((a, b) => {
if (sortBy === 'name') {
return a.dataset.name.localeCompare(b.dataset.name);
} else if (sortBy === 'recent') {
// In real implementation, would use actual usage data
return 0;
} else if (sortBy === 'created') {
// In real implementation, would use creation timestamps
return 0;
}
return 0;
});
cards.forEach(card => container.appendChild(card));
}
function setView(view) {
currentView = view;
const container = document.getElementById('presets-container');
const gridBtn = document.getElementById('view-grid');
const listBtn = document.getElementById('view-list');
if (view === 'grid') {
container.style.gridTemplateColumns = 'repeat(auto-fill, minmax(300px, 1fr))';
gridBtn.classList.add('active');
listBtn.classList.remove('active');
} else {
container.style.gridTemplateColumns = '1fr';
gridBtn.classList.remove('active');
listBtn.classList.add('active');
}
}
function showCreateModal() {
editingPreset = null;
document.getElementById('modal-title').textContent = 'Create Preset';
document.getElementById('preset-form').reset();
document.getElementById('preset-delay').value = 100;
document.getElementById('delay-value-display').textContent = '100';
// Reset to 2 colors
initializeColorPickers();
document.getElementById('preset-modal').classList.add('active');
}
// Initialize color pickers function (defined before showCreateModal)
const presetColorPickers = [];
function initializeColorPickers() {
const colorInputs = document.getElementById('color-inputs');
colorInputs.innerHTML = '';
presetColorPickers.length = 0;
addColorPicker('#FF0000');
addColorPicker('#0000FF');
}
function addColorPicker(color = '#00FF00') {
const colorInputs = document.getElementById('color-inputs');
const wrapper = document.createElement('div');
wrapper.className = 'color-input-wrapper';
colorInputs.appendChild(wrapper);
const picker = new ColorPicker(wrapper, {
initialColor: color,
onColorChange: (newColor) => {
console.log('Preset color changed:', newColor);
}
});
presetColorPickers.push(picker);
return picker;
}
function editPreset(name) {
editingPreset = name;
document.getElementById('modal-title').textContent = 'Edit Preset';
// In real implementation, would load preset data
document.getElementById('preset-name').value = name;
document.getElementById('preset-modal').classList.add('active');
}
function closeModal() {
document.getElementById('preset-modal').classList.remove('active');
editingPreset = null;
}
function applyPreset(name) {
alert(`Applying preset: ${name}\n(In real implementation, this would send preset configuration to device(s))`);
}
function deletePreset(name) {
if (confirm(`Delete preset "${name}"?`)) {
alert(`Preset "${name}" deleted\n(In real implementation, this would remove the preset from storage)`);
}
}
function syncPresets() {
if (confirm('Sync all presets to all devices?\nThis will send all presets from master to all devices via ESPNow.')) {
alert('Syncing presets to all devices...\n(In real implementation, this would send all presets via ESPNow to all devices)');
}
}
function setAllNValues(value) {
for (let i = 1; i <= 8; i++) {
document.getElementById(`n${i}`).value = value;
}
}
function copyNValuesFromCurrent() {
// In real implementation, this would copy from current device settings
alert('Copying N values from current device settings...\n(In real implementation, this would load current N1-N8 values from the active device)');
// Example: would set values like this:
// document.getElementById('n1').value = currentSettings.n1;
// ... etc
}
function showNValueHelp() {
const helpText = `
Pattern Parameter Guide:
Rainbow:
N1: Step increment (1-255, default: 1)
Pulse:
N1: Attack time in ms (0-255)
N2: Hold time in ms (0-255)
N3: Decay time in ms (0-255)
Chase:
N1: LEDs of color 0 (1-255)
N2: LEDs of color 1 (1-255)
N3: Step movement on odd steps (can be negative)
N4: Step movement on even steps (can be negative)
Circle:
N1: Head moves per second (1-255)
N2: Max length in LEDs (1-255)
N3: Tail moves per second (1-255)
N4: Min length in LEDs (0-255)
Other patterns:
N1-N8: Reserved for future pattern enhancements
All values range from 0-255 unless otherwise specified.
`;
alert(helpText);
}
// Form submission
document.getElementById('preset-form').addEventListener('submit', function(e) {
e.preventDefault();
const name = document.getElementById('preset-name').value;
const action = editingPreset ? 'updated' : 'created';
alert(`Preset "${name}" ${action}!\n(In real implementation, this would save the preset to storage)`);
closeModal();
});
// Close modal on outside click
document.getElementById('preset-modal').addEventListener('click', function(e) {
if (e.target === this) {
closeModal();
}
});
</script>
<script src="color-picker.js"></script>
</body>
</html>
+491
View File
@@ -0,0 +1,491 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LED Driver - Settings</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 1000px;
margin: 0 auto;
}
.header {
background: white;
border-radius: 12px;
padding: 24px;
margin-bottom: 24px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.header h1 {
color: #667eea;
margin-bottom: 8px;
}
.header p {
color: #666;
}
.card {
background: white;
border-radius: 12px;
padding: 24px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
margin-bottom: 24px;
}
.card h2 {
color: #667eea;
margin-bottom: 20px;
font-size: 1.5rem;
border-bottom: 2px solid #e0e0e0;
padding-bottom: 12px;
}
.form-group {
margin-bottom: 24px;
}
.form-group label {
display: block;
margin-bottom: 8px;
font-weight: 500;
color: #333;
}
.form-group input[type="text"],
.form-group input[type="number"],
.form-group input[type="password"],
.form-group select {
width: 100%;
padding: 12px;
border: 1px solid #e0e0e0;
border-radius: 8px;
font-size: 1rem;
transition: border-color 0.2s;
}
.form-group input:focus,
.form-group select:focus {
outline: none;
border-color: #667eea;
}
.form-group input[type="range"] {
width: 100%;
height: 8px;
border-radius: 4px;
background: #e0e0e0;
outline: none;
-webkit-appearance: none;
}
.form-group input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 20px;
height: 20px;
border-radius: 50%;
background: #667eea;
cursor: pointer;
}
.form-group input[type="range"]::-moz-range-thumb {
width: 20px;
height: 20px;
border-radius: 50%;
background: #667eea;
cursor: pointer;
border: none;
}
.value-display {
display: inline-block;
margin-left: 12px;
font-weight: 600;
color: #667eea;
min-width: 60px;
}
.form-group small {
display: block;
margin-top: 4px;
color: #666;
font-size: 0.875rem;
}
.checkbox-group {
display: flex;
align-items: center;
gap: 12px;
}
.checkbox-group input[type="checkbox"] {
width: 20px;
height: 20px;
cursor: pointer;
}
.color-order {
display: flex;
gap: 12px;
flex-wrap: wrap;
}
.color-order-option {
flex: 1;
min-width: 120px;
padding: 12px;
border: 2px solid #e0e0e0;
border-radius: 8px;
text-align: center;
cursor: pointer;
transition: all 0.2s;
}
.color-order-option:hover {
border-color: #667eea;
}
.color-order-option.selected {
border-color: #667eea;
background: #667eea;
color: white;
}
.color-order-option .color-boxes {
display: flex;
justify-content: center;
gap: 4px;
margin-top: 8px;
}
.color-box {
width: 30px;
height: 30px;
border-radius: 4px;
}
.color-box.r { background: #ff0000; }
.color-box.g { background: #00ff00; }
.color-box.b { background: #0000ff; }
.actions {
display: flex;
gap: 12px;
margin-top: 32px;
padding-top: 24px;
border-top: 2px solid #e0e0e0;
}
.btn {
padding: 12px 24px;
border: none;
border-radius: 8px;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover {
background: #5568d3;
}
.btn-secondary {
background: #e0e0e0;
color: #333;
}
.btn-secondary:hover {
background: #d0d0d0;
}
.btn-danger {
background: #f44336;
color: white;
}
.btn-danger:hover {
background: #d32f2f;
}
.btn-full {
flex: 1;
}
.section-divider {
height: 1px;
background: #e0e0e0;
margin: 24px 0;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Device Settings</h1>
<p>Configure your LED driver device settings</p>
</div>
<!-- Basic Settings -->
<div class="card">
<h2>Basic Settings</h2>
<div class="form-group">
<label>Device Name</label>
<input type="text" id="device-name" value="led-device1" placeholder="led-device1">
<small>Unique identifier for this device</small>
</div>
<div class="form-group">
<label>LED Pin</label>
<input type="number" id="led-pin" value="10" min="0" max="40">
<small>GPIO pin number connected to LED data line</small>
</div>
<div class="form-group">
<label>Number of LEDs</label>
<input type="number" id="num-leds" value="50" min="1" max="1000">
<small>Total number of LEDs in your strip</small>
</div>
<div class="form-group">
<label>Color Order</label>
<div class="color-order">
<div class="color-order-option selected" data-order="rgb">
RGB
<div class="color-boxes">
<div class="color-box r"></div>
<div class="color-box g"></div>
<div class="color-box b"></div>
</div>
</div>
<div class="color-order-option" data-order="rbg">
RBG
<div class="color-boxes">
<div class="color-box r"></div>
<div class="color-box b"></div>
<div class="color-box g"></div>
</div>
</div>
<div class="color-order-option" data-order="grb">
GRB
<div class="color-boxes">
<div class="color-box g"></div>
<div class="color-box r"></div>
<div class="color-box b"></div>
</div>
</div>
<div class="color-order-option" data-order="gbr">
GBR
<div class="color-boxes">
<div class="color-box g"></div>
<div class="color-box b"></div>
<div class="color-box r"></div>
</div>
</div>
<div class="color-order-option" data-order="brg">
BRG
<div class="color-boxes">
<div class="color-box b"></div>
<div class="color-box r"></div>
<div class="color-box g"></div>
</div>
</div>
<div class="color-order-option" data-order="bgr">
BGR
<div class="color-boxes">
<div class="color-box b"></div>
<div class="color-box g"></div>
<div class="color-box r"></div>
</div>
</div>
</div>
</div>
</div>
<!-- Pattern Settings -->
<div class="card">
<h2>Pattern Settings</h2>
<div class="form-group">
<label>Pattern</label>
<select id="pattern">
<option value="on">On</option>
<option value="off">Off</option>
<option value="blink">Blink</option>
<option value="chase">Chase</option>
<option value="circle">Circle</option>
<option value="pulse">Pulse</option>
<option value="rainbow">Rainbow</option>
<option value="transition">Transition</option>
</select>
</div>
<div class="form-group">
<label>
Brightness
<span class="value-display" id="brightness-value">100</span>%
</label>
<input type="range" id="brightness" min="0" max="100" value="100">
</div>
<div class="form-group">
<label>
Delay
<span class="value-display" id="delay-value">100</span>ms
</label>
<input type="range" id="delay" min="10" max="1000" value="100" step="10">
</div>
</div>
<!-- Advanced Settings -->
<div class="card">
<h2>Advanced Settings</h2>
<div class="form-group">
<label>Step Counter</label>
<input type="text" id="step-counter" value="0" readonly style="background: #f5f5f5; cursor: not-allowed;">
<small>Current step position in pattern (read-only)</small>
</div>
<div class="form-group">
<label for="step-increment">
Step Increment
</label>
<input type="number" id="step-increment" value="1" min="1" max="255">
<small>Amount step counter increments per cycle. Controls pattern advancement speed.</small>
</div>
<div class="form-group">
<label>Pattern Parameters</label>
<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px;">
<div>
<label style="font-size: 0.875rem;">N1</label>
<input type="number" id="n1" value="0" min="0" max="255">
</div>
<div>
<label style="font-size: 0.875rem;">N2</label>
<input type="number" id="n2" value="0" min="0" max="255">
</div>
<div>
<label style="font-size: 0.875rem;">N3</label>
<input type="number" id="n3" value="0" min="0" max="255">
</div>
<div>
<label style="font-size: 0.875rem;">N4</label>
<input type="number" id="n4" value="0" min="0" max="255">
</div>
<div>
<label style="font-size: 0.875rem;">N5</label>
<input type="number" id="n5" value="0" min="0" max="255">
</div>
<div>
<label style="font-size: 0.875rem;">N6</label>
<input type="number" id="n6" value="0" min="0" max="255">
</div>
</div>
<small>Pattern-specific parameters (varies by pattern)</small>
</div>
<div class="form-group">
<label>Device ID</label>
<input type="number" id="device-id" value="1" min="0">
<small>Unique numeric identifier</small>
</div>
<div class="form-group">
<div class="checkbox-group">
<input type="checkbox" id="debug" checked>
<label for="debug" style="margin: 0;">Debug Mode</label>
</div>
<small>Enable debug logging</small>
</div>
</div>
<!-- Network Settings -->
<div class="card">
<h2>Network Settings</h2>
<div class="form-group">
<label>Access Point Name</label>
<input type="text" id="ap-name" value="led-AA:BB:CC:DD:EE:01" placeholder="led-device">
<small>WiFi access point name for device configuration</small>
</div>
<div class="form-group">
<label>Access Point Password</label>
<input type="password" id="ap-password" placeholder="Leave empty for open network">
<small>Password for the access point (optional)</small>
</div>
<div class="form-group">
<div class="checkbox-group">
<input type="checkbox" id="ap-enabled" checked>
<label for="ap-enabled" style="margin: 0;">Enable Access Point</label>
</div>
<small>Allow device to create its own WiFi network</small>
</div>
</div>
<!-- Actions -->
<div class="card">
<div class="actions">
<button class="btn btn-secondary btn-full" onclick="resetSettings()">Reset to Defaults</button>
<button class="btn btn-primary btn-full" onclick="saveSettings()">Save Settings</button>
</div>
</div>
</div>
<script>
// Brightness slider
document.getElementById('brightness').addEventListener('input', function(e) {
document.getElementById('brightness-value').textContent = e.target.value;
});
// Delay slider
document.getElementById('delay').addEventListener('input', function(e) {
document.getElementById('delay-value').textContent = e.target.value;
});
// Color order selection
document.querySelectorAll('.color-order-option').forEach(option => {
option.addEventListener('click', function() {
document.querySelectorAll('.color-order-option').forEach(o => o.classList.remove('selected'));
this.classList.add('selected');
});
});
function saveSettings() {
alert('Settings saved! (This is a mockup)');
}
function resetSettings() {
if (confirm('Reset all settings to defaults?')) {
alert('Settings reset! (This is a mockup)');
}
}
</script>
</body>
</html>
+23
View File
@@ -0,0 +1,23 @@
{
"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
}
Submodule
+1
Submodule led-driver added at 428ed8b884
Submodule
+1
Submodule led-tool added at 713cd6e9a1
+2
View File
@@ -0,0 +1,2 @@
from microdot.microdot import Microdot, Request, Response, abort, redirect, \
send_file # noqa: F401
+8
View File
@@ -0,0 +1,8 @@
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 _
File diff suppressed because it is too large Load Diff
+225
View File
@@ -0,0 +1,225 @@
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()
<microdot.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() <microdot.session.SessionDict.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
+70
View File
@@ -0,0 +1,70 @@
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
+231
View File
@@ -0,0 +1,231 @@
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)
+14
View File
@@ -0,0 +1,14 @@
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
+21
View File
@@ -0,0 +1,21 @@
# (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)
+188
View File
@@ -0,0 +1,188 @@
# (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)
-20
View File
@@ -1,20 +0,0 @@
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from api.routes import router
import uvicorn
app = FastAPI(title="Bar Control System", version="1.0.0")
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
app.include_router(router)
@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000, reload=True)
+3
View File
@@ -0,0 +1,3 @@
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_endpoints_pytest.py"]
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env sh
# Build docs/help.pdf from docs/help.md.
# Requires: pandoc, chromium (headless print-to-PDF).
set -eu
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
# HTML next to docs/help.md so relative image paths (e.g. images/help/*.svg) resolve.
HTML="$ROOT/docs/.help-print.html"
trap 'rm -f "$HTML"' EXIT
pandoc "$ROOT/docs/help.md" -s \
--css="$ROOT/scripts/help-pdf.css" \
--metadata title="LED controller — user guide" \
-o "$HTML"
chromium --headless --no-sandbox --disable-gpu \
--print-to-pdf="$ROOT/docs/help.pdf" \
"file://${HTML}"
echo "Wrote $ROOT/docs/help.pdf ($(wc -c < "$ROOT/docs/help.pdf") bytes)"
+96
View File
@@ -0,0 +1,96 @@
/* Print stylesheet for docs/help.md → PDF (Chromium headless) */
@page {
margin: 18mm;
size: A4;
}
html {
font-size: 11pt;
line-height: 1.4;
}
body {
font-family: "DejaVu Sans", "Liberation Sans", Helvetica, Arial, sans-serif;
color: #222;
max-width: 100%;
}
h1 {
font-size: 1.45rem;
border-bottom: 2px solid #333;
padding-bottom: 0.25em;
margin-top: 0;
}
h2 {
font-size: 1.15rem;
margin-top: 1.25em;
page-break-after: avoid;
}
h3 {
font-size: 1.05rem;
margin-top: 1em;
page-break-after: avoid;
}
code {
font-family: "DejaVu Sans Mono", "Liberation Mono", Consolas, monospace;
font-size: 0.92em;
background: #f3f3f3;
padding: 0.1em 0.35em;
border-radius: 3px;
}
pre {
font-family: "DejaVu Sans Mono", "Liberation Mono", Consolas, monospace;
font-size: 0.88em;
background: #f5f5f5;
border: 1px solid #ddd;
padding: 0.65em 0.85em;
overflow-x: auto;
page-break-inside: avoid;
}
pre code {
background: none;
padding: 0;
}
table {
border-collapse: collapse;
width: 100%;
margin: 0.75em 0;
font-size: 0.95em;
page-break-inside: avoid;
}
th, td {
border: 1px solid #bbb;
padding: 6px 8px;
text-align: left;
vertical-align: top;
}
th {
background: #eee;
}
a {
color: #1a5276;
text-decoration: none;
}
hr {
border: none;
border-top: 1px solid #ccc;
margin: 1.25em 0;
}
ul, ol {
padding-left: 1.35em;
}
li {
margin: 0.2em 0;
}
/* Images in docs/help.md */
img {
max-width: 100%;
height: auto;
page-break-inside: avoid;
border: 1px solid #ccc;
border-radius: 4px;
}
p.help-figure-caption {
font-size: 0.9em;
color: #555;
margin: 0.35em 0 1em 0;
line-height: 1.35;
}
+20
View File
@@ -0,0 +1,20 @@
#!/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
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"
+17
View File
@@ -0,0 +1,17 @@
[Unit]
Description=LED Controller web server
After=network-online.target
Wants=network-online.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
[Install]
WantedBy=multi-user.target
+35
View File
@@ -0,0 +1,35 @@
#!/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
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
# Start the LED controller web server (port 80 by default).
cd "$(dirname "$0")/.."
export PORT="${PORT:-80}"
pipenv run run
+33
View File
@@ -0,0 +1,33 @@
#!/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
-20
View File
@@ -1,20 +0,0 @@
{
"dj": {
"url": "ws://192.168.4.1/ws",
"color": "#1d011e",
"x": 614,
"y": 123
},
"bar2": {
"url": "ws://192.168.4.1/ws",
"color": "#3d0f00",
"x": 616,
"y": 330
},
"bar5": {
"url": "ws://192.168.4.1/ws",
"color": "#300d2a",
"x": 618,
"y": 567
}
}
+6
View File
@@ -0,0 +1,6 @@
# 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.
+1
View File
@@ -0,0 +1 @@
# Controllers package
+393
View File
@@ -0,0 +1,393 @@
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("/<id>")
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("/<id>")
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("/<id>")
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("/<id>/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("/<id>/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",
}
+50
View File
@@ -0,0 +1,50 @@
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('/<id>')
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('/<id>')
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('/<id>')
async def delete_group(request, id):
"""Delete a group."""
if groups.delete(id):
return json.dumps({"message": "Group deleted successfully"}), 200
return json.dumps({"error": "Group not found"}), 404
+189
View File
@@ -0,0 +1,189 @@
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
+58
View File
@@ -0,0 +1,58 @@
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('/<id>')
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('/<id>')
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('/<id>')
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
+500
View File
@@ -0,0 +1,500 @@
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/<name>')
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('/<name>/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('/<id>')
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('/<id>')
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('/<id>')
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
+322
View File
@@ -0,0 +1,322 @@
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('/<preset_id>')
@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('/<preset_id>')
@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('/<preset_id>')
@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'}
+390
View File
@@ -0,0 +1,390 @@
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('/<id>')
@with_session
async def get_profile(request, id, session):
"""Get a specific profile by ID."""
# Handle 'current' as a special case
if id == 'current':
return await get_current_profile(request, session)
profile = profiles.read(id)
if profile:
return json.dumps(profile), 200, {'Content-Type': 'application/json'}
return json.dumps({"error": "Profile not found"}), 404
@controller.post('/<id>/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('/<id>/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('/<id>')
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('/<id>')
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
+49
View File
@@ -0,0 +1,49 @@
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('/<id>')
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('/<id>')
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('/<id>')
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
+51
View File
@@ -0,0 +1,51 @@
from microdot import Microdot
from models.squence import Sequence
import json
controller = Microdot()
sequences = Sequence()
@controller.get('')
async def list_sequences(request):
"""List all sequences."""
return json.dumps(sequences), 200, {'Content-Type': 'application/json'}
@controller.get('/<id>')
async def get_sequence(request, id):
"""Get a specific sequence by ID."""
sequence = sequences.read(id)
if sequence:
return json.dumps(sequence), 200, {'Content-Type': 'application/json'}
return json.dumps({"error": "Sequence not found"}), 404
@controller.post('')
async def create_sequence(request):
"""Create a new sequence."""
try:
data = request.json or {}
group_name = data.get("group_name", "")
preset_names = data.get("presets", None)
sequence_id = sequences.create(group_name, preset_names)
if data:
sequences.update(sequence_id, data)
return json.dumps(sequences.read(sequence_id)), 201, {'Content-Type': 'application/json'}
except Exception as e:
return json.dumps({"error": str(e)}), 400
@controller.put('/<id>')
async def update_sequence(request, id):
"""Update an existing sequence."""
try:
data = request.json
if sequences.update(id, data):
return json.dumps(sequences.read(id)), 200, {'Content-Type': 'application/json'}
return json.dumps({"error": "Sequence not found"}), 404
except Exception as e:
return json.dumps({"error": str(e)}), 400
@controller.delete('/<id>')
async def delete_sequence(request, id):
"""Delete a sequence."""
if sequences.delete(id):
return json.dumps({"message": "Sequence deleted successfully"}), 200
return json.dumps({"error": "Sequence not found"}), 404
+87
View File
@@ -0,0 +1,87 @@
from microdot import Microdot, send_file
from settings import Settings
import json
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
@controller.put('/settings')
async def update_settings(request):
"""Update general settings."""
try:
data = request.json
for key, value in data.items():
if key == 'wifi_channel' and value is not None:
settings[key] = _validate_wifi_channel(value)
else:
settings[key] = value
settings.save()
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')
+361
View File
@@ -0,0 +1,361 @@
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 (
'<div class="zones-list">No profile selected</div>',
200,
{"Content-Type": "text/html"},
)
zone_order = get_profile_zone_order(profile_id)
current_zone_id = get_current_zone_id(request, session)
html = '<div class="zones-list">'
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 += (
'<button class="zone-button ' + active_class + '" '
'hx-get="/zones/' + str(zid) + '/content-fragment" '
'hx-target="#zone-content" '
'hx-swap="innerHTML" '
'hx-push-url="true" '
'hx-trigger="click" '
'onclick="document.querySelectorAll(\'.zone-button\').forEach(b => b.classList.remove(\'active\')); this.classList.add(\'active\');">'
+ zname
+ "</button>"
)
html += "</div>"
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 (
'<div class="error">No current zone set</div>',
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 '<div>Zone not found</div>', 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 = (
'<div class="presets-section" data-zone-id="' + str(id) + '">'
"<h3>Presets</h3>"
'<div class="profiles-actions" style="margin-bottom: 1rem;"></div>'
'<div id="presets-list-zone" class="presets-list">'
"<!-- Presets will be loaded here -->"
"</div>"
"</div>"
)
return html, 200, {"Content-Type": "text/html"}
@controller.get("/<id>/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("/<id>/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("/<id>")
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("/<id>")
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("/<id>")
@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("/<id>/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
+413
View File
@@ -0,0 +1,413 @@
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
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'),
]
# 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')
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')
# Serve settings page
@app.route('/settings')
def settings_page(request):
"""Serve the settings page."""
return send_file('templates/settings.html')
# Favicon: avoid 404 in browser console (no file needed)
@app.route('/favicon.ico')
def favicon(request):
return '', 204
# Static file route
@app.route("/static/<path:path>")
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()
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:
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))
+1
View File
@@ -0,0 +1 @@
# Models package
+285
View File
@@ -0,0 +1,285 @@
"""
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
+51
View File
@@ -0,0 +1,51 @@
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())
+125
View File
@@ -0,0 +1,125 @@
"""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
+113
View File
@@ -0,0 +1,113 @@
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()
+45
View File
@@ -0,0 +1,45 @@
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())
+38
View File
@@ -0,0 +1,38 @@
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())
+69
View File
@@ -0,0 +1,69 @@
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())

Some files were not shown because too many files have changed in this diff Show More