/* * 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 #include #include "driver/gpio.h" #include "esp_heap_caps.h" #include "esp_log.h" #include "esp_timer.h" #include "freertos/FreeRTOS.h" #include "freertos/semphr.h" #include "freertos/task.h" #include "effects.h" #include "patterns.h" #include "settings.h" #include "ws2812.h" #define FRAME_MS 10 static const char *TAG = "patterns"; typedef bool (*fx_fn)(fx_t &, st_t &); struct pattern_def_t { const char *name; fx_fn fn; }; // Same names as the MicroPython led-driver patterns static const pattern_def_t kPatterns[] = { { "off", fx_off }, { "on", fx_on }, { "blink", fx_blink }, { "aurora", fx_aurora }, { "bar_graph", fx_bar_graph }, { "blizzard", fx_blizzard }, { "candle_glow", fx_candle_glow }, { "chase", fx_chase }, { "circle", fx_circle }, { "clock_sweep", fx_clock_sweep }, { "colour_cycle", fx_colour_cycle }, { "field_wave", fx_field_wave }, { "flame", fx_flame }, { "flicker", fx_flicker }, { "gradient_wipe", fx_gradient_wipe }, { "grow", fx_grow }, { "hit", fx_hit }, { "icicles", fx_icicles }, { "keyframes", fx_keyframes }, { "meteor", fx_meteor }, { "orbit", fx_orbit }, { "palette_morph", fx_palette_morph }, { "particles", fx_particles }, { "plasma", fx_plasma }, { "pulse", fx_pulse }, { "radiate", fx_radiate }, { "rain_drops", fx_rain_drops }, { "rime", fx_rime }, { "ripple", fx_ripple }, { "sparkle", fx_sparkle }, { "spin", fx_spin }, { "strobe_burst", fx_strobe_burst }, { "sweep", fx_sweep }, { "transition", fx_transition }, { "twinkle", fx_twinkle }, }; #define PATTERN_COUNT ((int)(sizeof(kPatterns) / sizeof(kPatterns[0]))) static WS2812 *s_strip; static SemaphoreHandle_t s_lock; static preset_t s_cur; // the preset requested (under s_lock) static bool s_reset_pending; // a new pattern was selected (under s_lock) static preset_t s_run; // the preset the task is running static fx_t s_fx; // shadow frame and timing for the running pattern st_t g_st; // state of the running pattern // Crossfade: the last frame shown, and the frame it fades from static rgb *s_shown; // last frame shown (s_cap entries) static rgb *s_from; // frame the crossfade starts from static int s_cap; // LEDs the buffers are sized for static bool s_fading; // DDP: pixels sent by a controller. While they keep arriving they replace the pattern. #define DDP_TIMEOUT_MS 2000 static uint8_t s_ddp[FX_LEDS_MAX * 3]; static uint32_t s_ddp_last_ms; // 0: never static bool s_ddp_was; static uint32_t s_ddp_packets; static uint32_t s_ddp_frames; // frames completed (PUSH seen) static uint32_t s_ddp_sum; // checksum of the last completed frame static uint32_t s_ddp_log_ms; // last serial summary // Frame sync: while syncs keep arriving, a completed DDP frame waits for the next sync before it is shown #define DDP_SYNC_TIMEOUT_MS 2000 static uint8_t s_ddp_show[FX_LEDS_MAX * 3]; // the frame the strip shows static uint8_t s_ddp_held[FX_LEDS_MAX * 3]; // a completed frame waiting for a sync static bool s_ddp_held_ok; static uint32_t s_sync_last_ms; // 0: never static uint32_t s_sync_seq; // seq of the last sync static uint32_t s_sync_count; static uint32_t s_ddp_shown; // frames shown static uint8_t s_max_brightness = 255; static uint8_t s_global = 255; static uint8_t s_master = 255; static uint32_t s_fade_t0; static uint32_t s_fade_ms; int patterns_count(void) { return PATTERN_COUNT; } const char *patterns_name(int i) { return (i >= 0 && i < PATTERN_COUNT) ? kPatterns[i].name : ""; } int patterns_index(const char *name) { for (int i = 0; i < PATTERN_COUNT; i++) { if (strcmp(name, kPatterns[i].name) == 0) { return i; } } return -1; } void preset_defaults(preset_t *p, int pattern) { memset(p, 0, sizeof(*p)); p->pattern = pattern; p->ncol = 0; p->delay = 100; p->brightness = 127; p->autorun = true; p->reverse = false; p->fade = 0; p->beat_time = false; } // Keep a preset within the ranges the patterns expect static void sanitize(preset_t *p) { if (p->pattern < 0 || p->pattern >= PATTERN_COUNT) { p->pattern = 0; } if (p->delay < 10) p->delay = 10; if (p->delay > 10000) p->delay = 10000; if (p->ncol < 0) p->ncol = 0; if (p->ncol > PATTERN_MAX_COLOURS) p->ncol = PATTERN_MAX_COLOURS; if (p->fade > 10000) p->fade = 10000; for (int i = 1; i <= 6; i++) { if (p->n[i] < 0) p->n[i] = 0; if (p->n[i] > 100000) p->n[i] = 100000; } } // Live update: a change of pattern restarts it (with a crossfade if the preset asks); other changes // take effect straight away, keeping the pattern's place void patterns_set(const preset_t &p) { preset_t q = p; sanitize(&q); xSemaphoreTake(s_lock, portMAX_DELAY); bool changed = q.pattern != s_cur.pattern; s_cur = q; if (changed) { s_reset_pending = true; } xSemaphoreGive(s_lock); } // Select a preset: always restarts the pattern, crossfading in from the frame on the strip void patterns_select(const preset_t &p) { preset_t q = p; sanitize(&q); xSemaphoreTake(s_lock, portMAX_DELAY); s_cur = q; s_reset_pending = true; xSemaphoreGive(s_lock); } void patterns_set_global(uint8_t level) { xSemaphoreTake(s_lock, portMAX_DELAY); s_global = level; xSemaphoreGive(s_lock); } uint8_t patterns_get_global(void) { xSemaphoreTake(s_lock, portMAX_DELAY); uint8_t v = s_global; xSemaphoreGive(s_lock); return v; } void patterns_set_master(uint8_t level) { xSemaphoreTake(s_lock, portMAX_DELAY); s_master = level; xSemaphoreGive(s_lock); } uint8_t patterns_get_master(void) { xSemaphoreTake(s_lock, portMAX_DELAY); uint8_t v = s_master; xSemaphoreGive(s_lock); return v; } void patterns_get(preset_t *out) { xSemaphoreTake(s_lock, portMAX_DELAY); *out = s_cur; xSemaphoreGive(s_lock); } static uint32_t now_ms(void) { return (uint32_t)(esp_timer_get_time() / 1000); } // Show the shadow frame, crossfading from the previous frame while a fade runs static void output(uint32_t now, bool full_brightness) { // device brightness x master scale, under the max brightness ceiling. DDP frames are shown at // full brightness: the sender sets the colours. int s_scale = full_brightness ? 255 : s_global * s_master / 255 * s_max_brightness / 255; int k = -1; if (s_fading) { uint32_t el = now - s_fade_t0; if (el >= s_fade_ms) { s_fading = false; } else { k = (int)((el * 256) / s_fade_ms); } } for (int i = 0; i < s_fx.n; i++) { rgb c = s_fx.px[i]; c.r = c.r * s_scale / 255; c.g = c.g * s_scale / 255; c.b = c.b * s_scale / 255; if (k >= 0) { rgb a = s_from[i]; c.r = (a.r * (256 - k) + c.r * k) >> 8; c.g = (a.g * (256 - k) + c.g * k) >> 8; c.b = (a.b * (256 - k) + c.b * k) >> 8; } s_strip->set(i, c.r, c.g, c.b); s_shown[i] = c; } esp_err_t err = s_strip->write(); if (err != ESP_OK) { ESP_LOGW(TAG, "LED write failed: %s", esp_err_to_name(err)); } } // ---- per-LED buffers -------------------------------------------------------------------------- bool frame_alloc(int n) { if (n < 1) n = 1; if (n > FX_LEDS_MAX) n = FX_LEDS_MAX; void *fresh[12] = { calloc(n, sizeof(rgb)), calloc(n, sizeof(rgb)), calloc(n, sizeof(rgb)), calloc(n, sizeof(int)), calloc(n, sizeof(float)), calloc(n, sizeof(int)), calloc(n, 1), calloc(n, 1), calloc(n, sizeof(int)), calloc(n, sizeof(int)), calloc(n, sizeof(int)), calloc(n, sizeof(int)), }; for (int k = 0; k < 12; k++) { if (!fresh[k]) { for (int j = 0; j < 12; j++) free(fresh[j]); ESP_LOGE(TAG, "Out of memory for %d LEDs", n); return false; } } free(s_fx.px); free(s_shown); free(s_from); free(g_st.glow); free(g_st.m); free(g_st.shade); free(g_st.on); free(g_st.next_on); free(g_st.col_i); free(g_st.next_ci); free(g_st.light); free(g_st.dark); s_fx.px = (rgb *)fresh[0]; s_shown = (rgb *)fresh[1]; s_from = (rgb *)fresh[2]; g_st.glow = (int *)fresh[3]; g_st.m = (float *)fresh[4]; g_st.shade = (int *)fresh[5]; g_st.on = (uint8_t *)fresh[6]; g_st.next_on = (uint8_t *)fresh[7]; g_st.col_i = (int *)fresh[8]; g_st.next_ci = (int *)fresh[9]; g_st.light = (int *)fresh[10]; g_st.dark = (int *)fresh[11]; s_cap = n; return true; } void st_reset(void) { int *glow = g_st.glow, *shade = g_st.shade, *col_i = g_st.col_i, *next_ci = g_st.next_ci; int *light = g_st.light, *dark = g_st.dark; float *m = g_st.m; uint8_t *on = g_st.on, *next_on = g_st.next_on; memset(&g_st, 0, sizeof(g_st)); g_st.glow = glow; g_st.shade = shade; g_st.col_i = col_i; g_st.next_ci = next_ci; g_st.light = light; g_st.dark = dark; g_st.m = m; g_st.on = on; g_st.next_on = next_on; memset(glow, 0, s_cap * sizeof(int)); memset(shade, 0, s_cap * sizeof(int)); memset(col_i, 0, s_cap * sizeof(int)); memset(next_ci, 0, s_cap * sizeof(int)); memset(light, 0, s_cap * sizeof(int)); memset(dark, 0, s_cap * sizeof(int)); memset(m, 0, s_cap * sizeof(float)); memset(on, 0, s_cap); memset(next_on, 0, s_cap); } // The whole frame (pattern and output) runs under s_lock, so the buffers can't be replaced mid-frame static void patterns_task(void *arg) { (void)arg; s_fx.pr = &s_run; while (true) { xSemaphoreTake(s_lock, portMAX_DELAY); bool reset = s_reset_pending; s_reset_pending = false; s_run = s_cur; uint32_t now = now_ms(); bool ddp_on = s_ddp_last_ms != 0 && now - s_ddp_last_ms < DDP_TIMEOUT_MS; if (!ddp_on && s_ddp_was) { reset = true; // the pattern starts again when the pixels stop } s_ddp_was = ddp_on; if (reset) { if (s_run.fade > 0) { memcpy(s_from, s_shown, s_fx.n * sizeof(rgb)); s_fading = true; s_fade_t0 = now; s_fade_ms = s_run.fade; } else { s_fading = false; } st_reset(); g_st.t0 = now; } s_fx.now = now; s_fx.t = now - g_st.t0; if (ddp_on) { for (int i = 0; i < s_fx.n; i++) { s_fx.px[i] = { s_ddp_show[3 * i], s_ddp_show[3 * i + 1], s_ddp_show[3 * i + 2] }; } } else if (!g_st.done) { if (kPatterns[s_run.pattern].fn(s_fx, g_st)) { g_st.done = true; } } output(now, ddp_on); xSemaphoreGive(s_lock); vTaskDelay(pdMS_TO_TICKS(FRAME_MS)); } } static int clamp_leds(int n) { return n < 1 ? 1 : (n > FX_LEDS_MAX ? FX_LEDS_MAX : n); } void patterns_start(const hw_cfg_t &hw) { s_lock = xSemaphoreCreateMutex(); preset_defaults(&s_cur, 0); preset_defaults(&s_run, 0); s_cur.pattern = patterns_index("chase"); s_cur.delay = 1000; s_cur.brightness = 16; s_cur.col[0][0] = 255; s_reset_pending = true; int n = clamp_leds(hw.num_leds); if (!frame_alloc(n)) { ESP_ERROR_CHECK(ESP_ERR_NO_MEM); } s_fx.n = n; s_max_brightness = hw.max_brightness; s_global = hw.global_brightness; s_master = hw.master_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 --------------------------------------------------------------------------------------- // Make a completed frame the one the strip shows, and log it. Caller holds s_lock. static void ddp_show(const uint8_t *frame, uint32_t now) { size_t cap = (size_t)s_fx.n * 3; memcpy(s_ddp_show, frame, cap); s_ddp_shown++; uint32_t sum = 0; for (size_t i = 0; i < cap; i++) { sum += frame[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, frame[0], frame[1], frame[2], frame[cap - 3], frame[cap - 2], frame[cap - 1]); } } 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++; bool syncing = s_sync_last_ms != 0 && now - s_sync_last_ms < DDP_SYNC_TIMEOUT_MS; if (syncing) { // Syncs are arriving: hold the frame until the next one. The sender acks each frame before it // sends the sync, so the frame is always here when its sync arrives. memcpy(s_ddp_held, s_ddp, cap); s_ddp_held_ok = true; } else { s_ddp_held_ok = false; ddp_show(s_ddp, now); } } xSemaphoreGive(s_lock); } void patterns_ddp_sync(uint32_t seq) { xSemaphoreTake(s_lock, portMAX_DELAY); uint32_t now = now_ms(); s_sync_last_ms = now | 1; // never 0 s_sync_seq = seq; s_sync_count++; if (s_ddp_held_ok) { s_ddp_held_ok = false; ddp_show(s_ddp_held, now); } 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_ddp_debug(patterns_ddp_debug_t *out) { xSemaphoreTake(s_lock, portMAX_DELAY); uint32_t now = now_ms(); out->syncs = s_sync_count; out->sync_seq = s_sync_seq; out->sync_age_ms = s_sync_last_ms != 0 ? now - s_sync_last_ms : UINT32_MAX; out->frames = s_ddp_frames; out->shown = s_ddp_shown; out->held = s_ddp_held_ok; 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); }