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>
This commit is contained in:
jimmyandClaude Haiku 5.5 committed 2026-11-11 01:54:32 +13:00
1 parent 89f996096c
commit 9a04d28ecf
32 files changed
+6210 -398

No files matched your search

+3 -2
View File
@@ -1,5 +1,6 @@
idf_component_register(SRCS "main.cpp" "ws2812.cpp" "net.cpp" "settings.cpp" "web.cpp" "patterns.cpp"
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 cjson mdns esp_hw_support
esp_timer nvs_flash esp_http_server 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;
}
+10 -1
View File
@@ -4,8 +4,11 @@
#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";
@@ -20,9 +23,15 @@ extern "C" void app_main(void)
}
ESP_ERROR_CHECK(err);
patterns_start();
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));
+66 -4
View File
@@ -17,7 +17,6 @@ static const char *TAG = "net";
#define AP_CHANNEL 1
#define AP_MAX_CLIENTS 4
#define MDNS_HOSTNAME "led"
#define RETRY_MAX_MS 30000
static esp_netif_t *s_ap_netif;
@@ -37,6 +36,35 @@ static void apply_sta_config(const wifi_creds_t *c)
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;
@@ -52,6 +80,13 @@ static void on_wifi_event(void *arg, esp_event_base_t base, int32_t id, void *da
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;
@@ -133,12 +168,14 @@ esp_err_t net_start(void)
ESP_ERROR_CHECK(esp_wifi_start());
ESP_LOGI(TAG, "AP %s started", ssid);
// mDNS: led.local, with an HTTP service on port 80
// 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(MDNS_HOSTNAME));
ESP_ERROR_CHECK(mdns_hostname_set(n.hostname));
ESP_ERROR_CHECK(mdns_instance_name_set("LED controller"));
ESP_ERROR_CHECK(mdns_service_add(NULL, "_http", "_tcp", 80, NULL, 0));
ESP_LOGI(TAG, "mDNS: %s.local", MDNS_HOSTNAME);
ESP_LOGI(TAG, "mDNS: %s.local", n.hostname);
return ESP_OK;
}
@@ -167,6 +204,31 @@ esp_err_t net_sta_connect(const wifi_creds_t *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);
+7 -1
View File
@@ -10,7 +10,7 @@
#include "esp_wifi_types.h"
#include "settings.h"
/** @brief Start Wi-Fi (AP `led-XXXXXX` plus an optional client), and mDNS as led.local. Needs NVS. */
/** @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". */
@@ -22,5 +22,11 @@ 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);
+186
View File
@@ -0,0 +1,186 @@
#include "ota.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");
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");
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");
return httpd_resp_sendstr(req, buf);
}
static esp_err_t reboot_post_handler(httpd_req_t *req)
{
ESP_LOGI(TAG, "reboot requested");
httpd_resp_set_type(req, "application/json");
httpd_resp_sendstr(req, "{\"message\":\"rebooting\"}");
static esp_timer_handle_t t;
const esp_timer_create_args_t args = { .callback = reboot_cb, .name = "reboot" };
if (esp_timer_create(&args, &t) == ESP_OK) {
esp_timer_start_once(t, 500 * 1000);
} else {
esp_restart();
}
return ESP_OK;
}
esp_err_t ota_register(httpd_handle_t server)
{
const httpd_uri_t post = { .uri = "/ota", .method = HTTP_POST, .handler = ota_post_handler };
const httpd_uri_t get = { .uri = "/ota", .method = HTTP_GET, .handler = ota_get_handler };
esp_err_t err = httpd_register_uri_handler(server, &post);
if (err == ESP_OK) {
err = httpd_register_uri_handler(server, &get);
}
const httpd_uri_t reboot = { .uri = "/reboot", .method = HTTP_POST, .handler = reboot_post_handler };
if (err == ESP_OK) {
err = httpd_register_uri_handler(server, &reboot);
}
return err;
}
+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
+398 -122
View File
@@ -1,188 +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 "driver/gpio.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 RMT_LED_STRIP_GPIO_NUM GPIO_NUM_10
#define EXAMPLE_LED_NUMBERS 119
#define FRAME_MS 20
#define FRAME_MS 10
static const char *TAG = "patterns";
static const char *const s_names[PM_COUNT] = {
"solid", "rainbow", "chase", "breathe", "blink", "pulse", "transition", "circle",
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 pattern_params_t s_p = { PM_CHASE, { 255, 0, 0 }, { 0, 0, 0 }, 1000, 16 };
static preset_t s_cur; // the preset requested (under s_lock)
static bool s_reset_pending; // a new pattern was selected (under s_lock)
const char *patterns_mode_name(pattern_mode_t m)
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 (m >= 0 && m < PM_COUNT) ? s_names[m] : "";
return PATTERN_COUNT;
}
pattern_mode_t patterns_mode_from_name(const char *name)
const char *patterns_name(int i)
{
for (int i = 0; i < PM_COUNT; i++) {
if (strcmp(name, s_names[i]) == 0) {
return (pattern_mode_t)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 PM_COUNT;
return -1;
}
void patterns_set(const pattern_params_t &p)
void preset_defaults(preset_t *p, int pattern)
{
pattern_params_t q = p;
if (q.speed_ms < 10) q.speed_ms = 10;
if (q.speed_ms > 10000) q.speed_ms = 10000;
if (q.mode >= PM_COUNT) q.mode = PM_SOLID;
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);
s_p = q;
bool changed = q.pattern != s_cur.pattern;
s_cur = q;
if (changed) {
s_reset_pending = true;
}
xSemaphoreGive(s_lock);
}
pattern_params_t patterns_get(void)
// 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);
pattern_params_t p = s_p;
s_global = level;
xSemaphoreGive(s_lock);
return p;
}
// Linear blend from a (k=0) to b (k=255)
static void lerp(const uint8_t *a, const uint8_t *b, uint32_t k, uint8_t *out)
uint8_t patterns_get_global(void)
{
for (int i = 0; i < 3; i++) {
out[i] = (uint8_t)(a[i] + ((int)b[i] - a[i]) * (int)k / 255);
}
xSemaphoreTake(s_lock, portMAX_DELAY);
uint8_t v = s_global;
xSemaphoreGive(s_lock);
return v;
}
// Draw one frame of the pattern at time t (ms since the start of the pattern)
static void render(const pattern_params_t &p, uint32_t t, WS2812 &s)
void patterns_get(preset_t *out)
{
const size_t n = s.size();
const uint32_t sp = p.speed_ms;
uint8_t col[3];
xSemaphoreTake(s_lock, portMAX_DELAY);
*out = s_cur;
xSemaphoreGive(s_lock);
}
switch (p.mode) {
case PM_SOLID:
s.fill(p.c1[0], p.c1[1], p.c1[2]);
break;
static uint32_t now_ms(void)
{
return (uint32_t)(esp_timer_get_time() / 1000);
}
case PM_RAINBOW: {
uint32_t off = (t / sp) % 360;
for (size_t i = 0; i < n; i++) {
uint32_t r, g, b;
WS2812::hsv2rgb((i * 360 / n + off) % 360, 100, 100, &r, &g, &b);
s.set(i, r, g, b);
}
break;
}
case PM_CHASE: {
// Every third LED lit, moving one step per speed_ms; hue shifts each full cycle
uint32_t step = t / sp;
uint32_t phase = step % 3;
uint32_t off = ((step / 3) * 60) % 360;
s.fill(0, 0, 0);
for (size_t j = phase; j < n; j += 3) {
uint32_t r, g, b;
WS2812::hsv2rgb((j * 360 / n + off) % 360, 100, 100, &r, &g, &b);
s.set(j, r, g, b);
}
break;
}
case PM_BREATHE: {
uint32_t period = sp * 2 < 500 ? 500 : sp * 2;
uint32_t ph = t % period;
uint32_t k = ph * 2 < period ? (ph * 2 * 255) / period : ((period - ph) * 2 * 255) / period;
lerp(p.c2, p.c1, k, col);
s.fill(col[0], col[1], col[2]);
break;
}
case PM_BLINK:
if ((t / sp) % 2 == 0) {
s.fill(p.c1[0], p.c1[1], p.c1[2]);
// 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 {
s.fill(p.c2[0], p.c2[1], p.c2[2]);
k = (int)((el * 256) / s_fade_ms);
}
break;
case PM_PULSE: {
// Attack over the first 10% of the period, then a linear decay back to c2
uint32_t period = sp * 2 < 200 ? 200 : sp * 2;
uint32_t frac = ((t % period) * 1000) / period;
uint32_t k = frac < 100 ? frac * 255 / 100 : (1000 - frac) * 255 / 900;
lerp(p.c2, p.c1, k, col);
s.fill(col[0], col[1], col[2]);
break;
}
case PM_TRANSITION: {
// c1 -> c2 over speed_ms, then back again
uint32_t period = 2 * sp;
uint32_t ph = t % period;
uint32_t k = ph < sp ? ph * 255 / sp : (period - ph) * 255 / sp;
lerp(p.c1, p.c2, k, col);
s.fill(col[0], col[1], col[2]);
break;
}
case PM_CIRCLE: {
// A segment a third of the strip long, moving around the ring
size_t head = (t / sp) % n;
size_t len = n / 3 < 1 ? 1 : n / 3;
for (size_t i = 0; i < n; i++) {
size_t dist = (head + n - i) % n;
if (dist < len) {
s.set(i, p.c1[0], p.c1[1], p.c1[2]);
} else {
s.set(i, p.c2[0], p.c2[1], p.c2[2]);
}
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;
}
break;
s_strip->set(i, c.r, c.g, c.b);
s_shown[i] = c;
}
default:
break;
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;
const uint32_t t0 = (uint32_t)(esp_timer_get_time() / 1000);
s_fx.pr = &s_run;
while (true) {
pattern_params_t p = patterns_get();
uint32_t now = (uint32_t)(esp_timer_get_time() / 1000);
s_strip->setBrightness(p.brightness);
render(p, now - t0, *s_strip);
esp_err_t err = s_strip->write();
if (err != ESP_OK) {
ESP_LOGW(TAG, "LED write failed: %s", esp_err_to_name(err));
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));
}
}
void patterns_start(void)
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();
s_strip = new WS2812(RMT_LED_STRIP_GPIO_NUM, EXAMPLE_LED_NUMBERS);
xTaskCreate(patterns_task, "patterns", 4096, NULL, 5, NULL);
ESP_LOGI(TAG, "Started %d LEDs on GPIO %d", EXAMPLE_LED_NUMBERS, (int)RMT_LED_STRIP_GPIO_NUM);
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);
}
+54 -28
View File
@@ -3,40 +3,66 @@
*/
#pragma once
#include <cstddef>
#include <cstdint>
// Pattern names (also the strings the web UI uses). Order matters: the index is the mode id.
enum pattern_mode_t {
PM_SOLID,
PM_RAINBOW,
PM_CHASE,
PM_BREATHE,
PM_BLINK,
PM_PULSE,
PM_TRANSITION,
PM_CIRCLE,
PM_COUNT,
#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]
};
struct pattern_params_t {
pattern_mode_t mode;
uint8_t c1[3]; // main colour (ignored by rainbow and chase)
uint8_t c2[3]; // background / second colour
uint32_t speed_ms; // one step of the pattern, 10-10000 ms
uint8_t brightness; // 0-255
};
/** @brief Start the LED strip and the pattern task, with the strip settings. */
void patterns_start(const struct hw_cfg_t &hw);
/** @brief Start the LED strip and the pattern task. */
void patterns_start(void);
/** @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 Replace the running pattern. Values are clamped to valid ranges. */
void patterns_set(const pattern_params_t &p);
/** @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 Copy of the running pattern. */
pattern_params_t patterns_get(void);
/** @brief Select a preset: always restarts the pattern, crossfading from the frame on the strip. */
void patterns_select(const preset_t &p);
/** @brief Name of a mode, e.g. "rainbow". */
const char *patterns_mode_name(pattern_mode_t m);
/** @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 Mode for a name, or PM_COUNT if unknown. */
pattern_mode_t patterns_mode_from_name(const char *name);
/** @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);
+105
View File
@@ -1,6 +1,8 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#include <cstring>
#include "nvs.h"
#include "settings.h"
@@ -40,3 +42,106 @@ esp_err_t settings_save_wifi(const wifi_creds_t *c)
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;
}
+31
View File
@@ -3,6 +3,8 @@
*/
#pragma once
#include <stdbool.h>
#include "esp_err.h"
struct wifi_creds_t {
@@ -10,8 +12,37 @@ struct wifi_creds_t {
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);
+449 -58
View File
@@ -1,14 +1,20 @@
/*
* SPDX-License-Identifier: Apache-2.0
*/
#include <cstdlib>
#include <cstring>
#include "cJSON.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"
@@ -24,14 +30,19 @@ extern const char style_css_end[] asm("_binary_style_css_end");
static httpd_handle_t s_server;
#define MAX_BODY 512
#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");
return httpd_resp_send(req, start, end - start);
// 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);
}
static esp_err_t send_json(httpd_req_t *req, cJSON *obj)
@@ -74,26 +85,14 @@ static bool read_body(httpd_req_t *req, char *buf, size_t cap)
return true;
}
static void read_rgb(const cJSON *arr, uint8_t *out)
// 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)
{
if (!cJSON_IsArray(arr) || cJSON_GetArraySize(arr) != 3) {
return;
}
for (int i = 0; i < 3; i++) {
cJSON *v = cJSON_GetArrayItem(arr, i);
if (cJSON_IsNumber(v)) {
int x = v->valueint;
out[i] = (uint8_t)(x < 0 ? 0 : x > 255 ? 255 : x);
}
}
}
static void put_rgb(cJSON *obj, const char *key, const uint8_t *c)
{
cJSON *a = cJSON_AddArrayToObject(obj, key);
for (int i = 0; i < 3; i++) {
cJSON_AddItemToArray(a, cJSON_CreateNumber(c[i]));
char body[MAX_BODY];
if (!read_body(req, body, sizeof(body))) {
return NULL;
}
return cJSON_Parse(body);
}
// GET / , /app.js , /style.css
@@ -112,61 +111,45 @@ 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
// 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)
{
pattern_params_t p = patterns_get();
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));
cJSON *o = cJSON_CreateObject();
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, "mode", patterns_mode_name(p.mode));
cJSON *modes = cJSON_AddArrayToObject(o, "modes");
for (int i = 0; i < PM_COUNT; i++) {
cJSON_AddItemToArray(modes, cJSON_CreateString(patterns_mode_name((pattern_mode_t)i)));
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)));
}
put_rgb(o, "c1", p.c1);
put_rgb(o, "c2", p.c2);
cJSON_AddNumberToObject(o, "speed_ms", p.speed_ms);
cJSON_AddNumberToObject(o, "brightness", p.brightness);
return send_json(req, o);
}
// POST /api/pattern {"mode","c1":[r,g,b],"c2":[r,g,b],"speed_ms","brightness"}
// 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)
{
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);
cJSON *in = read_json(req);
if (!in) {
return send_error(req, "400 Bad Request", "invalid JSON");
}
pattern_params_t p = patterns_get();
cJSON *mode = cJSON_GetObjectItem(in, "mode");
if (cJSON_IsString(mode)) {
pattern_mode_t m = patterns_mode_from_name(mode->valuestring);
if (m == PM_COUNT) {
cJSON_Delete(in);
return send_error(req, "400 Bad Request", "unknown mode");
}
p.mode = m;
}
read_rgb(cJSON_GetObjectItem(in, "c1"), p.c1);
read_rgb(cJSON_GetObjectItem(in, "c2"), p.c2);
cJSON *speed = cJSON_GetObjectItem(in, "speed_ms");
if (cJSON_IsNumber(speed)) p.speed_ms = (uint32_t)speed->valueint;
cJSON *bright = cJSON_GetObjectItem(in, "brightness");
if (cJSON_IsNumber(bright)) {
int b = bright->valueint;
p.brightness = (uint8_t)(b < 0 ? 0 : b > 255 ? 255 : b);
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());
}
@@ -245,6 +228,399 @@ static esp_err_t wifi_scan_get(httpd_req_t *req)
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 };
@@ -254,7 +630,8 @@ static void add_uri(httpd_handle_t srv, const char *uri, httpd_method_t method,
esp_err_t web_start(void)
{
httpd_config_t cfg = HTTPD_DEFAULT_CONFIG();
cfg.max_uri_handlers = 12;
cfg.max_uri_handlers = 30;
cfg.stack_size = 8192;
cfg.lru_purge_enable = true;
cfg.max_open_sockets = 7;
cfg.backlog_conn = 10;
@@ -271,6 +648,20 @@ esp_err_t web_start(void)
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);
ota_register(s_server);
ESP_LOGI(TAG, "Web UI on port 80");
return ESP_OK;
}
+24 -3
View File
@@ -166,9 +166,30 @@ void WS2812::set(size_t index, uint8_t r, uint8_t g, uint8_t b)
return;
}
uint8_t *p = &pixels_[index * 3];
p[0] = g;
p[1] = r;
p[2] = b;
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)
+9 -1
View File
@@ -63,9 +63,17 @@ public:
*/
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_;
std::vector<uint8_t> pixels_; // GRB byte order, 3 bytes per LED, as WS2812 expects
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;