Files
led-controller/main/seqplay.c
T
jimmyandClaude Opus 5.5 04b56c6ef2 feat: device groups, combined brightness and beat-driven sequences from main
Groups (registry of driver MACs, optionally scoped to a profile) become
the drivers' group membership, alongside z<zone id> for zones that still
name drivers. Zones play to their group_ids. Group and device routes for
driver config, brightness (global x groups x device x zone) and identify.
The push path takes main's message shape: select as a list, groups as a
filter (one GROUP_CMD per group, or JSON when a preset has a background),
short keys so JSON fits a frame.

Sequences follow main: lanes of {preset_id, beats} steps played to each
lane's groups, advanced by the mic's beats or a clock at
audio_simulated_bpm; a switch waits for the next beat or downbeat; sync-
phase, stop (clears the zone's drivers) and status. This replaces the
time-based per-zone sequencer and scene playback, as in main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 18:09:42 +13:00

685 lines
21 KiB
C

#include "seqplay.h"
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include "api_util.h"
#include "beat.h"
#include "engine.h"
#include "esp_heap_caps.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/task.h"
#include "store.h"
static const char *TAG = "seqplay";
#define LANES_MAX 8
#define STEPS_MAX 64
#define ID_MAX 24
#define BPM_MIN 60
#define BPM_MAX 200
#define BEATS_PER_BAR 4
typedef struct {
char preset[ID_MAX];
int beats;
char group_ids[4][GROUP_ID_MAX]; // a single lane's step may carry its own groups
int ngroups;
} step_t;
typedef struct {
step_t step[STEPS_MAX];
int n, idx, count;
bool done;
char last[ID_MAX]; // preset last uploaded for this lane
} lane_t;
// Everything below is guarded by the store lock (the beat task and the HTTP handlers both take it).
// The lanes (about 57 KB) live in PSRAM, allocated by seqplay_init.
static struct {
bool active;
char seq[ID_MAX], zone[ID_MAX], profile[ID_MAX];
lane_t *lane;
int nlanes;
bool loop;
int loop_beat;
bool anchor_on_pass_start;
bool pending_switch; // a queued start takes over on the next beat; stop advancing meanwhile
} s_run;
static struct {
bool set;
char seq[ID_MAX], zone[ID_MAX], profile[ID_MAX];
} s_pend;
static char s_done_readout[24]; // "6/6" kept after a sequence ran to its end
static bool s_audio = true;
static uint32_t s_sim_beats; // simulated clock beats, for its bar phase
static int64_t s_last_beat_us;
/* ------------------------------------------------------------- settings */
static int simulated_bpm(void)
{
const cJSON *v = cJSON_GetObjectItem(store_settings(), "audio_simulated_bpm");
int bpm = cJSON_IsNumber(v) ? (int)v->valuedouble : 120;
return bpm < BPM_MIN ? BPM_MIN : (bpm > BPM_MAX ? BPM_MAX : bpm);
}
static bool audio_drives(void)
{
beat_info_t bi;
beat_get_info(&bi);
return s_audio && bi.locked;
}
// "downbeat" only while the mic is timing (the clock's bar is a guess); otherwise "beat"
static bool wait_for_downbeat(void)
{
const cJSON *v = cJSON_GetObjectItem(store_settings(), "sequence_switch_wait");
return audio_drives() && cJSON_IsString(v) && !strcasecmp(v->valuestring, "downbeat");
}
/* ---------------------------------------------------------------- targets */
static void add_id(cJSON *arr, const char *id)
{
const cJSON *it;
cJSON_ArrayForEach(it, arr)
{
if (!strcmp(it->valuestring, id)) {
return;
}
}
cJSON_AddItemToArray(arr, cJSON_CreateString(id));
}
static void add_list(cJSON *arr, const cJSON *list)
{
const cJSON *it;
cJSON_ArrayForEach(it, list)
{
char id[GROUP_ID_MAX];
if (api_id(it, id, sizeof(id))) {
add_id(arr, id);
}
}
}
// Groups a lane's step plays to (main's _group_ids_for_lane_step), falling back to the zone's groups
static cJSON *lane_groups(int lane, const step_t *st)
{
cJSON *out = cJSON_CreateArray();
const cJSON *seq = cJSON_GetObjectItem(store_coll("sequence"), s_run.seq);
const cJSON *lgs = cJSON_GetObjectItem(seq, "lanes_group_ids");
if (cJSON_IsArray(lgs) && lane < cJSON_GetArraySize(lgs)) {
add_list(out, cJSON_GetArrayItem(lgs, lane));
} else if (!(s_run.nlanes > 1 && cJSON_IsArray(lgs))) {
add_list(out, cJSON_GetObjectItem(seq, "group_ids"));
for (int i = 0; !out->child && s_run.nlanes == 1 && i < st->ngroups; i++) {
add_id(out, st->group_ids[i]);
}
}
if (!out->child) {
char t[ZONE_TARGETS_MAX][GROUP_ID_MAX];
int n = engine_zone_targets(s_run.zone, t, ZONE_TARGETS_MAX);
for (int i = 0; i < n; i++) {
add_id(out, t[i]);
}
}
return out;
}
static void send(cJSON *msg)
{
cJSON *messages = cJSON_CreateArray();
cJSON_AddItemToArray(messages, msg);
engine_push(messages, NULL);
cJSON_Delete(messages);
}
static cJSON *message(cJSON *groups)
{
cJSON *m = cJSON_CreateObject();
cJSON_AddStringToObject(m, "v", "1");
if (groups && groups->child) {
cJSON_AddItemToObject(m, "groups", groups);
} else {
cJSON_Delete(groups);
}
return m;
}
// Upload presets [from, to) of a lane (each once) to the lane's groups
static void send_presets(int lane, int from, int to)
{
lane_t *l = &s_run.lane[lane];
cJSON *presets = cJSON_CreateObject();
for (int i = from; i < to && i < l->n; i++) {
const char *id = l->step[i].preset;
cJSON *p = cJSON_GetObjectItem(presets, id) ? NULL : engine_preset_payload(id);
if (p) {
cJSON_AddItemToObject(presets, id, p);
}
}
if (!presets->child) {
cJSON_Delete(presets);
return;
}
cJSON *m = message(lane_groups(lane, &l->step[from]));
cJSON_AddItemToObject(m, "presets", presets);
send(m);
}
static void send_select(int lane)
{
lane_t *l = &s_run.lane[lane];
const step_t *st = &l->step[l->idx];
cJSON *m = message(lane_groups(lane, st));
cJSON *sel = cJSON_AddArrayToObject(m, "select");
cJSON_AddItemToArray(sel, cJSON_CreateString(st->preset));
send(m);
}
// Step change: upload the new step's preset unless it is already there, then select it
static void send_lane(int lane)
{
lane_t *l = &s_run.lane[lane];
if (l->done || l->idx >= l->n || !l->step[l->idx].preset[0]) {
return;
}
if (strcmp(l->last, l->step[l->idx].preset)) {
send_presets(lane, l->idx, l->idx + 1);
memcpy(l->last, l->step[l->idx].preset, ID_MAX);
}
send_select(lane);
}
// Every driver the zone reaches gets its combined brightness with the zone's slider value
static void zone_brightness(void)
{
const cJSON *zone = cJSON_GetObjectItem(store_coll("zone"), s_run.zone);
const cJSON *zb = cJSON_GetObjectItem(zone, "brightness");
int zone_b = cJSON_IsNumber(zb) ? (int)zb->valuedouble : 255;
zone_b = zone_b < 0 ? 0 : (zone_b > 255 ? 255 : zone_b);
cJSON *macs = cJSON_CreateArray();
char t[ZONE_TARGETS_MAX][GROUP_ID_MAX];
int n = engine_zone_targets(s_run.zone, t, ZONE_TARGETS_MAX);
for (int i = 0; i < n; i++) {
const cJSON *it;
if (t[i][0] == 'z') { // drivers named by the zone
const cJSON *d;
cJSON_ArrayForEach(d, store_coll("device"))
{
const cJSON *name = cJSON_GetObjectItem(d, "name");
cJSON_ArrayForEach(it, cJSON_GetObjectItem(zone, "names"))
{
if (cJSON_IsString(name) && cJSON_IsString(it) && !strcmp(name->valuestring, it->valuestring)) {
add_id(macs, d->string);
}
}
}
continue;
}
cJSON_ArrayForEach(it, cJSON_GetObjectItem(cJSON_GetObjectItem(store_coll("group"), t[i]), "devices"))
{
char mac[13];
if (api_mac(it, mac)) {
add_id(macs, mac);
}
}
}
const cJSON *mac;
cJSON_ArrayForEach(mac, macs)
{
cJSON *m = message(NULL);
cJSON_AddNumberToObject(m, "b", api_effective_brightness(mac->valuestring, zone_b));
cJSON_AddTrueToObject(m, "save");
cJSON *messages = cJSON_CreateArray(), *targets = cJSON_CreateArray();
cJSON_AddItemToArray(messages, m);
cJSON_AddItemToArray(targets, cJSON_CreateString(mac->valuestring));
engine_push(messages, targets);
cJSON_Delete(messages);
cJSON_Delete(targets);
}
cJSON_Delete(macs);
}
/* --------------------------------------------------------------- playback */
// The sequence's lanes as steps (main's _normalize_sequence_lanes); empty lanes are dropped
static int load_lanes(const cJSON *seq)
{
const cJSON *lanes = cJSON_GetObjectItem(seq, "lanes");
bool any = false;
const cJSON *l;
cJSON_ArrayForEach(l, lanes)
{
any = any || cJSON_GetArraySize(l) > 0;
}
cJSON *one = NULL;
if (!any && cJSON_GetArraySize(cJSON_GetObjectItem(seq, "steps"))) {
one = cJSON_CreateArray();
cJSON_AddItemReferenceToArray(one, cJSON_GetObjectItem(seq, "steps"));
lanes = one;
}
int n = 0;
cJSON_ArrayForEach(l, lanes)
{
if (n == LANES_MAX || !cJSON_IsArray(l) || !cJSON_GetArraySize(l)) {
continue;
}
lane_t *lane = &s_run.lane[n];
memset(lane, 0, sizeof(*lane));
const cJSON *s;
cJSON_ArrayForEach(s, l)
{
if (lane->n == STEPS_MAX || !cJSON_IsObject(s)) {
continue;
}
step_t *st = &lane->step[lane->n++];
const cJSON *pid = cJSON_GetObjectItem(s, "preset_id");
api_id(pid ? pid : cJSON_GetObjectItem(s, "presetId"), st->preset, sizeof(st->preset));
const cJSON *b = cJSON_GetObjectItem(s, "beats");
st->beats = cJSON_IsNumber(b) && b->valuedouble >= 1 ? (int)b->valuedouble : 1;
const cJSON *g;
cJSON_ArrayForEach(g, cJSON_GetObjectItem(s, "group_ids"))
{
if (st->ngroups < 4 && api_id(g, st->group_ids[st->ngroups], GROUP_ID_MAX)) {
st->ngroups++;
}
}
}
n += lane->n > 0;
}
cJSON_Delete(one);
return n;
}
static void anchor_bar(void)
{
s_sim_beats = 0; // the next clock beat is a downbeat
if (audio_drives()) {
beat_tap(); // the beat just counted is beat 1 of the bar
}
}
static void clear_drivers(void)
{
cJSON *groups = cJSON_CreateArray();
char t[ZONE_TARGETS_MAX][GROUP_ID_MAX];
int n = engine_zone_targets(s_run.zone, t, ZONE_TARGETS_MAX);
for (int i = 0; i < n; i++) {
add_id(groups, t[i]);
}
if (!groups->child) { // never clear every driver in range
cJSON_Delete(groups);
return;
}
cJSON *m = message(groups);
cJSON_AddTrueToObject(m, "clear_presets");
cJSON_AddTrueToObject(m, "save");
send(m);
}
static esp_err_t start_now(const char *seq_id, const char *zone_id, const char *profile_id, bool handoff,
bool downbeat, const char **msg)
{
const cJSON *seq = cJSON_GetObjectItem(store_coll("sequence"), seq_id);
if (!seq) {
return ESP_ERR_NOT_FOUND;
}
if (!cJSON_GetObjectItem(store_coll("zone"), zone_id)) {
*msg = "zone not found";
return ESP_ERR_INVALID_ARG;
}
s_pend.set = false;
s_run.active = false;
s_done_readout[0] = 0;
snprintf(s_run.seq, sizeof(s_run.seq), "%s", seq_id);
snprintf(s_run.zone, sizeof(s_run.zone), "%s", zone_id);
snprintf(s_run.profile, sizeof(s_run.profile), "%s", profile_id);
s_run.nlanes = load_lanes(seq);
if (!s_run.nlanes) {
*msg = "sequence has no steps";
return ESP_ERR_INVALID_SIZE;
}
const cJSON *loop = cJSON_GetObjectItem(seq, "loop");
s_run.loop = !loop || cJSON_IsTrue(loop) || (cJSON_IsNumber(loop) && loop->valuedouble != 0);
s_run.loop_beat = 0;
s_run.pending_switch = false;
s_run.anchor_on_pass_start = handoff ? downbeat : true;
// Step-0 presets, the selects, then the rest of each lane's presets (main's _prime_all_lanes)
for (int i = 0; i < s_run.nlanes; i++) {
send_presets(i, 0, 1);
memcpy(s_run.lane[i].last, s_run.lane[i].step[0].preset, ID_MAX);
}
for (int i = 0; i < s_run.nlanes; i++) {
send_select(i);
}
for (int i = 0; i < s_run.nlanes; i++) {
send_presets(i, 1, s_run.lane[i].n);
}
zone_brightness();
s_run.active = true;
ESP_LOGI(TAG, "sequence %s in zone %s: %d lane(s)", seq_id, zone_id, s_run.nlanes);
return ESP_OK;
}
static bool pass_start(void)
{
const lane_t *l = &s_run.lane[0];
return !l->done && l->idx == 0 && l->count == 0;
}
static int readout(char *buf, size_t len); // forward
static void advance(void)
{
if (!s_run.active || s_run.pending_switch) {
return;
}
if (pass_start() && s_run.anchor_on_pass_start) {
anchor_bar();
}
s_run.anchor_on_pass_start = true;
bool lane0_looped = false;
for (int i = 0; i < s_run.nlanes; i++) {
lane_t *l = &s_run.lane[i];
if (l->done || !l->n) {
continue;
}
int need = l->step[l->idx].beats;
if (++l->count < need) {
continue;
}
if (l->idx + 1 >= l->n) {
if (s_run.loop) {
lane0_looped = lane0_looped || i == 0;
l->count = 0;
l->idx = 0;
l->last[0] = 0; // step 0 goes up again on each wrap
send_lane(i);
} else {
l->count = need;
l->done = true;
}
} else {
l->count = 0;
l->idx++;
send_lane(i);
}
}
s_run.loop_beat = lane0_looped ? 1 : s_run.loop_beat + 1;
bool all_done = true;
for (int i = 0; i < s_run.nlanes; i++) {
all_done = all_done && s_run.lane[i].done;
}
if (all_done) {
readout(s_done_readout, sizeof(s_done_readout));
clear_drivers();
s_run.active = false;
ESP_LOGI(TAG, "sequence %s finished", s_run.seq);
}
}
static void on_beat(bool downbeat)
{
int64_t now = esp_timer_get_time();
if (now - s_last_beat_us < 60LL * 1000000 / BPM_MAX) { // never faster than BPM_MAX
return;
}
s_last_beat_us = now;
store_lock();
if (s_pend.set && (downbeat || !wait_for_downbeat())) {
const char *msg = NULL;
char seq[ID_MAX], zone[ID_MAX], profile[ID_MAX];
snprintf(seq, sizeof(seq), "%s", s_pend.seq);
snprintf(zone, sizeof(zone), "%s", s_pend.zone);
snprintf(profile, sizeof(profile), "%s", s_pend.profile);
if (start_now(seq, zone, profile, true, downbeat, &msg) != ESP_OK) {
ESP_LOGW(TAG, "queued sequence %s did not start: %s", seq, msg ? msg : "not found");
}
} else {
advance();
}
store_unlock();
}
static void beat_task(void *arg)
{
QueueHandle_t q = xQueueCreate(8, sizeof(beat_event_t));
if (!q || beat_subscribe(q) != ESP_OK) {
ESP_LOGE(TAG, "no beat subscription; the clock alone times sequences");
}
int64_t next = esp_timer_get_time();
for (;;) {
store_lock();
int64_t interval = 60LL * 1000000 / simulated_bpm();
store_unlock();
int64_t now = esp_timer_get_time();
if (next <= now) { // clock beat, counted only while the mic is not timing
next = (next + interval > now) ? next + interval : now + interval;
if (!audio_drives()) {
bool down = s_sim_beats % BEATS_PER_BAR == 0;
s_sim_beats++;
on_beat(down);
}
continue;
}
beat_event_t ev;
if (q && xQueueReceive(q, &ev, pdMS_TO_TICKS((next - now) / 1000) + 1) == pdTRUE && ev == BEAT_EVENT_BEAT &&
audio_drives()) {
beat_info_t bi;
beat_get_info(&bi);
on_beat(bi.bar_beat == 1);
}
}
}
/* --------------------------------------------------------------------- API */
esp_err_t seqplay_init(void)
{
s_run.lane = heap_caps_calloc(LANES_MAX, sizeof(lane_t), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (!s_run.lane) {
return ESP_ERR_NO_MEM;
}
store_lock();
const cJSON *a = cJSON_GetObjectItem(store_settings(), "audio_timing");
s_audio = !cJSON_IsFalse(a);
store_unlock();
return xTaskCreate(beat_task, "seqplay", 6144, NULL, 4, NULL) == pdPASS ? ESP_OK : ESP_ERR_NO_MEM;
}
esp_err_t seqplay_start(const char *seq_id, const char *zone_id, const char *profile_id, const char **msg)
{
*msg = NULL;
const cJSON *seq = cJSON_GetObjectItem(store_coll("sequence"), seq_id);
char owner[ID_MAX];
if (!seq || !api_id(cJSON_GetObjectItem(seq, "profile_id"), owner, sizeof(owner)) || strcmp(owner, profile_id)) {
*msg = "sequence not found";
return ESP_ERR_NOT_FOUND;
}
if (!s_run.active) {
return start_now(seq_id, zone_id, profile_id, false, false, msg);
}
// Another sequence plays: switch on the next beat (or downbeat)
s_pend.set = true;
snprintf(s_pend.seq, sizeof(s_pend.seq), "%s", seq_id);
snprintf(s_pend.zone, sizeof(s_pend.zone), "%s", zone_id);
snprintf(s_pend.profile, sizeof(s_pend.profile), "%s", profile_id);
s_run.pending_switch = true;
return ESP_OK;
}
void seqplay_stop(bool clear)
{
store_lock();
bool was = s_run.active;
s_pend.set = false;
s_run.active = false;
bool finished = true;
for (int i = 0; i < s_run.nlanes; i++) {
finished = finished && s_run.lane[i].done;
}
if (!finished) {
s_done_readout[0] = 0;
}
if (was && clear) {
clear_drivers();
}
store_unlock();
}
void seqplay_stop_if(const char *seq_id)
{
store_lock();
bool playing = s_run.active && !strcmp(s_run.seq, seq_id);
store_unlock();
if (playing) {
seqplay_stop(true);
}
}
bool seqplay_sync(const char *mode)
{
store_lock();
bool ok = s_run.active;
if (ok && (!strcasecmp(mode, "pass") || !strcasecmp(mode, "sequence") || !strcasecmp(mode, "restart"))) {
for (int i = 0; i < s_run.nlanes; i++) {
s_run.lane[i].idx = s_run.lane[i].count = 0;
s_run.lane[i].done = false;
}
s_run.loop_beat = 0;
for (int i = 0; i < s_run.nlanes; i++) {
send_lane(i);
}
} else if (ok) {
for (int i = 0; i < s_run.nlanes; i++) {
if (!s_run.lane[i].done) {
s_run.lane[i].count = 0;
}
}
}
if (ok) {
anchor_bar();
}
store_unlock();
return ok;
}
// Lane 0's position in the pass: beats so far and per pass
static void pass_position(int *at, int *per_pass)
{
const lane_t *l = &s_run.lane[0];
*at = *per_pass = 0;
for (int i = 0; i < l->n; i++) {
*per_pass += l->step[i].beats;
}
if (l->done) {
*at = *per_pass;
return;
}
for (int i = 0; i < l->idx && i < l->n; i++) {
*at += l->step[i].beats;
}
int bt = l->idx < l->n ? l->step[l->idx].beats : 1;
*at += l->count < 0 ? 0 : (l->count > bt ? bt : l->count);
}
static int readout(char *buf, size_t len)
{
int at, tot;
pass_position(&at, &tot);
buf[0] = 0;
if (tot > 0 && s_run.lane[0].done) {
return snprintf(buf, len, "%d/%d", tot, tot);
}
if (tot > 0 && at > 0) { // on the last beat of the pass show n/n
return snprintf(buf, len, "%d/%d", at == tot - 1 ? tot : (at < tot ? at : tot), tot);
}
return 0;
}
cJSON *seqplay_status(void)
{
cJSON *o = cJSON_CreateObject();
store_lock();
if (!s_run.active) {
cJSON_AddFalseToObject(o, "active");
cJSON_AddStringToObject(o, "beat_readout", "");
store_unlock();
return o;
}
const lane_t *l = &s_run.lane[0];
int total = 0;
for (int i = 0; i < s_run.nlanes; i++) {
total += s_run.lane[i].n;
}
int at, per_pass;
pass_position(&at, &per_pass);
int bps = !l->done && l->idx < l->n ? l->step[l->idx].beats : 1;
int beat_in = l->done ? 0 : (l->count > bps ? bps : l->count);
const char *pid = !l->done && l->idx < l->n ? l->step[l->idx].preset : "";
const cJSON *pdoc = pid[0] ? cJSON_GetObjectItem(store_coll("preset"), pid) : NULL;
const cJSON *pname = cJSON_GetObjectItem(pdoc, "name");
char ro[24];
readout(ro, sizeof(ro));
cJSON_AddTrueToObject(o, "active");
cJSON_AddStringToObject(o, "advance_mode", "beats");
cJSON_AddStringToObject(o, "sequence_id", s_run.seq);
cJSON_AddStringToObject(o, "zone_id", s_run.zone);
cJSON_AddNumberToObject(o, "num_lanes", s_run.nlanes);
cJSON_AddNumberToObject(o, "total_sequence_steps", total);
cJSON_AddNumberToObject(o, "lane0_current_step", l->done ? l->n : l->idx + 1);
cJSON_AddNumberToObject(o, "lane0_lane_length", l->n);
cJSON_AddNumberToObject(o, "lane0_beat_in_step", beat_in);
cJSON_AddNumberToObject(o, "lane0_beats_per_step", bps);
cJSON_AddStringToObject(o, "lane0_preset_id", pid);
cJSON_AddStringToObject(o, "lane0_preset_name",
cJSON_IsString(pname) && pname->valuestring[0] ? pname->valuestring : pid);
cJSON_AddNumberToObject(o, "sequence_beat_at", at);
cJSON_AddNumberToObject(o, "sequence_beats_per_pass", per_pass);
cJSON_AddNumberToObject(o, "sequence_loop_beat", s_run.loop_beat);
cJSON_AddStringToObject(o, "beat_readout", ro);
store_unlock();
return o;
}
cJSON *seqplay_pending(void)
{
cJSON *o = cJSON_CreateObject();
store_lock();
cJSON_AddBoolToObject(o, "pending", s_pend.set);
if (s_pend.set) {
cJSON_AddStringToObject(o, "wait_for", wait_for_downbeat() ? "downbeat" : "beat");
cJSON_AddStringToObject(o, "sequence_id", s_pend.seq);
cJSON_AddStringToObject(o, "zone_id", s_pend.zone);
}
store_unlock();
return o;
}
const char *seqplay_done_readout(void)
{
return s_done_readout;
}
void seqplay_set_audio(bool on)
{
store_lock();
s_audio = on;
api_set(store_settings(), "audio_timing", cJSON_CreateBool(on));
store_save("settings");
store_unlock();
}
bool seqplay_audio(void)
{
return s_audio;
}