Compare commits
9
Commits
a5a7fc575f
...
71bd320661
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
71bd320661 | ||
|
|
6c16998691 | ||
|
|
8d78af1246 | ||
|
|
899d4f2418 | ||
|
|
f7ac4ab290 | ||
|
|
d332d447aa | ||
|
|
a94d6a7de5 | ||
|
|
7336c7fb22 | ||
|
|
3a7723c586 |
No files matched your search
@@ -0,0 +1,98 @@
|
||||
# Build, flash and monitor the v2 ESP32-S3 controller (ESP-IDF in Docker).
|
||||
#
|
||||
# make list the targets
|
||||
# make build minify the web UI, then build the firmware
|
||||
# make flash build if needed and flash the S3
|
||||
# make monitor serial console (Ctrl-] to quit)
|
||||
# make flash-monitor
|
||||
#
|
||||
# Override on the command line, e.g. make flash PORT=/dev/ttyACM1
|
||||
|
||||
PORT ?= /dev/ttyACM0
|
||||
IDF_IMAGE ?= espressif/idf:v5.5.5
|
||||
SECS ?= 10
|
||||
V2 := v2
|
||||
|
||||
DOCKER_RUN = docker run --rm -v "$(CURDIR)/$(V2)":/project -w /project
|
||||
DEVICE = --device=$(PORT)
|
||||
# Interactive terminal only when there is one (monitor needs it, CI does not have it)
|
||||
TTY := $(shell [ -t 0 ] && echo -it)
|
||||
|
||||
# Rootless Docker maps container root to you, so files must end up owned by uid 0 inside; with a
|
||||
# normal daemon they must be owned by you.
|
||||
OWNER := $(shell docker info --format '{{.SecurityOptions}}' 2>/dev/null | grep -q rootless && echo 0:0 || echo $$(id -u):$$(id -g))
|
||||
FIX_OWNER = chown -R $(OWNER) /project
|
||||
|
||||
.PHONY: help web build flash ota monitor flash-monitor log size menuconfig clean fullclean erase test test-driver test-envelope
|
||||
|
||||
help:
|
||||
@echo "v2 controller (ESP32-S3):"
|
||||
@echo " make build minify + gzip the web UI, then build the firmware"
|
||||
@echo " make flash flash firmware and web UI to PORT ($(PORT))"
|
||||
@echo " make ota HOST=ip build, then upload the firmware (web UI included) over Ethernet (no USB)"
|
||||
@echo " make monitor serial console on PORT (Ctrl-] to quit)"
|
||||
@echo " make flash-monitor flash, then open the console"
|
||||
@echo " make log [SECS=10] print the console for SECS seconds and exit (no terminal needed)"
|
||||
@echo " make web only rebuild the web UI (needs node/npx)"
|
||||
@echo " make size memory use of the last build"
|
||||
@echo " make menuconfig change the ESP-NOW channel, marker pin, W5500 pins, ..."
|
||||
@echo " make erase erase the whole flash (loses the stored data)"
|
||||
@echo " make clean remove the build directory (keeps sdkconfig)"
|
||||
@echo " make fullclean also remove sdkconfig and the web UI output"
|
||||
@echo " make test driver unit tests + C/Python envelope cross-check"
|
||||
@echo "variables: PORT=$(PORT) IDF_IMAGE=$(IDF_IMAGE)"
|
||||
|
||||
# --- web UI ---------------------------------------------------------------
|
||||
web:
|
||||
cd $(V2) && tools/build_web.sh
|
||||
|
||||
# --- firmware -------------------------------------------------------------
|
||||
build: web
|
||||
$(DOCKER_RUN) $(IDF_IMAGE) bash -c 'idf.py build; rc=$$?; $(FIX_OWNER); exit $$rc'
|
||||
|
||||
flash: build
|
||||
$(DOCKER_RUN) $(DEVICE) $(IDF_IMAGE) bash -c 'idf.py -p $(PORT) flash; rc=$$?; $(FIX_OWNER); exit $$rc'
|
||||
|
||||
ota: build
|
||||
@test -n "$(HOST)" || { echo "usage: make ota HOST=<controller ip>"; exit 1; }
|
||||
python3 $(V2)/tools/ota.py $(HOST)
|
||||
|
||||
monitor:
|
||||
$(DOCKER_RUN) $(TTY) $(DEVICE) $(IDF_IMAGE) idf.py -p $(PORT) monitor
|
||||
|
||||
flash-monitor: flash monitor
|
||||
|
||||
# Non-interactive: reset the board and print what it says for SECS seconds
|
||||
log:
|
||||
python3 $(V2)/tools/serial_log.py $(PORT) $(SECS)
|
||||
|
||||
size:
|
||||
$(DOCKER_RUN) $(IDF_IMAGE) bash -c 'idf.py size; rc=$$?; $(FIX_OWNER); exit $$rc'
|
||||
|
||||
menuconfig:
|
||||
$(DOCKER_RUN) -it $(IDF_IMAGE) bash -c 'idf.py menuconfig; rc=$$?; $(FIX_OWNER); exit $$rc'
|
||||
|
||||
erase:
|
||||
$(DOCKER_RUN) $(DEVICE) $(IDF_IMAGE) idf.py -p $(PORT) erase-flash
|
||||
|
||||
clean:
|
||||
rm -rf $(V2)/build
|
||||
|
||||
fullclean: clean
|
||||
rm -rf $(V2)/sdkconfig $(V2)/sdkconfig.old $(V2)/www_dist
|
||||
|
||||
# --- tests ----------------------------------------------------------------
|
||||
test: test-driver test-envelope
|
||||
|
||||
# Host-side unit tests for the driver's link layer and beat sync (pure Python)
|
||||
test-driver:
|
||||
python3 $(V2)/tools/run_driver_tests.py
|
||||
|
||||
# The C envelope packer must produce the same bytes as v2/test/binary_envelope.py
|
||||
test-envelope:
|
||||
@tmp=$$(mktemp -d); \
|
||||
(cd $(V2)/test && python3 env_check.py) > $$tmp/py.txt; \
|
||||
docker run --rm -v "$(CURDIR)/$(V2)":/project -w /project/test $(IDF_IMAGE) bash -c \
|
||||
'gcc -Wall -I/opt/esp/idf/components/json/cJSON env_host.c ../main/envelope.c /opt/esp/idf/components/json/cJSON/cJSON.c -o /tmp/t -lm && /tmp/t' 2>&1 | tail -2 > $$tmp/c.txt; \
|
||||
if diff -q $$tmp/py.txt $$tmp/c.txt >/dev/null; then echo "envelope: C and Python agree"; rm -rf $$tmp; \
|
||||
else echo "envelope: MISMATCH"; diff $$tmp/py.txt $$tmp/c.txt; rm -rf $$tmp; exit 1; fi
|
||||
@@ -1,30 +0,0 @@
|
||||
[[source]]
|
||||
url = "https://pypi.org/simple"
|
||||
verify_ssl = true
|
||||
name = "pypi"
|
||||
|
||||
[packages]
|
||||
mpremote = "*"
|
||||
pyserial = "*"
|
||||
esptool = "*"
|
||||
pyjwt = "*"
|
||||
watchfiles = "*"
|
||||
requests = "*"
|
||||
selenium = "*"
|
||||
adafruit-ampy = "*"
|
||||
microdot = "*"
|
||||
websockets = "*"
|
||||
|
||||
[dev-packages]
|
||||
pytest = "*"
|
||||
|
||||
[requires]
|
||||
python_version = "3.11"
|
||||
|
||||
[scripts]
|
||||
web = "python /home/pi/led-controller/tests/web.py"
|
||||
watch = "python -m watchfiles 'python tests/web.py' src tests"
|
||||
install = "pipenv install"
|
||||
run = "sh -c 'cd src && python main.py'"
|
||||
dev = "watchfiles \"sh -c 'cd src && python main.py'\" src"
|
||||
help-pdf = "sh scripts/build_help_pdf.sh"
|
||||
Generated
-1026
File diff suppressed because it is too large.
Load diff
@@ -1,61 +1,43 @@
|
||||
# led-controller
|
||||
|
||||
LED controller web app for managing profiles, **zones**, presets, and colour palettes, and sending commands to LED devices. Outbound paths include:
|
||||
ESP32-S3 controller for LED drivers: W5500 Ethernet, web UI, I2S microphone beat detection and an ESP-NOW link to the drivers. The firmware lives in [`v2/`](v2/); see [`v2/docs/BENCH_TEST.md`](v2/docs/BENCH_TEST.md) for the bench tests.
|
||||
|
||||
- **Serial → ESP-NOW bridge**: JSON lines over UART to an ESP32 that forwards ESP-NOW frames (configure `serial_port` and baud in `settings.json` / Settings model).
|
||||
- **Wi-Fi LED drivers**: TCP JSON lines (default port **8765** on the Pi; drivers discover the controller via **UDP 8766** broadcast).
|
||||
|
||||
## Run
|
||||
|
||||
- One-time setup for port 80 without root: `sudo scripts/setup-port80.sh`
|
||||
- Start app: `pipenv run run` (override listen port with the **`PORT`** environment variable)
|
||||
- Dev watcher (auto-restart on `src/` changes): `pipenv run dev`
|
||||
- Regenerate **`docs/help.pdf`** from **`docs/help.md`**: `pipenv run help-pdf` (requires **pandoc** and **chromium** on the host)
|
||||
|
||||
## UI modes
|
||||
|
||||
- **Run mode**: focused control view. Select zones/presets and apply profiles. Editing actions are hidden.
|
||||
- **Edit mode**: management view. Shows **Zones**, Presets, Patterns, Colour Palette, and Send Presets controls, plus per-tile preset edit/remove and drag-reorder.
|
||||
|
||||
## Profiles
|
||||
|
||||
- Applying a profile updates session scope and refreshes the active zone content.
|
||||
- In **Run mode**, Profiles supports apply-only behaviour (no create/clone/delete).
|
||||
- In **Edit mode**, Profiles supports create/clone/delete.
|
||||
- Creating a profile always creates a populated `default` zone (starter presets).
|
||||
- Optional **DJ zone** seeding creates:
|
||||
- `dj` zone bound to device name `dj`
|
||||
- starter DJ presets (rainbow, single colour, transition)
|
||||
|
||||
## Preset colours and palette linking
|
||||
|
||||
- In preset editor, selecting a colour picker value auto-adds it when the picker closes.
|
||||
- Use **From Palette** to add a palette-linked preset colour.
|
||||
- Linked colours are stored as palette references and shown with a `P` badge.
|
||||
- When profile palette colours change, linked preset colours update across that profile.
|
||||
|
||||
## 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.
|
||||
|
||||
## Animation engine (Pi-side)
|
||||
|
||||
`src/engine/` lets the Pi drive LEDs itself, in addition to the ESP32 drivers:
|
||||
|
||||
- **Pixel generator**: runs the **unchanged** `led-driver/src/patterns/*.py` under CPython (a `utime` shim plus a NeoPixel-like buffer) with the same preset JSON the drivers get, and streams each frame to **pixel outputs**: DDP, Art-Net, sACN (E1.31), or USB-DMX (Enttec Pro / Open DMX). Configure outputs in **Outputs** (edit mode) and add an output's name to a zone's devices.
|
||||
- **Preset sequencer**: **Sequences** play timed chains of presets on a zone, switching both the pixel outputs and the zone's ESP32 drivers. Sequences resume after a restart.
|
||||
- ESP32 firmware is unchanged; drivers still get presets + `select`.
|
||||
|
||||
CLI (run from `src/`):
|
||||
## Build and flash
|
||||
|
||||
```bash
|
||||
python -m engine.cli --output "ddp://192.168.1.60?pixels=300" --test
|
||||
python -m engine.cli --output "artnet://192.168.1.61?universe=0&pixels=170" --preset 16
|
||||
python -m engine.cli --pattern rainbow --n1 2 --leds 60 # terminal preview
|
||||
make build # minify the web UI from v2/web, then build the firmware (ESP-IDF in Docker)
|
||||
make flash # flash over USB
|
||||
make ota HOST=<ip> # update firmware (web UI included) over Ethernet, no USB (POST /ota)
|
||||
make monitor # serial console
|
||||
make test # driver unit tests and the C/Python envelope cross-check
|
||||
```
|
||||
|
||||
Tests: `pipenv run pytest tests/engine_tests`.
|
||||
`make` lists every target. The web UI sources are in `v2/web/` (`static/`, `templates/`, `audio.html`).
|
||||
|
||||
## Other directories
|
||||
|
||||
- `led-driver/` (submodule): MicroPython firmware for the ESP32 LED drivers.
|
||||
- `led-tool/` (submodule): `led-cli`, configures drivers over serial and updates the controller over Ethernet (`led-cli --ota HOST`).
|
||||
- `led-simulator/` (submodule), `espnow-sender/`: test helpers.
|
||||
- `db/`: stored zones, presets and devices, importable with `PUT /db/<name>`.
|
||||
|
||||
## Docs
|
||||
|
||||
- API reference: `docs/API.md`
|
||||
- User guide: `docs/help.md` (`scripts/build_help_pdf.sh` regenerates `docs/help.pdf`)
|
||||
- Specification: `docs/SPECIFICATION.md`
|
||||
|
||||
## Network
|
||||
|
||||
The controller advertises `<hostname>.local` over mDNS (default `led-controller`, plus an `_http._tcp` service). Both settings below come from `/settings` and apply on reboot.
|
||||
|
||||
`static_ips` is a list of networks to try, in order, each time the Ethernet link comes up. The first entry whose gateway answers ARP is used; if none does (or the list is empty) the controller uses DHCP. `netmask` defaults to `255.255.255.0`, `dns` to the gateway.
|
||||
|
||||
```bash
|
||||
curl -X PUT http://led-controller.local/settings/settings -H 'Content-Type: application/json' -d '{
|
||||
"hostname": "stage",
|
||||
"static_ips": [
|
||||
{"ip": "192.168.1.50", "netmask": "255.255.255.0", "gw": "192.168.1.1"},
|
||||
{"ip": "10.0.0.50", "netmask": "255.255.255.0", "gw": "10.0.0.1"}
|
||||
]}'
|
||||
```
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"188b0e1560a8": {"id": "188b0e1560a8", "name": "led-188b0e1560a8", "type": "led", "transport": "wifi", "address": "10.1.1.192", "default_pattern": null, "zones": []}, "f0f5bdfb9d30": {"id": "f0f5bdfb9d30", "name": "led-f0f5bdfb9d30", "type": "led", "transport": "wifi", "address": "10.1.1.232", "default_pattern": null, "zones": []}}
|
||||
{"e8f60a16e074": {"id": "e8f60a16e074", "name": "mirror", "type": "led", "transport": "wifi", "address": "192.168.1.199", "default_pattern": null, "zones": []}, "e8f60a16d51c": {"id": "e8f60a16d51c", "name": "mirror", "type": "led", "transport": "wifi", "address": "192.168.1.77", "default_pattern": null, "zones": []}, "e8f60a170d68": {"id": "e8f60a170d68", "name": "mirror", "type": "led", "transport": "wifi", "address": "192.168.1.217", "default_pattern": null, "zones": []}, "588c81a1182c": {"id": "588c81a1182c", "name": "dj", "type": "led", "transport": "wifi", "address": "192.168.1.114", "default_pattern": null, "zones": []}, "dcb4d99988c8": {"id": "dcb4d99988c8", "name": "roof", "type": "led", "transport": "wifi", "address": "192.168.1.158", "default_pattern": null, "zones": []}, "48f6ee2097c0": {"id": "48f6ee2097c0", "name": "roof", "type": "led", "transport": "wifi", "address": "192.168.1.246", "default_pattern": null, "zones": []}, "48f6ee211d8c": {"id": "48f6ee211d8c", "name": "roof", "type": "led", "transport": "wifi", "address": "192.168.1.55", "default_pattern": null, "zones": []}, "dcb4d99b0e34": {"id": "dcb4d99b0e34", "name": "roof", "type": "led", "transport": "wifi", "address": "192.168.1.167", "default_pattern": null, "zones": []}, "588c81a337fc": {"id": "588c81a337fc", "name": "inner", "type": "led", "transport": "wifi", "address": "192.168.1.110", "default_pattern": null, "zones": []}, "588c81a32e1c": {"id": "588c81a32e1c", "name": "outer", "type": "led", "transport": "wifi", "address": "192.168.1.250", "default_pattern": null, "zones": []}, "e8f60a16f288": {"id": "e8f60a16f288", "name": "mirror", "type": "led", "transport": "wifi", "address": "192.168.1.249", "default_pattern": null, "zones": []}, "e4b323c53870": {"id": "e4b323c53870", "name": "speaker1", "type": "led", "transport": "wifi", "address": "192.168.1.23", "default_pattern": null, "zones": []}, "e8f60a16eba4": {"id": "e8f60a16eba4", "name": "speaker2", "type": "led", "transport": "wifi", "address": "192.168.1.31", "default_pattern": null, "zones": []}, "e8f60a1707c0": {"id": "e8f60a1707c0", "name": "speaker3", "type": "led", "transport": "wifi", "address": "192.168.1.134", "default_pattern": null, "zones": []}, "e8f60a16fb14": {"id": "e8f60a16fb14", "name": "speaker4", "type": "led", "transport": "wifi", "address": "192.168.1.30", "default_pattern": null, "zones": []}, "e8f60a16e57c": {"id": "e8f60a16e57c", "name": "speaker5", "type": "led", "transport": "wifi", "address": "192.168.1.63", "default_pattern": null, "zones": []}, "e8f60a16f1b4": {"id": "e8f60a16f1b4", "name": "speaker6", "type": "led", "transport": "wifi", "address": "192.168.1.224", "default_pattern": null, "zones": []}, "e4b323c5ad6c": {"id": "e4b323c5ad6c", "name": "speaker7", "type": "led", "transport": "wifi", "address": "192.168.1.94", "default_pattern": null, "zones": []}, "588c81a200d8": {"id": "588c81a200d8", "name": "speaker8", "type": "led", "transport": "wifi", "address": "192.168.1.122", "default_pattern": null, "zones": []}, "a085e34efaec": {"id": "a085e34efaec", "name": "alleyway", "type": "led", "transport": "wifi", "address": "192.168.1.22", "default_pattern": null, "zones": []}, "e8f60a16f94c": {"id": "e8f60a16f94c", "name": "speaker10", "type": "led", "transport": "wifi", "address": "192.168.1.195", "default_pattern": null, "zones": []}, "e8f60a1701a8": {"id": "e8f60a1701a8", "name": "speaker9", "type": "led", "transport": "wifi", "address": "192.168.1.179", "default_pattern": null, "zones": []}}
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"on": {"min_delay": 10, "max_delay": 10000, "max_colors": 1}, "off": {"min_delay": 10, "max_delay": 10000, "max_colors": 0}, "rainbow": {"n1": "Step Rate", "min_delay": 10, "max_delay": 10000, "max_colors": 0}, "colour_cycle": {"n1": "Step Rate", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "transition": {"min_delay": 10, "max_delay": 10000, "max_colors": 10}, "chase": {"n1": "Colour 1 Length", "n2": "Colour 2 Length", "n3": "Step 1", "n4": "Step 2", "min_delay": 10, "max_delay": 10000, "max_colors": 2}, "pulse": {"n1": "Attack", "n2": "Hold", "n3": "Decay", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "circle": {"n1": "Head Rate", "n2": "Max Length", "n3": "Tail Rate", "n4": "Min Length", "min_delay": 10, "max_delay": 10000, "max_colors": 2}, "blink": {"min_delay": 10, "max_delay": 10000, "max_colors": 10}, "flicker": {"n1": "Min brightness", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "flame": {"n1": "Min brightness", "n2": "Breath period (ms)", "n3": "Spark gap min (ms, 0=default 10\u201330 s, -1=off)", "n4": "Spark gap max (ms)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "twinkle": {"n1": "Twinkle activity (1\u2013255, higher = more changes)", "n2": "Density (0\u2013255, higher = more of the strip lit)", "n3": "Min adjacent LEDs per twinkle (same as max for fixed length)", "n4": "Max adjacent LEDs per twinkle (same as min for fixed length)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "radiate": {"n1": "Node spacing (LEDs)", "n2": "Out time (ms)", "n3": "In time (ms)", "min_delay": 10, "max_delay": 10000, "max_colors": 2}, "meteor_rain": {"n1": "Tail length", "n2": "Speed (LEDs per frame)", "n3": "Fade amount (1-255)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "scanner": {"n1": "Eye width", "n2": "End pause (frames)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "gradient_scroll": {"n1": "Scroll step rate", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "comet_dual": {"n1": "Tail length", "n2": "Speed", "n3": "Gap", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "sparkle_trail": {"n1": "Spark density", "n2": "Decay", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "wave": {"n1": "Wavelength", "n2": "Amplitude", "n3": "Drift speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "plasma": {"n1": "Scale", "n2": "Speed", "n3": "Contrast", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "segment_chase": {"n1": "Segment size", "n2": "Phase step", "n3": "Segment phase offset", "n4": "Gap per segment", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "bar_graph": {"n1": "Level percent", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "breathing_dual": {"n1": "Phase offset", "n2": "Ease", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "strobe_burst": {"n1": "Burst count", "n2": "Burst gap", "n3": "Cooldown", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "rain_drops": {"n1": "Drop rate", "n2": "Ripple width", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "fireflies": {"n1": "Count", "n2": "Twinkle speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "clock_sweep": {"n1": "Hand width", "n2": "Marker interval", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "marquee": {"n1": "On length", "n2": "Off length", "n3": "Step", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "aurora": {"n1": "Band count", "n2": "Shimmer", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "snowfall": {"n1": "Flake density", "n2": "Fall speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "heartbeat": {"n1": "Pulse 1 ms", "n2": "Pulse 2 ms", "n3": "Pause ms", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "orbit": {"n1": "Orbit count", "n2": "Base speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "palette_morph": {"n1": "Morph ms", "n2": "Warp rate", "n3": "Turbulence", "max_colors": 10, "min_delay": 10, "max_delay": 10000}}
|
||||
{"on": {"min_delay": 10, "max_delay": 10000, "max_colors": 1}, "off": {"min_delay": 10, "max_delay": 10000, "max_colors": 0}, "rainbow": {"n1": "Step Rate", "min_delay": 10, "max_delay": 10000, "max_colors": 0}, "colour_cycle": {"n1": "Step Rate", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "transition": {"min_delay": 10, "max_delay": 10000, "max_colors": 10}, "chase": {"n1": "Colour 1 Length", "n2": "Colour 2 Length", "n3": "Step 1", "n4": "Step 2", "min_delay": 10, "max_delay": 10000, "max_colors": 2}, "pulse": {"n1": "Attack", "n2": "Hold", "n3": "Decay", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "circle": {"n1": "Head Rate", "n2": "Max Length", "n3": "Tail Rate", "n4": "Min Length", "min_delay": 10, "max_delay": 10000, "max_colors": 2}, "blink": {"min_delay": 10, "max_delay": 10000, "max_colors": 10}, "flicker": {"n1": "Min brightness", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "flame": {"n1": "Min brightness", "n2": "Breath period (ms)", "n3": "Spark gap min (ms, 0=default 10\u201330 s, -1=off)", "n4": "Spark gap max (ms)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "twinkle": {"n1": "Twinkle activity (1\u2013255, higher = more changes)", "n2": "Density (0\u2013255, higher = more of the strip lit)", "n3": "Min adjacent LEDs per twinkle (same as max for fixed length)", "n4": "Max adjacent LEDs per twinkle (same as min for fixed length)", "min_delay": 84, "max_delay": 10000, "max_colors": 10}, "radiate": {"n1": "Node spacing (LEDs)", "n2": "Out time (ms)", "n3": "In time (ms)", "min_delay": 10, "max_delay": 10000, "max_colors": 2}, "meteor_rain": {"n1": "Tail length", "n2": "Speed (LEDs per frame)", "n3": "Fade amount (1-255)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "scanner": {"n1": "Eye width", "n2": "End pause (frames)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "gradient_scroll": {"n1": "Scroll step rate", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "comet_dual": {"n1": "Tail length", "n2": "Speed", "n3": "Gap", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "sparkle_trail": {"n1": "Spark density", "n2": "Decay", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "wave": {"n1": "Wavelength", "n2": "Amplitude", "n3": "Drift speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "plasma": {"n1": "Scale", "n2": "Speed", "n3": "Contrast", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "segment_chase": {"n1": "Segment size", "n2": "Phase step", "n3": "Segment phase offset", "n4": "Gap per segment", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "bar_graph": {"n1": "Level percent", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "breathing_dual": {"n1": "Phase offset", "n2": "Ease", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "strobe_burst": {"n1": "Burst count", "n2": "Burst gap", "n3": "Cooldown", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "rain_drops": {"n1": "Drop rate", "n2": "Ripple width", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "fireflies": {"n1": "Count", "n2": "Twinkle speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "clock_sweep": {"n1": "Hand width", "n2": "Marker interval", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "marquee": {"n1": "On length", "n2": "Off length", "n3": "Step", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "aurora": {"n1": "Band count", "n2": "Shimmer", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "snowfall": {"n1": "Flake density", "n2": "Fall speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "heartbeat": {"n1": "Pulse 1 ms", "n2": "Pulse 2 ms", "n3": "Pause ms", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "orbit": {"n1": "Orbit count", "n2": "Base speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "palette_morph": {"n1": "Morph ms", "n2": "Warp rate", "n3": "Turbulence", "max_colors": 10, "min_delay": 10, "max_delay": 10000}}
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"1": {"name": "on", "pattern": "on", "colors": ["#FFFFFF"], "brightness": 255, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "2": {"name": "off", "pattern": "off", "colors": [], "brightness": 0, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "3": {"name": "rainbow", "pattern": "rainbow", "colors": [], "brightness": 255, "delay": 100, "auto": true, "n1": 2, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "4": {"name": "transition", "pattern": "transition", "colors": ["#FF0000", "#00FF00", "#0000FF", "#FFFFFF", "#0000FF", "#FFFF00"], "brightness": 255, "delay": 5000, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null, null, 6, 2, 3]}, "5": {"name": "chase", "pattern": "chase", "colors": ["#FF0000", "#0000FF"], "brightness": 255, "delay": 200, "auto": true, "n1": 5, "n2": 5, "n3": 1, "n4": 1, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "6": {"name": "pulse", "pattern": "pulse", "colors": ["#00FF00"], "brightness": 255, "delay": 500, "auto": true, "n1": 1000, "n2": 500, "n3": 1000, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "7": {"name": "circle", "pattern": "circle", "colors": ["#FFA500", "#800080"], "brightness": 255, "delay": 200, "auto": true, "n1": 2, "n2": 10, "n3": 2, "n4": 5, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "8": {"name": "blink", "pattern": "blink", "colors": ["#FF0000", "#00FF00", "#0000FF", "#FFFF00"], "brightness": 255, "delay": 1000, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "9": {"name": "warm white", "pattern": "on", "colors": ["#FFF5E6"], "brightness": 200, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "10": {"name": "cool white", "pattern": "on", "colors": ["#E6F2FF"], "brightness": 200, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "11": {"name": "red", "pattern": "on", "colors": ["#FF0000"], "brightness": 255, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "12": {"name": "blue", "pattern": "on", "colors": ["#0000FF"], "brightness": 255, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "13": {"name": "rainbow slow", "pattern": "rainbow", "colors": [], "brightness": 255, "delay": 150, "auto": true, "n1": 1, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "14": {"name": "pulse slow", "pattern": "pulse", "colors": ["#FF6600"], "brightness": 255, "delay": 800, "auto": true, "n1": 2000, "n2": 1000, "n3": 2000, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "15": {"name": "blink red green", "pattern": "blink", "colors": ["#FF0000", "#00FF00"], "brightness": 255, "delay": 500, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "30": {"name": "rainbow slow", "pattern": "rainbow", "colors": [], "brightness": 255, "delay": 150, "auto": true, "n1": 1, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "31": {"name": "DJ Rainbow", "pattern": "rainbow", "colors": [], "brightness": 220, "delay": 60, "n1": 12, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "32": {"name": "DJ Single Color", "pattern": "on", "colors": ["#ff00ff"], "brightness": 220, "delay": 100, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "33": {"name": "DJ Transition", "pattern": "transition", "colors": ["#ff0000", "#00ff00", "#0000ff"], "brightness": 220, "delay": 250, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "34": {"name": "DJ Rainbow", "pattern": "rainbow", "colors": [], "brightness": 220, "delay": 60, "n1": 12, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "35": {"name": "DJ Single Color", "pattern": "on", "colors": ["#ff00ff"], "brightness": 220, "delay": 100, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "36": {"name": "DJ Transition", "pattern": "transition", "colors": ["#ff0000", "#00ff00", "#0000ff"], "brightness": 220, "delay": 250, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "37": {"name": "tranistion2", "pattern": "transition", "colors": ["#FF0000", "#FFFF00", "#FF00FF"], "brightness": 128, "delay": 1000, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [0, 3, 4]}, "38": {"name": "Colour Cycle", "pattern": "cLine truncated
|
||||
{"1": {"name": "on", "pattern": "on", "colors": [], "brightness": 32, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": []}, "2": {"name": "off", "pattern": "off", "colors": [], "brightness": 0, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "3": {"name": "rainbow", "pattern": "rainbow", "colors": [], "brightness": 32, "delay": 100, "auto": true, "n1": 2, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": []}, "4": {"name": "transition", "pattern": "transition", "colors": ["#0000FF", "#FF00FF", "#FF0000", "#00FF00", "#FFFF00", "#00FFFF"], "brightness": 32, "delay": 5000, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [2, 4, 0, 1, 3, 5]}, "5": {"name": "chase", "pattern": "chase", "colors": ["#006b12", "#2b02c0"], "brightness": 66, "delay": 150, "auto": true, "n1": 4, "n2": 4, "n3": 5, "n4": 1, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null]}, "6": {"name": "pulse", "pattern": "pulse", "colors": ["#f5e400"], "brightness": 255, "delay": 300, "auto": true, "n1": 200, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null]}, "7": {"name": "circle", "pattern": "circle", "colors": ["#ffbb00", "#000000"], "brightness": 64, "delay": 10, "auto": true, "n1": 25, "n2": 120, "n3": 27, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, 7]}, "8": {"name": "blink", "pattern": "blink", "colors": ["#FF0000", "#00FF00", "#0000FF", "#FFFF00"], "brightness": 255, "delay": 1000, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "9": {"name": "warm white", "pattern": "on", "colors": ["#FFF5E6"], "brightness": 255, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null]}, "10": {"name": "cool white", "pattern": "on", "colors": ["#E6F2FF"], "brightness": 200, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "11": {"name": "red", "pattern": "on", "colors": ["#FF0000"], "brightness": 64, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null]}, "12": {"name": "blue", "pattern": "on", "colors": ["#0000FF"], "brightness": 255, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "13": {"name": "rainbow slow", "pattern": "rainbow", "colors": [], "brightness": 255, "delay": 150, "auto": true, "n1": 1, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "14": {"name": "pulse slow", "pattern": "pulse", "colors": ["#FF6600", "#FF00FF", "#FFFF00"], "brightness": 127, "delay": 100, "auto": true, "n1": 2000, "n2": 1000, "n3": 1000, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, 4, 3]}, "15": {"name": "blink red green", "pattern": "blink", "colors": ["#FF0000", "#00FF00"], "brightness": 255, "delay": 500, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "30": {"name": "rainbow slow", "pattern": "rainbow", "colors": [], "brightness": 255, "delay": 150, "auto": true, "n1": 1, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "31": {"name": "DJ Rainbow", "pattern": "rainbow", "colors": [], "brightness": 220, "delay": 60, "n1": 12, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "32": {"name": "DJ Single Color", "pattern": "on", "colors": ["#ff00ff"], "brightness": 220, "delay": 100, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "33": {"name": "DJ Transition", "pattern": "transition", "colors": ["#ff0000", "#00ff00", "#0000ff"], "brightness": 220, "delay": 250, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "34": {"name": "DJ Rainbow", "pattern": "rainbow", "colors": [], "brightness": 220, "delay": 60, "n1": 12, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "35": {"name": "DJ Single Color", "pattern": "on", "colors": ["#ff00ff"], "brightness": 220, "delay": 100, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "36": {"name": "DJ Transition", "pattern": "transition", "colors": ["#ff0000", "#00ff00", "#0000ff"], "brightness": 220, "delay": 250, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "37": {"name": "tranistion2", "pattern": "transition", "colors": ["#FF0000", "#FFFF00"], "brightness": 1Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"1": {"name": "default", "type": "zones", "zones": ["1", "8"], "scenes": [], "palette_id": "1"}, "2": {"name": "test", "type": "zones", "zones": ["6", "7"], "scenes": [], "palette_id": "12"}}
|
||||
{"1": {"name": "default", "type": "zones", "zones": ["1", "8", "9", "10", "11", "12", "13"], "scenes": [], "palette_id": "1"}, "2": {"name": "test", "type": "zones", "zones": ["6", "7"], "scenes": [], "palette_id": "12"}}
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"1": {"name": "default", "names": ["led-188b0e1560a8", "led-f0f5bdfb9d30"], "presets": [["4", "2", "7"], ["3", "14", "5"], ["8", "9", "1"], ["6", "38", "42"], ["39", "40", "41"], ["43", "44", "45"], ["46", "47", "48"], ["49", "50", "51"], ["52", "53", "54"], ["55", "56", "57"], ["58", "59", "60"], ["61", "62"]], "presets_flat": ["4", "2", "7", "3", "14", "5", "8", "9", "1", "6", "38", "42", "39", "40", "41", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62"], "default_preset": "41"}, "2": {"name": "default", "names": ["1", "2", "3", "4", "5", "6", "7", "8", "0", "a"], "presets": [["16", "17", "18"], ["19", "20", "21"], ["22", "23", "24"], ["25", "26", "27"], ["28", "29", "30"]], "presets_flat": ["16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30"]}, "3": {"name": "default", "names": ["1"], "presets": [], "default_preset": null}, "4": {"name": "default", "names": ["1"], "presets": [], "default_preset": null}, "5": {"name": "dj", "names": ["dj"], "presets": [["31", "32", "33"]], "default_preset": "31", "presets_flat": ["31", "32", "33"]}, "6": {"name": "default", "names": ["1"], "presets": [], "default_preset": null, "presets_flat": []}, "7": {"name": "dj", "names": ["dj"], "presets": [["34", "35", "36"]], "default_preset": "34", "presets_flat": ["34", "35", "36"]}, "8": {"name": "test", "names": ["led-188b0e1560a8"], "presets": [["1", "2", "3"], ["4", "5"]], "default_preset": "1", "presets_flat": ["1", "2", "3", "4", "5"]}}
|
||||
{"1": {"name": "mirror", "names": ["mirror", "mirror", "mirror", "mirror"], "presets": [["4", "2", "3"], ["14", "5", "9"], ["42", "39", "40"], ["38", "55", "43"], ["44", "45", "46"], ["64", "50", "47"], ["49", "54", "58"], ["59", "41", "57"]], "presets_flat": ["4", "2", "3", "14", "5", "9", "42", "39", "40", "38", "55", "43", "44", "45", "46", "64", "50", "47", "49", "54", "58", "59", "41", "57"], "default_preset": "5"}, "2": {"name": "default", "names": ["1", "2", "3", "4", "5", "6", "7", "8", "0", "a"], "presets": [["16", "17", "18"], ["19", "20", "21"], ["22", "23", "24"], ["25", "26", "27"], ["28", "29", "30"]], "presets_flat": ["16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30"]}, "3": {"name": "default", "names": ["1"], "presets": [], "default_preset": null}, "4": {"name": "default", "names": ["1"], "presets": [], "default_preset": null}, "5": {"name": "dj", "names": ["dj"], "presets": [["31", "32", "33"]], "default_preset": "31", "presets_flat": ["31", "32", "33"]}, "6": {"name": "default", "names": ["1"], "presets": [], "default_preset": null, "presets_flat": []}, "7": {"name": "dj", "names": ["dj"], "presets": [["34", "35", "36"]], "default_preset": "34", "presets_flat": ["34", "35", "36"]}, "8": {"name": "dj", "names": ["dj"], "presets": [["1", "2", "3"], ["4", "5", "66"], ["63", "65", "11"], ["67"]], "default_preset": "11", "presets_flat": ["1", "2", "3", "4", "5", "66", "63", "65", "11", "67"]}, "9": {"name": "roof", "names": ["roof", "roof", "roof", "roof"], "presets": [["5", "3", "42"], ["2", "1", "55"], ["4", "11", "9"], ["6"]], "default_preset": "3", "presets_flat": ["5", "3", "42", "2", "1", "55", "4", "11", "9", "6"]}, "10": {"name": "inner", "names": ["inner"], "presets": [["3", "46", "7"], ["55", "54", "37"], ["1", "2", "5"], ["6"]], "default_preset": "7", "presets_flat": ["3", "46", "7", "55", "54", "37", "1", "2", "5", "6"]}, "11": {"name": "outer", "names": ["outer"], "presets": [["3", "46", "7"], ["55", "54", "37"], ["2", "1"]], "default_preset": "46", "presets_flat": ["3", "46", "7", "55", "54", "37", "2", "1"]}, "12": {"name": "speakers", "names": ["speaker1", "speaker2", "speaker4", "speaker3", "speaker8", "speaker5", "speaker7", "speaker6", "speaker10", "speaker9"], "presets": [["4", "2", "41"], ["64", "3", "14"], ["5", "42", "40"], ["43", "45", "46"], ["47", "49", "54"], ["55", "59"]], "default_preset": "4", "presets_flat": ["4", "2", "41", "64", "3", "14", "5", "42", "40", "43", "45", "46", "47", "49", "54", "55", "59"]}, "13": {"name": "alleyway", "names": ["alleyway"], "presets": [["4", "2", "3"], ["14", "5", "9"], ["42", "39", "40"], ["38", "41", "43"], ["44", "45", "46"], ["50", "47", "49"], ["54", "55", "57"], ["58", "59"]], "default_preset": "4", "presets_flat": ["4", "2", "3", "14", "5", "9", "42", "39", "40", "38", "41", "43", "44", "45", "46", "50", "47", "49", "54", "55", "57", "58", "59"]}}
|
||||
@@ -70,6 +70,7 @@ Below, `<id>` values are string identifiers used by the JSON stores (numeric str
|
||||
|--------|------|-------------|
|
||||
| GET | `/settings` | Full settings object (from `settings.json` / `Settings` model). |
|
||||
| PUT | `/settings/settings` | Merge keys into settings and save. Returns `{"message": "Settings updated successfully"}`. |
|
||||
| POST | `/reboot` | v2 controller: restart the board. Replies `{"message":"rebooting"}` first, then reboots after 0.5 s. Network settings (`hostname`, `static_ips`) apply on the next boot. |
|
||||
| GET | `/settings/wifi/ap` | Saved Wi‑Fi AP fields: `saved_ssid`, `saved_password`, `saved_channel`, `active` (Pi: `active` is always false). |
|
||||
| POST | `/settings/wifi/ap` | Body: `ssid` (required), `password`, `channel` (1–11). Persists AP-related settings. |
|
||||
| GET | `/settings/page` | Serves `templates/settings.html`. |
|
||||
|
||||
+42
-7
@@ -1,13 +1,14 @@
|
||||
# LED Driver System - Specification Document
|
||||
|
||||
**Version:** 1.0
|
||||
**Date:** December 2025
|
||||
**Version:** 1.1
|
||||
**Date:** October 2026
|
||||
**Status:** Draft
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Overview](#overview)
|
||||
2. [System Architecture](#system-architecture)
|
||||
- [Raspberry Pi Controller and Animation Engine](#raspberry-pi-controller-and-animation-engine)
|
||||
3. [User Interface Specifications](#user-interface-specifications)
|
||||
4. [Feature Specifications](#feature-specifications)
|
||||
5. [Preset System](#preset-system)
|
||||
@@ -54,6 +55,11 @@ The LED Driver system is a MicroPython-based application for controlling LED str
|
||||
- Persistent settings storage (usqlite database)
|
||||
- Web-based configuration interface (Microdot web server)
|
||||
- SQLite database for presets and event logging
|
||||
- **Raspberry Pi controller** (`src/`): Microdot web app with JSON-file storage (`db/*.json`) managing profiles, zones, presets, palettes, scenes, sequences and outputs
|
||||
- **Pi-side animation engine** (`src/engine/`): renders the unchanged driver patterns on the Pi and streams pixels over DDP, Art-Net, sACN (E1.31) or USB-DMX
|
||||
- **Preset sequencer**: timed preset chains per zone, resumed after restart
|
||||
- Server-wide global brightness (0-255) pushed to drivers, including on Wi-Fi reconnect
|
||||
- Search filter in the Devices, Zones and Presets lists
|
||||
|
||||
---
|
||||
|
||||
@@ -225,6 +231,29 @@ The LED Driver system uses a master/slave architecture where one device acts as
|
||||
|
||||
---
|
||||
|
||||
## Raspberry Pi Controller and Animation Engine
|
||||
|
||||
The current deployment adds a Raspberry Pi running the web app (`src/main.py`, Microdot on CPython). It is the authoritative store and UI host; ESP32 firmware is unchanged. Full route detail is in `docs/API.md`.
|
||||
|
||||
**Outbound paths**
|
||||
- Serial → ESP-NOW bridge (JSON lines over UART).
|
||||
- Wi-Fi drivers: TCP JSON lines (port 8765 on the Pi; drivers discover the Pi via UDP 8766 broadcast).
|
||||
- Pixel outputs rendered by the Pi engine (below).
|
||||
|
||||
**Data model (`db/*.json`):** profile, zone, preset, palette, pattern, device, scene, sequence, output. A zone's `names` list holds ESP32 device names and/or output names.
|
||||
|
||||
### Animation Engine (`src/engine/`)
|
||||
|
||||
- **Pixel generator:** loads `led-driver/src/patterns/*.py` unmodified under CPython (`utime` shim plus a NeoPixel-like buffer) and runs one render thread per zone from the same preset JSON the drivers receive. Static frames are re-sent as keepalive.
|
||||
- **Output drivers:** DDP (UDP 4048), Art-Net (ArtDMX/ArtSync, UDP 6454), sACN/E1.31 (UDP 5568, multicast or unicast), USB-DMX (Enttec DMX USB Pro or Open DMX). 170 RGB pixels per universe, consecutive universes for longer strips. A preset output for our ESP32 drivers (`outputs/driver.py`) reuses the existing preset + `select` path.
|
||||
- **Output record** (`db/output.json`): `name`, `protocol`, `host`, `port`, `universe`, `serial_port`, `dmx_mode`, `channel`, `pixel_count`, `pixel_offset`, `color_order`, `reverse`, `brightness` (0-255, multiplied by global brightness), `fps` (default 40), `enabled`. CRUD and a test pattern (R, G, B, W, off) at `/outputs`.
|
||||
- **Zone playback:** `POST /zones/<id>/play` renders a preset on every target and sends `select` to ESP32 drivers; `POST /zones/<id>/stop` blanks pixel outputs. `GET /zones/engine/status` reports per-zone and per-output counters.
|
||||
- **Sequencer:** a sequence is `{name, zone_id, loop, repeat_count, steps: [{preset_id, duration_s}], active}`. `duration_s` is clamped to 0.5-600 s (default 5); steps are hard cuts; `repeat_count` of 0 loops forever. Deadline-based scheduling, `active` sequences resume after restart, manual preset selection on a zone stops its sequence. Legacy records (`group_name`, `presets`, `sequence_duration` ms) are migrated on load. Scenes start/stop the sequences they list (`/scenes/<id>/play`, `/stop`).
|
||||
- **CLI:** `python -m engine.cli --output "ddp://host?pixels=300" --test | --preset N | --pattern NAME` (terminal preview when no output is given).
|
||||
- **UI:** Outputs and Sequences modals (edit mode), preset tiles drive pixel outputs, header brightness slider, list search filters.
|
||||
|
||||
---
|
||||
|
||||
## User Interface Specifications
|
||||
|
||||
### 1. Dashboard (Main Control Panel)
|
||||
@@ -1575,11 +1604,13 @@ peak_mem = usqlite.mem_peak()
|
||||
|
||||
### Flow 8: Sequence Between Presets
|
||||
|
||||
1. Scene activated with group having multiple presets
|
||||
2. Master applies first preset to itself (if in group), sends to slaves
|
||||
3. After duration expires, master transitions to next preset with fade effect
|
||||
4. Process repeats for all presets, loops if enabled
|
||||
5. Continues until scene changes or manual stop
|
||||
*(Implemented by the Pi-side sequencer; see Animation Engine.)*
|
||||
|
||||
1. User plays a sequence (or a scene that lists it) on a zone
|
||||
2. Pi applies the first step: renders it to the zone's pixel outputs and sends the preset + `select` to its ESP32 drivers
|
||||
3. After `duration_s` expires, the sequencer hard-cuts to the next step
|
||||
4. Process repeats for all steps; loops forever or for `repeat_count` passes
|
||||
5. Continues until stopped, the zone is played manually, or the app restarts (active sequences then resume)
|
||||
|
||||
---
|
||||
|
||||
@@ -1649,6 +1680,10 @@ peak_mem = usqlite.mem_peak()
|
||||
- Any length (1-1000 LEDs supported)
|
||||
- 5V power supply (external)
|
||||
|
||||
**Raspberry Pi (controller):**
|
||||
- Python 3.x, runs the web app and animation engine
|
||||
- Optional: Wi-Fi/Ethernet to DDP, Art-Net or sACN fixtures; USB-DMX adapter (Enttec DMX USB Pro / Open DMX)
|
||||
|
||||
**Host Computer:**
|
||||
- Python 3.x
|
||||
- pipenv for dependency management
|
||||
|
||||
+19
-4
@@ -19,7 +19,7 @@ The header has a mode toggle (desktop and mobile menu). The **label on the butto
|
||||
| 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. |
|
||||
| **Edit mode** | Full setup: zones, presets, patterns, outputs, sequences, 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.
|
||||
|
||||
@@ -30,7 +30,8 @@ The header has a mode toggle (desktop and mobile menu). The **label on the butto
|
||||
- **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.
|
||||
- **Brightness slider** (header, and in the mobile menu): adjusts the **global** brightness (0–255) sent to devices (`b` in the driver message), with a short debounce so small drags do not flood the link. The level is stored on the server (`global_brightness`) and re-sent to Wi-Fi drivers when they reconnect; the slider position is also remembered in your browser.
|
||||
- **Search**: the Devices, Zones and Presets lists have a search box that hides non-matching rows as you type. It clears when you reopen the list or press **Esc**.
|
||||
|
||||
---
|
||||
|
||||
@@ -41,7 +42,7 @@ The header has a mode toggle (desktop and mobile menu). The **label on the butto
|
||||
- **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.
|
||||
|
||||

|
||||

|
||||
|
||||
*The slider controls global brightness for the zone’s devices. Click the coloured area of a tile to select that preset.*
|
||||
|
||||
@@ -74,6 +75,20 @@ The **Presets** header button (Edit mode) opens a **profile-wide** list: **Add**
|
||||
|
||||
---
|
||||
|
||||
## Outputs (Edit mode)
|
||||
|
||||
Besides the ESP32 drivers, the Pi can render patterns itself and stream pixels to network or DMX fixtures. **Outputs** lists these fixtures; each has a **name**, a **protocol** (DDP, Art-Net, sACN/E1.31 or USB-DMX), its address (host/port, universe or serial port), pixel count and offset, colour order, brightness and frame rate. Use **Test** on an output to flash red, green, blue and white, then black.
|
||||
|
||||
To drive an output from a zone, add the output's **name** to the zone's device list (the same list used for ESP32 device names). Clicking a preset tile then renders it on the Pi for those outputs and still sends `select` to any ESP32 drivers in the zone.
|
||||
|
||||
---
|
||||
|
||||
## Sequences (Edit mode)
|
||||
|
||||
**Sequences** are timed chains of presets that play on one zone. Each step is a preset plus a duration (0.5–600 s); steps switch with hard cuts. Choose whether the sequence **loops** (and how many passes, 0 = forever), then **Play** or **Stop** it. Picking a preset by hand on that zone stops its sequence. Running sequences resume after the app restarts, and a **scene** can start every sequence it lists.
|
||||
|
||||
---
|
||||
|
||||
## 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.
|
||||
@@ -100,7 +115,7 @@ The **Patterns** dialog (Edit mode) lists pattern names and typical **delay** ra
|
||||
|
||||
## Mobile layout
|
||||
|
||||
On narrow screens, use **Menu** to reach the same actions as the desktop header (Profiles, Zones, Presets, Help, mode toggle, etc.).
|
||||
On narrow screens, use **Menu** to reach the same actions as the desktop header (Profiles, Zones, Presets, Outputs, Sequences, Help, mode toggle, brightness, etc.).
|
||||
|
||||

|
||||
|
||||
|
||||
+1
-1
Submodule led-driver updated: 2fcaf2f064...940d1d0a77.
+1
-1
Submodule led-tool updated: d6331a105c...892ccaec71.
@@ -1,2 +0,0 @@
|
||||
from microdot.microdot import Microdot, Request, Response, abort, redirect, \
|
||||
send_file # noqa: F401
|
||||
@@ -1,8 +0,0 @@
|
||||
try:
|
||||
from functools import wraps
|
||||
except ImportError: # pragma: no cover
|
||||
# MicroPython does not currently implement functools.wraps
|
||||
def wraps(wrapped):
|
||||
def _(wrapper):
|
||||
return wrapper
|
||||
return _
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,225 +0,0 @@
|
||||
try:
|
||||
import jwt
|
||||
HAS_JWT = True
|
||||
except ImportError:
|
||||
HAS_JWT = False
|
||||
try:
|
||||
import ubinascii
|
||||
except ImportError:
|
||||
import binascii as ubinascii
|
||||
try:
|
||||
import uhashlib as hashlib
|
||||
except ImportError:
|
||||
import hashlib
|
||||
try:
|
||||
import uhmac as hmac
|
||||
except ImportError:
|
||||
try:
|
||||
import hmac
|
||||
except ImportError:
|
||||
hmac = None
|
||||
import json
|
||||
|
||||
from microdot.microdot import invoke_handler
|
||||
from microdot.helpers import wraps
|
||||
|
||||
|
||||
class SessionDict(dict):
|
||||
"""A session dictionary.
|
||||
|
||||
The session dictionary is a standard Python dictionary that has been
|
||||
extended with convenience ``save()`` and ``delete()`` methods.
|
||||
"""
|
||||
def __init__(self, request, session_dict):
|
||||
super().__init__(session_dict)
|
||||
self.request = request
|
||||
|
||||
def save(self):
|
||||
"""Update the session cookie."""
|
||||
self.request.app._session.update(self.request, self)
|
||||
|
||||
def delete(self):
|
||||
"""Delete the session cookie."""
|
||||
self.request.app._session.delete(self.request)
|
||||
|
||||
|
||||
class Session:
|
||||
"""Session handling
|
||||
|
||||
:param app: The application instance.
|
||||
:param secret_key: The secret key, as a string or bytes object.
|
||||
:param cookie_options: A dictionary with cookie options to pass as
|
||||
arguments to :meth:`Response.set_cookie()
|
||||
<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
|
||||
@@ -1,70 +0,0 @@
|
||||
from utemplate import recompile
|
||||
|
||||
_loader = None
|
||||
|
||||
|
||||
class Template:
|
||||
"""A template object.
|
||||
|
||||
:param template: The filename of the template to render, relative to the
|
||||
configured template directory.
|
||||
"""
|
||||
@classmethod
|
||||
def initialize(cls, template_dir='templates',
|
||||
loader_class=recompile.Loader):
|
||||
"""Initialize the templating subsystem.
|
||||
|
||||
:param template_dir: the directory where templates are stored. This
|
||||
argument is optional. The default is to load
|
||||
templates from a *templates* subdirectory.
|
||||
:param loader_class: the ``utemplate.Loader`` class to use when loading
|
||||
templates. This argument is optional. The default
|
||||
is the ``recompile.Loader`` class, which
|
||||
automatically recompiles templates when they
|
||||
change.
|
||||
"""
|
||||
global _loader
|
||||
_loader = loader_class(None, template_dir)
|
||||
|
||||
def __init__(self, template):
|
||||
if _loader is None: # pragma: no cover
|
||||
self.initialize()
|
||||
#: The name of the template
|
||||
self.name = template
|
||||
self.template = _loader.load(template)
|
||||
|
||||
def generate(self, *args, **kwargs):
|
||||
"""Return a generator that renders the template in chunks, with the
|
||||
given arguments."""
|
||||
return self.template(*args, **kwargs)
|
||||
|
||||
def render(self, *args, **kwargs):
|
||||
"""Render the template with the given arguments and return it as a
|
||||
string."""
|
||||
return ''.join(self.generate(*args, **kwargs))
|
||||
|
||||
def generate_async(self, *args, **kwargs):
|
||||
"""Return an asynchronous generator that renders the template in
|
||||
chunks, using the given arguments."""
|
||||
class sync_to_async_iter():
|
||||
def __init__(self, iter):
|
||||
self.iter = iter
|
||||
|
||||
def __aiter__(self):
|
||||
return self
|
||||
|
||||
async def __anext__(self):
|
||||
try:
|
||||
return next(self.iter)
|
||||
except StopIteration:
|
||||
raise StopAsyncIteration
|
||||
|
||||
return sync_to_async_iter(self.generate(*args, **kwargs))
|
||||
|
||||
async def render_async(self, *args, **kwargs):
|
||||
"""Render the template with the given arguments asynchronously and
|
||||
return it as a string."""
|
||||
response = ''
|
||||
async for chunk in self.generate_async(*args, **kwargs):
|
||||
response += chunk
|
||||
return response
|
||||
@@ -1,231 +0,0 @@
|
||||
import binascii
|
||||
import hashlib
|
||||
from microdot import Request, Response
|
||||
from microdot.microdot import MUTED_SOCKET_ERRORS, print_exception
|
||||
from microdot.helpers import wraps
|
||||
|
||||
|
||||
class WebSocketError(Exception):
|
||||
"""Exception raised when an error occurs in a WebSocket connection."""
|
||||
pass
|
||||
|
||||
|
||||
class WebSocket:
|
||||
"""A WebSocket connection object.
|
||||
|
||||
An instance of this class is sent to handler functions to manage the
|
||||
WebSocket connection.
|
||||
"""
|
||||
CONT = 0
|
||||
TEXT = 1
|
||||
BINARY = 2
|
||||
CLOSE = 8
|
||||
PING = 9
|
||||
PONG = 10
|
||||
|
||||
#: Specify the maximum message size that can be received when calling the
|
||||
#: ``receive()`` method. Messages with payloads that are larger than this
|
||||
#: size will be rejected and the connection closed. Set to 0 to disable
|
||||
#: the size check (be aware of potential security issues if you do this),
|
||||
#: or to -1 to use the value set in
|
||||
#: ``Request.max_body_length``. The default is -1.
|
||||
#:
|
||||
#: Example::
|
||||
#:
|
||||
#: WebSocket.max_message_length = 4 * 1024 # up to 4KB messages
|
||||
max_message_length = -1
|
||||
|
||||
def __init__(self, request):
|
||||
self.request = request
|
||||
self.closed = False
|
||||
|
||||
async def handshake(self):
|
||||
response = self._handshake_response()
|
||||
await self.request.sock[1].awrite(
|
||||
b'HTTP/1.1 101 Switching Protocols\r\n')
|
||||
await self.request.sock[1].awrite(b'Upgrade: websocket\r\n')
|
||||
await self.request.sock[1].awrite(b'Connection: Upgrade\r\n')
|
||||
await self.request.sock[1].awrite(
|
||||
b'Sec-WebSocket-Accept: ' + response + b'\r\n\r\n')
|
||||
|
||||
async def receive(self):
|
||||
"""Receive a message from the client."""
|
||||
while True:
|
||||
opcode, payload = await self._read_frame()
|
||||
send_opcode, data = self._process_websocket_frame(opcode, payload)
|
||||
if send_opcode: # pragma: no cover
|
||||
await self.send(data, send_opcode)
|
||||
elif data: # pragma: no branch
|
||||
return data
|
||||
|
||||
async def send(self, data, opcode=None):
|
||||
"""Send a message to the client.
|
||||
|
||||
:param data: the data to send, given as a string or bytes.
|
||||
:param opcode: a custom frame opcode to use. If not given, the opcode
|
||||
is ``TEXT`` or ``BINARY`` depending on the type of the
|
||||
data.
|
||||
"""
|
||||
frame = self._encode_websocket_frame(
|
||||
opcode or (self.TEXT if isinstance(data, str) else self.BINARY),
|
||||
data)
|
||||
await self.request.sock[1].awrite(frame)
|
||||
|
||||
async def close(self):
|
||||
"""Close the websocket connection."""
|
||||
if not self.closed: # pragma: no cover
|
||||
self.closed = True
|
||||
await self.send(b'', self.CLOSE)
|
||||
|
||||
def _handshake_response(self):
|
||||
connection = False
|
||||
upgrade = False
|
||||
websocket_key = None
|
||||
for header, value in self.request.headers.items():
|
||||
h = header.lower()
|
||||
if h == 'connection':
|
||||
connection = True
|
||||
if 'upgrade' not in value.lower():
|
||||
return self.request.app.abort(400)
|
||||
elif h == 'upgrade':
|
||||
upgrade = True
|
||||
if not value.lower() == 'websocket':
|
||||
return self.request.app.abort(400)
|
||||
elif h == 'sec-websocket-key':
|
||||
websocket_key = value
|
||||
if not connection or not upgrade or not websocket_key:
|
||||
return self.request.app.abort(400)
|
||||
d = hashlib.sha1(websocket_key.encode())
|
||||
d.update(b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
|
||||
return binascii.b2a_base64(d.digest())[:-1]
|
||||
|
||||
@classmethod
|
||||
def _parse_frame_header(cls, header):
|
||||
fin = header[0] & 0x80
|
||||
opcode = header[0] & 0x0f
|
||||
if fin == 0 or opcode == cls.CONT: # pragma: no cover
|
||||
raise WebSocketError('Continuation frames not supported')
|
||||
has_mask = header[1] & 0x80
|
||||
length = header[1] & 0x7f
|
||||
if length == 126:
|
||||
length = -2
|
||||
elif length == 127:
|
||||
length = -8
|
||||
return fin, opcode, has_mask, length
|
||||
|
||||
def _process_websocket_frame(self, opcode, payload):
|
||||
if opcode == self.TEXT:
|
||||
payload = payload.decode()
|
||||
elif opcode == self.BINARY:
|
||||
pass
|
||||
elif opcode == self.CLOSE:
|
||||
raise WebSocketError('Websocket connection closed')
|
||||
elif opcode == self.PING:
|
||||
return self.PONG, payload
|
||||
elif opcode == self.PONG: # pragma: no branch
|
||||
return None, None
|
||||
return None, payload
|
||||
|
||||
@classmethod
|
||||
def _encode_websocket_frame(cls, opcode, payload):
|
||||
frame = bytearray()
|
||||
frame.append(0x80 | opcode)
|
||||
if opcode == cls.TEXT:
|
||||
payload = payload.encode()
|
||||
if len(payload) < 126:
|
||||
frame.append(len(payload))
|
||||
elif len(payload) < (1 << 16):
|
||||
frame.append(126)
|
||||
frame.extend(len(payload).to_bytes(2, 'big'))
|
||||
else:
|
||||
frame.append(127)
|
||||
frame.extend(len(payload).to_bytes(8, 'big'))
|
||||
frame.extend(payload)
|
||||
return frame
|
||||
|
||||
async def _read_frame(self):
|
||||
header = await self.request.sock[0].read(2)
|
||||
if len(header) != 2: # pragma: no cover
|
||||
raise WebSocketError('Websocket connection closed')
|
||||
fin, opcode, has_mask, length = self._parse_frame_header(header)
|
||||
if length == -2:
|
||||
length = await self.request.sock[0].read(2)
|
||||
length = int.from_bytes(length, 'big')
|
||||
elif length == -8:
|
||||
length = await self.request.sock[0].read(8)
|
||||
length = int.from_bytes(length, 'big')
|
||||
max_allowed_length = Request.max_body_length \
|
||||
if self.max_message_length == -1 else self.max_message_length
|
||||
if length > max_allowed_length:
|
||||
raise WebSocketError('Message too large')
|
||||
if has_mask: # pragma: no cover
|
||||
mask = await self.request.sock[0].read(4)
|
||||
payload = await self.request.sock[0].read(length)
|
||||
if has_mask: # pragma: no cover
|
||||
payload = bytes(x ^ mask[i % 4] for i, x in enumerate(payload))
|
||||
return opcode, payload
|
||||
|
||||
|
||||
async def websocket_upgrade(request):
|
||||
"""Upgrade a request handler to a websocket connection.
|
||||
|
||||
This function can be called directly inside a route function to process a
|
||||
WebSocket upgrade handshake, for example after the user's credentials are
|
||||
verified. The function returns the websocket object::
|
||||
|
||||
@app.route('/echo')
|
||||
async def echo(request):
|
||||
if not authenticate_user(request):
|
||||
abort(401)
|
||||
ws = await websocket_upgrade(request)
|
||||
while True:
|
||||
message = await ws.receive()
|
||||
await ws.send(message)
|
||||
"""
|
||||
ws = WebSocket(request)
|
||||
await ws.handshake()
|
||||
|
||||
@request.after_request
|
||||
async def after_request(request, response):
|
||||
return Response.already_handled
|
||||
|
||||
return ws
|
||||
|
||||
|
||||
def websocket_wrapper(f, upgrade_function):
|
||||
@wraps(f)
|
||||
async def wrapper(request, *args, **kwargs):
|
||||
ws = await upgrade_function(request)
|
||||
try:
|
||||
await f(request, ws, *args, **kwargs)
|
||||
except OSError as exc:
|
||||
if exc.errno not in MUTED_SOCKET_ERRORS: # pragma: no cover
|
||||
raise
|
||||
except WebSocketError:
|
||||
pass
|
||||
except Exception as exc:
|
||||
print_exception(exc)
|
||||
finally: # pragma: no cover
|
||||
try:
|
||||
await ws.close()
|
||||
except Exception:
|
||||
pass
|
||||
return Response.already_handled
|
||||
return wrapper
|
||||
|
||||
|
||||
def with_websocket(f):
|
||||
"""Decorator to make a route a WebSocket endpoint.
|
||||
|
||||
This decorator is used to define a route that accepts websocket
|
||||
connections. The route then receives a websocket object as a second
|
||||
argument that it can use to send and receive messages::
|
||||
|
||||
@app.route('/echo')
|
||||
@with_websocket
|
||||
async def echo(request, ws):
|
||||
while True:
|
||||
message = await ws.receive()
|
||||
await ws.send(message)
|
||||
"""
|
||||
return websocket_wrapper(f, websocket_upgrade)
|
||||
Whitespace-only changes.
@@ -1,14 +0,0 @@
|
||||
class Loader:
|
||||
|
||||
def __init__(self, pkg, dir):
|
||||
if dir == ".":
|
||||
dir = ""
|
||||
else:
|
||||
dir = dir.replace("/", ".") + "."
|
||||
if pkg and pkg != "__main__":
|
||||
dir = pkg + "." + dir
|
||||
self.p = dir
|
||||
|
||||
def load(self, name):
|
||||
name = name.replace(".", "_")
|
||||
return __import__(self.p + name, None, None, (name,)).render
|
||||
@@ -1,21 +0,0 @@
|
||||
# (c) 2014-2020 Paul Sokolovsky. MIT license.
|
||||
try:
|
||||
from uos import stat, remove
|
||||
except:
|
||||
from os import stat, remove
|
||||
from . import source
|
||||
|
||||
|
||||
class Loader(source.Loader):
|
||||
|
||||
def load(self, name):
|
||||
o_path = self.pkg_path + self.compiled_path(name)
|
||||
i_path = self.pkg_path + self.dir + "/" + name
|
||||
try:
|
||||
o_stat = stat(o_path)
|
||||
i_stat = stat(i_path)
|
||||
if i_stat[8] > o_stat[8]:
|
||||
# input file is newer, remove output to force recompile
|
||||
remove(o_path)
|
||||
finally:
|
||||
return super().load(name)
|
||||
@@ -1,188 +0,0 @@
|
||||
# (c) 2014-2019 Paul Sokolovsky. MIT license.
|
||||
from . import compiled
|
||||
|
||||
|
||||
class Compiler:
|
||||
|
||||
START_CHAR = "{"
|
||||
STMNT = "%"
|
||||
STMNT_END = "%}"
|
||||
EXPR = "{"
|
||||
EXPR_END = "}}"
|
||||
|
||||
def __init__(self, file_in, file_out, indent=0, seq=0, loader=None):
|
||||
self.file_in = file_in
|
||||
self.file_out = file_out
|
||||
self.loader = loader
|
||||
self.seq = seq
|
||||
self._indent = indent
|
||||
self.stack = []
|
||||
self.in_literal = False
|
||||
self.flushed_header = False
|
||||
self.args = "*a, **d"
|
||||
|
||||
def indent(self, adjust=0):
|
||||
if not self.flushed_header:
|
||||
self.flushed_header = True
|
||||
self.indent()
|
||||
self.file_out.write("def render%s(%s):\n" % (str(self.seq) if self.seq else "", self.args))
|
||||
self.stack.append("def")
|
||||
self.file_out.write(" " * (len(self.stack) + self._indent + adjust))
|
||||
|
||||
def literal(self, s):
|
||||
if not s:
|
||||
return
|
||||
if not self.in_literal:
|
||||
self.indent()
|
||||
self.file_out.write('yield """')
|
||||
self.in_literal = True
|
||||
self.file_out.write(s.replace('"', '\\"'))
|
||||
|
||||
def close_literal(self):
|
||||
if self.in_literal:
|
||||
self.file_out.write('"""\n')
|
||||
self.in_literal = False
|
||||
|
||||
def render_expr(self, e):
|
||||
self.indent()
|
||||
self.file_out.write('yield str(' + e + ')\n')
|
||||
|
||||
def parse_statement(self, stmt):
|
||||
tokens = stmt.split(None, 1)
|
||||
if tokens[0] == "args":
|
||||
if len(tokens) > 1:
|
||||
self.args = tokens[1]
|
||||
else:
|
||||
self.args = ""
|
||||
elif tokens[0] == "set":
|
||||
self.indent()
|
||||
self.file_out.write(stmt[3:].strip() + "\n")
|
||||
elif tokens[0] == "include":
|
||||
if not self.flushed_header:
|
||||
# If there was no other output, we still need a header now
|
||||
self.indent()
|
||||
tokens = tokens[1].split(None, 1)
|
||||
args = ""
|
||||
if len(tokens) > 1:
|
||||
args = tokens[1]
|
||||
if tokens[0][0] == "{":
|
||||
self.indent()
|
||||
# "1" as fromlist param is uPy hack
|
||||
self.file_out.write('_ = __import__(%s.replace(".", "_"), None, None, 1)\n' % tokens[0][2:-2])
|
||||
self.indent()
|
||||
self.file_out.write("yield from _.render(%s)\n" % args)
|
||||
return
|
||||
|
||||
with self.loader.input_open(tokens[0][1:-1]) as inc:
|
||||
self.seq += 1
|
||||
c = Compiler(inc, self.file_out, len(self.stack) + self._indent, self.seq)
|
||||
inc_id = self.seq
|
||||
self.seq = c.compile()
|
||||
self.indent()
|
||||
self.file_out.write("yield from render%d(%s)\n" % (inc_id, args))
|
||||
elif len(tokens) > 1:
|
||||
if tokens[0] == "elif":
|
||||
assert self.stack[-1] == "if"
|
||||
self.indent(-1)
|
||||
self.file_out.write(stmt + ":\n")
|
||||
else:
|
||||
self.indent()
|
||||
self.file_out.write(stmt + ":\n")
|
||||
self.stack.append(tokens[0])
|
||||
else:
|
||||
if stmt.startswith("end"):
|
||||
assert self.stack[-1] == stmt[3:]
|
||||
self.stack.pop(-1)
|
||||
elif stmt == "else":
|
||||
assert self.stack[-1] == "if"
|
||||
self.indent(-1)
|
||||
self.file_out.write("else:\n")
|
||||
else:
|
||||
assert False
|
||||
|
||||
def parse_line(self, l):
|
||||
while l:
|
||||
start = l.find(self.START_CHAR)
|
||||
if start == -1:
|
||||
self.literal(l)
|
||||
return
|
||||
self.literal(l[:start])
|
||||
self.close_literal()
|
||||
sel = l[start + 1]
|
||||
#print("*%s=%s=" % (sel, EXPR))
|
||||
if sel == self.STMNT:
|
||||
end = l.find(self.STMNT_END)
|
||||
assert end > 0
|
||||
stmt = l[start + len(self.START_CHAR + self.STMNT):end].strip()
|
||||
self.parse_statement(stmt)
|
||||
end += len(self.STMNT_END)
|
||||
l = l[end:]
|
||||
if not self.in_literal and l == "\n":
|
||||
break
|
||||
elif sel == self.EXPR:
|
||||
# print("EXPR")
|
||||
end = l.find(self.EXPR_END)
|
||||
assert end > 0
|
||||
expr = l[start + len(self.START_CHAR + self.EXPR):end].strip()
|
||||
self.render_expr(expr)
|
||||
end += len(self.EXPR_END)
|
||||
l = l[end:]
|
||||
else:
|
||||
self.literal(l[start])
|
||||
l = l[start + 1:]
|
||||
|
||||
def header(self):
|
||||
self.file_out.write("# Autogenerated file\n")
|
||||
|
||||
def compile(self):
|
||||
self.header()
|
||||
for l in self.file_in:
|
||||
self.parse_line(l)
|
||||
self.close_literal()
|
||||
return self.seq
|
||||
|
||||
|
||||
class Loader(compiled.Loader):
|
||||
|
||||
def __init__(self, pkg, dir):
|
||||
super().__init__(pkg, dir)
|
||||
self.dir = dir
|
||||
if pkg == "__main__":
|
||||
# if pkg isn't really a package, don't bother to use it
|
||||
# it means we're running from "filesystem directory", not
|
||||
# from a package.
|
||||
pkg = None
|
||||
|
||||
self.pkg_path = ""
|
||||
if pkg:
|
||||
p = __import__(pkg)
|
||||
if isinstance(p.__path__, str):
|
||||
# uPy
|
||||
self.pkg_path = p.__path__
|
||||
else:
|
||||
# CPy
|
||||
self.pkg_path = p.__path__[0]
|
||||
self.pkg_path += "/"
|
||||
|
||||
def input_open(self, template):
|
||||
path = self.pkg_path + self.dir + "/" + template
|
||||
return open(path)
|
||||
|
||||
def compiled_path(self, template):
|
||||
return self.dir + "/" + template.replace(".", "_") + ".py"
|
||||
|
||||
def load(self, name):
|
||||
try:
|
||||
return super().load(name)
|
||||
except (OSError, ImportError):
|
||||
pass
|
||||
|
||||
compiled_path = self.pkg_path + self.compiled_path(name)
|
||||
|
||||
f_in = self.input_open(name)
|
||||
f_out = open(compiled_path, "w")
|
||||
c = Compiler(f_in, f_out, loader=self)
|
||||
c.compile()
|
||||
f_in.close()
|
||||
f_out.close()
|
||||
return super().load(name)
|
||||
@@ -1,3 +0,0 @@
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
python_files = ["test_endpoints_pytest.py", "engine_tests/test_*.py"]
|
||||
@@ -1,16 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
PORT="${PORT:-80}"
|
||||
|
||||
# On watchfiles restarts the previous process can linger briefly.
|
||||
# Proactively terminate any listener on the target port before boot.
|
||||
pids="$(ss -ltnp "sport = :$PORT" 2>/dev/null | sed -n 's/.*pid=\([0-9]\+\).*/\1/p' | sort -u)"
|
||||
if [ -n "${pids}" ]; then
|
||||
kill -TERM ${pids} 2>/dev/null || true
|
||||
sleep 0.3
|
||||
fi
|
||||
|
||||
cd "$ROOT_DIR/src"
|
||||
exec python main.py
|
||||
@@ -1,32 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Install systemd service so LED controller starts at boot.
|
||||
# Run once: sudo scripts/install-boot-service.sh
|
||||
set -e
|
||||
cd "$(dirname "$0")/.."
|
||||
REPO="$(pwd)"
|
||||
SERVICE_NAME="led-controller.service"
|
||||
UNIT_PATH="/etc/systemd/system/$SERVICE_NAME"
|
||||
if [ ! -f "scripts/led-controller.service" ]; then
|
||||
echo "Run this script from the repo root."
|
||||
exit 1
|
||||
fi
|
||||
export PIPENV_VENV_IN_PROJECT="${PIPENV_VENV_IN_PROJECT:-1}"
|
||||
if command -v pipenv >/dev/null 2>&1; then
|
||||
PY="$(command -v python3)"
|
||||
if [ -z "$PY" ]; then
|
||||
echo "python3 not found; install python3." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Ensuring Pipenv deps with $PY (venv in project: .venv when PIPENV_VENV_IN_PROJECT=1)…"
|
||||
# --skip-lock: install from Pipfile only (avoids lock/Python hash mismatches on device).
|
||||
pipenv install --quiet --skip-lock --python "$PY"
|
||||
pipenv --venv > scripts/.led-controller-venv
|
||||
fi
|
||||
chmod +x scripts/start.sh
|
||||
sudo cp "scripts/led-controller.service" "$UNIT_PATH"
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable "$SERVICE_NAME"
|
||||
echo "Installed and enabled $SERVICE_NAME"
|
||||
echo "Start now: sudo systemctl start $SERVICE_NAME"
|
||||
echo "Status: sudo systemctl status $SERVICE_NAME"
|
||||
echo "Logs: journalctl -u $SERVICE_NAME -f"
|
||||
@@ -1,20 +0,0 @@
|
||||
[Unit]
|
||||
Description=LED Controller web server
|
||||
# Use network.target only. Ordering after network-online.target can block `systemctl start`
|
||||
# until wait-online finishes; Wi‑Fi/DHCP delays then look like a hung start job.
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=pi
|
||||
WorkingDirectory=/home/pi/led-controller
|
||||
Environment=PORT=80
|
||||
Environment=PATH=/home/pi/.local/bin:/usr/local/bin:/usr/bin:/bin
|
||||
ExecStart=/bin/bash /home/pi/led-controller/scripts/start.sh
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
# pipenv/first bind can be slow; avoid misleading "activating" forever if misconfigured
|
||||
TimeoutStartSec=120
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1 @@
|
||||
build/
|
||||
@@ -0,0 +1,3 @@
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
project(led_test)
|
||||
@@ -0,0 +1,20 @@
|
||||
dependencies:
|
||||
espressif/led_strip:
|
||||
component_hash: 28c6509a727ef74925b372ed404772aeedf11cce10b78c3f69b3c66799095e2d
|
||||
dependencies:
|
||||
- name: idf
|
||||
require: private
|
||||
version: '>=4.4'
|
||||
source:
|
||||
registry_url: https://components.espressif.com/
|
||||
type: service
|
||||
version: 2.5.5
|
||||
idf:
|
||||
source:
|
||||
type: idf
|
||||
version: 5.5.5
|
||||
direct_dependencies:
|
||||
- espressif/led_strip
|
||||
manifest_hash: 08e0dee6eca83e7d8d73c22998d68a19eb9f0d1566cff539c1124b10b36f26e6
|
||||
target: esp32c3
|
||||
version: 2.0.0
|
||||
@@ -0,0 +1 @@
|
||||
idf_component_register(SRCS "main.c" INCLUDE_DIRS ".")
|
||||
@@ -0,0 +1,2 @@
|
||||
dependencies:
|
||||
espressif/led_strip: "^2.5.0"
|
||||
@@ -0,0 +1,29 @@
|
||||
// Steady WS2812 signal on GPIO 10 for probing with a meter: the first 10 LEDs green, a frame
|
||||
// every 20 ms so the pin never idles. The data pin should read roughly 0.3-1 V DC against GND.
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "led_strip.h"
|
||||
#include "esp_log.h"
|
||||
|
||||
#define LED_GPIO 10
|
||||
#define NUM_LEDS 200
|
||||
#define LIT 10
|
||||
|
||||
static const char *TAG = "led_test";
|
||||
|
||||
void app_main(void)
|
||||
{
|
||||
led_strip_handle_t strip;
|
||||
led_strip_config_t cfg = { .strip_gpio_num = LED_GPIO, .max_leds = NUM_LEDS };
|
||||
led_strip_rmt_config_t rmt = { .resolution_hz = 10 * 1000 * 1000 };
|
||||
ESP_ERROR_CHECK(led_strip_new_rmt_device(&cfg, &rmt, &strip));
|
||||
for (int i = 0; i < LIT; i++)
|
||||
led_strip_set_pixel(strip, i, 0, 120, 0);
|
||||
ESP_LOGI(TAG, "sending to GPIO %d continuously", LED_GPIO);
|
||||
for (unsigned n = 0;; n++) {
|
||||
led_strip_refresh(strip);
|
||||
if (n % 250 == 0)
|
||||
ESP_LOGI(TAG, "frames sent: %u", n);
|
||||
vTaskDelay(pdMS_TO_TICKS(20));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
28c6509a727ef74925b372ed404772aeedf11cce10b78c3f69b3c66799095e2d
|
||||
@@ -0,0 +1,54 @@
|
||||
## 2.5.5
|
||||
|
||||
- Simplified the led_strip component dependency, the time of full build with ESP-IDF v5.3 can now be shorter.
|
||||
|
||||
## 2.5.4
|
||||
|
||||
- Inserted extra delay when initialize the SPI LED device, to ensure all LEDs are in the reset state correctly
|
||||
|
||||
## 2.5.3
|
||||
|
||||
- Extend reset time (280us) to support WS2812B-V5
|
||||
|
||||
## 2.5.2
|
||||
|
||||
- Added API reference doc (api.md)
|
||||
|
||||
## 2.5.0
|
||||
|
||||
- Enabled support for IDF4.4 and above
|
||||
- with RMT backend only
|
||||
- Added API `led_strip_set_pixel_hsv`
|
||||
|
||||
## 2.4.0
|
||||
|
||||
- Support configurable SPI mode to control leds
|
||||
- recommend enabling DMA when using SPI mode
|
||||
|
||||
## 2.3.0
|
||||
|
||||
- Support configurable RMT channel size by setting `mem_block_symbols`
|
||||
|
||||
## 2.2.0
|
||||
|
||||
- Support for 4 components RGBW leds (SK6812):
|
||||
- in led_strip_config_t new fields
|
||||
led_pixel_format, controlling byte format (LED_PIXEL_FORMAT_GRB, LED_PIXEL_FORMAT_GRBW)
|
||||
led_model, used to configure bit timing (LED_MODEL_WS2812, LED_MODEL_SK6812)
|
||||
- new API led_strip_set_pixel_rgbw
|
||||
- new interface type set_pixel_rgbw
|
||||
|
||||
## 2.1.0
|
||||
|
||||
- Support DMA feature, which offloads the CPU by a lot when it comes to drive a bunch of LEDs
|
||||
- Support various RMT clock sources
|
||||
- Acquire and release the power management lock before and after each refresh
|
||||
- New driver flag: `invert_out` which can invert the led control signal by hardware
|
||||
|
||||
## 2.0.0
|
||||
|
||||
- Reimplemented the driver using the new RMT driver (`driver/rmt_tx.h`)
|
||||
|
||||
## 1.0.0
|
||||
|
||||
- Initial driver version, based on the legacy RMT driver (`driver/rmt.h`)
|
||||
@@ -0,0 +1 @@
|
||||
{"version": "1.0", "algorithm": "sha256", "created_at": "2025-05-21T16:14:59.641729+00:00", "files": [{"path": "CMakeLists.txt", "size": 1131, "hash": "527e1c93841dcf98e4e30767c0b55ec117e1af52638eb72a7aec23d25a31074b"}, {"path": "api.md", "size": 12932, "hash": "fa49f00d63cab790d2e3ffb1cc2436ec337fab336f55a8c2730aa1d923b655e4"}, {"path": "LICENSE", "size": 11358, "hash": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"}, {"path": "CHANGELOG.md", "size": 1469, "hash": "8f323462bb2f1c0159b2e2c5fef08628d47a7ff55ef9829221889c2486bbfad8"}, {"path": "idf_component.yml", "size": 335, "hash": "12ff580cba4f58c8c41cff96d0c81bc001d40d99ad15ba16afabce64261d4b8a"}, {"path": "README.md", "size": 4920, "hash": "f94c5b61f704ec6247450b3252e35b6130b5350edff560dd172f3a7345fac637"}, {"path": "Doxyfile", "size": 684, "hash": "f05e35d4108be9b46398fbd7c0cef9880c0e802abbe36a36a49c7a0ac4126826"}, {"path": "interface/led_strip_interface.h", "size": 2934, "hash": "5b7d0c326d0d0d9748830d4aec46d765400e1446055d4a1197c83111e937d74c"}, {"path": "include/led_strip_spi.h", "size": 1596, "hash": "d79f3a803834ff28930a32380a48afe0977de167d31d673589e98c2a3cf66e5f"}, {"path": "include/led_strip_types.h", "size": 1352, "hash": "13fb81ed62bcaa6d8686c5b095c45adede526bcba3980ad0f9341c38b4bedc96"}, {"path": "include/led_strip_rmt.h", "size": 1876, "hash": "d3d6f0880f7443c21b48c1715e524282688ce9743085b4d7358322f6714b82d2"}, {"path": "include/led_strip.h", "size": 3586, "hash": "f01e0f282fe3042b03381495c616eae211d0b75d04c64e29b3dc92721fbadc4f"}, {"path": "src/led_strip_spi_dev.c", "size": 9346, "hash": "bff2b2e1dc3240d21b1679fba42f0f4395bf9449b21ee3c2408bbc1ae1b9c211"}, {"path": "src/led_strip_rmt_encoder.h", "size": 977, "hash": "690381c35ace2703a5c7156f6547a8524f4cbfe5bef40be619e2097960120a40"}, {"path": "src/led_strip_rmt_dev_idf4.c", "size": 7143, "hash": "81b4a239b554f1ed3326b5380490316a9602bc606a00691a5f325adcbdf2145c"}, {"path": "src/led_strip_api.c", "size": 2575, "hash": "2a8be1284ed6b2ad000907bca3829f71a499aa0d06d47f078d6306392dcc4f4c"}, {"path": "src/led_strip_rmt_encoder.c", "size": 6097, "hash": "7e349a50bd3a161932200dd3da24a6e7316438e0e31615aed6d20deeb3917558"}, {"path": "src/led_strip_rmt_dev.c", "size": 6885, "hash": "3a41df64f2582f3abedd4bddf3111a6bba4a1f886d58dd8391ac2b903ea82e9f"}, {"path": "examples/led_strip_rmt_ws2812/CMakeLists.txt", "size": 381, "hash": "26a31ebd66ad328361d8b69d7f99b9250685932d077dc300dc96280ff6623bc4"}, {"path": "examples/led_strip_rmt_ws2812/README.md", "size": 1200, "hash": "a5f39b31c5f7cbf548ee31b61ab22e430a6c823404c0ddb113703512bcb3ad3c"}, {"path": "examples/led_strip_spi_ws2812/CMakeLists.txt", "size": 381, "hash": "3096c4f9363c9ccf5733c19542163dcb4497764435fb996156552b81c55c6e14"}, {"path": "examples/led_strip_spi_ws2812/README.md", "size": 1201, "hash": "2c02a29197cd1f2d4af4c4c9cd44677e303b0e168a1773eef9fc3fdb39377d27"}, {"path": "examples/led_strip_spi_ws2812/main/CMakeLists.txt", "size": 99, "hash": "34e7f83d26bca924c629ea2012e6f200b415d486907863fe936d94872ff739eb"}, {"path": "examples/led_strip_spi_ws2812/main/idf_component.yml", "size": 142, "hash": "fe89054a1b7988a7068a2952d01bfc6ae40dc59a33bc7dcc8a98cbb231d472fb"}, {"path": "examples/led_strip_spi_ws2812/main/led_strip_spi_ws2812_main.c", "size": 2462, "hash": "8e052cbfd7e27d5e3382f5f115db23ea884db25f4a73fb69d34ed4867dfbf80a"}, {"path": "examples/led_strip_rmt_ws2812/main/CMakeLists.txt", "size": 99, "hash": "8960b68811805d3aa40e1a7f44ddf7400c0d0731829b6d2b3b1584d8dcd3b392"}, {"path": "examples/led_strip_rmt_ws2812/main/idf_component.yml", "size": 125, "hash": "05a57e3d6808bac9e1a2f41cbcfa26d90b5a3427d518b619a1ff4946e62d791d"}, {"path": "examples/led_strip_rmt_ws2812/main/led_strip_rmt_ws2812_main.c", "size": 2705, "hash": "497f3b88387865c41f7a30c7ab5e0086066a344bf16f250d973bf0af907fa78f"}]}
|
||||
@@ -0,0 +1,31 @@
|
||||
include($ENV{IDF_PATH}/tools/cmake/version.cmake)
|
||||
|
||||
set(srcs "src/led_strip_api.c")
|
||||
set(public_requires)
|
||||
|
||||
# Starting from esp-idf v5.x, the RMT driver is rewritten
|
||||
if("${IDF_VERSION_MAJOR}.${IDF_VERSION_MINOR}" VERSION_GREATER_EQUAL "5.0")
|
||||
if(CONFIG_SOC_RMT_SUPPORTED)
|
||||
list(APPEND srcs "src/led_strip_rmt_dev.c" "src/led_strip_rmt_encoder.c")
|
||||
endif()
|
||||
else()
|
||||
list(APPEND srcs "src/led_strip_rmt_dev_idf4.c")
|
||||
endif()
|
||||
|
||||
# the SPI backend driver relies on some feature that was available in IDF 5.1
|
||||
if("${IDF_VERSION_MAJOR}.${IDF_VERSION_MINOR}" VERSION_GREATER_EQUAL "5.1")
|
||||
if(CONFIG_SOC_GPSPI_SUPPORTED)
|
||||
list(APPEND srcs "src/led_strip_spi_dev.c")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
# Starting from esp-idf v5.3, the RMT and SPI drivers are moved to separate components
|
||||
if("${IDF_VERSION_MAJOR}.${IDF_VERSION_MINOR}" VERSION_GREATER_EQUAL "5.3")
|
||||
list(APPEND public_requires "esp_driver_rmt" "esp_driver_spi")
|
||||
else()
|
||||
list(APPEND public_requires "driver")
|
||||
endif()
|
||||
|
||||
idf_component_register(SRCS ${srcs}
|
||||
INCLUDE_DIRS "include" "interface"
|
||||
REQUIRES ${public_requires})
|
||||
@@ -0,0 +1,28 @@
|
||||
# Set this to the header file you want
|
||||
INPUT = \
|
||||
include/ \
|
||||
interface/
|
||||
|
||||
# Output goes into doxygen directory, which is added to gitignore
|
||||
OUTPUT_DIRECTORY = doxygen
|
||||
|
||||
# Warning-related settings, it's recommended to keep them enabled
|
||||
WARN_IF_UNDOC_ENUM_VAL = YES
|
||||
WARN_AS_ERROR = YES
|
||||
|
||||
# Other common settings
|
||||
FULL_PATH_NAMES = YES
|
||||
ENABLE_PREPROCESSING = YES
|
||||
MACRO_EXPANSION = YES
|
||||
OPTIMIZE_OUTPUT_FOR_C = YES
|
||||
EXPAND_ONLY_PREDEF = YES
|
||||
EXTRACT_ALL = YES
|
||||
PREDEFINED = $(ENV_DOXYGEN_DEFINES)
|
||||
HAVE_DOT = NO
|
||||
GENERATE_XML = YES
|
||||
XML_OUTPUT = xml
|
||||
GENERATE_HTML = NO
|
||||
HAVE_DOT = NO
|
||||
GENERATE_LATEX = NO
|
||||
QUIET = YES
|
||||
MARKDOWN_SUPPORT = YES
|
||||
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,97 @@
|
||||
# LED Strip Driver
|
||||
|
||||
[](https://components.espressif.com/components/espressif/led_strip)
|
||||
|
||||
This driver is designed for addressable LEDs like [WS2812](http://www.world-semi.com/Certifications/WS2812B.html), where each LED is controlled by a single data line.
|
||||
|
||||
## Backend Controllers
|
||||
|
||||
### The [RMT](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/rmt.html) Peripheral
|
||||
|
||||
This is the most economical way to drive the LEDs because it only consumes one RMT channel, leaving other channels free to use. However, the memory usage increases dramatically with the number of LEDs. If the RMT hardware can't be assist by DMA, the driver will going into interrupt very frequently, thus result in a high CPU usage. What's worse, if the RMT interrupt is delayed or not serviced in time (e.g. if Wi-Fi interrupt happens on the same CPU core), the RMT transaction will be corrupted and the LEDs will display incorrect colors. If you want to use RMT to drive a large number of LEDs, you'd better to enable the DMA feature if possible [^1].
|
||||
|
||||
#### Allocate LED Strip Object with RMT Backend
|
||||
|
||||
```c
|
||||
#define BLINK_GPIO 0
|
||||
|
||||
led_strip_handle_t led_strip;
|
||||
|
||||
/* LED strip initialization with the GPIO and pixels number*/
|
||||
led_strip_config_t strip_config = {
|
||||
.strip_gpio_num = BLINK_GPIO, // The GPIO that connected to the LED strip's data line
|
||||
.max_leds = 1, // The number of LEDs in the strip,
|
||||
.led_pixel_format = LED_PIXEL_FORMAT_GRB, // Pixel format of your LED strip
|
||||
.led_model = LED_MODEL_WS2812, // LED strip model
|
||||
.flags.invert_out = false, // whether to invert the output signal (useful when your hardware has a level inverter)
|
||||
};
|
||||
|
||||
led_strip_rmt_config_t rmt_config = {
|
||||
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)
|
||||
.rmt_channel = 0,
|
||||
#else
|
||||
.clk_src = RMT_CLK_SRC_DEFAULT, // different clock source can lead to different power consumption
|
||||
.resolution_hz = 10 * 1000 * 1000, // 10MHz
|
||||
.flags.with_dma = false, // whether to enable the DMA feature
|
||||
#endif
|
||||
};
|
||||
ESP_ERROR_CHECK(led_strip_new_rmt_device(&strip_config, &rmt_config, &led_strip));
|
||||
```
|
||||
|
||||
You can create multiple LED strip objects with different GPIOs and pixel numbers. The backend driver will automatically allocate the RMT channel for you if there is more available.
|
||||
|
||||
### The [SPI](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/peripherals/spi_master.html) Peripheral
|
||||
|
||||
SPI peripheral can also be used to generate the timing required by the LED strip. However this backend is not as economical as the RMT one, because it will take up the whole **bus**, unlike the RMT just takes one **channel**. You **CANT** connect other devices to the same SPI bus if it's been used by the led_strip, because the led_strip doesn't have the concept of "Chip Select".
|
||||
|
||||
Please note, the SPI backend has a dependency of **ESP-IDF >= 5.1**
|
||||
|
||||
#### Allocate LED Strip Object with SPI Backend
|
||||
|
||||
```c
|
||||
#define BLINK_GPIO 0
|
||||
|
||||
led_strip_handle_t led_strip;
|
||||
|
||||
/* LED strip initialization with the GPIO and pixels number*/
|
||||
led_strip_config_t strip_config = {
|
||||
.strip_gpio_num = BLINK_GPIO, // The GPIO that connected to the LED strip's data line
|
||||
.max_leds = 1, // The number of LEDs in the strip,
|
||||
.led_pixel_format = LED_PIXEL_FORMAT_GRB, // Pixel format of your LED strip
|
||||
.led_model = LED_MODEL_WS2812, // LED strip model
|
||||
.flags.invert_out = false, // whether to invert the output signal (useful when your hardware has a level inverter)
|
||||
};
|
||||
|
||||
led_strip_spi_config_t spi_config = {
|
||||
.clk_src = SPI_CLK_SRC_DEFAULT, // different clock source can lead to different power consumption
|
||||
.flags.with_dma = true, // Using DMA can improve performance and help drive more LEDs
|
||||
.spi_bus = SPI2_HOST, // SPI bus ID
|
||||
};
|
||||
ESP_ERROR_CHECK(led_strip_new_spi_device(&strip_config, &spi_config, &led_strip));
|
||||
```
|
||||
|
||||
The number of LED strip objects can be created depends on how many free SPI buses are free to use in your project.
|
||||
|
||||
## FAQ
|
||||
|
||||
* Which led_strip backend should I choose?
|
||||
* It depends on your application requirement and target chip's ability.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A{Is RMT supported?}
|
||||
A --> |No| B[SPI backend]
|
||||
B --> C{Does the led strip has \n a larger number of LEDs?}
|
||||
C --> |No| D[Don't have to enable the DMA of the backend]
|
||||
C --> |Yes| E[Enable the DMA of the backend]
|
||||
A --> |Yes| F{Does the led strip has \n a larger number of LEDs?}
|
||||
F --> |Yes| G{Does RMT support DMA?}
|
||||
G --> |Yes| E
|
||||
G --> |No| B
|
||||
F --> |No| H[RMT backend] --> D
|
||||
```
|
||||
|
||||
* How to set the brightness of the LED strip?
|
||||
* You can tune the brightness by scaling the value of each R-G-B element with a **same** factor. But pay attention to the overflow of the value.
|
||||
|
||||
[^1]: The RMT DMA feature is not available on all ESP chips. Please check the data sheet before using it.
|
||||
@@ -0,0 +1,454 @@
|
||||
# API Reference
|
||||
|
||||
## Header files
|
||||
|
||||
- [include/led_strip.h](#file-includeled_striph)
|
||||
- [include/led_strip_rmt.h](#file-includeled_strip_rmth)
|
||||
- [include/led_strip_spi.h](#file-includeled_strip_spih)
|
||||
- [include/led_strip_types.h](#file-includeled_strip_typesh)
|
||||
- [interface/led_strip_interface.h](#file-interfaceled_strip_interfaceh)
|
||||
|
||||
## File include/led_strip.h
|
||||
|
||||
## Functions
|
||||
|
||||
| Type | Name |
|
||||
| ---: | :--- |
|
||||
| esp\_err\_t | [**led\_strip\_clear**](#function-led_strip_clear) ([**led\_strip\_handle\_t**](#typedef-led_strip_handle_t) strip) <br>_Clear LED strip (turn off all LEDs)_ |
|
||||
| esp\_err\_t | [**led\_strip\_del**](#function-led_strip_del) ([**led\_strip\_handle\_t**](#typedef-led_strip_handle_t) strip) <br>_Free LED strip resources._ |
|
||||
| esp\_err\_t | [**led\_strip\_refresh**](#function-led_strip_refresh) ([**led\_strip\_handle\_t**](#typedef-led_strip_handle_t) strip) <br>_Refresh memory colors to LEDs._ |
|
||||
| esp\_err\_t | [**led\_strip\_set\_pixel**](#function-led_strip_set_pixel) ([**led\_strip\_handle\_t**](#typedef-led_strip_handle_t) strip, uint32\_t index, uint32\_t red, uint32\_t green, uint32\_t blue) <br>_Set RGB for a specific pixel._ |
|
||||
| esp\_err\_t | [**led\_strip\_set\_pixel\_hsv**](#function-led_strip_set_pixel_hsv) ([**led\_strip\_handle\_t**](#typedef-led_strip_handle_t) strip, uint32\_t index, uint16\_t hue, uint8\_t saturation, uint8\_t value) <br>_Set HSV for a specific pixel._ |
|
||||
| esp\_err\_t | [**led\_strip\_set\_pixel\_rgbw**](#function-led_strip_set_pixel_rgbw) ([**led\_strip\_handle\_t**](#typedef-led_strip_handle_t) strip, uint32\_t index, uint32\_t red, uint32\_t green, uint32\_t blue, uint32\_t white) <br>_Set RGBW for a specific pixel._ |
|
||||
|
||||
## Functions Documentation
|
||||
|
||||
### function `led_strip_clear`
|
||||
|
||||
_Clear LED strip (turn off all LEDs)_
|
||||
|
||||
```c
|
||||
esp_err_t led_strip_clear (
|
||||
led_strip_handle_t strip
|
||||
)
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
|
||||
- `strip` LED strip
|
||||
|
||||
**Returns:**
|
||||
|
||||
- ESP\_OK: Clear LEDs successfully
|
||||
- ESP\_FAIL: Clear LEDs failed because some other error occurred
|
||||
|
||||
### function `led_strip_del`
|
||||
|
||||
_Free LED strip resources._
|
||||
|
||||
```c
|
||||
esp_err_t led_strip_del (
|
||||
led_strip_handle_t strip
|
||||
)
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
|
||||
- `strip` LED strip
|
||||
|
||||
**Returns:**
|
||||
|
||||
- ESP\_OK: Free resources successfully
|
||||
- ESP\_FAIL: Free resources failed because error occurred
|
||||
|
||||
### function `led_strip_refresh`
|
||||
|
||||
_Refresh memory colors to LEDs._
|
||||
|
||||
```c
|
||||
esp_err_t led_strip_refresh (
|
||||
led_strip_handle_t strip
|
||||
)
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
|
||||
- `strip` LED strip
|
||||
|
||||
**Returns:**
|
||||
|
||||
- ESP\_OK: Refresh successfully
|
||||
- ESP\_FAIL: Refresh failed because some other error occurred
|
||||
|
||||
**Note:**
|
||||
|
||||
: After updating the LED colors in the memory, a following invocation of this API is needed to flush colors to strip.
|
||||
|
||||
### function `led_strip_set_pixel`
|
||||
|
||||
_Set RGB for a specific pixel._
|
||||
|
||||
```c
|
||||
esp_err_t led_strip_set_pixel (
|
||||
led_strip_handle_t strip,
|
||||
uint32_t index,
|
||||
uint32_t red,
|
||||
uint32_t green,
|
||||
uint32_t blue
|
||||
)
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
|
||||
- `strip` LED strip
|
||||
- `index` index of pixel to set
|
||||
- `red` red part of color
|
||||
- `green` green part of color
|
||||
- `blue` blue part of color
|
||||
|
||||
**Returns:**
|
||||
|
||||
- ESP\_OK: Set RGB for a specific pixel successfully
|
||||
- ESP\_ERR\_INVALID\_ARG: Set RGB for a specific pixel failed because of invalid parameters
|
||||
- ESP\_FAIL: Set RGB for a specific pixel failed because other error occurred
|
||||
|
||||
### function `led_strip_set_pixel_hsv`
|
||||
|
||||
_Set HSV for a specific pixel._
|
||||
|
||||
```c
|
||||
esp_err_t led_strip_set_pixel_hsv (
|
||||
led_strip_handle_t strip,
|
||||
uint32_t index,
|
||||
uint16_t hue,
|
||||
uint8_t saturation,
|
||||
uint8_t value
|
||||
)
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
|
||||
- `strip` LED strip
|
||||
- `index` index of pixel to set
|
||||
- `hue` hue part of color (0 - 360)
|
||||
- `saturation` saturation part of color (0 - 255, rescaled from 0 - 1. e.g. saturation = 0.5, rescaled to 127)
|
||||
- `value` value part of color (0 - 255, rescaled from 0 - 1. e.g. value = 0.5, rescaled to 127)
|
||||
|
||||
**Returns:**
|
||||
|
||||
- ESP\_OK: Set HSV color for a specific pixel successfully
|
||||
- ESP\_ERR\_INVALID\_ARG: Set HSV color for a specific pixel failed because of an invalid argument
|
||||
- ESP\_FAIL: Set HSV color for a specific pixel failed because other error occurred
|
||||
|
||||
### function `led_strip_set_pixel_rgbw`
|
||||
|
||||
_Set RGBW for a specific pixel._
|
||||
|
||||
```c
|
||||
esp_err_t led_strip_set_pixel_rgbw (
|
||||
led_strip_handle_t strip,
|
||||
uint32_t index,
|
||||
uint32_t red,
|
||||
uint32_t green,
|
||||
uint32_t blue,
|
||||
uint32_t white
|
||||
)
|
||||
```
|
||||
|
||||
**Note:**
|
||||
|
||||
Only call this function if your led strip does have the white component (e.g. SK6812-RGBW)
|
||||
|
||||
**Note:**
|
||||
|
||||
Also see `led_strip_set_pixel` if you only want to specify the RGB part of the color and bypass the white component
|
||||
|
||||
**Parameters:**
|
||||
|
||||
- `strip` LED strip
|
||||
- `index` index of pixel to set
|
||||
- `red` red part of color
|
||||
- `green` green part of color
|
||||
- `blue` blue part of color
|
||||
- `white` separate white component
|
||||
|
||||
**Returns:**
|
||||
|
||||
- ESP\_OK: Set RGBW color for a specific pixel successfully
|
||||
- ESP\_ERR\_INVALID\_ARG: Set RGBW color for a specific pixel failed because of an invalid argument
|
||||
- ESP\_FAIL: Set RGBW color for a specific pixel failed because other error occurred
|
||||
|
||||
## File include/led_strip_rmt.h
|
||||
|
||||
## Structures and Types
|
||||
|
||||
| Type | Name |
|
||||
| ---: | :--- |
|
||||
| struct | [**led\_strip\_rmt\_config\_t**](#struct-led_strip_rmt_config_t) <br>_LED Strip RMT specific configuration._ |
|
||||
|
||||
## Functions
|
||||
|
||||
| Type | Name |
|
||||
| ---: | :--- |
|
||||
| esp\_err\_t | [**led\_strip\_new\_rmt\_device**](#function-led_strip_new_rmt_device) (const [**led\_strip\_config\_t**](#struct-led_strip_config_t) \*led\_config, const [**led\_strip\_rmt\_config\_t**](#struct-led_strip_rmt_config_t) \*rmt\_config, [**led\_strip\_handle\_t**](#typedef-led_strip_handle_t) \*ret\_strip) <br>_Create LED strip based on RMT TX channel._ |
|
||||
|
||||
## Structures and Types Documentation
|
||||
|
||||
### struct `led_strip_rmt_config_t`
|
||||
|
||||
_LED Strip RMT specific configuration._
|
||||
|
||||
Variables:
|
||||
|
||||
- rmt\_clock\_source\_t clk_src <br>RMT clock source
|
||||
|
||||
- struct led\_strip\_rmt\_config\_t::@0 flags <br>Extra driver flags
|
||||
|
||||
- size\_t mem_block_symbols <br>How many RMT symbols can one RMT channel hold at one time. Set to 0 will fallback to use the default size.
|
||||
|
||||
- uint32\_t resolution_hz <br>RMT tick resolution, if set to zero, a default resolution (10MHz) will be applied
|
||||
|
||||
- uint32\_t with_dma <br>Use DMA to transmit data
|
||||
|
||||
## Functions Documentation
|
||||
|
||||
### function `led_strip_new_rmt_device`
|
||||
|
||||
_Create LED strip based on RMT TX channel._
|
||||
|
||||
```c
|
||||
esp_err_t led_strip_new_rmt_device (
|
||||
const led_strip_config_t *led_config,
|
||||
const led_strip_rmt_config_t *rmt_config,
|
||||
led_strip_handle_t *ret_strip
|
||||
)
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
|
||||
- `led_config` LED strip configuration
|
||||
- `rmt_config` RMT specific configuration
|
||||
- `ret_strip` Returned LED strip handle
|
||||
|
||||
**Returns:**
|
||||
|
||||
- ESP\_OK: create LED strip handle successfully
|
||||
- ESP\_ERR\_INVALID\_ARG: create LED strip handle failed because of invalid argument
|
||||
- ESP\_ERR\_NO\_MEM: create LED strip handle failed because of out of memory
|
||||
- ESP\_FAIL: create LED strip handle failed because some other error
|
||||
|
||||
## File include/led_strip_spi.h
|
||||
|
||||
## Structures and Types
|
||||
|
||||
| Type | Name |
|
||||
| ---: | :--- |
|
||||
| struct | [**led\_strip\_spi\_config\_t**](#struct-led_strip_spi_config_t) <br>_LED Strip SPI specific configuration._ |
|
||||
|
||||
## Functions
|
||||
|
||||
| Type | Name |
|
||||
| ---: | :--- |
|
||||
| esp\_err\_t | [**led\_strip\_new\_spi\_device**](#function-led_strip_new_spi_device) (const [**led\_strip\_config\_t**](#struct-led_strip_config_t) \*led\_config, const [**led\_strip\_spi\_config\_t**](#struct-led_strip_spi_config_t) \*spi\_config, [**led\_strip\_handle\_t**](#typedef-led_strip_handle_t) \*ret\_strip) <br>_Create LED strip based on SPI MOSI channel._ |
|
||||
|
||||
## Structures and Types Documentation
|
||||
|
||||
### struct `led_strip_spi_config_t`
|
||||
|
||||
_LED Strip SPI specific configuration._
|
||||
|
||||
Variables:
|
||||
|
||||
- spi\_clock\_source\_t clk_src <br>SPI clock source
|
||||
|
||||
- struct led\_strip\_spi\_config\_t::@1 flags <br>Extra driver flags
|
||||
|
||||
- spi\_host\_device\_t spi_bus <br>SPI bus ID. Which buses are available depends on the specific chip
|
||||
|
||||
- uint32\_t with_dma <br>Use DMA to transmit data
|
||||
|
||||
## Functions Documentation
|
||||
|
||||
### function `led_strip_new_spi_device`
|
||||
|
||||
_Create LED strip based on SPI MOSI channel._
|
||||
|
||||
```c
|
||||
esp_err_t led_strip_new_spi_device (
|
||||
const led_strip_config_t *led_config,
|
||||
const led_strip_spi_config_t *spi_config,
|
||||
led_strip_handle_t *ret_strip
|
||||
)
|
||||
```
|
||||
|
||||
**Note:**
|
||||
|
||||
Although only the MOSI line is used for generating the signal, the whole SPI bus can't be used for other purposes.
|
||||
|
||||
**Parameters:**
|
||||
|
||||
- `led_config` LED strip configuration
|
||||
- `spi_config` SPI specific configuration
|
||||
- `ret_strip` Returned LED strip handle
|
||||
|
||||
**Returns:**
|
||||
|
||||
- ESP\_OK: create LED strip handle successfully
|
||||
- ESP\_ERR\_INVALID\_ARG: create LED strip handle failed because of invalid argument
|
||||
- ESP\_ERR\_NOT\_SUPPORTED: create LED strip handle failed because of unsupported configuration
|
||||
- ESP\_ERR\_NO\_MEM: create LED strip handle failed because of out of memory
|
||||
- ESP\_FAIL: create LED strip handle failed because some other error
|
||||
|
||||
## File include/led_strip_types.h
|
||||
|
||||
## Structures and Types
|
||||
|
||||
| Type | Name |
|
||||
| ---: | :--- |
|
||||
| enum | [**led\_model\_t**](#enum-led_model_t) <br>_LED strip model._ |
|
||||
| enum | [**led\_pixel\_format\_t**](#enum-led_pixel_format_t) <br>_LED strip pixel format._ |
|
||||
| struct | [**led\_strip\_config\_t**](#struct-led_strip_config_t) <br>_LED Strip Configuration._ |
|
||||
| typedef struct [**led\_strip\_t**](#struct-led_strip_t) \* | [**led\_strip\_handle\_t**](#typedef-led_strip_handle_t) <br>_LED strip handle._ |
|
||||
|
||||
## Structures and Types Documentation
|
||||
|
||||
### enum `led_model_t`
|
||||
|
||||
_LED strip model._
|
||||
|
||||
```c
|
||||
enum led_model_t {
|
||||
LED_MODEL_WS2812,
|
||||
LED_MODEL_SK6812,
|
||||
LED_MODEL_INVALID
|
||||
};
|
||||
```
|
||||
|
||||
**Note:**
|
||||
|
||||
Different led model may have different timing parameters, so we need to distinguish them.
|
||||
|
||||
### enum `led_pixel_format_t`
|
||||
|
||||
_LED strip pixel format._
|
||||
|
||||
```c
|
||||
enum led_pixel_format_t {
|
||||
LED_PIXEL_FORMAT_GRB,
|
||||
LED_PIXEL_FORMAT_GRBW,
|
||||
LED_PIXEL_FORMAT_INVALID
|
||||
};
|
||||
```
|
||||
|
||||
### struct `led_strip_config_t`
|
||||
|
||||
_LED Strip Configuration._
|
||||
|
||||
Variables:
|
||||
|
||||
- struct led\_strip\_config\_t::@2 flags <br>Extra driver flags
|
||||
|
||||
- uint32\_t invert_out <br>Invert output signal
|
||||
|
||||
- [**led\_model\_t**](#enum-led_model_t) led_model <br>LED model
|
||||
|
||||
- [**led\_pixel\_format\_t**](#enum-led_pixel_format_t) led_pixel_format <br>LED pixel format
|
||||
|
||||
- uint32\_t max_leds <br>Maximum LEDs in a single strip
|
||||
|
||||
- int strip_gpio_num <br>GPIO number that used by LED strip
|
||||
|
||||
### typedef `led_strip_handle_t`
|
||||
|
||||
_LED strip handle._
|
||||
|
||||
```c
|
||||
typedef struct led_strip_t* led_strip_handle_t;
|
||||
```
|
||||
|
||||
## File interface/led_strip_interface.h
|
||||
|
||||
## Structures and Types
|
||||
|
||||
| Type | Name |
|
||||
| ---: | :--- |
|
||||
| struct | [**led\_strip\_t**](#struct-led_strip_t) <br>_LED strip interface definition._ |
|
||||
| typedef struct [**led\_strip\_t**](#struct-led_strip_t) | [**led\_strip\_t**](#typedef-led_strip_t) <br> |
|
||||
|
||||
## Structures and Types Documentation
|
||||
|
||||
### struct `led_strip_t`
|
||||
|
||||
_LED strip interface definition._
|
||||
|
||||
Variables:
|
||||
|
||||
- esp\_err\_t(\* clear <br>_Clear LED strip (turn off all LEDs)_<br>**Parameters:**
|
||||
|
||||
- `strip` LED strip
|
||||
- `timeout_ms` timeout value for clearing task
|
||||
|
||||
**Returns:**
|
||||
|
||||
- ESP\_OK: Clear LEDs successfully
|
||||
- ESP\_FAIL: Clear LEDs failed because some other error occurred
|
||||
|
||||
- esp\_err\_t(\* del <br>_Free LED strip resources._<br>**Parameters:**
|
||||
|
||||
- `strip` LED strip
|
||||
|
||||
**Returns:**
|
||||
|
||||
- ESP\_OK: Free resources successfully
|
||||
- ESP\_FAIL: Free resources failed because error occurred
|
||||
|
||||
- esp\_err\_t(\* refresh <br>_Refresh memory colors to LEDs._<br>**Parameters:**
|
||||
|
||||
- `strip` LED strip
|
||||
- `timeout_ms` timeout value for refreshing task
|
||||
|
||||
**Returns:**
|
||||
|
||||
- ESP\_OK: Refresh successfully
|
||||
- ESP\_FAIL: Refresh failed because some other error occurred
|
||||
|
||||
**Note:**
|
||||
|
||||
: After updating the LED colors in the memory, a following invocation of this API is needed to flush colors to strip.
|
||||
|
||||
- esp\_err\_t(\* set_pixel <br>_Set RGB for a specific pixel._<br>**Parameters:**
|
||||
|
||||
- `strip` LED strip
|
||||
- `index` index of pixel to set
|
||||
- `red` red part of color
|
||||
- `green` green part of color
|
||||
- `blue` blue part of color
|
||||
|
||||
**Returns:**
|
||||
|
||||
- ESP\_OK: Set RGB for a specific pixel successfully
|
||||
- ESP\_ERR\_INVALID\_ARG: Set RGB for a specific pixel failed because of invalid parameters
|
||||
- ESP\_FAIL: Set RGB for a specific pixel failed because other error occurred
|
||||
|
||||
- esp\_err\_t(\* set_pixel_rgbw <br>_Set RGBW for a specific pixel. Similar to_ `set_pixel`_but also set the white component._<br>**Parameters:**
|
||||
|
||||
- `strip` LED strip
|
||||
- `index` index of pixel to set
|
||||
- `red` red part of color
|
||||
- `green` green part of color
|
||||
- `blue` blue part of color
|
||||
- `white` separate white component
|
||||
|
||||
**Returns:**
|
||||
|
||||
- ESP\_OK: Set RGBW color for a specific pixel successfully
|
||||
- ESP\_ERR\_INVALID\_ARG: Set RGBW color for a specific pixel failed because of an invalid argument
|
||||
- ESP\_FAIL: Set RGBW color for a specific pixel failed because other error occurred
|
||||
|
||||
### typedef `led_strip_t`
|
||||
|
||||
```c
|
||||
typedef struct led_strip_t led_strip_t;
|
||||
```
|
||||
|
||||
Type of LED strip
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
# For more information about build system see
|
||||
# https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html
|
||||
# The following five lines of boilerplate have to be in your project's
|
||||
# CMakeLists in this exact order for cmake to work correctly
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
project(led_strip_rmt_ws2812)
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
# LED Strip Example (RMT backend + WS2812)
|
||||
|
||||
This example demonstrates how to blink the WS2812 LED using the [led_strip](https://components.espressif.com/component/espressif/led_strip) component.
|
||||
|
||||
## How to Use Example
|
||||
|
||||
### Hardware Required
|
||||
|
||||
* A development board with Espressif SoC
|
||||
* A USB cable for Power supply and programming
|
||||
* WS2812 LED strip
|
||||
|
||||
### Configure the Example
|
||||
|
||||
Before project configuration and build, be sure to set the correct chip target using `idf.py set-target <chip_name>`. Then assign the proper GPIO in the [source file](main/led_strip_rmt_ws2812_main.c). If your led strip has multiple LEDs, don't forget update the number.
|
||||
|
||||
### Build and Flash
|
||||
|
||||
Run `idf.py -p PORT build flash monitor` to build, flash and monitor the project.
|
||||
|
||||
(To exit the serial monitor, type ``Ctrl-]``.)
|
||||
|
||||
See the [Getting Started Guide](https://docs.espressif.com/projects/esp-idf/en/latest/get-started/index.html) for full steps to configure and use ESP-IDF to build projects.
|
||||
|
||||
## Example Output
|
||||
|
||||
```text
|
||||
I (299) gpio: GPIO[8]| InputEn: 0| OutputEn: 1| OpenDrain: 0| Pullup: 1| Pulldown: 0| Intr:0
|
||||
I (309) example: Created LED strip object with RMT backend
|
||||
I (309) example: Start blinking LED strip
|
||||
```
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
idf_component_register(SRCS "led_strip_rmt_ws2812_main.c"
|
||||
INCLUDE_DIRS ".")
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
## IDF Component Manager Manifest File
|
||||
dependencies:
|
||||
espressif/led_strip:
|
||||
version: '^2'
|
||||
override_path: '../../../'
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Unlicense OR CC0-1.0
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "led_strip.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_err.h"
|
||||
|
||||
// GPIO assignment
|
||||
#define LED_STRIP_BLINK_GPIO 2
|
||||
// Numbers of the LED in the strip
|
||||
#define LED_STRIP_LED_NUMBERS 24
|
||||
// 10MHz resolution, 1 tick = 0.1us (led strip needs a high resolution)
|
||||
#define LED_STRIP_RMT_RES_HZ (10 * 1000 * 1000)
|
||||
|
||||
static const char *TAG = "example";
|
||||
|
||||
led_strip_handle_t configure_led(void)
|
||||
{
|
||||
// LED strip general initialization, according to your led board design
|
||||
led_strip_config_t strip_config = {
|
||||
.strip_gpio_num = LED_STRIP_BLINK_GPIO, // The GPIO that connected to the LED strip's data line
|
||||
.max_leds = LED_STRIP_LED_NUMBERS, // The number of LEDs in the strip,
|
||||
.led_pixel_format = LED_PIXEL_FORMAT_GRB, // Pixel format of your LED strip
|
||||
.led_model = LED_MODEL_WS2812, // LED strip model
|
||||
.flags.invert_out = false, // whether to invert the output signal
|
||||
};
|
||||
|
||||
// LED strip backend configuration: RMT
|
||||
led_strip_rmt_config_t rmt_config = {
|
||||
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)
|
||||
.rmt_channel = 0,
|
||||
#else
|
||||
.clk_src = RMT_CLK_SRC_DEFAULT, // different clock source can lead to different power consumption
|
||||
.resolution_hz = LED_STRIP_RMT_RES_HZ, // RMT counter clock frequency
|
||||
.flags.with_dma = false, // DMA feature is available on ESP target like ESP32-S3
|
||||
#endif
|
||||
};
|
||||
|
||||
// LED Strip object handle
|
||||
led_strip_handle_t led_strip;
|
||||
ESP_ERROR_CHECK(led_strip_new_rmt_device(&strip_config, &rmt_config, &led_strip));
|
||||
ESP_LOGI(TAG, "Created LED strip object with RMT backend");
|
||||
return led_strip;
|
||||
}
|
||||
|
||||
void app_main(void)
|
||||
{
|
||||
led_strip_handle_t led_strip = configure_led();
|
||||
bool led_on_off = false;
|
||||
|
||||
ESP_LOGI(TAG, "Start blinking LED strip");
|
||||
while (1) {
|
||||
if (led_on_off) {
|
||||
/* Set the LED pixel using RGB from 0 (0%) to 255 (100%) for each color */
|
||||
for (int i = 0; i < LED_STRIP_LED_NUMBERS; i++) {
|
||||
ESP_ERROR_CHECK(led_strip_set_pixel(led_strip, i, 5, 5, 5));
|
||||
}
|
||||
/* Refresh the strip to send data */
|
||||
ESP_ERROR_CHECK(led_strip_refresh(led_strip));
|
||||
ESP_LOGI(TAG, "LED ON!");
|
||||
} else {
|
||||
/* Set all LED off to clear all pixels */
|
||||
ESP_ERROR_CHECK(led_strip_clear(led_strip));
|
||||
ESP_LOGI(TAG, "LED OFF!");
|
||||
}
|
||||
|
||||
led_on_off = !led_on_off;
|
||||
vTaskDelay(pdMS_TO_TICKS(500));
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
# For more information about build system see
|
||||
# https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/build-system.html
|
||||
# The following five lines of boilerplate have to be in your project's
|
||||
# CMakeLists in this exact order for cmake to work correctly
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
project(led_strip_spi_ws2812)
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
# LED Strip Example (SPI backend + WS2812)
|
||||
|
||||
This example demonstrates how to blink the WS2812 LED using the [led_strip](https://components.espressif.com/component/espressif/led_strip) component.
|
||||
|
||||
## How to Use Example
|
||||
|
||||
### Hardware Required
|
||||
|
||||
* A development board with Espressif SoC
|
||||
* A USB cable for Power supply and programming
|
||||
* WS2812 LED strip
|
||||
|
||||
### Configure the Example
|
||||
|
||||
Before project configuration and build, be sure to set the correct chip target using `idf.py set-target <chip_name>`. Then assign the proper GPIO in the [source file](main/led_strip_spi_ws2812_main.c). If your led strip has multiple LEDs, don't forget update the number.
|
||||
|
||||
### Build and Flash
|
||||
|
||||
Run `idf.py -p PORT build flash monitor` to build, flash and monitor the project.
|
||||
|
||||
(To exit the serial monitor, type ``Ctrl-]``.)
|
||||
|
||||
See the [Getting Started Guide](https://docs.espressif.com/projects/esp-idf/en/latest/get-started/index.html) for full steps to configure and use ESP-IDF to build projects.
|
||||
|
||||
## Example Output
|
||||
|
||||
```text
|
||||
I (299) gpio: GPIO[14]| InputEn: 0| OutputEn: 1| OpenDrain: 0| Pullup: 1| Pulldown: 0| Intr:0
|
||||
I (309) example: Created LED strip object with SPI backend
|
||||
I (309) example: Start blinking LED strip
|
||||
```
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
idf_component_register(SRCS "led_strip_spi_ws2812_main.c"
|
||||
INCLUDE_DIRS ".")
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
## IDF Component Manager Manifest File
|
||||
dependencies:
|
||||
espressif/led_strip:
|
||||
version: '^2.4'
|
||||
override_path: '../../../'
|
||||
idf: ">=5.1"
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2023 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Unlicense OR CC0-1.0
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "led_strip.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_err.h"
|
||||
|
||||
// GPIO assignment
|
||||
#define LED_STRIP_BLINK_GPIO 2
|
||||
// Numbers of the LED in the strip
|
||||
#define LED_STRIP_LED_NUMBERS 24
|
||||
|
||||
static const char *TAG = "example";
|
||||
|
||||
led_strip_handle_t configure_led(void)
|
||||
{
|
||||
// LED strip general initialization, according to your led board design
|
||||
led_strip_config_t strip_config = {
|
||||
.strip_gpio_num = LED_STRIP_BLINK_GPIO, // The GPIO that connected to the LED strip's data line
|
||||
.max_leds = LED_STRIP_LED_NUMBERS, // The number of LEDs in the strip,
|
||||
.led_pixel_format = LED_PIXEL_FORMAT_GRB, // Pixel format of your LED strip
|
||||
.led_model = LED_MODEL_WS2812, // LED strip model
|
||||
.flags.invert_out = false, // whether to invert the output signal
|
||||
};
|
||||
|
||||
// LED strip backend configuration: SPI
|
||||
led_strip_spi_config_t spi_config = {
|
||||
.clk_src = SPI_CLK_SRC_DEFAULT, // different clock source can lead to different power consumption
|
||||
.flags.with_dma = true, // Using DMA can improve performance and help drive more LEDs
|
||||
.spi_bus = SPI2_HOST, // SPI bus ID
|
||||
};
|
||||
|
||||
// LED Strip object handle
|
||||
led_strip_handle_t led_strip;
|
||||
ESP_ERROR_CHECK(led_strip_new_spi_device(&strip_config, &spi_config, &led_strip));
|
||||
ESP_LOGI(TAG, "Created LED strip object with SPI backend");
|
||||
return led_strip;
|
||||
}
|
||||
|
||||
void app_main(void)
|
||||
{
|
||||
led_strip_handle_t led_strip = configure_led();
|
||||
bool led_on_off = false;
|
||||
|
||||
ESP_LOGI(TAG, "Start blinking LED strip");
|
||||
while (1) {
|
||||
if (led_on_off) {
|
||||
/* Set the LED pixel using RGB from 0 (0%) to 255 (100%) for each color */
|
||||
for (int i = 0; i < LED_STRIP_LED_NUMBERS; i++) {
|
||||
ESP_ERROR_CHECK(led_strip_set_pixel(led_strip, i, 5, 5, 5));
|
||||
}
|
||||
/* Refresh the strip to send data */
|
||||
ESP_ERROR_CHECK(led_strip_refresh(led_strip));
|
||||
ESP_LOGI(TAG, "LED ON!");
|
||||
} else {
|
||||
/* Set all LED off to clear all pixels */
|
||||
ESP_ERROR_CHECK(led_strip_clear(led_strip));
|
||||
ESP_LOGI(TAG, "LED OFF!");
|
||||
}
|
||||
|
||||
led_on_off = !led_on_off;
|
||||
vTaskDelay(pdMS_TO_TICKS(500));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
dependencies:
|
||||
idf: '>=4.4'
|
||||
description: Driver for Addressable LED Strip (WS2812, etc)
|
||||
repository: git://github.com/espressif/idf-extra-components.git
|
||||
repository_info:
|
||||
commit_sha: 60c14263f3b69ac6e98ecae79beecbe5c18d5596
|
||||
path: led_strip
|
||||
url: https://github.com/espressif/idf-extra-components/tree/master/led_strip
|
||||
version: 2.5.5
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include "esp_err.h"
|
||||
#include "led_strip_rmt.h"
|
||||
#include "esp_idf_version.h"
|
||||
|
||||
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 1, 0)
|
||||
#include "led_strip_spi.h"
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Set RGB for a specific pixel
|
||||
*
|
||||
* @param strip: LED strip
|
||||
* @param index: index of pixel to set
|
||||
* @param red: red part of color
|
||||
* @param green: green part of color
|
||||
* @param blue: blue part of color
|
||||
*
|
||||
* @return
|
||||
* - ESP_OK: Set RGB for a specific pixel successfully
|
||||
* - ESP_ERR_INVALID_ARG: Set RGB for a specific pixel failed because of invalid parameters
|
||||
* - ESP_FAIL: Set RGB for a specific pixel failed because other error occurred
|
||||
*/
|
||||
esp_err_t led_strip_set_pixel(led_strip_handle_t strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue);
|
||||
|
||||
/**
|
||||
* @brief Set RGBW for a specific pixel
|
||||
*
|
||||
* @note Only call this function if your led strip does have the white component (e.g. SK6812-RGBW)
|
||||
* @note Also see `led_strip_set_pixel` if you only want to specify the RGB part of the color and bypass the white component
|
||||
*
|
||||
* @param strip: LED strip
|
||||
* @param index: index of pixel to set
|
||||
* @param red: red part of color
|
||||
* @param green: green part of color
|
||||
* @param blue: blue part of color
|
||||
* @param white: separate white component
|
||||
*
|
||||
* @return
|
||||
* - ESP_OK: Set RGBW color for a specific pixel successfully
|
||||
* - ESP_ERR_INVALID_ARG: Set RGBW color for a specific pixel failed because of an invalid argument
|
||||
* - ESP_FAIL: Set RGBW color for a specific pixel failed because other error occurred
|
||||
*/
|
||||
esp_err_t led_strip_set_pixel_rgbw(led_strip_handle_t strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue, uint32_t white);
|
||||
|
||||
/**
|
||||
* @brief Set HSV for a specific pixel
|
||||
*
|
||||
* @param strip: LED strip
|
||||
* @param index: index of pixel to set
|
||||
* @param hue: hue part of color (0 - 360)
|
||||
* @param saturation: saturation part of color (0 - 255, rescaled from 0 - 1. e.g. saturation = 0.5, rescaled to 127)
|
||||
* @param value: value part of color (0 - 255, rescaled from 0 - 1. e.g. value = 0.5, rescaled to 127)
|
||||
*
|
||||
* @return
|
||||
* - ESP_OK: Set HSV color for a specific pixel successfully
|
||||
* - ESP_ERR_INVALID_ARG: Set HSV color for a specific pixel failed because of an invalid argument
|
||||
* - ESP_FAIL: Set HSV color for a specific pixel failed because other error occurred
|
||||
*/
|
||||
esp_err_t led_strip_set_pixel_hsv(led_strip_handle_t strip, uint32_t index, uint16_t hue, uint8_t saturation, uint8_t value);
|
||||
|
||||
/**
|
||||
* @brief Refresh memory colors to LEDs
|
||||
*
|
||||
* @param strip: LED strip
|
||||
*
|
||||
* @return
|
||||
* - ESP_OK: Refresh successfully
|
||||
* - ESP_FAIL: Refresh failed because some other error occurred
|
||||
*
|
||||
* @note:
|
||||
* After updating the LED colors in the memory, a following invocation of this API is needed to flush colors to strip.
|
||||
*/
|
||||
esp_err_t led_strip_refresh(led_strip_handle_t strip);
|
||||
|
||||
/**
|
||||
* @brief Clear LED strip (turn off all LEDs)
|
||||
*
|
||||
* @param strip: LED strip
|
||||
*
|
||||
* @return
|
||||
* - ESP_OK: Clear LEDs successfully
|
||||
* - ESP_FAIL: Clear LEDs failed because some other error occurred
|
||||
*/
|
||||
esp_err_t led_strip_clear(led_strip_handle_t strip);
|
||||
|
||||
/**
|
||||
* @brief Free LED strip resources
|
||||
*
|
||||
* @param strip: LED strip
|
||||
*
|
||||
* @return
|
||||
* - ESP_OK: Free resources successfully
|
||||
* - ESP_FAIL: Free resources failed because error occurred
|
||||
*/
|
||||
esp_err_t led_strip_del(led_strip_handle_t strip);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include "esp_err.h"
|
||||
#include "led_strip_types.h"
|
||||
#include "esp_idf_version.h"
|
||||
|
||||
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)
|
||||
#include "driver/rmt_types.h"
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief LED Strip RMT specific configuration
|
||||
*/
|
||||
typedef struct {
|
||||
#if ESP_IDF_VERSION < ESP_IDF_VERSION_VAL(5, 0, 0)
|
||||
uint8_t rmt_channel; /*!< Specify the channel number, the legacy RMT driver doesn't support channel allocator */
|
||||
#else // new driver supports specify the clock source and clock resolution
|
||||
rmt_clock_source_t clk_src; /*!< RMT clock source */
|
||||
uint32_t resolution_hz; /*!< RMT tick resolution, if set to zero, a default resolution (10MHz) will be applied */
|
||||
#endif
|
||||
size_t mem_block_symbols; /*!< How many RMT symbols can one RMT channel hold at one time. Set to 0 will fallback to use the default size. */
|
||||
struct {
|
||||
uint32_t with_dma: 1; /*!< Use DMA to transmit data */
|
||||
} flags; /*!< Extra driver flags */
|
||||
} led_strip_rmt_config_t;
|
||||
|
||||
/**
|
||||
* @brief Create LED strip based on RMT TX channel
|
||||
*
|
||||
* @param led_config LED strip configuration
|
||||
* @param rmt_config RMT specific configuration
|
||||
* @param ret_strip Returned LED strip handle
|
||||
* @return
|
||||
* - ESP_OK: create LED strip handle successfully
|
||||
* - ESP_ERR_INVALID_ARG: create LED strip handle failed because of invalid argument
|
||||
* - ESP_ERR_NO_MEM: create LED strip handle failed because of out of memory
|
||||
* - ESP_FAIL: create LED strip handle failed because some other error
|
||||
*/
|
||||
esp_err_t led_strip_new_rmt_device(const led_strip_config_t *led_config, const led_strip_rmt_config_t *rmt_config, led_strip_handle_t *ret_strip);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include "esp_err.h"
|
||||
#include "driver/spi_master.h"
|
||||
#include "led_strip_types.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief LED Strip SPI specific configuration
|
||||
*/
|
||||
typedef struct {
|
||||
spi_clock_source_t clk_src; /*!< SPI clock source */
|
||||
spi_host_device_t spi_bus; /*!< SPI bus ID. Which buses are available depends on the specific chip */
|
||||
struct {
|
||||
uint32_t with_dma: 1; /*!< Use DMA to transmit data */
|
||||
} flags; /*!< Extra driver flags */
|
||||
} led_strip_spi_config_t;
|
||||
|
||||
/**
|
||||
* @brief Create LED strip based on SPI MOSI channel
|
||||
* @note Although only the MOSI line is used for generating the signal, the whole SPI bus can't be used for other purposes.
|
||||
*
|
||||
* @param led_config LED strip configuration
|
||||
* @param spi_config SPI specific configuration
|
||||
* @param ret_strip Returned LED strip handle
|
||||
* @return
|
||||
* - ESP_OK: create LED strip handle successfully
|
||||
* - ESP_ERR_INVALID_ARG: create LED strip handle failed because of invalid argument
|
||||
* - ESP_ERR_NOT_SUPPORTED: create LED strip handle failed because of unsupported configuration
|
||||
* - ESP_ERR_NO_MEM: create LED strip handle failed because of out of memory
|
||||
* - ESP_FAIL: create LED strip handle failed because some other error
|
||||
*/
|
||||
esp_err_t led_strip_new_spi_device(const led_strip_config_t *led_config, const led_strip_spi_config_t *spi_config, led_strip_handle_t *ret_strip);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief LED strip pixel format
|
||||
*/
|
||||
typedef enum {
|
||||
LED_PIXEL_FORMAT_GRB, /*!< Pixel format: GRB */
|
||||
LED_PIXEL_FORMAT_GRBW, /*!< Pixel format: GRBW */
|
||||
LED_PIXEL_FORMAT_INVALID /*!< Invalid pixel format */
|
||||
} led_pixel_format_t;
|
||||
|
||||
/**
|
||||
* @brief LED strip model
|
||||
* @note Different led model may have different timing parameters, so we need to distinguish them.
|
||||
*/
|
||||
typedef enum {
|
||||
LED_MODEL_WS2812, /*!< LED strip model: WS2812 */
|
||||
LED_MODEL_SK6812, /*!< LED strip model: SK6812 */
|
||||
LED_MODEL_INVALID /*!< Invalid LED strip model */
|
||||
} led_model_t;
|
||||
|
||||
/**
|
||||
* @brief LED strip handle
|
||||
*/
|
||||
typedef struct led_strip_t *led_strip_handle_t;
|
||||
|
||||
/**
|
||||
* @brief LED Strip Configuration
|
||||
*/
|
||||
typedef struct {
|
||||
int strip_gpio_num; /*!< GPIO number that used by LED strip */
|
||||
uint32_t max_leds; /*!< Maximum LEDs in a single strip */
|
||||
led_pixel_format_t led_pixel_format; /*!< LED pixel format */
|
||||
led_model_t led_model; /*!< LED model */
|
||||
|
||||
struct {
|
||||
uint32_t invert_out: 1; /*!< Invert output signal */
|
||||
} flags; /*!< Extra driver flags */
|
||||
} led_strip_config_t;
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include "esp_err.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
typedef struct led_strip_t led_strip_t; /*!< Type of LED strip */
|
||||
|
||||
/**
|
||||
* @brief LED strip interface definition
|
||||
*/
|
||||
struct led_strip_t {
|
||||
/**
|
||||
* @brief Set RGB for a specific pixel
|
||||
*
|
||||
* @param strip: LED strip
|
||||
* @param index: index of pixel to set
|
||||
* @param red: red part of color
|
||||
* @param green: green part of color
|
||||
* @param blue: blue part of color
|
||||
*
|
||||
* @return
|
||||
* - ESP_OK: Set RGB for a specific pixel successfully
|
||||
* - ESP_ERR_INVALID_ARG: Set RGB for a specific pixel failed because of invalid parameters
|
||||
* - ESP_FAIL: Set RGB for a specific pixel failed because other error occurred
|
||||
*/
|
||||
esp_err_t (*set_pixel)(led_strip_t *strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue);
|
||||
|
||||
/**
|
||||
* @brief Set RGBW for a specific pixel. Similar to `set_pixel` but also set the white component
|
||||
*
|
||||
* @param strip: LED strip
|
||||
* @param index: index of pixel to set
|
||||
* @param red: red part of color
|
||||
* @param green: green part of color
|
||||
* @param blue: blue part of color
|
||||
* @param white: separate white component
|
||||
*
|
||||
* @return
|
||||
* - ESP_OK: Set RGBW color for a specific pixel successfully
|
||||
* - ESP_ERR_INVALID_ARG: Set RGBW color for a specific pixel failed because of an invalid argument
|
||||
* - ESP_FAIL: Set RGBW color for a specific pixel failed because other error occurred
|
||||
*/
|
||||
esp_err_t (*set_pixel_rgbw)(led_strip_t *strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue, uint32_t white);
|
||||
|
||||
/**
|
||||
* @brief Refresh memory colors to LEDs
|
||||
*
|
||||
* @param strip: LED strip
|
||||
* @param timeout_ms: timeout value for refreshing task
|
||||
*
|
||||
* @return
|
||||
* - ESP_OK: Refresh successfully
|
||||
* - ESP_FAIL: Refresh failed because some other error occurred
|
||||
*
|
||||
* @note:
|
||||
* After updating the LED colors in the memory, a following invocation of this API is needed to flush colors to strip.
|
||||
*/
|
||||
esp_err_t (*refresh)(led_strip_t *strip);
|
||||
|
||||
/**
|
||||
* @brief Clear LED strip (turn off all LEDs)
|
||||
*
|
||||
* @param strip: LED strip
|
||||
* @param timeout_ms: timeout value for clearing task
|
||||
*
|
||||
* @return
|
||||
* - ESP_OK: Clear LEDs successfully
|
||||
* - ESP_FAIL: Clear LEDs failed because some other error occurred
|
||||
*/
|
||||
esp_err_t (*clear)(led_strip_t *strip);
|
||||
|
||||
/**
|
||||
* @brief Free LED strip resources
|
||||
*
|
||||
* @param strip: LED strip
|
||||
*
|
||||
* @return
|
||||
* - ESP_OK: Free resources successfully
|
||||
* - ESP_FAIL: Free resources failed because error occurred
|
||||
*/
|
||||
esp_err_t (*del)(led_strip_t *strip);
|
||||
};
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#include "esp_log.h"
|
||||
#include "esp_check.h"
|
||||
#include "led_strip.h"
|
||||
#include "led_strip_interface.h"
|
||||
|
||||
static const char *TAG = "led_strip";
|
||||
|
||||
esp_err_t led_strip_set_pixel(led_strip_handle_t strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue)
|
||||
{
|
||||
ESP_RETURN_ON_FALSE(strip, ESP_ERR_INVALID_ARG, TAG, "invalid argument");
|
||||
return strip->set_pixel(strip, index, red, green, blue);
|
||||
}
|
||||
|
||||
esp_err_t led_strip_set_pixel_hsv(led_strip_handle_t strip, uint32_t index, uint16_t hue, uint8_t saturation, uint8_t value)
|
||||
{
|
||||
ESP_RETURN_ON_FALSE(strip, ESP_ERR_INVALID_ARG, TAG, "invalid argument");
|
||||
|
||||
uint32_t red = 0;
|
||||
uint32_t green = 0;
|
||||
uint32_t blue = 0;
|
||||
|
||||
uint32_t rgb_max = value;
|
||||
uint32_t rgb_min = rgb_max * (255 - saturation) / 255.0f;
|
||||
|
||||
uint32_t i = hue / 60;
|
||||
uint32_t diff = hue % 60;
|
||||
|
||||
// RGB adjustment amount by hue
|
||||
uint32_t rgb_adj = (rgb_max - rgb_min) * diff / 60;
|
||||
|
||||
switch (i) {
|
||||
case 0:
|
||||
red = rgb_max;
|
||||
green = rgb_min + rgb_adj;
|
||||
blue = rgb_min;
|
||||
break;
|
||||
case 1:
|
||||
red = rgb_max - rgb_adj;
|
||||
green = rgb_max;
|
||||
blue = rgb_min;
|
||||
break;
|
||||
case 2:
|
||||
red = rgb_min;
|
||||
green = rgb_max;
|
||||
blue = rgb_min + rgb_adj;
|
||||
break;
|
||||
case 3:
|
||||
red = rgb_min;
|
||||
green = rgb_max - rgb_adj;
|
||||
blue = rgb_max;
|
||||
break;
|
||||
case 4:
|
||||
red = rgb_min + rgb_adj;
|
||||
green = rgb_min;
|
||||
blue = rgb_max;
|
||||
break;
|
||||
default:
|
||||
red = rgb_max;
|
||||
green = rgb_min;
|
||||
blue = rgb_max - rgb_adj;
|
||||
break;
|
||||
}
|
||||
|
||||
return strip->set_pixel(strip, index, red, green, blue);
|
||||
}
|
||||
|
||||
esp_err_t led_strip_set_pixel_rgbw(led_strip_handle_t strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue, uint32_t white)
|
||||
{
|
||||
ESP_RETURN_ON_FALSE(strip, ESP_ERR_INVALID_ARG, TAG, "invalid argument");
|
||||
return strip->set_pixel_rgbw(strip, index, red, green, blue, white);
|
||||
}
|
||||
|
||||
esp_err_t led_strip_refresh(led_strip_handle_t strip)
|
||||
{
|
||||
ESP_RETURN_ON_FALSE(strip, ESP_ERR_INVALID_ARG, TAG, "invalid argument");
|
||||
return strip->refresh(strip);
|
||||
}
|
||||
|
||||
esp_err_t led_strip_clear(led_strip_handle_t strip)
|
||||
{
|
||||
ESP_RETURN_ON_FALSE(strip, ESP_ERR_INVALID_ARG, TAG, "invalid argument");
|
||||
return strip->clear(strip);
|
||||
}
|
||||
|
||||
esp_err_t led_strip_del(led_strip_handle_t strip)
|
||||
{
|
||||
ESP_RETURN_ON_FALSE(strip, ESP_ERR_INVALID_ARG, TAG, "invalid argument");
|
||||
return strip->del(strip);
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/cdefs.h>
|
||||
#include "esp_log.h"
|
||||
#include "esp_check.h"
|
||||
#include "driver/rmt_tx.h"
|
||||
#include "led_strip.h"
|
||||
#include "led_strip_interface.h"
|
||||
#include "led_strip_rmt_encoder.h"
|
||||
|
||||
#define LED_STRIP_RMT_DEFAULT_RESOLUTION 10000000 // 10MHz resolution
|
||||
#define LED_STRIP_RMT_DEFAULT_TRANS_QUEUE_SIZE 4
|
||||
// the memory size of each RMT channel, in words (4 bytes)
|
||||
#if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2
|
||||
#define LED_STRIP_RMT_DEFAULT_MEM_BLOCK_SYMBOLS 64
|
||||
#else
|
||||
#define LED_STRIP_RMT_DEFAULT_MEM_BLOCK_SYMBOLS 48
|
||||
#endif
|
||||
|
||||
static const char *TAG = "led_strip_rmt";
|
||||
|
||||
typedef struct {
|
||||
led_strip_t base;
|
||||
rmt_channel_handle_t rmt_chan;
|
||||
rmt_encoder_handle_t strip_encoder;
|
||||
uint32_t strip_len;
|
||||
uint8_t bytes_per_pixel;
|
||||
uint8_t pixel_buf[];
|
||||
} led_strip_rmt_obj;
|
||||
|
||||
static esp_err_t led_strip_rmt_set_pixel(led_strip_t *strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue)
|
||||
{
|
||||
led_strip_rmt_obj *rmt_strip = __containerof(strip, led_strip_rmt_obj, base);
|
||||
ESP_RETURN_ON_FALSE(index < rmt_strip->strip_len, ESP_ERR_INVALID_ARG, TAG, "index out of maximum number of LEDs");
|
||||
uint32_t start = index * rmt_strip->bytes_per_pixel;
|
||||
// In thr order of GRB, as LED strip like WS2812 sends out pixels in this order
|
||||
rmt_strip->pixel_buf[start + 0] = green & 0xFF;
|
||||
rmt_strip->pixel_buf[start + 1] = red & 0xFF;
|
||||
rmt_strip->pixel_buf[start + 2] = blue & 0xFF;
|
||||
if (rmt_strip->bytes_per_pixel > 3) {
|
||||
rmt_strip->pixel_buf[start + 3] = 0;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t led_strip_rmt_set_pixel_rgbw(led_strip_t *strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue, uint32_t white)
|
||||
{
|
||||
led_strip_rmt_obj *rmt_strip = __containerof(strip, led_strip_rmt_obj, base);
|
||||
ESP_RETURN_ON_FALSE(index < rmt_strip->strip_len, ESP_ERR_INVALID_ARG, TAG, "index out of maximum number of LEDs");
|
||||
ESP_RETURN_ON_FALSE(rmt_strip->bytes_per_pixel == 4, ESP_ERR_INVALID_ARG, TAG, "wrong LED pixel format, expected 4 bytes per pixel");
|
||||
uint8_t *buf_start = rmt_strip->pixel_buf + index * 4;
|
||||
// SK6812 component order is GRBW
|
||||
*buf_start = green & 0xFF;
|
||||
*++buf_start = red & 0xFF;
|
||||
*++buf_start = blue & 0xFF;
|
||||
*++buf_start = white & 0xFF;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t led_strip_rmt_refresh(led_strip_t *strip)
|
||||
{
|
||||
led_strip_rmt_obj *rmt_strip = __containerof(strip, led_strip_rmt_obj, base);
|
||||
rmt_transmit_config_t tx_conf = {
|
||||
.loop_count = 0,
|
||||
};
|
||||
|
||||
ESP_RETURN_ON_ERROR(rmt_enable(rmt_strip->rmt_chan), TAG, "enable RMT channel failed");
|
||||
ESP_RETURN_ON_ERROR(rmt_transmit(rmt_strip->rmt_chan, rmt_strip->strip_encoder, rmt_strip->pixel_buf,
|
||||
rmt_strip->strip_len * rmt_strip->bytes_per_pixel, &tx_conf), TAG, "transmit pixels by RMT failed");
|
||||
ESP_RETURN_ON_ERROR(rmt_tx_wait_all_done(rmt_strip->rmt_chan, -1), TAG, "flush RMT channel failed");
|
||||
ESP_RETURN_ON_ERROR(rmt_disable(rmt_strip->rmt_chan), TAG, "disable RMT channel failed");
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t led_strip_rmt_clear(led_strip_t *strip)
|
||||
{
|
||||
led_strip_rmt_obj *rmt_strip = __containerof(strip, led_strip_rmt_obj, base);
|
||||
// Write zero to turn off all leds
|
||||
memset(rmt_strip->pixel_buf, 0, rmt_strip->strip_len * rmt_strip->bytes_per_pixel);
|
||||
return led_strip_rmt_refresh(strip);
|
||||
}
|
||||
|
||||
static esp_err_t led_strip_rmt_del(led_strip_t *strip)
|
||||
{
|
||||
led_strip_rmt_obj *rmt_strip = __containerof(strip, led_strip_rmt_obj, base);
|
||||
ESP_RETURN_ON_ERROR(rmt_del_channel(rmt_strip->rmt_chan), TAG, "delete RMT channel failed");
|
||||
ESP_RETURN_ON_ERROR(rmt_del_encoder(rmt_strip->strip_encoder), TAG, "delete strip encoder failed");
|
||||
free(rmt_strip);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t led_strip_new_rmt_device(const led_strip_config_t *led_config, const led_strip_rmt_config_t *rmt_config, led_strip_handle_t *ret_strip)
|
||||
{
|
||||
led_strip_rmt_obj *rmt_strip = NULL;
|
||||
esp_err_t ret = ESP_OK;
|
||||
ESP_GOTO_ON_FALSE(led_config && rmt_config && ret_strip, ESP_ERR_INVALID_ARG, err, TAG, "invalid argument");
|
||||
ESP_GOTO_ON_FALSE(led_config->led_pixel_format < LED_PIXEL_FORMAT_INVALID, ESP_ERR_INVALID_ARG, err, TAG, "invalid led_pixel_format");
|
||||
uint8_t bytes_per_pixel = 3;
|
||||
if (led_config->led_pixel_format == LED_PIXEL_FORMAT_GRBW) {
|
||||
bytes_per_pixel = 4;
|
||||
} else if (led_config->led_pixel_format == LED_PIXEL_FORMAT_GRB) {
|
||||
bytes_per_pixel = 3;
|
||||
} else {
|
||||
assert(false);
|
||||
}
|
||||
rmt_strip = calloc(1, sizeof(led_strip_rmt_obj) + led_config->max_leds * bytes_per_pixel);
|
||||
ESP_GOTO_ON_FALSE(rmt_strip, ESP_ERR_NO_MEM, err, TAG, "no mem for rmt strip");
|
||||
uint32_t resolution = rmt_config->resolution_hz ? rmt_config->resolution_hz : LED_STRIP_RMT_DEFAULT_RESOLUTION;
|
||||
|
||||
// for backward compatibility, if the user does not set the clk_src, use the default value
|
||||
rmt_clock_source_t clk_src = RMT_CLK_SRC_DEFAULT;
|
||||
if (rmt_config->clk_src) {
|
||||
clk_src = rmt_config->clk_src;
|
||||
}
|
||||
size_t mem_block_symbols = LED_STRIP_RMT_DEFAULT_MEM_BLOCK_SYMBOLS;
|
||||
// override the default value if the user sets it
|
||||
if (rmt_config->mem_block_symbols) {
|
||||
mem_block_symbols = rmt_config->mem_block_symbols;
|
||||
}
|
||||
rmt_tx_channel_config_t rmt_chan_config = {
|
||||
.clk_src = clk_src,
|
||||
.gpio_num = led_config->strip_gpio_num,
|
||||
.mem_block_symbols = mem_block_symbols,
|
||||
.resolution_hz = resolution,
|
||||
.trans_queue_depth = LED_STRIP_RMT_DEFAULT_TRANS_QUEUE_SIZE,
|
||||
.flags.with_dma = rmt_config->flags.with_dma,
|
||||
.flags.invert_out = led_config->flags.invert_out,
|
||||
};
|
||||
ESP_GOTO_ON_ERROR(rmt_new_tx_channel(&rmt_chan_config, &rmt_strip->rmt_chan), err, TAG, "create RMT TX channel failed");
|
||||
|
||||
led_strip_encoder_config_t strip_encoder_conf = {
|
||||
.resolution = resolution,
|
||||
.led_model = led_config->led_model
|
||||
};
|
||||
ESP_GOTO_ON_ERROR(rmt_new_led_strip_encoder(&strip_encoder_conf, &rmt_strip->strip_encoder), err, TAG, "create LED strip encoder failed");
|
||||
|
||||
|
||||
rmt_strip->bytes_per_pixel = bytes_per_pixel;
|
||||
rmt_strip->strip_len = led_config->max_leds;
|
||||
rmt_strip->base.set_pixel = led_strip_rmt_set_pixel;
|
||||
rmt_strip->base.set_pixel_rgbw = led_strip_rmt_set_pixel_rgbw;
|
||||
rmt_strip->base.refresh = led_strip_rmt_refresh;
|
||||
rmt_strip->base.clear = led_strip_rmt_clear;
|
||||
rmt_strip->base.del = led_strip_rmt_del;
|
||||
|
||||
*ret_strip = &rmt_strip->base;
|
||||
return ESP_OK;
|
||||
err:
|
||||
if (rmt_strip) {
|
||||
if (rmt_strip->rmt_chan) {
|
||||
rmt_del_channel(rmt_strip->rmt_chan);
|
||||
}
|
||||
if (rmt_strip->strip_encoder) {
|
||||
rmt_del_encoder(rmt_strip->strip_encoder);
|
||||
}
|
||||
free(rmt_strip);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/cdefs.h>
|
||||
#include "esp_log.h"
|
||||
#include "esp_check.h"
|
||||
#include "driver/rmt.h"
|
||||
#include "led_strip.h"
|
||||
#include "led_strip_interface.h"
|
||||
|
||||
static const char *TAG = "led_strip_rmt";
|
||||
|
||||
#define WS2812_T0H_NS (300)
|
||||
#define WS2812_T0L_NS (900)
|
||||
#define WS2812_T1H_NS (900)
|
||||
#define WS2812_T1L_NS (300)
|
||||
|
||||
#define SK6812_T0H_NS (300)
|
||||
#define SK6812_T0L_NS (900)
|
||||
#define SK6812_T1H_NS (600)
|
||||
#define SK6812_T1L_NS (600)
|
||||
|
||||
#define LED_STRIP_RESET_MS (10)
|
||||
|
||||
// the memory size of each RMT channel, in words (4 bytes)
|
||||
#if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2
|
||||
#define LED_STRIP_RMT_DEFAULT_MEM_BLOCK_SYMBOLS 64
|
||||
#else
|
||||
#define LED_STRIP_RMT_DEFAULT_MEM_BLOCK_SYMBOLS 48
|
||||
#endif
|
||||
|
||||
static uint32_t led_t0h_ticks = 0;
|
||||
static uint32_t led_t1h_ticks = 0;
|
||||
static uint32_t led_t0l_ticks = 0;
|
||||
static uint32_t led_t1l_ticks = 0;
|
||||
|
||||
typedef struct {
|
||||
led_strip_t base;
|
||||
rmt_channel_t rmt_channel;
|
||||
uint32_t strip_len;
|
||||
uint8_t bytes_per_pixel;
|
||||
uint8_t buffer[0];
|
||||
} led_strip_rmt_obj;
|
||||
|
||||
static void IRAM_ATTR ws2812_rmt_adapter(const void *src, rmt_item32_t *dest, size_t src_size,
|
||||
size_t wanted_num, size_t *translated_size, size_t *item_num)
|
||||
{
|
||||
if (src == NULL || dest == NULL) {
|
||||
*translated_size = 0;
|
||||
*item_num = 0;
|
||||
return;
|
||||
}
|
||||
const rmt_item32_t bit0 = {{{ led_t0h_ticks, 1, led_t0l_ticks, 0 }}}; //Logical 0
|
||||
const rmt_item32_t bit1 = {{{ led_t1h_ticks, 1, led_t1l_ticks, 0 }}}; //Logical 1
|
||||
size_t size = 0;
|
||||
size_t num = 0;
|
||||
uint8_t *psrc = (uint8_t *)src;
|
||||
rmt_item32_t *pdest = dest;
|
||||
while (size < src_size && num < wanted_num) {
|
||||
for (int i = 0; i < 8; i++) {
|
||||
// MSB first
|
||||
if (*psrc & (1 << (7 - i))) {
|
||||
pdest->val = bit1.val;
|
||||
} else {
|
||||
pdest->val = bit0.val;
|
||||
}
|
||||
num++;
|
||||
pdest++;
|
||||
}
|
||||
size++;
|
||||
psrc++;
|
||||
}
|
||||
*translated_size = size;
|
||||
*item_num = num;
|
||||
}
|
||||
|
||||
static esp_err_t led_strip_rmt_set_pixel(led_strip_t *strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue)
|
||||
{
|
||||
led_strip_rmt_obj *rmt_strip = __containerof(strip, led_strip_rmt_obj, base);
|
||||
ESP_RETURN_ON_FALSE(index < rmt_strip->strip_len, ESP_ERR_INVALID_ARG, TAG, "index out of the maximum number of leds");
|
||||
uint32_t start = index * rmt_strip->bytes_per_pixel;
|
||||
// In thr order of GRB
|
||||
rmt_strip->buffer[start + 0] = green & 0xFF;
|
||||
rmt_strip->buffer[start + 1] = red & 0xFF;
|
||||
rmt_strip->buffer[start + 2] = blue & 0xFF;
|
||||
if (rmt_strip->bytes_per_pixel > 3) {
|
||||
rmt_strip->buffer[start + 3] = 0;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t led_strip_rmt_refresh(led_strip_t *strip)
|
||||
{
|
||||
led_strip_rmt_obj *rmt_strip = __containerof(strip, led_strip_rmt_obj, base);
|
||||
ESP_RETURN_ON_ERROR(rmt_write_sample(rmt_strip->rmt_channel, rmt_strip->buffer, rmt_strip->strip_len * rmt_strip->bytes_per_pixel, true), TAG,
|
||||
"transmit RMT samples failed");
|
||||
vTaskDelay(pdMS_TO_TICKS(LED_STRIP_RESET_MS));
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t led_strip_rmt_clear(led_strip_t *strip)
|
||||
{
|
||||
led_strip_rmt_obj *rmt_strip = __containerof(strip, led_strip_rmt_obj, base);
|
||||
// Write zero to turn off all LEDs
|
||||
memset(rmt_strip->buffer, 0, rmt_strip->strip_len * rmt_strip->bytes_per_pixel);
|
||||
return led_strip_rmt_refresh(strip);
|
||||
}
|
||||
|
||||
static esp_err_t led_strip_rmt_del(led_strip_t *strip)
|
||||
{
|
||||
led_strip_rmt_obj *rmt_strip = __containerof(strip, led_strip_rmt_obj, base);
|
||||
ESP_RETURN_ON_ERROR(rmt_driver_uninstall(rmt_strip->rmt_channel), TAG, "uninstall RMT driver failed");
|
||||
free(rmt_strip);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t led_strip_new_rmt_device(const led_strip_config_t *led_config, const led_strip_rmt_config_t *dev_config, led_strip_handle_t *ret_strip)
|
||||
{
|
||||
led_strip_rmt_obj *rmt_strip = NULL;
|
||||
esp_err_t ret = ESP_OK;
|
||||
ESP_RETURN_ON_FALSE(led_config && dev_config && ret_strip, ESP_ERR_INVALID_ARG, TAG, "invalid argument");
|
||||
ESP_RETURN_ON_FALSE(led_config->led_pixel_format < LED_PIXEL_FORMAT_INVALID, ESP_ERR_INVALID_ARG, TAG, "invalid led_pixel_format");
|
||||
ESP_RETURN_ON_FALSE(dev_config->flags.with_dma == 0, ESP_ERR_NOT_SUPPORTED, TAG, "DMA is not supported");
|
||||
|
||||
uint8_t bytes_per_pixel = 3;
|
||||
if (led_config->led_pixel_format == LED_PIXEL_FORMAT_GRBW) {
|
||||
bytes_per_pixel = 4;
|
||||
} else if (led_config->led_pixel_format == LED_PIXEL_FORMAT_GRB) {
|
||||
bytes_per_pixel = 3;
|
||||
} else {
|
||||
assert(false);
|
||||
}
|
||||
|
||||
// allocate memory for led_strip object
|
||||
rmt_strip = calloc(1, sizeof(led_strip_rmt_obj) + led_config->max_leds * bytes_per_pixel);
|
||||
ESP_RETURN_ON_FALSE(rmt_strip, ESP_ERR_NO_MEM, TAG, "request memory for les_strip failed");
|
||||
|
||||
// install RMT channel driver
|
||||
rmt_config_t config = RMT_DEFAULT_CONFIG_TX(led_config->strip_gpio_num, dev_config->rmt_channel);
|
||||
// set the minimal clock division because the LED strip needs a high clock resolution
|
||||
config.clk_div = 2;
|
||||
|
||||
uint8_t mem_block_num = 2;
|
||||
// override the default value if the user specify the mem block size
|
||||
if (dev_config->mem_block_symbols) {
|
||||
mem_block_num = (dev_config->mem_block_symbols + LED_STRIP_RMT_DEFAULT_MEM_BLOCK_SYMBOLS / 2) / LED_STRIP_RMT_DEFAULT_MEM_BLOCK_SYMBOLS;
|
||||
}
|
||||
config.mem_block_num = mem_block_num;
|
||||
|
||||
ESP_GOTO_ON_ERROR(rmt_config(&config), err, TAG, "RMT config failed");
|
||||
ESP_GOTO_ON_ERROR(rmt_driver_install(config.channel, 0, 0), err, TAG, "RMT install failed");
|
||||
|
||||
uint32_t counter_clk_hz = 0;
|
||||
rmt_get_counter_clock((rmt_channel_t)dev_config->rmt_channel, &counter_clk_hz);
|
||||
// ns -> ticks
|
||||
float ratio = (float)counter_clk_hz / 1e9;
|
||||
if (led_config->led_model == LED_MODEL_WS2812) {
|
||||
led_t0h_ticks = (uint32_t)(ratio * WS2812_T0H_NS);
|
||||
led_t0l_ticks = (uint32_t)(ratio * WS2812_T0L_NS);
|
||||
led_t1h_ticks = (uint32_t)(ratio * WS2812_T1H_NS);
|
||||
led_t1l_ticks = (uint32_t)(ratio * WS2812_T1L_NS);
|
||||
} else if (led_config->led_model == LED_MODEL_SK6812) {
|
||||
led_t0h_ticks = (uint32_t)(ratio * SK6812_T0H_NS);
|
||||
led_t0l_ticks = (uint32_t)(ratio * SK6812_T0L_NS);
|
||||
led_t1h_ticks = (uint32_t)(ratio * SK6812_T1H_NS);
|
||||
led_t1l_ticks = (uint32_t)(ratio * SK6812_T1L_NS);
|
||||
} else {
|
||||
assert(false);
|
||||
}
|
||||
|
||||
// adapter to translates the LES strip date frame into RMT symbols
|
||||
rmt_translator_init((rmt_channel_t)dev_config->rmt_channel, ws2812_rmt_adapter);
|
||||
|
||||
rmt_strip->bytes_per_pixel = bytes_per_pixel;
|
||||
rmt_strip->rmt_channel = (rmt_channel_t)dev_config->rmt_channel;
|
||||
rmt_strip->strip_len = led_config->max_leds;
|
||||
rmt_strip->base.set_pixel = led_strip_rmt_set_pixel;
|
||||
rmt_strip->base.refresh = led_strip_rmt_refresh;
|
||||
rmt_strip->base.clear = led_strip_rmt_clear;
|
||||
rmt_strip->base.del = led_strip_rmt_del;
|
||||
|
||||
*ret_strip = &rmt_strip->base;
|
||||
return ESP_OK;
|
||||
|
||||
err:
|
||||
if (rmt_strip) {
|
||||
free(rmt_strip);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
#include "esp_check.h"
|
||||
#include "led_strip_rmt_encoder.h"
|
||||
|
||||
static const char *TAG = "led_rmt_encoder";
|
||||
|
||||
typedef struct {
|
||||
rmt_encoder_t base;
|
||||
rmt_encoder_t *bytes_encoder;
|
||||
rmt_encoder_t *copy_encoder;
|
||||
int state;
|
||||
rmt_symbol_word_t reset_code;
|
||||
} rmt_led_strip_encoder_t;
|
||||
|
||||
static size_t rmt_encode_led_strip(rmt_encoder_t *encoder, rmt_channel_handle_t channel, const void *primary_data, size_t data_size, rmt_encode_state_t *ret_state)
|
||||
{
|
||||
rmt_led_strip_encoder_t *led_encoder = __containerof(encoder, rmt_led_strip_encoder_t, base);
|
||||
rmt_encoder_handle_t bytes_encoder = led_encoder->bytes_encoder;
|
||||
rmt_encoder_handle_t copy_encoder = led_encoder->copy_encoder;
|
||||
rmt_encode_state_t session_state = 0;
|
||||
rmt_encode_state_t state = 0;
|
||||
size_t encoded_symbols = 0;
|
||||
switch (led_encoder->state) {
|
||||
case 0: // send RGB data
|
||||
encoded_symbols += bytes_encoder->encode(bytes_encoder, channel, primary_data, data_size, &session_state);
|
||||
if (session_state & RMT_ENCODING_COMPLETE) {
|
||||
led_encoder->state = 1; // switch to next state when current encoding session finished
|
||||
}
|
||||
if (session_state & RMT_ENCODING_MEM_FULL) {
|
||||
state |= RMT_ENCODING_MEM_FULL;
|
||||
goto out; // yield if there's no free space for encoding artifacts
|
||||
}
|
||||
// fall-through
|
||||
case 1: // send reset code
|
||||
encoded_symbols += copy_encoder->encode(copy_encoder, channel, &led_encoder->reset_code,
|
||||
sizeof(led_encoder->reset_code), &session_state);
|
||||
if (session_state & RMT_ENCODING_COMPLETE) {
|
||||
led_encoder->state = 0; // back to the initial encoding session
|
||||
state |= RMT_ENCODING_COMPLETE;
|
||||
}
|
||||
if (session_state & RMT_ENCODING_MEM_FULL) {
|
||||
state |= RMT_ENCODING_MEM_FULL;
|
||||
goto out; // yield if there's no free space for encoding artifacts
|
||||
}
|
||||
}
|
||||
out:
|
||||
*ret_state = state;
|
||||
return encoded_symbols;
|
||||
}
|
||||
|
||||
static esp_err_t rmt_del_led_strip_encoder(rmt_encoder_t *encoder)
|
||||
{
|
||||
rmt_led_strip_encoder_t *led_encoder = __containerof(encoder, rmt_led_strip_encoder_t, base);
|
||||
rmt_del_encoder(led_encoder->bytes_encoder);
|
||||
rmt_del_encoder(led_encoder->copy_encoder);
|
||||
free(led_encoder);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t rmt_led_strip_encoder_reset(rmt_encoder_t *encoder)
|
||||
{
|
||||
rmt_led_strip_encoder_t *led_encoder = __containerof(encoder, rmt_led_strip_encoder_t, base);
|
||||
rmt_encoder_reset(led_encoder->bytes_encoder);
|
||||
rmt_encoder_reset(led_encoder->copy_encoder);
|
||||
led_encoder->state = 0;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t rmt_new_led_strip_encoder(const led_strip_encoder_config_t *config, rmt_encoder_handle_t *ret_encoder)
|
||||
{
|
||||
esp_err_t ret = ESP_OK;
|
||||
rmt_led_strip_encoder_t *led_encoder = NULL;
|
||||
ESP_GOTO_ON_FALSE(config && ret_encoder, ESP_ERR_INVALID_ARG, err, TAG, "invalid argument");
|
||||
ESP_GOTO_ON_FALSE(config->led_model < LED_MODEL_INVALID, ESP_ERR_INVALID_ARG, err, TAG, "invalid led model");
|
||||
led_encoder = calloc(1, sizeof(rmt_led_strip_encoder_t));
|
||||
ESP_GOTO_ON_FALSE(led_encoder, ESP_ERR_NO_MEM, err, TAG, "no mem for led strip encoder");
|
||||
led_encoder->base.encode = rmt_encode_led_strip;
|
||||
led_encoder->base.del = rmt_del_led_strip_encoder;
|
||||
led_encoder->base.reset = rmt_led_strip_encoder_reset;
|
||||
rmt_bytes_encoder_config_t bytes_encoder_config;
|
||||
if (config->led_model == LED_MODEL_SK6812) {
|
||||
bytes_encoder_config = (rmt_bytes_encoder_config_t) {
|
||||
.bit0 = {
|
||||
.level0 = 1,
|
||||
.duration0 = 0.3 * config->resolution / 1000000, // T0H=0.3us
|
||||
.level1 = 0,
|
||||
.duration1 = 0.9 * config->resolution / 1000000, // T0L=0.9us
|
||||
},
|
||||
.bit1 = {
|
||||
.level0 = 1,
|
||||
.duration0 = 0.6 * config->resolution / 1000000, // T1H=0.6us
|
||||
.level1 = 0,
|
||||
.duration1 = 0.6 * config->resolution / 1000000, // T1L=0.6us
|
||||
},
|
||||
.flags.msb_first = 1 // SK6812 transfer bit order: G7...G0R7...R0B7...B0(W7...W0)
|
||||
};
|
||||
} else if (config->led_model == LED_MODEL_WS2812) {
|
||||
// different led strip might have its own timing requirements, following parameter is for WS2812
|
||||
bytes_encoder_config = (rmt_bytes_encoder_config_t) {
|
||||
.bit0 = {
|
||||
.level0 = 1,
|
||||
.duration0 = 0.3 * config->resolution / 1000000, // T0H=0.3us
|
||||
.level1 = 0,
|
||||
.duration1 = 0.9 * config->resolution / 1000000, // T0L=0.9us
|
||||
},
|
||||
.bit1 = {
|
||||
.level0 = 1,
|
||||
.duration0 = 0.9 * config->resolution / 1000000, // T1H=0.9us
|
||||
.level1 = 0,
|
||||
.duration1 = 0.3 * config->resolution / 1000000, // T1L=0.3us
|
||||
},
|
||||
.flags.msb_first = 1 // WS2812 transfer bit order: G7...G0R7...R0B7...B0
|
||||
};
|
||||
} else {
|
||||
assert(false);
|
||||
}
|
||||
ESP_GOTO_ON_ERROR(rmt_new_bytes_encoder(&bytes_encoder_config, &led_encoder->bytes_encoder), err, TAG, "create bytes encoder failed");
|
||||
rmt_copy_encoder_config_t copy_encoder_config = {};
|
||||
ESP_GOTO_ON_ERROR(rmt_new_copy_encoder(©_encoder_config, &led_encoder->copy_encoder), err, TAG, "create copy encoder failed");
|
||||
|
||||
uint32_t reset_ticks = config->resolution / 1000000 * 280 / 2; // reset code duration defaults to 280us to accomodate WS2812B-V5
|
||||
led_encoder->reset_code = (rmt_symbol_word_t) {
|
||||
.level0 = 0,
|
||||
.duration0 = reset_ticks,
|
||||
.level1 = 0,
|
||||
.duration1 = reset_ticks,
|
||||
};
|
||||
*ret_encoder = &led_encoder->base;
|
||||
return ESP_OK;
|
||||
err:
|
||||
if (led_encoder) {
|
||||
if (led_encoder->bytes_encoder) {
|
||||
rmt_del_encoder(led_encoder->bytes_encoder);
|
||||
}
|
||||
if (led_encoder->copy_encoder) {
|
||||
rmt_del_encoder(led_encoder->copy_encoder);
|
||||
}
|
||||
free(led_encoder);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include "driver/rmt_encoder.h"
|
||||
#include "led_strip_types.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Type of led strip encoder configuration
|
||||
*/
|
||||
typedef struct {
|
||||
uint32_t resolution; /*!< Encoder resolution, in Hz */
|
||||
led_model_t led_model; /*!< LED model */
|
||||
} led_strip_encoder_config_t;
|
||||
|
||||
/**
|
||||
* @brief Create RMT encoder for encoding LED strip pixels into RMT symbols
|
||||
*
|
||||
* @param[in] config Encoder configuration
|
||||
* @param[out] ret_encoder Returned encoder handle
|
||||
* @return
|
||||
* - ESP_ERR_INVALID_ARG for any invalid arguments
|
||||
* - ESP_ERR_NO_MEM out of memory when creating led strip encoder
|
||||
* - ESP_OK if creating encoder successfully
|
||||
*/
|
||||
esp_err_t rmt_new_led_strip_encoder(const led_strip_encoder_config_t *config, rmt_encoder_handle_t *ret_encoder);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,211 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/cdefs.h>
|
||||
#include "esp_log.h"
|
||||
#include "esp_check.h"
|
||||
#include "esp_rom_gpio.h"
|
||||
#include "soc/spi_periph.h"
|
||||
#include "led_strip.h"
|
||||
#include "led_strip_interface.h"
|
||||
#include "hal/spi_hal.h"
|
||||
|
||||
#define LED_STRIP_SPI_DEFAULT_RESOLUTION (2.5 * 1000 * 1000) // 2.5MHz resolution
|
||||
#define LED_STRIP_SPI_DEFAULT_TRANS_QUEUE_SIZE 4
|
||||
|
||||
#define SPI_BYTES_PER_COLOR_BYTE 3
|
||||
#define SPI_BITS_PER_COLOR_BYTE (SPI_BYTES_PER_COLOR_BYTE * 8)
|
||||
|
||||
static const char *TAG = "led_strip_spi";
|
||||
|
||||
typedef struct {
|
||||
led_strip_t base;
|
||||
spi_host_device_t spi_host;
|
||||
spi_device_handle_t spi_device;
|
||||
uint32_t strip_len;
|
||||
uint8_t bytes_per_pixel;
|
||||
uint8_t pixel_buf[];
|
||||
} led_strip_spi_obj;
|
||||
|
||||
// please make sure to zero-initialize the buf before calling this function
|
||||
static void __led_strip_spi_bit(uint8_t data, uint8_t *buf)
|
||||
{
|
||||
// Each color of 1 bit is represented by 3 bits of SPI, low_level:100 ,high_level:110
|
||||
// So a color byte occupies 3 bytes of SPI.
|
||||
*(buf + 2) |= data & BIT(0) ? BIT(2) | BIT(1) : BIT(2);
|
||||
*(buf + 2) |= data & BIT(1) ? BIT(5) | BIT(4) : BIT(5);
|
||||
*(buf + 2) |= data & BIT(2) ? BIT(7) : 0x00;
|
||||
*(buf + 1) |= BIT(0);
|
||||
*(buf + 1) |= data & BIT(3) ? BIT(3) | BIT(2) : BIT(3);
|
||||
*(buf + 1) |= data & BIT(4) ? BIT(6) | BIT(5) : BIT(6);
|
||||
*(buf + 0) |= data & BIT(5) ? BIT(1) | BIT(0) : BIT(1);
|
||||
*(buf + 0) |= data & BIT(6) ? BIT(4) | BIT(3) : BIT(4);
|
||||
*(buf + 0) |= data & BIT(7) ? BIT(7) | BIT(6) : BIT(7);
|
||||
}
|
||||
|
||||
static esp_err_t led_strip_spi_set_pixel(led_strip_t *strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue)
|
||||
{
|
||||
led_strip_spi_obj *spi_strip = __containerof(strip, led_strip_spi_obj, base);
|
||||
ESP_RETURN_ON_FALSE(index < spi_strip->strip_len, ESP_ERR_INVALID_ARG, TAG, "index out of maximum number of LEDs");
|
||||
// LED_PIXEL_FORMAT_GRB takes 72bits(9bytes)
|
||||
uint32_t start = index * spi_strip->bytes_per_pixel * SPI_BYTES_PER_COLOR_BYTE;
|
||||
memset(spi_strip->pixel_buf + start, 0, spi_strip->bytes_per_pixel * SPI_BYTES_PER_COLOR_BYTE);
|
||||
__led_strip_spi_bit(green, &spi_strip->pixel_buf[start]);
|
||||
__led_strip_spi_bit(red, &spi_strip->pixel_buf[start + SPI_BYTES_PER_COLOR_BYTE]);
|
||||
__led_strip_spi_bit(blue, &spi_strip->pixel_buf[start + SPI_BYTES_PER_COLOR_BYTE * 2]);
|
||||
if (spi_strip->bytes_per_pixel > 3) {
|
||||
__led_strip_spi_bit(0, &spi_strip->pixel_buf[start + SPI_BYTES_PER_COLOR_BYTE * 3]);
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t led_strip_spi_set_pixel_rgbw(led_strip_t *strip, uint32_t index, uint32_t red, uint32_t green, uint32_t blue, uint32_t white)
|
||||
{
|
||||
led_strip_spi_obj *spi_strip = __containerof(strip, led_strip_spi_obj, base);
|
||||
ESP_RETURN_ON_FALSE(index < spi_strip->strip_len, ESP_ERR_INVALID_ARG, TAG, "index out of maximum number of LEDs");
|
||||
ESP_RETURN_ON_FALSE(spi_strip->bytes_per_pixel == 4, ESP_ERR_INVALID_ARG, TAG, "wrong LED pixel format, expected 4 bytes per pixel");
|
||||
// LED_PIXEL_FORMAT_GRBW takes 96bits(12bytes)
|
||||
uint32_t start = index * spi_strip->bytes_per_pixel * SPI_BYTES_PER_COLOR_BYTE;
|
||||
// SK6812 component order is GRBW
|
||||
memset(spi_strip->pixel_buf + start, 0, spi_strip->bytes_per_pixel * SPI_BYTES_PER_COLOR_BYTE);
|
||||
__led_strip_spi_bit(green, &spi_strip->pixel_buf[start]);
|
||||
__led_strip_spi_bit(red, &spi_strip->pixel_buf[start + SPI_BYTES_PER_COLOR_BYTE]);
|
||||
__led_strip_spi_bit(blue, &spi_strip->pixel_buf[start + SPI_BYTES_PER_COLOR_BYTE * 2]);
|
||||
__led_strip_spi_bit(white, &spi_strip->pixel_buf[start + SPI_BYTES_PER_COLOR_BYTE * 3]);
|
||||
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t led_strip_spi_refresh(led_strip_t *strip)
|
||||
{
|
||||
led_strip_spi_obj *spi_strip = __containerof(strip, led_strip_spi_obj, base);
|
||||
spi_transaction_t tx_conf;
|
||||
memset(&tx_conf, 0, sizeof(tx_conf));
|
||||
|
||||
tx_conf.length = spi_strip->strip_len * spi_strip->bytes_per_pixel * SPI_BITS_PER_COLOR_BYTE;
|
||||
tx_conf.tx_buffer = spi_strip->pixel_buf;
|
||||
tx_conf.rx_buffer = NULL;
|
||||
ESP_RETURN_ON_ERROR(spi_device_transmit(spi_strip->spi_device, &tx_conf), TAG, "transmit pixels by SPI failed");
|
||||
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t led_strip_spi_clear(led_strip_t *strip)
|
||||
{
|
||||
led_strip_spi_obj *spi_strip = __containerof(strip, led_strip_spi_obj, base);
|
||||
//Write zero to turn off all leds
|
||||
memset(spi_strip->pixel_buf, 0, spi_strip->strip_len * spi_strip->bytes_per_pixel * SPI_BYTES_PER_COLOR_BYTE);
|
||||
uint8_t *buf = spi_strip->pixel_buf;
|
||||
for (int index = 0; index < spi_strip->strip_len * spi_strip->bytes_per_pixel; index++) {
|
||||
__led_strip_spi_bit(0, buf);
|
||||
buf += SPI_BYTES_PER_COLOR_BYTE;
|
||||
}
|
||||
|
||||
return led_strip_spi_refresh(strip);
|
||||
}
|
||||
|
||||
static esp_err_t led_strip_spi_del(led_strip_t *strip)
|
||||
{
|
||||
led_strip_spi_obj *spi_strip = __containerof(strip, led_strip_spi_obj, base);
|
||||
|
||||
ESP_RETURN_ON_ERROR(spi_bus_remove_device(spi_strip->spi_device), TAG, "delete spi device failed");
|
||||
ESP_RETURN_ON_ERROR(spi_bus_free(spi_strip->spi_host), TAG, "free spi bus failed");
|
||||
|
||||
free(spi_strip);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t led_strip_new_spi_device(const led_strip_config_t *led_config, const led_strip_spi_config_t *spi_config, led_strip_handle_t *ret_strip)
|
||||
{
|
||||
led_strip_spi_obj *spi_strip = NULL;
|
||||
esp_err_t ret = ESP_OK;
|
||||
ESP_GOTO_ON_FALSE(led_config && spi_config && ret_strip, ESP_ERR_INVALID_ARG, err, TAG, "invalid argument");
|
||||
ESP_GOTO_ON_FALSE(led_config->led_pixel_format < LED_PIXEL_FORMAT_INVALID, ESP_ERR_INVALID_ARG, err, TAG, "invalid led_pixel_format");
|
||||
uint8_t bytes_per_pixel = 3;
|
||||
if (led_config->led_pixel_format == LED_PIXEL_FORMAT_GRBW) {
|
||||
bytes_per_pixel = 4;
|
||||
} else if (led_config->led_pixel_format == LED_PIXEL_FORMAT_GRB) {
|
||||
bytes_per_pixel = 3;
|
||||
} else {
|
||||
assert(false);
|
||||
}
|
||||
uint32_t mem_caps = MALLOC_CAP_DEFAULT;
|
||||
if (spi_config->flags.with_dma) {
|
||||
// DMA buffer must be placed in internal SRAM
|
||||
mem_caps |= MALLOC_CAP_INTERNAL | MALLOC_CAP_DMA;
|
||||
}
|
||||
spi_strip = heap_caps_calloc(1, sizeof(led_strip_spi_obj) + led_config->max_leds * bytes_per_pixel * SPI_BYTES_PER_COLOR_BYTE, mem_caps);
|
||||
|
||||
ESP_GOTO_ON_FALSE(spi_strip, ESP_ERR_NO_MEM, err, TAG, "no mem for spi strip");
|
||||
|
||||
spi_strip->spi_host = spi_config->spi_bus;
|
||||
// for backward compatibility, if the user does not set the clk_src, use the default value
|
||||
spi_clock_source_t clk_src = SPI_CLK_SRC_DEFAULT;
|
||||
if (spi_config->clk_src) {
|
||||
clk_src = spi_config->clk_src;
|
||||
}
|
||||
|
||||
spi_bus_config_t spi_bus_cfg = {
|
||||
.mosi_io_num = led_config->strip_gpio_num,
|
||||
//Only use MOSI to generate the signal, set -1 when other pins are not used.
|
||||
.miso_io_num = -1,
|
||||
.sclk_io_num = -1,
|
||||
.quadwp_io_num = -1,
|
||||
.quadhd_io_num = -1,
|
||||
.max_transfer_sz = led_config->max_leds * bytes_per_pixel * SPI_BYTES_PER_COLOR_BYTE,
|
||||
};
|
||||
ESP_GOTO_ON_ERROR(spi_bus_initialize(spi_strip->spi_host, &spi_bus_cfg, spi_config->flags.with_dma ? SPI_DMA_CH_AUTO : SPI_DMA_DISABLED), err, TAG, "create SPI bus failed");
|
||||
|
||||
if (led_config->flags.invert_out == true) {
|
||||
esp_rom_gpio_connect_out_signal(led_config->strip_gpio_num, spi_periph_signal[spi_strip->spi_host].spid_out, true, false);
|
||||
}
|
||||
|
||||
spi_device_interface_config_t spi_dev_cfg = {
|
||||
.clock_source = clk_src,
|
||||
.command_bits = 0,
|
||||
.address_bits = 0,
|
||||
.dummy_bits = 0,
|
||||
.clock_speed_hz = LED_STRIP_SPI_DEFAULT_RESOLUTION,
|
||||
.mode = 0,
|
||||
//set -1 when CS is not used
|
||||
.spics_io_num = -1,
|
||||
.queue_size = LED_STRIP_SPI_DEFAULT_TRANS_QUEUE_SIZE,
|
||||
};
|
||||
|
||||
ESP_GOTO_ON_ERROR(spi_bus_add_device(spi_strip->spi_host, &spi_dev_cfg, &spi_strip->spi_device), err, TAG, "Failed to add spi device");
|
||||
//ensure the reset time is enough
|
||||
esp_rom_delay_us(10);
|
||||
int clock_resolution_khz = 0;
|
||||
spi_device_get_actual_freq(spi_strip->spi_device, &clock_resolution_khz);
|
||||
// TODO: ideally we should decide the SPI_BYTES_PER_COLOR_BYTE by the real clock resolution
|
||||
// But now, let's fixed the resolution, the downside is, we don't support a clock source whose frequency is not multiple of LED_STRIP_SPI_DEFAULT_RESOLUTION
|
||||
// clock_resolution between 2.2MHz to 2.8MHz is supported
|
||||
ESP_GOTO_ON_FALSE((clock_resolution_khz < LED_STRIP_SPI_DEFAULT_RESOLUTION / 1000 + 300) && (clock_resolution_khz > LED_STRIP_SPI_DEFAULT_RESOLUTION / 1000 - 300), ESP_ERR_NOT_SUPPORTED, err,
|
||||
TAG, "unsupported clock resolution:%dKHz", clock_resolution_khz);
|
||||
|
||||
spi_strip->bytes_per_pixel = bytes_per_pixel;
|
||||
spi_strip->strip_len = led_config->max_leds;
|
||||
spi_strip->base.set_pixel = led_strip_spi_set_pixel;
|
||||
spi_strip->base.set_pixel_rgbw = led_strip_spi_set_pixel_rgbw;
|
||||
spi_strip->base.refresh = led_strip_spi_refresh;
|
||||
spi_strip->base.clear = led_strip_spi_clear;
|
||||
spi_strip->base.del = led_strip_spi_del;
|
||||
|
||||
*ret_strip = &spi_strip->base;
|
||||
return ESP_OK;
|
||||
err:
|
||||
if (spi_strip) {
|
||||
if (spi_strip->spi_device) {
|
||||
spi_bus_remove_device(spi_strip->spi_device);
|
||||
}
|
||||
if (spi_strip->spi_host) {
|
||||
spi_bus_free(spi_strip->spi_host);
|
||||
}
|
||||
free(spi_strip);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
||||
CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y
|
||||
@@ -1,35 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Allow the app to bind to port 80 without root.
|
||||
# Run once: sudo scripts/setup-port80.sh (from repo root)
|
||||
# Or: scripts/setup-port80.sh (will prompt for sudo only for setcap)
|
||||
|
||||
set -e
|
||||
cd "$(dirname "$0")/.."
|
||||
REPO_ROOT="$(pwd)"
|
||||
# If run under sudo, use the invoking user's pipenv so the venv is found
|
||||
if [ -n "$SUDO_USER" ]; then
|
||||
VENV="$(sudo -u "$SUDO_USER" bash -c "cd '$REPO_ROOT' && pipenv --venv" 2>/dev/null)" || true
|
||||
else
|
||||
VENV="$(pipenv --venv 2>/dev/null)" || true
|
||||
fi
|
||||
if [ -z "$VENV" ]; then
|
||||
echo "Run 'pipenv install' first, then run this script again."
|
||||
exit 1
|
||||
fi
|
||||
PYTHON="${VENV}/bin/python3"
|
||||
if [ ! -f "$PYTHON" ]; then
|
||||
PYTHON="${VENV}/bin/python"
|
||||
fi
|
||||
if [ ! -f "$PYTHON" ]; then
|
||||
echo "Python not found in venv: $VENV"
|
||||
exit 1
|
||||
fi
|
||||
# Use the real binary (setcap can fail on symlinks or some filesystems)
|
||||
REAL_PYTHON="$(readlink -f "$PYTHON" 2>/dev/null)" || REAL_PYTHON="$PYTHON"
|
||||
if sudo setcap 'cap_net_bind_service=+ep' "$REAL_PYTHON" 2>/dev/null; then
|
||||
echo "OK: port 80 enabled for $REAL_PYTHON"
|
||||
echo "Start the app with: pipenv run run"
|
||||
else
|
||||
echo "setcap failed on $REAL_PYTHON"
|
||||
exit 1
|
||||
fi
|
||||
Executable
+82
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env bash
|
||||
# Enable VPN at boot on Raspberry Pi OS (NetworkManager or WireGuard).
|
||||
#
|
||||
# NetworkManager (import VPN in nm-connection-editor or nmcli first):
|
||||
# sudo ./scripts/setup-vpn-autoconnect.sh nm "My VPN connection name"
|
||||
#
|
||||
# WireGuard (/etc/wireguard/wg0.conf must exist; interface name without .conf):
|
||||
# sudo ./scripts/setup-vpn-autoconnect.sh wg wg0
|
||||
#
|
||||
# OpenVPN single file (needs network-manager-openvpn):
|
||||
# sudo ./scripts/setup-vpn-autoconnect.sh import-openvpn /home/pi/OpenVPN-Config.ovpn
|
||||
# sudo ./scripts/setup-vpn-autoconnect.sh nm OpenVPN-Config
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
usage() {
|
||||
sed -n '2,17p' "$0" | sed 's/^# \{0,1\}//'
|
||||
exit 1
|
||||
}
|
||||
|
||||
if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then
|
||||
usage
|
||||
fi
|
||||
|
||||
case "${1:-}" in
|
||||
import-openvpn|import-ovpn)
|
||||
FILE="${2:-}"
|
||||
if [ -z "$FILE" ] || [ ! -f "$FILE" ]; then
|
||||
echo "Usage: $0 import-openvpn /path/to/profile.ovpn" >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! command -v nmcli >/dev/null 2>&1; then
|
||||
echo "nmcli not found." >&2
|
||||
exit 1
|
||||
fi
|
||||
ABS="$(readlink -f "$FILE")"
|
||||
nmcli connection import type openvpn file "$ABS"
|
||||
NM_NAME="$(basename "$FILE" .ovpn)"
|
||||
nmcli connection modify "$NM_NAME" connection.autoconnect yes
|
||||
nmcli connection modify "$NM_NAME" connection.autoconnect-priority 20
|
||||
echo "Imported as NM connection: $NM_NAME (autoconnect on)"
|
||||
echo "Connect now: sudo nmcli connection up \"$NM_NAME\""
|
||||
;;
|
||||
nm|network-manager)
|
||||
NAME="${2:-}"
|
||||
if [ -z "$NAME" ]; then
|
||||
echo "Usage: $0 nm \"Connection name\"" >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! command -v nmcli >/dev/null 2>&1; then
|
||||
echo "nmcli not found. Install NetworkManager." >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! nmcli -t -f NAME connection show "$NAME" >/dev/null 2>&1; then
|
||||
echo "No NetworkManager connection named: $NAME" >&2
|
||||
echo "List: nmcli -f NAME,TYPE connection" >&2
|
||||
exit 1
|
||||
fi
|
||||
nmcli connection modify "$NAME" connection.autoconnect yes
|
||||
nmcli connection modify "$NAME" connection.autoconnect-priority 10
|
||||
echo "Enabled autoconnect for NM profile: $NAME"
|
||||
echo "Reconnect now: sudo nmcli connection up \"$NAME\""
|
||||
;;
|
||||
wg|wireguard)
|
||||
IFACE="${2:-}"
|
||||
if [ -z "$IFACE" ]; then
|
||||
echo "Usage: $0 wg wg0 (config must be /etc/wireguard/\${IFACE}.conf)" >&2
|
||||
exit 1
|
||||
fi
|
||||
CFG="/etc/wireguard/${IFACE}.conf"
|
||||
if [ ! -f "$CFG" ]; then
|
||||
echo "Missing $CFG — create it first (e.g. copy from your VPN provider)." >&2
|
||||
exit 1
|
||||
fi
|
||||
systemctl enable "wg-quick@${IFACE}.service"
|
||||
echo "Enabled: wg-quick@${IFACE}.service (starts at boot)"
|
||||
echo "Start now: sudo systemctl start wg-quick@${IFACE}"
|
||||
;;
|
||||
*)
|
||||
usage
|
||||
;;
|
||||
esac
|
||||
@@ -1,38 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Start the LED controller web server (port 80 by default).
|
||||
# Avoid `pipenv run` on the hot path — it re-resolves the env every time and is slow on a Pi.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
cd "$ROOT"
|
||||
export PORT="${PORT:-80}"
|
||||
export PIPENV_VENV_IN_PROJECT="${PIPENV_VENV_IN_PROJECT:-1}"
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
CACHE="$SCRIPT_DIR/.led-controller-venv"
|
||||
PYTHON=""
|
||||
|
||||
if [ -x "$ROOT/.venv/bin/python" ]; then
|
||||
PYTHON="$ROOT/.venv/bin/python"
|
||||
elif [ -f "$CACHE" ]; then
|
||||
_v="$(tr -d '\r\n' < "$CACHE")"
|
||||
if [ -n "$_v" ] && [ -x "$_v/bin/python" ]; then
|
||||
PYTHON="$_v/bin/python"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$PYTHON" ] && command -v pipenv >/dev/null 2>&1; then
|
||||
_v="$(cd "$ROOT" && pipenv --venv 2>/dev/null || true)"
|
||||
if [ -n "${_v:-}" ] && [ -x "$_v/bin/python" ]; then
|
||||
PYTHON="$_v/bin/python"
|
||||
printf '%s\n' "$_v" > "$CACHE" || true
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ -z "$PYTHON" ]; then
|
||||
echo 'led-controller: no venv resolved; using pipenv run (slow). Run: cd '"$ROOT"' && PIPENV_VENV_IN_PROJECT=1 pipenv install --skip-lock --python "$(command -v python3)"' >&2
|
||||
exec pipenv run run
|
||||
fi
|
||||
|
||||
cd "$ROOT/src"
|
||||
exec "$PYTHON" -u main.py
|
||||
@@ -1,33 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Test the app on port 80. Run after: sudo scripts/setup-port80.sh
|
||||
# Usage: ./scripts/test-port80.sh
|
||||
|
||||
set -e
|
||||
cd "$(dirname "$0")/.."
|
||||
APP_URL="${APP_URL:-http://127.0.0.1:80}"
|
||||
|
||||
echo "Starting app on port 80 in background..."
|
||||
pipenv run run &
|
||||
PID=$!
|
||||
trap "kill $PID 2>/dev/null; exit" EXIT
|
||||
|
||||
echo "Waiting for server to start..."
|
||||
for i in 1 2 3 4 5 6 7 8 9 10; do
|
||||
if curl -s -o /dev/null -w "%{http_code}" "$APP_URL/" 2>/dev/null | grep -q 200; then
|
||||
echo "Server is up."
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
echo "Requesting $APP_URL/ ..."
|
||||
CODE=$(curl -s -o /dev/null -w "%{http_code}" "$APP_URL/")
|
||||
if [ "$CODE" = "200" ]; then
|
||||
echo "OK: GET / returned HTTP $CODE"
|
||||
curl -s "$APP_URL/" | head -5
|
||||
echo "..."
|
||||
exit 0
|
||||
else
|
||||
echo "FAIL: GET / returned HTTP $CODE (expected 200)"
|
||||
exit 1
|
||||
fi
|
||||
@@ -1,6 +0,0 @@
|
||||
# Boot script (ESP only; no-op on Pi)
|
||||
import settings # noqa: F401
|
||||
from settings import Settings
|
||||
|
||||
s = Settings()
|
||||
# AP setup was here when running on ESP; Pi uses system networking.
|
||||
@@ -1 +0,0 @@
|
||||
# Controllers package
|
||||
@@ -1,393 +0,0 @@
|
||||
from microdot import Microdot
|
||||
from models.device import (
|
||||
Device,
|
||||
derive_device_mac,
|
||||
validate_device_transport,
|
||||
validate_device_type,
|
||||
)
|
||||
from models.transport import get_current_sender
|
||||
from models.wifi_ws_clients import (
|
||||
normalize_tcp_peer_ip,
|
||||
send_json_line_to_ip,
|
||||
tcp_client_connected,
|
||||
)
|
||||
from util.driver_patterns import driver_patterns_dir
|
||||
from util.espnow_message import build_message
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
from urllib.parse import quote
|
||||
|
||||
# Ephemeral driver preset name (never written to Pi preset store; ``save`` not set on wire).
|
||||
_IDENTIFY_PRESET_KEY = "__identify"
|
||||
|
||||
# Short-key payload: 10 Hz full cycle = 50 ms on + 50 ms off (driver ``blink`` toggles each ``d`` ms).
|
||||
_IDENTIFY_DRIVER_PRESET = {
|
||||
"p": "blink",
|
||||
"c": ["#ff0000"],
|
||||
"d": 50,
|
||||
"b": 128,
|
||||
"a": True,
|
||||
"n1": 0,
|
||||
"n2": 0,
|
||||
"n3": 0,
|
||||
"n4": 0,
|
||||
"n5": 0,
|
||||
"n6": 0,
|
||||
}
|
||||
|
||||
|
||||
def _compact_v1_json(*, presets=None, select=None, save=False):
|
||||
"""Single-line v1 object; compact so serial/ESP-NOW stays small."""
|
||||
body = {"v": "1"}
|
||||
if presets is not None:
|
||||
body["presets"] = presets
|
||||
if save:
|
||||
body["save"] = True
|
||||
if select is not None:
|
||||
body["select"] = select
|
||||
return json.dumps(body, separators=(",", ":"))
|
||||
|
||||
# Seconds after identify blink before selecting built-in ``off`` (tests may monkeypatch).
|
||||
IDENTIFY_OFF_DELAY_S = 2.0
|
||||
|
||||
controller = Microdot()
|
||||
devices = Device()
|
||||
|
||||
|
||||
def _device_live_connected(dev_dict):
|
||||
"""
|
||||
Wi-Fi: whether the controller has an outbound WebSocket to this device's IP.
|
||||
ESP-NOW: None (no Wi-Fi session on the Pi for that transport).
|
||||
"""
|
||||
tr = (dev_dict.get("transport") or "espnow").strip().lower()
|
||||
if tr != "wifi":
|
||||
return None
|
||||
ip = normalize_tcp_peer_ip(dev_dict.get("address") or "")
|
||||
if not ip:
|
||||
return False
|
||||
return tcp_client_connected(ip)
|
||||
|
||||
|
||||
def _device_json_with_live_status(dev_dict):
|
||||
row = dict(dev_dict)
|
||||
row["connected"] = _device_live_connected(dev_dict)
|
||||
return row
|
||||
|
||||
|
||||
def _safe_pattern_filename(name):
|
||||
if not isinstance(name, str):
|
||||
return False
|
||||
if not name.endswith(".py"):
|
||||
return False
|
||||
if "/" in name or "\\" in name or ".." in name:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _http_post_pattern_source(ip, filename, code_text, reload_patterns=True, timeout_s=10.0):
|
||||
"""POST source to driver /patterns/upload?name=...&reload=...; return True on 2xx."""
|
||||
if not isinstance(ip, str) or not ip.strip():
|
||||
return False
|
||||
if not isinstance(filename, str) or not filename:
|
||||
return False
|
||||
if not isinstance(code_text, str):
|
||||
return False
|
||||
|
||||
name_q = quote(filename, safe="")
|
||||
reload_q = "1" if reload_patterns else "0"
|
||||
path = "/patterns/upload?name=%s&reload=%s" % (name_q, reload_q)
|
||||
body = code_text.encode("utf-8")
|
||||
req = (
|
||||
"POST %s HTTP/1.1\r\n"
|
||||
"Host: %s\r\n"
|
||||
"Content-Type: text/plain; charset=utf-8\r\n"
|
||||
"Content-Length: %d\r\n"
|
||||
"Connection: close\r\n"
|
||||
"\r\n" % (path, ip, len(body))
|
||||
).encode("utf-8") + body
|
||||
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
try:
|
||||
sock.settimeout(timeout_s)
|
||||
sock.connect((ip.strip(), 80))
|
||||
sock.sendall(req)
|
||||
data = b""
|
||||
while True:
|
||||
chunk = sock.recv(1024)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
except OSError:
|
||||
return False
|
||||
finally:
|
||||
try:
|
||||
sock.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
first_line = data.split(b"\r\n", 1)[0] if data else b""
|
||||
return b" 2" in first_line
|
||||
|
||||
|
||||
async def _identify_send_off_after_delay(sender, transport, wifi_ip, dev_id, name):
|
||||
try:
|
||||
await asyncio.sleep(IDENTIFY_OFF_DELAY_S)
|
||||
off_msg = build_message(select={name: ["off"]})
|
||||
if transport == "wifi":
|
||||
await send_json_line_to_ip(wifi_ip, off_msg)
|
||||
else:
|
||||
await sender.send(off_msg, addr=dev_id)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@controller.get("")
|
||||
async def list_devices(request):
|
||||
"""List all devices (includes ``connected`` for live Wi-Fi WebSocket presence)."""
|
||||
devices_data = {}
|
||||
for dev_id in devices.list():
|
||||
d = devices.read(dev_id)
|
||||
if d:
|
||||
devices_data[dev_id] = _device_json_with_live_status(d)
|
||||
return json.dumps(devices_data), 200, {"Content-Type": "application/json"}
|
||||
|
||||
|
||||
@controller.get("/<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",
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
from microdot import Microdot
|
||||
from models.group import Group
|
||||
import json
|
||||
|
||||
controller = Microdot()
|
||||
groups = Group()
|
||||
|
||||
@controller.get('')
|
||||
async def list_groups(request):
|
||||
"""List all groups."""
|
||||
return json.dumps(groups), 200, {'Content-Type': 'application/json'}
|
||||
|
||||
@controller.get('/<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
|
||||
@@ -1,189 +0,0 @@
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from microdot import Microdot
|
||||
from serial.tools import list_ports
|
||||
|
||||
controller = Microdot()
|
||||
|
||||
|
||||
def _repo_root() -> str:
|
||||
return os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
|
||||
|
||||
|
||||
def _led_cli_path() -> str:
|
||||
return os.path.join(_repo_root(), "led-tool", "cli.py")
|
||||
|
||||
|
||||
def _build_led_cli_command(port: str, payload: dict):
|
||||
cmd = [sys.executable, _led_cli_path(), "--port", port]
|
||||
|
||||
flag_map = (
|
||||
("name", "--name"),
|
||||
("led_pin", "--pin"),
|
||||
("num_leds", "--leds"),
|
||||
("brightness", "--brightness"),
|
||||
("transport", "--transport"),
|
||||
("ssid", "--ssid"),
|
||||
("password", "--wifi-password"),
|
||||
("wifi_channel", "--wifi-channel"),
|
||||
("default", "--default"),
|
||||
)
|
||||
|
||||
for key, flag in flag_map:
|
||||
value = payload.get(key)
|
||||
if value is None:
|
||||
continue
|
||||
value_str = str(value).strip()
|
||||
if value_str == "":
|
||||
continue
|
||||
cmd.extend([flag, value_str])
|
||||
|
||||
return cmd
|
||||
|
||||
|
||||
def _run_led_cli_command(cmd, cli_path: str, timeout_s=180):
|
||||
try:
|
||||
result = subprocess.run(
|
||||
cmd,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=timeout_s,
|
||||
cwd=os.path.dirname(cli_path),
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
return (
|
||||
json.dumps({"error": "led-tool command timed out after 180 seconds"}),
|
||||
504,
|
||||
{"Content-Type": "application/json"},
|
||||
)
|
||||
except Exception as exc:
|
||||
return (
|
||||
json.dumps({"error": str(exc)}),
|
||||
500,
|
||||
{"Content-Type": "application/json"},
|
||||
)
|
||||
|
||||
return (
|
||||
json.dumps(
|
||||
{
|
||||
"ok": result.returncode == 0,
|
||||
"returncode": result.returncode,
|
||||
"stdout": result.stdout,
|
||||
"stderr": result.stderr,
|
||||
"command": cmd,
|
||||
}
|
||||
),
|
||||
200,
|
||||
{"Content-Type": "application/json"},
|
||||
)
|
||||
|
||||
|
||||
def _extract_settings_from_stdout(stdout: str):
|
||||
text = (stdout or "").strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
parsed = json.loads(text)
|
||||
return parsed if isinstance(parsed, dict) else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
@controller.get("/ports")
|
||||
async def list_serial_ports(request):
|
||||
ports = []
|
||||
for info in list_ports.comports():
|
||||
ports.append(
|
||||
{
|
||||
"device": info.device,
|
||||
"description": info.description,
|
||||
"hwid": info.hwid,
|
||||
}
|
||||
)
|
||||
return (
|
||||
json.dumps(
|
||||
{
|
||||
"ports": ports,
|
||||
"led_cli_exists": os.path.exists(_led_cli_path()),
|
||||
}
|
||||
),
|
||||
200,
|
||||
{"Content-Type": "application/json"},
|
||||
)
|
||||
|
||||
|
||||
@controller.post("/settings")
|
||||
async def apply_settings(request):
|
||||
data = request.json or {}
|
||||
port = str(data.get("port") or "").strip()
|
||||
if not port:
|
||||
return (
|
||||
json.dumps({"error": "port is required"}),
|
||||
400,
|
||||
{"Content-Type": "application/json"},
|
||||
)
|
||||
|
||||
cli_path = _led_cli_path()
|
||||
if not os.path.exists(cli_path):
|
||||
return (
|
||||
json.dumps({"error": "led-tool/cli.py not found"}),
|
||||
500,
|
||||
{"Content-Type": "application/json"},
|
||||
)
|
||||
|
||||
cmd = _build_led_cli_command(port, data) + ["--follow"]
|
||||
return _run_led_cli_command(cmd, cli_path, timeout_s=None)
|
||||
|
||||
|
||||
@controller.post("/reset")
|
||||
@controller.post("/reset/")
|
||||
async def reset_device(request):
|
||||
data = request.json or {}
|
||||
port = str(data.get("port") or "").strip()
|
||||
if not port:
|
||||
return (
|
||||
json.dumps({"error": "port is required"}),
|
||||
400,
|
||||
{"Content-Type": "application/json"},
|
||||
)
|
||||
|
||||
cli_path = _led_cli_path()
|
||||
if not os.path.exists(cli_path):
|
||||
return (
|
||||
json.dumps({"error": "led-tool/cli.py not found"}),
|
||||
500,
|
||||
{"Content-Type": "application/json"},
|
||||
)
|
||||
|
||||
cmd = [sys.executable, cli_path, "--port", port, "--reset", "--follow"]
|
||||
return _run_led_cli_command(cmd, cli_path, timeout_s=None)
|
||||
|
||||
|
||||
@controller.get("/settings")
|
||||
async def read_settings(request):
|
||||
port = str(request.args.get("port") or "").strip()
|
||||
if not port:
|
||||
return (
|
||||
json.dumps({"error": "port is required"}),
|
||||
400,
|
||||
{"Content-Type": "application/json"},
|
||||
)
|
||||
|
||||
cli_path = _led_cli_path()
|
||||
if not os.path.exists(cli_path):
|
||||
return (
|
||||
json.dumps({"error": "led-tool/cli.py not found"}),
|
||||
500,
|
||||
{"Content-Type": "application/json"},
|
||||
)
|
||||
|
||||
cmd = [sys.executable, cli_path, "--port", port, "--show"]
|
||||
body, status, headers = _run_led_cli_command(cmd, cli_path)
|
||||
if status != 200:
|
||||
return body, status, headers
|
||||
data = json.loads(body)
|
||||
data["settings"] = _extract_settings_from_stdout(data.get("stdout") or "")
|
||||
return json.dumps(data), status, headers
|
||||
@@ -1,85 +0,0 @@
|
||||
from microdot import Microdot
|
||||
from models.output import Output
|
||||
from engine.outputs import open_output
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
controller = Microdot()
|
||||
outputs = Output()
|
||||
|
||||
_JSON = {'Content-Type': 'application/json'}
|
||||
|
||||
TEST_COLORS = ((255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255))
|
||||
|
||||
|
||||
async def run_output_test(out, step_s=1.0):
|
||||
"""Red, green, blue, white for ``step_s`` each, then black."""
|
||||
await out.open()
|
||||
try:
|
||||
for color in TEST_COLORS:
|
||||
frame = bytes(color) * out.pixel_count
|
||||
end = asyncio.get_running_loop().time() + step_s
|
||||
while asyncio.get_running_loop().time() < end:
|
||||
await out.send(frame)
|
||||
await asyncio.sleep(1.0 / out.fps)
|
||||
finally:
|
||||
await out.close()
|
||||
return out.status()
|
||||
|
||||
|
||||
@controller.get('')
|
||||
async def list_outputs(request):
|
||||
"""List all pixel outputs."""
|
||||
return json.dumps(outputs), 200, _JSON
|
||||
|
||||
|
||||
@controller.get('/<id>')
|
||||
async def get_output(request, id):
|
||||
doc = outputs.read(id)
|
||||
if doc:
|
||||
return json.dumps(doc), 200, _JSON
|
||||
return json.dumps({"error": "Output not found"}), 404, _JSON
|
||||
|
||||
|
||||
@controller.post('')
|
||||
async def create_output(request):
|
||||
try:
|
||||
output_id = outputs.create(request.json or {})
|
||||
return json.dumps(outputs.read(output_id)), 201, _JSON
|
||||
except ValueError as e:
|
||||
return json.dumps({"error": str(e)}), 400, _JSON
|
||||
|
||||
|
||||
@controller.put('/<id>')
|
||||
async def update_output(request, id):
|
||||
try:
|
||||
if outputs.update(id, request.json or {}):
|
||||
return json.dumps(outputs.read(id)), 200, _JSON
|
||||
return json.dumps({"error": "Output not found"}), 404, _JSON
|
||||
except ValueError as e:
|
||||
return json.dumps({"error": str(e)}), 400, _JSON
|
||||
|
||||
|
||||
@controller.delete('/<id>')
|
||||
async def delete_output(request, id):
|
||||
if outputs.delete(id):
|
||||
return json.dumps({"message": "Output deleted successfully"}), 200, _JSON
|
||||
return json.dumps({"error": "Output not found"}), 404, _JSON
|
||||
|
||||
|
||||
@controller.post('/<id>/test')
|
||||
async def test_output(request, id):
|
||||
"""Send a short red/green/blue/white test sequence, then black."""
|
||||
doc = outputs.read(id)
|
||||
if not doc:
|
||||
return json.dumps({"error": "Output not found"}), 404, _JSON
|
||||
data = request.json or {}
|
||||
try:
|
||||
step_s = max(0.1, min(5.0, float(data.get("step_s", 1.0))))
|
||||
except (TypeError, ValueError):
|
||||
step_s = 1.0
|
||||
try:
|
||||
status = await run_output_test(open_output(doc), step_s=step_s)
|
||||
except Exception as e:
|
||||
return json.dumps({"error": f"Test failed: {e}"}), 503, _JSON
|
||||
return json.dumps({"message": "Test sent", "status": status}), 200, _JSON
|
||||
@@ -1,58 +0,0 @@
|
||||
from microdot import Microdot
|
||||
from models.pallet import Palette
|
||||
import json
|
||||
|
||||
controller = Microdot()
|
||||
palettes = Palette()
|
||||
|
||||
@controller.get('')
|
||||
async def list_palettes(request):
|
||||
"""List all palettes."""
|
||||
data = {}
|
||||
for pid in palettes.list():
|
||||
colors = palettes.read(pid)
|
||||
data[pid] = colors
|
||||
return json.dumps(data), 200, {'Content-Type': 'application/json'}
|
||||
|
||||
@controller.get('/<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
|
||||
@@ -1,500 +0,0 @@
|
||||
from microdot import Microdot
|
||||
from models.pattern import Pattern
|
||||
from models.device import Device
|
||||
from util.driver_patterns import (
|
||||
driver_patterns_dir,
|
||||
is_firmware_builtin_pattern_module,
|
||||
normalize_pattern_py_filename,
|
||||
)
|
||||
import json
|
||||
import re
|
||||
import os
|
||||
import socket
|
||||
from urllib.parse import quote
|
||||
|
||||
controller = Microdot()
|
||||
patterns = Pattern()
|
||||
|
||||
|
||||
def _project_root():
|
||||
"""Project root (parent of ``src/``). CWD is often ``src/`` when running ``main.py``."""
|
||||
here = os.path.dirname(os.path.abspath(__file__))
|
||||
return os.path.abspath(os.path.join(here, "..", ".."))
|
||||
|
||||
|
||||
def _safe_pattern_filename(name):
|
||||
if not isinstance(name, str):
|
||||
return False
|
||||
if not name.endswith(".py"):
|
||||
return False
|
||||
if "/" in name or "\\" in name or ".." in name:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
_PATTERN_KEY_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]{0,63}$")
|
||||
|
||||
|
||||
def _normalize_pattern_key(raw):
|
||||
"""Pattern id / module basename (no .py)."""
|
||||
if not isinstance(raw, str):
|
||||
return ""
|
||||
s = raw.strip()
|
||||
if s.lower().endswith(".py"):
|
||||
s = s[:-3].strip()
|
||||
return s
|
||||
|
||||
|
||||
def _valid_pattern_key(key):
|
||||
return bool(key and _PATTERN_KEY_RE.match(key))
|
||||
|
||||
|
||||
def _http_post_pattern_source(ip, filename, code_text, reload_patterns=True, timeout_s=10.0):
|
||||
"""POST source to driver /patterns/upload?name=...&reload=...; return True on 2xx."""
|
||||
if not isinstance(ip, str) or not ip.strip():
|
||||
return False
|
||||
if not isinstance(filename, str) or not filename:
|
||||
return False
|
||||
if not isinstance(code_text, str):
|
||||
return False
|
||||
|
||||
name_q = quote(filename, safe="")
|
||||
reload_q = "1" if reload_patterns else "0"
|
||||
path = "/patterns/upload?name=%s&reload=%s" % (name_q, reload_q)
|
||||
body = code_text.encode("utf-8")
|
||||
req = (
|
||||
"POST %s HTTP/1.1\r\n"
|
||||
"Host: %s\r\n"
|
||||
"Content-Type: text/plain; charset=utf-8\r\n"
|
||||
"Content-Length: %d\r\n"
|
||||
"Connection: close\r\n"
|
||||
"\r\n" % (path, ip, len(body))
|
||||
).encode("utf-8") + body
|
||||
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
try:
|
||||
sock.settimeout(timeout_s)
|
||||
sock.connect((ip.strip(), 80))
|
||||
sock.sendall(req)
|
||||
data = b""
|
||||
while True:
|
||||
chunk = sock.recv(1024)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
except OSError:
|
||||
return False
|
||||
finally:
|
||||
try:
|
||||
sock.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
first_line = data.split(b"\r\n", 1)[0] if data else b""
|
||||
# Accept any 2xx status.
|
||||
return b" 2" in first_line
|
||||
|
||||
def load_pattern_definitions():
|
||||
"""Load pattern definitions from pattern.json file."""
|
||||
try:
|
||||
root = _project_root()
|
||||
paths = [
|
||||
os.path.join(root, "db", "pattern.json"),
|
||||
os.path.join(root, "pattern.json"),
|
||||
"db/pattern.json",
|
||||
"pattern.json",
|
||||
"/db/pattern.json",
|
||||
]
|
||||
for path in paths:
|
||||
try:
|
||||
with open(path, "r") as f:
|
||||
return json.load(f)
|
||||
except OSError:
|
||||
continue
|
||||
return {}
|
||||
except Exception as e:
|
||||
print(f"Error loading pattern.json: {e}")
|
||||
return {}
|
||||
|
||||
|
||||
def load_driver_pattern_names():
|
||||
"""List available pattern module names from led-driver/src/patterns."""
|
||||
try:
|
||||
names = []
|
||||
for filename in os.listdir(driver_patterns_dir()):
|
||||
if not _safe_pattern_filename(filename) or filename == "__init__.py":
|
||||
continue
|
||||
names.append(filename[:-3])
|
||||
names.sort()
|
||||
return names
|
||||
except OSError:
|
||||
return []
|
||||
|
||||
|
||||
def build_runtime_pattern_map():
|
||||
"""
|
||||
Runtime pattern map for UI menus.
|
||||
Keep pattern DB metadata as primary, then add any local driver pattern files
|
||||
missing from the DB so new OTA files still appear in menus.
|
||||
"""
|
||||
definitions = load_pattern_definitions()
|
||||
available = load_driver_pattern_names()
|
||||
result = {}
|
||||
for name, meta in definitions.items():
|
||||
result[name] = dict(meta) if isinstance(meta, dict) else {}
|
||||
for name in available:
|
||||
if name not in result:
|
||||
result[name] = {}
|
||||
return result
|
||||
|
||||
@controller.get('/definitions')
|
||||
async def get_pattern_definitions(request):
|
||||
"""Get definitions for patterns currently available on the driver."""
|
||||
definitions = build_runtime_pattern_map()
|
||||
return json.dumps(definitions), 200, {'Content-Type': 'application/json'}
|
||||
|
||||
|
||||
@controller.get('/ota/manifest')
|
||||
async def ota_manifest(request):
|
||||
"""Manifest of driver pattern source files for OTA pulls."""
|
||||
base_dir = driver_patterns_dir()
|
||||
host = request.headers.get("Host", "")
|
||||
if not host:
|
||||
return json.dumps({"error": "Missing Host header"}), 400, {
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
try:
|
||||
names = sorted(os.listdir(base_dir))
|
||||
except OSError as e:
|
||||
return json.dumps({"error": str(e)}), 500, {"Content-Type": "application/json"}
|
||||
|
||||
files = []
|
||||
for name in names:
|
||||
if not _safe_pattern_filename(name) or name == "__init__.py":
|
||||
continue
|
||||
files.append({
|
||||
"name": name,
|
||||
"url": "http://%s/patterns/ota/file/%s" % (host, name),
|
||||
})
|
||||
|
||||
return json.dumps({"files": files}), 200, {"Content-Type": "application/json"}
|
||||
|
||||
|
||||
@controller.get('/ota/file/<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
|
||||
@@ -1,322 +0,0 @@
|
||||
from microdot import Microdot
|
||||
from microdot.session import with_session
|
||||
from models.preset import Preset
|
||||
from models.profile import Profile
|
||||
from models.device import Device, normalize_mac
|
||||
from models.transport import get_current_sender
|
||||
from util.driver_delivery import deliver_json_messages, deliver_preset_broadcast_then_per_device
|
||||
from util.espnow_message import build_message, build_preset_dict
|
||||
import json
|
||||
|
||||
controller = Microdot()
|
||||
presets = Preset()
|
||||
profiles = Profile()
|
||||
|
||||
def get_current_profile_id(session=None):
|
||||
"""Get the current active profile ID from session or fallback to first."""
|
||||
profile_list = profiles.list()
|
||||
session_profile = None
|
||||
if session is not None:
|
||||
session_profile = session.get('current_profile')
|
||||
if session_profile and session_profile in profile_list:
|
||||
return session_profile
|
||||
if profile_list:
|
||||
return profile_list[0]
|
||||
return None
|
||||
|
||||
@controller.get('')
|
||||
@with_session
|
||||
async def list_presets(request, session):
|
||||
"""List presets for the current profile."""
|
||||
current_profile_id = get_current_profile_id(session)
|
||||
if not current_profile_id:
|
||||
return json.dumps({}), 200, {'Content-Type': 'application/json'}
|
||||
scoped = {
|
||||
pid: pdata for pid, pdata in presets.items()
|
||||
if isinstance(pdata, dict) and str(pdata.get("profile_id")) == str(current_profile_id)
|
||||
}
|
||||
return json.dumps(scoped), 200, {'Content-Type': 'application/json'}
|
||||
|
||||
@controller.get('/<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'}
|
||||
|
||||
@@ -1,390 +0,0 @@
|
||||
from microdot import Microdot
|
||||
from microdot.session import with_session
|
||||
from models.profile import Profile
|
||||
from models.zone import Zone
|
||||
from models.preset import Preset
|
||||
import json
|
||||
|
||||
controller = Microdot()
|
||||
profiles = Profile()
|
||||
zones = Zone()
|
||||
presets = Preset()
|
||||
|
||||
@controller.get('')
|
||||
@with_session
|
||||
async def list_profiles(request, session):
|
||||
"""List all profiles with current profile info."""
|
||||
profile_list = profiles.list()
|
||||
current_id = session.get('current_profile')
|
||||
if current_id and current_id not in profile_list:
|
||||
current_id = None
|
||||
|
||||
# If no current profile in session, use first one
|
||||
if not current_id and profile_list:
|
||||
current_id = profile_list[0]
|
||||
session['current_profile'] = str(current_id)
|
||||
session.save()
|
||||
|
||||
# Build profiles object
|
||||
profiles_data = {}
|
||||
for profile_id in profile_list:
|
||||
profile_data = profiles.read(profile_id)
|
||||
if profile_data:
|
||||
profiles_data[profile_id] = profile_data
|
||||
|
||||
return json.dumps({
|
||||
"profiles": profiles_data,
|
||||
"current_profile_id": current_id
|
||||
}), 200, {'Content-Type': 'application/json'}
|
||||
|
||||
@controller.get('/current')
|
||||
@with_session
|
||||
async def get_current_profile(request, session):
|
||||
"""Get the current profile ID from session (or fallback)."""
|
||||
profile_list = profiles.list()
|
||||
current_id = session.get('current_profile')
|
||||
if current_id and current_id not in profile_list:
|
||||
current_id = None
|
||||
if not current_id and profile_list:
|
||||
current_id = profile_list[0]
|
||||
session['current_profile'] = str(current_id)
|
||||
session.save()
|
||||
if current_id:
|
||||
profile = profiles.read(current_id)
|
||||
return json.dumps({"id": current_id, "profile": profile}), 200, {'Content-Type': 'application/json'}
|
||||
return json.dumps({"error": "No profile available"}), 404
|
||||
|
||||
@controller.get('/<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
|
||||
@@ -1,83 +0,0 @@
|
||||
from microdot import Microdot
|
||||
from models.scene import Scene
|
||||
import json
|
||||
|
||||
controller = Microdot()
|
||||
scenes = Scene()
|
||||
|
||||
@controller.get('')
|
||||
async def list_scenes(request):
|
||||
"""List all scenes."""
|
||||
return json.dumps(scenes), 200, {'Content-Type': 'application/json'}
|
||||
|
||||
@controller.get('/<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
|
||||
|
||||
|
||||
@controller.post('/<id>/play')
|
||||
async def play_scene(request, id):
|
||||
"""Start every sequence in the scene (one per zone; later ones win a shared zone)."""
|
||||
from engine import get_engine
|
||||
from engine.core import EngineError
|
||||
|
||||
scene = scenes.read(id)
|
||||
if not scene:
|
||||
return json.dumps({"error": "Scene not found"}), 404, {'Content-Type': 'application/json'}
|
||||
started, errors = [], {}
|
||||
for sid in scene.get("sequences") or []:
|
||||
try:
|
||||
await get_engine().sequences.play(sid)
|
||||
started.append(str(sid))
|
||||
except EngineError as e:
|
||||
errors[str(sid)] = str(e)
|
||||
return json.dumps({"started": started, "errors": errors}), 200, {'Content-Type': 'application/json'}
|
||||
|
||||
|
||||
@controller.post('/<id>/stop')
|
||||
async def stop_scene(request, id):
|
||||
"""Stop every sequence in the scene."""
|
||||
from engine import get_engine
|
||||
|
||||
scene = scenes.read(id)
|
||||
if not scene:
|
||||
return json.dumps({"error": "Scene not found"}), 404, {'Content-Type': 'application/json'}
|
||||
stopped = []
|
||||
for sid in scene.get("sequences") or []:
|
||||
if await get_engine().sequences.stop(sid):
|
||||
stopped.append(str(sid))
|
||||
return json.dumps({"stopped": stopped}), 200, {'Content-Type': 'application/json'}
|
||||
@@ -1,78 +0,0 @@
|
||||
from microdot import Microdot
|
||||
from models.squence import Sequence
|
||||
from engine import get_engine
|
||||
from engine.core import EngineError
|
||||
import json
|
||||
|
||||
controller = Microdot()
|
||||
sequences = Sequence()
|
||||
|
||||
_JSON = {'Content-Type': 'application/json'}
|
||||
|
||||
|
||||
@controller.get('')
|
||||
async def list_sequences(request):
|
||||
"""List all sequences."""
|
||||
return json.dumps(sequences), 200, _JSON
|
||||
|
||||
|
||||
@controller.get('/status')
|
||||
async def sequences_status(request):
|
||||
"""Running state of every sequence started since boot."""
|
||||
return json.dumps(get_engine().sequences.status()), 200, _JSON
|
||||
|
||||
|
||||
@controller.get('/<id>')
|
||||
async def get_sequence(request, id):
|
||||
"""Get a specific sequence by ID."""
|
||||
sequence = sequences.read(id)
|
||||
if sequence:
|
||||
return json.dumps(sequence), 200, _JSON
|
||||
return json.dumps({"error": "Sequence not found"}), 404, _JSON
|
||||
|
||||
|
||||
@controller.post('')
|
||||
async def create_sequence(request):
|
||||
"""Create a sequence: {name, zone_id, loop, repeat_count, steps: [{preset_id, duration_s}]}."""
|
||||
try:
|
||||
sequence_id = sequences.create(request.json or {})
|
||||
return json.dumps(sequences.read(sequence_id)), 201, _JSON
|
||||
except ValueError as e:
|
||||
return json.dumps({"error": str(e)}), 400, _JSON
|
||||
|
||||
|
||||
@controller.put('/<id>')
|
||||
async def update_sequence(request, id):
|
||||
"""Update an existing sequence."""
|
||||
try:
|
||||
if sequences.update(id, request.json or {}):
|
||||
return json.dumps(sequences.read(id)), 200, _JSON
|
||||
return json.dumps({"error": "Sequence not found"}), 404, _JSON
|
||||
except ValueError as e:
|
||||
return json.dumps({"error": str(e)}), 400, _JSON
|
||||
|
||||
|
||||
@controller.delete('/<id>')
|
||||
async def delete_sequence(request, id):
|
||||
"""Delete a sequence (stops it first if running)."""
|
||||
await get_engine().sequences.stop(id)
|
||||
if sequences.delete(id):
|
||||
return json.dumps({"message": "Sequence deleted successfully"}), 200, _JSON
|
||||
return json.dumps({"error": "Sequence not found"}), 404, _JSON
|
||||
|
||||
|
||||
@controller.post('/<id>/play')
|
||||
async def play_sequence(request, id):
|
||||
"""Start the sequence on its zone (replaces any sequence already running there)."""
|
||||
try:
|
||||
state = await get_engine().sequences.play(id)
|
||||
return json.dumps(state), 200, _JSON
|
||||
except EngineError as e:
|
||||
return json.dumps({"error": str(e)}), e.status, _JSON
|
||||
|
||||
|
||||
@controller.post('/<id>/stop')
|
||||
async def stop_sequence(request, id):
|
||||
"""Stop the sequence; the zone keeps showing its current preset."""
|
||||
stopped = await get_engine().sequences.stop(id)
|
||||
return json.dumps({"stopped": stopped}), 200, _JSON
|
||||
@@ -1,110 +0,0 @@
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
from microdot import Microdot, send_file
|
||||
|
||||
from models import wifi_ws_clients
|
||||
from settings import Settings
|
||||
|
||||
controller = Microdot()
|
||||
settings = Settings()
|
||||
|
||||
@controller.get('')
|
||||
async def get_settings(request):
|
||||
"""Get all settings."""
|
||||
# Settings is already a dict subclass; avoid dict() wrapper which can
|
||||
# trigger MicroPython's "dict update sequence has wrong length" quirk.
|
||||
return json.dumps(settings), 200, {'Content-Type': 'application/json'}
|
||||
|
||||
@controller.get('/wifi/ap')
|
||||
async def get_ap_config(request):
|
||||
"""Get saved AP configuration (Pi: no in-device AP)."""
|
||||
config = {
|
||||
'saved_ssid': settings.get('wifi_ap_ssid'),
|
||||
'saved_password': settings.get('wifi_ap_password'),
|
||||
'saved_channel': settings.get('wifi_ap_channel'),
|
||||
'active': False,
|
||||
}
|
||||
return json.dumps(config), 200, {'Content-Type': 'application/json'}
|
||||
|
||||
@controller.post('/wifi/ap')
|
||||
async def configure_ap(request):
|
||||
"""Save AP configuration to settings (Pi: no in-device AP)."""
|
||||
try:
|
||||
data = request.json
|
||||
ssid = data.get('ssid')
|
||||
password = data.get('password', '')
|
||||
channel = data.get('channel')
|
||||
|
||||
if not ssid:
|
||||
return json.dumps({"error": "SSID is required"}), 400
|
||||
|
||||
# Validate channel (1-11 for 2.4GHz)
|
||||
if channel is not None:
|
||||
channel = int(channel)
|
||||
if channel < 1 or channel > 11:
|
||||
return json.dumps({"error": "Channel must be between 1 and 11"}), 400
|
||||
|
||||
settings['wifi_ap_ssid'] = ssid
|
||||
settings['wifi_ap_password'] = password
|
||||
if channel is not None:
|
||||
settings['wifi_ap_channel'] = channel
|
||||
settings.save()
|
||||
|
||||
return json.dumps({
|
||||
"message": "AP settings saved",
|
||||
"ssid": ssid,
|
||||
"channel": channel
|
||||
}), 200, {'Content-Type': 'application/json'}
|
||||
except Exception as e:
|
||||
return json.dumps({"error": str(e)}), 500
|
||||
|
||||
def _validate_wifi_channel(value):
|
||||
"""Return int 1–11 or raise ValueError."""
|
||||
ch = int(value)
|
||||
if ch < 1 or ch > 11:
|
||||
raise ValueError("wifi_channel must be between 1 and 11")
|
||||
return ch
|
||||
|
||||
|
||||
def _validate_global_brightness(value):
|
||||
"""Return int 0–255 or raise ValueError."""
|
||||
v = int(value)
|
||||
if v < 0 or v > 255:
|
||||
raise ValueError("global_brightness must be between 0 and 255")
|
||||
return v
|
||||
|
||||
|
||||
@controller.put('/settings')
|
||||
async def update_settings(request):
|
||||
"""Update general settings."""
|
||||
try:
|
||||
data = request.json
|
||||
global_brightness_changed = False
|
||||
for key, value in data.items():
|
||||
if key == 'wifi_channel' and value is not None:
|
||||
settings[key] = _validate_wifi_channel(value)
|
||||
elif key == 'global_brightness' and value is not None:
|
||||
settings[key] = _validate_global_brightness(value)
|
||||
global_brightness_changed = True
|
||||
else:
|
||||
settings[key] = value
|
||||
settings.save()
|
||||
if global_brightness_changed:
|
||||
try:
|
||||
asyncio.get_running_loop().create_task(
|
||||
wifi_ws_clients.broadcast_global_brightness_to_tcp_drivers()
|
||||
)
|
||||
except RuntimeError:
|
||||
pass
|
||||
return json.dumps({"message": "Settings updated successfully"}), 200, {'Content-Type': 'application/json'}
|
||||
except ValueError as e:
|
||||
return json.dumps({"error": str(e)}), 400
|
||||
except Exception as e:
|
||||
return json.dumps({"error": str(e)}), 500
|
||||
|
||||
@controller.get('/page')
|
||||
async def settings_page(request):
|
||||
"""Serve the settings page."""
|
||||
return send_file('templates/settings.html')
|
||||
|
||||
@@ -1,400 +0,0 @@
|
||||
from microdot import Microdot, send_file
|
||||
from microdot.session import with_session
|
||||
from models.zone import Zone
|
||||
from models.profile import Profile
|
||||
import json
|
||||
|
||||
controller = Microdot()
|
||||
zones = Zone()
|
||||
profiles = Profile()
|
||||
|
||||
|
||||
def get_current_profile_id(session=None):
|
||||
"""Get the current active profile ID from session or fallback to first."""
|
||||
profile_list = profiles.list()
|
||||
session_profile = None
|
||||
if session is not None:
|
||||
session_profile = session.get("current_profile")
|
||||
if session_profile and session_profile in profile_list:
|
||||
return session_profile
|
||||
if profile_list:
|
||||
return profile_list[0]
|
||||
return None
|
||||
|
||||
|
||||
def _profile_zone_id_list(profile):
|
||||
"""Ordered zone ids for a profile (``zones``, legacy ``tabs``, or ``zone_order``)."""
|
||||
if not profile or not isinstance(profile, dict):
|
||||
return []
|
||||
z = profile.get("zones")
|
||||
if isinstance(z, list) and z:
|
||||
return list(z)
|
||||
t = profile.get("zones")
|
||||
if isinstance(t, list) and t:
|
||||
return list(t)
|
||||
o = profile.get("zone_order")
|
||||
if isinstance(o, list) and o:
|
||||
return list(o)
|
||||
return []
|
||||
|
||||
|
||||
def get_profile_zone_order(profile_id):
|
||||
if not profile_id:
|
||||
return []
|
||||
profile = profiles.read(profile_id)
|
||||
return _profile_zone_id_list(profile)
|
||||
|
||||
|
||||
def _set_profile_zone_order(profile, ids):
|
||||
profile["zones"] = list(ids)
|
||||
profile.pop("tabs", None)
|
||||
profile.pop("zone_order", None)
|
||||
|
||||
|
||||
def get_current_zone_id(request, session=None):
|
||||
"""Cookie ``current_zone``, legacy ``current_zone``, then first zone in profile."""
|
||||
z = request.cookies.get("current_zone") or request.cookies.get("current_zone")
|
||||
if z:
|
||||
return z
|
||||
profile_id = get_current_profile_id(session)
|
||||
if profile_id:
|
||||
profile = profiles.read(profile_id)
|
||||
order = _profile_zone_id_list(profile)
|
||||
if order:
|
||||
return order[0]
|
||||
return None
|
||||
|
||||
|
||||
def _render_zones_list_fragment(request, session):
|
||||
"""Render zone strip HTML for HTMX / JS."""
|
||||
profile_id = get_current_profile_id(session)
|
||||
if not profile_id:
|
||||
return (
|
||||
'<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("/engine/status")
|
||||
async def engine_status(request):
|
||||
"""Pi-side engine state: rendering zones and running sequences."""
|
||||
from engine import get_engine
|
||||
|
||||
return json.dumps(get_engine().status()), 200, {"Content-Type": "application/json"}
|
||||
|
||||
|
||||
@controller.post("/<id>/play")
|
||||
async def play_zone(request, id):
|
||||
"""Run a preset on every target in the zone.
|
||||
|
||||
Body: {"preset_id": "16", "drivers": true}. Pixel outputs (DDP/Art-Net/sACN/DMX)
|
||||
are rendered on the Pi; ESP32 led-drivers get the preset + select as before
|
||||
unless ``drivers`` is false. Stops any sequence running on the zone.
|
||||
"""
|
||||
from engine import get_engine
|
||||
from engine.core import EngineError
|
||||
|
||||
data = request.json or {}
|
||||
preset_id = data.get("preset_id")
|
||||
if preset_id in (None, ""):
|
||||
return json.dumps({"error": "preset_id is required"}), 400, {"Content-Type": "application/json"}
|
||||
try:
|
||||
status = await get_engine().play(id, str(preset_id), drivers=data.get("drivers", True) is not False)
|
||||
except EngineError as e:
|
||||
return json.dumps({"error": str(e)}), e.status, {"Content-Type": "application/json"}
|
||||
return json.dumps(status), 200, {"Content-Type": "application/json"}
|
||||
|
||||
|
||||
@controller.post("/<id>/stop")
|
||||
async def stop_zone(request, id):
|
||||
"""Stop the zone's sequence and Pi rendering (pixel outputs go black)."""
|
||||
from engine import get_engine
|
||||
|
||||
stopped = await get_engine().stop(id)
|
||||
return json.dumps({"stopped": stopped}), 200, {"Content-Type": "application/json"}
|
||||
|
||||
|
||||
@controller.get("/<id>")
|
||||
async def get_zone(request, id):
|
||||
z = zones.read(id)
|
||||
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
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
"""Pi-side animation engine.
|
||||
|
||||
* ``engine.outputs`` — protocol drivers (DDP, Art-Net, sACN, USB-DMX, ESP32 presets)
|
||||
* ``engine.renderer`` — runs unchanged led-driver patterns under CPython
|
||||
* ``engine.player`` — per-zone frame streaming
|
||||
* ``engine.sequence_runner`` — timed preset chains
|
||||
|
||||
``get_engine()`` returns the process-wide Engine (created on first use).
|
||||
"""
|
||||
|
||||
_engine = None
|
||||
|
||||
|
||||
def get_engine():
|
||||
global _engine
|
||||
if _engine is None:
|
||||
from engine.core import Engine
|
||||
_engine = Engine()
|
||||
return _engine
|
||||
|
||||
|
||||
def set_engine(engine):
|
||||
global _engine
|
||||
_engine = engine
|
||||
return engine
|
||||
@@ -1,148 +0,0 @@
|
||||
"""Engine CLI (run from ``src/``) — portal's ``run_cli`` equivalent.
|
||||
|
||||
python -m engine.cli --output ddp://10.0.0.5?pixels=300 --test
|
||||
python -m engine.cli --output artnet://10.0.0.6?universe=0&pixels=170 --color ff0000
|
||||
python -m engine.cli --output sacn://?universe=1&pixels=170 --preset 16
|
||||
python -m engine.cli --pattern rainbow --n1 2 --leds 60 # stdout preview
|
||||
python -m engine.cli --output dmx_serial:///dev/ttyUSB0?pixels=10 --pattern pulse \\
|
||||
--colors ff0000,0000ff --n1 300 --n2 200 --n3 300
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from engine.outputs import parse_output_url
|
||||
from engine.outputs.base import FrameOutput
|
||||
from engine.player import ZonePlayer
|
||||
from engine.zone_targets import ZoneTargets
|
||||
|
||||
|
||||
class StdoutOutput(FrameOutput):
|
||||
"""Truecolour terminal strip, one line redrawn per frame."""
|
||||
|
||||
protocol = "stdout"
|
||||
|
||||
async def _send_prepared(self, payload):
|
||||
cells = []
|
||||
for i in range(0, len(payload), 3):
|
||||
r, g, b = payload[i], payload[i + 1], payload[i + 2]
|
||||
cells.append(f"\x1b[48;2;{r};{g};{b}m ")
|
||||
sys.stdout.write("\r" + "".join(cells) + "\x1b[0m")
|
||||
sys.stdout.flush()
|
||||
self.stats.packets += 1
|
||||
|
||||
|
||||
def _output_factory(cfg):
|
||||
if cfg.get("protocol") == "stdout":
|
||||
return StdoutOutput(cfg)
|
||||
from engine.outputs import open_output
|
||||
return open_output(cfg)
|
||||
|
||||
|
||||
def build_parser():
|
||||
p = argparse.ArgumentParser(prog="python -m engine.cli", description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
p.add_argument("--output", action="append", default=[],
|
||||
help="ddp://, artnet://, sacn://, dmx_serial:// URL (repeatable); default stdout")
|
||||
p.add_argument("--leds", type=int, default=None, help="pixel count (default: from output URL, else 60)")
|
||||
p.add_argument("--fps", type=int, default=None, help="output fps cap")
|
||||
p.add_argument("--global-brightness", type=int, default=255, help="0-255, applied at send")
|
||||
p.add_argument("--duration", type=float, default=None, help="seconds to run (default: until Ctrl-C)")
|
||||
what = p.add_mutually_exclusive_group()
|
||||
what.add_argument("--test", action="store_true", help="red, green, blue, white, then black")
|
||||
what.add_argument("--color", help="solid colour hex, e.g. ff0000")
|
||||
what.add_argument("--preset", help="preset id from db/preset.json")
|
||||
what.add_argument("--pattern", help="driver pattern name, e.g. rainbow")
|
||||
p.add_argument("--colors", default="ffffff", help="comma-separated hex colours for --pattern")
|
||||
p.add_argument("--delay", type=int, default=100)
|
||||
p.add_argument("--brightness", type=int, default=255, help="preset brightness 0-255")
|
||||
p.add_argument("--no-auto", action="store_true", help="manual (beat) mode: auto=false")
|
||||
for i in range(1, 7):
|
||||
p.add_argument(f"--n{i}", type=int, default=0)
|
||||
return p
|
||||
|
||||
|
||||
def _frame_cfgs(args):
|
||||
urls = args.output or ["stdout://"]
|
||||
cfgs = []
|
||||
for url in urls:
|
||||
cfg = {"protocol": "stdout", "name": "stdout"} if url.startswith("stdout") else parse_output_url(url)
|
||||
if args.leds is not None:
|
||||
cfg["pixel_count"] = args.leds
|
||||
cfg.setdefault("pixel_count", 60)
|
||||
if args.fps is not None:
|
||||
cfg["fps"] = args.fps
|
||||
elif cfg["protocol"] == "stdout":
|
||||
cfg.setdefault("fps", 20)
|
||||
cfgs.append(cfg)
|
||||
return cfgs
|
||||
|
||||
|
||||
def _payload_from_args(args):
|
||||
if args.preset:
|
||||
from engine.presets import preset_payload
|
||||
payload = preset_payload(args.preset)
|
||||
if payload is None:
|
||||
raise SystemExit(f"preset {args.preset!r} not found")
|
||||
return args.preset, payload
|
||||
if args.color:
|
||||
return "cli", {"p": "on", "c": ["#" + args.color.lstrip("#")], "b": args.brightness}
|
||||
payload = {
|
||||
"p": args.pattern or "rainbow",
|
||||
"c": ["#" + c.strip().lstrip("#") for c in args.colors.split(",") if c.strip()],
|
||||
"d": args.delay,
|
||||
"b": args.brightness,
|
||||
"a": not args.no_auto,
|
||||
}
|
||||
for i in range(1, 7):
|
||||
payload[f"n{i}"] = getattr(args, f"n{i}")
|
||||
return "cli", payload
|
||||
|
||||
|
||||
async def _run_test(player, step_s=1.0):
|
||||
for color in ((255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255)):
|
||||
await player.apply("cli", {"p": "on", "c": [color], "b": 255})
|
||||
await asyncio.sleep(step_s)
|
||||
|
||||
|
||||
async def run(args):
|
||||
from engine.pattern_loader import get_library
|
||||
|
||||
library = get_library()
|
||||
if library.errors:
|
||||
print(f"pattern load errors: {library.errors}", file=sys.stderr)
|
||||
targets = ZoneTargets("cli", _frame_cfgs(args), [])
|
||||
player = ZonePlayer(targets, library, lambda: args.global_brightness, output_factory=_output_factory)
|
||||
await player.start()
|
||||
try:
|
||||
if args.test:
|
||||
await _run_test(player)
|
||||
return
|
||||
preset_id, payload = _payload_from_args(args)
|
||||
if payload.get("p") not in library.ids():
|
||||
raise SystemExit(f"unknown pattern {payload.get('p')!r}; available: {', '.join(library.ids())}")
|
||||
await player.apply(preset_id, payload)
|
||||
if args.duration:
|
||||
await asyncio.sleep(args.duration)
|
||||
else:
|
||||
while True:
|
||||
await asyncio.sleep(3600)
|
||||
finally:
|
||||
await player.stop()
|
||||
print()
|
||||
for st in player.status()["outputs"]:
|
||||
print(f"{st['name']}: frames={st['frames']} packets={st['packets']} errors={st['errors']}"
|
||||
+ (f" last_error={st['last_error']}" if st["last_error"] else ""))
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
args = build_parser().parse_args(argv)
|
||||
try:
|
||||
asyncio.run(run(args))
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,89 +0,0 @@
|
||||
"""Engine: one ZonePlayer per zone + the preset sequencer on top."""
|
||||
|
||||
import asyncio
|
||||
|
||||
from engine.pattern_loader import get_library
|
||||
from engine.player import ZonePlayer
|
||||
from engine.presets import preset_payload
|
||||
from engine.sequence_runner import SequenceRunner
|
||||
from engine.zone_targets import resolve_zone
|
||||
|
||||
|
||||
class EngineError(Exception):
|
||||
def __init__(self, message, status=400):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
|
||||
|
||||
class Engine:
|
||||
def __init__(self, library=None, brightness_getter=None, zone_resolver=None,
|
||||
payload_resolver=None, player_factory=None, sequences_model=None):
|
||||
self._library = library
|
||||
self.brightness_getter = brightness_getter or (lambda: 255)
|
||||
self._resolve_zone = zone_resolver or resolve_zone
|
||||
self._payload = payload_resolver or preset_payload
|
||||
self._player_factory = player_factory or ZonePlayer
|
||||
self.players = {}
|
||||
self._lock = None
|
||||
self.sequences = SequenceRunner(self, sequences_model=sequences_model)
|
||||
|
||||
@property
|
||||
def library(self):
|
||||
if self._library is None:
|
||||
self._library = get_library()
|
||||
return self._library
|
||||
|
||||
def _get_lock(self):
|
||||
if self._lock is None:
|
||||
self._lock = asyncio.Lock()
|
||||
return self._lock
|
||||
|
||||
async def play(self, zone_id, preset_id, source="manual", drivers=True):
|
||||
"""Run ``preset_id`` on every target of ``zone_id`` (pixel outputs + ESP32s).
|
||||
|
||||
``source="manual"`` (UI pick) stops any sequence running on the zone.
|
||||
``drivers=False`` leaves the ESP32s alone (the UI already sent to them).
|
||||
"""
|
||||
zone_id = str(zone_id)
|
||||
if source == "manual":
|
||||
await self.sequences.stop_zone(zone_id)
|
||||
targets = self._resolve_zone(zone_id)
|
||||
if targets is None:
|
||||
raise EngineError("Zone not found", 404)
|
||||
payload = self._payload(str(preset_id))
|
||||
if payload is None:
|
||||
raise EngineError("Preset not found", 404)
|
||||
async with self._get_lock():
|
||||
player = self.players.get(zone_id)
|
||||
if player is not None and player.targets.signature() != targets.signature():
|
||||
await player.stop()
|
||||
player = None
|
||||
if player is None:
|
||||
player = self._player_factory(targets, self.library, self.brightness_getter)
|
||||
await player.start()
|
||||
self.players[zone_id] = player
|
||||
await player.apply(str(preset_id), payload, drivers=drivers)
|
||||
return player.status()
|
||||
|
||||
async def stop(self, zone_id):
|
||||
"""Stop the zone's sequence and Pi rendering (pixel outputs go black)."""
|
||||
zone_id = str(zone_id)
|
||||
await self.sequences.stop_zone(zone_id)
|
||||
async with self._get_lock():
|
||||
player = self.players.pop(zone_id, None)
|
||||
if player is not None:
|
||||
await player.stop()
|
||||
return player is not None
|
||||
|
||||
async def stop_all(self, persist=False):
|
||||
await self.sequences.stop_all(persist=persist)
|
||||
async with self._get_lock():
|
||||
players, self.players = list(self.players.values()), {}
|
||||
for player in players:
|
||||
await player.stop()
|
||||
|
||||
def status(self):
|
||||
return {
|
||||
"zones": {zid: p.status() for zid, p in self.players.items()},
|
||||
"sequences": self.sequences.status(),
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
"""Stand-in for the led-driver ``Presets`` object that patterns draw into.
|
||||
|
||||
Same surface the patterns use on the ESP32 (``n[i]``, ``n.write()``,
|
||||
``n.fill``, ``num_leds``, ``step``, ``fill``, ``off``, ``on``,
|
||||
``apply_brightness``), but ``write()`` hands the frame to a callback instead
|
||||
of a NeoPixel strip.
|
||||
"""
|
||||
|
||||
|
||||
class PixelBuffer:
|
||||
"""NeoPixel-compatible buffer of RGB tuples."""
|
||||
|
||||
def __init__(self, num_leds, on_write=None):
|
||||
self.n = int(num_leds)
|
||||
self._px = [(0, 0, 0)] * self.n
|
||||
self.on_write = on_write
|
||||
|
||||
def __len__(self):
|
||||
return self.n
|
||||
|
||||
def __setitem__(self, i, color):
|
||||
self._px[i] = (int(color[0]) & 0xFF, int(color[1]) & 0xFF, int(color[2]) & 0xFF)
|
||||
|
||||
def __getitem__(self, i):
|
||||
return self._px[i]
|
||||
|
||||
def fill(self, color):
|
||||
c = (int(color[0]) & 0xFF, int(color[1]) & 0xFF, int(color[2]) & 0xFF)
|
||||
self._px = [c] * self.n
|
||||
|
||||
def to_bytes(self):
|
||||
out = bytearray(self.n * 3)
|
||||
for i, (r, g, b) in enumerate(self._px):
|
||||
j = i * 3
|
||||
out[j] = r
|
||||
out[j + 1] = g
|
||||
out[j + 2] = b
|
||||
return bytes(out)
|
||||
|
||||
def write(self):
|
||||
if self.on_write is not None:
|
||||
self.on_write(self.to_bytes())
|
||||
|
||||
|
||||
class FrameDriver:
|
||||
def __init__(self, num_leds, on_write=None):
|
||||
self.num_leds = int(num_leds)
|
||||
self.n = PixelBuffer(self.num_leds, on_write)
|
||||
self.step = 0
|
||||
# Global brightness is applied per output at send time, not here.
|
||||
self.b = 255
|
||||
|
||||
def apply_brightness(self, color, brightness_override=None):
|
||||
local = brightness_override if brightness_override is not None else 255
|
||||
effective_brightness = int(local * self.b / 255)
|
||||
return tuple(int(c * effective_brightness / 255) for c in color)
|
||||
|
||||
def fill(self, color=None):
|
||||
self.n.fill(color if color is not None else (0, 0, 0))
|
||||
self.n.write()
|
||||
|
||||
def off(self, preset=None):
|
||||
self.fill((0, 0, 0))
|
||||
|
||||
def on(self, preset):
|
||||
colors = preset.c
|
||||
color = colors[0] if colors else (255, 255, 255)
|
||||
self.fill(self.apply_brightness(color, preset.b))
|
||||
@@ -1,86 +0,0 @@
|
||||
"""MicroPython compatibility for running led-driver patterns under CPython.
|
||||
|
||||
Installs a ``utime`` module whose clock is chosen per thread:
|
||||
|
||||
* ``RealClock`` — monotonic wall clock, ``sleep_ms`` really sleeps (render threads).
|
||||
* ``VirtualClock`` — manual time; ``sleep_ms`` just advances it (tests, offline render).
|
||||
|
||||
Patterns only use ``ticks_ms``/``ticks_diff``/``ticks_add``/``sleep_ms``; tick
|
||||
values never wrap here, so the diff/add helpers are plain arithmetic.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import types
|
||||
|
||||
|
||||
class RealClock:
|
||||
def __init__(self):
|
||||
self._t0 = time.monotonic()
|
||||
|
||||
def ticks_ms(self):
|
||||
return int((time.monotonic() - self._t0) * 1000)
|
||||
|
||||
def ticks_us(self):
|
||||
return int((time.monotonic() - self._t0) * 1000000)
|
||||
|
||||
def sleep_ms(self, ms):
|
||||
if ms > 0:
|
||||
time.sleep(ms / 1000.0)
|
||||
|
||||
|
||||
class VirtualClock:
|
||||
def __init__(self, start_ms=0):
|
||||
self.now_us = int(start_ms) * 1000
|
||||
|
||||
def ticks_ms(self):
|
||||
return self.now_us // 1000
|
||||
|
||||
def ticks_us(self):
|
||||
return self.now_us
|
||||
|
||||
def advance_ms(self, ms):
|
||||
self.now_us += int(ms * 1000)
|
||||
|
||||
def sleep_ms(self, ms):
|
||||
if ms > 0:
|
||||
self.advance_ms(ms)
|
||||
|
||||
|
||||
_local = threading.local()
|
||||
_default_clock = RealClock()
|
||||
|
||||
|
||||
def current_clock():
|
||||
return getattr(_local, "clock", None) or _default_clock
|
||||
|
||||
|
||||
def set_thread_clock(clock):
|
||||
"""Use ``clock`` for ``utime`` calls made on the current thread (None = real)."""
|
||||
_local.clock = clock
|
||||
|
||||
|
||||
def _build_utime():
|
||||
mod = types.ModuleType("utime")
|
||||
mod.ticks_ms = lambda: current_clock().ticks_ms()
|
||||
mod.ticks_us = lambda: current_clock().ticks_us()
|
||||
mod.ticks_cpu = mod.ticks_us
|
||||
mod.ticks_diff = lambda a, b: a - b
|
||||
mod.ticks_add = lambda a, b: a + b
|
||||
mod.sleep_ms = lambda ms: current_clock().sleep_ms(ms)
|
||||
mod.sleep_us = lambda us: current_clock().sleep_ms(us / 1000.0)
|
||||
mod.sleep = lambda s: current_clock().sleep_ms(s * 1000.0)
|
||||
mod.time = time.time
|
||||
mod.__led_controller_shim__ = True
|
||||
return mod
|
||||
|
||||
|
||||
def install():
|
||||
"""Register the shim as ``utime`` (idempotent; never replaces a real utime)."""
|
||||
existing = sys.modules.get("utime")
|
||||
if existing is not None:
|
||||
return existing
|
||||
mod = _build_utime()
|
||||
sys.modules["utime"] = mod
|
||||
return mod
|
||||
@@ -1,72 +0,0 @@
|
||||
"""Engine output drivers and the factory that builds them from config."""
|
||||
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
from engine.outputs.artnet import ArtNetOutput
|
||||
from engine.outputs.base import FrameOutput, PresetOutput
|
||||
from engine.outputs.ddp import DdpOutput
|
||||
from engine.outputs.dmx_serial import DmxSerialOutput
|
||||
from engine.outputs.sacn import SacnOutput
|
||||
|
||||
FRAME_PROTOCOLS = {
|
||||
"ddp": DdpOutput,
|
||||
"artnet": ArtNetOutput,
|
||||
"sacn": SacnOutput,
|
||||
"dmx_serial": DmxSerialOutput,
|
||||
}
|
||||
|
||||
_URL_ALIASES = {"e131": "sacn", "dmx": "dmx_serial", "art-net": "artnet"}
|
||||
_QUERY_KEYS = {
|
||||
"pixels": "pixel_count",
|
||||
"order": "color_order",
|
||||
"offset": "pixel_offset",
|
||||
"mode": "dmx_mode",
|
||||
}
|
||||
|
||||
|
||||
def open_output(cfg):
|
||||
"""Build a FrameOutput from an output record (``protocol`` selects the driver)."""
|
||||
protocol = str((cfg or {}).get("protocol") or "").lower()
|
||||
protocol = _URL_ALIASES.get(protocol, protocol)
|
||||
cls = FRAME_PROTOCOLS.get(protocol)
|
||||
if cls is None:
|
||||
raise ValueError(f"unknown output protocol: {protocol!r}")
|
||||
return cls(cfg)
|
||||
|
||||
|
||||
def parse_output_url(url):
|
||||
"""``ddp://10.0.0.5:4048?pixels=300&order=grb`` → output config dict.
|
||||
|
||||
``dmx_serial:///dev/ttyUSB0?mode=open_dmx&channel=1`` for serial DMX.
|
||||
"""
|
||||
# urlparse rejects "_" in schemes (dmx_serial://), so split the scheme off first.
|
||||
scheme, sep, rest = str(url).partition("://")
|
||||
if not sep:
|
||||
raise ValueError(f"output URL needs a scheme, e.g. ddp://host: {url!r}")
|
||||
scheme = scheme.strip().lower()
|
||||
protocol = _URL_ALIASES.get(scheme, scheme)
|
||||
parsed = urlparse("udp://" + rest)
|
||||
cfg = {"protocol": protocol, "name": url}
|
||||
if protocol == "dmx_serial":
|
||||
cfg["serial_port"] = parsed.path or parsed.netloc
|
||||
else:
|
||||
if parsed.hostname:
|
||||
cfg["host"] = parsed.hostname
|
||||
if parsed.port:
|
||||
cfg["port"] = parsed.port
|
||||
for key, values in parse_qs(parsed.query).items():
|
||||
cfg[_QUERY_KEYS.get(key, key)] = values[-1]
|
||||
return cfg
|
||||
|
||||
|
||||
__all__ = [
|
||||
"FrameOutput",
|
||||
"PresetOutput",
|
||||
"DdpOutput",
|
||||
"ArtNetOutput",
|
||||
"SacnOutput",
|
||||
"DmxSerialOutput",
|
||||
"FRAME_PROTOCOLS",
|
||||
"open_output",
|
||||
"parse_output_url",
|
||||
]
|
||||
@@ -1,78 +0,0 @@
|
||||
"""Art-Net (ArtDMX) output — UDP 6454.
|
||||
|
||||
ArtDMX packet:
|
||||
0 "Art-Net\\0"
|
||||
8 OpCode 0x5000 (little-endian)
|
||||
10 ProtVer 14 (big-endian)
|
||||
12 Sequence 1..255 (0 disables re-ordering)
|
||||
13 Physical 0
|
||||
14 Port-Address: SubUni (low byte), Net (high 7 bits)
|
||||
16 Length (big-endian, even, 2..512)
|
||||
18 DMX data
|
||||
|
||||
170 RGB pixels per universe; consecutive universes from ``universe``.
|
||||
Optional ArtSync (OpCode 0x5200) after each frame when ``sync`` is set.
|
||||
"""
|
||||
|
||||
import struct
|
||||
|
||||
from engine.outputs.base import UdpFrameOutput, _bool, _int, split_universes
|
||||
|
||||
ARTNET_PORT = 6454
|
||||
ARTNET_ID = b"Art-Net\x00"
|
||||
OP_DMX = 0x5000
|
||||
OP_SYNC = 0x5200
|
||||
PROT_VER = 14
|
||||
|
||||
|
||||
def build_artdmx(universe, data, sequence=0, physical=0):
|
||||
data = bytes(data[:512])
|
||||
if len(data) % 2:
|
||||
data += b"\x00"
|
||||
if len(data) < 2:
|
||||
data = data + bytes(2 - len(data))
|
||||
universe &= 0x7FFF
|
||||
return (
|
||||
ARTNET_ID
|
||||
+ struct.pack("<H", OP_DMX)
|
||||
+ struct.pack(">H", PROT_VER)
|
||||
+ bytes((sequence & 0xFF, physical & 0xFF, universe & 0xFF, (universe >> 8) & 0x7F))
|
||||
+ struct.pack(">H", len(data))
|
||||
+ data
|
||||
)
|
||||
|
||||
|
||||
def build_artsync():
|
||||
return ARTNET_ID + struct.pack("<H", OP_SYNC) + struct.pack(">H", PROT_VER) + b"\x00\x00"
|
||||
|
||||
|
||||
class ArtNetOutput(UdpFrameOutput):
|
||||
protocol = "artnet"
|
||||
default_port = ARTNET_PORT
|
||||
|
||||
def __init__(self, cfg):
|
||||
super().__init__(cfg)
|
||||
if not self.host:
|
||||
self.host = "255.255.255.255"
|
||||
self.broadcast = True
|
||||
self.universe = _int(self.cfg.get("universe"), 0, 0, 0x7FFF)
|
||||
self.sync = _bool(self.cfg.get("sync"), False)
|
||||
self._sequence = 0
|
||||
|
||||
def next_sequence(self):
|
||||
self._sequence = (self._sequence % 255) + 1
|
||||
return self._sequence
|
||||
|
||||
def packets_for(self, payload):
|
||||
seq = self.next_sequence()
|
||||
packets = [
|
||||
build_artdmx(self.universe + i, chunk, seq)
|
||||
for i, chunk in enumerate(split_universes(payload))
|
||||
]
|
||||
if self.sync:
|
||||
packets.append(build_artsync())
|
||||
return packets
|
||||
|
||||
async def _send_prepared(self, payload):
|
||||
for packet in self.packets_for(payload):
|
||||
self.sendto(packet)
|
||||
@@ -1,254 +0,0 @@
|
||||
"""Common output-driver interface and helpers.
|
||||
|
||||
Two kinds of output:
|
||||
|
||||
* ``FrameOutput`` — the Pi renders pixels and streams raw RGB frames
|
||||
(DDP, Art-Net, sACN, USB-DMX).
|
||||
* ``PresetOutput`` — the device renders itself; the engine only tells it which
|
||||
preset to run (our ESP32 led-drivers over Wi-Fi / ESP-NOW).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import functools
|
||||
import socket
|
||||
|
||||
COLOR_ORDERS = {
|
||||
"rgb": (0, 1, 2),
|
||||
"rbg": (0, 2, 1),
|
||||
"grb": (1, 0, 2),
|
||||
"gbr": (1, 2, 0),
|
||||
"brg": (2, 0, 1),
|
||||
"bgr": (2, 1, 0),
|
||||
}
|
||||
|
||||
DEFAULT_FPS = 40
|
||||
|
||||
|
||||
def _int(value, default, lo=None, hi=None):
|
||||
try:
|
||||
v = int(value)
|
||||
except (TypeError, ValueError):
|
||||
v = default
|
||||
if lo is not None:
|
||||
v = max(lo, v)
|
||||
if hi is not None:
|
||||
v = min(hi, v)
|
||||
return v
|
||||
|
||||
|
||||
def _bool(value, default=False):
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if isinstance(value, (int, float)):
|
||||
return bool(value)
|
||||
if isinstance(value, str):
|
||||
s = value.strip().lower()
|
||||
if s in ("1", "true", "yes", "on"):
|
||||
return True
|
||||
if s in ("0", "false", "no", "off"):
|
||||
return False
|
||||
return default
|
||||
|
||||
|
||||
class OutputStats:
|
||||
def __init__(self):
|
||||
self.frames = 0
|
||||
self.packets = 0
|
||||
self.bytes = 0
|
||||
self.errors = 0
|
||||
self.last_error = None
|
||||
|
||||
def error(self, exc):
|
||||
self.errors += 1
|
||||
self.last_error = repr(exc)
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
"frames": self.frames,
|
||||
"packets": self.packets,
|
||||
"bytes": self.bytes,
|
||||
"errors": self.errors,
|
||||
"last_error": self.last_error,
|
||||
}
|
||||
|
||||
|
||||
class FrameOutput:
|
||||
"""Base class for pixel-streaming outputs."""
|
||||
|
||||
kind = "frame"
|
||||
protocol = ""
|
||||
# Resend the last frame this often when the pattern is static, so receivers
|
||||
# don't time out (sACN drops a source after 2.5 s; DMX expects a steady stream).
|
||||
keepalive_s = 1.0
|
||||
|
||||
def __init__(self, cfg):
|
||||
cfg = dict(cfg or {})
|
||||
self.cfg = cfg
|
||||
self.name = str(cfg.get("name") or cfg.get("id") or self.protocol)
|
||||
self.pixel_count = _int(cfg.get("pixel_count"), 60, 1, 100000)
|
||||
self.pixel_offset = _int(cfg.get("pixel_offset"), 0, 0)
|
||||
order = str(cfg.get("color_order") or "rgb").lower()
|
||||
self.color_order = order if order in COLOR_ORDERS else "rgb"
|
||||
self.reverse = _bool(cfg.get("reverse"), False)
|
||||
self.brightness = _int(cfg.get("brightness"), 255, 0, 255)
|
||||
self.fps = _int(cfg.get("fps"), DEFAULT_FPS, 1, 120)
|
||||
self.stats = OutputStats()
|
||||
self._index_map = self._build_index_map()
|
||||
|
||||
# -- frame preparation -------------------------------------------------
|
||||
|
||||
def _build_index_map(self):
|
||||
"""Byte index map: out[i] = src[map[i]] (colour order + reverse)."""
|
||||
order = COLOR_ORDERS[self.color_order]
|
||||
n = self.pixel_count
|
||||
idx = []
|
||||
for p in range(n):
|
||||
src_px = (n - 1 - p) if self.reverse else p
|
||||
base = src_px * 3
|
||||
idx.extend((base + order[0], base + order[1], base + order[2]))
|
||||
return idx
|
||||
|
||||
@staticmethod
|
||||
@functools.lru_cache(maxsize=64)
|
||||
def brightness_table(level):
|
||||
level = max(0, min(255, int(level)))
|
||||
return bytes((v * level + 127) // 255 for v in range(256))
|
||||
|
||||
def prepare(self, rgb, global_brightness=255):
|
||||
"""Pad/truncate, apply brightness, colour order and reverse."""
|
||||
need = self.pixel_count * 3
|
||||
data = bytes(rgb[:need])
|
||||
if len(data) < need:
|
||||
data = data + bytes(need - len(data))
|
||||
level = (self.brightness * max(0, min(255, int(global_brightness))) + 127) // 255
|
||||
if level < 255:
|
||||
data = data.translate(self.brightness_table(level))
|
||||
if self.color_order == "rgb" and not self.reverse:
|
||||
return data
|
||||
m = self._index_map
|
||||
return bytes(data[i] for i in m)
|
||||
|
||||
# -- lifecycle -----------------------------------------------------------
|
||||
|
||||
async def open(self):
|
||||
pass
|
||||
|
||||
async def send(self, rgb, global_brightness=255):
|
||||
"""Send one frame of logical RGB (pixel_count*3 bytes)."""
|
||||
try:
|
||||
payload = self.prepare(rgb, global_brightness)
|
||||
await self._send_prepared(payload)
|
||||
self.stats.frames += 1
|
||||
except Exception as e:
|
||||
self.stats.error(e)
|
||||
|
||||
async def _send_prepared(self, payload):
|
||||
raise NotImplementedError
|
||||
|
||||
async def blackout(self):
|
||||
await self.send(bytes(self.pixel_count * 3))
|
||||
|
||||
async def close(self):
|
||||
try:
|
||||
await self.blackout()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def status(self):
|
||||
return {
|
||||
"name": self.name,
|
||||
"protocol": self.protocol,
|
||||
"kind": self.kind,
|
||||
"pixel_count": self.pixel_count,
|
||||
**self.stats.to_dict(),
|
||||
}
|
||||
|
||||
|
||||
class _DatagramSink(asyncio.DatagramProtocol):
|
||||
def __init__(self, owner):
|
||||
self.owner = owner
|
||||
|
||||
def error_received(self, exc):
|
||||
self.owner.stats.error(exc)
|
||||
|
||||
|
||||
class UdpFrameOutput(FrameOutput):
|
||||
"""FrameOutput that sends UDP datagrams to one host:port."""
|
||||
|
||||
default_port = 0
|
||||
|
||||
def __init__(self, cfg):
|
||||
super().__init__(cfg)
|
||||
self.host = str(self.cfg.get("host") or "").strip()
|
||||
self.port = _int(self.cfg.get("port"), self.default_port, 1, 65535)
|
||||
self.broadcast = _bool(self.cfg.get("broadcast"), False)
|
||||
self._transport = None
|
||||
|
||||
def destination(self):
|
||||
return (self.host, self.port)
|
||||
|
||||
def _make_socket(self):
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
sock.setblocking(False)
|
||||
if self.broadcast or self.host.endswith(".255"):
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||
return sock
|
||||
|
||||
async def open(self):
|
||||
if self._transport is not None:
|
||||
return
|
||||
loop = asyncio.get_running_loop()
|
||||
self._transport, _ = await loop.create_datagram_endpoint(
|
||||
lambda: _DatagramSink(self), sock=self._make_socket()
|
||||
)
|
||||
|
||||
def sendto(self, packet, addr=None):
|
||||
if self._transport is None:
|
||||
raise RuntimeError("output not open")
|
||||
self._transport.sendto(packet, addr or self.destination())
|
||||
self.stats.packets += 1
|
||||
self.stats.bytes += len(packet)
|
||||
|
||||
async def send(self, rgb, global_brightness=255):
|
||||
if self._transport is None:
|
||||
try:
|
||||
await self.open()
|
||||
except Exception as e:
|
||||
self.stats.error(e)
|
||||
return
|
||||
await super().send(rgb, global_brightness)
|
||||
|
||||
async def close(self):
|
||||
await super().close()
|
||||
if self._transport is not None:
|
||||
self._transport.close()
|
||||
self._transport = None
|
||||
|
||||
|
||||
class PresetOutput:
|
||||
"""Base class for outputs that render presets on the device itself."""
|
||||
|
||||
kind = "preset"
|
||||
protocol = ""
|
||||
|
||||
def __init__(self, cfg=None):
|
||||
self.cfg = dict(cfg or {})
|
||||
self.name = str(self.cfg.get("name") or self.protocol)
|
||||
self.stats = OutputStats()
|
||||
|
||||
async def open(self):
|
||||
pass
|
||||
|
||||
async def apply(self, preset_id, preset_payload):
|
||||
raise NotImplementedError
|
||||
|
||||
async def close(self):
|
||||
pass
|
||||
|
||||
def status(self):
|
||||
return {"name": self.name, "protocol": self.protocol, "kind": self.kind, **self.stats.to_dict()}
|
||||
|
||||
|
||||
def split_universes(data, channels_per_universe=510):
|
||||
"""Split RGB bytes into DMX-universe sized chunks (170 RGB px = 510 ch)."""
|
||||
return [data[i:i + channels_per_universe] for i in range(0, len(data), channels_per_universe)] or [b""]
|
||||
@@ -1,61 +0,0 @@
|
||||
"""DDP (Distributed Display Protocol) output — UDP 4048.
|
||||
|
||||
Header (10 bytes, big-endian):
|
||||
0 flags 0x40 = version 1, | 0x01 = PUSH (last packet of a frame)
|
||||
1 sequence 1..15 (0 = sequence numbers unused)
|
||||
2 data type 0x0B = RGB, 8 bits per channel
|
||||
3 dest id 0x01 = default output device
|
||||
4 offset uint32 byte offset into the frame
|
||||
8 length uint16 payload length
|
||||
"""
|
||||
|
||||
import struct
|
||||
|
||||
from engine.outputs.base import UdpFrameOutput, _int
|
||||
|
||||
DDP_PORT = 4048
|
||||
DDP_FLAG_VER1 = 0x40
|
||||
DDP_FLAG_PUSH = 0x01
|
||||
DDP_TYPE_RGB8 = 0x0B
|
||||
DDP_ID_DISPLAY = 0x01
|
||||
DDP_MAX_DATA = 1440 # 480 RGB pixels; fits a 1500-byte MTU
|
||||
|
||||
|
||||
def build_ddp_packets(data, sequence, max_data=DDP_MAX_DATA, dest_id=DDP_ID_DISPLAY):
|
||||
"""Split one frame into DDP packets; PUSH set on the last."""
|
||||
packets = []
|
||||
total = len(data)
|
||||
offset = 0
|
||||
while True:
|
||||
chunk = data[offset:offset + max_data]
|
||||
last = offset + len(chunk) >= total
|
||||
flags = DDP_FLAG_VER1 | (DDP_FLAG_PUSH if last else 0)
|
||||
header = struct.pack(
|
||||
">BBBBIH", flags, sequence & 0x0F, DDP_TYPE_RGB8, dest_id, offset, len(chunk)
|
||||
)
|
||||
packets.append(header + bytes(chunk))
|
||||
offset += len(chunk)
|
||||
if last:
|
||||
break
|
||||
return packets
|
||||
|
||||
|
||||
class DdpOutput(UdpFrameOutput):
|
||||
protocol = "ddp"
|
||||
default_port = DDP_PORT
|
||||
|
||||
def __init__(self, cfg):
|
||||
super().__init__(cfg)
|
||||
self.dest_id = _int(self.cfg.get("dest_id"), DDP_ID_DISPLAY, 0, 255)
|
||||
self._sequence = 0
|
||||
|
||||
def next_sequence(self):
|
||||
self._sequence = (self._sequence % 15) + 1
|
||||
return self._sequence
|
||||
|
||||
def packets_for(self, payload):
|
||||
return build_ddp_packets(payload, self.next_sequence(), dest_id=self.dest_id)
|
||||
|
||||
async def _send_prepared(self, payload):
|
||||
for packet in self.packets_for(payload):
|
||||
self.sendto(packet)
|
||||
@@ -1,97 +0,0 @@
|
||||
"""USB-DMX output via pyserial (one universe, 512 channels).
|
||||
|
||||
Modes:
|
||||
enttec_pro Enttec DMX USB Pro: 0x7E, label 6, len LE, start code + data, 0xE7
|
||||
open_dmx FTDI "Open DMX": 250000 baud 8N2, break, MAB, start code + 512 slots
|
||||
|
||||
Pixels start at DMX channel ``channel`` (1-based). Max 170 RGB pixels.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import struct
|
||||
import time
|
||||
|
||||
from engine.outputs.base import FrameOutput, _int
|
||||
|
||||
ENTTEC_SOM = 0x7E
|
||||
ENTTEC_EOM = 0xE7
|
||||
ENTTEC_LABEL_SEND_DMX = 6
|
||||
DMX_CHANNELS = 512
|
||||
|
||||
|
||||
def dmx_universe(payload, channel=1):
|
||||
"""512-slot universe with ``payload`` starting at 1-based ``channel``."""
|
||||
start = max(1, int(channel)) - 1
|
||||
universe = bytearray(DMX_CHANNELS)
|
||||
data = bytes(payload[: max(0, DMX_CHANNELS - start)])
|
||||
universe[start:start + len(data)] = data
|
||||
return bytes(universe)
|
||||
|
||||
|
||||
def build_enttec_pro(universe):
|
||||
body = b"\x00" + bytes(universe) # start code 0
|
||||
return bytes((ENTTEC_SOM, ENTTEC_LABEL_SEND_DMX)) + struct.pack("<H", len(body)) + body + bytes((ENTTEC_EOM,))
|
||||
|
||||
|
||||
class DmxSerialOutput(FrameOutput):
|
||||
protocol = "dmx_serial"
|
||||
keepalive_s = 0.1
|
||||
|
||||
def __init__(self, cfg, serial_factory=None):
|
||||
super().__init__(cfg)
|
||||
self.serial_port = str(self.cfg.get("serial_port") or "/dev/ttyUSB0")
|
||||
mode = str(self.cfg.get("dmx_mode") or "enttec_pro").lower()
|
||||
self.mode = mode if mode in ("enttec_pro", "open_dmx") else "enttec_pro"
|
||||
self.channel = _int(self.cfg.get("channel"), 1, 1, DMX_CHANNELS)
|
||||
self.fps = min(self.fps, 44) # DMX512 refresh ceiling
|
||||
self._serial_factory = serial_factory
|
||||
self._ser = None
|
||||
self._lock = asyncio.Lock()
|
||||
|
||||
def _open_serial(self):
|
||||
if self._serial_factory is not None:
|
||||
return self._serial_factory(self)
|
||||
import serial # pyserial
|
||||
|
||||
if self.mode == "open_dmx":
|
||||
return serial.Serial(
|
||||
self.serial_port, baudrate=250000, bytesize=8,
|
||||
parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_TWO, timeout=0.1,
|
||||
)
|
||||
return serial.Serial(self.serial_port, baudrate=57600, timeout=0.1)
|
||||
|
||||
async def open(self):
|
||||
if self._ser is None:
|
||||
self._ser = await asyncio.to_thread(self._open_serial)
|
||||
|
||||
def frame_bytes(self, payload):
|
||||
universe = dmx_universe(payload, self.channel)
|
||||
if self.mode == "enttec_pro":
|
||||
return build_enttec_pro(universe)
|
||||
return b"\x00" + universe
|
||||
|
||||
def _write(self, data):
|
||||
ser = self._ser
|
||||
if self.mode == "open_dmx":
|
||||
ser.break_condition = True
|
||||
time.sleep(0.000176) # >= 88 us break
|
||||
ser.break_condition = False
|
||||
time.sleep(0.000012) # >= 8 us mark-after-break
|
||||
ser.write(data)
|
||||
self.stats.packets += 1
|
||||
self.stats.bytes += len(data)
|
||||
|
||||
async def _send_prepared(self, payload):
|
||||
async with self._lock:
|
||||
if self._ser is None:
|
||||
await self.open()
|
||||
await asyncio.to_thread(self._write, self.frame_bytes(payload))
|
||||
|
||||
async def close(self):
|
||||
await super().close()
|
||||
if self._ser is not None:
|
||||
try:
|
||||
self._ser.close()
|
||||
except Exception:
|
||||
pass
|
||||
self._ser = None
|
||||
@@ -1,75 +0,0 @@
|
||||
"""Preset output for our own ESP32 led-drivers (Wi-Fi and ESP-NOW).
|
||||
|
||||
The firmware renders patterns itself, so the engine only sends the preset
|
||||
definition followed by a ``select`` for the zone's device names — the same
|
||||
two-message sequence the UI posts to ``/presets/push`` today.
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
from engine.outputs.base import PresetOutput
|
||||
from models.device import Device
|
||||
from models.transport import get_current_sender
|
||||
from util.driver_delivery import deliver_json_messages
|
||||
|
||||
|
||||
def resolve_device_macs(names, devices=None):
|
||||
"""Zone device names → MACs, one distinct device per repeated name (as zones.js)."""
|
||||
devices = devices if devices is not None else Device()
|
||||
used = set()
|
||||
rows = []
|
||||
for raw in names or []:
|
||||
name = str(raw or "").strip()
|
||||
if not name:
|
||||
continue
|
||||
for mac, doc in devices.items():
|
||||
if mac in used or not isinstance(doc, dict):
|
||||
continue
|
||||
if str(doc.get("name") or "").strip() == name:
|
||||
used.add(mac)
|
||||
rows.append((name, mac))
|
||||
break
|
||||
return rows
|
||||
|
||||
|
||||
class DriverOutput(PresetOutput):
|
||||
protocol = "driver"
|
||||
|
||||
def __init__(self, names, cfg=None, sender_getter=None, devices=None, save=False, delay_s=0.05):
|
||||
super().__init__(cfg)
|
||||
self.names = [str(n).strip() for n in (names or []) if str(n or "").strip()]
|
||||
self.name = self.cfg.get("name") or ",".join(self.names) or "driver"
|
||||
self._sender_getter = sender_getter or get_current_sender
|
||||
self._devices = devices
|
||||
self.save = bool(save)
|
||||
self.delay_s = delay_s
|
||||
|
||||
def messages_for(self, preset_id, preset_payload):
|
||||
pid = str(preset_id)
|
||||
preset_msg = {"v": "1", "presets": {pid: preset_payload}}
|
||||
if self.save:
|
||||
preset_msg["save"] = True
|
||||
messages = [json.dumps(preset_msg)]
|
||||
names = list(dict.fromkeys(self.names))
|
||||
if names:
|
||||
messages.append(json.dumps({"v": "1", "select": {n: [pid] for n in names}}))
|
||||
return messages
|
||||
|
||||
async def apply(self, preset_id, preset_payload):
|
||||
sender = self._sender_getter()
|
||||
if sender is None:
|
||||
self.stats.error(RuntimeError("transport not configured"))
|
||||
return 0
|
||||
devices = self._devices if self._devices is not None else Device()
|
||||
macs = [mac for _name, mac in resolve_device_macs(self.names, devices)]
|
||||
try:
|
||||
delivered, _ = await deliver_json_messages(
|
||||
sender, self.messages_for(preset_id, preset_payload), macs or None, devices,
|
||||
delay_s=self.delay_s,
|
||||
)
|
||||
self.stats.frames += 1
|
||||
self.stats.packets += delivered
|
||||
return delivered
|
||||
except Exception as e:
|
||||
self.stats.error(e)
|
||||
return 0
|
||||
@@ -1,92 +0,0 @@
|
||||
"""sACN / E1.31 output — UDP 5568, multicast 239.255.<hi>.<lo> by default.
|
||||
|
||||
One data packet per universe (170 RGB pixels each), 126-byte header +
|
||||
start code + up to 512 slots. Layer lengths are 12-bit, OR'd with 0x7000
|
||||
(flags).
|
||||
"""
|
||||
|
||||
import socket
|
||||
import struct
|
||||
import uuid
|
||||
|
||||
from engine.outputs.base import UdpFrameOutput, _bool, _int, split_universes
|
||||
|
||||
SACN_PORT = 5568
|
||||
ACN_PACKET_ID = b"ASC-E1.17\x00\x00\x00"
|
||||
VECTOR_ROOT_E131_DATA = 0x00000004
|
||||
VECTOR_E131_DATA_PACKET = 0x00000002
|
||||
VECTOR_DMP_SET_PROPERTY = 0x02
|
||||
DEFAULT_PRIORITY = 100
|
||||
|
||||
|
||||
def multicast_address(universe):
|
||||
return f"239.255.{(universe >> 8) & 0xFF}.{universe & 0xFF}"
|
||||
|
||||
|
||||
def stable_cid(seed):
|
||||
"""Deterministic 16-byte CID from a name, so receivers see one source."""
|
||||
return uuid.uuid5(uuid.NAMESPACE_URL, f"led-controller/sacn/{seed}").bytes
|
||||
|
||||
|
||||
def build_e131(universe, data, sequence, cid, source_name="led-controller", priority=DEFAULT_PRIORITY):
|
||||
slots = b"\x00" + bytes(data[:512]) # start code 0 + DMX
|
||||
prop_count = len(slots)
|
||||
dmp_len = 10 + prop_count
|
||||
framing_len = 77 + dmp_len
|
||||
root_len = 22 + framing_len
|
||||
name = source_name.encode("utf-8")[:63].ljust(64, b"\x00")
|
||||
|
||||
root = (
|
||||
struct.pack(">HH", 0x0010, 0x0000)
|
||||
+ ACN_PACKET_ID
|
||||
+ struct.pack(">HI", 0x7000 | root_len, VECTOR_ROOT_E131_DATA)
|
||||
+ bytes(cid)
|
||||
)
|
||||
framing = (
|
||||
struct.pack(">HI", 0x7000 | framing_len, VECTOR_E131_DATA_PACKET)
|
||||
+ name
|
||||
+ struct.pack(">BHBBH", priority & 0xFF, 0, sequence & 0xFF, 0, universe & 0xFFFF)
|
||||
)
|
||||
dmp = (
|
||||
struct.pack(">HBBHHH", 0x7000 | dmp_len, VECTOR_DMP_SET_PROPERTY, 0xA1, 0x0000, 0x0001, prop_count)
|
||||
+ slots
|
||||
)
|
||||
return root + framing + dmp
|
||||
|
||||
|
||||
class SacnOutput(UdpFrameOutput):
|
||||
protocol = "sacn"
|
||||
default_port = SACN_PORT
|
||||
|
||||
def __init__(self, cfg):
|
||||
super().__init__(cfg)
|
||||
self.universe = _int(self.cfg.get("universe"), 1, 1, 63999)
|
||||
self.priority = _int(self.cfg.get("priority"), DEFAULT_PRIORITY, 0, 200)
|
||||
self.multicast = not self.host or _bool(self.cfg.get("multicast"), False)
|
||||
self.source_name = str(self.cfg.get("source_name") or f"led-controller {self.name}")
|
||||
self.cid = stable_cid(self.cfg.get("cid") or self.cfg.get("id") or self.name)
|
||||
self._sequences = {}
|
||||
|
||||
def _make_socket(self):
|
||||
sock = super()._make_socket()
|
||||
if self.multicast:
|
||||
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 8)
|
||||
return sock
|
||||
|
||||
def _next_sequence(self, universe):
|
||||
seq = (self._sequences.get(universe, -1) + 1) & 0xFF
|
||||
self._sequences[universe] = seq
|
||||
return seq
|
||||
|
||||
def packets_for(self, payload):
|
||||
out = []
|
||||
for i, chunk in enumerate(split_universes(payload)):
|
||||
u = self.universe + i
|
||||
pkt = build_e131(u, chunk, self._next_sequence(u), self.cid, self.source_name, self.priority)
|
||||
addr = (multicast_address(u), self.port) if self.multicast else self.destination()
|
||||
out.append((pkt, addr))
|
||||
return out
|
||||
|
||||
async def _send_prepared(self, payload):
|
||||
for packet, addr in self.packets_for(payload):
|
||||
self.sendto(packet, addr)
|
||||
@@ -1,116 +0,0 @@
|
||||
"""Load the led-driver pattern modules (and its Preset class) for Pi-side rendering.
|
||||
|
||||
Mirrors ``Presets._load_dynamic_patterns`` in ``led-driver/src/presets.py``:
|
||||
every ``*.py`` in the patterns dir except ``__init__.py``/``main.py``, using
|
||||
the first class in the module that has ``run()``.
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
import threading
|
||||
|
||||
from engine import mpcompat
|
||||
from util.driver_patterns import driver_patterns_dir
|
||||
|
||||
_MODULE_PREFIX = "led_driver_patterns."
|
||||
|
||||
|
||||
def _load_module(name, path):
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
class _FallbackPreset:
|
||||
"""Used only when led-driver/src/preset.py is not deployed next to the patterns."""
|
||||
|
||||
_aliases = {"pattern": "p", "colors": "c", "delay": "d", "brightness": "b", "auto": "a"}
|
||||
|
||||
def __init__(self, data):
|
||||
self.p, self.d, self.b, self.c, self.a = "off", 100, 127, [(255, 255, 255)], True
|
||||
self.n1 = self.n2 = self.n3 = self.n4 = self.n5 = self.n6 = 0
|
||||
self.edit(data)
|
||||
|
||||
def edit(self, data=None):
|
||||
for key, value in (data or {}).items():
|
||||
key = self._aliases.get(key, key)
|
||||
if key in ("d", "b", "n1", "n2", "n3", "n4", "n5", "n6"):
|
||||
try:
|
||||
value = max(0, int(value))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if key == "b":
|
||||
value = min(255, value)
|
||||
elif key == "a":
|
||||
value = bool(value)
|
||||
elif key not in ("p", "c"):
|
||||
continue
|
||||
setattr(self, key, value)
|
||||
return True
|
||||
|
||||
|
||||
class PatternLibrary:
|
||||
def __init__(self, patterns_dir=None):
|
||||
self.patterns_dir = patterns_dir or driver_patterns_dir()
|
||||
self._lock = threading.Lock()
|
||||
self.classes = {}
|
||||
self.errors = {}
|
||||
self.preset_class = _FallbackPreset
|
||||
self.load()
|
||||
|
||||
def load(self):
|
||||
mpcompat.install()
|
||||
classes, errors = {}, {}
|
||||
try:
|
||||
files = sorted(os.listdir(self.patterns_dir))
|
||||
except OSError as e:
|
||||
files = []
|
||||
errors["*"] = repr(e)
|
||||
for filename in files:
|
||||
if not filename.endswith(".py") or filename in ("__init__.py", "main.py"):
|
||||
continue
|
||||
base = filename[:-3]
|
||||
try:
|
||||
module = _load_module(_MODULE_PREFIX + base, os.path.join(self.patterns_dir, filename))
|
||||
except Exception as e:
|
||||
errors[base] = repr(e)
|
||||
continue
|
||||
for attr_name in dir(module):
|
||||
attr = getattr(module, attr_name)
|
||||
if isinstance(attr, type) and hasattr(attr, "run"):
|
||||
classes[base] = attr
|
||||
break
|
||||
preset_cls = _FallbackPreset
|
||||
preset_path = os.path.join(os.path.dirname(self.patterns_dir), "preset.py")
|
||||
if os.path.isfile(preset_path):
|
||||
try:
|
||||
preset_cls = _load_module("led_driver_preset", preset_path).Preset
|
||||
except Exception as e:
|
||||
errors["preset.py"] = repr(e)
|
||||
with self._lock:
|
||||
self.classes = classes
|
||||
self.errors = errors
|
||||
self.preset_class = preset_cls
|
||||
return self
|
||||
|
||||
reload = load
|
||||
|
||||
def ids(self):
|
||||
return sorted(set(self.classes) | {"on", "off"})
|
||||
|
||||
def get(self, pattern_id):
|
||||
return self.classes.get(pattern_id)
|
||||
|
||||
def make_preset(self, payload):
|
||||
return self.preset_class(dict(payload or {}))
|
||||
|
||||
|
||||
_library = None
|
||||
|
||||
|
||||
def get_library():
|
||||
global _library
|
||||
if _library is None:
|
||||
_library = PatternLibrary()
|
||||
return _library
|
||||
@@ -1,148 +0,0 @@
|
||||
"""Per-zone player: render on a thread, stream frames to pixel outputs.
|
||||
|
||||
Modelled on portal's ``PatternPlayer``: the asyncio side only ships frames.
|
||||
The render thread runs the driver pattern exactly like the ESP32 main loop,
|
||||
and each ``n.write()`` wakes the sender, which pushes the newest frame to
|
||||
every output (coalescing writes faster than the outputs' fps).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
|
||||
from engine.outputs import open_output
|
||||
from engine.renderer import Renderer, RenderThread
|
||||
|
||||
SEND_TIMEOUT_S = 0.05
|
||||
|
||||
|
||||
def _default_driver_output(names):
|
||||
from engine.outputs.driver import DriverOutput # pulls in the Wi-Fi/serial stack
|
||||
|
||||
return DriverOutput(names)
|
||||
|
||||
|
||||
class ZonePlayer:
|
||||
def __init__(self, targets, library, brightness_getter=None, output_factory=None,
|
||||
driver_factory=None):
|
||||
self.targets = targets
|
||||
self.zone_id = targets.zone_id
|
||||
self.library = library
|
||||
self._brightness = brightness_getter or (lambda: 255)
|
||||
make_output = output_factory or open_output
|
||||
self.frame_outputs = [make_output(cfg) for cfg in targets.frame_cfgs]
|
||||
make_driver = driver_factory or _default_driver_output
|
||||
self.driver_output = make_driver(targets.driver_names) if targets.driver_names else None
|
||||
self.preset_id = None
|
||||
self.started_at = None
|
||||
self._loop = None
|
||||
self._latest = None
|
||||
self._frame_event = None
|
||||
self._sender_task = None
|
||||
self._render = None
|
||||
self.renderer = None
|
||||
|
||||
@property
|
||||
def fps(self):
|
||||
return min((o.fps for o in self.frame_outputs), default=0)
|
||||
|
||||
async def start(self):
|
||||
self._loop = asyncio.get_running_loop()
|
||||
if not self.frame_outputs:
|
||||
return
|
||||
for out in self.frame_outputs:
|
||||
try:
|
||||
await out.open()
|
||||
except Exception as e:
|
||||
out.stats.error(e)
|
||||
self._frame_event = asyncio.Event()
|
||||
self.renderer = Renderer(self.library, self.targets.frame_length, on_frame=self._on_frame_thread)
|
||||
self._render = RenderThread(self.renderer, name=f"engine-zone-{self.zone_id}").start()
|
||||
self._sender_task = asyncio.create_task(self._send_loop(), name=f"engine-send-{self.zone_id}")
|
||||
|
||||
def _on_frame_thread(self, frame):
|
||||
loop = self._loop
|
||||
if loop is None or loop.is_closed():
|
||||
return
|
||||
try:
|
||||
loop.call_soon_threadsafe(self._frame_ready, frame)
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
def _frame_ready(self, frame):
|
||||
self._latest = frame
|
||||
if self._frame_event is not None:
|
||||
self._frame_event.set()
|
||||
|
||||
async def send_frame(self, frame):
|
||||
level = self._brightness()
|
||||
tasks = []
|
||||
for out in self.frame_outputs:
|
||||
start = out.pixel_offset * 3
|
||||
tasks.append(asyncio.ensure_future(out.send(frame[start:start + out.pixel_count * 3], level)))
|
||||
if not tasks:
|
||||
return
|
||||
_done, pending = await asyncio.wait(tasks, timeout=SEND_TIMEOUT_S)
|
||||
for t in pending:
|
||||
t.cancel()
|
||||
|
||||
@property
|
||||
def keepalive_s(self):
|
||||
return min((o.keepalive_s for o in self.frame_outputs), default=1.0)
|
||||
|
||||
async def _send_loop(self):
|
||||
interval = 1.0 / max(1, self.fps)
|
||||
keepalive = self.keepalive_s
|
||||
while True:
|
||||
try:
|
||||
await asyncio.wait_for(self._frame_event.wait(), timeout=keepalive)
|
||||
except asyncio.TimeoutError:
|
||||
pass # no new frame: resend the last one
|
||||
self._frame_event.clear()
|
||||
started = time.monotonic()
|
||||
frame = self._latest
|
||||
if frame is not None:
|
||||
await self.send_frame(frame)
|
||||
rest = interval - (time.monotonic() - started)
|
||||
if rest > 0:
|
||||
await asyncio.sleep(rest)
|
||||
|
||||
async def apply(self, preset_id, payload, drivers=True):
|
||||
self.preset_id = str(preset_id)
|
||||
self.started_at = time.time()
|
||||
if self._render is not None:
|
||||
self._render.apply(preset_id, payload)
|
||||
if drivers and self.driver_output is not None:
|
||||
await self.driver_output.apply(preset_id, payload)
|
||||
|
||||
async def stop(self):
|
||||
if self._render is not None:
|
||||
self._render.stop()
|
||||
self._render = None
|
||||
if self._sender_task is not None:
|
||||
self._sender_task.cancel()
|
||||
try:
|
||||
await self._sender_task
|
||||
except (asyncio.CancelledError, Exception):
|
||||
pass
|
||||
self._sender_task = None
|
||||
for out in self.frame_outputs:
|
||||
try:
|
||||
await out.close()
|
||||
except Exception:
|
||||
pass
|
||||
if self.driver_output is not None:
|
||||
await self.driver_output.close()
|
||||
|
||||
def status(self):
|
||||
r = self.renderer
|
||||
return {
|
||||
"zone_id": self.zone_id,
|
||||
"preset_id": self.preset_id,
|
||||
"pattern": r.pattern_id if r else None,
|
||||
"error": r.error if r else None,
|
||||
"started_at": self.started_at,
|
||||
"frame_length": self.targets.frame_length,
|
||||
"fps": self.fps,
|
||||
"outputs": [o.status() for o in self.frame_outputs]
|
||||
+ ([self.driver_output.status()] if self.driver_output else []),
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
"""Resolve stored presets into driver payloads (short keys, palette refs applied)."""
|
||||
|
||||
from models.pallet import Palette
|
||||
from models.preset import Preset as PresetModel
|
||||
from models.profile import Profile
|
||||
from util.espnow_message import build_preset_dict
|
||||
|
||||
|
||||
def resolve_palette_colors(colors, palette_refs, palette):
|
||||
"""Same rule as presets.js ``resolveColorsWithPaletteRefs``."""
|
||||
base = list(colors) if isinstance(colors, list) else []
|
||||
refs = palette_refs if isinstance(palette_refs, list) else []
|
||||
pal = palette if isinstance(palette, list) else []
|
||||
out = []
|
||||
for idx, color in enumerate(base):
|
||||
ref = refs[idx] if idx < len(refs) else None
|
||||
try:
|
||||
ref = int(ref)
|
||||
except (TypeError, ValueError):
|
||||
ref = None
|
||||
if ref is not None and 0 <= ref < len(pal) and pal[ref]:
|
||||
out.append(pal[ref])
|
||||
else:
|
||||
out.append(color)
|
||||
return out
|
||||
|
||||
|
||||
def profile_palette(profile_id):
|
||||
if profile_id is None:
|
||||
return []
|
||||
profile = Profile().read(profile_id) or {}
|
||||
palette_id = profile.get("palette_id")
|
||||
if palette_id is None:
|
||||
return []
|
||||
return Palette().read(palette_id)
|
||||
|
||||
|
||||
def preset_payload(preset_id, preset_data=None):
|
||||
"""Driver payload (``p``, ``c``, ``d``, ``b``, ``a``, ``n1``..) for a stored preset."""
|
||||
data = preset_data if preset_data is not None else PresetModel().read(preset_id)
|
||||
if not data:
|
||||
return None
|
||||
data = dict(data)
|
||||
refs = data.get("palette_refs")
|
||||
if refs:
|
||||
data["colors"] = resolve_palette_colors(
|
||||
data.get("colors") or [], refs, profile_palette(data.get("profile_id"))
|
||||
)
|
||||
return build_preset_dict(data)
|
||||
|
||||
|
||||
def hex_to_rgb(color):
|
||||
if isinstance(color, (list, tuple)) and len(color) >= 3:
|
||||
return tuple(max(0, min(255, int(c))) for c in color[:3])
|
||||
s = str(color or "").strip().lstrip("#")
|
||||
if len(s) == 3:
|
||||
s = "".join(ch * 2 for ch in s)
|
||||
try:
|
||||
return (int(s[0:2], 16), int(s[2:4], 16), int(s[4:6], 16))
|
||||
except (ValueError, IndexError):
|
||||
return (255, 255, 255)
|
||||
@@ -1,157 +0,0 @@
|
||||
"""Run one led-driver pattern generator and collect the frames it writes.
|
||||
|
||||
``Renderer`` is synchronous and clock-agnostic (tests drive it with a
|
||||
``VirtualClock``). ``RenderThread`` runs a Renderer on its own thread with the
|
||||
real clock, the way the ESP32 main loop calls ``Presets.tick()``: patterns may
|
||||
block in ``utime.sleep_ms`` between writes and every ``n.write()`` becomes a frame.
|
||||
"""
|
||||
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
import types
|
||||
|
||||
from engine import mpcompat
|
||||
from engine.frame_driver import FrameDriver
|
||||
from engine.presets import hex_to_rgb
|
||||
|
||||
BUILTIN_PATTERNS = ("on", "off")
|
||||
|
||||
|
||||
class Renderer:
|
||||
def __init__(self, library, num_leds, on_frame=None):
|
||||
self.library = library
|
||||
self.on_frame = on_frame
|
||||
self.driver = FrameDriver(num_leds, on_write=self._frame_written)
|
||||
self.preset = None
|
||||
self.preset_id = None
|
||||
self.pattern_id = None
|
||||
self.generator = None
|
||||
self.last_frame = bytes(self.driver.num_leds * 3)
|
||||
self.frame_count = 0
|
||||
self.error = None
|
||||
|
||||
def _frame_written(self, frame):
|
||||
self.last_frame = frame
|
||||
self.frame_count += 1
|
||||
if self.on_frame is not None:
|
||||
self.on_frame(frame)
|
||||
|
||||
def set_preset(self, preset_id, payload):
|
||||
"""Select a preset, mirroring ``Presets.select`` (step reset rules included)."""
|
||||
data = dict(payload or {})
|
||||
colors = data.get("c", data.get("colors"))
|
||||
if isinstance(colors, list):
|
||||
data["c"] = [hex_to_rgb(c) for c in colors]
|
||||
data.pop("colors", None)
|
||||
preset = self.library.make_preset(data)
|
||||
pid = str(preset_id)
|
||||
if preset.p == "off" or pid != self.preset_id:
|
||||
self.driver.step = 0
|
||||
self.preset = preset
|
||||
self.preset_id = pid
|
||||
self.pattern_id = preset.p
|
||||
self.error = None
|
||||
self.generator = None
|
||||
|
||||
if preset.p in BUILTIN_PATTERNS:
|
||||
getattr(self.driver, preset.p)(preset)
|
||||
return True
|
||||
cls = self.library.get(preset.p)
|
||||
if cls is None:
|
||||
self.error = f"pattern not found: {preset.p}"
|
||||
self.driver.off()
|
||||
return False
|
||||
try:
|
||||
result = cls(self.driver).run(preset)
|
||||
except Exception as e:
|
||||
self.error = repr(e)
|
||||
return False
|
||||
if isinstance(result, types.GeneratorType):
|
||||
self.generator = result
|
||||
return True
|
||||
|
||||
def tick(self):
|
||||
"""Advance the pattern by one generator step (one device tick)."""
|
||||
gen = self.generator
|
||||
if gen is None:
|
||||
return False
|
||||
try:
|
||||
next(gen)
|
||||
return True
|
||||
except StopIteration:
|
||||
self.generator = None
|
||||
except Exception as e:
|
||||
self.error = repr(e)
|
||||
print(f"[engine] pattern {self.pattern_id!r} error: {e!r}")
|
||||
self.generator = None
|
||||
return False
|
||||
|
||||
def render_virtual(self, preset_id, payload, ticks, tick_ms=1, clock=None):
|
||||
"""Offline render with a virtual clock; returns the list of frames written."""
|
||||
frames = []
|
||||
prev_cb = self.on_frame
|
||||
self.on_frame = frames.append
|
||||
clock = clock or mpcompat.VirtualClock()
|
||||
mpcompat.set_thread_clock(clock)
|
||||
try:
|
||||
self.set_preset(preset_id, payload)
|
||||
for _ in range(int(ticks)):
|
||||
self.tick()
|
||||
clock.advance_ms(tick_ms)
|
||||
finally:
|
||||
mpcompat.set_thread_clock(None)
|
||||
self.on_frame = prev_cb
|
||||
return frames
|
||||
|
||||
|
||||
class RenderThread:
|
||||
"""Ticks a Renderer on a daemon thread; ``apply`` hot-swaps presets thread-safely."""
|
||||
|
||||
def __init__(self, renderer, tick_s=0.001, name="engine-render"):
|
||||
self.renderer = renderer
|
||||
self.tick_s = tick_s
|
||||
self._pending = None
|
||||
self._lock = threading.Lock()
|
||||
self._wake = threading.Event()
|
||||
self._stop = threading.Event()
|
||||
self._thread = threading.Thread(target=self._run, name=name, daemon=True)
|
||||
|
||||
def start(self):
|
||||
self._thread.start()
|
||||
return self
|
||||
|
||||
def apply(self, preset_id, payload):
|
||||
with self._lock:
|
||||
self._pending = (preset_id, payload)
|
||||
self._wake.set()
|
||||
|
||||
def stop(self, timeout=1.0):
|
||||
self._stop.set()
|
||||
self._wake.set()
|
||||
if self._thread.is_alive() and threading.current_thread() is not self._thread:
|
||||
self._thread.join(timeout)
|
||||
|
||||
def _take_pending(self):
|
||||
with self._lock:
|
||||
pending, self._pending = self._pending, None
|
||||
return pending
|
||||
|
||||
def _run(self):
|
||||
mpcompat.set_thread_clock(mpcompat.RealClock())
|
||||
r = self.renderer
|
||||
while not self._stop.is_set():
|
||||
pending = self._take_pending()
|
||||
if pending is not None:
|
||||
try:
|
||||
r.set_preset(*pending)
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
if r.generator is None:
|
||||
# Static frame (on/off/finished): sleep until the next preset.
|
||||
self._wake.wait()
|
||||
self._wake.clear()
|
||||
continue
|
||||
r.tick()
|
||||
if self.tick_s:
|
||||
time.sleep(self.tick_s)
|
||||
Loaded 100 of 225 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user