36 Commits
Author SHA1 Message Date
jimmyandClaude Haiku 5.5 47f4eba0d6 test: DDP test finds every device on the subnet and runs animations
- With no arguments, probe the local /24 for devices answering /api/ddp and test each one
  (--subnet picks another subnet; named hosts still override discovery).
- Test all devices at the same time, one thread each.
- Add chase, rainbow and breathe animations; check the last frame of each is shown.
- Compare readback against the output scale (global x master x max brightness) the
  firmware applies, read from /api/status and /api/hardware.
- Check the out-of-range packet and the timeout fallback against the last frame shown.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-11 12:57:14 +13:00
jimmyandClaude Haiku 5.5 d32f3d69cf feat: control several drivers from one web UI
- Device dropdown: All devices, this device by name, then drivers found by
  mDNS (tagged app=led-strip) and any added by hand.
- POST /api/relay: a driver calls another driver's API for the page, so the
  browser only talks to its own board. Limited to /api/*, /ota and /reboot.
- All devices sends brightness and preset plays to every device.
- Settings: sync this device's presets, order and startup to the others.
- CORS for LAN and localhost origins, and an OPTIONS handler for /ota.
- Header labels are removed; the controls keep aria-labels.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-11 02:48:48 +13:00
jimmyandClaude Haiku 5.5 4b623bb156 chore: remove MicroPython driver code (src, lib, tests, dev.py)
The cpp branch is the ESP-IDF firmware; the MicroPython drivers are removed.
Uncommitted MicroPython work was saved outside the repo before removal.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-11 02:07:44 +13:00
jimmyandClaude Haiku 5.5 9a04d28ecf feat: web UI with AP, Wi-Fi client, mDNS, presets, OTA and DDP
- Wi-Fi access point led-XXXXXX plus a client network, configurable
  mDNS name and static client address
- Preset tiles with an editor, drag to reorder, default presets,
  global brightness, Run and Edit modes, collapsible menu on phones
- 35 patterns ported from led-driver, up to 512 LEDs, colour order,
  max brightness and data pin settings
- Over-the-air updates (POST /ota) with rollback, and a CLI in tools/ota.py
- DDP receiver on UDP 4048 with tools/ddp_test.py
- LED refresh every 10 ms; lwIP sockets raised to 16 so mDNS, HTTP
  and DDP can run together

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-11 01:54:32 +13:00
jimmyandClaude Haiku 5.5 89f996096c Add LED web UI with AP, Wi-Fi client, mDNS and patterns
Brings the led_strip example into the cpp app, targeting the ESP32-C3:
- Access point led-XXXXXX (open) plus a Wi-Fi client configured from the
  web Settings tab, with credentials stored in NVS and reconnect backoff
- mDNS as led.local with an HTTP service on port 80
- HTTP server with an embedded web UI and a JSON API for patterns and Wi-Fi
- Pattern runner for solid, rainbow, chase, breathe, blink, pulse,
  transition and circle on a 119-LED WS2812 strip (GPIO 10)

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-11 00:02:49 +13:00
jimmyandClaude Haiku 5.5 df43820acd Add basic ESP-IDF app skeleton
Adds a minimal ESP-IDF project for ESP32-S3 at the repo root: top-level
CMakeLists, a main component with a C++ app_main that logs a heartbeat,
sdkconfig.defaults selecting esp32s3, and build notes in the README.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-10 23:23:08 +13:00
jimmyandClaude Sonnet 5.5 97df6e3cbe feat: max_brightness ceiling set from the controller's device config
Neither the global nor a preset's brightness goes above max_brightness; a
change redraws a static pattern under the new ceiling.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 01:48:42 +13:00
jimmyandClaude Sonnet 5.5 08d7277204 fix(beat): follow a controller that restarted its beat counter
A run of three consecutive indices that all look old means the controller
rebooted and restarted its counter, so resync to it; one or two stray old
frames are still dropped as late copies.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 01:48:42 +13:00
jimmyandClaude Opus 5.5 495da4e366 feat(espnow): app-file OTA over the reliable link
New espnow_ota module, loaded on the first OTA packet (types 0x07-0x0C,
status reply 0x26). Files are written by chunk index to <path>.new,
checked against their sha256, and moved into place together on commit,
followed by a reset. Unchanged files are skipped, and a repeated commit
after the reset still gets OK.

- receive ESP-NOW frames from esp.irq() so frames are not lost while
  presets.tick() runs; polling remains as a fallback
- raise rxbuf to 2048 and the link inbox to 24 frames
- file_hashes: MicroPython's sha256 has no hexdigest()
- bench stats line includes esp.stats()

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 23:41:17 +13:00
jimmyandClaude Sonnet 5.5 940d1d0a77 fix(espnow): start ESP-NOW before the pattern library on boot
On the ESP32-C3 the radio tasks failed to start (Wifi Unknown Error 0x0101)
on about every other cold boot once the link and beat modules were loaded.
Bringing ESP-NOW up before the pattern library and the LED driver claim
memory made 6 of 6 cold boots start cleanly.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 22:30:26 +13:00
jimmyandClaude Sonnet 5.5 20d1af7177 feat(espnow): reliable link and beat trigger on the 0x4C protocol
Adds the driver half of the v2 controller link as extra 0x4C message types:
DATA with fragment reassembly, de-duplication and acks, a state-version
digest with jittered resync requests, a bench echo, and a BEAT frame handled
by BeatSync (accepts one of the two copies, free-runs on the last period
when a beat is missed). Presets.beat() steps the selected pattern without a
message. Optional settings: espnow_loss, bench, beat_pin, usb_log.

The working tree also carries the files already running on the bench device,
which were ahead of origin/p2p: board.py (per-chip LED pin and CPU speed),
the reversed device_config flag in controller_messages.py, and the
apply_cpu_freq call in main.py.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-27 17:15:28 +13:00
jimmyandCursor 3286c4002d chore(settings): update default num_leds and color_order
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-29 16:00:56 +12:00
jimmyandCursor 68eb547ec4 feat(espnow): add debug logging and channel diagnostics
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-29 16:00:54 +12:00
jimmyandCursor 8403df531d feat(espnow): improve bridge transport and driver sync
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-28 00:38:09 +12:00
jimmyandCursor 088fe161a8 fix(main): blocking espnow rx loop and pass peer host
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 21:55:46 +12:00
jimmyandCursor c9895df512 fix(presets): phase-lock blink and one tick on re-select
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 21:55:46 +12:00
jimmyandCursor 39a84696c3 feat(espnow): ping request/response with jittered delay
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 21:55:39 +12:00
jimmyandCursor c7560b2e87 fix(settings): default wifi channel to 5
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 21:55:36 +12:00
jimmyandCursor ea21563900 fix(controller): apply select when presets not in message
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 21:55:30 +12:00
jimmyandCursor a97f6c7c2c feat(espnow): groups filter and v1 select list on driver
Apply group membership on RX, accept select as [preset_id, step?],
and fix identify/off plus presets layout for manual beat stepping.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-24 01:44:21 +12:00
jimmyandCursor 1fdb2c9441 fix(espnow): handle binary and JSON RX in simplified main
Use init_espnow for channel alignment; route wire CMD/GROUPS and JSON
v1 payloads to process_data from the poll loop.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 22:45:13 +12:00
jimmyandCursor 3e718f7432 feat(espnow): add wire transport and simplify broadcast main
Binary espnow_wire/espnow_transport modules plus a minimal main that
broadcasts a JSON hello and polls ESP-NOW while running presets.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 22:44:39 +12:00
jimmyandCursor 85490a3bd0 feat(deploy): add file_hashes.json manifest on device
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-17 19:14:51 +12:00
jimmyandCursor 94266d5a7c feat(patterns): reverse animation direction via preset n8
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-17 18:32:01 +12:00
jimmyandCursor 55a97ac51c feat(patterns): merge pattern styles and add mode support
Consolidate legacy pattern ids into meteor, particles, sparkle, chase,
and colour_cycle with n6/mode style selection; add pattern_modes helper,
self-contained tests/all.py, and preset mode alias on wire.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-16 21:14:54 +12:00
jimmyandCursor 794f1a2841 feat(patterns): add northern wave, candle glow, starfall, ice sparkle
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-16 15:11:32 +12:00
jimmyandCursor 8f8bc894a9 feat(patterns): add icicles blizzard and rime winter effects
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-16 15:09:59 +12:00
jimmyandCursor 2a768376d0 chore(release): beta-1.03
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-10 16:13:59 +12:00
jimmyandCursor 170a0e05ab feat(patterns): align manual and auto behaviour
Unify manual/auto timing semantics for key patterns, add preset background support, and improve runtime observability while keeping the driver responsive under beat-triggered selects.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-09 20:07:58 +12:00
jimmy 4879fcfe90 fix(patterns): use preset background fallback across animations
Align pattern background rendering to use preset.background_or(...) and update pulse/radiate single-step behaviour to preserve visible frames and step progression.
2026-05-09 14:28:05 +12:00
jimmyandCursor fbebe9f4f9 fix(patterns): correct non-blocking timing and blink off phase
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-06 20:28:52 +12:00
jimmyandCursor a79c6f4dd3 fix(patterns): remove blocking sleeps from pattern loops
Replace sleep-based timing in pattern generators with non-blocking tick checks so long delays do not block the main loop and risk watchdog resets.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-04 22:37:33 +12:00
piandCursor 2fcaf2f064 fix(driver): persist brightness when message includes save and b
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-03 22:15:23 +12:00
piandCursor 3b38264b70 chore(wifi): log connecting while waiting for STA
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-03 21:27:29 +12:00
jimmyandCursor 3ee89ce3b4 feat(driver): add HTTP routes, startup split, and binary envelope support
Wire controller messages through new modules (background tasks, runtime state,
startup) and add binary envelope handling.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-03 14:54:12 +12:00
jimmy 74b4b495f9 feat(patterns): add expanded animation pack with smoke tests
Add a broad set of new pattern modules and matching pattern smoke scripts so the new effects can be validated directly on-device.
2026-04-23 20:10:01 +12:00
84 changed files with 8129 additions and 6849 deletions

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
# The following 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.22)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
# "Trim" the build. Include the minimal set of components, main, and anything it depends on.
idf_build_set_property(MINIMAL_BUILD ON)
project(led_driver)
+80
View File
@@ -0,0 +1,80 @@
# Top-level Makefile for the led_strip ESP-IDF project.
# Thin wrapper around idf.py. Runs on Linux, macOS (bash) and Windows (GNU make with cmd.exe or sh).
#
# Override any variable on the command line, for example:
# make flash PORT=/dev/ttyUSB0 # Linux
# make flash PORT=/dev/cu.usbmodem101 # macOS
# make flash PORT=COM4 # Windows
ifeq ($(OS),Windows_NT)
HOST_OS := windows
HOME_DIR := $(USERPROFILE)
DEFAULT_PORT := COM3
else
HOST_OS := $(shell uname -s)
HOME_DIR := $(HOME)
ifeq ($(HOST_OS),Darwin)
DEFAULT_PORT := /dev/cu.usbmodem101
else
DEFAULT_PORT := /dev/ttyACM0
endif
endif
IDF_PATH ?= $(HOME_DIR)/.espressif/v6.1/esp-idf
IDF_PYTHON_ENV_PATH ?= $(HOME_DIR)/.espressif/python_env/idf6.1_py3.12_env
PORT ?= $(DEFAULT_PORT)
export IDF_PATH
export IDF_PYTHON_ENV_PATH
# Run idf.py in a shell that has sourced ESP-IDF's environment script (sets PATH and toolchains).
ifeq ($(HOST_OS),windows)
define idf
cmd /c "$(subst /,\,$(IDF_PATH))\export.bat && idf.py $(1)"
endef
else
define idf
bash -c '. "$(IDF_PATH)/export.sh" >/dev/null 2>&1 && idf.py $(1)'
endef
endif
.PHONY: all build flash monitor flash-monitor menuconfig clean fullclean help
all: build
build:
$(call idf,build)
flash: build
$(call idf,-p $(PORT) flash)
monitor:
$(call idf,-p $(PORT) monitor)
flash-monitor: build
$(call idf,-p $(PORT) flash monitor)
menuconfig:
$(call idf,menuconfig)
clean:
$(call idf,clean)
fullclean:
$(call idf,fullclean)
help:
@echo Targets:
@echo build Build the firmware
@echo flash Build, then flash to the board on PORT
@echo monitor Open the serial monitor on PORT
@echo flash-monitor Build, flash, then open the serial monitor
@echo menuconfig Open the project configuration menu
@echo clean Remove build outputs
@echo fullclean Delete the build directory entirely
@echo help Show this help
# Over-the-air update over Wi-Fi (the access point or the home network): make ota HOST=<ip or name>
ota: HOST ?= led.local
ota: build
python3 tools/ota.py $(HOST)
+32
View File
@@ -50,3 +50,35 @@ led-driver/
## Further reading
- **`docs/API.md`** — JSON message fields as used in examples (`pattern`, `colors`, …). The Pi app may send **short keys** (`p`, `c`, …); behaviour matches once normalised on device.
## C++ app (ESP-IDF)
The `cpp` branch is an ESP-IDF app for the ESP32-C3 at the repo root (`CMakeLists.txt`, `main/`, `web/`). It drives a 119-LED WS2812 strip on GPIO 10 (set in `main/patterns.cpp`).
### Web UI, access point and Wi-Fi client
The firmware runs three things at once:
- **Access point** `led-XXXXXX` (the last three bytes of the MAC), open, no password. Join it and browse to `http://192.168.4.1/`.
- **Wi-Fi client**: set a network from the Settings tab (scan, pick, enter password). Credentials are saved to NVS, and the client reconnects with backoff after a drop.
- **mDNS**: once on a network, the device answers as `http://led.local/`.
Patterns: solid, rainbow, chase, breathe, blink, pulse, transition and circle. The web UI is embedded in the firmware from `web/`.
JSON API (port 80):
| Method | Path | Purpose |
|--------|------|---------|
| GET | `/api/status` | Current pattern and parameters, AP name, client state and IP |
| POST | `/api/pattern` | `{"mode","c1":[r,g,b],"c2":[r,g,b],"speed_ms","brightness"}` |
| GET | `/api/wifi` | Saved client SSID and connection state |
| POST | `/api/wifi` | `{"ssid","password"}`: save and connect |
| GET | `/api/wifi/scan` | Visible networks |
Build and flash for the ESP32-C3:
```bash
. ~/.espressif/v6.1/esp-idf/export.sh
idf.py set-target esp32c3
idf.py build flash monitor
```
Executable
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
PORT="${1:-/dev/ttyACM0}"
while true; do
ls "$PORT" && led-cli -p "$PORT" --erase --src --patterns && led-cli -p "$PORT" --reset -f
sleep 0.5
done
+31
View File
@@ -0,0 +1,31 @@
dependencies:
espressif/cjson:
component_hash: e788323270d90738662d66fffa910bfe1fba019bba087f01557e70c40485b469
dependencies:
- name: idf
require: private
version: '>=5.0'
source:
registry_url: https://components.espressif.com/
type: service
version: 1.7.19~2
espressif/mdns:
component_hash: 2fa43caa78cc170842255bc7bf71f306bc815cae12e9496bfb12372423019ac7
dependencies:
- name: idf
require: private
version: '>=5.0'
source:
registry_url: https://components.espressif.com/
type: service
version: 1.15.1
idf:
source:
type: idf
version: 6.1.0
direct_dependencies:
- espressif/cjson
- espressif/mdns
manifest_hash: d0a7e36d6cc4abacaa550a978cbc8f50812589b67060a807571ef39c1e829dfd
target: esp32c3
version: 3.0.0
-93
View File
@@ -1,93 +0,0 @@
#!/usr/bin/env python3
import shutil
import subprocess
import serial
import sys
from pathlib import Path
def mpremote_base():
"""mpremote on PATH, or same interpreter as this script (e.g. pipenv venv)."""
exe = shutil.which("mpremote")
if exe:
return [exe]
return [sys.executable, "-m", "mpremote"]
print(sys.argv)
# Extract port (first arg if it's not a command)
commands = ["src", "lib", "ls", "reset", "follow", "db", "test"]
port = None
if len(sys.argv) > 1 and sys.argv[1] not in commands:
port = sys.argv[1]
for cmd in sys.argv[1:]:
print(cmd)
match cmd:
case "src":
if port:
subprocess.call(
[*mpremote_base(), "connect", port, "fs", "cp", "-r", ".", ":"],
cwd="src",
)
else:
print("Error: Port required for 'src' command")
case "lib":
if port:
subprocess.call([*mpremote_base(), "connect", port, "fs", "cp", "-r", "lib", ":"])
else:
print("Error: Port required for 'lib' command")
case "ls":
if port:
subprocess.call([*mpremote_base(), "connect", port, "fs", "ls", ":"])
else:
print("Error: Port required for 'ls' command")
case "reset":
if port:
with serial.Serial(port, baudrate=115200) as ser:
ser.write(b'\x03\x03\x04')
else:
print("Error: Port required for 'reset' command")
case "follow":
if port:
with serial.Serial(port, baudrate=115200) as ser:
while True:
if ser.in_waiting > 0: # Check if there is data in the buffer
data = ser.readline().decode('utf-8').strip() # Read and decode the data
print(data)
else:
print("Error: Port required for 'follow' command")
case "db":
if port:
subprocess.call([*mpremote_base(), "connect", port, "fs", "cp", "-r", "db", ":"])
else:
print("Error: Port required for 'db' command")
case "test":
if port:
if "all" in sys.argv[1:]:
test_files = sorted(
str(path)
for path in Path("test").rglob("*.py")
if path.is_file()
)
failed = []
for test_file in test_files:
print(f"Running {test_file}")
code = subprocess.call(
[*mpremote_base(), "connect", port, "run", test_file]
)
if code != 0:
failed.append((test_file, code))
if failed:
print("Some tests failed:")
for test_file, code in failed:
print(f" {test_file} (exit {code})")
else:
subprocess.call(
[*mpremote_base(), "connect", port, "run", "test/all.py"]
)
else:
print("Error: Port required for 'test' command")
+7
View File
@@ -97,6 +97,13 @@ Presets define LED patterns with their configuration. Each preset has a name and
- **`n3`**: Tail movement rate (LEDs per second)
- **`n4`**: Minimum length
#### Gradient Wipe (`gradient_wipe`)
One-shot: lights LEDs from `n1` to `n2` (backwards if `n1 > n2`) with a gradient from the first to the second colour, then stops.
- **`n1`**: First LED
- **`n2`**: Last LED
- **`delay`**: Total time in milliseconds to sweep from `n1` to `n2`
- **`background`**: Colour for the rest of the strip
## Select Messages
Select messages control which preset is active on which device. The format uses a list to support step synchronization.
+118
View File
@@ -0,0 +1,118 @@
# Patterns and presets on the LED driver
This document describes **how patterns are wired**, how **presets** map to patterns, and what each **shipped pattern** expects. For the JSON wire format (`v`: `"1"`, `presets`, `select`, short keys `p` / `c` / `b`, etc.), see [API.md](API.md).
## End-to-end control
1. The controller sends a **v1 JSON** object (ESP-NOW, serial bridge, or one line per message over TCP WebSocket in Wi-Fi mode).
2. `controller_messages.process_data()` parses it and applies fields in a fixed order (see `src/controller_messages.py`):
- `device_config` — name, LED count, colour order, startup mode; may reload `presets.json` and re-select the previous preset.
- `b` — **global** output brightness (0–255), stored in settings and in `presets.b`.
- `presets` — merge definitions into the in-memory preset table (`Presets.edit()` per id).
- `clear_presets` — optional wipe of all presets.
- `select` — pick the active preset (and optional step) for **this** device (matched by `settings["name"]`).
- `default` — update saved default preset when `targets` includes this device.
- `manifest` — pattern OTA: fetch pattern `.py` files and `reload_patterns()`.
- `save` — persist presets and/or settings when combined with the relevant fields.
3. The main loop calls `presets.tick()` so the active pattern **generator** advances one frame per iteration.
## Presets
- **Class:** `src/preset.py` — `Preset` holds the pattern configuration.
- **Short keys** (what the driver uses internally after `apply_presets` normalisation):
| Key | Meaning | Default |
|-----|---------|--------|
| `p` | Pattern id (string), must match a registered pattern | `"off"` |
| `c` | Colours as RGB tuples (after colour-order conversion) | `[(255,255,255)]` |
| `d` | Delay (ms); meaning is pattern-specific | `100` |
| `b` | Preset brightness 0–255 (combined with global `presets.b`) | `127` |
| `a` | Auto: continuous animation; `false` = manual / beat-stepped where supported | `True` |
| `bg` | Background colour (hex string or RGB tuple on device) | `(0,0,0)` |
| `n1`–`n6` | Pattern-specific integers | `0` |
Long aliases from the controller (`pattern`, `colors`, `delay`, `brightness`, `auto`, `background`) are converted in `Preset.edit()`.
- **Persistence:** `presets.json` on flash; **`MAX_PRESETS` = 32** (exceptions for auto-created `"on"` / `"off"`).
- **Activation:** `Presets.select(preset_name, step=None)` loads the preset, looks up **`preset.p`** in the pattern registry, and sets `generator = patterns[preset.p](preset)`, then runs one `tick()` so the first frame appears.
## Brightness
- **Global:** `presets.b` from message `{"v":"1","b":…}` scales every output channel.
- **Per preset:** `preset.b`; combined in `Presets.apply_brightness(colour, preset.b)` as
`effective = round(preset_channel * presets.b / 255)` with preset level applied first conceptually (`apply_brightness` takes the preset’s `b` as the override for that colour).
## Pattern registry
Built in `Presets.reload_patterns()` (`src/presets.py`):
1. **Built-ins:** `"off"` and `"on"` — methods on the `Presets` instance (not separate files).
2. **Dynamic modules:** Every `patterns/*.py` on flash (except `__init__.py`), imported as `patterns.<basename>`. The loader takes the **first class** in the module that defines **`run`**, instantiates it with `Presets(self)` (the driver / NeoPixel wrapper), and registers:
```text
patterns[basename] = PatternClass(driver).run
```
So the **`p` field must equal the file basename without `.py`** (e.g. file `radiate.py` ⇒ pattern `"radiate"`).
### Adding or updating patterns on device
- **OTA:** v1 message with `"manifest"` (URL or inline JSON listing `files` with `name`, `url` or `code`) — see `apply_patterns_ota()` in `controller_messages.py`.
- **HTTP:** `POST /patterns/upload` on the device (`src/main.py`) with a safe `.py` filename; optional reload of the registry.
After new files land in `patterns/`, call `presets.reload_patterns()` (done automatically by OTA and upload when configured).
## Auto vs manual (`a`)
- **`a: true` (auto):** The main loop keeps calling `tick()`; the generator runs continuously (subject to internal `yield` timing / `utime`).
- **`a: false` (manual):** Intended for patterns that advance **once per explicit `select`** (or per beat routing from the controller). The driver does **not** call `select()` again when editing a manual preset-only push — manual steps are driven by incoming `select` messages.
Special case in `Presets.select()`: for **manual chase**, if the same preset is re-selected mid-generator, pending frames may be flushed so step indices stay aligned with beats.
## Built-in patterns
### `off`
- **Registration:** built-in method `Presets.off`.
- **Behaviour:** fills the strip with black (after generator setup, `tick` completes immediately).
- **Parameters:** ignores preset colours for the strip; optional `preset` argument unused for pixels.
### `on`
- **Registration:** built-in method `Presets.on`.
- **Behaviour:** solid fill with `preset.c[0]` (or white if no colours), via `apply_brightness(..., preset.b)`.
- **Parameters:** `c`, `b`; `d` / `n*` not used.
## Dynamic pattern: `radiate`
- **File:** `src/patterns/radiate.py`
- **Class:** `Radiate` — `run(self, preset)` is a **generator** (must `yield` each frame).
- **Pattern key:** `p` = `"radiate"`
Concept: repeating **nodes** along the strip every **`n1`** LEDs; from each node a lit region expands outward then contracts (timed by **`n2`** / **`n3`**). In **auto**, a new pulse train starts every **`d`** ms and the active colour index advances. In **manual**, a **single** out-and-back cycle runs, then the generator ends (next colour on the next `select`).
| Field | Role |
|-------|------|
| `n1` | Node spacing in LEDs (`>= 1`; half-spacing used for symmetry) |
| `n2` | Outbound travel time (ms), `>= 1` |
| `n3` | Return travel time (ms), `>= 1` |
| `d` | Auto only: interval (ms) between re-triggers; `>= 1` |
| `c` | Colour list; cycles per retrigger / per manual cycle |
| `bg` | Off state / gap colour (via `preset.background_or`) |
| `b` | Preset brightness |
| `a` | `true` = repeating pulses on a timer; `false` = one shot per select |
Debug: if `presets.debug` is true (from settings), periodic logs print timing and lit LED counts.
## Other pattern names (`blink`, `rainbow`, `pulse`, …)
Those pattern **ids** are valid on the **wire** and in **led-controller** `db/pattern.json`, but they are **not** all present in this repository’s `src/patterns/` tree. On a real device they normally appear as **additional** `patterns/*.py` files delivered by OTA or upload. For the intended **`n1`–`n6`** semantics on the wire, use [API.md](API.md) **Pattern-Specific Parameters**; the implementation must match that contract in each module’s `run(preset)` generator.
## Quick reference: files
| File | Role |
|------|------|
| `src/preset.py` | Preset field model and aliases |
| `src/presets.py` | Registry, `select`, `tick`, `off` / `on`, dynamic load |
| `src/controller_messages.py` | Parse v1 JSON, apply presets/select/brightness/OTA |
| `src/patterns/*.py` | One pattern module per dynamic id (basename = `p`) |
-2
View File
@@ -1,2 +0,0 @@
from microdot.microdot import Microdot, Request, Response, abort, redirect, \
send_file # noqa: F401
-8
View File
@@ -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
-225
View File
@@ -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
-70
View File
@@ -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
-231
View File
@@ -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)
View File
Whitespace-only changes.
-14
View File
@@ -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
-21
View File
@@ -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)
-188
View File
@@ -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)
+6
View File
@@ -0,0 +1,6 @@
idf_component_register(SRCS "main.cpp" "ws2812.cpp" "net.cpp" "settings.cpp" "web.cpp" "patterns.cpp" "presets.cpp"
"effects_util.cpp" "effects_a.cpp" "effects_b.cpp" "effects_rig.cpp" "ota.c" "ddp.cpp"
PRIV_REQUIRES esp_driver_rmt esp_driver_gpio esp_wifi esp_netif esp_event
esp_timer nvs_flash esp_http_server esp_http_client cjson mdns esp_hw_support app_update esp_app_format lwip
INCLUDE_DIRS "."
EMBED_TXTFILES "../web/index.html" "../web/app.js" "../web/style.css")
+84
View File
@@ -0,0 +1,84 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#include <cstring>
#include "ddp.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "lwip/sockets.h"
#include "patterns.h"
static const char *TAG = "ddp";
// Header: flags, sequence, data type, destination, data offset (4), data length (2); with the timecode
// flag, 4 more bytes follow. Version 1 is flags bits 6-7 = 01.
#define DDP_FLAG_VER1 0x40
#define DDP_VER_MASK 0xC0
#define DDP_FLAG_TIMECODE 0x10
#define DDP_HEADER 10
static uint32_t be32(const uint8_t *p)
{
return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | p[3];
}
static uint16_t be16(const uint8_t *p)
{
return (uint16_t)((p[0] << 8) | p[1]);
}
static void ddp_task(void *arg)
{
(void)arg;
int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
if (sock < 0) {
ESP_LOGE(TAG, "socket failed");
vTaskDelete(NULL);
return;
}
struct sockaddr_in addr = {};
addr.sin_family = AF_INET;
addr.sin_port = htons(DDP_PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
ESP_LOGE(TAG, "bind to port %d failed", DDP_PORT);
close(sock);
vTaskDelete(NULL);
return;
}
ESP_LOGI(TAG, "DDP listening on UDP port %d", DDP_PORT);
uint8_t buf[1500];
while (true) {
int n = recv(sock, buf, sizeof(buf), 0);
if (n < DDP_HEADER) {
continue;
}
uint8_t flags = buf[0];
if ((flags & DDP_VER_MASK) != DDP_FLAG_VER1) {
continue;
}
size_t hdr = DDP_HEADER + ((flags & DDP_FLAG_TIMECODE) ? 4 : 0);
if ((size_t)n < hdr) {
continue;
}
uint8_t dtype = buf[2];
if (dtype != 0x00 && dtype != 0x01) {
continue; // only 8-bit RGB
}
uint32_t offset = be32(buf + 4);
size_t len = be16(buf + 8);
if (len > (size_t)n - hdr) {
len = (size_t)n - hdr;
}
patterns_ddp_write(offset, buf + hdr, len, (flags & 0x01) != 0);
}
}
esp_err_t ddp_start(void)
{
BaseType_t ok = xTaskCreate(ddp_task, "ddp", 4096, NULL, 4, NULL);
return ok == pdPASS ? ESP_OK : ESP_ERR_NO_MEM;
}
+14
View File
@@ -0,0 +1,14 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* DDP (Distributed Display Protocol) receiver: RGB pixels over UDP, port 4048. Packets fill the strip
* while they keep arriving (see patterns.cpp).
*/
#pragma once
#include "esp_err.h"
#define DDP_PORT 4048
/** @brief Start listening for DDP packets. */
esp_err_t ddp_start(void);
+149
View File
@@ -0,0 +1,149 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* Pattern engine shared by the effect files. Ports the MicroPython led-driver patterns: each pattern
* gets the same preset fields (colours, delay d, brightness b, auto a, reverse, n1..n6) and renders into
* a shadow frame, which patterns.cpp shows (with crossfade) on the strip.
*/
#pragma once
#include <cstdint>
#include "patterns.h"
#define FX_LEDS_MAX 512 // largest strip the engine supports (per-LED buffers are sized at run time)
struct rgb {
int r, g, b;
};
// Per-frame view handed to a pattern
struct fx_t {
int n; // LEDs in the strip
const preset_t *pr; // the running preset (copy)
uint32_t now; // ms now
uint32_t t; // ms since the pattern started
rgb *px; // shadow frame, physical order; persists between frames (n entries)
};
// Per-pattern state. Patterns run one at a time, so one instance is reset on each select.
struct flake_t { int pos, ci, wj; };
struct star_t { int h, ci; };
struct spark_t { int p, lv, ci; };
struct bug_t { int pos, ph; };
struct drop_t { int pos, age; };
struct st_t {
bool done; // one-shot finished: hold the frame
bool started; // one-time setup done
uint32_t last, aux; // timers
uint32_t t0; // start time
int ci; // colour index
int phase, dir, pause; // animation state
int head, tail; // moving head / tail
int p1, p2; // comet heads
int cnt; // counters
int sc; // chase step count
int stage; // state machine stage
int flash_idx;
int rise; // flame
int cj[8]; // flame cluster jitter
uint32_t breath_origin, last_cluster, next_spark, spark_start;
int spark_dur;
bool spark_active;
int breath_ms, lo, hi, gap_lo, gap_hi;
bool sparks_on;
int centers[32];
int ncent;
int *glow; // per-LED buffers, n entries each (see frame_alloc)
flake_t flakes[64];
int nflakes;
star_t stars[8];
int nstars;
spark_t sparks[32];
int nsparks;
bug_t bugs[16];
int nbugs;
drop_t drops[32];
int ndrops;
uint8_t *on, *next_on;
int *col_i, *next_ci;
int *light, *dark;
int nlight, ndark;
float *m; // rig: position of each LED along the pattern
int *shade; // rig: shade of each LED
};
extern st_t g_st;
// Allocate the per-LED buffers for n LEDs (frame and pattern state). False if out of memory, in which
// case the old buffers are kept. Call with the pattern lock held.
bool frame_alloc(int n);
// Reset the pattern state for a new pattern, keeping the buffers and clearing them.
void st_reset(void);
// ---- helpers ------------------------------------------------------------------------------
int clampi(int v, int lo, int hi);
int fdiv(int a, int b); // floor division, as Python's //
int pmod(int a, int m); // non-negative modulo, as Python's %
int nz(int v, int def); // v when v > 0, else def
rgb mk(int r, int g, int b); // clamped
rgb ab(rgb c, int level); // c scaled by level/255
rgb mix(rgb a, rgb b, int k); // a -> b, k 0..255
int sgn(const fx_t &f, int v); // v, negated when reversed
int led_at(const fx_t &f, int i); // logical index -> physical (reverse)
void put(fx_t &f, int phys, rgb c);
void putl(fx_t &f, int logical, rgb c);
void fill(fx_t &f, rgb c);
bool due(uint32_t now, uint32_t &last, uint32_t d); // true (and last += d) once d ms have passed
uint32_t dur(const fx_t &f, int v); // ms, or quarter beats with beat_time
int get_colours(const fx_t &f, const rgb *def, int ndef, rgb *out); // preset colours or the default
int rnd(int lo, int hi); // random integer, inclusive
rgb grad_at(const rgb *cols, int ncols, float t); // colour at t (0..1) along the list
rgb wheel(int pos); // hue wheel, 0..255 -> colour
// Colour table for the rig patterns: shades of the colour list, at LEVELS brightness steps
#define RIG_SHADES 16
#define RIG_LEVELS 16
rgb rig_entry(const fx_t &f, const rgb *cols, int ncols, int shades, int shade, int level);
// Pattern entry points (return true once a one-shot has finished)
bool fx_off(fx_t &f, st_t &s);
bool fx_on(fx_t &f, st_t &s);
bool fx_blink(fx_t &f, st_t &s);
bool fx_aurora(fx_t &f, st_t &s);
bool fx_bar_graph(fx_t &f, st_t &s);
bool fx_blizzard(fx_t &f, st_t &s);
bool fx_candle_glow(fx_t &f, st_t &s);
bool fx_chase(fx_t &f, st_t &s);
bool fx_circle(fx_t &f, st_t &s);
bool fx_clock_sweep(fx_t &f, st_t &s);
bool fx_colour_cycle(fx_t &f, st_t &s);
bool fx_flicker(fx_t &f, st_t &s);
bool fx_gradient_wipe(fx_t &f, st_t &s);
bool fx_hit(fx_t &f, st_t &s);
bool fx_icicles(fx_t &f, st_t &s);
bool fx_keyframes(fx_t &f, st_t &s);
bool fx_orbit(fx_t &f, st_t &s);
bool fx_pulse(fx_t &f, st_t &s);
bool fx_transition(fx_t &f, st_t &s);
bool fx_strobe_burst(fx_t &f, st_t &s);
bool fx_plasma(fx_t &f, st_t &s);
bool fx_meteor(fx_t &f, st_t &s);
bool fx_particles(fx_t &f, st_t &s);
bool fx_sparkle(fx_t &f, st_t &s);
bool fx_rain_drops(fx_t &f, st_t &s);
bool fx_rime(fx_t &f, st_t &s);
bool fx_twinkle(fx_t &f, st_t &s);
bool fx_radiate(fx_t &f, st_t &s);
bool fx_palette_morph(fx_t &f, st_t &s);
bool fx_flame(fx_t &f, st_t &s);
bool fx_field_wave(fx_t &f, st_t &s);
bool fx_grow(fx_t &f, st_t &s);
bool fx_ripple(fx_t &f, st_t &s);
bool fx_spin(fx_t &f, st_t &s);
bool fx_sweep(fx_t &f, st_t &s);
+897
View File
@@ -0,0 +1,897 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* Basic and colour patterns, ported from the MicroPython led-driver (patterns folder).
*/
#include <cmath>
#include <cstdlib>
#include "effects.h"
static const rgb WHITE = { 255, 255, 255 };
static const rgb BLACK = { 0, 0, 0 };
static bool first_call(st_t &s)
{
if (s.started) {
return false;
}
s.started = true;
return true;
}
// ---- off, on, blink ----------------------------------------------------------------------------
bool fx_off(fx_t &f, st_t &)
{
fill(f, BLACK);
return true;
}
bool fx_on(fx_t &f, st_t &)
{
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, &WHITE, 1, c);
fill(f, ab(c[0], f.pr->brightness));
(void)nc;
return false;
}
bool fx_blink(fx_t &f, st_t &s)
{
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, &WHITE, 1, c);
int b = f.pr->brightness;
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
if (first_call(s)) {
s.last = f.now;
s.stage = 1; // on
}
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
if (due(f.now, s.last, d)) {
if (s.stage) {
fill(f, ab(c[s.ci % nc], b));
s.ci++;
} else {
fill(f, bgc);
}
s.stage = !s.stage;
}
return false;
}
// ---- aurora ------------------------------------------------------------------------------------
bool fx_aurora(fx_t &f, st_t &s)
{
const rgb bands_def[3] = { { 40, 200, 140 }, { 80, 120, 255 }, { 160, 80, 220 } };
const rgb north_def[3] = { { 20, 55, 120 }, { 60, 140, 220 }, { 180, 220, 255 } };
rgb c[PATTERN_MAX_COLOURS + 1];
bool northern = f.pr->n[6] == 1;
int nc = get_colours(f, northern ? north_def : bands_def, 3, c);
int b = f.pr->brightness;
int nled = f.n;
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
if (!northern) {
int bands = nz(f.pr->n[1], 3);
int shimmer = clampi(nz(f.pr->n[2], 40), 0, 255);
if (!due(f.now, s.last, d)) {
return false;
}
for (int i = 0; i < nled; i++) {
int idx = (((i * bands) / (nled > 0 ? nled : 1)) + s.phase / 32) % nc;
rgb col = ab(c[idx], b);
int w = 255 - abs(128 - ((i * 8 + s.phase) & 255)) * 2;
w = clampi(w + shimmer, 0, 255);
rgb px = { col.r * w / 255, col.g * w / 255, col.b * w / 255 };
putl(f, i, px);
}
s.phase = pmod(s.phase + sgn(f, 1), 256);
return !f.pr->autorun;
}
// Northern wave: a sine of brightness along the strip, blended through the colours
int period = nz(f.pr->n[1], 20);
if (period < 4) period = 4;
int contrast = clampi(nz(f.pr->n[2], 200), 1, 255);
int drift = nz(f.pr->n[3], 2);
if (nc < 2) {
c[nc] = mk(120, 180, 255);
nc++;
}
if (!due(f.now, s.last, d)) {
return false;
}
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
const float twopi = 6.2831853f;
for (int i = 0; i < nled; i++) {
float t = (i * twopi / period) + (s.phase * twopi / 256.0f);
float w = (sinf(t) + 1.0f) * 0.5f;
int u = (int)(w * (nc - 1) * 256.0f);
int fi = u >> 8;
int frac = u & 255;
if (fi >= nc - 1) {
fi = nc - 2;
frac = 255;
}
rgb peak = ab(mix(c[fi], c[fi + 1], frac), b);
int mixf = (int)(w * contrast * 2);
mixf = mixf >> 1;
if (mixf > 255) mixf = 255;
putl(f, i, mix(bgc, peak, mixf));
}
s.phase = pmod(s.phase + sgn(f, drift), 256);
return !f.pr->autorun;
}
// ---- bar graph ---------------------------------------------------------------------------------
bool fx_bar_graph(fx_t &f, st_t &s)
{
const rgb def[2] = { { 0, 255, 0 }, { 255, 80, 0 } };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 2, c);
(void)nc;
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
if (!due(f.now, s.last, d)) {
return false;
}
int b = f.pr->brightness;
int level = clampi(f.pr->n[1], 0, 100);
int target = (f.n * level) / 100;
rgb lit = ab(c[0], b);
rgb unlit = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
for (int i = 0; i < f.n; i++) {
put(f, i, i < target ? lit : unlit);
}
return !f.pr->autorun;
}
// ---- blizzard ----------------------------------------------------------------------------------
bool fx_blizzard(fx_t &f, st_t &s)
{
const rgb def[3] = { { 255, 255, 255 }, { 200, 230, 255 }, { 180, 210, 255 } };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 3, c);
int b = f.pr->brightness;
int nled = f.n;
int density = nz(f.pr->n[1], 90);
int speed = nz(f.pr->n[2], 2);
int wraw = f.pr->n[3];
int wind = wraw <= 0 ? 0 : clampi(fdiv(wraw - 128, 20), -4, 4);
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
if (!due(f.now, s.last, d)) {
return false;
}
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
for (int i = 0; i < nled; i++) {
put(f, i, bgc);
}
if (rnd(0, 255) < density && s.nflakes < 64) {
flake_t fl = { nled - 1, rnd(0, nc - 1), wind == 0 ? 0 : rnd(-1, 1) };
s.flakes[s.nflakes++] = fl;
}
int keep = 0;
for (int k = 0; k < s.nflakes; k++) {
flake_t fl = s.flakes[k];
int p = fl.pos;
int lateral = wind + fl.wj;
p -= sgn(f, speed);
p += sgn(f, lateral);
if (p < -2 || p >= nled + 2) {
continue;
}
int pi = clampi(p, 0, nled - 1);
putl(f, pi, ab(c[fl.ci], b));
s.flakes[keep] = { p, fl.ci, fl.wj };
keep++;
}
s.nflakes = keep;
return false;
}
// ---- candle glow -------------------------------------------------------------------------------
bool fx_candle_glow(fx_t &f, st_t &s)
{
const rgb def[3] = { { 255, 140, 40 }, { 255, 200, 120 }, { 255, 90, 20 } };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 3, c);
int b = f.pr->brightness;
int nled = f.n;
if (first_call(s)) {
int nc_candles = clampi(nz(f.pr->n[1], 4), 1, nled);
if (nc_candles > 32) nc_candles = 32;
s.ncent = nc_candles;
for (int k = 0; k < nc_candles; k++) {
s.centers[k] = rnd(0, nled > 0 ? nled - 1 : 0);
}
s.last = f.now;
}
int width = nz(f.pr->n[2], 3);
int flicker = clampi(nz(f.pr->n[3], 90), 1, 255);
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
if (!due(f.now, s.last, d)) {
return false;
}
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
for (int i = 0; i < nled; i++) {
put(f, i, bgc);
}
int base_lo = 180 - flicker / 2;
if (base_lo < 40) base_lo = 40;
for (int ci = 0; ci < s.ncent; ci++) {
int centre = s.centers[ci];
rgb warmth = c[ci % nc];
int pulse = clampi(base_lo + rnd(0, flicker), 0, 255);
for (int off = -width; off <= width; off++) {
int idx = centre + off;
if (idx < 0 || idx >= nled) {
continue;
}
int dist = abs(off);
int fall = ((width - dist + 1) * 256) / (width + 1);
int fac = (fall * pulse) / 256;
rgb px = { warmth.r * fac / 255, warmth.g * fac / 255, warmth.b * fac / 255 };
rgb lit = ab(px, b);
rgb o = f.px[idx];
f.px[idx] = { o.r > lit.r ? o.r : lit.r, o.g > lit.g ? o.g : lit.g, o.b > lit.b ? o.b : lit.b };
}
}
return false;
}
// ---- chase -------------------------------------------------------------------------------------
static void chase_draw(fx_t &f, int pos, int n1, int n2, int n3, int n4, rgb c0, rgb c1)
{
int seg = n1 + n2;
(void)n3;
(void)n4;
for (int i = 0; i < f.n; i++) {
int rel = pmod(i - pos, seg);
putl(f, i, rel < n1 ? c0 : c1);
}
}
bool fx_chase(fx_t &f, st_t &s)
{
int b = f.pr->brightness;
int nled = f.n;
if (f.pr->n[6] == 1) {
// Marquee: dashes that scroll
const rgb def[1] = { WHITE };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 1, c);
(void)nc;
int on_len = nz(f.pr->n[1], 3);
int off_len = nz(f.pr->n[2], 2);
int step = abs(sgn(f, nz(f.pr->n[3], 1)));
if (step < 1) step = 1;
int period = on_len + off_len;
if (first_call(s)) {
s.last = f.now;
}
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
if (!due(f.now, s.last, d)) {
return false;
}
rgb col = ab(c[0], b);
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
for (int i = 0; i < nled; i++) {
int m = pmod(i + s.phase, period);
putl(f, i, m < on_len ? col : bgc);
}
s.phase = pmod(s.phase + sgn(f, step), period);
return !f.pr->autorun;
}
// Chase: two colours moving along the strip, n1/n2 segment lengths, n3/n4 steps
const rgb def[2] = { WHITE, WHITE };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 2, c);
rgb color0 = ab(c[0], b);
rgb color1 = ab(nc > 1 ? c[1] : c[0], b);
int n1 = nz(f.pr->n[1], 1);
int n2 = nz(f.pr->n[2], 1);
int n3 = sgn(f, f.pr->n[3]);
int n4 = sgn(f, f.pr->n[4]);
int seg = n1 + n2;
int max_pos = nled + seg;
auto position = [&](int sc) {
int pos;
if (sc % 2 == 0) {
pos = (sc / 2) * (n3 + n4) + n3;
} else {
pos = ((sc + 1) / 2) * (n3 + n4);
}
return pmod(pos, max_pos);
};
if (!f.pr->autorun) {
chase_draw(f, position(s.sc), n1, n2, n3, n4, color0, color1);
s.sc = (s.sc + 1) % 2;
return true;
}
uint32_t dur_ms = f.pr->delay < 10 ? 10 : f.pr->delay;
if (first_call(s)) {
s.last = f.now - dur_ms; // the first step is immediate
}
if ((int32_t)(f.now - s.last) >= (int32_t)dur_ms) {
chase_draw(f, position(s.sc), n1, n2, n3, n4, color0, color1);
s.sc = (s.sc + 1) % 2;
s.last += dur_ms;
}
return false;
}
// ---- circle ------------------------------------------------------------------------------------
bool fx_circle(fx_t &f, st_t &s)
{
int b = f.pr->brightness;
rgb color0, color1;
if (f.pr->ncol == 0) {
color0 = color1 = ab(WHITE, b);
} else {
color0 = ab(mk(f.pr->col[0][0], f.pr->col[0][1], f.pr->col[0][2]), b);
color1 = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
}
int nled = f.n;
int head_rate = nz(f.pr->n[1], 1);
int max_length = nz(f.pr->n[2], 1);
int tail_rate = nz(f.pr->n[3], 1);
int min_length = f.pr->n[4] > 0 ? f.pr->n[4] : 0;
if (first_call(s)) {
s.aux = f.now; // head timer
s.last = f.now; // tail timer
s.phase = 0; // 0 growing, 1 shrinking, 2 off
}
// Draw the ring: background, then the segment from the tail to the head
int seg = pmod(s.head - s.tail, nled);
if (seg == 0 && s.head != s.tail) {
seg = nled;
}
for (int i = 0; i < nled; i++) {
put(f, i, color1);
}
for (int i = 0; i <= seg; i++) {
put(f, (s.tail + i) % nled, color0);
}
// Head moves at n1 LEDs per second
uint32_t head_delay = 1000u / (uint32_t)head_rate;
if ((int32_t)(f.now - s.aux) >= (int32_t)head_delay) {
s.aux += head_delay;
s.head = (s.head + 1) % nled;
}
// Tail behaviour by phase
if (s.phase == 0) {
if (seg >= max_length) {
s.phase = 1;
}
} else if (s.phase == 1) {
uint32_t tail_delay = 1000u / (uint32_t)tail_rate;
if ((int32_t)(f.now - s.last) >= (int32_t)tail_delay) {
s.last += tail_delay;
s.tail = (s.tail + 1) % nled;
int cur = pmod(s.head - s.tail, nled);
if (cur == 0 && s.head != s.tail) {
cur = nled;
}
if (min_length == 0 && cur <= 1) {
s.phase = 2;
} else if (min_length > 0 && cur <= min_length) {
s.phase = 0;
}
}
} else {
s.tail = s.head;
s.phase = 0;
}
return false;
}
// ---- clock sweep -------------------------------------------------------------------------------
bool fx_clock_sweep(fx_t &f, st_t &s)
{
const rgb def[2] = { WHITE, { 60, 60, 60 } };
rgb c[PATTERN_MAX_COLOURS];
get_colours(f, def, 2, c);
int width = nz(f.pr->n[1], 1);
int marker = f.pr->n[2] > 0 ? f.pr->n[2] : 0;
int b = f.pr->brightness;
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
if (first_call(s)) {
s.last = f.now;
}
if (!due(f.now, s.last, d)) {
return false;
}
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
rgb fg = ab(c[0], b);
rgb dim = { bgc.r * 2 / 3, bgc.g * 2 / 3, bgc.b * 2 / 3 };
for (int i = 0; i < f.n; i++) {
put(f, i, bgc);
if (marker > 0 && i % marker == 0) {
put(f, i, dim);
}
}
for (int w = 0; w < width; w++) {
put(f, (s.phase + w) % f.n, fg);
}
s.phase = (s.phase + 1) % (f.n > 0 ? f.n : 1);
return !f.pr->autorun;
}
// ---- colour cycle ------------------------------------------------------------------------------
static void gradient_render(fx_t &f, const rgb *cols, int nc, int phase)
{
int b = f.pr->brightness;
int nled = f.n;
if (nc == 1) {
fill(f, ab(cols[0], b));
return;
}
int full_span = nc * 256;
int phase_shift = (phase * full_span) / 256;
for (int i = 0; i < nled; i++) {
int pos = (((i * full_span) / nled) + phase_shift) % full_span;
int idx = pos / 256;
int frac = pos & 255;
rgb c1 = cols[idx];
rgb c2 = cols[(idx + 1) % nc];
rgb blended = mix(c1, c2, frac);
putl(f, i, ab(blended, b));
}
}
static void rainbow_render(fx_t &f, int phase)
{
int b = f.pr->brightness;
int nled = f.n;
for (int i = 0; i < nled; i++) {
int rc = (i * 256) / (nled > 0 ? nled : 1) + phase;
putl(f, i, ab(wheel(rc & 255), b));
}
}
bool fx_colour_cycle(fx_t &f, st_t &s)
{
int step_amount = nz(f.pr->n[1], 1);
if (f.pr->n[6] == 1) {
// Fixed spectrum wheel, scrolling
if (!f.pr->autorun) {
rainbow_render(f, s.phase);
s.phase = pmod(s.phase + sgn(f, step_amount), 256);
return true;
}
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
if (!due(f.now, s.last, d)) {
return false;
}
rainbow_render(f, s.phase);
s.phase = pmod(s.phase + sgn(f, step_amount), 256);
return false;
}
const rgb def[2] = { { 255, 0, 0 }, { 0, 0, 255 } };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 2, c);
if (!f.pr->autorun) {
gradient_render(f, c, nc, s.phase);
s.phase = pmod(s.phase + sgn(f, step_amount), 256);
return true;
}
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
if (!due(f.now, s.last, d)) {
return false;
}
gradient_render(f, c, nc, s.phase);
s.phase = pmod(s.phase + sgn(f, step_amount), 256);
return false;
}
// ---- flicker -----------------------------------------------------------------------------------
bool fx_flicker(fx_t &f, st_t &s)
{
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, &WHITE, 1, c);
int lo = clampi(f.pr->n[1], 0, 255);
int hi = clampi(f.pr->brightness, 0, 255);
if (lo > hi) {
int t = lo;
lo = hi;
hi = t;
}
if (!f.pr->autorun) {
int level = rnd(lo, hi);
fill(f, ab(c[s.ci % nc], level));
return true;
}
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
if (first_call(s)) {
s.last = f.now;
}
if (!due(f.now, s.last, d)) {
return false;
}
int level = rnd(lo, hi);
fill(f, ab(c[s.ci % nc], level));
s.ci++;
return false;
}
// ---- gradient wipe (always one-shot) -----------------------------------------------------------
bool fx_gradient_wipe(fx_t &f, st_t &s)
{
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, &WHITE, 1, c);
int b = f.pr->brightness;
rgb c1 = c[0];
rgb c2 = nc > 1 ? c[1] : c[0];
int last = f.n > 0 ? f.n - 1 : 0;
int n1 = clampi(f.pr->n[1], 0, last);
int n2 = clampi(f.pr->n[2], 0, last);
int count = abs(n2 - n1) + 1;
int step = n2 >= n1 ? 1 : -1;
uint32_t duration = f.pr->delay < 1 ? 1 : f.pr->delay;
if (first_call(s)) {
fill(f, ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b));
}
if (s.cnt >= count) {
return true;
}
int lit = (int)((f.t * (uint32_t)count) / duration) + 1;
if (lit > count) {
lit = count;
}
for (int k = s.cnt; k < lit; k++) {
rgb col;
if (count == 1) {
col = c1;
} else {
float t = (float)k / (count - 1);
col = { (int)(c1.r + (c2.r - c1.r) * t), (int)(c1.g + (c2.g - c1.g) * t),
(int)(c1.b + (c2.b - c1.b) * t) };
}
putl(f, n1 + k * step, ab(col, b));
}
if (lit > s.cnt) {
s.cnt = lit;
}
return s.cnt >= count;
}
// ---- hit ---------------------------------------------------------------------------------------
bool fx_hit(fx_t &f, st_t &s)
{
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, &WHITE, 1, c);
int b = f.pr->brightness;
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
if (first_call(s)) {
s.aux = f.now;
}
for (int guard = 0; guard < 2; guard++) {
int attack = (int)dur(f, f.pr->n[1]);
int hold = (int)dur(f, f.pr->n[2]);
int decay = (int)dur(f, f.pr->n[3]);
int gap = f.pr->autorun ? (int)dur(f, (int)f.pr->delay) : 0;
rgb base = c[s.ci % nc];
int t = (int)(f.now - s.aux);
if (t < attack) {
rgb sc = { base.r * t / attack, base.g * t / attack, base.b * t / attack };
fill(f, ab(sc, b));
} else if (t < attack + hold) {
fill(f, ab(base, b));
} else if (t < attack + hold + decay) {
int left = decay - (t - attack - hold);
rgb sc = { base.r * left / decay, base.g * left / decay, base.b * left / decay };
rgb v = ab(sc, b);
rgb m = { v.r > bgc.r ? v.r : bgc.r, v.g > bgc.g ? v.g : bgc.g, v.b > bgc.b ? v.b : bgc.b };
fill(f, m);
} else if (!f.pr->autorun) {
fill(f, f.pr->n[4] == 1 ? ab(base, b) : bgc);
return true;
} else if (t < attack + hold + decay + gap) {
fill(f, bgc);
} else {
s.ci = (s.ci + 1) % nc;
s.aux = f.now;
continue; // the next flash starts on this frame
}
return false;
}
return false;
}
// ---- icicles -----------------------------------------------------------------------------------
bool fx_icicles(fx_t &f, st_t &s)
{
const rgb def[3] = { { 240, 248, 255 }, { 160, 210, 255 }, { 255, 255, 255 } };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 3, c);
int b = f.pr->brightness;
int nled = f.n;
int spacing = nz(f.pr->n[1], 12);
int cap = nled / 4;
if (cap > 14) cap = 14;
if (cap < 3) cap = 3;
int max_len = nz(f.pr->n[2], cap);
if (max_len < 2) max_len = 2;
if (max_len > (nled > 2 ? nled : 2)) max_len = nled > 2 ? nled : 2;
int span = max_len * 2;
int phase_step = nz(f.pr->n[3], 1);
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
if (first_call(s)) {
s.last = f.now;
}
if (!due(f.now, s.last, d)) {
return false;
}
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
for (int i = 0; i < nled; i++) {
put(f, i, bgc);
}
int aidx = 0;
for (int anchor = 0; anchor < nled; anchor += spacing) {
int tri_i = pmod(s.phase + aidx * 5, span);
int ic_len = tri_i <= max_len ? tri_i : span - tri_i;
rgb tip = ab(c[aidx % nc], b);
for (int k = 0; k < ic_len; k++) {
int idx = anchor + k;
if (idx >= nled) {
break;
}
int br = ((k + 1) * 255) / (ic_len > 1 ? ic_len : 1);
rgb px = { (tip.r * br + bgc.r * (255 - br)) / 255, (tip.g * br + bgc.g * (255 - br)) / 255,
(tip.b * br + bgc.b * (255 - br)) / 255 };
putl(f, idx, px);
}
aidx++;
}
s.phase = pmod(s.phase + sgn(f, phase_step), span);
return !f.pr->autorun;
}
// ---- keyframes ---------------------------------------------------------------------------------
static float ease_t(float t, int mode)
{
if (t <= 0) return 0;
if (t >= 1) return 1;
switch (mode) {
case 1: return t * t * (3 - 2 * t); // in-out
case 2: return 0; // step
case 3: return t * t; // in
case 4: return 1 - (1 - t) * (1 - t); // out
default: return t; // linear
}
}
bool fx_keyframes(fx_t &f, st_t &s)
{
const rgb def[1] = { WHITE };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 1, c);
int b = f.pr->brightness;
(void)s;
int total = (int)dur(f, (int)f.pr->delay);
if (total < 1) total = 1;
bool loop = f.pr->autorun;
int segs = loop ? nc : (nc - 1 > 1 ? nc - 1 : 1);
int t = (int)f.t;
if (!loop && t >= total) {
if (f.pr->n[2] == 1) {
fill(f, ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b));
} else if (f.pr->n[2] == 2) {
fill(f, BLACK);
} else {
fill(f, ab(c[nc - 1], b));
}
return true;
}
float x = ((float)(t % total) / total) * segs;
int i = (int)x;
rgb a = c[i % nc];
rgb bb = c[(i + 1) % nc];
float k = ease_t(x - i, f.pr->n[1]);
rgb m = { (int)(a.r + (bb.r - a.r) * k), (int)(a.g + (bb.g - a.g) * k), (int)(a.b + (bb.b - a.b) * k) };
fill(f, ab(m, b));
return false;
}
// ---- orbit -------------------------------------------------------------------------------------
bool fx_orbit(fx_t &f, st_t &s)
{
const rgb def[3] = { WHITE, { 0, 180, 255 }, { 255, 0, 120 } };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 3, c);
int b = f.pr->brightness;
int nled = f.n;
int orbits = nz(f.pr->n[1], 3);
int speed = nz(f.pr->n[2], 1);
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
if (first_call(s)) {
s.last = f.now;
}
if (!due(f.now, s.last, d)) {
return false;
}
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
for (int i = 0; i < nled; i++) {
put(f, i, bgc);
}
for (int k = 0; k < orbits; k++) {
int idx = ((s.phase * (k + 1)) / 8 + (k * nled) / orbits) % (nled > 0 ? nled : 1);
put(f, idx, ab(c[k % nc], b));
}
s.phase = (s.phase + speed) & 255;
return !f.pr->autorun;
}
// ---- pulse -------------------------------------------------------------------------------------
bool fx_pulse(fx_t &f, st_t &s)
{
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, &WHITE, 1, c);
int b = f.pr->brightness;
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
bool manual = !f.pr->autorun;
if (first_call(s)) {
fill(f, bgc);
s.aux = f.now; // cycle start
}
int attack = nz(f.pr->n[1], 0);
int hold = nz(f.pr->n[2], 0);
int decay = nz(f.pr->n[3], 0);
int delay = manual ? 0 : (int)f.pr->delay;
int total = attack + hold + decay + delay;
if (total <= 0) total = 1;
int elapsed = (int)(f.now - s.aux);
rgb base = c[s.ci % nc];
if (elapsed < attack && attack > 0) {
rgb col = { (int)(base.r * ((float)elapsed / attack)), (int)(base.g * ((float)elapsed / attack)),
(int)(base.b * ((float)elapsed / attack)) };
fill(f, ab(col, b));
} else if (elapsed < attack + hold) {
fill(f, ab(base, b));
} else if (elapsed < attack + hold + decay && decay > 0) {
float fac = 1.0f - (float)(elapsed - attack - hold) / decay;
if (fac < 0) fac = 0;
rgb col = { (int)(base.r * fac), (int)(base.g * fac), (int)(base.b * fac) };
fill(f, ab(col, b));
} else if (elapsed < total) {
fill(f, bgc);
} else {
int nclr = nc > 1 ? nc : 1;
s.ci = (s.ci + 1) % nclr;
if (manual) {
fill(f, bgc);
return true;
}
s.aux = f.now;
}
return false;
}
// ---- transition --------------------------------------------------------------------------------
bool fx_transition(fx_t &f, st_t &s)
{
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, &WHITE, 1, c);
int b = f.pr->brightness;
if (nc == 1) {
fill(f, ab(c[0], b));
return false;
}
if (first_call(s)) {
s.aux = f.now;
}
int duration = f.pr->delay < 10 ? 10 : (int)f.pr->delay;
int elapsed = (int)(f.now - s.aux);
if (elapsed >= duration) {
if (!f.pr->autorun) {
fill(f, ab(c[(s.ci + 1) % nc], b));
return true;
}
s.ci = (s.ci + 1) % nc;
s.aux = f.now;
return false;
}
rgb c1 = c[s.ci % nc];
rgb c2 = c[(s.ci + 1) % nc];
float factor = (float)elapsed / duration;
rgb m = { (int)(c1.r + (c2.r - c1.r) * factor), (int)(c1.g + (c2.g - c1.g) * factor),
(int)(c1.b + (c2.b - c1.b) * factor) };
fill(f, ab(m, b));
return false;
}
// ---- strobe burst ------------------------------------------------------------------------------
bool fx_strobe_burst(fx_t &f, st_t &s)
{
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, &WHITE, 1, c);
(void)nc;
int b = f.pr->brightness;
if (first_call(s)) {
s.stage = 0; // 0 flash on, 1 flash off, 2 cooldown
s.flash_idx = 0;
s.aux = f.now; // state start
}
int count = nz(f.pr->n[1], 3);
int gap = nz(f.pr->n[2], 60);
int cooldown = nz(f.pr->n[3], 400);
int on_ms = (int)f.pr->delay / 2;
if (on_ms < 1) on_ms = 1;
rgb col = ab(c[0], b);
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
int since = (int)(f.now - s.aux);
if (s.stage == 0) {
fill(f, col);
if (since >= on_ms) {
s.stage = 1;
s.aux += on_ms;
}
} else if (s.stage == 1) {
fill(f, bgc);
if (since >= gap) {
s.flash_idx++;
if (s.flash_idx >= count) {
if (!f.pr->autorun) {
return true;
}
s.stage = 2;
s.flash_idx = 0;
s.aux += gap;
} else {
s.stage = 0;
s.aux += gap;
}
}
} else {
fill(f, bgc);
if (since >= cooldown) {
s.stage = 0;
s.aux += cooldown;
}
}
return false;
}
// ---- plasma ------------------------------------------------------------------------------------
bool fx_plasma(fx_t &f, st_t &s)
{
int b = f.pr->brightness;
int nled = f.n;
int scale = nz(f.pr->n[1], 6);
int speed = nz(f.pr->n[2], 2);
int contrast = nz(f.pr->n[3], 2);
uint32_t d = f.pr->delay < 1 ? 1 : f.pr->delay;
if (first_call(s)) {
s.last = f.now;
}
if (!due(f.now, s.last, d)) {
return false;
}
int t = s.phase;
for (int i = 0; i < nled; i++) {
int v = (i * scale + t) & 255;
int v2 = ((i * scale) / contrast - t * 2) & 255;
put(f, i, ab(wheel((v + v2) & 255), b));
}
s.phase = pmod(s.phase + speed, 256);
return !f.pr->autorun;
}
+894
View File
@@ -0,0 +1,894 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* Moving lights, particles and sparkles, ported from the MicroPython led-driver (patterns folder).
*/
#include <cstdlib>
#include "effects.h"
static const rgb WHITE = { 255, 255, 255 };
static bool first_call(st_t &s)
{
if (s.started) {
return false;
}
s.started = true;
return true;
}
static uint32_t period_of(const fx_t &f)
{
return f.pr->delay < 1 ? 1 : f.pr->delay;
}
// Fade every LED's stored colour towards black (the shadow frame persists between frames)
static void fade_frame(fx_t &f, int amount)
{
for (int i = 0; i < f.n; i++) {
rgb c = f.px[i];
f.px[i] = { c.r * amount / 255, c.g * amount / 255, c.b * amount / 255 };
}
}
// ---- meteor / comet / scanner ------------------------------------------------------------------
static bool meteor_run(fx_t &f, st_t &s, const rgb *cols, int nc)
{
int b = f.pr->brightness;
int tail = nz(f.pr->n[1], 8);
int speed = nz(f.pr->n[2], 1);
int fade_amount = clampi(nz(f.pr->n[3], 192), 1, 255);
if (first_call(s)) {
s.last = f.now;
s.dir = f.pr->reverse ? -1 : 1;
s.head = f.pr->reverse ? (f.n > 0 ? f.n - 1 : 0) : 0;
s.ci = 0;
}
if (!due(f.now, s.last, period_of(f))) {
return false;
}
fade_frame(f, fade_amount);
rgb lit = ab(cols[s.ci % nc], b);
if (s.head >= 0 && s.head < f.n) {
putl(f, s.head, lit);
}
s.head += sgn(f, s.dir * speed);
if (s.head >= f.n + tail) {
s.head = f.n - 1;
s.dir = -1;
s.ci++;
} else if (s.head < -tail) {
s.head = 0;
s.dir = 1;
s.ci++;
}
return !f.pr->autorun;
}
static bool comet_run(fx_t &f, st_t &s, const rgb *cols, int nc)
{
int b = f.pr->brightness;
int nled = f.n;
int tail = nz(f.pr->n[1], 6);
int speed = nz(f.pr->n[2], 1);
int gap = f.pr->n[3] > 0 ? f.pr->n[3] : 0;
if (first_call(s)) {
s.last = f.now;
if (f.pr->reverse) {
s.p1 = nled - 1;
s.p2 = gap;
} else {
s.p1 = 0;
s.p2 = nled - 1 - gap;
}
}
if (!due(f.now, s.last, period_of(f))) {
return false;
}
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
for (int i = 0; i < nled; i++) {
put(f, i, bgc);
}
rgb c1 = ab(cols[0], b);
rgb c2 = ab(nc > 1 ? cols[1] : cols[0], b);
int denom = tail > 1 ? tail : 1;
for (int t = 0; t < tail; t++) {
int i1 = s.p1 - t;
if (i1 >= 0 && i1 < nled) {
int k = (255 * (tail - t)) / denom;
putl(f, i1, { c1.r * k / 255, c1.g * k / 255, c1.b * k / 255 });
}
int i2 = s.p2 + t;
if (i2 >= 0 && i2 < nled) {
int k = (255 * (tail - t)) / denom;
putl(f, i2, { c2.r * k / 255, c2.g * k / 255, c2.b * k / 255 });
}
}
s.p1 += sgn(f, speed);
s.p2 -= sgn(f, speed);
if (s.p1 - tail > nled && s.p2 + tail < 0) {
s.p1 = 0;
s.p2 = nled - 1 - gap;
}
return !f.pr->autorun;
}
static bool scanner_run(fx_t &f, st_t &s, const rgb *cols, int nc)
{
int b = f.pr->brightness;
int nled = f.n;
int width = nz(f.pr->n[1], 4);
int end_pause = f.pr->n[2] > 0 ? f.pr->n[2] : 0;
if (first_call(s)) {
s.last = f.now;
s.ci = 0;
s.pause = 0;
s.dir = f.pr->reverse ? -1 : 1;
s.head = f.pr->reverse ? (nled > 0 ? nled - 1 : 0) : 0; // centre
}
if (!due(f.now, s.last, period_of(f))) {
return false;
}
rgb base = ab(cols[s.ci % nc], b);
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
int denom = width > 1 ? width : 1;
for (int i = 0; i < nled; i++) {
int dist = abs(i - s.head);
if (dist > width) {
putl(f, i, bgc);
} else {
int sc = ((width - dist) * 255) / denom;
putl(f, i, { base.r * sc / 255, base.g * sc / 255, base.b * sc / 255 });
}
}
if (s.pause > 0) {
s.pause--;
} else {
s.head += sgn(f, s.dir);
if (s.head >= nled - 1) {
s.head = nled - 1;
s.dir = -1;
s.pause = end_pause;
s.ci++;
} else if (s.head <= 0) {
s.head = 0;
s.dir = 1;
s.pause = end_pause;
s.ci++;
}
}
return !f.pr->autorun;
}
bool fx_meteor(fx_t &f, st_t &s)
{
const rgb def[1] = { WHITE };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 1, c);
switch (f.pr->n[6]) {
case 1:
return comet_run(f, s, c, nc);
case 2:
return scanner_run(f, s, c, nc);
default:
return meteor_run(f, s, c, nc);
}
}
// ---- particles: snowfall and starfall ----------------------------------------------------------
static bool snow_run(fx_t &f, st_t &s)
{
const rgb def[2] = { WHITE, { 180, 220, 255 } };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 2, c);
int b = f.pr->brightness;
int density = nz(f.pr->n[1], 20);
int speed = abs(sgn(f, nz(f.pr->n[2], 1)));
if (speed < 1) speed = 1;
if (first_call(s)) {
s.last = f.now;
}
if (!due(f.now, s.last, period_of(f))) {
return false;
}
if (rnd(0, 255) < density && s.nflakes < 64) {
s.flakes[s.nflakes++] = { f.n - 1, rnd(0, nc - 1), 0 };
}
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
for (int i = 0; i < f.n; i++) {
put(f, i, bgc);
}
int keep = 0;
for (int k = 0; k < s.nflakes; k++) {
flake_t fl = s.flakes[k];
if (fl.pos >= 0 && fl.pos < f.n) {
putl(f, fl.pos, ab(c[fl.ci], b));
}
fl.pos -= sgn(f, speed);
if (fl.pos >= -1) {
s.flakes[keep++] = fl;
}
}
s.nflakes = keep;
return !f.pr->autorun;
}
static bool starfall_run(fx_t &f, st_t &s)
{
const rgb def[3] = { WHITE, { 200, 230, 255 }, { 255, 248, 220 } };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 3, c);
int b = f.pr->brightness;
int rate = clampi(nz(f.pr->n[1], 14), 1, 255);
int speed = abs(sgn(f, nz(f.pr->n[2], 2)));
if (speed < 1) speed = 1;
int tail = nz(f.pr->n[3], 10);
if (tail < 2) tail = 2;
if (first_call(s)) {
s.last = f.now;
}
if (!due(f.now, s.last, period_of(f))) {
return false;
}
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
for (int i = 0; i < f.n; i++) {
put(f, i, bgc);
}
if (s.nstars < 4 && rnd(0, 255) < rate) {
int extra = f.n / 2;
if (extra > 8) extra = 8;
int top = f.n - 1 + rnd(0, extra);
s.stars[s.nstars++] = { top, rnd(0, nc - 1) };
}
int keep = 0;
for (int k = 0; k < s.nstars; k++) {
star_t st = s.stars[k];
for (int t = 0; t < tail; t++) {
int idx = st.h + t;
if (idx < 0 || idx >= f.n) {
continue;
}
int fade = 255 - (t * 255) / (tail - 1 > 1 ? tail - 1 : 1);
rgb base = c[st.ci];
rgb lit = ab({ base.r * fade / 255, base.g * fade / 255, base.b * fade / 255 }, b);
int pix = led_at(f, idx);
rgb o = f.px[pix];
f.px[pix] = { o.r > lit.r ? o.r : lit.r, o.g > lit.g ? o.g : lit.g, o.b > lit.b ? o.b : lit.b };
}
st.h -= sgn(f, speed);
if (st.h >= -tail) {
s.stars[keep++] = st;
}
}
s.nstars = keep;
return !f.pr->autorun;
}
bool fx_particles(fx_t &f, st_t &s)
{
return f.pr->n[6] == 1 ? starfall_run(f, s) : snow_run(f, s);
}
// ---- sparkle: trail, ice burst, fireflies ------------------------------------------------------
static bool sparkle_trail(fx_t &f, st_t &s)
{
const rgb def[1] = { { 120, 120, 255 } };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 1, c);
int b = f.pr->brightness;
int density = nz(f.pr->n[1], 24);
int decay = clampi(nz(f.pr->n[2], 210), 1, 255);
if (first_call(s)) {
s.last = f.now;
}
if (!due(f.now, s.last, period_of(f))) {
return false;
}
fade_frame(f, decay);
int sparks = f.n * density / 255;
if (sparks < 1) sparks = 1;
for (int k = 0; k < sparks; k++) {
int idx = rnd(0, f.n > 0 ? f.n - 1 : 0);
put(f, idx, ab(c[rnd(0, nc - 1)], b));
}
return !f.pr->autorun;
}
static bool sparkle_ice(fx_t &f, st_t &s)
{
const rgb def[3] = { { 240, 248, 255 }, { 200, 235, 255 }, { 255, 255, 255 } };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 3, c);
int b = f.pr->brightness;
int rate = clampi(nz(f.pr->n[1], 55), 1, 255);
int decay = clampi(nz(f.pr->n[2], 140), 1, 255);
int halo = clampi(f.pr->n[3], 0, 3);
const int cap = 28;
if (first_call(s)) {
s.last = f.now;
}
if (!due(f.now, s.last, period_of(f))) {
return false;
}
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
for (int i = 0; i < f.n; i++) {
put(f, i, bgc);
}
int keep = 0;
for (int k = 0; k < s.nsparks; k++) {
spark_t sp = s.sparks[k];
sp.lv -= decay;
if (sp.lv > 0) {
s.sparks[keep++] = sp;
}
}
s.nsparks = keep;
if (s.nsparks < cap && rnd(0, 255) < rate) {
s.sparks[s.nsparks++] = { rnd(0, f.n > 0 ? f.n - 1 : 0), 255, rnd(0, nc - 1) };
}
for (int k = 0; k < s.nsparks; k++) {
spark_t sp = s.sparks[k];
rgb base = c[sp.ci];
for (int off = -halo; off <= halo; off++) {
int idx = sp.p + off;
if (idx < 0 || idx >= f.n) {
continue;
}
int dist = abs(off);
int fac = dist == 0 ? sp.lv : (sp.lv * (halo - dist + 1)) / (halo + 1);
rgb lit = ab({ base.r * fac / 255, base.g * fac / 255, base.b * fac / 255 }, b);
rgb o = f.px[idx];
f.px[idx] = { o.r + lit.r > 255 ? 255 : o.r + lit.r, o.g + lit.g > 255 ? 255 : o.g + lit.g,
o.b + lit.b > 255 ? 255 : o.b + lit.b };
}
}
return !f.pr->autorun;
}
static bool sparkle_fireflies(fx_t &f, st_t &s)
{
const rgb def[2] = { { 255, 210, 80 }, { 120, 255, 120 } };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 2, c);
int b = f.pr->brightness;
int count = nz(f.pr->n[1], 6);
if (count > 16) count = 16;
int speed = nz(f.pr->n[2], 8);
if (first_call(s)) {
s.last = f.now;
s.nbugs = count;
for (int k = 0; k < count; k++) {
s.bugs[k] = { rnd(0, f.n > 0 ? f.n - 1 : 0), rnd(0, 255) };
}
}
if (!due(f.now, s.last, period_of(f))) {
return false;
}
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
for (int i = 0; i < f.n; i++) {
put(f, i, bgc);
}
for (int k = 0; k < s.nbugs; k++) {
bug_t &bg = s.bugs[k];
int tri = 255 - abs(128 - bg.ph) * 2;
rgb col = ab(c[bg.pos % nc], b);
put(f, bg.pos, { col.r * tri / 255, col.g * tri / 255, col.b * tri / 255 });
bg.ph = (bg.ph + speed) & 255;
if (rnd(0, 31) == 0) {
bg.pos = rnd(0, f.n > 0 ? f.n - 1 : 0);
}
}
return !f.pr->autorun;
}
bool fx_sparkle(fx_t &f, st_t &s)
{
switch (f.pr->n[6]) {
case 1:
return sparkle_ice(f, s);
case 2:
return sparkle_fireflies(f, s);
default:
return sparkle_trail(f, s);
}
}
// ---- rain drops --------------------------------------------------------------------------------
bool fx_rain_drops(fx_t &f, st_t &s)
{
const rgb def[1] = { { 120, 180, 255 } };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 1, c);
int b = f.pr->brightness;
int rate = nz(f.pr->n[1], 32);
int width = nz(f.pr->n[2], 3);
if (first_call(s)) {
s.last = f.now;
}
if (!due(f.now, s.last, period_of(f))) {
return false;
}
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
for (int i = 0; i < f.n; i++) {
put(f, i, bgc);
}
if (rnd(0, 255) < rate && s.ndrops < 32) {
s.drops[s.ndrops++] = { rnd(0, f.n > 0 ? f.n - 1 : 0), 0 };
}
int keep = 0;
int denom = width + 1;
for (int k = 0; k < s.ndrops; k++) {
drop_t dr = s.drops[k];
for (int off = -width; off <= width; off++) {
int idx = dr.pos + off;
if (idx < 0 || idx >= f.n) {
continue;
}
int lvl = 255 - (abs(off) * 255 / (denom > 1 ? denom : 1) + dr.age * 40);
if (lvl < 0) lvl = 0;
rgb base = ab(c[dr.age % nc], b);
put(f, idx, { base.r * lvl / 255, base.g * lvl / 255, base.b * lvl / 255 });
}
dr.age++;
if (dr.age < 8) {
s.drops[keep++] = dr;
}
}
s.ndrops = keep;
return !f.pr->autorun;
}
// ---- rime: slow frost build-up -----------------------------------------------------------------
bool fx_rime(fx_t &f, st_t &s)
{
const rgb def[3] = { { 220, 235, 255 }, WHITE, { 185, 220, 255 } };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 3, c);
int b = f.pr->brightness;
int num = f.n;
if (num <= 0) {
return false;
}
int chill = clampi(nz(f.pr->n[1], 36), 1, 255);
int melt = clampi(nz(f.pr->n[2], 12), 1, 255);
int spark_cap = clampi(nz(f.pr->n[3], 3), 1, num);
if (first_call(s)) {
for (int i = 0; i < num; i++) {
s.glow[i] = 0;
}
s.last = f.now;
}
if (!due(f.now, s.last, period_of(f))) {
return false;
}
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
for (int i = 0; i < num; i++) {
s.glow[i] = s.glow[i] > melt ? s.glow[i] - melt : 0;
}
int spawned = 0;
int tries = spark_cap + num / 8;
for (int t = 0; t < tries; t++) {
if (spawned >= spark_cap) {
break;
}
if (rnd(0, 255) >= chill) {
continue;
}
int j = rnd(0, num - 1);
int g = s.glow[j] + rnd(80, 200);
s.glow[j] = g > 255 ? 255 : g;
spawned++;
}
for (int i = 0; i < num; i++) {
int g = clampi(s.glow[i], 0, 255);
rgb hi = ab(c[i % nc], b);
rgb px = { (hi.r * g + bgc.r * (255 - g)) / 255, (hi.g * g + bgc.g * (255 - g)) / 255,
(hi.b * g + bgc.b * (255 - g)) / 255 };
put(f, i, px);
}
return !f.pr->autorun;
}
// ---- twinkle -----------------------------------------------------------------------------------
static const rgb kCool[6] = {
{ 120, 200, 255 }, { 80, 140, 255 }, { 180, 120, 255 },
{ 100, 220, 240 }, { 160, 200, 255 }, { 90, 180, 220 },
};
static int cluster_lo(const fx_t &f, int *hi_out)
{
int lo = f.pr->n[3];
int hi = f.pr->n[4];
int num = f.n;
if (lo <= 0 && hi <= 0) {
lo = 1;
hi = num < 4 ? num : 4;
} else {
if (lo <= 0) lo = 1;
if (hi <= 0) hi = lo;
if (hi < lo) {
int t = lo;
lo = hi;
hi = t;
}
}
lo = clampi(lo, 1, num > 0 ? num : 1);
hi = clampi(hi, lo, num > 0 ? num : 1);
*hi_out = hi;
return lo;
}
static int cluster_len(const fx_t &f)
{
int hi;
int lo = cluster_lo(f, &hi);
return lo == hi ? lo : rnd(lo, hi);
}
static int cluster_base(const fx_t &f, int start, int k)
{
k = clampi(k, 0, f.n);
if (k <= 0) {
return 0;
}
int b = start < f.n - k ? start : f.n - k;
return b < 0 ? 0 : b;
}
bool fx_twinkle(fx_t &f, st_t &s)
{
rgb palette[PATTERN_MAX_COLOURS];
int np = get_colours(f, kCool, 6, palette);
int b = f.pr->brightness;
int num = f.n;
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
if (num <= 0) {
return false;
}
if (first_call(s)) {
int dens0 = clampi(f.pr->n[2] > 0 ? f.pr->n[2] : 128, 0, 255);
for (int i = 0; i < num; i++) {
s.on[i] = rnd(0, 255) < dens0;
s.col_i[i] = rnd(0, np - 1);
}
s.last = f.now;
}
if (!f.pr->autorun) {
for (int i = 0; i < num; i++) {
put(f, i, s.on[i] ? ab(palette[s.col_i[i] % np], b) : bgc);
}
return true;
}
uint32_t d = period_of(f);
if (!due(f.now, s.last, d)) {
return false;
}
int rate = clampi(f.pr->n[1] > 0 ? f.pr->n[1] : 48, 1, 255);
int dens = clampi(f.pr->n[2] > 0 ? f.pr->n[2] : 128, 0, 255);
for (int i = 0; i < num; i++) {
s.next_on[i] = s.on[i];
s.next_ci[i] = s.col_i[i];
}
s.nlight = 0;
s.ndark = 0;
for (int i = 0; i < num; i++) {
if (rnd(0, 255) < rate) {
int r = rnd(0, 255);
if (!s.on[i]) {
if (r < dens) s.light[s.nlight++] = i;
} else {
if (r < 255 - dens) s.dark[s.ndark++] = i;
}
}
}
for (int k = 0; k < s.ndark; k++) {
int start = s.dark[k];
int len = cluster_len(f);
int base = cluster_base(f, start, len);
for (int dj = 0; dj < len; dj++) {
s.next_on[base + dj] = 0;
}
}
for (int k = 0; k < s.nlight; k++) {
int start = s.light[k];
int len = cluster_len(f);
int base = cluster_base(f, start, len);
for (int dj = 0; dj < len; dj++) {
s.next_on[base + dj] = 1;
s.next_ci[base + dj] = rnd(0, np - 1);
}
}
for (int i = 0; i < num; i++) {
put(f, i, s.next_on[i] ? ab(palette[s.next_ci[i] % np], b) : bgc);
s.on[i] = s.next_on[i];
s.col_i[i] = s.next_ci[i];
}
return false;
}
// ---- radiate: pulses from nodes ----------------------------------------------------------------
static int radiate_front(int age, int outward, int ret, int maxd)
{
if (age <= outward) {
return (age * maxd + outward - 1) / outward;
}
if (age <= outward + ret) {
int rem = ret - (age - outward);
return (rem * maxd + ret - 1) / ret;
}
return -1;
}
bool fx_radiate(fx_t &f, st_t &s)
{
const rgb def[1] = { WHITE };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 1, c);
int b = f.pr->brightness;
rgb off_c = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
int spacing = nz(f.pr->n[1], 1);
int outward = nz(f.pr->n[2], 1);
int ret = nz(f.pr->n[3], 1);
int maxd = spacing / 2;
int life = outward + ret;
int num = f.n;
if (!f.pr->autorun) {
// One pulse, then hold
if (first_call(s)) {
s.aux = f.now;
}
int age = (int)(f.now - s.aux);
if (age < 1) age = 1;
int front = radiate_front(age, outward, ret, maxd);
if (front < 0) front = 0;
rgb lit = ab(c[s.ci % nc], b);
for (int i = 0; i < num; i++) {
int offset = (i + spacing / 2) % spacing;
int dist = offset < spacing - offset ? offset : spacing - offset;
put(f, i, dist <= front ? lit : off_c);
}
if (age >= life) {
s.ci++;
return true;
}
return false;
}
uint32_t delay = period_of(f);
if (first_call(s)) {
s.last = f.now;
s.ncent = 1;
s.centers[0] = (int)f.now;
}
if ((int32_t)(f.now - s.last) >= (int32_t)delay) {
s.ncent = 1;
s.centers[0] = (int)f.now;
s.last += delay;
s.ci++;
}
int kept = 0;
for (int k = 0; k < s.ncent; k++) {
if ((int)(f.now - s.centers[k]) < life) {
s.centers[kept++] = s.centers[k];
}
}
s.ncent = kept;
rgb lit = ab(c[s.ci % nc], b);
for (int i = 0; i < num; i++) {
int offset = (i + spacing / 2) % spacing;
int dist = offset < spacing - offset ? offset : spacing - offset;
bool on = false;
for (int k = 0; k < s.ncent && !on; k++) {
int age = (int)(f.now - s.centers[k]);
if (age <= 0) {
continue;
}
int front = radiate_front(age, outward, ret, maxd);
if (front < 0) {
continue;
}
if (dist <= front) {
on = true;
}
}
put(f, i, on ? lit : off_c);
}
return false;
}
// ---- palette morph -----------------------------------------------------------------------------
bool fx_palette_morph(fx_t &f, st_t &s)
{
const rgb def[3] = { { 255, 0, 0 }, { 0, 255, 0 }, { 0, 0, 255 } };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 3, c);
int b = f.pr->brightness;
int num = f.n;
if (nc < 2) {
fill(f, ab(c[0], b));
return false;
}
int morph = nz(f.pr->n[1], 1200);
if (morph < 50) morph = 50;
int warp = nz(f.pr->n[2], 3);
int turb = nz(f.pr->n[3], 24);
if (first_call(s)) {
s.aux = f.now; // morph start
s.last = f.now; // frame timer
s.ci = 0; // base colour index
s.phase = 0;
}
uint32_t delay = period_of(f);
if (!due(f.now, s.last, delay)) {
return false;
}
int age = (int)(f.now - s.aux);
int t = age < morph ? (age * 255) / morph : 255;
rgb a = c[s.ci % nc];
rgb bb = c[(s.ci + 1) % nc];
rgb anchor = mix(a, bb, t);
for (int i = 0; i < num; i++) {
int pos = (i * 256) / (num > 0 ? num : 1);
int wobble = (((pos * turb) / 32) + s.phase + (t / 2)) & 255;
int breath = 255 - abs(128 - wobble) * 2;
int local = (pos + breath / 3 + t / 4) % 256;
int idx = (s.ci + ((local * nc) / 256)) % nc;
int frac = (local * nc) & 255;
rgb grad = mix(c[idx], c[(idx + 1) % nc], frac);
rgb out = mix(grad, anchor, 80);
put(f, i, ab(out, b));
}
if (age >= morph) {
s.ci = (s.ci + 1) % nc;
s.aux = f.now;
if (!f.pr->autorun) {
return true;
}
}
s.phase = (s.phase + warp) & 255;
return false;
}
// ---- flame -------------------------------------------------------------------------------------
static int tri255(uint32_t elapsed, uint32_t period)
{
if (period < 400) period = 400;
uint32_t p = elapsed % period;
uint32_t half = period >> 1;
if (half == 0) return 128;
if (p < half) return (int)((p * 255) / half);
return (int)(((period - p) * 255) / (period - half));
}
static rgb palette_sample(const rgb *pal, int n, int pos)
{
if (n == 1) return pal[0];
int span = (n - 1) * pos;
int seg = span >> 8;
if (seg >= n - 1) return pal[n - 1];
int frac = span & 0xFF;
rgb a = pal[seg];
rgb b = pal[seg + 1];
rgb o = { a.r + (((b.r - a.r) * frac) >> 8), a.g + (((b.g - a.g) * frac) >> 8),
a.b + (((b.b - a.b) * frac) >> 8) };
return o;
}
static void flame_frame(fx_t &f, st_t &s, const rgb *pal, int np, uint32_t breath_el, bool spark_on)
{
int num = f.n;
int denom = num > 1 ? num - 1 : 1;
int breathe = tri255(breath_el, (uint32_t)s.breath_ms);
int base_level = s.lo + (((s.hi - s.lo) * breathe) >> 8);
int micro = 232 + rnd(0, 35);
int level = clampi((base_level * micro) >> 8, s.lo, s.hi);
int boost = 0;
rgb white = { 0, 0, 0 };
if (spark_on && s.spark_dur > 0) {
int el = (int)(f.now - s.spark_start);
if (el < 0) el = 0;
if (el < s.spark_dur) {
int env = 255 - (el * 255) / s.spark_dur;
boost = (env * 90) >> 8;
white = { (env * 55) >> 8, (env * 50) >> 8, (env * 40) >> 8 };
}
}
int cell = num >> 3;
if (cell < 1) cell = 1;
for (int i = 0; i < num; i++) {
int h = (i * 256) / denom;
int flow = (h + s.rise + (i / cell) * 17) & 255;
int pos = (flow + s.cj[(i >> 2) & 7]) & 255;
rgb c = palette_sample(pal, np, pos);
if (boost) {
c = { clampi(c.r + white.r + ((boost * 3) >> 2), 0, 255), clampi(c.g + white.g + (boost >> 1), 0, 255),
clampi(c.b + white.b + (boost >> 2), 0, 255) };
}
put(f, i, ab(c, level));
}
}
bool fx_flame(fx_t &f, st_t &s)
{
const rgb def[4] = { { 90, 8, 8 }, { 200, 40, 12 }, { 255, 120, 30 }, { 255, 220, 140 } };
rgb pal[PATTERN_MAX_COLOURS];
int np = get_colours(f, def, 4, pal);
int lo = clampi(f.pr->n[1], 0, 255);
int hi = clampi(f.pr->brightness, 0, 255);
if (lo > hi) {
int t = lo;
lo = hi;
hi = t;
}
int bp = f.pr->n[2];
int breath_ms = bp > 0 ? bp : 2500;
if (breath_ms < 800) breath_ms = 800;
int gap_lo = f.pr->n[3];
int gap_hi = f.pr->n[4];
if (gap_lo == 0 && gap_hi == 0) {
gap_lo = 10000;
gap_hi = 30000;
} else {
if (gap_lo < 500) gap_lo = 500;
}
if (gap_hi < gap_lo) gap_hi = gap_lo;
uint32_t delay = f.pr->delay < 16 ? 16 : f.pr->delay;
if (first_call(s)) {
s.breath_ms = breath_ms;
s.lo = lo;
s.hi = hi;
s.rise = rnd(0, 255);
for (int k = 0; k < 8; k++) {
s.cj[k] = rnd(-18, 18);
}
s.last = f.now; // last frame
s.breath_origin = f.now;
s.last_cluster = f.now;
s.spark_active = false;
s.spark_dur = 0;
s.next_spark = f.now + (uint32_t)rnd(gap_lo, gap_hi);
}
s.lo = lo;
s.hi = hi;
s.breath_ms = breath_ms;
if (!f.pr->autorun) {
flame_frame(f, s, pal, np, 0, false);
return true;
}
if ((int32_t)(f.now - s.last) < (int32_t)delay) {
return false;
}
s.last += delay;
s.rise = (s.rise + rnd(-10, 12)) & 255;
if ((int32_t)(f.now - s.last_cluster) >= (int32_t)(delay * 4)) {
s.last_cluster = f.now;
for (int k = 0; k < 8; k++) {
s.cj[k] = rnd(-18, 18);
}
}
if (s.spark_active) {
if ((int)(f.now - s.spark_start) >= s.spark_dur) {
s.spark_active = false;
s.next_spark = f.now + (uint32_t)rnd(gap_lo, gap_hi);
}
} else if ((int32_t)(f.now - s.next_spark) >= 0) {
s.spark_active = true;
s.spark_start = f.now;
s.spark_dur = rnd(180, 360);
}
flame_frame(f, s, pal, np, f.now - s.breath_origin, s.spark_active);
return false;
}
+295
View File
@@ -0,0 +1,295 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* Patterns that span the rig, ported from the MicroPython led-driver (rig.py and patterns folder).
* The rig geometry is the MicroPython default for a lone strip: the bar runs from (-1, 0) to (1, 0), so
* LED i sits at x = -1 + 2 (i + 0.5) / n. The rig placement (place) is not configurable on this board.
*/
#include <cmath>
#include "effects.h"
static const rgb WHITE = { 255, 255, 255 };
static bool first_call(st_t &s)
{
if (s.started) {
return false;
}
s.started = true;
return true;
}
// Position of LED i on the bar
static float led_x(int i, int n)
{
return -1.0f + 2.0f * (i + 0.5f) / n;
}
// Distance from the centre, 0..1
static float led_r(int i, int n)
{
float x = led_x(i, n);
return x < 0 ? -x : x;
}
// Angle round the centre, 0..1 of a turn: the left half is at 1/2, the right at 0
static float led_a(int i, int n)
{
return led_x(i, n) < 0 ? 0.5f : 0.0f;
}
// Position of LED i along a direction across the rig, 0..1
static float along(int i, int n, float angle_deg)
{
float rad = angle_deg * 3.14159265f / 180.0f;
return (led_x(i, n) * cosf(rad) + 1.0f) / 2.0f;
}
static int shade_of(float p)
{
int s = (int)(p * (RIG_SHADES - 1) + 0.5f);
return s < 0 ? 0 : (s > RIG_SHADES - 1 ? RIG_SHADES - 1 : s);
}
// Shade of a brightness-free sine: 0..15
static int sin_shade(int i)
{
float v = (sinf(i * 6.2831853f / 256.0f) + 1.0f) / 2.0f * (RIG_SHADES - 1) + 0.5f;
return (int)v;
}
// ---- field wave --------------------------------------------------------------------------------
bool fx_field_wave(fx_t &f, st_t &s)
{
const rgb def[1] = { WHITE };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 1, c);
int n = f.n;
int kind = f.pr->n[3];
int lam = nz(f.pr->n[2], 1000);
uint32_t period = dur(f, (int)f.pr->delay);
if (period < 1) period = 1;
(void)first_call(s);
uint32_t t = f.t;
bool done = !f.pr->autorun && t >= period;
int ph = done ? 256 : (int)((t % period) * 256 / period);
for (int i = 0; i < n; i++) {
int shade;
if (kind == 3) {
// Plasma: two sines of the position, summed
// Lone bar: y is always 0, so the second sine is taken at -p13
int px = (int)(led_x(i, n) * 3 * 256000 / (lam * 6.283f));
int p13 = ph * 13 / 10;
float v = sinf(((px + ph) & 255) * 6.2831853f / 256.0f)
+ sinf(((-p13) & 255) * 6.2831853f / 256.0f); // -2..2
shade = sin_shade(((int)(v * 41) + ph) & 255);
} else {
float m = kind == 1 ? led_r(i, n) : (kind == 2 ? led_a(i, n) : along(i, n, (float)f.pr->n[1]));
int mi = (int)(m * 256000 / lam);
shade = sin_shade((mi - ph) & 255);
}
put(f, i, rig_entry(f, c, nc, RIG_SHADES, shade, RIG_LEVELS - 1));
}
return done;
}
// ---- grow --------------------------------------------------------------------------------------
bool fx_grow(fx_t &f, st_t &s)
{
const rgb def[1] = { WHITE };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 1, c);
int n = f.n;
int mode = f.pr->n[1];
const int top = RIG_LEVELS - 1;
const float edge = 0.06f;
(void)first_call(s);
for (int i = 0; i < n; i++) {
float m;
if (mode == 1) {
m = 1 - led_r(i, n);
} else if (mode == 2) {
m = led_a(i, n);
} else if (mode == 3) {
m = along(i, n, (float)f.pr->n[3]);
} else {
m = led_r(i, n);
}
s.m[i] = m;
s.shade[i] = shade_of(m);
}
uint32_t total = dur(f, (int)f.pr->delay);
if (total < 1) total = 1;
bool empties = f.pr->n[2] == 1 || f.pr->n[2] == 2 || f.pr->autorun;
int phases = empties ? 2 : 1;
uint32_t t = f.t;
if (!f.pr->autorun && t >= total * phases) {
if (f.pr->n[2] == 3 || empties) {
fill(f, ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), f.pr->brightness));
} else {
for (int i = 0; i < n; i++) {
put(f, i, rig_entry(f, c, nc, RIG_SHADES, s.shade[i], top));
}
}
return true;
}
float ph;
if (f.pr->autorun) {
ph = (float)(t % (total * phases)) / total;
} else {
ph = (float)t / total;
if (ph > phases) ph = (float)phases;
}
float front;
bool rising;
if (ph <= 1) {
front = ph * (1 + edge);
rising = true;
} else if (f.pr->n[2] == 2) {
front = (ph - 1) * (1 + edge);
rising = false;
} else {
front = (2 - ph) * (1 + edge);
rising = true;
}
for (int i = 0; i < n; i++) {
float v = (rising ? (front - s.m[i]) : (s.m[i] - front)) / edge;
int lv = v <= 0 ? 0 : (v >= 1 ? top : (int)(v * top));
put(f, i, rig_entry(f, c, nc, RIG_SHADES, s.shade[i], lv));
}
return false;
}
// ---- ripple ------------------------------------------------------------------------------------
bool fx_ripple(fx_t &f, st_t &s)
{
const rgb def[1] = { WHITE };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 1, c);
int n = f.n;
int b = f.pr->brightness;
const int top = RIG_LEVELS - 1;
(void)first_call(s);
uint32_t period = dur(f, (int)f.pr->delay);
if (period < 1) period = 1;
float hw = (f.pr->n[1] > 0 ? f.pr->n[1] : 150) / 2000.0f;
int rings = f.pr->autorun ? nz(f.pr->n[2], 1) : 1;
if (rings > 8) rings = 8;
float fade = (f.pr->n[4] > 0 ? f.pr->n[4] : 0) / 1000.0f;
uint32_t t = f.t;
if (!f.pr->autorun && t >= period) {
fill(f, ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b));
return true;
}
float base = f.pr->autorun ? (float)(t % period) / period : (float)t / period;
float span = 1 + 4 * hw;
float rads[8];
for (int k = 0; k < rings; k++) {
float x = base + (float)k / rings;
x = x - floorf(x);
rads[k] = -2 * hw + x * span;
}
int shade = (int)((t / period) % (uint32_t)nc);
for (int i = 0; i < n; i++) {
float r = (f.pr->n[3] == 1) ? (1 - led_r(i, n)) : led_r(i, n);
float best = 0;
for (int k = 0; k < rings; k++) {
float v = 1 - fabsf(r - rads[k]) / hw;
if (v > best) best = v;
}
if (fade > 0 && best > 0) {
best *= 1 - fade * r;
if (best < 0) best = 0;
}
put(f, i, rig_entry(f, c, nc, nc, shade, (int)(best * top)));
}
return false;
}
// ---- spin --------------------------------------------------------------------------------------
bool fx_spin(fx_t &f, st_t &s)
{
const rgb def[1] = { WHITE };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 1, c);
int n = f.n;
const int top = RIG_LEVELS - 1;
(void)first_call(s);
uint32_t period = dur(f, (int)f.pr->delay);
if (period < 1) period = 1;
float span = 1.0f / (f.pr->n[1] > 0 ? f.pr->n[1] : 1);
float width = (f.pr->n[2] > 0 ? f.pr->n[2] : 20) / 360.0f;
float tail = (f.pr->n[3] > 0 ? f.pr->n[3] : 90) / 360.0f;
uint32_t t = f.t;
if (!f.pr->autorun && t >= period) {
fill(f, ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), f.pr->brightness));
return true;
}
float rot = fmodf((float)t / period, 1.0f);
for (int i = 0; i < n; i++) {
float ang = f.pr->n[4] == 1 ? 1 - led_a(i, n) : led_a(i, n);
float x = rot - ang;
float behind = x - floorf(x / span) * span;
if (behind < width) {
put(f, i, rig_entry(f, c, nc, RIG_SHADES, 0, top));
} else {
float fr = (behind - width) / tail;
if (fr >= 1) {
put(f, i, rig_entry(f, c, nc, RIG_SHADES, 0, 0));
} else {
int shade = (int)(fr * (RIG_SHADES - 1));
int lv = (int)((1 - fr) * top);
put(f, i, rig_entry(f, c, nc, RIG_SHADES, shade, lv));
}
}
}
return false;
}
// ---- sweep -------------------------------------------------------------------------------------
bool fx_sweep(fx_t &f, st_t &s)
{
const rgb def[1] = { WHITE };
rgb c[PATTERN_MAX_COLOURS];
int nc = get_colours(f, def, 1, c);
int n = f.n;
const int top = RIG_LEVELS - 1;
(void)first_call(s);
for (int i = 0; i < n; i++) {
s.m[i] = along(i, n, (float)f.pr->n[1]);
s.shade[i] = shade_of(s.m[i]);
}
uint32_t total = dur(f, (int)f.pr->delay);
if (total < 1) total = 1;
float hw = (f.pr->n[2] > 0 ? f.pr->n[2] : 200) / 2000.0f;
float trail = (f.pr->n[3] > 0 ? f.pr->n[3] : 0) / 1000.0f;
bool keep = f.pr->n[4] == 1;
uint32_t t = f.t;
bool done = !f.pr->autorun && t >= total;
float p = done ? 1.0f : (float)(t % total) / total;
float head = -hw + p * (1 + 2 * hw + trail);
for (int i = 0; i < n; i++) {
float d = s.m[i] - head;
float k;
if (d > hw) {
k = 0;
} else if (d >= -hw) {
k = (keep && d < 0) ? 1.0f : 1 - fabsf(d) / hw;
} else if (keep) {
k = 1;
} else if (trail > 0) {
k = 1 + (d + hw) / trail;
if (k < 0) k = 0;
} else {
k = 0;
}
put(f, i, rig_entry(f, c, nc, RIG_SHADES, s.shade[i], (int)(k * top)));
}
return done;
}
+185
View File
@@ -0,0 +1,185 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* Helpers shared by the pattern files: integer maths that matches Python's // and %, colour mixing,
* random numbers and the rig colour table.
*/
#include <cmath>
#include <cstring>
#include "esp_random.h"
#include "effects.h"
int clampi(int v, int lo, int hi)
{
return v < lo ? lo : (v > hi ? hi : v);
}
int fdiv(int a, int b)
{
int q = a / b;
if ((a % b != 0) && ((a < 0) != (b < 0))) {
q--;
}
return q;
}
int pmod(int a, int m)
{
int r = a % m;
return r < 0 ? r + m : r;
}
int nz(int v, int def)
{
return v > 0 ? v : def;
}
rgb mk(int r, int g, int b)
{
rgb c = { clampi(r, 0, 255), clampi(g, 0, 255), clampi(b, 0, 255) };
return c;
}
rgb ab(rgb c, int level)
{
rgb o = { fdiv(c.r * level, 255), fdiv(c.g * level, 255), fdiv(c.b * level, 255) };
return o;
}
rgb mix(rgb a, rgb b, int k)
{
rgb o = {
a.r + fdiv((b.r - a.r) * k, 255),
a.g + fdiv((b.g - a.g) * k, 255),
a.b + fdiv((b.b - a.b) * k, 255),
};
return o;
}
int sgn(const fx_t &f, int v)
{
return f.pr->reverse ? -v : v;
}
int led_at(const fx_t &f, int i)
{
return (f.pr->reverse && i >= 0 && i < f.n) ? f.n - 1 - i : i;
}
void put(fx_t &f, int phys, rgb c)
{
if (phys >= 0 && phys < f.n) {
f.px[phys] = c;
}
}
void putl(fx_t &f, int logical, rgb c)
{
put(f, led_at(f, logical), c);
}
void fill(fx_t &f, rgb c)
{
for (int i = 0; i < f.n; i++) {
f.px[i] = c;
}
}
bool due(uint32_t now, uint32_t &last, uint32_t d)
{
if ((int32_t)(now - last) >= (int32_t)d) {
last += d;
return true;
}
return false;
}
// The beat is 500 ms here (there is no beat source on this board)
uint32_t dur(const fx_t &f, int v)
{
if (v < 0) {
v = 0;
}
return f.pr->beat_time ? (uint32_t)(v * 500 / 4) : (uint32_t)v;
}
int get_colours(const fx_t &f, const rgb *def, int ndef, rgb *out)
{
if (f.pr->ncol > 0) {
int n = f.pr->ncol > PATTERN_MAX_COLOURS ? PATTERN_MAX_COLOURS : f.pr->ncol;
for (int i = 0; i < n; i++) {
out[i] = mk(f.pr->col[i][0], f.pr->col[i][1], f.pr->col[i][2]);
}
return n;
}
for (int i = 0; i < ndef; i++) {
out[i] = def[i];
}
return ndef;
}
int rnd(int lo, int hi)
{
if (hi <= lo) {
return lo;
}
return lo + (int)(esp_random() % (uint32_t)(hi - lo + 1));
}
rgb grad_at(const rgb *cols, int m, float t)
{
if (m == 1 || t <= 0) {
return cols[0];
}
if (t >= 1) {
return cols[m - 1];
}
float x = t * (m - 1);
int j = (int)x;
float f = x - j;
rgb a = cols[j];
rgb b = cols[j + 1];
rgb o = { (int)(a.r + (b.r - a.r) * f), (int)(a.g + (b.g - a.g) * f), (int)(a.b + (b.b - a.b) * f) };
return o;
}
// Colour of one entry of the rig table: a shade of the colour list at a brightness level (0..15),
// over the background. Mirrors rig.Lut in the MicroPython driver.
rgb rig_entry(const fx_t &f, const rgb *cols, int ncols, int shades, int shade, int level)
{
int b = f.pr->brightness;
rgb bgc = ab(mk(f.pr->bg[0], f.pr->bg[1], f.pr->bg[2]), b);
rgb c = (shades > 1) ? grad_at(cols, ncols, (float)shade / (shades - 1)) : cols[0];
rgb sc = { fdiv((int)c.r * b, 255), fdiv((int)c.g * b, 255), fdiv((int)c.b * b, 255) };
int top = RIG_LEVELS - 1;
rgb o = {
bgc.r + fdiv((sc.r - bgc.r) * level, top),
bgc.g + fdiv((sc.g - bgc.g) * level, top),
bgc.b + fdiv((sc.b - bgc.b) * level, top),
};
return o;
}
// Hue wheel, 0..255 -> colour
rgb wheel(int pos)
{
pos &= 255;
rgb c;
if (pos < 85) {
c.r = pos * 3;
c.g = 255 - pos * 3;
c.b = 0;
} else if (pos < 170) {
pos -= 85;
c.r = 255 - pos * 3;
c.g = 0;
c.b = pos * 3;
} else {
pos -= 170;
c.r = 0;
c.g = pos * 3;
c.b = 255 - pos * 3;
}
return c;
}
+5
View File
@@ -0,0 +1,5 @@
dependencies:
espressif/mdns:
version: "^1.4.0"
espressif/cjson:
version: "^1.7.19"
+39
View File
@@ -0,0 +1,39 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#include "esp_log.h"
#include "nvs_flash.h"
#include "ddp.h"
#include "net.h"
#include "ota.h"
#include "patterns.h"
#include "presets.h"
#include "web.h"
static const char *TAG = "example";
extern "C" void app_main(void)
{
// NVS holds the saved Wi-Fi client credentials
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
ESP_ERROR_CHECK(err);
hw_cfg_t hw;
settings_load_hw(&hw);
patterns_start(hw);
ESP_ERROR_CHECK(presets_init());
presets_apply_startup();
ESP_ERROR_CHECK(net_start());
ESP_ERROR_CHECK(web_start());
ESP_ERROR_CHECK(ddp_start());
ota_confirm_later();
char ssid[16];
net_ap_ssid(ssid, sizeof(ssid));
ESP_LOGI(TAG, "Ready: join Wi-Fi %s and open http://192.168.4.1/, or http://led.local/ on your network", ssid);
}
+244
View File
@@ -0,0 +1,244 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#include <cstdio>
#include <cstring>
#include "esp_event.h"
#include "esp_log.h"
#include "esp_mac.h"
#include "esp_netif.h"
#include "esp_timer.h"
#include "esp_wifi.h"
#include "mdns.h"
#include "net.h"
static const char *TAG = "net";
#define AP_CHANNEL 1
#define AP_MAX_CLIENTS 4
#define RETRY_MAX_MS 30000
static esp_netif_t *s_ap_netif;
static esp_netif_t *s_sta_netif;
static esp_timer_handle_t s_retry_timer;
static volatile bool s_sta_up;
static esp_ip4_addr_t s_sta_ip;
static int s_retries;
// Set the STA config from credentials. Empty password means an open network.
static void apply_sta_config(const wifi_creds_t *c)
{
wifi_config_t cfg = {};
strncpy((char *)cfg.sta.ssid, c->ssid, sizeof(cfg.sta.ssid) - 1);
strncpy((char *)cfg.sta.password, c->pass, sizeof(cfg.sta.password) - 1);
cfg.sta.threshold.authmode = c->pass[0] ? WIFI_AUTH_WPA2_PSK : WIFI_AUTH_OPEN;
esp_wifi_set_config(WIFI_IF_STA, &cfg);
}
// Client address: DHCP, or the static address from settings. Called before the client connects.
static esp_err_t apply_client_ip(const net_cfg_t *c)
{
if (!c->use_static) {
esp_err_t err = esp_netif_dhcpc_start(s_sta_netif);
// Already running is fine
return (err == ESP_OK || err == ESP_ERR_ESP_NETIF_DHCP_ALREADY_STARTED) ? ESP_OK : err;
}
esp_netif_ip_info_t info = {};
if (esp_netif_str_to_ip4(c->ip, &info.ip) != ESP_OK ||
esp_netif_str_to_ip4(c->netmask, &info.netmask) != ESP_OK ||
esp_netif_str_to_ip4(c->gateway, &info.gw) != ESP_OK) {
return ESP_ERR_INVALID_ARG;
}
esp_netif_dhcpc_stop(s_sta_netif); // ignore "not started"
esp_err_t err = esp_netif_set_ip_info(s_sta_netif, &info);
if (err != ESP_OK) {
return err;
}
esp_netif_dns_info_t dns = {};
const char *dns_str = c->dns[0] ? c->dns : c->gateway;
if (esp_netif_str_to_ip4(dns_str, &dns.ip.u_addr.ip4) == ESP_OK) {
dns.ip.type = ESP_IPADDR_TYPE_V4;
esp_netif_set_dns_info(s_sta_netif, ESP_NETIF_DNS_MAIN, &dns);
}
ESP_LOGI(TAG, "Client static IP %s/%s gw %s", c->ip, c->netmask, c->gateway);
return ESP_OK;
}
static void retry_cb(void *arg)
{
(void)arg;
esp_wifi_connect();
}
static void on_wifi_event(void *arg, esp_event_base_t base, int32_t id, void *data)
{
(void)arg;
(void)base;
(void)data;
switch (id) {
case WIFI_EVENT_STA_START: {
wifi_creds_t c;
if (settings_load_wifi(&c) == ESP_OK && c.ssid[0]) {
net_cfg_t n;
settings_load_net(&n);
if (apply_client_ip(&n) != ESP_OK) {
ESP_LOGW(TAG, "Static IP settings are invalid; using DHCP");
n.use_static = false;
apply_client_ip(&n);
}
esp_wifi_connect();
}
break;
}
case WIFI_EVENT_STA_DISCONNECTED: {
// Back off 1 s, 2 s, 4 s ... up to RETRY_MAX_MS
s_sta_up = false;
uint32_t delay_ms = 1000u << (s_retries < 5 ? s_retries : 5);
if (delay_ms > RETRY_MAX_MS) delay_ms = RETRY_MAX_MS;
s_retries++;
esp_timer_stop(s_retry_timer);
esp_timer_start_once(s_retry_timer, (uint64_t)delay_ms * 1000);
break;
}
default:
break;
}
}
static void on_ip_event(void *arg, esp_event_base_t base, int32_t id, void *data)
{
(void)arg;
(void)base;
(void)id;
ip_event_got_ip_t *e = (ip_event_got_ip_t *)data;
s_sta_ip = e->ip_info.ip;
s_sta_up = true;
s_retries = 0;
ESP_LOGI(TAG, "Client IP " IPSTR, IP2STR(&e->ip_info.ip));
}
void net_ap_ssid(char *buf, size_t len)
{
uint8_t mac[6];
esp_read_mac(mac, ESP_MAC_WIFI_SOFTAP);
snprintf(buf, len, "led-%02X%02X%02X", mac[3], mac[4], mac[5]);
}
esp_err_t net_start(void)
{
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
s_ap_netif = esp_netif_create_default_wifi_ap();
s_sta_netif = esp_netif_create_default_wifi_sta();
wifi_init_config_t init_cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&init_cfg));
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, on_wifi_event, NULL, NULL));
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, on_ip_event, NULL, NULL));
const esp_timer_create_args_t timer_args = {
.callback = retry_cb,
.arg = NULL,
.dispatch_method = ESP_TIMER_TASK,
.name = "wifi_retry",
.skip_unhandled_events = false,
};
ESP_ERROR_CHECK(esp_timer_create(&timer_args, &s_retry_timer));
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_APSTA));
// Open access point named led-XXXXXX
char ssid[16];
net_ap_ssid(ssid, sizeof(ssid));
wifi_config_t ap = {};
strncpy((char *)ap.ap.ssid, ssid, sizeof(ap.ap.ssid) - 1);
ap.ap.ssid_len = strlen(ssid);
ap.ap.channel = AP_CHANNEL;
ap.ap.max_connection = AP_MAX_CLIENTS;
ap.ap.authmode = WIFI_AUTH_OPEN;
ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &ap));
// Client credentials, if any were saved
wifi_creds_t c;
if (settings_load_wifi(&c) == ESP_OK && c.ssid[0]) {
apply_sta_config(&c);
}
ESP_ERROR_CHECK(esp_wifi_start());
ESP_LOGI(TAG, "AP %s started", ssid);
// mDNS: <hostname>.local, with an HTTP service on port 80
net_cfg_t n;
settings_load_net(&n);
ESP_ERROR_CHECK(mdns_init());
ESP_ERROR_CHECK(mdns_hostname_set(n.hostname));
ESP_ERROR_CHECK(mdns_instance_name_set("LED controller"));
// app=led-strip lets other drivers' discovery (GET /api/devices) pick out LED drivers from other HTTP devices
static mdns_txt_item_t txt[] = { { "app", "led-strip" } };
ESP_ERROR_CHECK(mdns_service_add(NULL, "_http", "_tcp", 80, txt, 1));
ESP_LOGI(TAG, "mDNS: %s.local", n.hostname);
return ESP_OK;
}
bool net_sta_status(char *ip, size_t ip_len)
{
if (ip_len) {
ip[0] = '\0';
}
if (!s_sta_up) {
return false;
}
snprintf(ip, ip_len, IPSTR, IP2STR(&s_sta_ip));
return true;
}
esp_err_t net_sta_connect(const wifi_creds_t *c)
{
esp_err_t err = settings_save_wifi(c);
if (err != ESP_OK) {
return err;
}
esp_timer_stop(s_retry_timer);
esp_wifi_disconnect();
s_retries = 0;
apply_sta_config(c);
return esp_wifi_connect();
}
esp_err_t net_save_network(const net_cfg_t *c)
{
esp_err_t err = settings_save_net(c);
if (err != ESP_OK) {
return err;
}
err = mdns_hostname_set(c->hostname);
if (err != ESP_OK) {
return err;
}
// Reconnect with the new address settings if a client is configured
wifi_creds_t w;
if (settings_load_wifi(&w) != ESP_OK || !w.ssid[0]) {
return ESP_OK;
}
esp_timer_stop(s_retry_timer);
esp_wifi_disconnect();
s_retries = 0;
err = apply_client_ip(c);
if (err != ESP_OK) {
return err;
}
return esp_wifi_connect();
}
esp_err_t net_scan(wifi_ap_record_t *recs, uint16_t *count)
{
esp_err_t err = esp_wifi_scan_start(NULL, true);
if (err != ESP_OK) {
return err;
}
uint16_t max = *count;
err = esp_wifi_scan_get_ap_records(&max, recs);
*count = max;
return err;
}
+32
View File
@@ -0,0 +1,32 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <cstddef>
#include <cstdint>
#include "esp_err.h"
#include "esp_wifi_types.h"
#include "settings.h"
/** @brief Start Wi-Fi (AP `led-XXXXXX` plus an optional client), and mDNS. Needs NVS. */
esp_err_t net_start(void);
/** @brief Fill buf with the AP SSID, e.g. "led-A1B2C3". */
void net_ap_ssid(char *buf, size_t len);
/** @brief Client link state and its IPv4 address ("" if not connected). */
bool net_sta_status(char *ip, size_t ip_len);
/** @brief Save credentials, then connect the client with them. */
esp_err_t net_sta_connect(const wifi_creds_t *c);
/**
* @brief Save network settings and apply them: mDNS name, static or DHCP client address.
* A connected or configured client reconnects so the new address takes effect.
*/
esp_err_t net_save_network(const net_cfg_t *c);
/** @brief Scan for networks. On entry *count is the array size; on exit, the number found. */
esp_err_t net_scan(wifi_ap_record_t *recs, uint16_t *count);
+206
View File
@@ -0,0 +1,206 @@
#include "ota.h"
#include "web.h"
#include <stdio.h>
#include <stdlib.h>
#include "esp_log.h"
#include "esp_ota_ops.h"
#include "esp_app_format.h"
#include "esp_system.h"
#include <string.h>
#include "esp_timer.h"
static const char *TAG = "ota";
#define CHUNK 4096
#define CONFIRM_AFTER_US (10 * 1000000LL)
static bool s_busy;
static void reboot_cb(void *arg)
{
esp_restart();
}
static void confirm_cb(void *arg)
{
esp_err_t err = esp_ota_mark_app_valid_cancel_rollback();
if (err == ESP_OK) {
ESP_LOGI(TAG, "running image confirmed");
}
}
void ota_confirm_later(void)
{
esp_ota_img_states_t state;
const esp_partition_t *run = esp_ota_get_running_partition();
if (esp_ota_get_state_partition(run, &state) != ESP_OK || state != ESP_OTA_IMG_PENDING_VERIFY) {
return;
}
static esp_timer_handle_t t;
const esp_timer_create_args_t args = { .callback = confirm_cb, .name = "ota_confirm" };
if (esp_timer_create(&args, &t) == ESP_OK) {
esp_timer_start_once(t, CONFIRM_AFTER_US);
}
}
static esp_err_t fail(httpd_req_t *req, const char *status, const char *msg)
{
ESP_LOGE(TAG, "%s", msg);
httpd_resp_set_status(req, status);
httpd_resp_set_type(req, "application/json");
web_allow_lan_origin(req);
char buf[160];
snprintf(buf, sizeof(buf), "{\"error\":\"%s\"}", msg);
return httpd_resp_sendstr(req, buf);
}
static esp_err_t ota_post_handler(httpd_req_t *req)
{
if (req->content_len == 0) {
return fail(req, "400 Bad Request", "empty body");
}
const esp_partition_t *part = esp_ota_get_next_update_partition(NULL);
if (!part) {
return fail(req, "500 Internal Server Error", "no update partition");
}
if (req->content_len > part->size) {
return fail(req, "413 Payload Too Large", "image larger than the app slot");
}
if (s_busy) {
return fail(req, "409 Conflict", "update already running");
}
s_busy = true;
char *buf = malloc(CHUNK);
if (!buf) {
s_busy = false;
return fail(req, "500 Internal Server Error", "out of memory");
}
esp_ota_handle_t handle = 0;
esp_err_t err = esp_ota_begin(part, req->content_len, &handle);
if (err != ESP_OK) {
free(buf);
s_busy = false;
return fail(req, "500 Internal Server Error", "ota begin failed");
}
ESP_LOGI(TAG, "receiving %u bytes into %s", (unsigned)req->content_len, part->label);
size_t got = 0;
const char *bad = NULL;
while (got < req->content_len) {
int want = req->content_len - got;
int r = httpd_req_recv(req, buf, want > CHUNK ? CHUNK : want);
if (r == HTTPD_SOCK_ERR_TIMEOUT) {
continue;
}
if (r <= 0) {
bad = "receive failed";
break;
}
if (got == 0 && (r < (int)(sizeof(esp_image_header_t)) || (uint8_t)buf[0] != ESP_IMAGE_HEADER_MAGIC)) {
bad = "not an ESP32 app image";
break;
}
if (esp_ota_write(handle, buf, r) != ESP_OK) {
bad = "flash write failed";
break;
}
got += r;
}
free(buf);
if (bad) {
esp_ota_abort(handle);
s_busy = false;
return fail(req, "400 Bad Request", bad);
}
// esp_ota_end checks the image checksum and hash
if (esp_ota_end(handle) != ESP_OK) {
s_busy = false;
return fail(req, "400 Bad Request", "image failed validation");
}
if (esp_ota_set_boot_partition(part) != ESP_OK) {
s_busy = false;
return fail(req, "500 Internal Server Error", "set boot partition failed");
}
ESP_LOGI(TAG, "update ok, rebooting");
httpd_resp_set_type(req, "application/json");
web_allow_lan_origin(req);
httpd_resp_sendstr(req, "{\"message\":\"update written, rebooting\"}");
static esp_timer_handle_t t;
const esp_timer_create_args_t args = { .callback = reboot_cb, .name = "ota_reboot" };
if (esp_timer_create(&args, &t) == ESP_OK) {
esp_timer_start_once(t, 500 * 1000);
} else {
esp_restart();
}
return ESP_OK;
}
static esp_err_t ota_get_handler(httpd_req_t *req)
{
const esp_partition_t *run = esp_ota_get_running_partition();
const esp_app_desc_t *app = esp_app_get_description();
// The build date is only recompiled with its own file, so the ELF hash is what tells two builds apart
char sha[17];
for (int i = 0; i < 8; i++) {
snprintf(sha + 2 * i, 3, "%02x", app->app_elf_sha256[i]);
}
char buf[288];
snprintf(buf, sizeof(buf),
"{\"partition\":\"%s\",\"version\":\"%s\",\"built\":\"%s %s\",\"idf\":\"%s\",\"sha\":\"%s\"}",
run ? run->label : "?", app->version, app->date, app->time, app->idf_ver, sha);
httpd_resp_set_type(req, "application/json");
web_allow_lan_origin(req);
return httpd_resp_sendstr(req, buf);
}
static esp_err_t reboot_post_handler(httpd_req_t *req)
{
ESP_LOGI(TAG, "reboot requested");
httpd_resp_set_type(req, "application/json");
web_allow_lan_origin(req);
httpd_resp_sendstr(req, "{\"message\":\"rebooting\"}");
static esp_timer_handle_t t;
const esp_timer_create_args_t args = { .callback = reboot_cb, .name = "reboot" };
if (esp_timer_create(&args, &t) == ESP_OK) {
esp_timer_start_once(t, 500 * 1000);
} else {
esp_restart();
}
return ESP_OK;
}
// Browser preflight for a firmware upload from another device's page (octet-stream is not a simple request)
static esp_err_t ota_preflight_handler(httpd_req_t *req)
{
web_allow_lan_origin(req);
httpd_resp_set_hdr(req, "Access-Control-Allow-Methods", "POST");
httpd_resp_set_hdr(req, "Access-Control-Allow-Headers", "Content-Type");
httpd_resp_set_hdr(req, "Access-Control-Max-Age", "600");
httpd_resp_set_status(req, "204 No Content");
return httpd_resp_send(req, NULL, 0);
}
esp_err_t ota_register(httpd_handle_t server)
{
const httpd_uri_t post = { .uri = "/ota", .method = HTTP_POST, .handler = ota_post_handler };
const httpd_uri_t get = { .uri = "/ota", .method = HTTP_GET, .handler = ota_get_handler };
const httpd_uri_t preflight = { .uri = "/ota", .method = HTTP_OPTIONS, .handler = ota_preflight_handler };
esp_err_t err = httpd_register_uri_handler(server, &post);
if (err == ESP_OK) {
err = httpd_register_uri_handler(server, &get);
}
if (err == ESP_OK) {
err = httpd_register_uri_handler(server, &preflight);
}
const httpd_uri_t reboot = { .uri = "/reboot", .method = HTTP_POST, .handler = reboot_post_handler };
if (err == ESP_OK) {
err = httpd_register_uri_handler(server, &reboot);
}
return err;
}
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include "esp_err.h"
#include "esp_http_server.h"
#ifdef __cplusplus
extern "C" {
#endif
// Register POST /ota (raw firmware .bin as the body) and GET /ota (running image info).
// The web UI is part of the image, so one upload updates both.
// POST /reboot restarts the board (replies first, reboots after 0.5 s).
// A good upload is written to the idle app slot, becomes the boot image and the board reboots.
esp_err_t ota_register(httpd_handle_t server);
// Call once at boot: confirms the running image after it has stayed up for a few seconds, so
// a new image that crashes on start rolls back to the previous one.
void ota_confirm_later(void);
#ifdef __cplusplus
}
#endif
+464
View File
@@ -0,0 +1,464 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* Pattern engine: runs the selected pattern once per frame into a shadow frame, crossfades from the
* previous frame when a preset asks for it, and shows the result on the WS2812 strip.
*/
#include <cstdlib>
#include <cstring>
#include "driver/gpio.h"
#include "esp_heap_caps.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#include "effects.h"
#include "patterns.h"
#include "settings.h"
#include "ws2812.h"
#define FRAME_MS 10
static const char *TAG = "patterns";
typedef bool (*fx_fn)(fx_t &, st_t &);
struct pattern_def_t {
const char *name;
fx_fn fn;
};
// Same names as the MicroPython led-driver patterns
static const pattern_def_t kPatterns[] = {
{ "off", fx_off },
{ "on", fx_on },
{ "blink", fx_blink },
{ "aurora", fx_aurora },
{ "bar_graph", fx_bar_graph },
{ "blizzard", fx_blizzard },
{ "candle_glow", fx_candle_glow },
{ "chase", fx_chase },
{ "circle", fx_circle },
{ "clock_sweep", fx_clock_sweep },
{ "colour_cycle", fx_colour_cycle },
{ "field_wave", fx_field_wave },
{ "flame", fx_flame },
{ "flicker", fx_flicker },
{ "gradient_wipe", fx_gradient_wipe },
{ "grow", fx_grow },
{ "hit", fx_hit },
{ "icicles", fx_icicles },
{ "keyframes", fx_keyframes },
{ "meteor", fx_meteor },
{ "orbit", fx_orbit },
{ "palette_morph", fx_palette_morph },
{ "particles", fx_particles },
{ "plasma", fx_plasma },
{ "pulse", fx_pulse },
{ "radiate", fx_radiate },
{ "rain_drops", fx_rain_drops },
{ "rime", fx_rime },
{ "ripple", fx_ripple },
{ "sparkle", fx_sparkle },
{ "spin", fx_spin },
{ "strobe_burst", fx_strobe_burst },
{ "sweep", fx_sweep },
{ "transition", fx_transition },
{ "twinkle", fx_twinkle },
};
#define PATTERN_COUNT ((int)(sizeof(kPatterns) / sizeof(kPatterns[0])))
static WS2812 *s_strip;
static SemaphoreHandle_t s_lock;
static preset_t s_cur; // the preset requested (under s_lock)
static bool s_reset_pending; // a new pattern was selected (under s_lock)
static preset_t s_run; // the preset the task is running
static fx_t s_fx; // shadow frame and timing for the running pattern
st_t g_st; // state of the running pattern
// Crossfade: the last frame shown, and the frame it fades from
static rgb *s_shown; // last frame shown (s_cap entries)
static rgb *s_from; // frame the crossfade starts from
static int s_cap; // LEDs the buffers are sized for
static bool s_fading;
// DDP: pixels sent by a controller. While they keep arriving they replace the pattern.
#define DDP_TIMEOUT_MS 2000
static uint8_t s_ddp[FX_LEDS_MAX * 3];
static uint32_t s_ddp_last_ms; // 0: never
static bool s_ddp_was;
static uint32_t s_ddp_packets;
static uint32_t s_ddp_frames; // frames completed (PUSH seen)
static uint32_t s_ddp_sum; // checksum of the last completed frame
static uint32_t s_ddp_log_ms; // last serial summary
static uint8_t s_max_brightness = 255;
static uint8_t s_global = 255;
static uint32_t s_fade_t0;
static uint32_t s_fade_ms;
int patterns_count(void)
{
return PATTERN_COUNT;
}
const char *patterns_name(int i)
{
return (i >= 0 && i < PATTERN_COUNT) ? kPatterns[i].name : "";
}
int patterns_index(const char *name)
{
for (int i = 0; i < PATTERN_COUNT; i++) {
if (strcmp(name, kPatterns[i].name) == 0) {
return i;
}
}
return -1;
}
void preset_defaults(preset_t *p, int pattern)
{
memset(p, 0, sizeof(*p));
p->pattern = pattern;
p->ncol = 0;
p->delay = 100;
p->brightness = 127;
p->autorun = true;
p->reverse = false;
p->fade = 0;
p->beat_time = false;
}
// Keep a preset within the ranges the patterns expect
static void sanitize(preset_t *p)
{
if (p->pattern < 0 || p->pattern >= PATTERN_COUNT) {
p->pattern = 0;
}
if (p->delay < 10) p->delay = 10;
if (p->delay > 10000) p->delay = 10000;
if (p->ncol < 0) p->ncol = 0;
if (p->ncol > PATTERN_MAX_COLOURS) p->ncol = PATTERN_MAX_COLOURS;
if (p->fade > 10000) p->fade = 10000;
for (int i = 1; i <= 6; i++) {
if (p->n[i] < 0) p->n[i] = 0;
if (p->n[i] > 100000) p->n[i] = 100000;
}
}
// Live update: a change of pattern restarts it (with a crossfade if the preset asks); other changes
// take effect straight away, keeping the pattern's place
void patterns_set(const preset_t &p)
{
preset_t q = p;
sanitize(&q);
xSemaphoreTake(s_lock, portMAX_DELAY);
bool changed = q.pattern != s_cur.pattern;
s_cur = q;
if (changed) {
s_reset_pending = true;
}
xSemaphoreGive(s_lock);
}
// Select a preset: always restarts the pattern, crossfading in from the frame on the strip
void patterns_select(const preset_t &p)
{
preset_t q = p;
sanitize(&q);
xSemaphoreTake(s_lock, portMAX_DELAY);
s_cur = q;
s_reset_pending = true;
xSemaphoreGive(s_lock);
}
void patterns_set_global(uint8_t level)
{
xSemaphoreTake(s_lock, portMAX_DELAY);
s_global = level;
xSemaphoreGive(s_lock);
}
uint8_t patterns_get_global(void)
{
xSemaphoreTake(s_lock, portMAX_DELAY);
uint8_t v = s_global;
xSemaphoreGive(s_lock);
return v;
}
void patterns_get(preset_t *out)
{
xSemaphoreTake(s_lock, portMAX_DELAY);
*out = s_cur;
xSemaphoreGive(s_lock);
}
static uint32_t now_ms(void)
{
return (uint32_t)(esp_timer_get_time() / 1000);
}
// Show the shadow frame, crossfading from the previous frame while a fade runs
static void output(uint32_t now)
{
int s_scale = s_global * s_max_brightness / 255; // global brightness under the ceiling
int k = -1;
if (s_fading) {
uint32_t el = now - s_fade_t0;
if (el >= s_fade_ms) {
s_fading = false;
} else {
k = (int)((el * 256) / s_fade_ms);
}
}
for (int i = 0; i < s_fx.n; i++) {
rgb c = s_fx.px[i];
c.r = c.r * s_scale / 255;
c.g = c.g * s_scale / 255;
c.b = c.b * s_scale / 255;
if (k >= 0) {
rgb a = s_from[i];
c.r = (a.r * (256 - k) + c.r * k) >> 8;
c.g = (a.g * (256 - k) + c.g * k) >> 8;
c.b = (a.b * (256 - k) + c.b * k) >> 8;
}
s_strip->set(i, c.r, c.g, c.b);
s_shown[i] = c;
}
esp_err_t err = s_strip->write();
if (err != ESP_OK) {
ESP_LOGW(TAG, "LED write failed: %s", esp_err_to_name(err));
}
}
// ---- per-LED buffers --------------------------------------------------------------------------
bool frame_alloc(int n)
{
if (n < 1) n = 1;
if (n > FX_LEDS_MAX) n = FX_LEDS_MAX;
void *fresh[12] = {
calloc(n, sizeof(rgb)), calloc(n, sizeof(rgb)), calloc(n, sizeof(rgb)),
calloc(n, sizeof(int)), calloc(n, sizeof(float)), calloc(n, sizeof(int)),
calloc(n, 1), calloc(n, 1),
calloc(n, sizeof(int)), calloc(n, sizeof(int)),
calloc(n, sizeof(int)), calloc(n, sizeof(int)),
};
for (int k = 0; k < 12; k++) {
if (!fresh[k]) {
for (int j = 0; j < 12; j++) free(fresh[j]);
ESP_LOGE(TAG, "Out of memory for %d LEDs", n);
return false;
}
}
free(s_fx.px);
free(s_shown);
free(s_from);
free(g_st.glow);
free(g_st.m);
free(g_st.shade);
free(g_st.on);
free(g_st.next_on);
free(g_st.col_i);
free(g_st.next_ci);
free(g_st.light);
free(g_st.dark);
s_fx.px = (rgb *)fresh[0];
s_shown = (rgb *)fresh[1];
s_from = (rgb *)fresh[2];
g_st.glow = (int *)fresh[3];
g_st.m = (float *)fresh[4];
g_st.shade = (int *)fresh[5];
g_st.on = (uint8_t *)fresh[6];
g_st.next_on = (uint8_t *)fresh[7];
g_st.col_i = (int *)fresh[8];
g_st.next_ci = (int *)fresh[9];
g_st.light = (int *)fresh[10];
g_st.dark = (int *)fresh[11];
s_cap = n;
return true;
}
void st_reset(void)
{
int *glow = g_st.glow, *shade = g_st.shade, *col_i = g_st.col_i, *next_ci = g_st.next_ci;
int *light = g_st.light, *dark = g_st.dark;
float *m = g_st.m;
uint8_t *on = g_st.on, *next_on = g_st.next_on;
memset(&g_st, 0, sizeof(g_st));
g_st.glow = glow;
g_st.shade = shade;
g_st.col_i = col_i;
g_st.next_ci = next_ci;
g_st.light = light;
g_st.dark = dark;
g_st.m = m;
g_st.on = on;
g_st.next_on = next_on;
memset(glow, 0, s_cap * sizeof(int));
memset(shade, 0, s_cap * sizeof(int));
memset(col_i, 0, s_cap * sizeof(int));
memset(next_ci, 0, s_cap * sizeof(int));
memset(light, 0, s_cap * sizeof(int));
memset(dark, 0, s_cap * sizeof(int));
memset(m, 0, s_cap * sizeof(float));
memset(on, 0, s_cap);
memset(next_on, 0, s_cap);
}
// The whole frame (pattern and output) runs under s_lock, so the buffers can't be replaced mid-frame
static void patterns_task(void *arg)
{
(void)arg;
s_fx.pr = &s_run;
while (true) {
xSemaphoreTake(s_lock, portMAX_DELAY);
bool reset = s_reset_pending;
s_reset_pending = false;
s_run = s_cur;
uint32_t now = now_ms();
bool ddp_on = s_ddp_last_ms != 0 && now - s_ddp_last_ms < DDP_TIMEOUT_MS;
if (!ddp_on && s_ddp_was) {
reset = true; // the pattern starts again when the pixels stop
}
s_ddp_was = ddp_on;
if (reset) {
if (s_run.fade > 0) {
memcpy(s_from, s_shown, s_fx.n * sizeof(rgb));
s_fading = true;
s_fade_t0 = now;
s_fade_ms = s_run.fade;
} else {
s_fading = false;
}
st_reset();
g_st.t0 = now;
}
s_fx.now = now;
s_fx.t = now - g_st.t0;
if (ddp_on) {
for (int i = 0; i < s_fx.n; i++) {
s_fx.px[i] = { s_ddp[3 * i], s_ddp[3 * i + 1], s_ddp[3 * i + 2] };
}
} else if (!g_st.done) {
if (kPatterns[s_run.pattern].fn(s_fx, g_st)) {
g_st.done = true;
}
}
output(now);
xSemaphoreGive(s_lock);
vTaskDelay(pdMS_TO_TICKS(FRAME_MS));
}
}
static int clamp_leds(int n)
{
return n < 1 ? 1 : (n > FX_LEDS_MAX ? FX_LEDS_MAX : n);
}
void patterns_start(const hw_cfg_t &hw)
{
s_lock = xSemaphoreCreateMutex();
preset_defaults(&s_cur, 0);
preset_defaults(&s_run, 0);
s_cur.pattern = patterns_index("chase");
s_cur.delay = 1000;
s_cur.brightness = 16;
s_cur.col[0][0] = 255;
s_reset_pending = true;
int n = clamp_leds(hw.num_leds);
if (!frame_alloc(n)) {
ESP_ERROR_CHECK(ESP_ERR_NO_MEM);
}
s_fx.n = n;
s_max_brightness = hw.max_brightness;
s_global = hw.global_brightness;
s_strip = new WS2812((gpio_num_t)hw.pin, n);
s_strip->setOrder(hw.order);
s_strip->setBrightness(255); // brightness is applied per colour by the patterns
xTaskCreate(patterns_task, "patterns", 6144, NULL, 5, NULL);
ESP_LOGI(TAG, "Started %d LEDs on GPIO %d (%s), %d patterns", n, hw.pin, hw.order, PATTERN_COUNT);
}
// Change the strip: count, byte order and brightness ceiling. The buffers and the driver are replaced
// under the lock the frame runs under; on out-of-memory the old strip is kept.
esp_err_t patterns_set_hardware(const hw_cfg_t &hw)
{
int n = clamp_leds(hw.num_leds);
xSemaphoreTake(s_lock, portMAX_DELAY);
if (!frame_alloc(n)) {
xSemaphoreGive(s_lock);
return ESP_ERR_NO_MEM;
}
s_fx.n = n;
delete s_strip;
s_strip = new WS2812((gpio_num_t)hw.pin, n);
s_strip->setOrder(hw.order);
s_strip->setBrightness(255);
s_max_brightness = hw.max_brightness;
s_fading = false;
s_reset_pending = true;
xSemaphoreGive(s_lock);
ESP_LOGI(TAG, "LED strip: %d LEDs on GPIO %d, %s, max brightness %u, free heap %u", n, hw.pin, hw.order,
(unsigned)hw.max_brightness, (unsigned)esp_get_free_heap_size());
return ESP_OK;
}
// ---- DDP ---------------------------------------------------------------------------------------
void patterns_ddp_write(uint32_t offset, const uint8_t *data, size_t len, bool push)
{
xSemaphoreTake(s_lock, portMAX_DELAY);
size_t cap = (size_t)s_fx.n * 3;
if (offset < cap) {
if (offset + len > cap) {
len = cap - offset;
}
memcpy(s_ddp + offset, data, len);
}
uint32_t now = now_ms();
s_ddp_last_ms = now | 1; // never 0
s_ddp_packets++;
if (push) {
s_ddp_frames++;
uint32_t sum = 0;
for (size_t i = 0; i < cap; i++) {
sum += s_ddp[i];
}
s_ddp_sum = sum;
// Summary on the serial log, at most twice a second, so the test can check what was shown
if (now - s_ddp_log_ms >= 500) {
s_ddp_log_ms = now;
ESP_LOGI(TAG, "DDP frames=%u packets=%u sum=%u led0=%u,%u,%u led_last=%u,%u,%u",
(unsigned)s_ddp_frames, (unsigned)s_ddp_packets, (unsigned)s_ddp_sum,
s_ddp[0], s_ddp[1], s_ddp[2],
s_ddp[cap - 3], s_ddp[cap - 2], s_ddp[cap - 1]);
}
}
xSemaphoreGive(s_lock);
}
void patterns_ddp_status(bool *active, uint32_t *packets)
{
xSemaphoreTake(s_lock, portMAX_DELAY);
*active = s_ddp_last_ms != 0 && now_ms() - s_ddp_last_ms < DDP_TIMEOUT_MS;
*packets = s_ddp_packets;
xSemaphoreGive(s_lock);
}
void patterns_shown_pixel(int i, uint8_t out[3])
{
xSemaphoreTake(s_lock, portMAX_DELAY);
if (i >= 0 && i < s_fx.n) {
out[0] = (uint8_t)s_shown[i].r;
out[1] = (uint8_t)s_shown[i].g;
out[2] = (uint8_t)s_shown[i].b;
}
xSemaphoreGive(s_lock);
}
+68
View File
@@ -0,0 +1,68 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <cstddef>
#include <cstdint>
#include "esp_err.h"
#define PATTERN_MAX_COLOURS 8
// Preset fields follow the MicroPython presets: pattern, colours, background, delay (d), brightness (b),
// auto (a), reverse, fade, beat_time (tb) and the pattern-specific numbers n1..n6 (n6 is the style).
struct preset_t {
char name[32]; // "" for the live settings
int pattern; // index into the pattern table
int ncol; // 0 uses each pattern's own default colours
uint8_t col[PATTERN_MAX_COLOURS][3];
uint8_t bg[3]; // background (d off colour)
uint32_t delay; // d, ms
uint8_t brightness; // b, 0-255
bool autorun; // a: keep running; false runs one cycle and holds
bool reverse; // run the other way along the strip
uint32_t fade; // crossfade in from the previous frame, ms
bool beat_time; // tb: durations are quarter beats (500 ms beat here)
int n[7]; // n[1]..n[6]
};
/** @brief Start the LED strip and the pattern task, with the strip settings. */
void patterns_start(const struct hw_cfg_t &hw);
/** @brief Apply new strip settings (count, colour order, brightness ceiling) while running. */
esp_err_t patterns_set_hardware(const struct hw_cfg_t &hw);
/** @brief Live update of the preset on the strip. A new pattern restarts; other changes keep its place. */
void patterns_set(const preset_t &p);
/** @brief Select a preset: always restarts the pattern, crossfading from the frame on the strip. */
void patterns_select(const preset_t &p);
/** @brief DDP pixel data for the strip: byte offset into the RGB buffer, data, length. Replaces the pattern. */
void patterns_ddp_write(uint32_t offset, const uint8_t *data, size_t len, bool push);
/** @brief Whether DDP pixels are arriving, and how many packets have come in. */
void patterns_ddp_status(bool *active, uint32_t *packets);
/** @brief The colour last shown on LED i, as RGB. */
void patterns_shown_pixel(int i, uint8_t out[3]);
/** @brief Live brightness for every pattern, 0-255 (applied under the max brightness ceiling). */
void patterns_set_global(uint8_t level);
uint8_t patterns_get_global(void);
/** @brief Copy of the preset being shown. */
void patterns_get(preset_t *out);
/** @brief Number of patterns. */
int patterns_count(void);
/** @brief Name of pattern i, e.g. "chase". */
const char *patterns_name(int i);
/** @brief Index for a pattern name, or -1 if unknown. */
int patterns_index(const char *name);
/** @brief Fill a preset with the defaults for a pattern: colours and timing as the MicroPython presets. */
void preset_defaults(preset_t *p, int pattern);
+391
View File
@@ -0,0 +1,391 @@
/*
* SPDX-License-Identifier: Apache-2.0
*
* Named presets, stored in NVS as one JSON list (as the MicroPython presets.json), with a startup preset.
*/
#include <cstdlib>
#include <cstring>
#include "cJSON.h"
#include "esp_log.h"
#include "nvs.h"
#include "presets.h"
static const char *TAG = "presets";
static const char *NS = "presets";
static preset_t s_list[PRESETS_MAX];
static size_t s_count;
static char s_startup[32];
static char s_selected[32];
static int find(const char *name)
{
for (size_t i = 0; i < s_count; i++) {
if (strcmp(s_list[i].name, name) == 0) {
return (int)i;
}
}
return -1;
}
static cJSON *rgb_json(const uint8_t *c)
{
cJSON *a = cJSON_CreateArray();
for (int i = 0; i < 3; i++) {
cJSON_AddItemToArray(a, cJSON_CreateNumber(c[i]));
}
return a;
}
static bool read_rgb(const cJSON *a, uint8_t *out)
{
if (!cJSON_IsArray(a) || cJSON_GetArraySize(a) != 3) {
return false;
}
for (int i = 0; i < 3; i++) {
cJSON *v = cJSON_GetArrayItem(a, i);
if (!cJSON_IsNumber(v)) {
return false;
}
int x = v->valueint;
out[i] = (uint8_t)(x < 0 ? 0 : (x > 255 ? 255 : x));
}
return true;
}
cJSON *preset_to_json(const preset_t *p)
{
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "name", p->name);
cJSON_AddStringToObject(o, "pattern", patterns_name(p->pattern));
cJSON *colors = cJSON_AddArrayToObject(o, "colors");
for (int i = 0; i < p->ncol; i++) {
cJSON_AddItemToArray(colors, rgb_json(p->col[i]));
}
cJSON_AddItemToObject(o, "background", rgb_json(p->bg));
cJSON_AddNumberToObject(o, "delay", p->delay);
cJSON_AddNumberToObject(o, "brightness", p->brightness);
cJSON_AddBoolToObject(o, "auto", p->autorun);
cJSON_AddBoolToObject(o, "reverse", p->reverse);
cJSON_AddNumberToObject(o, "fade", p->fade);
cJSON_AddBoolToObject(o, "beat_time", p->beat_time);
cJSON_AddNumberToObject(o, "n1", p->n[1]);
cJSON_AddNumberToObject(o, "n2", p->n[2]);
cJSON_AddNumberToObject(o, "n3", p->n[3]);
cJSON_AddNumberToObject(o, "n4", p->n[4]);
cJSON_AddNumberToObject(o, "mode", p->n[6]); // n6: the pattern's style
return o;
}
bool preset_from_json(const cJSON *o, preset_t *p)
{
if (!cJSON_IsObject(o)) {
return false;
}
cJSON *v = cJSON_GetObjectItem(o, "name");
if (cJSON_IsString(v)) {
strncpy(p->name, v->valuestring, sizeof(p->name) - 1);
p->name[sizeof(p->name) - 1] = '\0';
}
v = cJSON_GetObjectItem(o, "pattern");
if (cJSON_IsString(v)) {
int idx = patterns_index(v->valuestring);
if (idx < 0) {
return false;
}
p->pattern = idx;
}
v = cJSON_GetObjectItem(o, "colors");
if (cJSON_IsArray(v)) {
int n = cJSON_GetArraySize(v);
if (n > PATTERN_MAX_COLOURS) n = PATTERN_MAX_COLOURS;
p->ncol = 0;
for (int i = 0; i < n; i++) {
if (read_rgb(cJSON_GetArrayItem(v, i), p->col[p->ncol])) {
p->ncol++;
}
}
}
read_rgb(cJSON_GetObjectItem(o, "background"), p->bg);
v = cJSON_GetObjectItem(o, "delay");
if (cJSON_IsNumber(v)) p->delay = (uint32_t)(v->valueint < 0 ? 0 : v->valueint);
v = cJSON_GetObjectItem(o, "brightness");
if (cJSON_IsNumber(v)) p->brightness = (uint8_t)(v->valueint < 0 ? 0 : (v->valueint > 255 ? 255 : v->valueint));
v = cJSON_GetObjectItem(o, "auto");
if (cJSON_IsBool(v)) p->autorun = cJSON_IsTrue(v);
v = cJSON_GetObjectItem(o, "reverse");
if (cJSON_IsBool(v)) p->reverse = cJSON_IsTrue(v);
v = cJSON_GetObjectItem(o, "fade");
if (cJSON_IsNumber(v)) p->fade = (uint32_t)(v->valueint < 0 ? 0 : v->valueint);
v = cJSON_GetObjectItem(o, "beat_time");
if (cJSON_IsBool(v)) p->beat_time = cJSON_IsTrue(v);
static const char *keys[] = { "n1", "n2", "n3", "n4" };
for (int i = 0; i < 4; i++) {
v = cJSON_GetObjectItem(o, keys[i]);
if (cJSON_IsNumber(v)) p->n[i + 1] = v->valueint;
}
v = cJSON_GetObjectItem(o, "mode");
if (cJSON_IsNumber(v)) p->n[6] = v->valueint;
return true;
}
// Write the whole list to NVS as one JSON blob
static esp_err_t save_list(void)
{
cJSON *arr = cJSON_CreateArray();
for (size_t i = 0; i < s_count; i++) {
cJSON_AddItemToArray(arr, preset_to_json(&s_list[i]));
}
char *s = cJSON_PrintUnformatted(arr);
cJSON_Delete(arr);
if (!s) {
return ESP_ERR_NO_MEM;
}
nvs_handle_t h;
esp_err_t err = nvs_open(NS, NVS_READWRITE, &h);
if (err == ESP_OK) {
err = nvs_set_blob(h, "list", s, strlen(s));
if (err == ESP_OK) err = nvs_set_str(h, "startup", s_startup);
if (err == ESP_OK) err = nvs_commit(h);
nvs_close(h);
}
cJSON_free(s);
return err;
}
// The presets a new board starts with (added by presets_add_defaults, and on a board that has none saved)
static int build_defaults(preset_t *out, int max)
{
int n = 0;
auto add = [&](const char *name, const char *pattern) -> preset_t * {
if (n >= max) {
return NULL;
}
preset_t *p = &out[n++];
preset_defaults(p, patterns_index(pattern));
strncpy(p->name, name, sizeof(p->name) - 1);
p->name[sizeof(p->name) - 1] = '\0';
return p;
};
preset_t *p;
if ((p = add("Rainbow", "colour_cycle"))) {
p->n[6] = 1; // rainbow wheel
p->n[1] = 2;
p->delay = 60;
p->brightness = 160;
}
if ((p = add("Chase", "chase"))) {
p->ncol = 2;
p->col[0][0] = 255; p->col[0][1] = 80; p->col[0][2] = 0;
p->col[1][0] = 0; p->col[1][1] = 120; p->col[1][2] = 255;
p->n[1] = 4; p->n[2] = 4; p->n[3] = 1; p->n[4] = 1;
p->delay = 150;
p->brightness = 180;
}
if ((p = add("Aurora", "aurora"))) {
p->n[1] = 3;
p->n[2] = 40;
p->delay = 40;
p->brightness = 150;
}
if ((p = add("Candle", "candle_glow"))) {
p->ncol = 3;
p->col[0][0] = 255; p->col[0][1] = 140; p->col[0][2] = 40;
p->col[1][0] = 255; p->col[1][1] = 200; p->col[1][2] = 120;
p->col[2][0] = 255; p->col[2][1] = 90; p->col[2][2] = 20;
p->n[1] = 4; p->n[2] = 3; p->n[3] = 90;
p->delay = 120;
p->brightness = 200;
}
if ((p = add("Twinkle", "twinkle"))) {
p->ncol = 1;
p->col[0][0] = 200; p->col[0][1] = 220; p->col[0][2] = 255;
p->bg[2] = 20;
p->n[1] = 48; p->n[2] = 128;
p->delay = 100;
p->brightness = 200;
}
if ((p = add("Flame", "flame"))) {
p->delay = 40;
p->brightness = 255;
p->n[2] = 2500;
}
if ((p = add("Sweep", "sweep"))) {
p->ncol = 2;
p->col[0][0] = 255; p->col[0][1] = 0; p->col[0][2] = 120;
p->col[1][0] = 0; p->col[1][1] = 200; p->col[1][2] = 255;
p->n[1] = 90; p->n[2] = 200; p->n[3] = 200;
p->delay = 2000;
p->brightness = 200;
}
if ((p = add("Off", "off"))) {
p->brightness = 255;
}
return n;
}
// Add the default presets whose names aren't in the list yet. Returns how many were added.
int presets_add_defaults(void)
{
preset_t defs[16];
int n = build_defaults(defs, 16);
int added = 0;
for (int i = 0; i < n; i++) {
if (find(defs[i].name) < 0 && s_count < PRESETS_MAX) {
s_list[s_count++] = defs[i];
added++;
}
}
if (added > 0) {
save_list();
}
return added;
}
esp_err_t presets_init(void)
{
s_count = 0;
s_startup[0] = '\0';
s_selected[0] = '\0';
nvs_handle_t h;
if (nvs_open(NS, NVS_READONLY, &h) != ESP_OK) {
presets_add_defaults(); // a new board
return ESP_OK;
}
size_t len = 0;
bool have_list = nvs_get_blob(h, "list", NULL, &len) == ESP_OK;
if (have_list && len > 0) {
char *buf = (char *)malloc(len + 1);
if (buf && nvs_get_blob(h, "list", buf, &len) == ESP_OK) {
buf[len] = '\0';
cJSON *arr = cJSON_Parse(buf);
cJSON *o;
cJSON_ArrayForEach(o, arr) {
if (s_count >= PRESETS_MAX) break;
preset_t p;
preset_defaults(&p, 0);
if (preset_from_json(o, &p) && p.name[0]) {
s_list[s_count++] = p;
}
}
cJSON_Delete(arr);
}
free(buf);
}
len = sizeof(s_startup);
if (nvs_get_str(h, "startup", s_startup, &len) != ESP_OK) {
s_startup[0] = '\0';
}
nvs_close(h);
if (!have_list) {
presets_add_defaults(); // nothing saved yet: start with the defaults
}
ESP_LOGI(TAG, "%u presets loaded", (unsigned)s_count);
return ESP_OK;
}
size_t presets_count(void)
{
return s_count;
}
const preset_t *presets_at(size_t i)
{
return i < s_count ? &s_list[i] : NULL;
}
esp_err_t presets_save(const preset_t *preset)
{
int idx = find(preset->name);
if (idx < 0) {
if (s_count >= PRESETS_MAX) {
return ESP_ERR_NO_MEM;
}
idx = (int)s_count++;
}
s_list[idx] = *preset;
return save_list();
}
esp_err_t presets_set_order(const char *const *names, size_t n)
{
// Static: this is too big for the HTTP server's task stack, and only that task calls it
static preset_t fresh[PRESETS_MAX];
bool used[PRESETS_MAX] = { false };
size_t m = 0;
for (size_t k = 0; k < n && m < s_count; k++) {
int idx = find(names[k]);
if (idx >= 0 && !used[idx]) {
used[idx] = true;
fresh[m++] = s_list[idx];
}
}
for (size_t i = 0; i < s_count; i++) {
if (!used[i]) {
fresh[m++] = s_list[i];
}
}
memcpy(s_list, fresh, m * sizeof(preset_t));
s_count = m;
return save_list();
}
esp_err_t presets_delete(const char *name)
{
int idx = find(name);
if (idx < 0) {
return ESP_ERR_NOT_FOUND;
}
for (size_t i = (size_t)idx; i + 1 < s_count; i++) {
s_list[i] = s_list[i + 1];
}
s_count--;
if (strcmp(s_startup, name) == 0) {
s_startup[0] = '\0';
}
if (strcmp(s_selected, name) == 0) {
s_selected[0] = '\0';
}
return save_list();
}
esp_err_t presets_select(const char *name)
{
int idx = find(name);
if (idx < 0) {
return ESP_ERR_NOT_FOUND;
}
patterns_select(s_list[idx]);
strncpy(s_selected, name, sizeof(s_selected) - 1);
s_selected[sizeof(s_selected) - 1] = '\0';
return ESP_OK;
}
const char *presets_selected(void)
{
return s_selected;
}
esp_err_t presets_set_startup(const char *name)
{
if (name[0] && find(name) < 0) {
return ESP_ERR_NOT_FOUND;
}
strncpy(s_startup, name, sizeof(s_startup) - 1);
s_startup[sizeof(s_startup) - 1] = '\0';
return save_list();
}
const char *presets_startup(void)
{
return s_startup;
}
void presets_apply_startup(void)
{
if (s_startup[0] && presets_select(s_startup) == ESP_OK) {
ESP_LOGI(TAG, "Startup preset: %s", s_startup);
}
}
+57
View File
@@ -0,0 +1,57 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <cstddef>
#include "cJSON.h"
#include "esp_err.h"
#include "patterns.h"
#define PRESETS_MAX 32
/** @brief Load the saved presets and the startup name from NVS. Call after NVS is initialised. */
esp_err_t presets_init(void);
/** @brief Add the default presets whose names are not in the list yet. Returns how many were added. */
int presets_add_defaults(void);
/** @brief Number of presets. */
size_t presets_count(void);
/** @brief Preset at index i (0 <= i < presets_count()). */
const preset_t *presets_at(size_t i);
/** @brief Create a preset, or update the one with the same name. ESP_ERR_NO_MEM when full. */
esp_err_t presets_save(const preset_t *preset);
/** @brief Put the presets in this order. Names not given keep their place at the end. */
esp_err_t presets_set_order(const char *const *names, size_t n);
/** @brief Delete a preset by name. Clears the startup name if it was that preset. */
esp_err_t presets_delete(const char *name);
/** @brief Select a preset: crossfades in and restarts its pattern. ESP_ERR_NOT_FOUND if no such name. */
esp_err_t presets_select(const char *name);
/** @brief Name of the last preset selected since boot, or "". */
const char *presets_selected(void);
/** @brief Set the preset applied at boot. An empty name clears it. */
esp_err_t presets_set_startup(const char *name);
/** @brief Name of the startup preset, or "". */
const char *presets_startup(void);
/** @brief Apply the startup preset, if one is set and still exists. */
void presets_apply_startup(void);
/** @brief A preset as JSON, with the MicroPython field names. The caller frees it with cJSON_Delete. */
cJSON *preset_to_json(const preset_t *p);
/**
* @brief Apply the fields present in JSON onto p; missing fields keep their value.
* @return false if a field is malformed (an unknown pattern name, for example).
*/
bool preset_from_json(const cJSON *o, preset_t *p);
+147
View File
@@ -0,0 +1,147 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#include <cstring>
#include "nvs.h"
#include "settings.h"
static const char *NS = "led";
esp_err_t settings_load_wifi(wifi_creds_t *c)
{
nvs_handle_t h;
esp_err_t err = nvs_open(NS, NVS_READONLY, &h);
if (err != ESP_OK) {
return err;
}
size_t len = sizeof(c->ssid);
err = nvs_get_str(h, "sta_ssid", c->ssid, &len);
if (err == ESP_OK) {
len = sizeof(c->pass);
err = nvs_get_str(h, "sta_pass", c->pass, &len);
if (err == ESP_ERR_NVS_NOT_FOUND) {
c->pass[0] = '\0';
err = ESP_OK;
}
}
nvs_close(h);
return err;
}
esp_err_t settings_save_wifi(const wifi_creds_t *c)
{
nvs_handle_t h;
esp_err_t err = nvs_open(NS, NVS_READWRITE, &h);
if (err != ESP_OK) {
return err;
}
err = nvs_set_str(h, "sta_ssid", c->ssid);
if (err == ESP_OK) err = nvs_set_str(h, "sta_pass", c->pass);
if (err == ESP_OK) err = nvs_commit(h);
nvs_close(h);
return err;
}
esp_err_t settings_load_hw(hw_cfg_t *c)
{
strncpy(c->order, "grb", sizeof(c->order));
c->max_brightness = 255;
c->num_leds = 119;
c->pin = 10;
c->global_brightness = 255;
nvs_handle_t h;
if (nvs_open(NS, NVS_READONLY, &h) != ESP_OK) {
return ESP_OK;
}
size_t len = sizeof(c->order);
if (nvs_get_str(h, "rgb_order", c->order, &len) != ESP_OK) {
strncpy(c->order, "grb", sizeof(c->order));
}
uint8_t mb;
if (nvs_get_u8(h, "max_bright", &mb) == ESP_OK) {
c->max_brightness = mb;
}
int32_t n;
if (nvs_get_i32(h, "num_leds", &n) == ESP_OK) {
c->num_leds = (int)n;
}
if (nvs_get_i32(h, "pin", &n) == ESP_OK) {
c->pin = (int)n;
}
if (nvs_get_u8(h, "global_bright", &mb) == ESP_OK) {
c->global_brightness = mb;
}
nvs_close(h);
return ESP_OK;
}
esp_err_t settings_save_hw(const hw_cfg_t *c)
{
nvs_handle_t h;
esp_err_t err = nvs_open(NS, NVS_READWRITE, &h);
if (err != ESP_OK) {
return err;
}
err = nvs_set_str(h, "rgb_order", c->order);
if (err == ESP_OK) err = nvs_set_u8(h, "max_bright", c->max_brightness);
if (err == ESP_OK) err = nvs_set_i32(h, "num_leds", c->num_leds);
if (err == ESP_OK) err = nvs_set_i32(h, "pin", c->pin);
if (err == ESP_OK) err = nvs_set_u8(h, "global_bright", c->global_brightness);
if (err == ESP_OK) err = nvs_commit(h);
nvs_close(h);
return err;
}
// Read a string key; use def when it is missing or unreadable
static void get_str(nvs_handle_t h, const char *key, char *buf, size_t len, const char *def)
{
size_t n = len;
if (nvs_get_str(h, key, buf, &n) != ESP_OK) {
strncpy(buf, def, len - 1);
buf[len - 1] = '\0';
}
}
esp_err_t settings_load_net(net_cfg_t *c)
{
memset(c, 0, sizeof(*c));
nvs_handle_t h;
esp_err_t err = nvs_open(NS, NVS_READONLY, &h);
if (err == ESP_ERR_NVS_NOT_FOUND) {
// Nothing saved yet: defaults
strncpy(c->hostname, "led", sizeof(c->hostname) - 1);
return ESP_OK;
}
if (err != ESP_OK) {
return err;
}
get_str(h, "hostname", c->hostname, sizeof(c->hostname), "led");
char mode[8];
get_str(h, "ip_mode", mode, sizeof(mode), "dhcp");
c->use_static = strcmp(mode, "static") == 0;
get_str(h, "ip", c->ip, sizeof(c->ip), "");
get_str(h, "netmask", c->netmask, sizeof(c->netmask), "");
get_str(h, "gateway", c->gateway, sizeof(c->gateway), "");
get_str(h, "dns", c->dns, sizeof(c->dns), "");
nvs_close(h);
return ESP_OK;
}
esp_err_t settings_save_net(const net_cfg_t *c)
{
nvs_handle_t h;
esp_err_t err = nvs_open(NS, NVS_READWRITE, &h);
if (err != ESP_OK) {
return err;
}
err = nvs_set_str(h, "hostname", c->hostname);
if (err == ESP_OK) err = nvs_set_str(h, "ip_mode", c->use_static ? "static" : "dhcp");
if (err == ESP_OK) err = nvs_set_str(h, "ip", c->ip);
if (err == ESP_OK) err = nvs_set_str(h, "netmask", c->netmask);
if (err == ESP_OK) err = nvs_set_str(h, "gateway", c->gateway);
if (err == ESP_OK) err = nvs_set_str(h, "dns", c->dns);
if (err == ESP_OK) err = nvs_commit(h);
nvs_close(h);
return err;
}
+48
View File
@@ -0,0 +1,48 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <stdbool.h>
#include "esp_err.h"
struct wifi_creds_t {
char ssid[33];
char pass[65];
};
struct net_cfg_t {
char hostname[64]; // mDNS name, without ".local"
bool use_static; // false: DHCP on the client interface
char ip[16]; // static client address, dotted quad
char netmask[16];
char gateway[16];
char dns[16]; // optional; empty uses the gateway
};
/** @brief Read saved Wi-Fi client credentials. ESP_ERR_NVS_NOT_FOUND if none are saved. */
esp_err_t settings_load_wifi(wifi_creds_t *c);
/** @brief Save Wi-Fi client credentials to NVS. */
esp_err_t settings_save_wifi(const wifi_creds_t *c);
struct hw_cfg_t {
char order[4]; // colour order of the strip: rgb, rbg, grb, gbr, brg or bgr
uint8_t max_brightness; // ceiling for every output colour, 0-255
int num_leds; // 1-512
int pin; // GPIO for the data line
uint8_t global_brightness; // live brightness for all patterns, 0-255 (under max_brightness)
};
/** @brief Read the LED strip settings. Missing keys get their defaults (grb, 255, 119). */
esp_err_t settings_load_hw(hw_cfg_t *c);
/** @brief Save the LED strip settings. */
esp_err_t settings_save_hw(const hw_cfg_t *c);
/** @brief Read network settings. Missing keys get their defaults (hostname "led", DHCP). */
esp_err_t settings_load_net(net_cfg_t *c);
/** @brief Save network settings to NVS. */
esp_err_t settings_save_net(const net_cfg_t *c);
+915
View File
@@ -0,0 +1,915 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "cJSON.h"
#include "esp_http_client.h"
#include "mdns.h"
#include "esp_http_server.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_wifi.h"
#include "net.h"
#include "ota.h"
#include "ddp.h"
#include "patterns.h"
#include "effects.h"
#include "presets.h"
#include "settings.h"
#include "web.h"
static const char *TAG = "web";
// Files embedded from web/ (see main/CMakeLists.txt EMBED_TXTFILES)
extern const char index_html_start[] asm("_binary_index_html_start");
extern const char index_html_end[] asm("_binary_index_html_end");
extern const char app_js_start[] asm("_binary_app_js_start");
extern const char app_js_end[] asm("_binary_app_js_end");
extern const char style_css_start[] asm("_binary_style_css_start");
extern const char style_css_end[] asm("_binary_style_css_end");
static httpd_handle_t s_server;
#define MAX_BODY 1024
#define MAX_SCAN 20
static esp_err_t send_embedded(httpd_req_t *req, const char *type, const char *start, const char *end)
{
httpd_resp_set_type(req, type);
httpd_resp_set_hdr(req, "Cache-Control", "no-cache");
// EMBED_TXTFILES includes the file's terminating NUL; don't send it
size_t len = end - start;
if (len > 0 && start[len - 1] == '\0') {
len--;
}
return httpd_resp_send(req, start, len);
}
// True for http://<private IPv4>, http://<name>.local and localhost, with an optional port.
// Pages on the internet are refused, so only the LAN and this computer can read the API cross-origin.
static bool origin_is_lan(const char *o)
{
static const char prefix[] = "http://";
if (strncmp(o, prefix, sizeof(prefix) - 1) != 0) {
return false;
}
char host[64];
const char *p = o + sizeof(prefix) - 1;
size_t n = 0;
while (p[n] && p[n] != ':') {
if (n + 1 >= sizeof(host)) {
return false;
}
host[n] = p[n];
n++;
}
host[n] = '\0';
if (p[n] == ':') { // port: digits only
for (const char *q = p + n + 1; *q; q++) {
if (*q < '0' || *q > '9') {
return false;
}
}
}
if (n == 0) {
return false;
}
if (strcmp(host, "localhost") == 0) {
return true;
}
size_t len = strlen(host);
if (len > 6 && strcmp(host + len - 6, ".local") == 0) {
for (size_t i = 0; i < len - 6; i++) {
char c = host[i];
bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '.';
if (!ok) {
return false;
}
}
return true;
}
unsigned a, b, c, d;
char extra;
if (sscanf(host, "%u.%u.%u.%u%c", &a, &b, &c, &d, &extra) != 4) {
return false;
}
for (const char *q = host; *q; q++) {
if (!((*q >= '0' && *q <= '9') || *q == '.')) {
return false;
}
}
if (a > 255 || b > 255 || c > 255 || d > 255) {
return false;
}
return a == 10 || (a == 192 && b == 168) || (a == 172 && b >= 16 && b <= 31);
}
void web_allow_lan_origin(httpd_req_t *req)
{
// The httpd server runs one handler at a time, and the header keeps a pointer to this buffer
// until the reply is sent, so a static buffer is safe here.
static char origin[96];
if (httpd_req_get_hdr_value_str(req, "Origin", origin, sizeof(origin)) != ESP_OK) {
return;
}
if (!origin_is_lan(origin)) {
return;
}
httpd_resp_set_hdr(req, "Access-Control-Allow-Origin", origin);
httpd_resp_set_hdr(req, "Vary", "Origin");
}
static esp_err_t send_json(httpd_req_t *req, cJSON *obj)
{
char *s = cJSON_PrintUnformatted(obj);
cJSON_Delete(obj);
web_allow_lan_origin(req);
if (!s) {
return httpd_resp_send_500(req);
}
httpd_resp_set_type(req, "application/json");
esp_err_t err = httpd_resp_sendstr(req, s);
cJSON_free(s);
return err;
}
static esp_err_t send_error(httpd_req_t *req, const char *status, const char *msg)
{
httpd_resp_set_status(req, status);
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "error", msg);
return send_json(req, o);
}
// Read the request body into buf (NUL-terminated). False if missing, too big or unreadable.
static bool read_body(httpd_req_t *req, char *buf, size_t cap)
{
int len = req->content_len;
if (len <= 0 || (size_t)len >= cap) {
return false;
}
int got = 0;
while (got < len) {
int r = httpd_req_recv(req, buf + got, len - got);
if (r <= 0) {
return false;
}
got += r;
}
buf[got] = '\0';
return true;
}
// Read a JSON body; NULL (no reply sent) if missing, too big or not JSON. Caller frees with cJSON_Delete.
static cJSON *read_json(httpd_req_t *req)
{
char body[MAX_BODY];
if (!read_body(req, body, sizeof(body))) {
return NULL;
}
return cJSON_Parse(body);
}
// GET / , /app.js , /style.css
static esp_err_t index_get(httpd_req_t *req)
{
return send_embedded(req, "text/html", index_html_start, index_html_end);
}
static esp_err_t app_js_get(httpd_req_t *req)
{
return send_embedded(req, "application/javascript", app_js_start, app_js_end);
}
static esp_err_t style_css_get(httpd_req_t *req)
{
return send_embedded(req, "text/css", style_css_start, style_css_end);
}
// GET /api/status : the running preset (same fields as a preset), plus device and network state
static esp_err_t status_get(httpd_req_t *req)
{
preset_t p;
patterns_get(&p);
char ap[16], ip[16];
net_ap_ssid(ap, sizeof(ap));
bool up = net_sta_status(ip, sizeof(ip));
net_cfg_t n;
settings_load_net(&n);
cJSON *o = preset_to_json(&p);
cJSON_AddStringToObject(o, "ap_ssid", ap);
cJSON_AddStringToObject(o, "hostname", n.hostname);
cJSON_AddBoolToObject(o, "sta_connected", up);
cJSON_AddStringToObject(o, "sta_ip", ip);
cJSON_AddStringToObject(o, "selected", presets_selected());
cJSON_AddNumberToObject(o, "global_brightness", patterns_get_global());
cJSON *modes = cJSON_AddArrayToObject(o, "patterns");
for (int i = 0; i < patterns_count(); i++) {
cJSON_AddItemToArray(modes, cJSON_CreateString(patterns_name(i)));
}
return send_json(req, o);
}
// POST /api/pattern : change the running settings. Fields missing from the body keep their value.
static esp_err_t pattern_post(httpd_req_t *req)
{
cJSON *in = read_json(req);
if (!in) {
return send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
}
preset_t p;
patterns_get(&p);
bool ok = preset_from_json(in, &p);
cJSON_Delete(in);
if (!ok) {
return send_error(req, "400 Bad Request", "unknown pattern");
}
patterns_set(p);
return send_json(req, cJSON_CreateObject());
}
// GET /api/wifi : saved client SSID and connection state
static esp_err_t wifi_get(httpd_req_t *req)
{
wifi_creds_t c = {};
settings_load_wifi(&c);
char ip[16];
bool up = net_sta_status(ip, sizeof(ip));
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "ssid", c.ssid);
cJSON_AddBoolToObject(o, "connected", up);
cJSON_AddStringToObject(o, "ip", ip);
return send_json(req, o);
}
// POST /api/wifi {"ssid","password"} : save and connect
static esp_err_t wifi_post(httpd_req_t *req)
{
char body[MAX_BODY];
if (!read_body(req, body, sizeof(body))) {
return send_error(req, "400 Bad Request", "empty or too large body");
}
cJSON *in = cJSON_Parse(body);
if (!in) {
return send_error(req, "400 Bad Request", "invalid JSON");
}
cJSON *ssid = cJSON_GetObjectItem(in, "ssid");
cJSON *pass = cJSON_GetObjectItem(in, "password");
const char *pw = cJSON_IsString(pass) ? pass->valuestring : "";
if (!cJSON_IsString(ssid) || !ssid->valuestring[0] || strlen(ssid->valuestring) > 32) {
cJSON_Delete(in);
return send_error(req, "400 Bad Request", "SSID must be 1-32 characters");
}
size_t plen = strlen(pw);
if (plen > 0 && (plen < 8 || plen > 64)) {
cJSON_Delete(in);
return send_error(req, "400 Bad Request", "password must be empty or 8-64 characters");
}
wifi_creds_t c = {};
strncpy(c.ssid, ssid->valuestring, sizeof(c.ssid) - 1);
strncpy(c.pass, pw, sizeof(c.pass) - 1);
cJSON_Delete(in);
esp_err_t err = net_sta_connect(&c);
if (err != ESP_OK) {
ESP_LOGW(TAG, "Connect to %s failed: %s", c.ssid, esp_err_to_name(err));
return send_error(req, "500 Internal Server Error", esp_err_to_name(err));
}
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "message", "saved; connecting");
return send_json(req, o);
}
// GET /api/wifi/scan : visible networks
static esp_err_t wifi_scan_get(httpd_req_t *req)
{
static wifi_ap_record_t recs[MAX_SCAN];
uint16_t count = MAX_SCAN;
esp_err_t err = net_scan(recs, &count);
if (err != ESP_OK) {
return send_error(req, "500 Internal Server Error", esp_err_to_name(err));
}
cJSON *arr = cJSON_CreateArray();
for (int i = 0; i < count; i++) {
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "ssid", (const char *)recs[i].ssid);
cJSON_AddNumberToObject(o, "rssi", recs[i].rssi);
cJSON_AddBoolToObject(o, "open", recs[i].authmode == WIFI_AUTH_OPEN);
cJSON_AddItemToArray(arr, o);
}
cJSON *root = cJSON_CreateObject();
cJSON_AddItemToObject(root, "networks", arr);
return send_json(req, root);
}
// A DNS label: 1-63 letters, digits or hyphens, not starting or ending with a hyphen
static bool valid_hostname(const char *s)
{
size_t n = strlen(s);
if (n == 0 || n > 63 || s[0] == '-' || s[n - 1] == '-') {
return false;
}
for (size_t i = 0; i < n; i++) {
char c = s[i];
bool ok = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-';
if (!ok) {
return false;
}
}
return true;
}
static bool valid_ipv4(const char *s)
{
esp_ip4_addr_t a;
return s && s[0] && esp_netif_str_to_ip4(s, &a) == ESP_OK;
}
// GET /api/network : mDNS name and client address settings, with the current address
static esp_err_t network_get(httpd_req_t *req)
{
net_cfg_t n;
settings_load_net(&n);
char ip[16];
bool up = net_sta_status(ip, sizeof(ip));
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "hostname", n.hostname);
cJSON_AddStringToObject(o, "mode", n.use_static ? "static" : "dhcp");
cJSON_AddStringToObject(o, "ip", n.ip);
cJSON_AddStringToObject(o, "netmask", n.netmask);
cJSON_AddStringToObject(o, "gateway", n.gateway);
cJSON_AddStringToObject(o, "dns", n.dns);
cJSON_AddBoolToObject(o, "connected", up);
cJSON_AddStringToObject(o, "current_ip", ip);
return send_json(req, o);
}
// POST /api/network {"hostname","mode":"dhcp"|"static","ip","netmask","gateway","dns"}
// Missing fields keep their current value. Saves, applies and reconnects the client.
static esp_err_t network_post(httpd_req_t *req)
{
cJSON *in = read_json(req);
if (!in) {
return send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
}
net_cfg_t n;
settings_load_net(&n);
cJSON *h = cJSON_GetObjectItem(in, "hostname");
if (cJSON_IsString(h)) {
char name[64];
strncpy(name, h->valuestring, sizeof(name) - 1);
name[sizeof(name) - 1] = '\0';
for (char *p = name; *p; p++) {
if (*p >= 'A' && *p <= 'Z') *p = *p - 'A' + 'a';
}
if (!valid_hostname(name)) {
cJSON_Delete(in);
return send_error(req, "400 Bad Request", "hostname: 1-63 letters, digits or hyphens");
}
strncpy(n.hostname, name, sizeof(n.hostname) - 1);
}
cJSON *mode = cJSON_GetObjectItem(in, "mode");
if (cJSON_IsString(mode)) {
if (strcmp(mode->valuestring, "static") == 0) {
n.use_static = true;
} else if (strcmp(mode->valuestring, "dhcp") == 0) {
n.use_static = false;
} else {
cJSON_Delete(in);
return send_error(req, "400 Bad Request", "mode must be dhcp or static");
}
}
struct { const char *key; char *dst; size_t len; } fields[] = {
{ "ip", n.ip, sizeof(n.ip) },
{ "netmask", n.netmask, sizeof(n.netmask) },
{ "gateway", n.gateway, sizeof(n.gateway) },
{ "dns", n.dns, sizeof(n.dns) },
};
for (auto &f : fields) {
cJSON *v = cJSON_GetObjectItem(in, f.key);
if (cJSON_IsString(v)) {
strncpy(f.dst, v->valuestring, f.len - 1);
f.dst[f.len - 1] = '\0';
}
}
cJSON_Delete(in);
if (n.use_static) {
if (!valid_ipv4(n.ip) || !valid_ipv4(n.netmask) || !valid_ipv4(n.gateway)) {
return send_error(req, "400 Bad Request", "static mode needs ip, netmask and gateway as IPv4 addresses");
}
if (n.dns[0] && !valid_ipv4(n.dns)) {
return send_error(req, "400 Bad Request", "dns must be an IPv4 address or empty");
}
}
esp_err_t err = net_save_network(&n);
if (err != ESP_OK) {
ESP_LOGW(TAG, "Network apply failed: %s", esp_err_to_name(err));
return send_error(req, "500 Internal Server Error", esp_err_to_name(err));
}
// With a static address the page's current address changes, so say where to go next
char addr[80];
if (n.use_static) {
snprintf(addr, sizeof(addr), "%s", n.ip);
} else {
snprintf(addr, sizeof(addr), "%s.local", n.hostname);
}
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "message", "saved; reconnecting");
cJSON_AddStringToObject(o, "address", addr);
return send_json(req, o);
}
// ---- presets -----------------------------------------------------------------------------------
// ---- LED strip hardware ------------------------------------------------------------------------
static bool valid_order(const char *s)
{
if (strlen(s) != 3) return false;
bool seen[3] = { false, false, false };
for (int i = 0; i < 3; i++) {
int k = s[i] == 'r' ? 0 : (s[i] == 'g' ? 1 : (s[i] == 'b' ? 2 : -1));
if (k < 0 || seen[k]) return false;
seen[k] = true;
}
return true;
}
// GPIOs that can drive the strip on the ESP32-C3: not the flash (11-17) or the USB (18, 19)
static bool valid_pin(int pin)
{
return (pin >= 0 && pin <= 10) || pin == 20 || pin == 21;
}
// GET /api/hardware : LED strip settings
static esp_err_t hardware_get(httpd_req_t *req)
{
hw_cfg_t hw;
settings_load_hw(&hw);
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "rgb_order", hw.order);
cJSON_AddNumberToObject(o, "max_brightness", hw.max_brightness);
cJSON_AddNumberToObject(o, "num_leds", hw.num_leds);
cJSON_AddNumberToObject(o, "pin", hw.pin);
return send_json(req, o);
}
// POST /api/hardware {"rgb_order","max_brightness":0-255,"num_leds":1-512}. Missing fields keep their value.
static esp_err_t hardware_post(httpd_req_t *req)
{
cJSON *in = read_json(req);
if (!in) {
return send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
}
hw_cfg_t hw;
settings_load_hw(&hw);
cJSON *v = cJSON_GetObjectItem(in, "rgb_order");
if (cJSON_IsString(v)) {
char order[4];
for (int i = 0; i < 3; i++) order[i] = (char)(v->valuestring[i] >= 'A' && v->valuestring[i] <= 'Z' ? v->valuestring[i] + 32 : v->valuestring[i]);
order[3] = '\0';
if (!valid_order(order)) {
cJSON_Delete(in);
return send_error(req, "400 Bad Request", "rgb_order must be rgb, rbg, grb, gbr, brg or bgr");
}
strncpy(hw.order, order, sizeof(hw.order));
}
v = cJSON_GetObjectItem(in, "max_brightness");
if (cJSON_IsNumber(v)) {
if (v->valueint < 0 || v->valueint > 255) {
cJSON_Delete(in);
return send_error(req, "400 Bad Request", "max_brightness must be 0-255");
}
hw.max_brightness = (uint8_t)v->valueint;
}
v = cJSON_GetObjectItem(in, "num_leds");
if (cJSON_IsNumber(v)) {
if (v->valueint < 1 || v->valueint > FX_LEDS_MAX) {
cJSON_Delete(in);
return send_error(req, "400 Bad Request", "num_leds must be 1-512");
}
hw.num_leds = v->valueint;
}
v = cJSON_GetObjectItem(in, "pin");
if (cJSON_IsNumber(v)) {
if (!valid_pin(v->valueint)) {
cJSON_Delete(in);
return send_error(req, "400 Bad Request", "pin must be 0-10 or 20-21 (not 11-19, which the flash and USB use)");
}
hw.pin = v->valueint;
}
cJSON_Delete(in);
esp_err_t err = patterns_set_hardware(hw);
if (err != ESP_OK) {
return send_error(req, "500 Internal Server Error", esp_err_to_name(err));
}
err = settings_save_hw(&hw);
if (err != ESP_OK) {
return send_error(req, "500 Internal Server Error", esp_err_to_name(err));
}
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "message", "saved");
return send_json(req, o);
}
// GET /api/ddp[?led=N] : DDP receiver state, and the colour shown on LED N (for checks)
static esp_err_t ddp_get(httpd_req_t *req)
{
bool active;
uint32_t packets;
patterns_ddp_status(&active, &packets);
int led = 0;
char q[32];
if (httpd_req_get_url_query_str(req, q, sizeof(q)) == ESP_OK) {
char v[8];
if (httpd_query_key_value(q, "led", v, sizeof(v)) == ESP_OK) {
led = atoi(v);
}
}
uint8_t px[3];
patterns_shown_pixel(led, px);
cJSON *o = cJSON_CreateObject();
cJSON_AddBoolToObject(o, "active", active);
cJSON_AddNumberToObject(o, "packets", packets);
cJSON_AddNumberToObject(o, "port", DDP_PORT);
cJSON_AddNumberToObject(o, "led", led);
cJSON *px_arr = cJSON_AddArrayToObject(o, "rgb");
for (int i = 0; i < 3; i++) {
cJSON_AddItemToArray(px_arr, cJSON_CreateNumber(px[i]));
}
return send_json(req, o);
}
// POST /api/presets/order {"names":[...]} : the presets' order on the front page
static esp_err_t presets_order_post(httpd_req_t *req)
{
cJSON *in = read_json(req);
if (!in) {
return send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
}
cJSON *arr = cJSON_GetObjectItem(in, "names");
if (!cJSON_IsArray(arr)) {
cJSON_Delete(in);
return send_error(req, "400 Bad Request", "names must be a list");
}
const char *names[PRESETS_MAX];
size_t n = 0;
cJSON *item;
cJSON_ArrayForEach(item, arr) {
if (n < PRESETS_MAX && cJSON_IsString(item)) {
names[n++] = item->valuestring;
}
}
presets_set_order(names, n);
cJSON_Delete(in);
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "message", "saved");
return send_json(req, o);
}
// POST /api/presets/defaults : add the default presets that are missing
static esp_err_t presets_defaults_post(httpd_req_t *req)
{
cJSON *o = cJSON_CreateObject();
cJSON_AddNumberToObject(o, "added", presets_add_defaults());
return send_json(req, o);
}
// GET /api/presets
static esp_err_t presets_get(httpd_req_t *req)
{
cJSON *o = cJSON_CreateObject();
cJSON *arr = cJSON_AddArrayToObject(o, "presets");
for (size_t i = 0; i < presets_count(); i++) {
cJSON_AddItemToArray(arr, preset_to_json(presets_at(i)));
}
cJSON_AddStringToObject(o, "selected", presets_selected());
cJSON_AddStringToObject(o, "startup", presets_startup());
cJSON_AddNumberToObject(o, "max", PRESETS_MAX);
return send_json(req, o);
}
// POST /api/brightness {"brightness":0-255} : live brightness for every pattern, saved
static esp_err_t brightness_post(httpd_req_t *req)
{
cJSON *in = read_json(req);
if (!in) {
return send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
}
cJSON *v = cJSON_GetObjectItem(in, "brightness");
if (!cJSON_IsNumber(v) || v->valueint < 0 || v->valueint > 255) {
cJSON_Delete(in);
return send_error(req, "400 Bad Request", "brightness must be 0-255");
}
uint8_t level = (uint8_t)v->valueint;
cJSON_Delete(in);
patterns_set_global(level);
hw_cfg_t hw;
settings_load_hw(&hw);
hw.global_brightness = level;
settings_save_hw(&hw);
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "message", "saved");
return send_json(req, o);
}
// POST /api/presets : create or update by name. Missing fields take the running settings.
static esp_err_t presets_post(httpd_req_t *req)
{
cJSON *in = read_json(req);
if (!in) {
return send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
}
cJSON *name = cJSON_GetObjectItem(in, "name");
if (!cJSON_IsString(name) || !name->valuestring[0] || strlen(name->valuestring) >= 32) {
cJSON_Delete(in);
return send_error(req, "400 Bad Request", "name must be 1-31 characters");
}
preset_t pr;
patterns_get(&pr);
bool ok = preset_from_json(in, &pr);
cJSON_Delete(in);
if (!ok) {
return send_error(req, "400 Bad Request", "unknown pattern");
}
esp_err_t err = presets_save(&pr);
if (err == ESP_ERR_NO_MEM) {
return send_error(req, "400 Bad Request", "preset list is full");
}
if (err != ESP_OK) {
return send_error(req, "500 Internal Server Error", esp_err_to_name(err));
}
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "message", "saved");
return send_json(req, o);
}
// Shared body for select, delete and startup: {"name"}
static esp_err_t preset_name_action(httpd_req_t *req, esp_err_t (*action)(const char *), const char *ok_msg)
{
cJSON *in = read_json(req);
if (!in) {
return send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
}
cJSON *name = cJSON_GetObjectItem(in, "name");
if (!cJSON_IsString(name)) {
cJSON_Delete(in);
return send_error(req, "400 Bad Request", "name is required");
}
char buf[32];
strncpy(buf, name->valuestring, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = '\0';
cJSON_Delete(in);
esp_err_t err = action(buf);
if (err == ESP_ERR_NOT_FOUND) {
return send_error(req, "404 Not Found", "no such preset");
}
if (err != ESP_OK) {
return send_error(req, "500 Internal Server Error", esp_err_to_name(err));
}
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "message", ok_msg);
return send_json(req, o);
}
static esp_err_t select_post(httpd_req_t *req)
{
return preset_name_action(req, presets_select, "selected");
}
static esp_err_t delete_post(httpd_req_t *req)
{
return preset_name_action(req, presets_delete, "deleted");
}
static esp_err_t startup_post(httpd_req_t *req)
{
return preset_name_action(req, presets_set_startup, "startup set");
}
static void add_uri(httpd_handle_t srv, const char *uri, httpd_method_t method, esp_err_t (*handler)(httpd_req_t *))
{
httpd_uri_t u = { .uri = uri, .method = method, .handler = handler, .user_ctx = NULL };
httpd_register_uri_handler(srv, &u);
}
// Host part of a relay target: letters, digits, dots, dashes and an optional :port.
static bool relay_host_ok(const char *h)
{
size_t n = strlen(h);
if (n == 0 || n > 80) {
return false;
}
for (const char *p = h; *p; p++) {
char c = *p;
bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == ':';
if (!ok) {
return false;
}
}
return true;
}
// Only this driver's own API and its firmware info and reboot, so the relay cannot reach other services.
static bool relay_path_ok(const char *p)
{
if (strcmp(p, "/ota") == 0 || strcmp(p, "/reboot") == 0) {
return true;
}
if (strncmp(p, "/api/", 5) != 0 || strcmp(p, "/api/relay") == 0 || strlen(p) > 120) {
return false;
}
return strstr(p, "..") == NULL && strchr(p, ' ') == NULL && strchr(p, '\r') == NULL && strchr(p, '\n') == NULL;
}
// POST /api/relay {"host": "10.1.1.50", "method": "GET" or "POST", "path": "/api/status", "body": "..."}
// Calls another driver from here and answers {"status": n, "body": "..."}. A page on this driver only
// talks to this driver, so the browser never has to reach the other device itself.
static esp_err_t relay_post(httpd_req_t *req)
{
// Heap buffers: the HTTP server task has an 8 KB stack
char *in = (char *)malloc(2048);
char *out = (char *)malloc(4096);
if (!in || !out) {
free(in);
free(out);
return send_error(req, "503 Service Unavailable", "out of memory");
}
esp_err_t result = ESP_FAIL;
if (!read_body(req, in, 2048)) {
result = send_error(req, "400 Bad Request", "empty, too large or invalid JSON");
goto done;
} else {
cJSON *top = cJSON_Parse(in);
const cJSON *jh = top ? cJSON_GetObjectItem(top, "host") : NULL;
const cJSON *jm = top ? cJSON_GetObjectItem(top, "method") : NULL;
const cJSON *jp = top ? cJSON_GetObjectItem(top, "path") : NULL;
const cJSON *jb = top ? cJSON_GetObjectItem(top, "body") : NULL;
if (!cJSON_IsString(jh) || !cJSON_IsString(jm) || !cJSON_IsString(jp) || !relay_host_ok(jh->valuestring)
|| !relay_path_ok(jp->valuestring) || (strcmp(jm->valuestring, "GET") != 0 && strcmp(jm->valuestring, "POST") != 0)) {
cJSON_Delete(top);
result = send_error(req, "400 Bad Request", "need host, method GET or POST, and a path under /api/");
goto done;
}
const bool is_post = strcmp(jm->valuestring, "POST") == 0;
const char *body = (is_post && cJSON_IsString(jb)) ? jb->valuestring : "";
const int body_len = (int)strlen(body);
char url[200];
snprintf(url, sizeof(url), "http://%s%s", jh->valuestring, jp->valuestring);
esp_http_client_config_t ccfg = {};
ccfg.url = url;
ccfg.method = is_post ? HTTP_METHOD_POST : HTTP_METHOD_GET;
ccfg.timeout_ms = 4000;
esp_http_client_handle_t cl = esp_http_client_init(&ccfg);
if (!cl) {
cJSON_Delete(top);
result = send_error(req, "502 Bad Gateway", "could not start the request");
goto done;
}
esp_http_client_set_header(cl, "Content-Type", "text/plain");
esp_err_t err = esp_http_client_open(cl, is_post ? body_len : 0);
if (err == ESP_OK && is_post && body_len > 0) {
if (esp_http_client_write(cl, body, body_len) != body_len) {
err = ESP_FAIL;
}
}
int got = 0;
int status = 0;
if (err == ESP_OK && esp_http_client_fetch_headers(cl) >= 0) {
status = esp_http_client_get_status_code(cl);
int r;
while (got < 4095 && (r = esp_http_client_read(cl, out + got, 4095 - got)) > 0) {
got += r;
}
} else {
err = ESP_FAIL;
}
esp_http_client_close(cl);
esp_http_client_cleanup(cl);
cJSON_Delete(top);
if (err != ESP_OK) {
result = send_error(req, "502 Bad Gateway", "could not reach that device");
goto done;
}
out[got] = '\0';
cJSON *o = cJSON_CreateObject();
cJSON_AddNumberToObject(o, "status", status);
cJSON_AddStringToObject(o, "body", out);
result = send_json(req, o);
}
done:
free(in);
free(out);
return result;
}
// GET /api/devices: the LED drivers on this network, found by mDNS (they advertise app=led-strip).
// Includes this driver; the page leaves it out, since "This device" is already in the list.
static esp_err_t devices_get(httpd_req_t *req)
{
cJSON *arr = cJSON_CreateArray();
mdns_result_t *res = NULL;
if (mdns_query_ptr("_http", "_tcp", 1500, 30, &res) == ESP_OK && res) {
for (mdns_result_t *r = res; r; r = r->next) {
if (!r->hostname) {
continue;
}
bool is_strip = false;
for (size_t i = 0; i < r->txt_count && r->txt; i++) {
if (r->txt[i].key && r->txt[i].value && strcmp(r->txt[i].key, "app") == 0
&& strcmp(r->txt[i].value, "led-strip") == 0) {
is_strip = true;
}
}
if (!is_strip) {
continue;
}
char ip[16] = "";
for (mdns_ip_addr_t *a = r->addr; a; a = a->next) {
if (a->addr.type == ESP_IPADDR_TYPE_V4) {
snprintf(ip, sizeof(ip), IPSTR, IP2STR(&a->addr.u_addr.ip4));
break;
}
}
if (ip[0] == '\0') {
continue;
}
bool seen = false; // one entry per address (a service can be listed twice)
for (int i = 0; i < cJSON_GetArraySize(arr); i++) {
const cJSON *ip_item = cJSON_GetObjectItem(cJSON_GetArrayItem(arr, i), "ip");
if (cJSON_IsString(ip_item) && strcmp(ip_item->valuestring, ip) == 0) {
seen = true;
}
}
if (seen) {
continue;
}
char host[96];
snprintf(host, sizeof(host), "%s.local", r->hostname);
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "name", r->hostname);
cJSON_AddStringToObject(o, "host", host);
cJSON_AddStringToObject(o, "ip", ip);
cJSON_AddItemToArray(arr, o);
}
}
if (res) {
mdns_query_results_free(res);
}
cJSON *top = cJSON_CreateObject();
cJSON_AddItemToObject(top, "devices", arr);
return send_json(req, top);
}
esp_err_t web_start(void)
{
httpd_config_t cfg = HTTPD_DEFAULT_CONFIG();
cfg.max_uri_handlers = 30;
cfg.stack_size = 8192;
cfg.lru_purge_enable = true;
cfg.max_open_sockets = 7;
cfg.backlog_conn = 10;
esp_err_t err = httpd_start(&s_server, &cfg);
if (err != ESP_OK) {
ESP_LOGE(TAG, "HTTP server start failed: %s", esp_err_to_name(err));
return err;
}
add_uri(s_server, "/", HTTP_GET, index_get);
add_uri(s_server, "/app.js", HTTP_GET, app_js_get);
add_uri(s_server, "/style.css", HTTP_GET, style_css_get);
add_uri(s_server, "/api/status", HTTP_GET, status_get);
add_uri(s_server, "/api/pattern", HTTP_POST, pattern_post);
add_uri(s_server, "/api/wifi", HTTP_GET, wifi_get);
add_uri(s_server, "/api/wifi", HTTP_POST, wifi_post);
add_uri(s_server, "/api/wifi/scan", HTTP_GET, wifi_scan_get);
add_uri(s_server, "/api/network", HTTP_GET, network_get);
add_uri(s_server, "/api/network", HTTP_POST, network_post);
add_uri(s_server, "/api/ddp", HTTP_GET, ddp_get);
add_uri(s_server, "/api/hardware", HTTP_GET, hardware_get);
add_uri(s_server, "/api/hardware", HTTP_POST, hardware_post);
add_uri(s_server, "/api/presets", HTTP_GET, presets_get);
add_uri(s_server, "/api/presets", HTTP_POST, presets_post);
add_uri(s_server, "/api/presets/select", HTTP_POST, select_post);
add_uri(s_server, "/api/presets/delete", HTTP_POST, delete_post);
add_uri(s_server, "/api/presets/startup", HTTP_POST, startup_post);
add_uri(s_server, "/api/presets/defaults", HTTP_POST, presets_defaults_post);
add_uri(s_server, "/api/presets/order", HTTP_POST, presets_order_post);
add_uri(s_server, "/api/brightness", HTTP_POST, brightness_post);
add_uri(s_server, "/api/relay", HTTP_POST, relay_post);
add_uri(s_server, "/api/devices", HTTP_GET, devices_get);
ota_register(s_server);
ESP_LOGI(TAG, "Web UI on port 80");
return ESP_OK;
}
+24
View File
@@ -0,0 +1,24 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include "esp_err.h"
#include "esp_http_server.h"
#ifdef __cplusplus
extern "C" {
#endif
/** @brief Start the HTTP server on port 80 (UI and JSON API). */
esp_err_t web_start(void);
/**
* @brief Add Access-Control-Allow-Origin for a LAN or localhost page that asked (the Origin header).
* Call before the response is sent. Other origins get no header, so the browser blocks them.
*/
void web_allow_lan_origin(httpd_req_t *req);
#ifdef __cplusplus
}
#endif
+258
View File
@@ -0,0 +1,258 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#include "ws2812.h"
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "esp_check.h"
#include "esp_log.h"
static const char *TAG = "ws2812";
/* ---- RMT encoder: turns RGB bytes into WS2812 waveform symbols ---- */
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_ws2812_encoder_t;
RMT_ENCODER_FUNC_ATTR
static size_t rmt_encode_ws2812(rmt_encoder_t *encoder, rmt_channel_handle_t channel, const void *primary_data, size_t data_size, rmt_encode_state_t *ret_state)
{
rmt_ws2812_encoder_t *led_encoder = __containerof(encoder, rmt_ws2812_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 = RMT_ENCODING_RESET;
rmt_encode_state_t state = RMT_ENCODING_RESET;
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 = static_cast<rmt_encode_state_t>(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 = RMT_ENCODING_RESET; // back to the initial encoding session
state = static_cast<rmt_encode_state_t>(state | RMT_ENCODING_COMPLETE);
}
if (session_state & RMT_ENCODING_MEM_FULL) {
state = static_cast<rmt_encode_state_t>(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_ws2812_encoder(rmt_encoder_t *encoder)
{
rmt_ws2812_encoder_t *led_encoder = __containerof(encoder, rmt_ws2812_encoder_t, base);
rmt_del_encoder(led_encoder->bytes_encoder);
rmt_del_encoder(led_encoder->copy_encoder);
free(led_encoder);
return ESP_OK;
}
RMT_ENCODER_FUNC_ATTR
static esp_err_t rmt_ws2812_encoder_reset(rmt_encoder_t *encoder)
{
rmt_ws2812_encoder_t *led_encoder = __containerof(encoder, rmt_ws2812_encoder_t, base);
rmt_encoder_reset(led_encoder->bytes_encoder);
rmt_encoder_reset(led_encoder->copy_encoder);
led_encoder->state = RMT_ENCODING_RESET;
return ESP_OK;
}
static esp_err_t new_ws2812_encoder(uint32_t resolution, rmt_encoder_handle_t *ret_encoder)
{
// Declared up front: the error path jumps forward to `err`, which C++ forbids
// across initialised declarations.
esp_err_t ret = ESP_OK;
rmt_ws2812_encoder_t *led_encoder = NULL;
rmt_bytes_encoder_config_t bytes_encoder_config = {};
rmt_copy_encoder_config_t copy_encoder_config = {};
uint32_t reset_ticks = 0;
ESP_GOTO_ON_FALSE(ret_encoder, ESP_ERR_INVALID_ARG, err, TAG, "invalid argument");
led_encoder = static_cast<rmt_ws2812_encoder_t *>(rmt_alloc_encoder_mem(sizeof(rmt_ws2812_encoder_t)));
ESP_GOTO_ON_FALSE(led_encoder, ESP_ERR_NO_MEM, err, TAG, "no mem for ws2812 encoder");
led_encoder->base.encode = rmt_encode_ws2812;
led_encoder->base.del = rmt_del_ws2812_encoder;
led_encoder->base.reset = rmt_ws2812_encoder_reset;
// WS2812 timing
bytes_encoder_config.bit0.level0 = 1;
bytes_encoder_config.bit0.duration0 = 0.3 * resolution / 1000000; // T0H=0.3us
bytes_encoder_config.bit0.level1 = 0;
bytes_encoder_config.bit0.duration1 = 0.9 * resolution / 1000000; // T0L=0.9us
bytes_encoder_config.bit1.level0 = 1;
bytes_encoder_config.bit1.duration0 = 0.9 * resolution / 1000000; // T1H=0.9us
bytes_encoder_config.bit1.level1 = 0;
bytes_encoder_config.bit1.duration1 = 0.3 * resolution / 1000000; // T1L=0.3us
bytes_encoder_config.flags.msb_first = 1; // WS2812 transfer bit order: G7...G0R7...R0B7...B0
ESP_GOTO_ON_ERROR(rmt_new_bytes_encoder(&bytes_encoder_config, &led_encoder->bytes_encoder), err, TAG, "create bytes encoder failed");
ESP_GOTO_ON_ERROR(rmt_new_copy_encoder(&copy_encoder_config, &led_encoder->copy_encoder), err, TAG, "create copy encoder failed");
reset_ticks = resolution / 1000000 * 50 / 2; // reset code duration defaults to 50us
led_encoder->reset_code.level0 = 0;
led_encoder->reset_code.duration0 = reset_ticks;
led_encoder->reset_code.level1 = 0;
led_encoder->reset_code.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;
}
/* ---- WS2812 strip ---- */
WS2812::WS2812(gpio_num_t gpio, size_t num_leds, uint32_t resolution_hz)
: num_leds_(num_leds), pixels_(num_leds * 3, 0), tx_pixels_(num_leds * 3, 0)
{
rmt_tx_channel_config_t tx_chan_config = {};
tx_chan_config.clk_src = RMT_CLK_SRC_DEFAULT;
tx_chan_config.gpio_num = gpio;
tx_chan_config.mem_block_symbols = 64; // larger blocks reduce flicker
tx_chan_config.resolution_hz = resolution_hz;
tx_chan_config.trans_queue_depth = 4;
ESP_ERROR_CHECK(rmt_new_tx_channel(&tx_chan_config, &channel_));
ESP_ERROR_CHECK(new_ws2812_encoder(resolution_hz, &encoder_));
ESP_ERROR_CHECK(rmt_enable(channel_));
tx_config_.loop_count = 0; // send once per write()
ESP_LOGI(TAG, "Strip ready: %zu LEDs on GPIO %d", num_leds_, (int)gpio);
}
WS2812::~WS2812()
{
if (channel_) {
rmt_tx_wait_all_done(channel_, portMAX_DELAY);
rmt_disable(channel_);
rmt_del_channel(channel_);
}
if (encoder_) {
encoder_->del(encoder_);
}
}
void WS2812::set(size_t index, uint8_t r, uint8_t g, uint8_t b)
{
if (index >= num_leds_) {
return;
}
uint8_t *p = &pixels_[index * 3];
uint8_t c[3] = { r, g, b };
p[0] = c[order_[0]];
p[1] = c[order_[1]];
p[2] = c[order_[2]];
}
void WS2812::setOrder(const char *order)
{
if (!order || strlen(order) != 3) {
return;
}
uint8_t idx[3];
for (int i = 0; i < 3; i++) {
switch (order[i]) {
case 'r': idx[i] = 0; break;
case 'g': idx[i] = 1; break;
case 'b': idx[i] = 2; break;
default: return;
}
}
if (idx[0] == idx[1] || idx[1] == idx[2] || idx[0] == idx[2]) {
return;
}
memcpy(order_, idx, sizeof(order_));
}
void WS2812::fill(uint8_t r, uint8_t g, uint8_t b)
{
for (size_t i = 0; i < num_leds_; i++) {
set(i, r, g, b);
}
}
esp_err_t WS2812::write()
{
for (size_t i = 0; i < pixels_.size(); i++) {
tx_pixels_[i] = static_cast<uint8_t>(pixels_[i] * brightness_ / 255);
}
esp_err_t ret = rmt_transmit(channel_, encoder_, tx_pixels_.data(), tx_pixels_.size(), &tx_config_);
if (ret != ESP_OK) {
return ret;
}
return rmt_tx_wait_all_done(channel_, portMAX_DELAY);
}
void WS2812::hsv2rgb(uint32_t h, uint32_t s, uint32_t v, uint32_t *r, uint32_t *g, uint32_t *b)
{
h %= 360; // h -> [0,360]
uint32_t rgb_max = v * 2.55f;
uint32_t rgb_min = rgb_max * (100 - s) / 100.0f;
uint32_t i = h / 60;
uint32_t diff = h % 60;
// RGB adjustment amount by hue
uint32_t rgb_adj = (rgb_max - rgb_min) * diff / 60;
switch (i) {
case 0:
*r = rgb_max;
*g = rgb_min + rgb_adj;
*b = rgb_min;
break;
case 1:
*r = rgb_max - rgb_adj;
*g = rgb_max;
*b = rgb_min;
break;
case 2:
*r = rgb_min;
*g = rgb_max;
*b = rgb_min + rgb_adj;
break;
case 3:
*r = rgb_min;
*g = rgb_max - rgb_adj;
*b = rgb_max;
break;
case 4:
*r = rgb_min + rgb_adj;
*g = rgb_min;
*b = rgb_max;
break;
default:
*r = rgb_max;
*g = rgb_min;
*b = rgb_max - rgb_adj;
break;
}
}
+82
View File
@@ -0,0 +1,82 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <cstddef>
#include <cstdint>
#include <vector>
#include "driver/gpio.h"
#include "driver/rmt_encoder.h"
#include "driver/rmt_tx.h"
#include "esp_err.h"
/**
* @brief WS2812-style addressable LED strip driven through the RMT peripheral.
*
* Pixel data is kept in a local buffer. set() and fill() only update that buffer;
* call write() to push the buffer out to the strip.
*/
class WS2812 {
public:
/**
* @param gpio GPIO connected to the strip's data input (DI)
* @param num_leds Number of LEDs in the strip
* @param resolution_hz RMT tick resolution; 10 MHz gives 0.1 us ticks, which WS2812 needs
*/
WS2812(gpio_num_t gpio, size_t num_leds, uint32_t resolution_hz = 10000000);
~WS2812();
WS2812(const WS2812 &) = delete;
WS2812 &operator=(const WS2812 &) = delete;
/** @brief Set one pixel in the buffer. Out-of-range indices are ignored. */
void set(size_t index, uint8_t r, uint8_t g, uint8_t b);
/** @brief Set every pixel in the buffer to the same colour. */
void fill(uint8_t r, uint8_t g, uint8_t b);
/**
* @brief Transmit the buffer to the strip and wait until the transfer finishes.
* @return ESP_OK on success, or an error from the RMT driver.
*/
esp_err_t write();
/** @brief Number of LEDs in the strip. */
size_t size() const { return num_leds_; }
/**
* @brief Set the output brightness, 0 (off) to 255 (full). Applied in write();
* the pixel buffer keeps its full-colour values. Defaults to 255.
*/
void setBrightness(uint8_t level) { brightness_ = level; }
/** @brief Current output brightness, 0-255. */
uint8_t brightness() const { return brightness_; }
/**
* @brief Convert HSV to RGB.
*
* h is the hue in degrees (wrapped to [0, 360)); s and v are 0-100 percent.
* Wiki: https://en.wikipedia.org/wiki/HSL_and_HSV
*/
static void hsv2rgb(uint32_t h, uint32_t s, uint32_t v, uint32_t *r, uint32_t *g, uint32_t *b);
/**
* @brief Byte order of the strip, as the letters of the colours in the order they are sent.
* "grb" (the default) is the WS2812 norm; "rgb", "rbg", "gbr", "brg" and "bgr" cover the rest.
* Unknown names keep the current order.
*/
void setOrder(const char *order);
private:
size_t num_leds_;
uint8_t order_[3] = { 1, 0, 2 }; // indices into (r, g, b) for each byte sent: GRB
std::vector<uint8_t> pixels_; // 3 bytes per LED, in the strip's byte order
std::vector<uint8_t> tx_pixels_; // pixels_ scaled by brightness_, sent by write()
uint8_t brightness_ = 255;
rmt_channel_handle_t channel_ = nullptr;
rmt_encoder_handle_t encoder_ = nullptr;
rmt_transmit_config_t tx_config_ = {};
};
+6
View File
@@ -0,0 +1,6 @@
# Name, Type, SubType, Offset, Size
nvs, data, nvs, 0x9000, 0x6000
otadata, data, ota, 0xf000, 0x2000
phy_init, data, phy, 0x11000, 0x1000
ota_0, app, ota_0, 0x20000, 0x1E0000
ota_1, app, ota_1, 0x200000, 0x1E0000
1 # Name Type SubType Offset Size
2 nvs data nvs 0x9000 0x6000
3 otadata data ota 0xf000 0x2000
4 phy_init data phy 0x11000 0x1000
5 ota_0 app ota_0 0x20000 0x1E0000
6 ota_1 app ota_1 0x200000 0x1E0000
+11
View File
@@ -0,0 +1,11 @@
CONFIG_IDF_TARGET="esp32c3"
# The mDNS console CLI needs the console component; the app does not use it.
CONFIG_MDNS_ENABLE_CONSOLE_CLI=n
# The chip has 4 MB: two app slots for over-the-air updates (see partitions.csv)
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
# A new OTA image must confirm itself (ota_confirm_later) or the bootloader goes back to the old one
CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
# mDNS opens sockets on both the AP and client interfaces, plus HTTP and DDP. The default 10 runs out and httpd stops accepting.
CONFIG_LWIP_MAX_SOCKETS=16
-239
View File
@@ -1,239 +0,0 @@
"""Parse controller JSON (v1) and apply brightness, presets, OTA patterns, etc."""
import json
import socket
from utils import convert_and_reorder_colors
try:
import uos as os
except ImportError:
import os
def process_data(payload, settings, presets, controller_ip=None):
"""Read one controller message; json.loads (bytes or str), then apply fields."""
try:
data = json.loads(payload)
print(payload)
if data.get("v", "") != "1":
return
except (ValueError, TypeError):
return
if "b" in data:
apply_brightness(data, settings, presets)
if "presets" in data:
apply_presets(data, settings, presets)
if "clear_presets" in data:
apply_clear_presets(data, presets)
if "select" in data:
apply_select(data, settings, presets)
if "default" in data:
apply_default(data, settings, presets)
if "manifest" in data:
apply_patterns_ota(data, presets, controller_ip=controller_ip)
if "save" in data and ("presets" in data or "default" in data):
presets.save()
if "save" in data and "clear_presets" in data:
presets.save()
def apply_brightness(data, settings, presets):
try:
presets.b = max(0, min(255, int(data["b"])))
settings["brightness"] = presets.b
except (TypeError, ValueError):
pass
def apply_presets(data, settings, presets):
presets_map = data["presets"]
for id, preset_data in presets_map.items():
if not preset_data:
continue
color_key = "c" if "c" in preset_data else ("colors" if "colors" in preset_data else None)
if color_key is not None:
try:
preset_data[color_key] = convert_and_reorder_colors(
preset_data[color_key], settings
)
except (TypeError, ValueError, KeyError):
continue
presets.edit(id, preset_data)
print(f"Edited preset {id}: {preset_data.get('name', '')}")
def apply_select(data, settings, presets):
select_map = data["select"]
device_name = settings["name"]
select_list = select_map.get(device_name, [])
if not select_list:
return
preset_name = select_list[0]
step = select_list[1] if len(select_list) > 1 else None
presets.select(preset_name, step=step)
def apply_clear_presets(data, presets):
clear_value = data.get("clear_presets")
if isinstance(clear_value, bool):
should_clear = clear_value
elif isinstance(clear_value, int):
should_clear = bool(clear_value)
elif isinstance(clear_value, str):
should_clear = clear_value.lower() in ("true", "1", "yes", "on")
else:
should_clear = False
if not should_clear:
return
presets.delete_all()
print("Cleared all presets.")
def apply_default(data, settings, presets):
targets = data.get("targets") or []
default_name = data["default"]
if (
settings["name"] in targets
and isinstance(default_name, str)
and default_name in presets.presets
):
settings["default"] = default_name
settings.save()
def _parse_http_url(url):
"""Parse http://host[:port]/path into (host, port, path)."""
if not isinstance(url, str):
raise ValueError("url must be a string")
if not url.startswith("http://"):
raise ValueError("only http:// URLs are supported")
remainder = url[7:]
slash_idx = remainder.find("/")
if slash_idx == -1:
host_port = remainder
path = "/"
else:
host_port = remainder[:slash_idx]
path = remainder[slash_idx:]
if ":" in host_port:
host, port_s = host_port.rsplit(":", 1)
port = int(port_s)
else:
host = host_port
port = 80
if not host:
raise ValueError("missing host")
return host, port, path
def _http_get_raw(url, timeout_s=10.0):
host, port, path = _parse_http_url(url)
req = (
"GET %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n" % (path, host)
).encode("utf-8")
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.settimeout(timeout_s)
sock.connect((host, int(port)))
sock.send(req)
data = b""
while True:
chunk = sock.recv(1024)
if not chunk:
break
data += chunk
finally:
try:
sock.close()
except Exception:
pass
sep = b"\r\n\r\n"
if sep not in data:
raise OSError("invalid HTTP response")
head, body = data.split(sep, 1)
status_line = head.split(b"\r\n", 1)[0]
if b" 200 " not in status_line:
raise OSError("HTTP status not OK: %s" % status_line.decode("utf-8"))
return body
def _http_get_json(url, timeout_s=10.0):
body = _http_get_raw(url, timeout_s=timeout_s)
return json.loads(body.decode("utf-8"))
def _http_get_text(url, timeout_s=10.0, controller_ip=None):
# Support relative URLs from controller messages.
if isinstance(url, str) and url.startswith("/"):
if not controller_ip:
raise OSError("controller IP unavailable for relative URL")
url = "http://%s%s" % (controller_ip, url)
try:
body = _http_get_raw(url, timeout_s=timeout_s)
return body.decode("utf-8")
except Exception:
# Fallback for mDNS/unresolvable host: retry against current controller IP.
if not controller_ip or not isinstance(url, str) or not url.startswith("http://"):
raise
_host, _port, path = _parse_http_url(url)
fallback = "http://%s:%d%s" % (controller_ip, _port, path)
body = _http_get_raw(fallback, timeout_s=timeout_s)
return body.decode("utf-8")
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 apply_patterns_ota(data, presets, controller_ip=None):
manifest_payload = data.get("manifest")
if not manifest_payload:
return
try:
if isinstance(manifest_payload, dict):
manifest = manifest_payload
elif isinstance(manifest_payload, str):
manifest = _http_get_json(manifest_payload, timeout_s=20.0)
else:
print("patterns_ota: invalid manifest payload type")
return
files = manifest.get("files", [])
if not isinstance(files, list) or not files:
print("patterns_ota: no files in manifest")
return
try:
os.mkdir("patterns")
except OSError:
pass
updated = 0
for item in files:
if not isinstance(item, dict):
continue
name = item.get("name")
url = item.get("url")
inline_code = item.get("code")
if not _safe_pattern_filename(name):
continue
if isinstance(inline_code, str):
code = inline_code
elif isinstance(url, str):
code = _http_get_text(url, timeout_s=20.0, controller_ip=controller_ip)
else:
continue
with open("patterns/" + name, "w") as f:
f.write(code)
updated += 1
if updated > 0:
presets.reload_patterns()
print("patterns_ota: updated", updated, "pattern file(s)")
else:
print("patterns_ota: no valid files downloaded")
except Exception as e:
print("patterns_ota failed:", e)
-191
View File
@@ -1,191 +0,0 @@
"""LED hello JSON line and UDP broadcast on port 8766.
Used so led-controller can register the device (name, MAC, IP) when ``wait_reply`` is
false; the controller may then connect to the device's WebSocket. With
``wait_reply`` true, blocks for an echo and returns the controller IP (legacy discovery).
Wi-Fi must already be connected; this module does not use Settings or call connect().
"""
import json
import socket
import ubinascii
import network
# Match led-controller/tests/udp_server.py
DISCOVERY_UDP_PORT = 8766
DEFAULT_RECV_TIMEOUT_S = 3
def pack_hello_dict(sta, device_name=""):
"""Same fields as main HTTP/ESP-NOW hello."""
mac = sta.config("mac")
return {
"v": "1",
"device_name": device_name,
"mac": ubinascii.hexlify(mac).decode().lower(),
"type": "led",
}
def pack_hello_bytes(sta, device_name=""):
return json.dumps(pack_hello_dict(sta, device_name)).encode("utf-8")
def pack_hello_line(sta, device_name=""):
"""JSON hello + newline (HTTP/UDP discovery payloads)."""
return pack_hello_bytes(sta, device_name) + b"\n"
def ipv4_broadcast(ip, netmask):
"""Directed broadcast (e.g. 192.168.1.0/24 -> 192.168.1.255)."""
ia = [int(x) for x in ip.split(".")]
im = [int(x) for x in netmask.split(".")]
if len(ia) != 4 or len(im) != 4:
return None
# STA often reports 255.255.255.255; "broadcast" would equal the host IP — useless for LAN.
if netmask == "255.255.255.255":
return None
bcast = ".".join(str(ia[i] | (255 - im[i])) for i in range(4))
if bcast == ip:
return None
return bcast
def udp_discovery_targets(ip, mask):
"""(directed_broadcast, port) then limited broadcast."""
out = [("255.255.255.255", DISCOVERY_UDP_PORT)]
b = ipv4_broadcast(ip, mask)
if b:
out.insert(0, (b, DISCOVERY_UDP_PORT))
return out
def _udp_discovery_targets_single(ip, mask):
"""One destination: subnet broadcast if known, else limited broadcast."""
b = ipv4_broadcast(ip, mask)
if b:
return [(b, DISCOVERY_UDP_PORT)]
return [("255.255.255.255", DISCOVERY_UDP_PORT)]
def broadcast_hello_udp(
sta,
device_name="",
*,
wait_reply=True,
recv_timeout_s=DEFAULT_RECV_TIMEOUT_S,
wdt=None,
dual_destinations=True,
):
"""
Send pack_hello_line on DISCOVERY_UDP_PORT.
STA must already be connected with a valid IPv4 (caller brings up Wi-Fi).
If dual_destinations (default), send subnet broadcast then 255.255.255.255 so
discovery works on awkward APs — the controller may receive two packets.
If dual_destinations is False, send only one (subnet broadcast or limited),
e.g. after TCP connect so the Pi does not run duplicate resync handlers.
If wait_reply, wait for first UDP echo. Returns controller IP string or None.
"""
ip, mask, _gw, _dns = sta.ifconfig()
msg = pack_hello_line(sta, device_name)
print("hello:", msg)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
except (AttributeError, OSError) as e:
print("SO_BROADCAST not set:", e)
try:
sock.bind((ip, 0))
except (AttributeError, OSError, TypeError) as e:
try:
sock.bind(("0.0.0.0", 0))
except (AttributeError, OSError) as e2:
print("bind skipped:", e, e2)
if wait_reply:
try:
sock.settimeout(recv_timeout_s)
except (AttributeError, OSError):
pass
discovered = None
targets = (
udp_discovery_targets(ip, mask)
if dual_destinations
else _udp_discovery_targets_single(ip, mask)
)
for dest_ip, dest_port in targets:
if wdt is not None:
wdt.feed()
label = "%s:%s" % (dest_ip, dest_port)
target = (dest_ip, dest_port)
try:
sock.sendto(msg, target)
print("sent hello ->", target)
except OSError as e:
print("sendto failed:", e)
continue
if not wait_reply:
continue
if wdt is not None:
wdt.feed()
try:
data, addr = sock.recvfrom(2048)
print("reply from", addr, ":", data)
remote_ip = addr[0]
if data != msg:
print("(warning: reply payload differs from hello; still using source IP.)")
discovered = remote_ip
print("Discovered controller at", remote_ip)
break
except OSError as e:
print("recv (no reply):", e, "via", label)
if dest_ip == "255.255.255.255":
print(
"(hint: many APs drop Wi-Fi client broadcast; try wired server or AP without client isolation.)"
)
sock.close()
return discovered
def discover_controller_udp(device_name="", wdt=None):
"""
Broadcast hello; return controller IP from first UDP echo, or None.
STA must already be connected.
device_name: logical name in the JSON (caller supplies, e.g. from Settings elsewhere).
wdt: optional WDT to feed during waits.
"""
sta = network.WLAN(network.STA_IF)
if not sta.isconnected():
print("hello: STA not connected — connect Wi-Fi before discovery.")
raise SystemExit(1)
ip, mask, _g, _d = sta.ifconfig()
if ip == "0.0.0.0":
print("hello: STA has no IP address.")
raise SystemExit(1)
print("STA IP:", ip, "mask:", mask)
discovered = broadcast_hello_udp(
sta,
device_name,
wait_reply=True,
wdt=wdt,
)
if discovered:
print("discover done; controller =", repr(discovered))
else:
print("discover done; controller not found")
return discovered
if __name__ == "__main__":
if not discover_controller_udp():
raise SystemExit(1)
-208
View File
@@ -1,208 +0,0 @@
from settings import Settings
import machine
import network
import utime
import asyncio
import json
import gc
from microdot import Microdot
from microdot.websocket import WebSocketError, with_websocket
from presets import Presets
from controller_messages import process_data
from hello import broadcast_hello_udp
try:
import uos as os
except ImportError:
import os
machine.freq(160000000)
settings = Settings()
print(settings)
wdt = machine.WDT(timeout=10000)
wdt.feed()
gc.collect()
print("mem before presets:", {"free": gc.mem_free(), "alloc": gc.mem_alloc()})
presets = Presets(settings["led_pin"], settings["num_leds"])
presets.load(settings)
presets.b = settings.get("brightness", 255)
presets.debug = bool(settings.get("debug", False))
gc.collect()
print("mem after presets:", {"free": gc.mem_free(), "alloc": gc.mem_alloc()})
default_preset = settings.get("default", "")
if default_preset and default_preset in presets.presets:
if presets.select(default_preset):
print(f"Selected startup preset: {default_preset}")
else:
print("Startup preset failed (invalid pattern?):", default_preset)
# On ESP32-C3, soft reboots can leave Wi-Fi driver state allocated.
# Reset both interfaces and collect before bringing STA up.
ap_if = network.WLAN(network.AP_IF)
ap_if.active(False)
sta_if = network.WLAN(network.STA_IF)
if sta_if.active():
sta_if.active(False)
utime.sleep_ms(100)
gc.collect()
sta_if.active(True)
sta_if.config(pm=network.WLAN.PM_NONE)
sta_if.connect(settings["ssid"], settings["password"])
while not sta_if.isconnected():
utime.sleep(1)
wdt.feed()
print(sta_if.ifconfig())
app = Microdot()
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
@app.route("/ws")
@with_websocket
async def ws_handler(request, ws):
print("WS client connected")
controller_ip = None
try:
client_addr = getattr(request, "client_addr", None)
if isinstance(client_addr, (tuple, list)) and client_addr:
controller_ip = client_addr[0]
elif isinstance(client_addr, str):
controller_ip = client_addr
except Exception:
controller_ip = None
print("WS controller_ip:", controller_ip)
try:
while True:
data = await ws.receive()
if not data:
print("WS client disconnected (closed)")
break
print("WS recv bytes:", len(data) if isinstance(data, (bytes, bytearray)) else len(str(data)))
print(data)
process_data(data, settings, presets, controller_ip=controller_ip)
except WebSocketError as e:
print("WS client disconnected:", e)
except OSError as e:
print("WS client dropped (OSError):", e)
@app.post("/patterns/upload")
async def upload_pattern(request):
"""Receive one pattern file body from led-controller and reload patterns."""
raw_name = request.args.get("name")
reload_raw = request.args.get("reload", "1")
reload_patterns = str(reload_raw).strip().lower() not in ("0", "false", "no", "off")
print("patterns/upload request:", {"name": raw_name, "reload": reload_patterns})
if not isinstance(raw_name, str) or not raw_name.strip():
return json.dumps({"error": "name is required"}), 400, {
"Content-Type": "application/json"
}
body = request.body
if not isinstance(body, (bytes, bytearray)) or not body:
print("patterns/upload rejected: empty body")
return json.dumps({"error": "code is required"}), 400, {
"Content-Type": "application/json"
}
print("patterns/upload body_bytes:", len(body))
try:
code = body.decode("utf-8")
except UnicodeError:
print("patterns/upload rejected: body not utf-8")
return json.dumps({"error": "body must be utf-8 text"}), 400, {
"Content-Type": "application/json"
}
if not code.strip():
return json.dumps({"error": "code is required"}), 400, {
"Content-Type": "application/json"
}
name = raw_name.strip()
if not name.endswith(".py"):
name += ".py"
if not _safe_pattern_filename(name) or name in ("__init__.py", "main.py"):
return json.dumps({"error": "invalid pattern filename"}), 400, {
"Content-Type": "application/json"
}
try:
os.mkdir("patterns")
except OSError:
pass
path = "patterns/" + name
try:
print("patterns/upload writing:", path)
with open(path, "w") as f:
f.write(code)
if reload_patterns:
print("patterns/upload reloading patterns")
presets.reload_patterns()
except OSError as e:
print("patterns/upload failed:", e)
return json.dumps({"error": str(e)}), 500, {
"Content-Type": "application/json"
}
print("patterns/upload success:", {"name": name, "reloaded": reload_patterns})
return json.dumps({
"message": "pattern uploaded",
"name": name,
"reloaded": reload_patterns,
}), 201, {"Content-Type": "application/json"}
async def presets_loop():
last_mem_log = utime.ticks_ms()
while True:
presets.tick()
wdt.feed()
if bool(getattr(presets, "debug", False)):
now = utime.ticks_ms()
if utime.ticks_diff(now, last_mem_log) >= 5000:
gc.collect()
print("mem runtime:", {"free": gc.mem_free(), "alloc": gc.mem_alloc()})
last_mem_log = now
# tick() does not await; yield so UDP hello and HTTP/WebSocket can run.
await asyncio.sleep(0)
async def _udp_hello_after_http_ready():
"""Hello must run after the HTTP server binds, or discovery clients time out on /ws."""
await asyncio.sleep(1)
print("UDP hello: broadcasting…")
try:
broadcast_hello_udp(
sta_if,
settings.get("name", ""),
wait_reply=False,
wdt=wdt,
dual_destinations=True,
)
except Exception as ex:
print("UDP hello broadcast failed:", ex)
async def main(port=80):
asyncio.create_task(presets_loop())
asyncio.create_task(_udp_hello_after_http_ready())
await app.start_server(host="0.0.0.0", port=port)
if __name__ == "__main__":
asyncio.run(main(port=80))
-5
View File
@@ -1,5 +0,0 @@
"""Pattern modules are registered only via Presets._load_dynamic_patterns().
This file is ignored as a pattern (see presets.py). Keep it free of imports so
adding a pattern does not require editing this package.
"""
-33
View File
@@ -1,33 +0,0 @@
import utime
class Blink:
def __init__(self, driver):
self.driver = driver
def run(self, preset):
"""Blink pattern: toggles LEDs on/off using preset delay, cycling through colors."""
# Use provided colors, or default to white if none
colors = preset.c if preset.c else [(255, 255, 255)]
color_index = 0
state = True # True = on, False = off
last_update = utime.ticks_ms()
while True:
current_time = utime.ticks_ms()
# Re-read delay each loop so live updates to preset.d take effect
delay_ms = max(1, int(preset.d))
if utime.ticks_diff(current_time, last_update) >= delay_ms:
if state:
base_color = colors[color_index % len(colors)]
color = self.driver.apply_brightness(base_color, preset.b)
self.driver.fill(color)
# Advance to next color for the next "on" phase
color_index += 1
else:
# "Off" phase: turn all LEDs off
self.driver.fill((0, 0, 0))
state = not state
last_update = utime.ticks_add(last_update, delay_ms)
# Yield once per tick so other logic can run
yield
-125
View File
@@ -1,125 +0,0 @@
import utime
class Chase:
def __init__(self, driver):
self.driver = driver
def run(self, preset):
"""Chase pattern: n1 LEDs of color0, n2 LEDs of color1, repeating.
Moves by n3 on even steps, n4 on odd steps (n3/n4 can be positive or negative)"""
colors = preset.c
if len(colors) < 1:
# Need at least 1 color
return
# Access colors, delay, and n values from preset
if not colors:
return
# If only one color provided, use it for both colors
if len(colors) < 2:
color0 = colors[0]
color1 = colors[0]
else:
color0 = colors[0]
color1 = colors[1]
color0 = self.driver.apply_brightness(color0, preset.b)
color1 = self.driver.apply_brightness(color1, preset.b)
n1 = max(1, int(preset.n1)) # LEDs of color 0
n2 = max(1, int(preset.n2)) # LEDs of color 1
n3 = int(preset.n3) # Step movement on even steps (can be negative)
n4 = int(preset.n4) # Step movement on odd steps (can be negative)
segment_length = n1 + n2
# Calculate position from step_count
step_count = self.driver.step
# Position alternates: step 0 adds n3, step 1 adds n4, step 2 adds n3, etc.
if step_count % 2 == 0:
# Even steps: (step_count//2) pairs of (n3+n4) plus one extra n3
position = (step_count // 2) * (n3 + n4) + n3
else:
# Odd steps: ((step_count+1)//2) pairs of (n3+n4)
position = ((step_count + 1) // 2) * (n3 + n4)
# Wrap position to keep it reasonable
max_pos = self.driver.num_leds + segment_length
position = position % max_pos
if position < 0:
position += max_pos
# If auto is False, run a single step and then stop
if not preset.a:
# Clear all LEDs
self.driver.n.fill((0, 0, 0))
# Draw repeating pattern starting at position
for i in range(self.driver.num_leds):
# Calculate position in the repeating segment
relative_pos = (i - position) % segment_length
if relative_pos < 0:
relative_pos = (relative_pos + segment_length) % segment_length
# Determine which color based on position in segment
if relative_pos < n1:
self.driver.n[i] = color0
else:
self.driver.n[i] = color1
self.driver.n.write()
# Increment step for next beat
self.driver.step = step_count + 1
# Allow tick() to advance the generator once
yield
return
# Auto mode: continuous loop
# Use transition_duration for timing and force the first update to happen immediately
transition_duration = max(10, int(preset.d))
last_update = utime.ticks_ms() - transition_duration
while True:
current_time = utime.ticks_ms()
if utime.ticks_diff(current_time, last_update) >= transition_duration:
# Calculate current position from step_count
if step_count % 2 == 0:
position = (step_count // 2) * (n3 + n4) + n3
else:
position = ((step_count + 1) // 2) * (n3 + n4)
# Wrap position
max_pos = self.driver.num_leds + segment_length
position = position % max_pos
if position < 0:
position += max_pos
# Clear all LEDs
self.driver.n.fill((0, 0, 0))
# Draw repeating pattern starting at position
for i in range(self.driver.num_leds):
# Calculate position in the repeating segment
relative_pos = (i - position) % segment_length
if relative_pos < 0:
relative_pos = (relative_pos + segment_length) % segment_length
# Determine which color based on position in segment
if relative_pos < n1:
self.driver.n[i] = color0
else:
self.driver.n[i] = color1
self.driver.n.write()
# Increment step
step_count += 1
self.driver.step = step_count
last_update = utime.ticks_add(last_update, transition_duration)
transition_duration = max(10, int(preset.d))
# Yield once per tick so other logic can run
yield
-100
View File
@@ -1,100 +0,0 @@
import utime
class Circle:
def __init__(self, driver):
self.driver = driver
def run(self, preset):
"""Circle loading pattern - grows to n2, then tail moves forward at n3 until min length n4"""
head = 0
tail = 0
# Calculate timing from preset
head_rate = max(1, int(preset.n1)) # n1 = head moves per second
tail_rate = max(1, int(preset.n3)) # n3 = tail moves per second
max_length = max(1, int(preset.n2)) # n2 = max length
min_length = max(0, int(preset.n4)) # n4 = min length
head_delay = 1000 // head_rate # ms between head movements
tail_delay = 1000 // tail_rate # ms between tail movements
last_head_move = utime.ticks_ms()
last_tail_move = utime.ticks_ms()
phase = "growing" # "growing", "shrinking", or "off"
# Support up to two colors (like chase). If only one color is provided,
# use black for the second; if none, default to white.
colors = preset.c
if not colors:
base0 = base1 = (255, 255, 255)
elif len(colors) == 1:
base0 = colors[0]
base1 = (0, 0, 0)
else:
base0 = colors[0]
base1 = colors[1]
color0 = self.driver.apply_brightness(base0, preset.b)
color1 = self.driver.apply_brightness(base1, preset.b)
while True:
current_time = utime.ticks_ms()
# Background: use second color during the "off" phase, otherwise clear to black
if phase == "off":
self.driver.n.fill(color1)
else:
self.driver.n.fill((0, 0, 0))
# Calculate segment length
segment_length = (head - tail) % self.driver.num_leds
if segment_length == 0 and head != tail:
segment_length = self.driver.num_leds
# Draw segment from tail to head as a solid color (no per-LED alternation)
current_color = color0
for i in range(segment_length + 1):
led_pos = (tail + i) % self.driver.num_leds
self.driver.n[led_pos] = current_color
# Move head continuously at n1 LEDs per second
if utime.ticks_diff(current_time, last_head_move) >= head_delay:
head = (head + 1) % self.driver.num_leds
last_head_move = utime.ticks_add(last_head_move, head_delay)
head_rate = max(1, int(preset.n1))
head_delay = 1000 // head_rate
# Tail behavior based on phase
if phase == "growing":
# Growing phase: tail stays at 0 until max length reached
if segment_length >= max_length:
phase = "shrinking"
elif phase == "shrinking":
# Shrinking phase: move tail forward at n3 LEDs per second
if utime.ticks_diff(current_time, last_tail_move) >= tail_delay:
tail = (tail + 1) % self.driver.num_leds
last_tail_move = utime.ticks_add(last_tail_move, tail_delay)
tail_rate = max(1, int(preset.n3))
tail_delay = 1000 // tail_rate
# Check if we've reached min length
current_length = (head - tail) % self.driver.num_leds
if current_length == 0 and head != tail:
current_length = self.driver.num_leds
# For min_length = 0, we need at least 1 LED (the head)
if min_length == 0 and current_length <= 1:
phase = "off" # All LEDs off for 1 step
elif min_length > 0 and current_length <= min_length:
phase = "growing" # Cycle repeats
else: # phase == "off"
# Off phase: second color fills the ring for 1 step, then restart
tail = head # Reset tail to head position to start fresh
phase = "growing"
self.driver.n.write()
# Yield once per tick so other logic can run
yield
-56
View File
@@ -1,56 +0,0 @@
import utime
class ColourCycle:
def __init__(self, driver):
self.driver = driver
def _render(self, colors, phase, brightness):
num_leds = self.driver.num_leds
color_count = len(colors)
if num_leds <= 0 or color_count <= 0:
return
if color_count == 1:
self.driver.fill(self.driver.apply_brightness(colors[0], brightness))
return
full_span = color_count * 256
# Match rainbow behaviour: phase is 0..255 and maps to one full-strip shift.
phase_shift = (phase * full_span) // 256
for i in range(num_leds):
# Position around the colour loop, shifted by phase.
pos = ((i * full_span) // num_leds + phase_shift) % full_span
idx = pos // 256
frac = pos & 255
c1 = colors[idx]
c2 = colors[(idx + 1) % color_count]
blended = (
c1[0] + ((c2[0] - c1[0]) * frac) // 256,
c1[1] + ((c2[1] - c1[1]) * frac) // 256,
c1[2] + ((c2[2] - c1[2]) * frac) // 256,
)
self.driver.n[i] = self.driver.apply_brightness(blended, brightness)
self.driver.n.write()
def run(self, preset):
colors = preset.c if preset.c else [(255, 255, 255)]
phase = self.driver.step % 256
step_amount = max(1, int(preset.n1))
if not preset.a:
self._render(colors, phase, preset.b)
self.driver.step = (phase + step_amount) % 256
yield
return
last_update = utime.ticks_ms()
while True:
current_time = utime.ticks_ms()
delay_ms = max(1, int(preset.d))
if utime.ticks_diff(current_time, last_update) >= delay_ms:
self._render(colors, phase, preset.b)
phase = (phase + step_amount) % 256
self.driver.step = phase
last_update = utime.ticks_add(last_update, delay_ms)
yield
-210
View File
@@ -1,210 +0,0 @@
import random
import utime
# Default warm palette: ember → orange → yellow → pale hot (RGB)
_DEFAULT_PALETTE = (
(90, 8, 8),
(200, 40, 12),
(255, 120, 30),
(255, 220, 140),
)
def _clamp(x, lo, hi):
if x < lo:
return lo
if x > hi:
return hi
return x
def _lerp_chan(a, b, t):
return a + ((b - a) * t >> 8)
def _lerp_rgb(c0, c1, t):
return (
_lerp_chan(c0[0], c1[0], t),
_lerp_chan(c0[1], c1[1], t),
_lerp_chan(c0[2], c1[2], t),
)
def _palette_sample(palette, pos256):
n = len(palette)
if n == 0:
return (255, 160, 60)
if n == 1:
return palette[0]
span = (n - 1) * pos256
seg = span >> 8
if seg >= n - 1:
return palette[n - 1]
frac = span & 0xFF
return _lerp_rgb(palette[seg], palette[seg + 1], frac)
def _triangle_255(elapsed_ms, period_ms):
period_ms = max(period_ms, 400)
p = elapsed_ms % period_ms
half = period_ms >> 1
if half <= 0:
return 128
if p < half:
return (p * 255) // half
return ((period_ms - p) * 255) // (period_ms - half)
class Flame:
def __init__(self, driver):
self.driver = driver
def _build_palette(self, preset):
colors = preset.c
if not colors:
return list(_DEFAULT_PALETTE)
out = []
for c in colors:
if isinstance(c, (list, tuple)) and len(c) == 3:
out.append(
(
_clamp(int(c[0]), 0, 255),
_clamp(int(c[1]), 0, 255),
_clamp(int(c[2]), 0, 255),
)
)
return out if out else list(_DEFAULT_PALETTE)
def _draw_frame(self, preset, palette, ticks_now, breath_el_ms, rise, cluster_jit, breath_ms, lo, hi, spark_state):
"""spark_state: (active: bool, start_ticks, duration_ms). ticks_now for sparks; breath_el_ms for slow wave."""
num = self.driver.num_leds
denom = num - 1 if num > 1 else 1
breathe = _triangle_255(breath_el_ms, breath_ms)
base_level = lo + (((hi - lo) * breathe) >> 8)
micro = 232 + random.randint(0, 35)
level = (base_level * micro) >> 8
level = _clamp(level, lo, hi)
spark_boost = 0
spark_white = (0, 0, 0)
active, s0, dur = spark_state
if active and dur > 0:
el = utime.ticks_diff(ticks_now, s0)
if el < 0:
el = 0
if el >= dur:
spark_boost = 0
else:
env = 255 - ((el * 255) // dur)
spark_boost = (env * 90) >> 8
spark_white = ((env * 55) >> 8, (env * 50) >> 8, (env * 40) >> 8)
for i in range(num):
h = (i * 256) // denom
flow = (h + rise + ((i // max(1, num >> 3)) * 17)) & 255
pos = (flow + cluster_jit[(i >> 2) & 7]) & 255
rgb = _palette_sample(palette, pos)
if spark_boost:
rgb = (
_clamp(rgb[0] + spark_white[0] + (spark_boost * 3 >> 2), 0, 255),
_clamp(rgb[1] + spark_white[1] + (spark_boost >> 1), 0, 255),
_clamp(rgb[2] + spark_white[2] + (spark_boost >> 2), 0, 255),
)
self.driver.n[i] = self.driver.apply_brightness(rgb, level)
self.driver.n.write()
def run(self, preset):
"""Salt-lamp / hearth-style flame: warm gradient, breathing, jitter, drift, rare sparks."""
palette = self._build_palette(preset)
lo = max(0, min(255, int(preset.n1)))
hi = max(0, min(255, int(preset.b)))
if lo > hi:
lo, hi = hi, lo
bp = int(preset.n2)
breath_ms = max(800, bp if bp > 0 else 2500)
gap_lo = int(preset.n3)
gap_hi = int(preset.n4)
# n3 < 0 disables sparks; n3=n4=0 uses ~10–30 s gaps (hearth pops).
if gap_lo < 0:
sparks_on = False
else:
sparks_on = True
if gap_lo == 0 and gap_hi == 0:
gap_lo, gap_hi = 10000, 30000
else:
gap_lo = max(gap_lo, 500)
if gap_hi < gap_lo:
gap_hi = gap_lo
delay_ms = max(16, int(preset.d))
rise = random.randint(0, 255)
cluster_jit = [random.randint(-18, 18) for _ in range(8)]
last_draw = utime.ticks_ms()
breath_origin = last_draw
last_cluster = last_draw
spark_active = False
spark_start = 0
spark_dur = 0
next_spark = utime.ticks_add(last_draw, random.randint(gap_lo, gap_hi)) if sparks_on else 0
if not preset.a:
now = utime.ticks_ms()
self._draw_frame(
preset,
palette,
now,
utime.ticks_diff(now, breath_origin),
rise,
cluster_jit,
breath_ms,
lo,
hi,
(False, 0, 0),
)
yield
return
while True:
now = utime.ticks_ms()
if utime.ticks_diff(now, last_draw) < delay_ms:
yield
continue
last_draw = utime.ticks_add(last_draw, delay_ms)
rise = (rise + random.randint(-10, 12)) & 255
if utime.ticks_diff(now, last_cluster) >= (delay_ms * 4):
last_cluster = now
cluster_jit = [random.randint(-18, 18) for _ in range(8)]
spark_state = (spark_active, spark_start, spark_dur)
if sparks_on:
if spark_active:
if utime.ticks_diff(now, spark_start) >= spark_dur:
spark_active = False
next_spark = utime.ticks_add(
now,
random.randint(gap_lo, gap_hi),
)
elif utime.ticks_diff(now, next_spark) >= 0:
spark_active = True
spark_start = now
spark_dur = random.randint(180, 360)
self._draw_frame(
preset,
palette,
now,
utime.ticks_diff(now, breath_origin),
rise,
cluster_jit,
breath_ms,
lo,
hi,
(spark_active, spark_start, spark_dur),
)
yield
-40
View File
@@ -1,40 +0,0 @@
import random
import utime
class Flicker:
def __init__(self, driver):
self.driver = driver
def run(self, preset):
"""Random brightness between n1 (min) and b (max); delay d ms between updates."""
colors = preset.c if preset.c else [(255, 255, 255)]
color_index = 0
last_update = utime.ticks_ms()
def brightness_bounds():
lo = max(0, min(255, int(preset.n1)))
hi = max(0, min(255, int(preset.b)))
if lo > hi:
lo, hi = hi, lo
return lo, hi
if not preset.a:
lo, hi = brightness_bounds()
level = random.randint(lo, hi)
base = colors[color_index % len(colors)]
self.driver.fill(self.driver.apply_brightness(base, level))
yield
return
while True:
current_time = utime.ticks_ms()
delay_ms = max(1, int(preset.d))
lo, hi = brightness_bounds()
if utime.ticks_diff(current_time, last_update) >= delay_ms:
level = random.randint(lo, hi)
base = colors[color_index % len(colors)]
self.driver.fill(self.driver.apply_brightness(base, level))
color_index += 1
last_update = utime.ticks_add(last_update, delay_ms)
yield
-64
View File
@@ -1,64 +0,0 @@
import utime
class Pulse:
def __init__(self, driver):
self.driver = driver
def run(self, preset):
self.driver.off()
# Get colors from preset
colors = preset.c
if not colors:
colors = [(255, 255, 255)]
color_index = 0
cycle_start = utime.ticks_ms()
# State machine based pulse using a single generator loop
while True:
# Read current timing parameters from preset
attack_ms = max(0, int(preset.n1)) # Attack time in ms
hold_ms = max(0, int(preset.n2)) # Hold time in ms
decay_ms = max(0, int(preset.n3)) # Decay time in ms
delay_ms = max(0, int(preset.d))
total_ms = attack_ms + hold_ms + decay_ms + delay_ms
if total_ms <= 0:
total_ms = 1
now = utime.ticks_ms()
elapsed = utime.ticks_diff(now, cycle_start)
base_color = colors[color_index % len(colors)]
if elapsed < attack_ms and attack_ms > 0:
# Attack: fade 0 -> 1
factor = elapsed / attack_ms
color = tuple(int(c * factor) for c in base_color)
self.driver.fill(self.driver.apply_brightness(color, preset.b))
elif elapsed < attack_ms + hold_ms:
# Hold: full brightness
self.driver.fill(self.driver.apply_brightness(base_color, preset.b))
elif elapsed < attack_ms + hold_ms + decay_ms and decay_ms > 0:
# Decay: fade 1 -> 0
dec_elapsed = elapsed - attack_ms - hold_ms
factor = max(0.0, 1.0 - (dec_elapsed / decay_ms))
color = tuple(int(c * factor) for c in base_color)
self.driver.fill(self.driver.apply_brightness(color, preset.b))
elif elapsed < total_ms:
# Delay phase: LEDs off between pulses
self.driver.fill((0, 0, 0))
else:
# End of cycle, move to next color and restart timing
color_index += 1
cycle_start = now
if not preset.a:
break
# Skip drawing this tick, start next cycle
yield
continue
# Yield once per tick
yield
-136
View File
@@ -1,136 +0,0 @@
import utime
_RADIATE_DBG_INTERVAL_MS = 1000
class Radiate:
def __init__(self, driver):
self.driver = driver
def run(self, preset):
"""Radiate from nodes every n1 LEDs, retriggering every delay (d).
- n1: node spacing in LEDs
- n2: outbound travel time in ms
- n3: return travel time in ms
- d: retrigger interval in ms
"""
colors = preset.c if preset.c else [(255, 255, 255)]
base_on = colors[0]
base_off = colors[1] if len(colors) > 1 else (0, 0, 0)
spacing = max(1, int(preset.n1))
outward_ms = max(1, int(preset.n2))
return_ms = max(1, int(preset.n3))
max_dist = spacing // 2
lit_color = self.driver.apply_brightness(base_on, preset.b)
off_color = self.driver.apply_brightness(base_off, preset.b)
now = utime.ticks_ms()
last_trigger = now
active_pulses = [now]
last_dbg = now
dbg_banner = False
if not preset.a:
# Single-step render uses only the first instant pulse.
active_pulses = [utime.ticks_ms()]
while True:
now = utime.ticks_ms()
delay_ms = max(1, int(preset.d))
spacing = max(1, int(preset.n1))
outward_ms = max(1, int(preset.n2))
return_ms = max(1, int(preset.n3))
max_dist = spacing // 2
lit_color = self.driver.apply_brightness(base_on, preset.b)
off_color = self.driver.apply_brightness(base_off, preset.b)
if preset.a and utime.ticks_diff(now, last_trigger) >= delay_ms:
# Keep one pulse train at a time; replacing instead of appending
# prevents overlap from keeping color[0] continuously visible.
active_pulses = [now]
last_trigger = utime.ticks_add(last_trigger, delay_ms)
if bool(getattr(self.driver, "debug", False)):
print(
"[radiate] trigger spacing=%d out=%d in=%d delay=%d"
% (spacing, outward_ms, return_ms, delay_ms)
)
# Drop pulses once their out-and-back lifetime ends.
pulse_lifetime = outward_ms + return_ms
kept = []
for start in active_pulses:
age = utime.ticks_diff(now, start)
if age < pulse_lifetime:
kept.append(start)
active_pulses = kept
debug_front = -1
lit_count = 0
for i in range(self.driver.num_leds):
# Nearest node distance for a repeating node grid every `spacing` LEDs.
offset = i % spacing
dist = min(offset, spacing - offset)
lit = False
for start in active_pulses:
age = utime.ticks_diff(now, start)
# Do not render on the exact trigger tick; this avoids
# node LEDs appearing "stuck on" between cycles.
if age <= 0:
continue
if age <= outward_ms:
# Integer-ceiling progression so peak can be reached even
# when tick timing skips the exact outward_ms boundary.
front = (age * max_dist + outward_ms - 1) // outward_ms
elif age <= outward_ms + return_ms:
back_age = age - outward_ms
remaining = return_ms - back_age
front = (remaining * max_dist + return_ms - 1) // return_ms
else:
continue
if dist <= front:
lit = True
if front > debug_front:
debug_front = front
break
self.driver.n[i] = lit_color if lit else off_color
if lit:
lit_count += 1
self.driver.n.write()
if bool(getattr(self.driver, "debug", False)):
if not dbg_banner:
dbg_banner = True
print(
"[radiate] debug on: spacing=%s out=%s in=%s d=%s num=%d"
% (
preset.n1,
preset.n2,
preset.n3,
preset.d,
self.driver.num_leds,
)
)
if utime.ticks_diff(now, last_dbg) >= _RADIATE_DBG_INTERVAL_MS:
pulse_age = -1
if active_pulses:
pulse_age = utime.ticks_diff(now, active_pulses[0])
print(
"[radiate] age=%d front=%d max=%d active=%d lit=%d"
% (pulse_age, debug_front, max_dist, len(active_pulses), lit_count)
)
if lit_count == 0:
print("[radiate] fully off")
last_dbg = now
if not preset.a:
yield
return
yield
-51
View File
@@ -1,51 +0,0 @@
import utime
class Rainbow:
def __init__(self, driver):
self.driver = driver
def _wheel(self, pos):
if pos < 85:
return (pos * 3, 255 - pos * 3, 0)
elif pos < 170:
pos -= 85
return (255 - pos * 3, 0, pos * 3)
else:
pos -= 170
return (0, pos * 3, 255 - pos * 3)
def run(self, preset):
step = self.driver.step % 256
step_amount = max(1, int(preset.n1)) # n1 controls step increment
# If auto is False, run a single step and then stop
if not preset.a:
for i in range(self.driver.num_leds):
rc_index = (i * 256 // self.driver.num_leds) + step
self.driver.n[i] = self.driver.apply_brightness(self._wheel(rc_index & 255), preset.b)
self.driver.n.write()
# Increment step by n1 for next manual call
self.driver.step = (step + step_amount) % 256
# Allow tick() to advance the generator once
yield
return
last_update = utime.ticks_ms()
while True:
current_time = utime.ticks_ms()
sleep_ms = max(1, int(preset.d)) # Get delay from preset
if utime.ticks_diff(current_time, last_update) >= sleep_ms:
for i in range(self.driver.num_leds):
rc_index = (i * 256 // self.driver.num_leds) + step
self.driver.n[i] = self.driver.apply_brightness(
self._wheel(rc_index & 255),
preset.b,
)
self.driver.n.write()
step = (step + step_amount) % 256
self.driver.step = step
last_update = utime.ticks_add(last_update, sleep_ms)
# Yield once per tick so other logic can run
yield
-57
View File
@@ -1,57 +0,0 @@
import utime
class Transition:
def __init__(self, driver):
self.driver = driver
def run(self, preset):
"""Transition between colors, blending over `delay` ms."""
colors = preset.c
if not colors:
self.driver.off()
yield
return
# Only one color: just keep it on
if len(colors) == 1:
while True:
self.driver.fill(self.driver.apply_brightness(colors[0], preset.b))
yield
return
color_index = 0
start_time = utime.ticks_ms()
while True:
if not colors:
break
# Get current and next color based on live list
c1 = colors[color_index % len(colors)]
c2 = colors[(color_index + 1) % len(colors)]
duration = max(10, int(preset.d)) # At least 10ms
now = utime.ticks_ms()
elapsed = utime.ticks_diff(now, start_time)
if elapsed >= duration:
# End of this transition step
if not preset.a:
# One-shot: transition from first to second color only
self.driver.fill(self.driver.apply_brightness(c2, preset.b))
break
# Auto: move to next pair
color_index = (color_index + 1) % len(colors)
start_time = now
yield
continue
# Interpolate between c1 and c2
factor = elapsed / duration
interpolated = tuple(
int(c1[i] + (c2[i] - c1[i]) * factor) for i in range(3)
)
self.driver.fill(self.driver.apply_brightness(interpolated, preset.b))
yield
-227
View File
@@ -1,227 +0,0 @@
import random
import utime
# Default cool palette (icy blues, violet, mint) when preset has no colours.
# When `driver.debug` is True, print stats every N twinkle ticks (serial can be slow).
_TWINKLE_DBG_INTERVAL = 40
_DEFAULT_COOL = (
(120, 200, 255),
(80, 140, 255),
(180, 120, 255),
(100, 220, 240),
(160, 200, 255),
(90, 180, 220),
)
class Twinkle:
def __init__(self, driver):
self.driver = driver
def _palette(self, preset):
colors = preset.c
if not colors:
return list(_DEFAULT_COOL)
out = []
for c in colors:
if isinstance(c, (list, tuple)) and len(c) == 3:
out.append(
(
max(0, min(255, int(c[0]))),
max(0, min(255, int(c[1]))),
max(0, min(255, int(c[2]))),
)
)
return out if out else list(_DEFAULT_COOL)
def run(self, preset):
"""Twinkle: n1 activity, n2 density; n3/n4 min/max length of adjacent on/off runs."""
palette = self._palette(preset)
num = self.driver.num_leds
if num <= 0:
while True:
yield
return
def activity_rate():
r = int(preset.n1)
if r <= 0:
r = 48
return max(1, min(255, r))
def density255():
"""Higher → more LEDs lit on average when a twinkle step fires (0 = default mid)."""
d = int(preset.n2)
if d <= 0:
d = 128
return max(0, min(255, d))
def cluster_len_bounds():
"""n3 = min adjacent LEDs per twinkle, n4 = max (both 0 → 1..4)."""
lo = int(preset.n3)
hi = int(preset.n4)
if lo <= 0 and hi <= 0:
lo, hi = 1, min(4, num)
else:
if lo <= 0:
lo = 1
if hi <= 0:
hi = lo
if hi < lo:
lo, hi = hi, lo
lo = max(1, min(lo, num))
hi = max(lo, min(hi, num))
return lo, hi
def random_cluster_len():
lo, hi = cluster_len_bounds()
# When min and max match, every lit/dim run is exactly that many LEDs (still capped by strip length).
if lo == hi:
return lo
return random.randint(lo, hi)
def cluster_base_index(start, k):
"""Shift run left so a length-k segment fits; keeps full k when num >= k."""
k = min(max(0, int(k)), num)
if k <= 0:
return 0
return max(0, min(int(start), num - k))
dens = density255()
on = [random.randint(0, 255) < dens for _ in range(num)]
colour_i = [random.randint(0, len(palette) - 1) for _ in range(num)]
last_update = utime.ticks_ms()
dbg_tick = 0
dbg_banner = False
def on_run_min_max(bits):
"""Smallest and largest contiguous run of True in bits (0,0 if all off)."""
best_min = num + 1
best_max = 0
cur = 0
for j in range(num):
if bits[j]:
cur += 1
else:
if cur:
if cur < best_min:
best_min = cur
if cur > best_max:
best_max = cur
cur = 0
if cur:
if cur < best_min:
best_min = cur
if cur > best_max:
best_max = cur
if best_min == num + 1:
return 0, 0
return best_min, best_max
if not preset.a:
for i in range(num):
if on[i]:
base = palette[colour_i[i] % len(palette)]
self.driver.n[i] = self.driver.apply_brightness(base, preset.b)
else:
self.driver.n[i] = (0, 0, 0)
self.driver.n.write()
yield
return
while True:
now = utime.ticks_ms()
delay_ms = max(1, int(preset.d))
if utime.ticks_diff(now, last_update) >= delay_ms:
rate = activity_rate()
dens = density255()
dbg = bool(getattr(self.driver, "debug", False))
dbg_tick += 1
# Snapshot for decisions; apply all darks then all lights so
# overlaps in the same tick favour lit runs (lights win).
prev_on = on[:]
prev_ci = colour_i[:]
next_on = list(prev_on)
next_ci = list(prev_ci)
dbg_ops = {"L": 0, "D": 0}
light_i = []
dark_i = []
for i in range(num):
if random.randint(0, 255) < rate:
r = random.randint(0, 255)
if not prev_on[i]:
if r < dens:
light_i.append(i)
else:
if r < (255 - dens):
dark_i.append(i)
def light_adjacent(start):
dbg_ops["L"] += 1
k = random_cluster_len()
b = cluster_base_index(start, k)
for dj in range(k):
idx = b + dj
next_on[idx] = True
next_ci[idx] = random.randint(0, len(palette) - 1)
def dark_adjacent(start):
dbg_ops["D"] += 1
k = random_cluster_len()
b = cluster_base_index(start, k)
for dj in range(k):
idx = b + dj
next_on[idx] = False
for i in dark_i:
dark_adjacent(i)
for i in light_i:
light_adjacent(i)
for i in range(num):
if next_on[i]:
base = palette[next_ci[i] % len(palette)]
self.driver.n[i] = self.driver.apply_brightness(base, preset.b)
else:
self.driver.n[i] = (0, 0, 0)
self.driver.n.write()
on = next_on
colour_i = next_ci
last_update = utime.ticks_add(last_update, delay_ms)
if dbg:
lo, hi = cluster_len_bounds()
if not dbg_banner:
dbg_banner = True
print(
"[twinkle] debug on: n1=%s n2=%s n3=%s n4=%s d=%s -> lo=%d hi=%d num=%d"
% (
preset.n1,
preset.n2,
preset.n3,
preset.n4,
preset.d,
lo,
hi,
num,
)
)
rmin, rmax = on_run_min_max(on)
bad = lo > 0 and rmin > 0 and rmin < lo and num >= lo
if bad or (dbg_tick % _TWINKLE_DBG_INTERVAL == 0):
print(
"[twinkle] tick=%d rate=%d dens=%d L=%d D=%d on_runs min=%d max=%d%s"
% (
dbg_tick,
rate,
dens,
dbg_ops["L"],
dbg_ops["D"],
rmin,
rmax,
" **run<lo**" if bad else "",
)
)
yield
-116
View File
@@ -1,116 +0,0 @@
class Preset:
def __init__(self, data):
# Set default values for all preset attributes
self.p = "off"
self.d = 100
self.b = 127
self.c = [(255, 255, 255)]
self.a = True
self.n1 = 0
self.n2 = 0
self.n3 = 0
self.n4 = 0
self.n5 = 0
self.n6 = 0
# Override defaults with provided data
self.edit(data)
def edit(self, data=None):
if not data:
return False
aliases = {
"pattern": "p",
"colors": "c",
"delay": "d",
"brightness": "b",
"auto": "a",
}
int_fields = {"d", "b", "n1", "n2", "n3", "n4", "n5", "n6"}
allowed_fields = {"p", "c", "d", "b", "a", "n1", "n2", "n3", "n4", "n5", "n6"}
for key, value in data.items():
key = aliases.get(key, key)
if key not in allowed_fields:
continue
if key in int_fields:
try:
parsed = int(value)
if key == "b":
parsed = max(0, min(255, parsed))
elif key in ("d", "n1", "n2", "n3", "n4", "n5", "n6"):
parsed = max(0, parsed)
setattr(self, key, parsed)
except (TypeError, ValueError):
continue
elif key == "a":
if isinstance(value, bool):
self.a = value
elif isinstance(value, int):
self.a = bool(value)
elif isinstance(value, str):
lowered = value.lower()
if lowered in ("true", "1", "yes", "on"):
self.a = True
elif lowered in ("false", "0", "no", "off"):
self.a = False
elif key == "c":
if isinstance(value, (list, tuple)):
self.c = value
else:
setattr(self, key, value)
return True
@property
def pattern(self):
return self.p
@pattern.setter
def pattern(self, value):
self.p = value
@property
def delay(self):
return self.d
@delay.setter
def delay(self, value):
self.d = value
@property
def brightness(self):
return self.b
@brightness.setter
def brightness(self, value):
self.b = value
@property
def colors(self):
return self.c
@colors.setter
def colors(self, value):
self.c = value
@property
def auto(self):
return self.a
@auto.setter
def auto(self, value):
self.a = value
def to_dict(self):
return {
"p": self.p,
"d": self.d,
"b": self.b,
"c": self.c,
"a": self.a,
"n1": self.n1,
"n2": self.n2,
"n3": self.n3,
"n4": self.n4,
"n5": self.n5,
"n6": self.n6,
}
-199
View File
@@ -1,199 +0,0 @@
from machine import Pin
from neopixel import NeoPixel
from preset import Preset
from utils import convert_and_reorder_colors
import json
import sys
try:
import uos as os
except ImportError:
import os
MAX_PRESETS = 32
class Presets:
def __init__(self, pin, num_leds):
self.n = NeoPixel(Pin(pin, Pin.OUT), num_leds)
self.num_leds = num_leds
self.step = 0
# Global brightness (0–255), controlled via ESPNow {"b": <value>}
self.b = 255
self.generator = None
self.presets = {}
self.selected = None
self.reload_patterns()
def reload_patterns(self):
# Register built-in methods first, then discovered pattern classes
self.patterns = {
"off": self.off,
"on": self.on,
}
self.patterns.update(self._load_dynamic_patterns())
def _load_dynamic_patterns(self):
loaded = {}
try:
files = os.listdir("patterns")
except OSError:
return loaded
for filename in files:
if not filename.endswith(".py") or filename in ("__init__.py", "main.py"):
continue
module_basename = filename[:-3]
module_name = "patterns." + module_basename
try:
if module_name in sys.modules:
del sys.modules[module_name]
module = __import__(module_name, None, None, ["*"])
except Exception as e:
print("Pattern import failed:", module_name, e)
continue
pattern_class = None
for attr_name in dir(module):
attr = getattr(module, attr_name)
# Pick the first class in the module that exposes run()
if isinstance(attr, type) and hasattr(attr, "run"):
pattern_class = attr
break
if pattern_class is None:
continue
try:
loaded[module_basename] = pattern_class(self).run
except Exception as e:
print("Pattern init failed:", module_name, e)
return loaded
def save(self):
"""Save the presets to a file."""
with open("presets.json", "w") as f:
json.dump({name: preset.to_dict() for name, preset in self.presets.items()}, f)
return True
def load(self, settings=None):
"""Load presets from a file.
`settings` is used to convert hex strings in `c` to RGB tuples and apply
the device's colour order (same as ESPNow receive). If omitted, RGB order
is assumed.
"""
try:
with open("presets.json", "r") as f:
data = json.load(f)
except OSError:
# Create an empty presets file if missing
self.presets = {}
self.save()
return True
order = settings if settings is not None else "rgb"
self.presets = {}
for name, preset_data in data.items():
if len(self.presets) >= MAX_PRESETS:
print("Preset limit reached on load:", MAX_PRESETS)
break
color_key = "c" if "c" in preset_data else ("colors" if "colors" in preset_data else None)
if color_key is not None:
preset_data[color_key] = convert_and_reorder_colors(
preset_data[color_key], order
)
self.presets[name] = Preset(preset_data)
if self.presets:
print("Loaded presets:")
#for name in sorted(self.presets.keys()):
# print(f" {name}: {self.presets[name].to_dict()}")
return True
def edit(self, name, data):
"""Create or update a preset with the given name."""
if name in self.presets:
# Update existing preset
self.presets[name].edit(data)
else:
if len(self.presets) >= MAX_PRESETS and name not in ("on", "off"):
print("Preset limit reached:", MAX_PRESETS)
return False
# Create new preset
self.presets[name] = Preset(data)
return True
def delete(self, name):
if name in self.presets:
del self.presets[name]
return True
return False
def delete_all(self):
self.presets = {}
self.generator = None
self.selected = None
return True
def tick(self):
if self.generator is None:
return
try:
next(self.generator)
except StopIteration:
self.generator = None
except Exception as e:
print(f"Error in tick: {e}")
self.generator = None
def select(self, preset_name, step=None):
# Auto-create simple built-in presets for common names on first use
if preset_name not in self.presets and preset_name in ("on", "off"):
if preset_name == "on":
self.presets[preset_name] = Preset({"p": "on"})
else:
self.presets[preset_name] = Preset({"p": "off"})
if preset_name in self.presets:
preset = self.presets[preset_name]
if preset.p in self.patterns:
# Set step value if explicitly provided
if step is not None:
self.step = step
elif preset.p == "off" or self.selected != preset_name:
self.step = 0
self.generator = self.patterns[preset.p](preset)
self.selected = preset_name # Store the preset name, not the object
return True
print("select failed: pattern not found for preset", preset_name, "pattern=", preset.p)
return False
print("select failed: preset not found", preset_name)
# If preset doesn't exist or pattern not found, indicate failure
return False
def update_num_leds(self, pin, num_leds):
self.n = NeoPixel(Pin(pin, Pin.OUT), num_leds)
self.num_leds = num_leds
def apply_brightness(self, color, brightness_override=None):
# Combine per-preset brightness (override) with global brightness self.b
local = brightness_override if brightness_override is not None else 255
# Scale preset brightness by global brightness
effective_brightness = int(local * self.b / 255)
return tuple(int(c * effective_brightness / 255) for c in color)
def fill(self, color=None):
fill_color = color if color is not None else (0, 0, 0)
for i in range(self.num_leds):
self.n[i] = fill_color
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))
-99
View File
@@ -1,99 +0,0 @@
import json
import ubinascii
import machine
import network
class Settings(dict):
SETTINGS_FILE = "/settings.json"
def __init__(self):
super().__init__()
self.load() # Load settings from file during initialization
self.color_order = self.get_color_order(self["color_order"])
def set_defaults(self):
self["led_pin"] = 10
self["num_leds"] = 119
self["color_order"] = "rgb"
sta = network.WLAN(network.STA_IF)
sta.active(True)
#use led-mac for name
mac = sta.config("mac")
mac = ubinascii.hexlify(mac).decode().lower()
self["name"] = "led-" + mac
self["debug"] = False
self["default"] = "on"
self["brightness"] = 32
self["transport_type"] = "espnow"
self["wifi_channel"] = 1
# ESP-NOW transport (requires espnow firmware; uses wifi_channel).
self["ssid"] = ""
self["password"] = ""
def save(self):
try:
j = json.dumps(self)
with open(self.SETTINGS_FILE, 'w') as file:
file.write(j)
print("Settings saved successfully.")
except Exception as e:
print(f"Error saving settings: {e}")
def load(self):
try:
with open(self.SETTINGS_FILE, 'r') as file:
loaded_settings = json.load(file)
self.update(loaded_settings)
print("Settings loaded successfully.")
except Exception as e:
print(f"Error loading settings")
self.set_defaults()
self.save()
def get_color_order(self, color_order):
"""Convert color order string to tuple of hex string indices."""
color_orders = {
"rgb": (1, 3, 5),
"rbg": (1, 5, 3),
"grb": (3, 1, 5),
"gbr": (3, 5, 1),
"brg": (5, 1, 3),
"bgr": (5, 3, 1)
}
return color_orders.get(color_order.lower(), (1, 3, 5)) # Default to RGB
def get_rgb_channel_order(self, color_order=None):
"""Convert color order string to RGB channel indices for reordering tuples.
Returns tuple of channel indices: (r_channel, g_channel, b_channel)
Example: 'grb' -> (1, 0, 2) means (G, R, B)"""
if color_order is None:
color_order = self.get("color_order", "rgb")
color_order = color_order.lower()
# Map hex string positions to RGB channel indices
# Position 1 (R in hex) -> channel 0, Position 3 (G) -> channel 1, Position 5 (B) -> channel 2
hex_to_channel = {1: 0, 3: 1, 5: 2}
hex_indices = self.get_color_order(color_order)
return tuple(hex_to_channel[pos] for pos in hex_indices)
# Example usage
def main():
settings = Settings()
print(f"Number of LEDs: {settings['num_leds']}")
settings['num_leds'] = 100
print(f"Updated number of LEDs: {settings['num_leds']}")
settings.save()
# Create a new Settings object to test loading
new_settings = Settings()
print(f"Loaded number of LEDs: {new_settings['num_leds']}")
print(settings)
# Run the example
if __name__ == "__main__":
main()
-58
View File
@@ -1,58 +0,0 @@
def convert_and_reorder_colors(colors, settings_or_color_order):
"""Convert hex color strings to RGB tuples and reorder based on device color order.
Args:
colors: List of colors, either hex strings like "#FF0000" or RGB tuples like (255, 0, 0)
settings_or_color_order: Either a Settings object or a color_order string (e.g., "rgb", "grb")
Returns:
List of RGB tuples reordered according to device color order
"""
# Get channel order from settings or color_order string
if hasattr(settings_or_color_order, 'get_rgb_channel_order'):
# It's a Settings object
channel_order = settings_or_color_order.get_rgb_channel_order()
elif isinstance(settings_or_color_order, str):
# It's a color_order string, convert to channel order
color_order = settings_or_color_order.lower()
color_orders = {
"rgb": (1, 3, 5),
"rbg": (1, 5, 3),
"grb": (3, 1, 5),
"gbr": (3, 5, 1),
"brg": (5, 1, 3),
"bgr": (5, 3, 1)
}
hex_indices = color_orders.get(color_order, (1, 3, 5))
# Map hex string positions to RGB channel indices
hex_to_channel = {1: 0, 3: 1, 5: 2}
channel_order = tuple(hex_to_channel[pos] for pos in hex_indices)
else:
# Assume it's already a channel order tuple
channel_order = settings_or_color_order
converted_colors = []
for color in colors:
try:
# Convert "#RRGGBB" to (R, G, B)
if isinstance(color, str) and color.startswith("#") and len(color) == 7:
r = int(color[1:3], 16)
g = int(color[3:5], 16)
b = int(color[5:7], 16)
rgb = (r, g, b)
elif isinstance(color, (list, tuple)) and len(color) == 3:
# Already a tuple/list, just coerce and clamp.
rgb = tuple(max(0, min(255, int(x))) for x in color)
else:
# Unknown format: ignore safely.
continue
# Reorder based on device color order
reordered = (rgb[channel_order[0]], rgb[channel_order[1]], rgb[channel_order[2]])
converted_colors.append(reordered)
except (TypeError, ValueError, IndexError):
# Skip malformed color entries to avoid crashing pattern loops.
continue
if not converted_colors:
converted_colors.append((255, 255, 255))
return converted_colors
-261
View File
@@ -1,261 +0,0 @@
#!/usr/bin/env python3
"""Self-contained led-driver test runner for MicroPython/mpremote."""
import json
import os
import utime
from machine import WDT
from settings import Settings
from presets import Presets, run_tick
from utils import convert_and_reorder_colors
class _TestContext:
def __init__(self):
self.settings = Settings()
self.settings["name"] = self.settings.get("name", "test_device")
self.presets = Presets(self.settings["led_pin"], self.settings["num_leds"])
self.presets.b = self.settings.get("brightness", 255)
self.wdt = WDT(timeout=10000)
def tick_for_ms(self, duration_ms, sleep_ms=5):
start = utime.ticks_ms()
while utime.ticks_diff(utime.ticks_ms(), start) < duration_ms:
self.wdt.feed()
run_tick(self.presets)
utime.sleep_ms(sleep_ms)
def _process_message(ctx, payload):
"""Small test helper that mirrors the main message handling logic."""
try:
if isinstance(payload, (bytes, bytearray)):
data = json.loads(payload)
elif isinstance(payload, str):
data = json.loads(payload)
else:
data = payload
except (TypeError, ValueError):
return "invalid_json"
if not isinstance(data, dict):
return "invalid_shape"
if data.get("v") != "1":
return "wrong_version"
if "b" in data:
try:
ctx.presets.b = max(0, min(255, int(data["b"])))
except (TypeError, ValueError):
pass
if isinstance(data.get("presets"), dict):
for name, preset_data in data["presets"].items():
if not isinstance(preset_data, dict):
continue
color_key = "c" if "c" in preset_data else ("colors" if "colors" in preset_data else None)
if color_key is not None:
try:
preset_data[color_key] = convert_and_reorder_colors(
preset_data[color_key], ctx.settings
)
except (TypeError, ValueError):
continue
ctx.presets.edit(name, preset_data)
if isinstance(data.get("select"), dict) and ctx.settings.get("name") in data["select"]:
select_list = data["select"][ctx.settings.get("name")]
if isinstance(select_list, list) and select_list:
preset_name = select_list[0]
step = select_list[1] if len(select_list) > 1 else None
if isinstance(preset_name, str):
ctx.presets.select(preset_name, step=step)
if "default" in data:
default_name = data["default"]
this_device_name = ctx.settings.get("name")
this_device_name_norm = (
this_device_name.strip().lower()
if isinstance(this_device_name, str)
else None
)
should_apply_default = True
if "targets" in data:
should_apply_default = False
targets = data.get("targets")
if isinstance(targets, list) and this_device_name_norm:
normalized_targets = [
target.strip().lower()
for target in targets
if isinstance(target, str) and target.strip()
]
should_apply_default = this_device_name_norm in normalized_targets
if (
should_apply_default
and
isinstance(default_name, str)
and default_name
and default_name in ctx.presets.presets
):
ctx.settings["default"] = default_name
if "save" in data:
ctx.presets.save()
return "ok"
def test_invalid_messages_do_not_crash():
ctx = _TestContext()
cases = [
b"{not-json",
"[]",
json.dumps({"v": "2"}),
json.dumps({"v": "1", "presets": ["bad"]}),
json.dumps({"v": "1", "select": {"test_device": "not-list"}}),
json.dumps({"v": "1", "presets": {"x": {"c": ["#GG0000"]}}}),
]
for payload in cases:
_process_message(ctx, payload)
ctx.wdt.feed()
def test_preset_edit_sanitization():
ctx = _TestContext()
ctx.presets.edit(
"sanitize",
{
"pattern": "blink",
"delay": "120",
"brightness": "999",
"auto": "false",
"n1": "-5",
"n2": "7",
"unknown_field": "ignored",
},
)
p = ctx.presets.presets["sanitize"]
assert p.p == "blink"
assert p.d == 120
assert p.b == 255
assert p.a is False
assert p.n1 == 0
assert p.n2 == 7
assert not hasattr(p, "unknown_field")
def test_colour_conversion_and_transition():
ctx = _TestContext()
msg = {
"v": "1",
"presets": {
"fade": {
"p": "transition",
"c": ["#ff0000", "#00ff00"],
"d": 80,
"a": True,
}
},
"select": {ctx.settings["name"]: ["fade"]},
}
result = _process_message(ctx, msg)
assert result == "ok"
assert ctx.presets.selected == "fade"
# Smoke-run the generator to ensure math runs without type errors.
ctx.tick_for_ms(250)
def test_pattern_smoke():
ctx = _TestContext()
cases = {
"t_on": {"p": "on", "c": [(16, 8, 4)]},
"t_off": {"p": "off"},
"t_blink": {"p": "blink", "c": [(255, 0, 0)], "d": 20},
"t_rainbow": {"p": "rainbow", "d": 5, "n1": 2},
"t_pulse": {"p": "pulse", "c": [(255, 0, 0)], "n1": 20, "n2": 10, "n3": 20, "d": 10},
"t_transition": {"p": "transition", "c": [(255, 0, 0), (0, 0, 255)], "d": 30},
"t_chase": {"p": "chase", "c": [(255, 0, 0), (0, 0, 255)], "n1": 3, "n2": 2, "n3": 1, "n4": 1, "d": 20},
"t_circle": {"p": "circle", "c": [(255, 255, 0), (0, 0, 8)], "n1": 5, "n2": 10, "n3": 5, "n4": 2},
}
for name, data in cases.items():
ctx.presets.edit(name, data)
assert ctx.presets.select(name), "select failed: %s" % name
ctx.tick_for_ms(120)
def test_default_requires_existing_preset():
ctx = _TestContext()
_process_message(ctx, {"v": "1", "default": "missing"})
assert ctx.settings.get("default") != "missing"
ctx.presets.edit("exists", {"p": "on"})
_process_message(ctx, {"v": "1", "default": "exists"})
assert ctx.settings.get("default") == "exists"
def test_default_targets_gate_by_device_name():
ctx = _TestContext()
ctx.settings["name"] = "a"
ctx.presets.edit("targeted", {"p": "on"})
ctx.settings["default"] = "baseline"
_process_message(
ctx,
{"v": "1", "default": "targeted", "targets": ["11"]},
)
assert ctx.settings.get("default") == "baseline"
_process_message(
ctx,
{"v": "1", "default": "targeted", "targets": [" A "]},
)
assert ctx.settings.get("default") == "targeted"
def test_save_and_load_roundtrip():
ctx = _TestContext()
ctx.presets.edit(
"persist",
{"p": "blink", "c": [(1, 2, 3), (4, 5, 6)], "d": 77, "b": 123, "a": False},
)
assert ctx.presets.save()
reloaded = Presets(ctx.settings["led_pin"], ctx.settings["num_leds"])
assert reloaded.load(ctx.settings)
p = reloaded.presets.get("persist")
assert p is not None
assert p.p == "blink"
assert p.d == 77
assert p.b == 123
assert p.a is False
assert p.c == [(1, 2, 3), (4, 5, 6)]
try:
os.remove("presets.json")
except OSError:
pass
def run_all():
tests = [
test_invalid_messages_do_not_crash,
test_preset_edit_sanitization,
test_colour_conversion_and_transition,
test_pattern_smoke,
test_default_requires_existing_preset,
test_default_targets_gate_by_device_name,
test_save_and_load_roundtrip,
]
print("=" * 56)
print("led-driver self-contained tests")
print("=" * 56)
for test_func in tests:
print("Running %s ..." % test_func.__name__)
test_func()
print(" PASS")
print("-" * 56)
print("All tests passed")
if __name__ == "__main__":
run_all()
-190
View File
@@ -1,190 +0,0 @@
#!/usr/bin/env python3
import utime
from machine import WDT
from settings import Settings
from presets import Presets, run_tick
def run_for(p, wdt, duration_ms):
"""Run pattern for specified duration."""
start = utime.ticks_ms()
while utime.ticks_diff(utime.ticks_ms(), start) < duration_ms:
wdt.feed()
run_tick(p)
utime.sleep_ms(10)
def main():
s = Settings()
pin = s.get("led_pin", 10)
num = s.get("num_leds", 30)
p = Presets(pin=pin, num_leds=num)
wdt = WDT(timeout=10000)
print("=" * 50)
print("Testing Auto and Manual Modes")
print("=" * 50)
# Test 1: Rainbow in AUTO mode (continuous)
print("\nTest 1: Rainbow pattern in AUTO mode (should run continuously)")
p.edit("rainbow_auto", {
"p": "rainbow",
"b": 128,
"d": 50,
"n1": 2,
"a": True,
})
p.select("rainbow_auto")
print("Running rainbow_auto for 3 seconds...")
run_for(p, wdt, 3000)
print("✓ Auto mode: Pattern ran continuously")
# Test 2: Rainbow in MANUAL mode (one step per tick)
print("\nTest 2: Rainbow pattern in MANUAL mode (one step per tick)")
p.edit("rainbow_manual", {
"p": "rainbow",
"b": 128,
"d": 50,
"n1": 2,
"a": False,
})
p.select("rainbow_manual")
print("Calling tick() 5 times (should advance 5 steps)...")
for i in range(5):
run_tick(p)
utime.sleep_ms(100) # Small delay to see changes
print(f" Tick {i+1}: generator={'active' if p.generator is not None else 'stopped'}")
# Check if generator stopped after one cycle
if p.generator is None:
print("✓ Manual mode: Generator stopped after one step (as expected)")
else:
print("⚠ Manual mode: Generator still active (may need multiple ticks)")
# Test 3: Pulse in AUTO mode (continuous cycles)
print("\nTest 3: Pulse pattern in AUTO mode (should pulse continuously)")
p.edit("pulse_auto", {
"p": "pulse",
"b": 128,
"d": 100,
"n1": 500, # Attack
"n2": 200, # Hold
"n3": 500, # Decay
"c": [(255, 0, 0)],
"a": True,
})
p.select("pulse_auto")
print("Running pulse_auto for 3 seconds...")
run_for(p, wdt, 3000)
print("✓ Auto mode: Pulse ran continuously")
# Test 4: Pulse in MANUAL mode (one cycle then stop)
print("\nTest 4: Pulse pattern in MANUAL mode (one cycle then stop)")
p.edit("pulse_manual", {
"p": "pulse",
"b": 128,
"d": 100,
"n1": 300, # Attack
"n2": 200, # Hold
"n3": 300, # Decay
"c": [(0, 255, 0)],
"a": False,
})
p.select("pulse_manual")
print("Running pulse_manual until generator stops...")
tick_count = 0
max_ticks = 200 # Safety limit
while p.generator is not None and tick_count < max_ticks:
run_tick(p)
tick_count += 1
utime.sleep_ms(10)
if p.generator is None:
print(f"✓ Manual mode: Pulse completed one cycle after {tick_count} ticks")
else:
print(f"⚠ Manual mode: Pulse still running after {tick_count} ticks")
# Test 5: Transition in AUTO mode (continuous transitions)
print("\nTest 5: Transition pattern in AUTO mode (continuous transitions)")
p.edit("transition_auto", {
"p": "transition",
"b": 128,
"d": 500,
"c": [(255, 0, 0), (0, 255, 0), (0, 0, 255)],
"a": True,
})
p.select("transition_auto")
print("Running transition_auto for 3 seconds...")
run_for(p, wdt, 3000)
print("✓ Auto mode: Transition ran continuously")
# Test 6: Transition in MANUAL mode (one transition then stop)
print("\nTest 6: Transition pattern in MANUAL mode (one transition then stop)")
p.edit("transition_manual", {
"p": "transition",
"b": 128,
"d": 500,
"c": [(255, 0, 0), (0, 255, 0)],
"a": False,
})
p.select("transition_manual")
print("Running transition_manual until generator stops...")
tick_count = 0
max_ticks = 200
while p.generator is not None and tick_count < max_ticks:
run_tick(p)
tick_count += 1
utime.sleep_ms(10)
if p.generator is None:
print(f"✓ Manual mode: Transition completed after {tick_count} ticks")
else:
print(f"⚠ Manual mode: Transition still running after {tick_count} ticks")
# Test 7: Switching between auto and manual modes
print("\nTest 7: Switching between auto and manual modes")
p.edit("switch_test", {
"p": "rainbow",
"b": 128,
"d": 50,
"n1": 2,
"a": True,
})
p.select("switch_test")
print("Running in auto mode for 1 second...")
run_for(p, wdt, 1000)
# Switch to manual mode by editing the preset
print("Switching to manual mode...")
p.edit("switch_test", {"a": False})
p.select("switch_test") # Re-select to apply changes
print("Calling tick() 3 times in manual mode...")
for i in range(3):
run_tick(p)
utime.sleep_ms(100)
print(f" Tick {i+1}: generator={'active' if p.generator is not None else 'stopped'}")
# Switch back to auto mode
print("Switching back to auto mode...")
p.edit("switch_test", {"a": True})
p.select("switch_test")
print("Running in auto mode for 1 second...")
run_for(p, wdt, 1000)
print("✓ Successfully switched between auto and manual modes")
# Cleanup
print("\nCleaning up...")
p.edit("cleanup_off", {"p": "off"})
p.select("cleanup_off")
run_tick(p)
utime.sleep_ms(100)
print("\n" + "=" * 50)
print("All tests completed!")
print("=" * 50)
if __name__ == "__main__":
main()
-35
View File
@@ -1,35 +0,0 @@
#!/usr/bin/env python3
import utime
from machine import WDT
from settings import Settings
from presets import Presets, run_tick
def main():
s = Settings()
pin = s.get("led_pin", 10)
num = s.get("num_leds", 30)
p = Presets(pin=pin, num_leds=num)
wdt = WDT(timeout=10000)
# Create blink preset (use short-key fields: p=pattern, b=brightness, d=delay, c=colors)
p.edit("test_blink", {
"p": "blink",
"b": 64,
"d": 200,
"c": [(255, 0, 0), (0, 0, 255)],
})
p.select("test_blink")
start = utime.ticks_ms()
while utime.ticks_diff(utime.ticks_ms(), start) < 1500:
wdt.feed()
run_tick(p)
utime.sleep_ms(10)
if __name__ == "__main__":
main()
-161
View File
@@ -1,161 +0,0 @@
#!/usr/bin/env python3
import utime
from machine import WDT
from settings import Settings
from presets import Presets, run_tick
def run_for(p, wdt, ms):
"""Helper: run current pattern for given ms using tick()."""
start = utime.ticks_ms()
while utime.ticks_diff(utime.ticks_ms(), start) < ms:
wdt.feed()
run_tick(p)
utime.sleep_ms(10)
def main():
s = Settings()
pin = s.get("led_pin", 10)
num = s.get("num_leds", 30)
p = Presets(pin=pin, num_leds=num)
wdt = WDT(timeout=10000)
# Test 1: Basic chase (n1=5, n2=5, n3=1, n4=1)
print("Test 1: Basic chase (n1=5, n2=5, n3=1, n4=1)")
p.edit("chase1", {
"p": "chase",
"b": 255,
"d": 200,
"n1": 5,
"n2": 5,
"n3": 1,
"n4": 1,
"c": [(255, 0, 0), (0, 255, 0)],
})
p.select("chase1")
run_for(p, wdt, 3000)
# Test 2: Forward and backward (n3=2, n4=-1)
print("Test 2: Forward and backward (n3=2, n4=-1)")
p.edit("chase2", {
"p": "chase",
"n1": 3,
"n2": 3,
"n3": 2,
"n4": -1,
"d": 150,
"c": [(0, 0, 255), (255, 255, 0)],
})
p.select("chase2")
run_for(p, wdt, 3000)
# Test 3: Large segments (n1=10, n2=5)
print("Test 3: Large segments (n1=10, n2=5, n3=3, n4=3)")
p.edit("chase3", {
"p": "chase",
"n1": 10,
"n2": 5,
"n3": 3,
"n4": 3,
"d": 200,
"c": [(255, 128, 0), (128, 0, 255)],
})
p.select("chase3")
run_for(p, wdt, 3000)
# Test 4: Fast movement (n3=5, n4=5)
print("Test 4: Fast movement (n3=5, n4=5)")
p.edit("chase4", {
"p": "chase",
"n1": 4,
"n2": 4,
"n3": 5,
"n4": 5,
"d": 100,
"c": [(255, 0, 255), (0, 255, 255)],
})
p.select("chase4")
run_for(p, wdt, 2000)
# Test 5: Backward movement (n3=-2, n4=-2)
print("Test 5: Backward movement (n3=-2, n4=-2)")
p.edit("chase5", {
"p": "chase",
"n1": 6,
"n2": 4,
"n3": -2,
"n4": -2,
"d": 200,
"c": [(255, 255, 255), (0, 0, 0)],
})
p.select("chase5")
run_for(p, wdt, 3000)
# Test 6: Alternating forward/backward (n3=3, n4=-2)
print("Test 6: Alternating forward/backward (n3=3, n4=-2)")
p.edit("chase6", {
"p": "chase",
"n1": 5,
"n2": 5,
"n3": 3,
"n4": -2,
"d": 250,
"c": [(255, 0, 0), (0, 255, 0)],
})
p.select("chase6")
run_for(p, wdt, 4000)
# Test 7: Manual mode - advance one step per beat
print("Test 7: Manual mode chase (auto=False, n3=2, n4=1)")
p.edit("chase_manual", {
"p": "chase",
"n1": 4,
"n2": 4,
"n3": 2,
"n4": 1,
"d": 200,
"c": [(255, 255, 0), (0, 255, 255)],
"a": False,
})
p.step = 0 # Reset step counter
print(" Advancing pattern with 10 beats (select + tick)...")
for i in range(10):
p.select("chase_manual") # Simulate beat - restarts generator
run_tick(p) # Advance one step
utime.sleep_ms(500) # Pause to see the pattern
wdt.feed()
print(f" Beat {i+1}: step={p.step}")
# Test 8: Verify step increments correctly in manual mode
print("Test 8: Verify step increments (auto=False)")
p.edit("chase_manual2", {
"p": "chase",
"n1": 3,
"n2": 3,
"n3": 1,
"n4": 1,
"a": False,
})
p.step = 0
initial_step = p.step
p.select("chase_manual2")
run_tick(p)
final_step = p.step
print(f" Step updated from {initial_step} to {final_step} (expected: 1)")
if final_step == 1:
print(" ✓ Step increment working correctly")
else:
print(f" ✗ Step increment mismatch! Expected 1, got {final_step}")
# Cleanup
print("Test complete, turning off")
p.edit("cleanup_off", {"p": "off"})
p.select("cleanup_off")
run_for(p, wdt, 100)
if __name__ == "__main__":
main()
-113
View File
@@ -1,113 +0,0 @@
#!/usr/bin/env python3
import utime
from machine import WDT
from settings import Settings
from presets import Presets, run_tick
def run_for(p, wdt, ms):
"""Helper: run current pattern for given ms using tick()."""
start = utime.ticks_ms()
while utime.ticks_diff(utime.ticks_ms(), start) < ms:
wdt.feed()
run_tick(p)
utime.sleep_ms(10)
def main():
s = Settings()
pin = s.get("led_pin", 10)
num = s.get("num_leds", 30)
p = Presets(pin=pin, num_leds=num)
wdt = WDT(timeout=10000)
# Test 1: Basic circle (n1=50, n2=100, n3=200, n4=0)
print("Test 1: Basic circle (n1=50, n2=100, n3=200, n4=0)")
p.edit("circle1", {
"p": "circle",
"b": 255,
"n1": 50, # Head moves 50 LEDs/second
"n2": 100, # Max length 100 LEDs
"n3": 200, # Tail moves 200 LEDs/second
"n4": 0, # Min length 0 LEDs
"c": [(255, 0, 0)], # Red
})
p.select("circle1")
run_for(p, wdt, 5000)
# Test 2: Slow growth, fast shrink (n1=20, n2=50, n3=100, n4=0)
print("Test 2: Slow growth, fast shrink (n1=20, n2=50, n3=100, n4=0)")
p.edit("circle2", {
"p": "circle",
"n1": 20,
"n2": 50,
"n3": 100,
"n4": 0,
"c": [(0, 255, 0)], # Green
})
p.select("circle2")
run_for(p, wdt, 5000)
# Test 3: Fast growth, slow shrink (n1=100, n2=30, n3=20, n4=0)
print("Test 3: Fast growth, slow shrink (n1=100, n2=30, n3=20, n4=0)")
p.edit("circle3", {
"p": "circle",
"n1": 100,
"n2": 30,
"n3": 20,
"n4": 0,
"c": [(0, 0, 255)], # Blue
})
p.select("circle3")
run_for(p, wdt, 5000)
# Test 4: With minimum length (n1=50, n2=40, n3=100, n4=10)
print("Test 4: With minimum length (n1=50, n2=40, n3=100, n4=10)")
p.edit("circle4", {
"p": "circle",
"n1": 50,
"n2": 40,
"n3": 100,
"n4": 10,
"c": [(255, 255, 0)], # Yellow
})
p.select("circle4")
run_for(p, wdt, 5000)
# Test 5: Very fast (n1=200, n2=20, n3=200, n4=0)
print("Test 5: Very fast (n1=200, n2=20, n3=200, n4=0)")
p.edit("circle5", {
"p": "circle",
"n1": 200,
"n2": 20,
"n3": 200,
"n4": 0,
"c": [(255, 0, 255)], # Magenta
})
p.select("circle5")
run_for(p, wdt, 3000)
# Test 6: Very slow (n1=10, n2=25, n3=10, n4=0)
print("Test 6: Very slow (n1=10, n2=25, n3=10, n4=0)")
p.edit("circle6", {
"p": "circle",
"n1": 10,
"n2": 25,
"n3": 10,
"n4": 0,
"c": [(0, 255, 255)], # Cyan
})
p.select("circle6")
run_for(p, wdt, 5000)
# Cleanup
print("Test complete, turning off")
p.edit("cleanup_off", {"p": "off"})
p.select("cleanup_off")
run_for(p, wdt, 100)
if __name__ == "__main__":
main()
-30
View File
@@ -1,30 +0,0 @@
#!/usr/bin/env python3
import utime
from machine import WDT
from settings import Settings
from presets import Presets, run_tick
def main():
s = Settings()
pin = s.get("led_pin", 10)
num = s.get("num_leds", 30)
p = Presets(pin=pin, num_leds=num)
wdt = WDT(timeout=10000)
# Create an "off" preset (use short-key field `p` for pattern)
p.edit("test_off", {"p": "off"})
p.select("test_off")
start = utime.ticks_ms()
while utime.ticks_diff(utime.ticks_ms(), start) < 200:
wdt.feed()
run_tick(p)
utime.sleep_ms(10)
if __name__ == "__main__":
main()
-47
View File
@@ -1,47 +0,0 @@
#!/usr/bin/env python3
import utime
from machine import WDT
from settings import Settings
from presets import Presets, run_tick
def main():
s = Settings()
pin = s.get("led_pin", 10)
num = s.get("num_leds", 30)
p = Presets(pin=pin, num_leds=num)
wdt = WDT(timeout=10000)
# Create presets for on and off using the short-key fields that Presets expects
# Preset fields:
# p = pattern name, b = brightness, d = delay, c = list of (r,g,b) colors
p.edit("test_on", {
"p": "on",
"b": 64,
"d": 120,
"c": [(255, 0, 0), (0, 0, 255)],
})
p.edit("test_off", {"p": "off"})
# ON phase
p.select("test_on")
start = utime.ticks_ms()
while utime.ticks_diff(utime.ticks_ms(), start) < 800:
wdt.feed()
run_tick(p)
utime.sleep_ms(10)
# OFF phase
p.select("test_off")
start = utime.ticks_ms()
while utime.ticks_diff(utime.ticks_ms(), start) < 100:
wdt.feed()
run_tick(p)
utime.sleep_ms(10)
if __name__ == "__main__":
main()
-92
View File
@@ -1,92 +0,0 @@
#!/usr/bin/env python3
import utime
from machine import WDT
from settings import Settings
from presets import Presets, run_tick
def run_for(p, wdt, ms):
"""Helper: run current pattern for given ms using tick()."""
start = utime.ticks_ms()
while utime.ticks_diff(utime.ticks_ms(), start) < ms:
wdt.feed()
run_tick(p)
utime.sleep_ms(10)
def main():
s = Settings()
pin = s.get("led_pin", 10)
num = s.get("num_leds", 30)
p = Presets(pin=pin, num_leds=num)
wdt = WDT(timeout=10000)
# Test 1: Simple single-color pulse
print("Test 1: Single-color pulse (attack=500, hold=500, decay=500, delay=500)")
p.edit("pulse1", {
"p": "pulse",
"b": 255,
"c": [(255, 0, 0)],
"n1": 500, # attack ms
"n2": 500, # hold ms
"n3": 500, # decay ms
"d": 500, # delay ms between pulses
"a": True,
})
p.select("pulse1")
run_for(p, wdt, 5000)
# Test 2: Faster pulse
print("Test 2: Fast pulse (attack=100, hold=100, decay=100, delay=100)")
p.edit("pulse2", {
"p": "pulse",
"n1": 100,
"n2": 100,
"n3": 100,
"d": 100,
"c": [(0, 255, 0)],
})
p.select("pulse2")
run_for(p, wdt, 4000)
# Test 3: Multi-color pulse cycle
print("Test 3: Multi-color pulse (red -> green -> blue)")
p.edit("pulse3", {
"p": "pulse",
"n1": 300,
"n2": 300,
"n3": 300,
"d": 200,
"c": [(255, 0, 0), (0, 255, 0), (0, 0, 255)],
"a": True,
})
p.select("pulse3")
run_for(p, wdt, 6000)
# Test 4: One-shot pulse (auto=False)
print("Test 4: Single pulse, auto=False")
p.edit("pulse4", {
"p": "pulse",
"n1": 400,
"n2": 0,
"n3": 400,
"d": 0,
"c": [(255, 255, 255)],
"a": False,
})
p.select("pulse4")
# Run long enough to allow one full pulse cycle
run_for(p, wdt, 1500)
# Cleanup
print("Test complete, turning off")
p.edit("cleanup_off", {"p": "off"})
p.select("cleanup_off")
run_for(p, wdt, 200)
if __name__ == "__main__":
main()
-151
View File
@@ -1,151 +0,0 @@
#!/usr/bin/env python3
import utime
from machine import WDT
from settings import Settings
from presets import Presets, run_tick
def run_for(p, wdt, ms):
"""Helper: run current pattern for given ms using tick()."""
start = utime.ticks_ms()
while utime.ticks_diff(utime.ticks_ms(), start) < ms:
wdt.feed()
run_tick(p)
utime.sleep_ms(10)
def main():
s = Settings()
pin = s.get("led_pin", 10)
num = s.get("num_leds", 30)
p = Presets(pin=pin, num_leds=num)
wdt = WDT(timeout=10000)
# Test 1: Basic rainbow with auto=True (continuous)
print("Test 1: Basic rainbow (auto=True, n1=1)")
p.edit("rainbow1", {
"p": "rainbow",
"b": 255,
"d": 100,
"n1": 1,
"a": True,
})
p.select("rainbow1")
run_for(p, wdt, 3000)
# Test 2: Fast rainbow
print("Test 2: Fast rainbow (low delay, n1=1)")
p.edit("rainbow2", {
"p": "rainbow",
"d": 50,
"n1": 1,
"a": True,
})
p.select("rainbow2")
run_for(p, wdt, 2000)
# Test 3: Slow rainbow
print("Test 3: Slow rainbow (high delay, n1=1)")
p.edit("rainbow3", {
"p": "rainbow",
"d": 500,
"n1": 1,
"a": True,
})
p.select("rainbow3")
run_for(p, wdt, 3000)
# Test 4: Low brightness rainbow
print("Test 4: Low brightness rainbow (n1=1)")
p.edit("rainbow4", {
"p": "rainbow",
"b": 64,
"d": 100,
"n1": 1,
"a": True,
})
p.select("rainbow4")
run_for(p, wdt, 2000)
# Test 5: Single-step rainbow (auto=False)
print("Test 5: Single-step rainbow (auto=False, n1=1)")
p.edit("rainbow5", {
"p": "rainbow",
"b": 255,
"d": 100,
"n1": 1,
"a": False,
})
p.step = 0
for i in range(10):
p.select("rainbow5")
# One tick advances the generator one frame when auto=False
run_tick(p)
utime.sleep_ms(100)
wdt.feed()
# Test 6: Verify step updates correctly
print("Test 6: Verify step updates (auto=False, n1=1)")
p.edit("rainbow6", {
"p": "rainbow",
"n1": 1,
"a": False,
})
initial_step = p.step
p.select("rainbow6")
run_tick(p)
final_step = p.step
print(f"Step updated from {initial_step} to {final_step} (expected increment: 1)")
# Test 7: Fast step increment (n1=5)
print("Test 7: Fast rainbow (n1=5, auto=True)")
p.edit("rainbow7", {
"p": "rainbow",
"b": 255,
"d": 100,
"n1": 5,
"a": True,
})
p.select("rainbow7")
run_for(p, wdt, 2000)
# Test 8: Very fast step increment (n1=10)
print("Test 8: Very fast rainbow (n1=10, auto=True)")
p.edit("rainbow8", {
"p": "rainbow",
"n1": 10,
"a": True,
})
p.select("rainbow8")
run_for(p, wdt, 2000)
# Test 9: Verify n1 controls step increment (auto=False)
print("Test 9: Verify n1 step increment (auto=False, n1=5)")
p.edit("rainbow9", {
"p": "rainbow",
"n1": 5,
"a": False,
})
p.step = 0
initial_step = p.step
p.select("rainbow9")
run_tick(p)
final_step = p.step
expected_step = (initial_step + 5) % 256
print(f"Step updated from {initial_step} to {final_step} (expected: {expected_step})")
if final_step == expected_step:
print("✓ n1 step increment working correctly")
else:
print(f"✗ Step increment mismatch! Expected {expected_step}, got {final_step}")
# Cleanup
print("Test complete, turning off")
p.edit("cleanup_off", {"p": "off"})
p.select("cleanup_off")
run_for(p, wdt, 100)
if __name__ == "__main__":
main()
-81
View File
@@ -1,81 +0,0 @@
#!/usr/bin/env python3
import utime
from machine import WDT
from settings import Settings
from presets import Presets, run_tick
def run_for(p, wdt, ms):
"""Helper: run current pattern for given ms using tick()."""
start = utime.ticks_ms()
while utime.ticks_diff(utime.ticks_ms(), start) < ms:
wdt.feed()
run_tick(p)
utime.sleep_ms(10)
def main():
s = Settings()
pin = s.get("led_pin", 10)
num = s.get("num_leds", 30)
p = Presets(pin=pin, num_leds=num)
wdt = WDT(timeout=10000)
# Test 1: Simple two-color transition
print("Test 1: Two-color transition (red <-> blue, delay=1000)")
p.edit("transition1", {
"p": "transition",
"b": 255,
"d": 1000, # transition duration
"c": [(255, 0, 0), (0, 0, 255)],
"a": True,
})
p.select("transition1")
run_for(p, wdt, 6000)
# Test 2: Multi-color transition
print("Test 2: Multi-color transition (red -> green -> blue -> white)")
p.edit("transition2", {
"p": "transition",
"d": 800,
"c": [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255)],
"a": True,
})
p.select("transition2")
run_for(p, wdt, 8000)
# Test 3: One-shot transition (auto=False)
print("Test 3: One-shot transition (auto=False)")
p.edit("transition3", {
"p": "transition",
"d": 1000,
"c": [(255, 0, 0), (0, 255, 0)],
"a": False,
})
p.select("transition3")
# Run long enough for a single transition step
run_for(p, wdt, 2000)
# Test 4: Single-color behavior (should just stay on)
print("Test 4: Single-color transition (should hold color)")
p.edit("transition4", {
"p": "transition",
"c": [(0, 0, 255)],
"d": 500,
"a": True,
})
p.select("transition4")
run_for(p, wdt, 3000)
# Cleanup
print("Test complete, turning off")
p.edit("cleanup_off", {"p": "off"})
p.select("cleanup_off")
run_for(p, wdt, 200)
if __name__ == "__main__":
main()
-25
View File
@@ -1,25 +0,0 @@
from espnow import ESPNow
import network
sta = network.WLAN(network.STA_IF)
sta.active(True)
espnow = ESPNow()
espnow.active(True)
# add_peer() expects a 6-byte MAC (bytes/bytearray), not integers.
# Unicast placeholders (not broadcast/multicast) so get_peers() lists them.
# PEERS = aa:aa:aa:aa:aa:START … aa:aa:aa:aa:aa:END (inclusive last octet).
_PREFIX = b"\xaa\xaa\xaa\xaa\xaa"
_START_LAST_OCTET = 1
_END_LAST_OCTET = 40
PEERS = tuple(_PREFIX + bytes((i,)) for i in range(_START_LAST_OCTET, _END_LAST_OCTET + 1))
for peer in PEERS:
espnow.add_peer(peer)
print("peers:", PEERS)
for peer in PEERS:
espnow.send(peer, b"Hello, world!")
print(espnow.get_peers())
-41
View File
@@ -1,41 +0,0 @@
#!/usr/bin/env python3
"""MicroPython AP example with power management disabled (pm=0).
Run on device:
mpremote connect /dev/ttyACM0 run tests/test_ap_pm0.py
"""
import network
import time
AP_SSID = "led-ap"
AP_PASSWORD = "ledpass123"
AP_CHANNEL = 6
def main():
ap = network.WLAN(network.AP_IF)
ap.active(True)
# Explicitly disable Wi-Fi power save for AP mode.
try:
ap.config(pm=0)
except (AttributeError, ValueError, TypeError):
try:
ap.config(pm=network.WLAN.PM_NONE)
except (AttributeError, ValueError, TypeError):
pass
ap.config(essid=AP_SSID, password=AP_PASSWORD, channel=AP_CHANNEL, authmode=3)
print("[ap-pm0] AP active:", ap.active())
print("[ap-pm0] SSID:", AP_SSID)
print("[ap-pm0] IFCONFIG:", ap.ifconfig())
print("[ap-pm0] Waiting for clients. Ctrl+C to stop.")
while True:
time.sleep(2)
if __name__ == "__main__":
main()
-694
View File
@@ -1,694 +0,0 @@
#!/usr/bin/env python3
"""Test ESPNow receive functionality - runs on MicroPython device."""
import json
import os
import utime
from settings import Settings
from presets import Presets, run_tick
from utils import convert_and_reorder_colors
class MockESPNow:
"""Mock ESPNow for testing that can send messages."""
def __init__(self):
self.messages = []
self.active_state = False
def active(self, state):
self.active_state = state
def any(self):
"""Return True if there are messages."""
return len(self.messages) > 0
def recv(self):
"""Receive a message (removes it from queue)."""
if self.messages:
return self.messages.pop(0)
return None, None
def send_message(self, host, msg_data):
"""Send a message by adding it to the queue (testing helper)."""
if isinstance(msg_data, dict):
msg = json.dumps(msg_data)
else:
msg = msg_data
self.messages.append((host, msg))
def clear(self):
"""Clear all messages (testing helper)."""
self.messages = []
from machine import WDT
def get_wdt():
"""Get a real WDT instance for tests."""
return WDT(timeout=10000) # 10 second timeout for tests
def run_main_loop_iterations(espnow, patterns, settings, wdt, max_iterations=10):
"""Run main loop iterations until no messages or max reached."""
iterations = 0
results = []
while iterations < max_iterations:
wdt.feed()
run_tick(patterns)
if espnow.any():
host, msg = espnow.recv()
data = json.loads(msg)
if data.get("v") != "1":
results.append(("version_rejected", data))
continue
if "presets" in data:
for name, preset_data in data["presets"].items():
# Convert hex color strings to RGB tuples and reorder based on device color order
if "colors" in preset_data:
preset_data["colors"] = convert_and_reorder_colors(preset_data["colors"], settings)
patterns.edit(name, preset_data)
results.append(("presets_processed", list(data["presets"].keys())))
if settings.get("name") in data.get("select", {}):
select_list = data["select"][settings.get("name")]
# Select value is always a list: ["preset_name"] or ["preset_name", step]
if select_list:
preset_name = select_list[0]
step = select_list[1] if len(select_list) > 1 else None
if patterns.select(preset_name, step=step):
results.append(("selected", preset_name))
iterations += 1
# Stop if no more messages
if not espnow.any():
break
return results
def test_version_check():
"""Test that messages with wrong version are rejected."""
print("Test 1: Version check")
settings = Settings()
patterns = Presets(settings["led_pin"], settings["num_leds"])
mock_espnow = MockESPNow()
wdt = get_wdt()
# Send message with wrong version
mock_espnow.send_message(b"\xaa\xaa\xaa\xaa\xaa\xaa", {"v": "2", "presets": {"test": {"pattern": "on"}}})
results = run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
assert len([r for r in results if r[0] == "version_rejected"]) > 0, "Should reject wrong version"
assert "test" not in patterns.presets, "Preset should not be created"
print(" ✓ Version check passed")
# Send message with correct version
mock_espnow.clear()
mock_espnow.send_message(b"\xaa\xaa\xaa\xaa\xaa\xaa", {"v": "1", "presets": {"test": {"pattern": "on"}}})
results = run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
assert len([r for r in results if r[0] == "presets_processed"]) > 0, "Should process correct version"
assert "test" in patterns.presets, "Preset should be created"
print(" ✓ Correct version accepted")
def test_preset_creation():
"""Test preset creation from ESPNow messages."""
print("\nTest 2: Preset creation")
settings = Settings()
patterns = Presets(settings["led_pin"], settings["num_leds"])
mock_espnow = MockESPNow()
wdt = get_wdt()
msg = {
"v": "1",
"presets": {
"test_blink": {
"pattern": "blink",
"colors": ["#FF0000", "#00FF00"],
"delay": 200,
"brightness": 128
},
"test_rainbow": {
"pattern": "rainbow",
"delay": 100,
"n1": 2
}
}
}
mock_espnow.send_message(b"\xbb\xbb\xbb\xbb\xbb\xbb", msg)
run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
assert "test_blink" in patterns.presets, "test_blink preset should exist"
assert "test_rainbow" in patterns.presets, "test_rainbow preset should exist"
# Check preset values
blink_preset = patterns.presets["test_blink"]
assert blink_preset.pattern == "blink", "Pattern should be blink"
assert blink_preset.delay == 200, "Delay should be 200"
assert blink_preset.brightness == 128, "Brightness should be 128"
rainbow_preset = patterns.presets["test_rainbow"]
assert rainbow_preset.pattern == "rainbow", "Pattern should be rainbow"
assert rainbow_preset.n1 == 2, "n1 should be 2"
print(" ✓ Presets created correctly")
def test_color_conversion():
"""Test hex color string conversion and reordering."""
print("\nTest 3: Color conversion")
settings = Settings()
settings["color_order"] = "rgb" # Default RGB order
patterns = Presets(settings["led_pin"], settings["num_leds"])
mock_espnow = MockESPNow()
wdt = get_wdt()
msg = {
"v": "1",
"presets": {
"test_colors": {
"pattern": "on",
"colors": ["#FF0000", "#00FF00", "#0000FF"] # Red, Green, Blue
}
}
}
mock_espnow.send_message(b"\xcc\xcc\xcc\xcc\xcc\xcc", msg)
run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
preset = patterns.presets["test_colors"]
assert len(preset.colors) == 3, "Should have 3 colors"
assert preset.colors[0] == (255, 0, 0), "First color should be red (255,0,0)"
assert preset.colors[1] == (0, 255, 0), "Second color should be green (0,255,0)"
assert preset.colors[2] == (0, 0, 255), "Third color should be blue (0,0,255)"
print(" ✓ Colors converted correctly (RGB order)")
# Test GRB order
settings["color_order"] = "grb"
patterns2 = Presets(settings["led_pin"], settings["num_leds"])
mock_espnow2 = MockESPNow()
msg2 = {
"v": "1",
"presets": {
"test_grb": {
"pattern": "on",
"colors": ["#FF0000"] # Red in RGB, should become (0, 255, 0) in GRB
}
}
}
mock_espnow2.send_message(b"\xdd\xdd\xdd\xdd\xdd\xdd", msg2)
wdt2 = get_wdt()
run_main_loop_iterations(mock_espnow2, patterns2, settings, wdt2)
preset2 = patterns2.presets["test_grb"]
assert preset2.colors[0] == (0, 255, 0), "GRB: Red should become green (0,255,0)"
print(" ✓ Colors reordered correctly (GRB order)")
def test_preset_update():
"""Test that editing an existing preset updates it."""
print("\nTest 4: Preset update")
settings = Settings()
patterns = Presets(settings["led_pin"], settings["num_leds"])
mock_espnow = MockESPNow()
wdt = get_wdt()
# Create initial preset
msg1 = {
"v": "1",
"presets": {
"test_update": {
"pattern": "blink",
"delay": 100,
"brightness": 64
}
}
}
mock_espnow.send_message(b"\xee\xee\xee\xee\xee\xee", msg1)
run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
assert patterns.presets["test_update"].delay == 100, "Initial delay should be 100"
# Update preset
mock_espnow.clear()
msg2 = {
"v": "1",
"presets": {
"test_update": {
"pattern": "blink",
"delay": 200,
"brightness": 128
}
}
}
mock_espnow.send_message(b"\xff\xff\xff\xff\xff\xff", msg2)
run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
assert patterns.presets["test_update"].delay == 200, "Updated delay should be 200"
assert patterns.presets["test_update"].brightness == 128, "Updated brightness should be 128"
print(" ✓ Preset updated correctly")
def test_select():
"""Test preset selection."""
print("\nTest 5: Preset selection")
settings = Settings()
settings["name"] = "device1"
patterns = Presets(settings["led_pin"], settings["num_leds"])
mock_espnow = MockESPNow()
wdt = get_wdt()
# Create presets
msg1 = {
"v": "1",
"presets": {
"preset1": {"pattern": "on", "colors": [(255, 0, 0)]},
"preset2": {"pattern": "rainbow", "delay": 50}
}
}
mock_espnow.send_message(b"\x11\x11\x11\x11\x11\x11", msg1)
run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
# Select preset
mock_espnow.clear()
msg2 = {
"v": "1",
"select": {
"device1": ["preset1"],
"device2": ["preset2"]
}
}
mock_espnow.send_message(b"\x22\x22\x22\x22\x22\x22", msg2)
run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
assert patterns.selected == "preset1", "Should select preset1"
print(" ✓ Preset selected correctly")
def test_full_message():
"""Test a full message with presets and select."""
print("\nTest 6: Full message (presets + select)")
settings = Settings()
settings["name"] = "test_device"
patterns = Presets(settings["led_pin"], settings["num_leds"])
mock_espnow = MockESPNow()
wdt = get_wdt()
msg = {
"v": "1",
"presets": {
"my_preset": {
"pattern": "pulse",
"colors": ["#FF0000", "#00FF00"],
"delay": 150,
"n1": 500,
"n2": 200,
"n3": 500
}
},
"select": {
"test_device": ["my_preset"],
"other_device": ["other_preset"]
}
}
mock_espnow.send_message(b"\x44\x44\x44\x44\x44\x44", msg)
run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
assert "my_preset" in patterns.presets, "Preset should be created"
assert patterns.selected == "my_preset", "Preset should be selected"
preset = patterns.presets["my_preset"]
assert preset.pattern == "pulse", "Pattern should be pulse"
assert preset.delay == 150, "Delay should be 150"
assert preset.n1 == 500, "n1 should be 500"
print(" ✓ Full message processed correctly")
def test_switch_presets():
"""Test switching between different presets."""
print("\nTest 7: Switch between presets")
settings = Settings()
settings["name"] = "switch_device"
patterns = Presets(settings["led_pin"], settings["num_leds"])
mock_espnow = MockESPNow()
wdt = get_wdt()
# Create multiple presets
msg1 = {
"v": "1",
"presets": {
"preset_blink": {"pattern": "blink", "delay": 200, "colors": [(255, 0, 0)]},
"preset_rainbow": {"pattern": "rainbow", "delay": 100, "n1": 2},
"preset_pulse": {"pattern": "pulse", "delay": 150, "n1": 500, "n2": 200, "n3": 500}
}
}
mock_espnow.send_message(b"\x55\x55\x55\x55\x55\x55", msg1)
run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
# Select and run first preset for 2 seconds
mock_espnow.clear()
msg2 = {
"v": "1",
"select": {
"switch_device": ["preset_blink"]
}
}
mock_espnow.send_message(b"\x66\x66\x66\x66\x66\x66", msg2)
run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
assert patterns.selected == "preset_blink", "Should select preset_blink"
print(" ✓ Selected preset_blink, running for 2 seconds...")
start = utime.ticks_ms()
while utime.ticks_diff(utime.ticks_ms(), start) < 2000:
wdt.feed()
run_tick(patterns)
utime.sleep_ms(10)
# Switch to second preset and run for 2 seconds
mock_espnow.clear()
msg3 = {
"v": "1",
"select": {
"switch_device": ["preset_rainbow"]
}
}
mock_espnow.send_message(b"\x77\x77\x77\x77\x77\x77", msg3)
run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
assert patterns.selected == "preset_rainbow", "Should switch to preset_rainbow"
print(" ✓ Switched to preset_rainbow, running for 2 seconds...")
start = utime.ticks_ms()
while utime.ticks_diff(utime.ticks_ms(), start) < 2000:
wdt.feed()
run_tick(patterns)
utime.sleep_ms(10)
# Switch to third preset and run for 2 seconds
mock_espnow.clear()
msg4 = {
"v": "1",
"select": {
"switch_device": ["preset_pulse"]
}
}
mock_espnow.send_message(b"\x88\x88\x88\x88\x88\x88", msg4)
run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
assert patterns.selected == "preset_pulse", "Should switch to preset_pulse"
print(" ✓ Switched to preset_pulse, running for 2 seconds...")
start = utime.ticks_ms()
while utime.ticks_diff(utime.ticks_ms(), start) < 2000:
wdt.feed()
run_tick(patterns)
utime.sleep_ms(10)
# Switch back to first preset and run for 2 seconds
mock_espnow.clear()
msg5 = {
"v": "1",
"select": {
"switch_device": ["preset_blink"]
}
}
mock_espnow.send_message(b"\x99\x99\x99\x99\x99\x99", msg5)
run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
assert patterns.selected == "preset_blink", "Should switch back to preset_blink"
print(" ✓ Switched back to preset_blink, running for 2 seconds...")
start = utime.ticks_ms()
while utime.ticks_diff(utime.ticks_ms(), start) < 2000:
wdt.feed()
run_tick(patterns)
utime.sleep_ms(10)
print(" ✓ Preset switching works correctly")
def test_beat_functionality():
"""Test beat functionality - calling select() again with same preset restarts pattern."""
print("\nTest 8: Beat functionality")
settings = Settings()
settings["name"] = "beat_device"
patterns = Presets(settings["led_pin"], settings["num_leds"])
mock_espnow = MockESPNow()
wdt = get_wdt()
# Create presets with manual mode
msg1 = {
"v": "1",
"presets": {
"beat_rainbow": {"pattern": "rainbow", "delay": 100, "n1": 1, "auto": False},
"beat_chase": {"pattern": "chase", "delay": 200, "n1": 4, "n2": 4, "n3": 2, "n4": 1, "auto": False},
"beat_pulse": {"pattern": "pulse", "delay": 150, "n1": 300, "n2": 100, "n3": 300, "auto": False}
}
}
mock_espnow.send_message(b"\xaa\xaa\xaa\xaa\xaa\xaa", msg1)
run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
# Test 1: Beat with rainbow (manual mode) - should advance one step per beat
print(" Test 8.1: Beat with rainbow (manual mode)")
patterns.step = 0
mock_espnow.clear()
msg2 = {
"v": "1",
"select": {
"beat_device": ["beat_rainbow"]
}
}
mock_espnow.send_message(b"\xbb\xbb\xbb\xbb\xbb\xbb", msg2)
run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
assert patterns.selected == "beat_rainbow", "Should select beat_rainbow"
initial_step = patterns.step
# First beat - advance one step
mock_espnow.clear()
mock_espnow.send_message(b"\xcc\xcc\xcc\xcc\xcc\xcc", msg2) # Same select message = beat
run_main_loop_iterations(mock_espnow, patterns, settings, wdt, max_iterations=5)
# tick() is already called in run_main_loop_iterations, so step should be incremented
assert patterns.step == (initial_step + 1) % 256, f"Step should increment from {initial_step} to {(initial_step + 1) % 256}, got {patterns.step}"
# Second beat - advance another step
mock_espnow.clear()
mock_espnow.send_message(b"\xdd\xdd\xdd\xdd\xdd\xdd", msg2) # Beat again
run_main_loop_iterations(mock_espnow, patterns, settings, wdt, max_iterations=5)
assert patterns.step == (initial_step + 2) % 256, f"Step should increment to {(initial_step + 2) % 256}, got {patterns.step}"
print(" ✓ Rainbow beat advances one step per beat")
# Test 2: Beat with chase (manual mode) - should advance one step per beat
print(" Test 8.2: Beat with chase (manual mode)")
patterns.step = 0
mock_espnow.clear()
msg3 = {
"v": "1",
"select": {
"beat_device": ["beat_chase"]
}
}
mock_espnow.send_message(b"\xee\xee\xee\xee\xee\xee", msg3)
run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
assert patterns.selected == "beat_chase", "Should select beat_chase"
initial_step = patterns.step
# First beat
mock_espnow.clear()
mock_espnow.send_message(b"\xff\xff\xff\xff\xff\xff", msg3) # Beat
run_main_loop_iterations(mock_espnow, patterns, settings, wdt, max_iterations=5)
# tick() is already called in run_main_loop_iterations
assert patterns.step == initial_step + 1, f"Chase step should increment from {initial_step} to {initial_step + 1}, got {patterns.step}"
# Second beat
mock_espnow.clear()
mock_espnow.send_message(b"\x11\x11\x11\x11\x11\x11", msg3) # Beat again
run_main_loop_iterations(mock_espnow, patterns, settings, wdt, max_iterations=5)
assert patterns.step == initial_step + 2, f"Chase step should increment to {initial_step + 2}, got {patterns.step}"
print(" ✓ Chase beat advances one step per beat")
# Test 3: Beat with pulse (manual mode) - should restart full cycle
print(" Test 8.3: Beat with pulse (manual mode)")
mock_espnow.clear()
msg4 = {
"v": "1",
"select": {
"beat_device": ["beat_pulse"]
}
}
mock_espnow.send_message(b"\x22\x22\x22\x22\x22\x22", msg4)
run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
assert patterns.selected == "beat_pulse", "Should select beat_pulse"
assert patterns.generator is not None, "Generator should be active"
# First beat - should restart generator
initial_generator = patterns.generator
mock_espnow.clear()
mock_espnow.send_message(b"\x33\x33\x33\x33\x33\x33", msg4) # Beat
run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
assert patterns.generator is not None, "Generator should still be active after beat"
assert patterns.generator != initial_generator, "Generator should be restarted (new instance)"
print(" ✓ Pulse beat restarts generator for full cycle")
# Test 4: Multiple beats in sequence
print(" Test 8.4: Multiple beats in sequence")
patterns.step = 0
mock_espnow.clear()
mock_espnow.send_message(b"\x44\x44\x44\x44\x44\x44", msg2) # Select rainbow
run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
# Send 5 beats
for i in range(5):
mock_espnow.clear()
mock_espnow.send_message(b"\x55\x55\x55\x55\x55\x55", msg2) # Beat
run_main_loop_iterations(mock_espnow, patterns, settings, wdt, max_iterations=5)
# tick() is already called in run_main_loop_iterations
wdt.feed()
utime.sleep_ms(50)
assert patterns.step == 5, f"After 5 beats, step should be 5, got {patterns.step}"
print(" ✓ Multiple beats work correctly")
print(" ✓ Beat functionality works correctly")
def test_select_with_step():
"""Test selecting a preset with an explicit step value."""
print("\nTest 9: Select with step value")
settings = Settings()
settings["name"] = "step_device"
patterns = Presets(settings["led_pin"], settings["num_leds"])
mock_espnow = MockESPNow()
wdt = get_wdt()
# Create preset
msg1 = {
"v": "1",
"presets": {
"step_preset": {"pattern": "rainbow", "delay": 100, "n1": 1, "auto": False}
}
}
mock_espnow.send_message(b"\xaa\xaa\xaa\xaa\xaa\xaa", msg1)
run_main_loop_iterations(mock_espnow, patterns, settings, wdt)
# Select with explicit step value
mock_espnow.clear()
msg2 = {
"v": "1",
"select": {
"step_device": ["step_preset", 10]
}
}
mock_espnow.send_message(b"\xbb\xbb\xbb\xbb\xbb\xbb", msg2)
run_main_loop_iterations(mock_espnow, patterns, settings, wdt, max_iterations=2)
# Ensure tick() is called after select() to advance the step
run_tick(patterns)
assert patterns.selected == "step_preset", "Should select step_preset"
# Step is set to 10, then tick() advances it, so it should be 11
assert patterns.step == 11, f"Step should be set to 10 then advanced to 11 by tick(), got {patterns.step}"
print(" ✓ Step value set correctly")
# Select without step (should use default behavior)
mock_espnow.clear()
msg3 = {
"v": "1",
"select": {
"step_device": ["step_preset"]
}
}
mock_espnow.send_message(b"\xcc\xcc\xcc\xcc\xcc\xcc", msg3)
initial_step = patterns.step # Should be 11
run_main_loop_iterations(mock_espnow, patterns, settings, wdt, max_iterations=2)
# Ensure tick() is called after select() to advance the step
run_tick(patterns)
# Since it's the same preset, step should not be reset, but tick() will advance it
# So step should be initial_step + 1 (one tick call)
assert patterns.step == initial_step + 1, f"Step should advance from {initial_step} to {initial_step + 1} (not reset), got {patterns.step}"
print(" ✓ Step preserved when selecting same preset without step (tick advances it)")
# Select different preset with step
patterns.edit("other_preset", {"p": "rainbow", "a": False})
mock_espnow.clear()
msg4 = {
"v": "1",
"select": {
"step_device": ["other_preset", 5]
}
}
mock_espnow.send_message(b"\xdd\xdd\xdd\xdd\xdd\xdd", msg4)
run_main_loop_iterations(mock_espnow, patterns, settings, wdt, max_iterations=2)
# Ensure tick() is called after select() to advance the step
run_tick(patterns)
assert patterns.selected == "other_preset", "Should select other_preset"
# Step is set to 5, then tick() advances it, so it should be 6
assert patterns.step == 6, f"Step should be set to 5 then advanced to 6 by tick(), got {patterns.step}"
print(" ✓ Step set correctly when switching presets")
def test_preset_save_load():
"""Test saving and loading presets to/from JSON."""
print("\nTest 10: Preset save/load")
settings = Settings()
patterns = Presets(settings["led_pin"], settings["num_leds"])
patterns.edit("saved_preset", {
"p": "blink",
"d": 150,
"b": 200,
"c": [(1, 2, 3), (4, 5, 6)],
"a": False,
"n1": 1,
"n2": 2,
"n3": 3,
"n4": 4,
"n5": 5,
"n6": 6,
})
assert patterns.save(), "Save should return True"
reloaded = Presets(settings["led_pin"], settings["num_leds"])
assert reloaded.load(settings), "Load should return True"
preset = reloaded.presets.get("saved_preset")
assert preset is not None, "Preset should be loaded"
assert preset.p == "blink", "Pattern should be blink"
assert preset.d == 150, "Delay should be 150"
assert preset.b == 200, "Brightness should be 200"
assert preset.c == [(1, 2, 3), (4, 5, 6)], "Colors should be restored as tuples"
assert preset.a is False, "Auto should be False"
assert (preset.n1, preset.n2, preset.n3, preset.n4, preset.n5, preset.n6) == (1, 2, 3, 4, 5, 6), "n1-n6 should match"
try:
os.remove("presets.json")
except OSError:
pass
print(" ✓ Preset save/load works correctly")
def main():
"""Run all tests."""
print("=" * 60)
print("ESPNow Receive Functionality Tests")
print("=" * 60)
try:
test_version_check()
test_preset_creation()
test_color_conversion()
test_preset_update()
test_select()
test_full_message()
test_switch_presets()
test_beat_functionality()
test_select_with_step()
test_preset_save_load()
print("\n" + "=" * 60)
print("All tests passed! ✓")
print("=" * 60)
except AssertionError as e:
print("\n✗ Test failed:", e)
raise
except Exception as e:
print("\n✗ Unexpected error:", e)
raise
if __name__ == "__main__":
main()
-239
View File
@@ -1,239 +0,0 @@
#!/usr/bin/env python3
"""mDNS smoke test — runs on the MicroPython device (ESP32).
Loads Wi-Fi credentials from /settings.json via Settings (same as main firmware).
Sets the network hostname before connect so the chip can advertise as <hostname>.local
on builds where mDNS is enabled (see network.hostname() in MicroPython docs).
By default the script stays connected until you stop it (reset or mpremote Ctrl+C) so you
can ping the mDNS name from another machine (e.g. name "a" -> leda.local; hyphens are omitted
in the hostname because ESP32 mDNS often breaks on '-').
After flashing, do a full hardware reset once so the first DHCP sees the new hostname.
Deploy src to the device (including utils.py with mdns_hostname), then from the host:
mpremote connect PORT run tests/test_mdns.py
Copy ``utils.py`` from ``src/`` onto the device if imports fail.
Or with cwd led-driver:
mpremote connect /dev/ttyUSB0 run tests/test_mdns.py
"""
import time
import network
import socket
import utime
from machine import WDT
from settings import Settings
from utils import mdns_hostname
CONNECT_TIMEOUT_S = 45
# ESP32 MicroPython WDT timeout is capped (typically 10000 ms). Longer blocking work
# (PHY calibration) runs with no WDT; WDT is only used in HOLD_S.
WDT_TIMEOUT_MS = 10000
# socket.getaddrinfo("<self>.local", …) often hangs a long time or indefinitely on ESP32; off by default.
SELF_LOCAL_GETADDRINFO = False
# After checks: 0 = exit immediately; >0 = stay up that many seconds; -1 = until reset/Ctrl+C (for remote ping).
HOLD_S = -1
# Set False to silence [mdns-test] timing lines (phase labels + elapsed ms since test start).
DEBUG = True
def _dbg(t0, msg):
if not DEBUG:
return
ms = utime.ticks_diff(utime.ticks_ms(), t0)
print("[mdns-test +%dms] %s" % (ms, msg))
def _set_hostname(h, sta):
"""Apply hostname on this STA object before active(True) / connect (DHCP + mDNS)."""
try:
network.hostname(h)
how = "network.hostname"
except (AttributeError, ValueError, OSError) as e:
how = None
last = e
try:
sta.config(hostname=h)
how = how or "WLAN.config(hostname=)"
except (AttributeError, ValueError, OSError) as e:
if how is None:
last = e
if how:
return how
print("Warning: could not set hostname (%s); mDNS name may be default." % last)
return None
def _sta_ip(sta):
try:
pair = sta.ipconfig("addr4")
if isinstance(pair, tuple) and pair:
return pair[0].split("/")[0] if isinstance(pair[0], str) else str(pair[0])
except (AttributeError, OSError, TypeError, ValueError):
pass
return sta.ifconfig()[0]
def _wait_wifi(sta, timeout_s, wdt, t0):
"""Wait for connection. If wdt is set, feed each iteration (keep gap < WDT_TIMEOUT_MS)."""
deadline = utime.ticks_add(utime.ticks_ms(), int(timeout_s * 1000))
n = 0
while not sta.isconnected():
if utime.ticks_diff(deadline, utime.ticks_ms()) <= 0:
_dbg(t0, "WiFi wait TIMEOUT after %d iterations, status=%s" % (n, sta.status()))
return False
st = sta.status()
n += 1
if DEBUG:
_dbg(t0, "WiFi wait iter #%d status=%s" % (n, st))
else:
print("WiFi status:", st, "(waiting)")
if wdt is not None:
wdt.feed()
time.sleep(1)
if wdt is not None:
wdt.feed()
_dbg(t0, "WiFi connected after %d wait iterations" % n)
return True
def _try_resolve_local(hostname, t0):
"""Best-effort: resolve our own *.local via getaddrinfo (often blocks a very long time on ESP32)."""
fqdn = hostname + ".local"
_dbg(t0, "getaddrinfo(%r) starting (may block a long time)" % fqdn)
t_gai = utime.ticks_ms()
try:
ai = socket.getaddrinfo(fqdn, 80)
dt = utime.ticks_diff(utime.ticks_ms(), t_gai)
print("getaddrinfo(%r) -> %s" % (fqdn, ai))
_dbg(t0, "getaddrinfo OK (call took %dms)" % dt)
return True
except OSError as e:
dt = utime.ticks_diff(utime.ticks_ms(), t_gai)
print("getaddrinfo(%r) failed: %s" % (fqdn, e))
_dbg(t0, "getaddrinfo OSError after %dms" % dt)
return False
def main():
t0 = utime.ticks_ms()
_dbg(t0, "start")
settings = Settings()
_dbg(t0, "Settings() loaded")
ssid = settings.get("ssid") or ""
password = settings.get("password") or ""
if not ssid:
print("mDNS test skipped: ssid empty in settings.json (configure Wi-Fi to run this test).")
raise SystemExit(0)
hostname = mdns_hostname(settings)
_dbg(t0, "mdns_hostname -> %r" % hostname)
sta = network.WLAN(network.STA_IF)
how = _set_hostname(hostname, sta)
if how:
print("Hostname set via %s: %r" % (how, hostname))
_dbg(t0, "set_hostname done (%s)" % (how or "failed"))
_dbg(t0, "before sta.active(True) (often slow: RF calibration)")
print("WiFi active(True) (can take a while for calibration)...")
sta.active(True)
_dbg(t0, "after sta.active(True)")
try:
sta.config(pm=network.WLAN.PM_NONE)
_dbg(t0, "sta.config(pm=PM_NONE) OK")
except (AttributeError, ValueError, TypeError) as e:
_dbg(t0, "sta.config(pm=PM_NONE) skipped: %s" % e)
print("Connecting to SSID %r ..." % ssid)
_dbg(t0, "before sta.connect()")
sta.connect(ssid, password)
_dbg(t0, "after sta.connect() (returned; association may still be in progress)")
# No WDT during calibration/wait/getaddrinfo — they can block longer than WDT_TIMEOUT_MS.
if not _wait_wifi(sta, CONNECT_TIMEOUT_S, None, t0):
print("Timeout: not connected. status=", sta.status())
raise SystemExit(1)
ip = _sta_ip(sta)
print("WiFi OK, IP:", ip)
try:
stack_host = network.hostname()
except (AttributeError, ValueError, TypeError, OSError):
stack_host = None
if stack_host:
print(
"mDNS: use what the stack reports — ping %s.local (avahi-resolve -n %s.local)"
% (stack_host, stack_host)
)
if str(stack_host) != str(hostname):
print(
"(We asked for %r but stack reports %r — ping the stack name; cold boot may help.)"
% (hostname, stack_host)
)
else:
print("From another machine: ping %s.local" % hostname)
print("(or: avahi-resolve -n %s.local)" % hostname)
if SELF_LOCAL_GETADDRINFO:
_try_resolve_local(hostname, t0)
else:
_dbg(
t0,
"skip getaddrinfo(%s.local): SELF_LOCAL_GETADDRINFO=False (on-device self-.local lookup often hangs)"
% hostname,
)
print(
"Skipped on-device getaddrinfo(*.local); verify mDNS from a PC (ping above). "
"Set SELF_LOCAL_GETADDRINFO = True to attempt (may hang)."
)
if HOLD_S != 0:
forever = HOLD_S < 0
_dbg(
t0,
"starting WDT(%dms) + hold %s"
% (WDT_TIMEOUT_MS, "forever" if forever else ("%ds" % HOLD_S)),
)
wdt = WDT(timeout=WDT_TIMEOUT_MS)
wdt.feed()
if forever:
ping_target = stack_host or hostname
print(
"Staying online until you stop (reset device or mpremote Ctrl+C). "
"From another host: ping %s.local" % ping_target
)
else:
print("Keeping connection up for %d s (Ctrl+C or reset to stop) ..." % HOLD_S)
end = None if forever else utime.ticks_add(utime.ticks_ms(), HOLD_S * 1000)
hold_i = 0
while True:
wdt.feed()
time.sleep(2)
hold_i += 1
if not sta.isconnected():
print("lost WiFi connection")
break
if forever:
if DEBUG and hold_i % 15 == 0:
_dbg(t0, "hold alive #%d IP %s" % (hold_i, _sta_ip(sta)))
else:
_dbg(t0, "hold tick #%d" % hold_i)
print("still connected, IP", _sta_ip(sta))
if utime.ticks_diff(end, utime.ticks_ms()) <= 0:
break
_dbg(t0, "hold loop finished")
_dbg(t0, "Done.")
print("Done.")
if __name__ == "__main__":
main()
-102
View File
@@ -1,102 +0,0 @@
#!/usr/bin/env python3
"""Wi-Fi connection smoke test for MicroPython on ESP32.
Runs on-device via mpremote and uses /settings.json credentials.
Usage:
mpremote connect /dev/ttyACM0 run tests/test_wifi.py
"""
import time
import utime
import network
from machine import WDT
from settings import Settings
CONNECT_TIMEOUT_S = 30
RETRY_DELAY_S = 2
WDT_TIMEOUT_MS = 10000
def _wifi_status_label(code):
names = {
getattr(network, "STAT_IDLE", 0): "idle",
getattr(network, "STAT_CONNECTING", 1): "connecting",
getattr(network, "STAT_WRONG_PASSWORD", -3): "wrong_password",
getattr(network, "STAT_NO_AP_FOUND", -2): "no_ap_found",
getattr(network, "STAT_CONNECT_FAIL", -1): "connect_fail",
getattr(network, "STAT_GOT_IP", 3): "got_ip",
}
return names.get(code, str(code))
def connect_wifi_with_wdt(sta, ssid, password, wdt):
attempt = 0
while not sta.isconnected():
attempt += 1
print("[wifi-test] attempt", attempt, "ssid=", repr(ssid))
try:
sta.disconnect()
except Exception:
pass
sta.connect(ssid, password)
start = utime.time()
last_status = None
while not sta.isconnected():
status = sta.status()
if status != last_status:
print("[wifi-test] status:", status, _wifi_status_label(status))
last_status = status
if status in (
getattr(network, "STAT_WRONG_PASSWORD", -3),
getattr(network, "STAT_NO_AP_FOUND", -2),
getattr(network, "STAT_CONNECT_FAIL", -1),
):
break
if utime.time() - start >= CONNECT_TIMEOUT_S:
print("[wifi-test] timeout after", CONNECT_TIMEOUT_S, "seconds")
break
time.sleep(1)
wdt.feed()
if sta.isconnected():
return True
print("[wifi-test] retry in", RETRY_DELAY_S, "seconds")
for _ in range(RETRY_DELAY_S):
time.sleep(1)
wdt.feed()
return True
def main():
settings = Settings()
ssid = settings.get("ssid") or ""
password = settings.get("password") or ""
if not ssid:
print("[wifi-test] skipped: settings.ssid is empty")
raise SystemExit(0)
wdt = WDT(timeout=WDT_TIMEOUT_MS)
wdt.feed()
sta = network.WLAN(network.STA_IF)
sta.active(True)
try:
sta.config(pm=network.WLAN.PM_NONE)
except (AttributeError, ValueError, TypeError):
pass
ok = connect_wifi_with_wdt(sta, ssid, password, wdt)
if not ok or not sta.isconnected():
print("[wifi-test] FAILED: not connected")
raise SystemExit(1)
print("[wifi-test] OK:", sta.ifconfig())
if __name__ == "__main__":
main()
-71
View File
@@ -1,71 +0,0 @@
#!/usr/bin/env python3
"""UDP discovery test — runs on MicroPython (ESP32).
Brings up Wi-Fi from settings (test harness only), then **`hello.discover_controller_udp(device_name, wdt)`**.
`hello` does not use Settings or connect Wi‑Fi.
In firmware, **`main.py`** discovers the controller IP in RAM for HTTP; it is not written to settings.
Deploy `src` (including `hello.py`), then from host with cwd `led-driver`:
mpremote connect PORT run tests/udp_client.py
"""
import time
import network
import utime
from machine import WDT
from hello import discover_controller_udp
from settings import Settings
CONNECT_WAIT_S = 45
WDT_MS = 10000
def _wait_wifi(sta, timeout_s, wdt):
deadline = utime.ticks_add(utime.ticks_ms(), int(timeout_s * 1000))
while not sta.isconnected():
wdt.feed()
if utime.ticks_diff(deadline, utime.ticks_ms()) <= 0:
return False
print("WiFi status:", sta.status())
wdt.feed()
time.sleep(1)
wdt.feed()
return True
def main():
settings = Settings()
ssid = settings.get("ssid") or ""
password = settings.get("password") or ""
if not ssid:
print("udp_client: set ssid/password in settings.json (test harness Wi-Fi).")
raise SystemExit(1)
sta = network.WLAN(network.STA_IF)
sta.active(True)
try:
sta.config(pm=network.WLAN.PM_NONE)
except (AttributeError, ValueError, TypeError):
pass
wdt = WDT(timeout=WDT_MS)
wdt.feed()
print("udp_client: connecting to", repr(ssid))
sta.connect(ssid, password)
wdt.feed()
if not _wait_wifi(sta, CONNECT_WAIT_S, wdt):
print("WiFi timeout, status=", sta.status())
raise SystemExit(1)
ip = discover_controller_udp(settings.get("name", ""), wdt=wdt)
if not ip:
raise SystemExit(1)
if __name__ == "__main__":
main()
+282
View File
@@ -0,0 +1,282 @@
#!/usr/bin/env python3
"""
Test the LED driver's DDP receiver (UDP port 4048).
Sends frames of RGB pixels the way a DDP controller does: a version 1 header, the pixel data split
across two packets, and the PUSH flag on the last packet of a frame. Then checks through the driver's
HTTP API that the pixels were shown, runs a few test animations, and that the pattern comes back once
the pixels stop. Every device is tested at the same time, one thread each.
python3 tools/ddp_test.py # finds every device on this machine's subnet (/24)
python3 tools/ddp_test.py --subnet=192.168.4 # or pick the subnet
python3 tools/ddp_test.py led1.local led2.local # or name hosts explicitly
python3 tools/ddp_test.py led1.local --serial=/dev/ttyACM0 # also check the serial log (one host only)
"""
import colorsys
import json
import math
import re
import socket
import struct
import sys
import threading
import time
import urllib.request
from concurrent.futures import ThreadPoolExecutor
PORT = 4048
LEDS = 119
PUSH = 0x01
VER1 = 0x40
RGB = 0x01
ANIM_FRAMES = 40 # about 1 s at 40 fps
def packet(seq, offset, data, push):
flags = VER1 | (PUSH if push else 0)
header = struct.pack(">BBBBIH", flags, seq & 0x0F, RGB, 1, offset, len(data))
return header + data
def send_frame(sock, host, pixels, seq):
"""Send pixels (a list of (r, g, b)) as two packets, PUSH on the second."""
raw = bytes(c for px in pixels for c in px)
split = (len(pixels) // 2) * 3
sock.sendto(packet(seq, 0, raw[:split], False), (host, PORT))
sock.sendto(packet(seq, split, raw[split:], True), (host, PORT))
def frame_sum(pixels):
"""The driver's checksum of a frame: the sum of its bytes, as an unsigned 32-bit value."""
return sum(c for px in pixels for c in px) & 0xFFFFFFFF
def read_serial(port, seconds, lines):
"""Collect the driver's log lines from the USB serial port for a few seconds."""
import serial
ser = serial.Serial(port, 115200, timeout=0.2)
end = time.time() + seconds
buf = b""
while time.time() < end:
buf += ser.read(4096)
ser.close()
lines.extend(buf.decode("utf-8", "replace").splitlines())
def get(host, path):
with urllib.request.urlopen(f"http://{host}{path}", timeout=5) as r:
return json.loads(r.read().decode())
def local_prefix():
"""The first three octets of this machine's IPv4 address (assumes a /24 subnet)."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
finally:
s.close()
return ip.rsplit(".", 1)[0]
def find_devices(prefix):
"""Every host on the subnet that answers the driver's /api/ddp endpoint."""
def probe(ip):
try:
with urllib.request.urlopen(f"http://{ip}/api/ddp", timeout=1) as r:
json.loads(r.read().decode())
return ip
except Exception:
return None
ips = [f"{prefix}.{i}" for i in range(1, 255)]
with ThreadPoolExecutor(64) as pool:
return [ip for ip in pool.map(probe, ips) if ip]
# Test animations: each maps (LED index, frame number) to an RGB colour
def anim_chase(i, k):
return (255, 160, 0) if (i - 2 * k) % LEDS < 6 else (0, 0, 0)
def anim_rainbow(i, k):
r, g, b = colorsys.hsv_to_rgb(((i * 3 + k * 5) % 256) / 256, 1, 1)
return (int(r * 255), int(g * 255), int(b * 255))
def anim_breathe(i, k):
v = int(127.5 * (1 - math.cos(k / 6)))
return (v, v, v)
ANIMATIONS = {"chase": anim_chase, "rainbow": anim_rainbow, "breathe": anim_breathe}
def output_scale(host):
"""The factor the driver applies to every pixel before it is shown: global x master x max brightness,
with the same integer steps as the firmware (patterns.cpp)."""
st = get(host, "/api/status")
hw = get(host, "/api/hardware")
return st["global_brightness"] * st["master_brightness"] // 255 * hw["max_brightness"] // 255
def expected(pixels, scale):
"""What the driver shows for a pixel: each channel scaled by the output factor."""
return [[c * scale // 255 for c in px] for px in pixels]
def mismatch_detail(bad):
return "" if not bad else f"first mismatch LED {bad[0][0]}: got {bad[0][1]} want {bad[0][2]}"
def verify_frame(host, sock, pixels, scale):
"""Read every LED back while keeping the frame on the strip (the readback is slower than the DDP
timeout). Returns the LEDs that do not match what the driver should show."""
want_all = expected(pixels, scale)
stop = threading.Event()
def keep_sending():
seq = 100
while not stop.is_set():
send_frame(sock, host, pixels, seq)
seq += 1
time.sleep(0.025)
sender = threading.Thread(target=keep_sending, daemon=True)
sender.start()
bad = []
for i in range(LEDS):
got = get(host, f"/api/ddp?led={i}")["rgb"]
want = want_all[i]
if got != want:
bad.append((i, got, want))
stop.set()
sender.join()
return bad
def run(host, serial_port):
"""Run every check against one device. Returns (failures, output lines)."""
out = []
failures = 0
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def log(line=""):
out.append(line)
def check(name, ok, detail=""):
nonlocal failures
log(("PASS " if ok else "FAIL ") + name + (f" {detail}" if detail else ""))
if not ok:
failures += 1
before = get(host, "/api/ddp")
log(f"before: active={before['active']} packets={before['packets']}")
scale = output_scale(host)
log(f"output scale: {scale}/255")
# A frame: LED i is a colour that depends on i, so every LED is distinguishable
def frame(k):
return [((i * 7 + k) % 256, (i * 13) % 256, (255 - i * 3) % 256) for i in range(LEDS)]
serial_lines = []
reader = None
if serial_port:
reader = threading.Thread(target=read_serial, args=(serial_port, 3.0, serial_lines), daemon=True)
reader.start()
sent_sums = {}
last = None
for k in range(60): # about 1.5 s at 40 fps
last = frame(k)
sent_sums[frame_sum(last)] = k
send_frame(sock, host, last, k)
time.sleep(0.025)
time.sleep(0.2)
mid = get(host, "/api/ddp")
check("receiving while sending", mid["active"], f"packets={mid['packets']}")
check("packets counted", mid["packets"] - before["packets"] >= 120,
f"+{mid['packets'] - before['packets']}")
bad = verify_frame(host, sock, last, scale)
check(f"all {LEDS} LEDs show the frame", not bad, mismatch_detail(bad))
shown = last
if reader is not None:
reader.join()
pat = re.compile(r"DDP frames=\d+ packets=\d+ sum=(\d+) led0=(\d+),(\d+),(\d+) led_last=(\d+),(\d+),(\d+)")
summaries = [m for m in (pat.search(line) for line in serial_lines) if m]
check("serial log has DDP summaries", len(summaries) > 0, f"{len(summaries)} lines")
matched = [m for m in summaries if int(m.group(1)) in sent_sums]
check("logged checksums are of sent frames", len(matched) == len(summaries),
f"{len(matched)}/{len(summaries)} match")
for m in summaries[-1:]:
k = sent_sums.get(int(m.group(1)))
if k is not None:
sent = frame(k)
check("serial led0 and last LED match that frame",
[int(m.group(i)) for i in (2, 3, 4)] == list(sent[0]) and
[int(m.group(i)) for i in (5, 6, 7)] == list(sent[-1]),
f"led0 {m.group(2, 3, 4)} led_last {m.group(5, 6, 7)}")
# Test animations: send each one, then check the last frame is shown
for name, fn in ANIMATIONS.items():
pixels = None
for k in range(ANIM_FRAMES):
pixels = [fn(i, k) for i in range(LEDS)]
send_frame(sock, host, pixels, k)
time.sleep(0.025)
time.sleep(0.2)
bad = verify_frame(host, sock, pixels, scale)
check(f"animation {name} shows its last frame", not bad, mismatch_detail(bad))
shown = pixels
# Pixels past the strip end are ignored and don't break the rest
sock.sendto(packet(0, LEDS * 3 + 30, b"\xff" * 30, True), (host, PORT))
time.sleep(0.1)
check("out-of-range packet ignored", get(host, "/api/ddp?led=0")["rgb"] == expected([shown[0]], scale)[0])
# Stop sending: the pattern should come back after the timeout
time.sleep(3.0)
after = get(host, "/api/ddp")
check("inactive after pixels stop", not after["active"])
now_led0 = get(host, "/api/ddp?led=0")["rgb"]
check("pattern is shown again", now_led0 != expected([shown[0]], scale)[0], f"LED 0 now {now_led0}")
return failures, out
def main():
args = [a for a in sys.argv[1:] if not a.startswith("--")]
serial_port = next((a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--serial=")), None)
subnet = next((a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--subnet=")), None)
if args:
hosts = args
else:
prefix = subnet or local_prefix()
hosts = find_devices(prefix)
print(f"found {len(hosts)} device(s) on {prefix}.0/24: {', '.join(hosts) or 'none'}\n")
if not hosts:
sys.exit(1)
if serial_port and len(hosts) > 1:
print("note: --serial is only used when testing one device\n")
serial_port = None
# All devices at the same time, one thread each
with ThreadPoolExecutor(max_workers=len(hosts)) as pool:
results = list(pool.map(lambda h: run(h, serial_port), hosts))
failures = 0
for host, (device_failures, out) in zip(hosts, results):
print(f"== {host}")
print("\n".join(out))
print()
failures += device_failures
print("RESULT:", "all passed" if not failures else f"{failures} failed")
sys.exit(1 if failures else 0)
if __name__ == "__main__":
main()
+91
View File
@@ -0,0 +1,91 @@
"""
Over-the-air firmware update for the LED driver (ESP32-C3, Wi-Fi, plain HTTP).
The driver takes the raw app image on POST /ota, writes it to the idle slot and reboots.
"""
import http.client
import json
import os
import time
from typing import Optional
IMAGE_NAME = "led_driver.bin"
# Searched in order when no image is given (relative to where the tool is run, since the
# PyInstaller binary has no useful location of its own)
DEFAULT_IMAGES = [
os.path.join("build", IMAGE_NAME),
]
def _default_image() -> Optional[str]:
return next((p for p in DEFAULT_IMAGES if os.path.isfile(p)), None)
def _info(host: str, port: int) -> Optional[dict]:
try:
conn = http.client.HTTPConnection(host, port, timeout=5)
conn.request("GET", "/ota")
r = conn.getresponse()
return json.loads(r.read().decode()) if r.status == 200 else None
except (OSError, ValueError):
return None
def ota_update(host: str, image: Optional[str] = None, port: int = 80) -> None:
"""Upload image to host and wait for it to come back. Raises RuntimeError on failure."""
image = image or _default_image()
if not image:
raise RuntimeError(f"no image given and {IMAGE_NAME} not found under ./build")
if not os.path.isfile(image):
raise RuntimeError(f"image not found: {image}")
size = os.path.getsize(image)
before = _info(host, port)
if before is None:
raise RuntimeError(f"no OTA endpoint at http://{host}:{port}/ota (is this the LED driver?)")
print(f"Running {before['partition']} (built {before['built']})")
print(f"Uploading {image} ({size} bytes)...")
conn = http.client.HTTPConnection(host, port, timeout=60)
with open(image, "rb") as f:
conn.request("POST", "/ota", body=f, headers={
"Content-Length": str(size),
"Content-Type": "application/octet-stream",
})
r = conn.getresponse()
body = r.read().decode()
if r.status != 200:
try:
body = json.loads(body).get("error", body)
except ValueError:
pass
raise RuntimeError(f"update rejected ({r.status}): {body}")
print("Written, waiting for reboot...")
time.sleep(3)
for _ in range(30):
after = _info(host, port)
if after:
print(f"Back up on {after['partition']} (built {after['built']})")
if after["partition"] == before["partition"]:
raise RuntimeError("driver came back on the same slot: new image was rejected or rolled back")
return
time.sleep(1)
raise RuntimeError("driver did not come back within 30 s")
if __name__ == "__main__":
import argparse
import sys
ap = argparse.ArgumentParser(description="Update the LED driver firmware over Wi-Fi.")
ap.add_argument("host", help="address or name of the driver, e.g. 192.168.4.1 or led.local")
ap.add_argument("image", nargs="?", help=f"firmware image (default: build/{IMAGE_NAME})")
ap.add_argument("--port", type=int, default=80)
args = ap.parse_args()
try:
ota_update(args.host, args.image, args.port)
except RuntimeError as e:
print(f"error: {e}", file=sys.stderr)
sys.exit(1)
+1113
View File
File diff suppressed because it is too large. Load diff
+212
View File
@@ -0,0 +1,212 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>LED strip</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<header>
<h1>LED strip</h1>
<button id="menuToggle" type="button" class="menu-toggle" aria-controls="menu" aria-expanded="false" aria-label="Menu">
<span class="menu-bars" aria-hidden="true"></span>
</button>
<nav id="menu">
<button class="tab active" data-tab="presets">Presets</button>
<button class="tab" data-tab="settings">Settings</button>
<button id="modeToggle" type="button" class="mode-toggle" aria-pressed="false">Edit mode</button>
<button id="newPreset" type="button" class="tab-action" hidden>+ New preset</button>
<div class="header-device">
<select id="deviceSelect" aria-label="Device"></select>
</div>
<div class="header-bright">
<input type="range" id="globalBright" min="0" max="255" step="1" aria-label="Brightness">
<output id="globalOut"></output>
</div>
</nav>
</header>
<main>
<!-- Front: the preset buttons, each with an Edit button -->
<section id="presets">
<div id="presetList" class="preset-grid"></div>
<p id="status" class="muted" role="status"></p>
</section>
<section id="settings" hidden>
<h2>Devices</h2>
<p class="muted">Control other LED drivers from this page. Add each one by its address, such as 10.1.1.50 or led-desk.local. The list is kept in this browser.</p>
<ul id="devList" class="list"></ul>
<form id="devAdd">
<label>Address
<input id="devHost" maxlength="80" autocomplete="off" placeholder="10.1.1.50">
</label>
<button type="submit">Add device</button>
</form>
<p id="devMsg" class="muted" role="status"></p>
<h2>Presets</h2>
<p class="muted">Adds the default presets (Rainbow, Chase, Aurora, Candle, Twinkle, Flame, Sweep, Off) that are not in the list yet. Your own presets are kept.</p>
<button id="addDefaults" type="button">Add default presets</button>
<p id="defaultsMsg" class="muted" role="status"></p>
<h2>Sync presets</h2>
<p class="muted">Copy this device's presets, their order and its startup preset to every other device. A preset with the same name is replaced. Presets that only the other devices have are kept.</p>
<button id="syncPresets" type="button">Sync presets to other devices</button>
<p id="syncMsg" class="muted" role="status"></p>
<h2>LED strip</h2>
<form id="hwForm">
<label>Number of LEDs
<input type="number" id="hwLeds" min="1" max="512" step="1" required>
</label>
<label>Data pin (GPIO)
<input type="number" id="hwPin" min="0" max="21" step="1" required>
</label>
<p class="muted">0-10 or 20-21. Pins 11-19 are used by the flash and USB.</p>
<label>Colour order
<select id="hwOrder">
<option value="rgb">RGB</option>
<option value="rbg">RBG</option>
<option value="grb">GRB (WS2812 default)</option>
<option value="gbr">GBR</option>
<option value="brg">BRG</option>
<option value="bgr">BGR</option>
</select>
</label>
<label>Max brightness <output id="hwMaxOut"></output>
<input type="range" id="hwMax" min="0" max="255" step="1">
</label>
<button type="submit">Save strip settings</button>
</form>
<p id="hwMsg" class="muted" role="status"></p>
<h2>Firmware</h2>
<p>Running <span id="fwInfo">…</span></p>
<form id="fwForm">
<label>Firmware file (.bin)
<input type="file" id="fwFile" accept=".bin,application/octet-stream">
</label>
<button type="submit" id="fwUpload">Update firmware</button>
</form>
<div class="row">
<button id="fwReboot" type="button" class="btn-secondary">Reboot</button>
</div>
<p id="fwMsg" class="muted" role="status"></p>
<h2>Access point</h2>
<p>Network <strong id="apName">…</strong> (open). Address <strong>192.168.4.1</strong>.</p>
<h2>Wi-Fi client</h2>
<p>Status: <span id="staState">…</span></p>
<button id="scan" type="button">Scan for networks</button>
<ul id="networks" class="list"></ul>
<form id="wifiForm">
<label>Network name (SSID)
<input id="ssid" required maxlength="32" autocomplete="off">
</label>
<label>Password <span class="muted">(blank for open networks)</span>
<input id="pass" type="password" maxlength="64" autocomplete="off">
</label>
<button type="submit">Save and connect</button>
</form>
<p id="wifiMsg" class="muted" role="status"></p>
<h2>Device name and address</h2>
<form id="netForm">
<label>Name (<span id="mdnsName">led</span>.local)
<input id="hostname" required maxlength="63" pattern="[-A-Za-z0-9]+" autocomplete="off">
</label>
<label>Client address
<select id="ipMode">
<option value="dhcp">Automatic (DHCP)</option>
<option value="static">Static</option>
</select>
</label>
<div id="staticFields" hidden>
<label>IP address
<input id="sIp" inputmode="decimal" placeholder="192.168.1.50" autocomplete="off">
</label>
<label>Netmask
<input id="sMask" inputmode="decimal" placeholder="255.255.255.0" autocomplete="off">
</label>
<label>Gateway
<input id="sGw" inputmode="decimal" placeholder="192.168.1.1" autocomplete="off">
</label>
<label>DNS <span class="muted">(optional, blank uses the gateway)</span>
<input id="sDns" inputmode="decimal" autocomplete="off">
</label>
</div>
<button type="submit">Save network settings</button>
</form>
<p id="netMsg" class="muted" role="status"></p>
<p class="muted">The access point always stays at 192.168.4.1, so you can get back in if a setting breaks the client connection.</p>
</section>
</main>
<!-- Preset editor: a child window opened from Edit or New preset -->
<div id="editor-modal" class="modal" hidden>
<div class="modal-content" role="dialog" aria-modal="true" aria-labelledby="editor-title">
<div class="modal-head">
<h2 id="editor-title">Preset</h2>
<button id="editorClose" type="button" class="modal-close" aria-label="Close">×</button>
</div>
<label>Preset name
<input id="presetName" maxlength="31" autocomplete="off" placeholder="e.g. warm chase">
</label>
<label>Pattern
<select id="pattern"></select>
</label>
<div class="field">
<span class="label">Colours</span>
<div id="colours" class="swatches"></div>
<div class="row">
<button id="addColour" type="button">Add colour</button>
<button id="removeColour" type="button">Remove colour</button>
</div>
</div>
<label>Background
<input type="color" id="bg" value="#000000">
</label>
<label>Delay <output id="delayOut"></output>
<input type="range" id="delay" min="10" max="3000" step="10">
</label>
<label>Brightness <output id="brightOut"></output>
<input type="range" id="bright" min="0" max="255" step="1">
</label>
<label>Fade in <output id="fadeOut"></output>
<input type="range" id="fade" min="0" max="5000" step="50">
</label>
<div class="checks">
<label class="check"><input type="checkbox" id="auto"> Keep running (auto)</label>
<label class="check"><input type="checkbox" id="reverse"> Reverse direction</label>
<label class="check"><input type="checkbox" id="beatTime"> Beat timing (quarter beats)</label>
</div>
<label id="styleRow" hidden>Style
<select id="style"></select>
</label>
<div id="numbers" class="numbers"></div>
<p id="presetMsg" class="muted" role="status"></p>
<div class="modal-actions">
<button id="apply" type="button" class="btn-secondary">Apply to strip</button>
<button id="presetStartup" type="button" class="btn-secondary" disabled>Use at startup</button>
<button id="presetDelete" type="button" class="btn-danger" disabled>Delete</button>
<button id="presetSave" type="button">Save preset</button>
</div>
</div>
</div>
<script src="/app.js"></script>
</body>
</html>
+604
View File
@@ -0,0 +1,604 @@
/* Styled to match led-controller: dark grey panels, a darker header, grey buttons, purple selection */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
background-color: #2e2e2e;
color: white;
min-height: 100vh;
}
[hidden] { display: none !important; }
/* Header: title, tabs */
header {
background-color: #1a1a1a;
padding: 0.75rem 1rem;
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
border-bottom: 2px solid #4a4a4a;
gap: 0.75rem;
}
header h1 {
font-size: 1.35rem;
font-weight: 600;
}
nav {
display: flex;
gap: 0.5rem;
}
button.tab {
padding: 0.45rem 0.9rem;
border: none;
border-radius: 4px;
background-color: #3a3a3a;
color: white;
font-size: 0.9rem;
font-weight: 500;
cursor: pointer;
}
button.tab:hover { background-color: #4a4a4a; }
button.tab.active {
background-color: #6a5acd;
}
/* Run/Edit mode switch: the label is the mode it switches to */
button.mode-toggle {
padding: 0.45rem 0.9rem;
border: 1px solid #6a5acd;
border-radius: 4px;
background-color: transparent;
color: white;
font-size: 0.9rem;
font-weight: 500;
cursor: pointer;
}
button.mode-toggle:hover { background-color: #3a3a3a; }
body.mode-edit button.mode-toggle {
background-color: #6a5acd;
}
/* Run mode: the Edit button and drag handles are not shown */
body.mode-run button.preset-edit {
display: none;
}
body.mode-run .preset-tile-row {
cursor: default;
}
/* Main panel */
main {
padding: 1rem;
max-width: 760px;
margin: 0 auto;
}
section > * + * { margin-top: 0.85rem; }
h2 {
font-size: 1.1rem;
font-weight: 600;
margin-top: 1.25rem;
}
/* Form controls */
label {
display: flex;
flex-direction: column;
gap: 0.35rem;
font-weight: 500;
}
output {
font-weight: 400;
color: #bdbdbd;
}
select,
input[type="text"],
input:not([type]),
input[type="password"],
input[type="number"] {
font: inherit;
padding: 0.4rem 0.5rem;
background-color: #2e2e2e;
border: 1px solid #4a4a4a;
border-radius: 4px;
color: white;
width: 100%;
}
input[type="color"] {
width: 100%;
height: 2.5rem;
padding: 0.15rem;
background-color: #2e2e2e;
border: 1px solid #4a4a4a;
border-radius: 4px;
}
input[type="range"] {
width: 100%;
accent-color: #6a5acd;
}
input[type="checkbox"] {
accent-color: #6a5acd;
}
button {
font: inherit;
padding: 0.45rem 0.9rem;
border: none;
border-radius: 4px;
background-color: #4a4a4a;
color: white;
font-size: 0.9rem;
font-weight: 500;
cursor: pointer;
transition: background-color 0.2s;
}
button:hover { background-color: #5a5a5a; }
button:disabled {
opacity: 0.45;
cursor: default;
}
button[type="submit"] {
background-color: #6a5acd;
}
button[type="submit"]:hover { background-color: #7b6bdb; }
form {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
form button { align-self: flex-start; }
.row {
display: flex;
gap: 0.75rem;
flex-wrap: wrap;
align-items: flex-end;
}
.row > label { flex: 1 1 140px; }
.field {
display: flex;
flex-direction: column;
gap: 0.35rem;
}
.swatches {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.swatches input[type="color"] { width: 3.5rem; }
.checks {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
label.check {
flex-direction: row;
align-items: center;
gap: 0.5rem;
font-weight: 400;
}
label.check input { width: auto; }
details {
background-color: #3a3a3a;
border-radius: 4px;
padding: 0.6rem 0.8rem;
}
details summary {
cursor: pointer;
font-weight: 500;
}
details > * + * { margin-top: 0.6rem; }
.muted {
color: #bdbdbd;
font-size: 0.9rem;
}
.list {
list-style: none;
}
.list li + li { margin-top: 0.35rem; }
button.net {
width: 100%;
text-align: left;
background-color: #3a3a3a;
}
button.net:hover { background-color: #4a4a4a; }
/* Preset tiles: as led-controller's pattern buttons, filled with the preset colours */
.preset-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(8rem, 1fr));
gap: 0.6rem;
}
button.preset-tile {
height: 5rem;
padding: 0 0.5rem;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 0.12rem;
position: relative;
background-color: #3a3a3a;
border: 3px solid #000;
border-radius: 4px;
color: white;
text-align: center;
text-shadow: 0 0 2px rgba(0, 0, 0, 0.8), 0 1px 2px rgba(0, 0, 0, 0.6);
overflow: hidden;
}
button.preset-tile:hover { filter: brightness(1.12); }
button.preset-tile.active {
border-color: #ffffff;
outline: 3px solid #ffffff;
outline-offset: 2px;
}
.header-device,
.header-bright {
flex-direction: row;
align-items: center;
gap: 0.5rem;
font-weight: 500;
font-size: 0.9rem;
}
.header-bright input[type="range"] { width: 7rem; }
.header-bright output { min-width: 2.5rem; color: #bdbdbd; font-weight: 400; }
button.tab-action {
padding: 0.45rem 0.9rem;
border: none;
border-radius: 4px;
background-color: #6a5acd;
color: white;
font-size: 0.9rem;
font-weight: 500;
cursor: pointer;
}
button.tab-action:hover { background-color: #7b6bdb; }
.preset-tile-name {
font-weight: 600;
font-size: 0.9rem;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.preset-tile-pattern {
font-size: 0.75rem;
opacity: 0.85;
}
.preset-tile-row {
display: flex;
flex-direction: column;
gap: 0.3rem;
}
.preset-tile-row.dragging {
opacity: 0.6;
outline: 2px dashed #bdbdbd;
outline-offset: 2px;
}
.preset-tile-row { touch-action: pan-y; }
button.preset-edit {
padding: 0.2rem 0.5rem;
font-size: 0.8rem;
background-color: #3a3a3a;
}
button.preset-edit:hover { background-color: #4a4a4a; }
/* Child window (the preset editor) */
.modal {
position: fixed;
inset: 0;
background-color: rgba(0, 0, 0, 0.6);
display: flex;
align-items: flex-start;
justify-content: center;
padding: 1rem;
overflow-y: auto;
z-index: 100;
}
.modal-content {
background-color: #2e2e2e;
padding: 1.25rem;
border-radius: 8px;
width: 100%;
max-width: 480px;
display: flex;
flex-direction: column;
gap: 0.85rem;
margin: auto 0;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
}
.modal-head {
display: flex;
justify-content: space-between;
align-items: center;
gap: 0.5rem;
}
.modal-head h2 {
margin: 0;
font-size: 1.2rem;
}
button.modal-close {
background: none;
font-size: 1.5rem;
line-height: 1;
padding: 0 0.4rem;
}
button.modal-close:hover { background: #3a3a3a; }
.modal-actions {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
justify-content: flex-end;
}
button.btn-secondary { background-color: #3a3a3a; }
button.btn-secondary:hover { background-color: #4a4a4a; }
button.btn-danger { background-color: #d32f2f; }
button.btn-danger:hover { background-color: #c62828; }
/* Phones and small tablets */
html {
-webkit-text-size-adjust: 100%;
text-size-adjust: 100%;
}
body {
overflow-x: hidden;
overflow-wrap: anywhere;
}
main {
width: 100%;
padding-left: max(1rem, env(safe-area-inset-left));
padding-right: max(1rem, env(safe-area-inset-right));
padding-bottom: max(1rem, env(safe-area-inset-bottom));
}
/* The menu toggle only shows on phones */
button.menu-toggle {
display: none;
}
@media (max-width: 600px) {
header {
padding: 0.6rem max(0.75rem, env(safe-area-inset-left));
gap: 0.5rem;
}
header h1 {
flex: 1;
font-size: 1.2rem;
}
/* ☰ button: three bars, pushed to the right of the title */
button.menu-toggle {
display: inline-flex;
align-items: center;
justify-content: center;
width: 2.75rem;
height: 2.75rem;
min-height: 2.75rem;
padding: 0;
background-color: #3a3a3a;
}
button.menu-toggle:hover { background-color: #4a4a4a; }
button.menu-toggle[aria-expanded="true"] {
background-color: #6a5acd;
}
.menu-bars {
position: relative;
display: block;
width: 1.25rem;
height: 2px;
background-color: white;
border-radius: 1px;
}
.menu-bars::before,
.menu-bars::after {
content: "";
position: absolute;
left: 0;
width: 100%;
height: 2px;
background-color: white;
border-radius: 1px;
}
.menu-bars::before { top: -6px; }
.menu-bars::after { top: 6px; }
/* The menu is collapsed until the toggle opens it */
nav {
display: none;
width: 100%;
flex-wrap: wrap;
gap: 0.4rem;
}
header.menu-open nav {
display: flex;
}
nav > button.tab,
nav > button.mode-toggle,
nav > button.tab-action {
flex: 1 1 auto;
text-align: center;
}
.header-bright {
width: 100%;
justify-content: space-between;
}
.header-bright input[type="range"] {
flex: 1;
width: auto;
}
/* 16px inputs stop iOS from zooming into the page when focused */
select,
input[type="text"],
input:not([type]),
input[type="password"],
input[type="number"],
input[type="color"],
input[type="file"] {
font-size: 16px;
}
/* Bigger touch targets */
button,
button.tab,
button.tab-action,
button.preset-edit {
min-height: 2.75rem;
padding: 0.5rem 0.9rem;
}
button.preset-edit {
min-height: 2.25rem;
}
input[type="range"] {
height: 1.75rem;
}
.preset-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.5rem;
}
button.preset-tile {
height: 5.5rem;
}
.row > label {
flex: 1 1 100%;
}
.row > button {
flex: 1 1 auto;
}
/* The preset editor fills the screen; its buttons stack */
.modal {
padding: 0;
}
.modal-content {
min-height: 100%;
max-width: none;
margin: 0;
border-radius: 0;
padding: max(1rem, env(safe-area-inset-top)) max(1rem, env(safe-area-inset-right))
max(1.25rem, env(safe-area-inset-bottom)) max(1rem, env(safe-area-inset-left));
overflow-y: auto;
}
.modal-actions {
flex-direction: column-reverse;
justify-content: stretch;
}
.modal-actions > button {
width: 100%;
}
.modal-head h2 {
font-size: 1.1rem;
}
button.modal-close {
min-height: 2.75rem;
min-width: 2.75rem;
font-size: 1.75rem;
}
/* Settings forms: the buttons span the width */
form button {
align-self: stretch;
}
button.net {
min-height: 2.75rem;
}
}
@media (hover: none) {
/* No hover on touch screens: keep the pressed state visible instead */
button.preset-tile:hover {
filter: none;
}
button.preset-tile:active {
filter: brightness(1.15);
}
}