refactor: move the v2 controller to the repository root

The ESP-IDF project, docs, tools, tests and web UI move from v2/ to the
root, and the Makefile, README, build scripts and test runner drop the
v2/ prefix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Opus 5.5 committed 2026-11-02 23:44:58 +13:00
1 parent 71bd320661
commit 1c222771a5
66 files changed
+30 -31

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
idf_component_register(SRCS "main.c" "mic.c" "beat.c" "beat_dsp.c" "espnow_tx.c" "store.c" "api.c" "web.c" "envelope.c" "engine.c" "rel.c" "bench.c" "audio.c" "ota.c"
INCLUDE_DIRS "."
REQUIRES esp_eth esp_netif esp_event esp_driver_spi esp_driver_gpio nvs_flash app_update esp_app_format
esp_http_server esp_timer esp_driver_i2s esp_wifi esp_rom json esp_driver_gpio
PRIV_REQUIRES littlefs mdns)
# The gzipped web UI is embedded in the app image (run tools/build_web.sh first)
if(NOT EXISTS ${PROJECT_DIR}/www_dist/www.pack)
message(FATAL_ERROR "www_dist/www.pack is missing: run tools/build_web.sh (make build does)")
endif()
target_add_binary_data(${COMPONENT_LIB} ${PROJECT_DIR}/www_dist/www.pack BINARY)
+139
View File
@@ -0,0 +1,139 @@
menu "W5500 config"
config W5500_SPI_HOST
int "SPI host number (1=SPI2, 2=SPI3)"
range 1 2
default 1
config W5500_SPI_CLOCK_MHZ
int "SPI clock speed (MHz)"
range 5 80
default 20
config W5500_SCLK_GPIO
int "SCLK GPIO (XIAO D8)"
default 7
config W5500_MISO_GPIO
int "MISO GPIO (XIAO D9)"
default 8
config W5500_MOSI_GPIO
int "MOSI GPIO (XIAO D10)"
default 9
config W5500_CS_GPIO
int "CS GPIO (XIAO D1)"
default 2
config W5500_INT_GPIO
int "INT GPIO (XIAO D2), -1 to poll"
default 3
config W5500_POLL_PERIOD_MS
int "RX poll period (ms) when INT is -1"
default 10
config W5500_RST_GPIO
int "RST GPIO (XIAO D0), -1 if not wired"
default 1
endmenu
menu "INMP441 mic config"
config MIC_SCK_GPIO
int "SCK GPIO (XIAO D4)"
default 5
config MIC_WS_GPIO
int "WS GPIO (XIAO D5)"
default 6
config MIC_SD_GPIO
int "SD GPIO (XIAO D6)"
default 43
config MIC_STREAM_GAIN
int "Digital gain for the audio stream (x)"
range 1 256
default 16
help
The INMP441 is quiet at full scale; x16 (+24 dB) makes speech
audible without clipping at normal distances.
endmenu
menu "Beat detection config"
config BEAT_LED_GPIO
int "Beat LED GPIO (XIAO user LED is 21), -1 for none"
default 21
config BEAT_LED_ACTIVE_LOW
bool "Beat LED lights when the pin is low"
default y
config BEAT_LED_PULSE_MS
int "Beat LED flash length (ms)"
range 10 500
default 60
config BEAT_LED_DOWNBEAT_MS
int "Beat LED flash length on the first beat of a bar (ms)"
range 10 1000
default 200
config BEAT_GATE_DBFS
int "Ignore audio quieter than this (dBFS, before stream gain)"
range -100 -20
default -75
help
The INMP441 self-noise is about -87 dBFS. Background music in a
room can sit around -65 dBFS, so keep this well below that.
config BEAT_LEAD_MS
int "Fire predicted beats this early (ms)"
range 0 200
default 30
help
Beats are predicted from the tempo, so they can be sent early
to cancel the ~30 ms of capture and analysis latency. Raise it
to cover output latency too (e.g. network or lights).
endmenu
menu "ESP-NOW config"
config ESPNOW_CHANNEL
int "Wi-Fi channel shared with the LED drivers"
range 1 13
default 6
config BEAT_TX_COPIES
int "Copies sent of every beat frame"
range 1 4
default 2
help
Each beat is broadcast this many times with the same beat index.
Drivers act on the first copy that arrives and drop the rest.
config BEAT_TX_GAP_US
int "Gap between beat copies (us)"
range 500 10000
default 2000
config BEAT_TEST_GPIO
int "GPIO toggled on every beat sent (-1 = off)"
range -1 48
default -1
help
For latency measurement: a logic analyzer or scope on this pin and on
the driver's beat pin shows the true master-to-LED delay.
config BULK_HOLDOFF_US
int "Hold bulk traffic back after a beat (us)"
range 0 20000
default 3000
endmenu
+628
View File
@@ -0,0 +1,628 @@
#include "api.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "cJSON.h"
#include "esp_log.h"
#include "bench.h"
#include "engine.h"
#include "espnow_tx.h"
#include "rel.h"
#include "store.h"
#include "web.h"
static const char *TAG = "api";
#define BODY_MAX (256 * 1024)
// URL resource -> store collection
static const struct {
const char *res;
const char *coll;
} RES[] = {
{ "devices", "device" }, { "zones", "zone" }, { "presets", "preset" },
{ "profiles", "profile" }, { "palettes", "palette" }, { "patterns", "pattern" },
{ "sequences", "sequence" }, { "scenes", "scene" }, { "groups", "group" },
{ "outputs", "output" },
};
static esp_err_t send_json(httpd_req_t *req, const char *status, cJSON *obj, bool own)
{
char *s = cJSON_PrintUnformatted(obj);
if (own) {
cJSON_Delete(obj);
}
if (!s) {
return httpd_resp_send_500(req);
}
httpd_resp_set_status(req, status);
httpd_resp_set_type(req, "application/json");
esp_err_t ret = httpd_resp_send(req, s, HTTPD_RESP_USE_STRLEN);
free(s);
return ret;
}
static esp_err_t send_error(httpd_req_t *req, const char *status, const char *msg)
{
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "error", msg);
return send_json(req, status, o, true);
}
// Parsed JSON object body, or NULL after an error response has been sent
static cJSON *read_body(httpd_req_t *req)
{
if (req->content_len == 0 || req->content_len > BODY_MAX) {
send_error(req, "400 Bad Request", req->content_len ? "body too large" : "body required");
return NULL;
}
char *buf = malloc(req->content_len + 1);
if (!buf) {
httpd_resp_send_500(req);
return NULL;
}
size_t got = 0;
while (got < req->content_len) {
int r = httpd_req_recv(req, buf + got, req->content_len - got);
if (r <= 0) {
free(buf);
httpd_resp_send_err(req, HTTPD_408_REQ_TIMEOUT, "read failed");
return NULL;
}
got += r;
}
buf[got] = 0;
cJSON *obj = cJSON_Parse(buf);
free(buf);
if (!cJSON_IsObject(obj)) {
cJSON_Delete(obj);
send_error(req, "400 Bad Request", "JSON object required");
return NULL;
}
return obj;
}
// Split "/res/id/action?query" into up to three segments
static int split_path(const char *uri, char seg[3][64])
{
int n = 0;
const char *p = uri;
while (*p == '/' && n < 3) {
p++;
size_t len = strcspn(p, "/?");
if (len == 0 || len >= 64) {
break;
}
memcpy(seg[n], p, len);
seg[n][len] = 0;
n++;
p += len;
}
return n;
}
static const char *coll_for(const char *res)
{
for (size_t i = 0; i < sizeof(RES) / sizeof(RES[0]); i++) {
if (strcmp(RES[i].res, res) == 0) {
return RES[i].coll;
}
}
return NULL;
}
static const char *current_profile(void)
{
cJSON *v = cJSON_GetObjectItem(store_settings(), "current_profile_id");
if (cJSON_IsString(v) && cJSON_GetObjectItem(store_coll("profile"), v->valuestring)) {
return v->valuestring;
}
cJSON *first = store_coll("profile")->child; // fall back to the first profile
return first ? first->string : NULL;
}
static bool preset_in_profile(cJSON *rec)
{
const char *cur = current_profile();
cJSON *pid = cJSON_GetObjectItem(rec, "profile_id");
if (!cur) {
return true;
}
char num[24] = "";
if (cJSON_IsNumber(pid)) {
snprintf(num, sizeof(num), "%d", (int)pid->valuedouble);
}
return (cJSON_IsString(pid) && strcmp(pid->valuestring, cur) == 0) || strcmp(num, cur) == 0;
}
static void merge(cJSON *dst, cJSON *src)
{
cJSON *it;
cJSON_ArrayForEach(it, src)
{
if (strcmp(it->string, "id") == 0) {
continue;
}
cJSON *copy = cJSON_Duplicate(it, true);
if (cJSON_GetObjectItem(dst, it->string)) {
cJSON_ReplaceItemInObject(dst, it->string, copy);
} else {
cJSON_AddItemToObject(dst, it->string, copy);
}
}
}
static esp_err_t send_message(httpd_req_t *req, const char *status, const char *msg)
{
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "message", msg);
return send_json(req, status, o, true);
}
static esp_err_t result(httpd_req_t *req, esp_err_t err, const char *ok_msg)
{
switch (err) {
case ESP_OK:
return send_message(req, "200 OK", ok_msg);
case ESP_ERR_NOT_FOUND:
return send_error(req, "404 Not Found", "not found");
case ESP_ERR_INVALID_SIZE:
return send_error(req, "413 Payload Too Large", "preset too large for one ESP-NOW frame");
default:
return send_error(req, "503 Service Unavailable", "send failed");
}
}
static esp_err_t not_implemented(httpd_req_t *req, const char *what)
{
char msg[96];
snprintf(msg, sizeof(msg), "%s is not implemented in v2 yet", what);
return send_error(req, "501 Not Implemented", msg);
}
static esp_err_t handle_profile_action(httpd_req_t *req, const char *id, const char *action)
{
if (strcmp(action, "apply") == 0) {
if (!cJSON_GetObjectItem(store_coll("profile"), id)) {
return send_error(req, "404 Not Found", "profile not found");
}
cJSON *st = store_settings();
cJSON_DeleteItemFromObject(st, "current_profile_id");
cJSON_AddStringToObject(st, "current_profile_id", id);
store_save("settings");
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "message", "Profile applied");
return send_json(req, "200 OK", o, true);
}
return not_implemented(req, action);
}
// Settings a driver keeps in its own settings.json and takes from a device_config message
static const char *const DEVICE_CONFIG_KEYS[] = { "max_brightness", "num_leds", "color_order", "startup_mode", "reversed" };
// The driver settings present in a device update, or NULL when it has none. Caller deletes the result.
static cJSON *device_config_from(const cJSON *body)
{
cJSON *dc = NULL;
for (size_t i = 0; i < sizeof(DEVICE_CONFIG_KEYS) / sizeof(DEVICE_CONFIG_KEYS[0]); i++) {
const cJSON *v = cJSON_GetObjectItem(body, DEVICE_CONFIG_KEYS[i]);
if (!v || cJSON_IsNull(v)) {
continue;
}
if (!dc) {
dc = cJSON_CreateObject();
}
cJSON_AddItemToObject(dc, DEVICE_CONFIG_KEYS[i], cJSON_Duplicate(v, true));
}
return dc;
}
// Send changed settings to an ESP-NOW driver; takes ownership of dc
static esp_err_t push_device_config(const cJSON *dev, cJSON *dc)
{
const cJSON *tr = cJSON_GetObjectItem(dev, "transport"), *addr = cJSON_GetObjectItem(dev, "address");
if (!cJSON_IsString(tr) || strcmp(tr->valuestring, "espnow") || !cJSON_IsString(addr)) {
cJSON_Delete(dc);
return ESP_ERR_INVALID_ARG;
}
cJSON *msg = cJSON_CreateObject();
cJSON_AddStringToObject(msg, "v", "1");
cJSON_AddItemToObject(msg, "device_config", dc);
cJSON_AddTrueToObject(msg, "save");
cJSON *messages = cJSON_CreateArray(), *targets = cJSON_CreateArray();
cJSON_AddItemToArray(messages, msg);
cJSON_AddItemToArray(targets, cJSON_CreateString(addr->valuestring));
esp_err_t err = engine_push(messages, targets);
cJSON_Delete(messages);
cJSON_Delete(targets);
return err;
}
static esp_err_t collection_handler_inner(httpd_req_t *req)
{
char seg[3][64];
int n = split_path(req->uri, seg);
const char *coll = n ? coll_for(seg[0]) : NULL;
if (!coll) {
return send_error(req, "404 Not Found", "unknown resource");
}
const bool is_presets = strcmp(coll, "preset") == 0;
const bool is_profiles = strcmp(coll, "profile") == 0;
cJSON *all = store_coll(coll);
const int method = req->method;
// GET /devices/status: per-driver delivery health from the acked link
if (n == 2 && method == HTTP_GET && !strcmp(seg[0], "devices") && !strcmp(seg[1], "status")) {
cJSON *o = cJSON_CreateObject(), *d;
cJSON_ArrayForEach(d, all)
{
const cJSON *addr = cJSON_GetObjectItem(d, "address");
const char *hex = (cJSON_IsString(addr) && strlen(addr->valuestring) == 12) ? addr->valuestring
: (strlen(d->string) == 12 ? d->string : NULL);
uint8_t mac[6];
unsigned v[6];
if (hex && sscanf(hex, "%2x%2x%2x%2x%2x%2x", &v[0], &v[1], &v[2], &v[3], &v[4], &v[5]) == 6) {
for (int i = 0; i < 6; i++) {
mac[i] = v[i];
}
int fails;
int age = rel_peer_status(mac, &fails);
cJSON *e = cJSON_AddObjectToObject(o, d->string);
cJSON_AddNumberToObject(e, "last_ack_ms_ago", age);
cJSON_AddNumberToObject(e, "failed_messages", fails);
}
}
return send_json(req, "200 OK", o, true);
}
// /<res>/<id>/<action>
if (n == 3 && !strcmp(seg[0], "zones") && !strcmp(seg[1], "engine") && !strcmp(seg[2], "status")) {
return send_json(req, "200 OK", engine_status(), true);
}
if (n == 3 && method == HTTP_POST && !strcmp(seg[0], "zones")) {
if (!strcmp(seg[2], "play")) {
cJSON *body = read_body(req);
if (!body) {
return ESP_OK;
}
const cJSON *pid = cJSON_GetObjectItem(body, "preset_id");
const cJSON *drv = cJSON_GetObjectItem(body, "drivers");
char key[24] = "";
if (cJSON_IsString(pid)) {
snprintf(key, sizeof(key), "%s", pid->valuestring);
} else if (cJSON_IsNumber(pid)) {
snprintf(key, sizeof(key), "%d", (int)pid->valuedouble);
}
// The UI sends drivers:false when it pushes to drivers itself; v2 has no pixel outputs
bool skip = cJSON_IsFalse(drv);
cJSON_Delete(body);
if (!key[0]) {
return send_error(req, "400 Bad Request", "preset_id required");
}
return result(req, skip ? ESP_OK : engine_play(seg[1], key), "Playing");
}
if (!strcmp(seg[2], "stop")) {
return result(req, engine_stop(seg[1]), "Stopped");
}
}
if (n == 3 && method == HTTP_POST && !strcmp(seg[0], "sequences")) {
if (!strcmp(seg[2], "play")) {
return result(req, engine_seq_play(seg[1]), "Sequence started");
}
if (!strcmp(seg[2], "stop")) {
return result(req, engine_seq_stop(seg[1]), "Sequence stopped");
}
}
if (n == 3 && method == HTTP_POST && !strcmp(seg[0], "scenes")) {
if (!strcmp(seg[2], "play")) {
return result(req, engine_scene_play(seg[1]), "Scene started");
}
if (!strcmp(seg[2], "stop")) {
return result(req, engine_scene_stop(seg[1]), "Scene stopped");
}
}
if (n == 2 && method == HTTP_GET && !strcmp(seg[0], "sequences") && !strcmp(seg[1], "status")) {
return send_json(req, "200 OK", engine_status(), true);
}
if (n == 3) {
if (is_profiles && method == HTTP_POST) {
return handle_profile_action(req, seg[1], seg[2]);
}
return not_implemented(req, seg[2]);
}
// /presets/send, /presets/push
if (is_presets && n == 2 && method == HTTP_POST && !strcmp(seg[1], "push")) {
cJSON *body = read_body(req);
if (!body) {
return ESP_OK;
}
const cJSON *seq = cJSON_GetObjectItem(body, "sequence");
const cJSON *payload = cJSON_GetObjectItem(body, "payload");
cJSON *one = NULL;
if (!cJSON_IsArray(seq) && payload) {
one = cJSON_CreateArray();
cJSON_AddItemReferenceToArray(one, (cJSON *)payload);
seq = one;
}
esp_err_t err = ESP_ERR_INVALID_ARG;
if (cJSON_IsArray(seq) && cJSON_GetArraySize(seq)) {
err = engine_push(seq, cJSON_GetObjectItem(body, "targets"));
}
cJSON_Delete(one);
cJSON_Delete(body);
return err == ESP_ERR_INVALID_ARG ? send_error(req, "400 Bad Request", "sequence or payload required")
: result(req, err, "Delivered");
}
if (is_presets && n == 2 && method == HTTP_POST && !strcmp(seg[1], "send")) {
cJSON *body = read_body(req);
if (!body) {
return ESP_OK;
}
const cJSON *ids = cJSON_GetObjectItem(body, "preset_ids");
if (!cJSON_IsArray(ids)) {
ids = cJSON_GetObjectItem(body, "ids");
}
if (!cJSON_IsArray(ids) || !cJSON_GetArraySize(ids)) {
cJSON_Delete(body);
return send_error(req, "400 Bad Request", "preset_ids must be a non-empty list");
}
const cJSON *save = cJSON_GetObjectItem(body, "save");
const cJSON *def = cJSON_GetObjectItem(body, "default");
char defbuf[24] = "";
if (cJSON_IsString(def)) {
snprintf(defbuf, sizeof(defbuf), "%s", def->valuestring);
} else if (cJSON_IsNumber(def)) {
snprintf(defbuf, sizeof(defbuf), "%d", (int)def->valuedouble);
}
const cJSON *targets = cJSON_GetObjectItem(body, "targets");
cJSON *single = NULL;
const cJSON *dest = cJSON_GetObjectItem(body, "destination_mac");
if (!cJSON_IsArray(targets) && cJSON_IsString(dest)) {
single = cJSON_CreateArray();
cJSON_AddItemToArray(single, cJSON_CreateString(dest->valuestring));
targets = single;
}
int sent = 0;
esp_err_t err = engine_send_presets(ids, !save || cJSON_IsTrue(save), defbuf[0] ? defbuf : NULL, targets, &sent);
cJSON_Delete(single);
cJSON_Delete(body);
if (err != ESP_OK) {
return result(req, err, "");
}
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "message", "Presets sent");
cJSON_AddNumberToObject(o, "presets_sent", sent);
return send_json(req, "200 OK", o, true);
}
// "current" profile aliases
const char *id = n == 2 ? seg[1] : NULL;
if (is_profiles && id && strcmp(id, "current") == 0) {
id = current_profile();
if (!id) {
return send_error(req, "404 Not Found", "no profiles");
}
if (method == HTTP_GET) {
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "id", id);
cJSON_AddItemReferenceToObject(o, "profile", cJSON_GetObjectItem(all, id));
return send_json(req, "200 OK", o, true);
}
}
if (!id) {
if (method == HTTP_GET) {
if (is_profiles) {
cJSON *o = cJSON_CreateObject();
cJSON_AddItemReferenceToObject(o, "profiles", all);
const char *cur = current_profile();
cJSON_AddStringToObject(o, "current_profile_id", cur ? cur : "");
return send_json(req, "200 OK", o, true);
}
if (is_presets) {
cJSON *o = cJSON_CreateObject(), *it;
cJSON_ArrayForEach(it, all)
{
if (preset_in_profile(it)) {
cJSON_AddItemReferenceToObject(o, it->string, it);
}
}
return send_json(req, "200 OK", o, true);
}
return send_json(req, "200 OK", all, false);
}
if (method == HTTP_POST) {
cJSON *body = read_body(req);
if (!body) {
return ESP_OK;
}
char nid[16];
store_next_id(coll, nid, sizeof(nid));
cJSON_AddStringToObject(body, "id", nid);
if (is_presets && current_profile() && !cJSON_GetObjectItem(body, "profile_id")) {
cJSON_AddStringToObject(body, "profile_id", current_profile());
}
cJSON_AddItemToObject(all, nid, body);
store_save(coll);
if (!strcmp(coll, "zone") || !strcmp(coll, "device")) {
engine_groups_changed();
}
cJSON *o = cJSON_CreateObject();
cJSON_AddItemReferenceToObject(o, nid, body);
return send_json(req, "201 Created", o, true);
}
return send_error(req, "405 Method Not Allowed", "method not allowed");
}
cJSON *rec = cJSON_GetObjectItem(all, id);
if (!rec || (is_presets && !preset_in_profile(rec))) {
return send_error(req, "404 Not Found", "not found");
}
switch (method) {
case HTTP_GET:
return send_json(req, "200 OK", rec, false);
case HTTP_PUT: {
cJSON *body = read_body(req);
if (!body) {
return ESP_OK;
}
cJSON *dev_cfg = !strcmp(coll, "device") ? device_config_from(body) : NULL;
merge(rec, body);
cJSON_Delete(body);
store_save(coll);
if (dev_cfg) {
push_device_config(rec, dev_cfg); // before the group resend: a second message right behind another may not be delivered
}
if (!strcmp(coll, "zone") || !strcmp(coll, "device")) {
engine_groups_changed();
}
return send_json(req, "200 OK", rec, false);
}
case HTTP_DELETE: {
cJSON_DeleteItemFromObject(all, id);
store_save(coll);
if (!strcmp(coll, "zone") || !strcmp(coll, "device")) {
engine_groups_changed();
}
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "message", "Deleted");
return send_json(req, "200 OK", o, true);
}
default:
return send_error(req, "405 Method Not Allowed", "method not allowed");
}
}
static esp_err_t settings_handler_inner(httpd_req_t *req)
{
char seg[3][64];
int n = split_path(req->uri, seg);
if (n == 2 && strcmp(seg[1], "page") == 0 && req->method == HTTP_GET) {
return web_send_page(req, "settings.html");
}
if (n == 1 && req->method == HTTP_GET) {
return send_json(req, "200 OK", store_settings(), false);
}
if (n == 2 && strcmp(seg[1], "settings") == 0 && req->method == HTTP_PUT) {
cJSON *body = read_body(req);
if (!body) {
return ESP_OK;
}
merge(store_settings(), body);
cJSON_Delete(body);
store_save("settings");
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "message", "Settings updated successfully");
return send_json(req, "200 OK", o, true);
}
return not_implemented(req, "this settings route");
}
// GET /db/<name> exports a collection, PUT /db/<name> replaces it (import of the Pi's db/*.json)
static esp_err_t db_handler_inner(httpd_req_t *req)
{
char seg[3][64];
int n = split_path(req->uri, seg);
if (n != 2 || !store_known(seg[1])) {
return send_error(req, "404 Not Found", "unknown collection");
}
if (req->method == HTTP_GET) {
return send_json(req, "200 OK", store_coll(seg[1]), false);
}
if (req->method == HTTP_PUT) {
cJSON *body = read_body(req);
if (!body) {
return ESP_OK;
}
if (store_replace(seg[1], body) != ESP_OK) {
return send_error(req, "500 Internal Server Error", "save failed");
}
cJSON *o = cJSON_CreateObject();
cJSON_AddNumberToObject(o, "records", cJSON_GetArraySize(store_coll(seg[1])));
return send_json(req, "200 OK", o, true);
}
return send_error(req, "405 Method Not Allowed", "method not allowed");
}
#define LOCKED(name) \
static esp_err_t name(httpd_req_t *req) \
{ \
store_lock(); \
esp_err_t r = name##_inner(req); \
store_unlock(); \
return r; \
}
LOCKED(collection_handler)
LOCKED(settings_handler)
LOCKED(db_handler)
// Bench tests: /test/loss and /test/beats
static esp_err_t test_handler_inner(httpd_req_t *req)
{
char seg[3][64];
int n = split_path(req->uri, seg);
if (n >= 2 && !strcmp(seg[1], "loss")) {
if (req->method == HTTP_POST) {
cJSON *b = read_body(req);
if (!b) {
return ESP_OK;
}
const cJSON *p = cJSON_GetObjectItem(b, "percent"), *beats = cJSON_GetObjectItem(b, "beats");
espnow_tx_set_loss(cJSON_IsNumber(p) ? (int)p->valuedouble : 0, !cJSON_IsFalse(beats));
cJSON_Delete(b);
}
bool inc;
int pct = espnow_tx_loss(&inc);
cJSON *o = cJSON_CreateObject();
cJSON_AddNumberToObject(o, "percent", pct);
cJSON_AddBoolToObject(o, "beats", inc);
return send_json(req, "200 OK", o, true);
}
if (n >= 2 && !strcmp(seg[1], "beats")) {
if (req->method == HTTP_POST && n == 3 && !strcmp(seg[2], "stop")) {
bench_stop();
} else if (req->method == HTTP_POST) {
cJSON *b = read_body(req);
if (!b) {
return ESP_OK;
}
const cJSON *bpm = cJSON_GetObjectItem(b, "bpm"), *count = cJSON_GetObjectItem(b, "count");
esp_err_t err = bench_start(cJSON_IsNumber(bpm) ? (float)bpm->valuedouble : 120,
cJSON_IsNumber(count) ? (int)count->valuedouble : 100);
cJSON_Delete(b);
if (err != ESP_OK) {
return send_error(req, "400 Bad Request", "bpm must be 30-300");
}
}
return send_json(req, "200 OK", bench_results(), true);
}
return send_error(req, "404 Not Found", "unknown test");
}
LOCKED(test_handler)
esp_err_t api_register(httpd_handle_t server)
{
static const char *const ROUTES[] = {
"/devices*", "/zones*", "/presets*", "/profiles*", "/palettes*",
"/patterns*", "/sequences*", "/scenes*", "/groups*", "/outputs*",
};
static const httpd_method_t METHODS[] = { HTTP_GET, HTTP_POST, HTTP_PUT, HTTP_DELETE };
for (size_t r = 0; r < sizeof(ROUTES) / sizeof(ROUTES[0]); r++) {
for (size_t m = 0; m < 4; m++) {
httpd_uri_t u = { .uri = ROUTES[r], .method = METHODS[m], .handler = collection_handler };
ESP_ERROR_CHECK_WITHOUT_ABORT(httpd_register_uri_handler(server, &u));
}
}
for (size_t m = 0; m < 4; m++) {
httpd_uri_t t = { .uri = "/test/*", .method = METHODS[m], .handler = test_handler };
ESP_ERROR_CHECK_WITHOUT_ABORT(httpd_register_uri_handler(server, &t));
}
for (size_t m = 0; m < 4; m++) {
httpd_uri_t s = { .uri = "/settings*", .method = METHODS[m], .handler = settings_handler };
httpd_uri_t d = { .uri = "/db/*", .method = METHODS[m], .handler = db_handler };
ESP_ERROR_CHECK_WITHOUT_ABORT(httpd_register_uri_handler(server, &s));
ESP_ERROR_CHECK_WITHOUT_ABORT(httpd_register_uri_handler(server, &d));
}
ESP_LOGI(TAG, "API registered");
return ESP_OK;
}
+8
View File
@@ -0,0 +1,8 @@
#pragma once
#include "esp_err.h"
#include "esp_http_server.h"
// Register the JSON API (CRUD over the store collections, profiles, settings,
// /db import and export). Actions that need the engine answer 501 for now.
esp_err_t api_register(httpd_handle_t server);
+227
View File
@@ -0,0 +1,227 @@
/*
* Live audio and beat endpoints: /audio.wav (16 kHz mono PCM stream), /beats (server-sent events from the
* beat detector), POST /tap (correct the bar position), /time (board clock). Ported from esp32-eth.
*/
#include "audio.h"
#include <stdio.h>
#include <string.h>
#include "beat.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "lwip/sockets.h"
#include "mic.h"
static const char *TAG = "audio";
static void wav_header(uint8_t h[44])
{
const uint32_t rate = MIC_SAMPLE_RATE, byte_rate = MIC_SAMPLE_RATE * 2, unknown = 0xFFFFFFFF;
const uint16_t pcm = 1, channels = 1, block_align = 2, bits = 16;
const uint32_t fmt_len = 16;
memcpy(h, "RIFF", 4); memcpy(h + 4, &unknown, 4);
memcpy(h + 8, "WAVEfmt ", 8); memcpy(h + 16, &fmt_len, 4);
memcpy(h + 20, &pcm, 2); memcpy(h + 22, &channels, 2);
memcpy(h + 24, &rate, 4); memcpy(h + 28, &byte_rate, 4);
memcpy(h + 32, &block_align, 2); memcpy(h + 34, &bits, 2);
memcpy(h + 36, "data", 4); memcpy(h + 40, &unknown, 4);
}
// httpd_send may write only part of the buffer; keep going until done
static bool send_all(httpd_req_t *req, const void *data, size_t len)
{
const char *p = data;
while (len > 0) {
int sent = httpd_send(req, p, len);
if (sent <= 0) {
return false;
}
p += sent;
len -= sent;
}
return true;
}
static void audio_stream_task(void *arg)
{
httpd_req_t *req = arg;
httpd_handle_t server = req->handle;
int fd = httpd_req_to_sockfd(req);
static uint8_t buf[1024];
// Send each 20 ms block immediately instead of letting Nagle batch them
int one = 1;
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
// Raw (non-chunked) response: chunked encoding splits every block into
// three tiny TCP segments, which fills lwIP's send queue and stalls on
// the client's delayed ACKs. One segment per block avoids that.
static const char http_hdr[] =
"HTTP/1.1 200 OK\r\n"
"Content-Type: audio/wav\r\n"
"Cache-Control: no-store\r\n"
"Connection: close\r\n\r\n";
uint8_t head[sizeof(http_hdr) - 1 + 44];
memcpy(head, http_hdr, sizeof(http_hdr) - 1);
wav_header(head + sizeof(http_hdr) - 1);
bool ok = send_all(req, head, sizeof(head));
ESP_LOGI(TAG, "Audio listener connected");
while (ok) {
size_t n = mic_stream_read(buf, sizeof(buf), pdMS_TO_TICKS(1000));
if (n > 0) {
ok = send_all(req, buf, n);
}
}
mic_stream_close();
ESP_LOGI(TAG, "Audio listener disconnected");
httpd_req_async_handler_complete(req);
httpd_sess_trigger_close(server, fd);
vTaskDelete(NULL);
}
static esp_err_t audio_get_handler(httpd_req_t *req)
{
if (mic_stream_open() != ESP_OK) {
httpd_resp_set_status(req, "409 Conflict");
return httpd_resp_sendstr(req, "Another listener is already connected\n");
}
// Stream from our own task so the server keeps answering /status
httpd_req_t *async_req = NULL;
if (httpd_req_async_handler_begin(req, &async_req) != ESP_OK) {
mic_stream_close();
return ESP_FAIL;
}
if (xTaskCreate(audio_stream_task, "audio_http", 4096, async_req, 5, NULL) != pdPASS) {
mic_stream_close();
httpd_req_async_handler_complete(async_req);
return ESP_FAIL;
}
return ESP_OK;
}
// Board clock for the page to line its own clock up with (esp_timer, us)
static esp_err_t time_get_handler(httpd_req_t *req)
{
char buf[48];
snprintf(buf, sizeof(buf), "{\"us\":%lld}", (long long)esp_timer_get_time());
httpd_resp_set_type(req, "application/json");
httpd_resp_set_hdr(req, "Cache-Control", "no-store");
return httpd_resp_sendstr(req, buf);
}
static esp_err_t tap_post_handler(httpd_req_t *req)
{
beat_tap();
httpd_resp_set_type(req, "application/json");
return httpd_resp_sendstr(req, "{\"ok\":true}");
}
#define BEAT_QUEUE_LEN 16
static void beats_stream_task(void *arg)
{
httpd_req_t *req = arg;
httpd_handle_t server = req->handle;
int fd = httpd_req_to_sockfd(req);
QueueHandle_t q = xQueueCreate(BEAT_QUEUE_LEN, sizeof(beat_event_t));
char msg[160];
int one = 1;
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
static const char http_hdr[] =
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/event-stream\r\n"
"Cache-Control: no-store\r\n"
"Connection: close\r\n\r\n";
bool ok = q && beat_subscribe(q) == ESP_OK;
if (!ok) {
static const char busy[] =
"HTTP/1.1 503 Service Unavailable\r\nConnection: close\r\n\r\nToo many beat listeners\n";
send_all(req, busy, sizeof(busy) - 1);
} else {
ok = send_all(req, http_hdr, sizeof(http_hdr) - 1);
ESP_LOGI(TAG, "Beat listener connected");
}
// Tempo goes out once a second even without beats, which also notices
// when the client has gone away
int64_t next_tempo = 0;
while (ok) {
int64_t now = esp_timer_get_time();
if (now >= next_tempo) {
beat_info_t b;
beat_get_info(&b);
int n = snprintf(msg, sizeof(msg),
"event: tempo\ndata: {\"bpm\":%.1f,\"confidence\":%.2f,\"locked\":%s,\"beats\":%lu}\n\n",
b.bpm, b.confidence, b.locked ? "true" : "false", (unsigned long)b.beat_count);
ok = send_all(req, msg, n);
next_tempo = now + 1000000;
continue;
}
beat_event_t ev;
TickType_t wait = pdMS_TO_TICKS((next_tempo - now) / 1000) + 1;
if (xQueueReceive(q, &ev, wait) != pdTRUE) {
continue;
}
int n;
if (ev == BEAT_EVENT_BEAT) {
beat_info_t b;
beat_get_info(&b);
n = snprintf(msg, sizeof(msg),
"event: beat\ndata: {\"bpm\":%.1f,\"n\":%lu,\"bar\":%d,\"meter\":%d,\"sure\":%s,\"us\":%lld}\n\n",
b.bpm, (unsigned long)b.beat_count, b.bar_beat, b.meter, b.bar_sure ? "true" : "false",
(long long)b.last_beat_us);
} else {
n = snprintf(msg, sizeof(msg), "event: onset\ndata: {}\n\n");
}
ok = send_all(req, msg, n);
}
if (q) {
beat_unsubscribe(q);
vQueueDelete(q);
}
ESP_LOGI(TAG, "Beat listener disconnected");
httpd_req_async_handler_complete(req);
httpd_sess_trigger_close(server, fd);
vTaskDelete(NULL);
}
static esp_err_t beats_get_handler(httpd_req_t *req)
{
// Long-lived like /audio.wav, so it gets its own task too
httpd_req_t *async_req = NULL;
if (httpd_req_async_handler_begin(req, &async_req) != ESP_OK) {
return ESP_FAIL;
}
if (xTaskCreate(beats_stream_task, "beats_http", 4096, async_req, 5, NULL) != pdPASS) {
httpd_req_async_handler_complete(async_req);
return ESP_FAIL;
}
return ESP_OK;
}
esp_err_t audio_register(httpd_handle_t server)
{
const httpd_uri_t uris[] = {
{ .uri = "/audio.wav", .method = HTTP_GET, .handler = audio_get_handler },
{ .uri = "/beats", .method = HTTP_GET, .handler = beats_get_handler },
{ .uri = "/tap", .method = HTTP_POST, .handler = tap_post_handler },
{ .uri = "/time", .method = HTTP_GET, .handler = time_get_handler },
};
for (size_t i = 0; i < sizeof(uris) / sizeof(uris[0]); i++) {
esp_err_t err = httpd_register_uri_handler(server, &uris[i]);
if (err != ESP_OK) {
ESP_LOGE(TAG, "register %s: %s", uris[i].uri, esp_err_to_name(err));
return err;
}
}
return ESP_OK;
}
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include "esp_err.h"
#include "esp_http_server.h"
// Register /audio.wav, /beats, /tap and /time (the page at /audio uses them)
esp_err_t audio_register(httpd_handle_t server);
+203
View File
@@ -0,0 +1,203 @@
/*
* Beat detection glue: runs beat_dsp on the mic feed, pulses the beat LED
* (longer on the downbeat), keeps the latest tempo and bar position for
* /status and fans events out to SSE listeners.
*/
#include <math.h>
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/semphr.h"
#include "esp_log.h"
#include "esp_check.h"
#include "esp_timer.h"
#include "driver/gpio.h"
#include "beat_dsp.h"
#include "beat.h"
#define MAX_SUBSCRIBERS 4
#define LOG_EVERY_BEATS 64
static const char *TAG = "beat";
static beat_dsp_t s_dsp; // ~10 KB, too big for the mic task's stack
static portMUX_TYPE s_lock = portMUX_INITIALIZER_UNLOCKED;
static beat_info_t s_info;
// Queue sends may yield, so the subscriber list gets a mutex, not s_lock
static SemaphoreHandle_t s_subs_mutex;
static QueueHandle_t s_subs[MAX_SUBSCRIBERS];
static esp_timer_handle_t s_led_timer;
static bool s_was_locked;
static int64_t s_tap_us; // pending tap time, 0 if none (guarded by s_lock)
static void led_set(bool on)
{
#if CONFIG_BEAT_LED_GPIO >= 0
#if CONFIG_BEAT_LED_ACTIVE_LOW
on = !on;
#endif
gpio_set_level(CONFIG_BEAT_LED_GPIO, on);
#endif
}
static void led_off_cb(void *arg)
{
led_set(false);
}
static beat_cb_t s_cb;
void beat_set_callback(beat_cb_t cb)
{
s_cb = cb;
}
static void publish(beat_event_t ev)
{
xSemaphoreTake(s_subs_mutex, portMAX_DELAY);
for (int i = 0; i < MAX_SUBSCRIBERS; i++) {
if (s_subs[i]) {
// A slow listener just misses events rather than stalling audio
xQueueSend(s_subs[i], &ev, 0);
}
}
xSemaphoreGive(s_subs_mutex);
}
static void dsp_event(void *ctx, int events, const beat_dsp_t *d)
{
int64_t now = esp_timer_get_time();
beat_info_t info;
portENTER_CRITICAL(&s_lock);
if (events & BEAT_EV_ONSET) {
s_info.onset_count++;
s_info.last_onset_us = now;
}
if (events & BEAT_EV_BEAT) {
s_info.beat_count++;
s_info.last_beat_us = now;
s_info.meter = d->meter;
s_info.bar_beat = d->bar_beat;
s_info.bar_sure = d->bar_sure;
}
if (events & BEAT_EV_DOWNBEAT) {
s_info.downbeat_count++;
}
info = s_info;
portEXIT_CRITICAL(&s_lock);
if (events & BEAT_EV_ONSET) {
publish(BEAT_EVENT_ONSET);
}
if (events & BEAT_EV_BEAT) {
if (s_cb) {
s_cb(&info, beat_dsp_bpm(d), (events & BEAT_EV_DOWNBEAT) != 0);
}
led_set(true);
esp_timer_stop(s_led_timer);
int pulse_ms = events & BEAT_EV_DOWNBEAT ? CONFIG_BEAT_LED_DOWNBEAT_MS : CONFIG_BEAT_LED_PULSE_MS;
esp_timer_start_once(s_led_timer, pulse_ms * 1000);
publish(BEAT_EVENT_BEAT);
if (info.beat_count % LOG_EVERY_BEATS == 0) {
ESP_LOGI(TAG, "%.1f BPM, confidence %.2f, %lu beats, %d/4 time, bar contrast %.2f",
beat_dsp_bpm(d), d->confidence, (unsigned long)info.beat_count, d->meter, d->bar_contrast);
}
}
}
esp_err_t beat_start(float sample_rate)
{
float gate_rms = powf(10.0f, CONFIG_BEAT_GATE_DBFS / 20.0f);
beat_dsp_init(&s_dsp, sample_rate, gate_rms, CONFIG_BEAT_LEAD_MS / 1000.0f);
s_info.meter = s_dsp.meter;
s_subs_mutex = xSemaphoreCreateMutex();
ESP_RETURN_ON_FALSE(s_subs_mutex, ESP_ERR_NO_MEM, TAG, "Mutex alloc failed");
#if CONFIG_BEAT_LED_GPIO >= 0
gpio_config_t io = {
.pin_bit_mask = 1ULL << CONFIG_BEAT_LED_GPIO,
.mode = GPIO_MODE_OUTPUT,
};
ESP_RETURN_ON_ERROR(gpio_config(&io), TAG, "LED GPIO config failed");
#endif
led_set(false);
const esp_timer_create_args_t timer_args = { .callback = led_off_cb, .name = "beat_led" };
ESP_RETURN_ON_ERROR(esp_timer_create(&timer_args, &s_led_timer), TAG, "LED timer create failed");
ESP_LOGI(TAG, "Beat detection on, %.1f onset frames/s, gate %d dBFS",
s_dsp.frame_rate, CONFIG_BEAT_GATE_DBFS);
return ESP_OK;
}
void beat_tap(void)
{
portENTER_CRITICAL(&s_lock);
s_tap_us = esp_timer_get_time();
portEXIT_CRITICAL(&s_lock);
}
void beat_feed(const float *x, size_t n)
{
beat_dsp_feed(&s_dsp, x, n, dsp_event, NULL);
// Taps arrive from the HTTP task; apply them here, in the detector's task
portENTER_CRITICAL(&s_lock);
int64_t tap_us = s_tap_us;
s_tap_us = 0;
portEXIT_CRITICAL(&s_lock);
if (tap_us) {
// The newest analysed frame is ~30 ms behind real time (capture block
// plus half the FFT window), so the tap is that much further back
float ago_s = (esp_timer_get_time() - tap_us) / 1e6f + 0.03f;
beat_dsp_tap(&s_dsp, ago_s * s_dsp.frame_rate);
ESP_LOGI(TAG, "Tap: beat 1 set, holding the bar for a while");
}
portENTER_CRITICAL(&s_lock);
s_info.bpm = beat_dsp_bpm(&s_dsp);
s_info.confidence = s_dsp.confidence;
s_info.locked = s_dsp.locked;
portEXIT_CRITICAL(&s_lock);
if (s_dsp.locked != s_was_locked) {
s_was_locked = s_dsp.locked;
if (s_was_locked) {
ESP_LOGI(TAG, "Locked at %.1f BPM (confidence %.2f)", beat_dsp_bpm(&s_dsp), s_dsp.confidence);
} else {
ESP_LOGI(TAG, "Lost the beat");
}
}
}
void beat_get_info(beat_info_t *out)
{
portENTER_CRITICAL(&s_lock);
*out = s_info;
portEXIT_CRITICAL(&s_lock);
}
esp_err_t beat_subscribe(QueueHandle_t q)
{
esp_err_t ret = ESP_ERR_NO_MEM;
xSemaphoreTake(s_subs_mutex, portMAX_DELAY);
for (int i = 0; i < MAX_SUBSCRIBERS; i++) {
if (!s_subs[i]) {
s_subs[i] = q;
ret = ESP_OK;
break;
}
}
xSemaphoreGive(s_subs_mutex);
return ret;
}
void beat_unsubscribe(QueueHandle_t q)
{
// Once this returns the queue is no longer touched and can be deleted
xSemaphoreTake(s_subs_mutex, portMAX_DELAY);
for (int i = 0; i < MAX_SUBSCRIBERS; i++) {
if (s_subs[i] == q) {
s_subs[i] = NULL;
}
}
xSemaphoreGive(s_subs_mutex);
}
+49
View File
@@ -0,0 +1,49 @@
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "esp_err.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
typedef struct {
float bpm; // 0 until a tempo has been found
float confidence; // 0..1, how periodic the onsets are
bool locked; // beats are being emitted
uint32_t beat_count;
int64_t last_beat_us; // esp_timer time of the last beat, 0 if none
int meter; // beats per bar, 3 or 4
int bar_beat; // 1..meter of the last beat (best guess), 0 early on
bool bar_sure; // bar_beat is reliable, downbeats are being flashed
uint32_t downbeat_count;
uint32_t onset_count;
int64_t last_onset_us;
} beat_info_t;
// Event codes posted to subscriber queues
typedef enum {
BEAT_EVENT_ONSET,
BEAT_EVENT_BEAT,
} beat_event_t;
// Set up the detector and beat LED; call before feeding audio
esp_err_t beat_start(float sample_rate);
// Feed DC-free mono samples at full scale +/-1 (called from the mic task)
void beat_feed(const float *x, size_t n);
void beat_get_info(beat_info_t *out);
// The user tapped beat 1 just now: correct the bar position to match
void beat_tap(void);
// Have beat_event_t values posted (without blocking) to a queue of
// beat_event_t. Returns ESP_ERR_NO_MEM when all subscriber slots are taken.
esp_err_t beat_subscribe(QueueHandle_t q);
void beat_unsubscribe(QueueHandle_t q);
// Called from the audio task the moment a beat is emitted, before any queue
// fan-out, so the radio can send it with minimal delay. Must not block.
typedef void (*beat_cb_t)(const beat_info_t *info, float bpm, bool downbeat);
void beat_set_callback(beat_cb_t cb);
+532
View File
@@ -0,0 +1,532 @@
/*
* Realtime beat tracker.
*
* 1. Onsets: every 16 ms, Hann-windowed 512-point FFT; novelty is the
* half-wave rectified rise in log magnitude (spectral flux) plus the rise
* in bass power. Log flux catches every instrument but rates a faint hat
* like a loud kick; the uncompressed bass term keeps the kick on the beat.
* 2. Tempo: every ~0.5 s, autocorrelate the last ~8 s of log flux alone
* (bass would pull rock with kicks on 1 and 3 to half time), weight
* lags with a log-normal prior around 120 BPM, and add the 2x lag so the
* bar-level pulse backs up the beat. A new tempo has to clearly beat the
* current one, several times in a row, before it is taken.
* 3. Phase: every frame, find the offset whose comb of past beat positions
* collects the most novelty. When that offset wraps back to zero a beat is
* due, so beats keep coming through quiet bars instead of only on onsets.
* 4. Lock: beats only go out while autocorrelation confidence times phase
* salience (on-grid vs. average onset energy) is high. Speech and noise
* can score on one of them but not both. Tuned on real music clips.
* 5. Bar: each grid beat gets two downbeat cues, the bass hit on it and how
* much new spectral energy its beat brings over the one before (chords
* change on the one). Cues are averaged per bar position
* for 3/4 and 4/4; the meter whose positions differ most wins, and its
* strongest position is the downbeat.
*/
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "beat_dsp.h"
#define NV_MASK (BEAT_NV_LEN - 1)
#define FLUX_MAX_BIN 192 // ~6 kHz; above that is mostly hats and hiss
#define BASS_MAX_BIN 6 // <~190 Hz, kick drums
#define BASS_WEIGHT 1.0f // bass power rise vs. full-band log flux
#define LOG_GAMMA 100.0f // log(1 + g*|X|) compression
#define TEMPO_EVERY 32 // frames between tempo estimates
#define TEMPO_MIN_EXTRA 128 // history beyond the longest lag before estimating
#define PRIOR_BPM 120.0f
#define PRIOR_OCTAVES 1.0f // std dev of the tempo prior
#define TEMPO_TOL 0.06f // relative change treated as the same tempo
#define TEMPO_MEMORY_S 3.0f // time constant of the history fade
#define TEMPO_MARGIN 1.5f // a new tempo must score this much better
#define TEMPO_SWITCH 3 // estimates in a row needed to jump tempo
#define COMB_BEATS 6 // past beats the phase comb looks at
#define COMB_DECAY 0.88f
#define PHASE_STICK 1.3f // bonus for the phase that follows on
#define LOCK_STRENGTH 0.9f // confidence x salience to start emitting beats
#define UNLOCK_STRENGTH 0.5f // ...and to keep going
#define ONSET_K 1.5f // onset threshold, x running novelty mean
#define ONSET_GAP_S 0.1f
#define SALIENCE_S 2.0f // smoothing of the on-beat energy ratio
#define ACTIVE_HOLD_S 2.0f // keep beating this long into silence
#define KICK_WEIGHT 1.0f // downbeat cue: bass hit on the beat
#define CHANGE_WEIGHT 1.0f // downbeat cue: spectral change into the beat
#define SPAN_FRAC 1.0f // part of each beat compared for harmonic change
#define BAR_RATE 0.08f // per-bar update rate of the position scores
#define BAR_MARGIN 1.1f // a new downbeat position must score this much more
#define METER_MARGIN 1.5f // ...and a new meter must stand out this much more
#define METER3_BIAS 0.5f // weight on the 3/4 evidence
#define BAR_SURE_ON 0.3f // contrast to call the bar position sure
#define BAR_SURE_OFF 0.2f // ...and to stop
#define BAR_WARMUP 8 // grid beats before guessing a bar position
#define TAP_BOOST 2.0f // head start for a tapped beat 1, x the best score
#define TAP_HOLD_BARS 16 // bars a tap holds the bar position
static float s_window[BEAT_FFT_SIZE];
static float s_cos[BEAT_FFT_SIZE / 2], s_sin[BEAT_FFT_SIZE / 2];
static uint16_t s_bitrev[BEAT_FFT_SIZE];
static int8_t s_band[FLUX_MAX_BIN + 1]; // bin -> band, -1 if unused
static float s_band_w[BEAT_BANDS]; // 1 / bins in band
static const int s_meters[BEAT_METERS] = {3, 4};
static bool s_tables_ready;
static void init_tables(void)
{
if (s_tables_ready) {
return;
}
const int n = BEAT_FFT_SIZE;
int bits = 0;
while ((1 << bits) < n) {
bits++;
}
for (int i = 0; i < n; i++) {
s_window[i] = 0.5f - 0.5f * cosf(2.0f * (float)M_PI * i / n);
int r = 0;
for (int b = 0; b < bits; b++) {
r |= ((i >> b) & 1) << (bits - 1 - b);
}
s_bitrev[i] = r;
}
for (int i = 0; i < n / 2; i++) {
s_cos[i] = cosf(2.0f * (float)M_PI * i / n);
s_sin[i] = -sinf(2.0f * (float)M_PI * i / n);
}
// Bands spaced evenly in log frequency from bin 2 (~60 Hz) up
int count[BEAT_BANDS] = {0};
for (int k = 0; k <= FLUX_MAX_BIN; k++) {
int b = k < 2 ? -1 : (int)(BEAT_BANDS * logf(k / 2.0f) / logf(FLUX_MAX_BIN / 2.0f));
s_band[k] = b < 0 ? -1 : b >= BEAT_BANDS ? BEAT_BANDS - 1 : b;
if (s_band[k] >= 0) {
count[s_band[k]]++;
}
}
for (int b = 0; b < BEAT_BANDS; b++) {
s_band_w[b] = count[b] ? 1.0f / count[b] : 0.0f;
}
s_tables_ready = true;
}
// In-place iterative radix-2 complex FFT
static void fft(float *re, float *im)
{
const int n = BEAT_FFT_SIZE;
for (int i = 0; i < n; i++) {
int j = s_bitrev[i];
if (j > i) {
float t = re[i]; re[i] = re[j]; re[j] = t;
t = im[i]; im[i] = im[j]; im[j] = t;
}
}
for (int len = 2; len <= n; len <<= 1) {
int half = len >> 1, step = n / len;
for (int start = 0; start < n; start += len) {
for (int k = 0; k < half; k++) {
float wr = s_cos[k * step], wi = s_sin[k * step];
int a = start + k, b = a + half;
float tr = re[b] * wr - im[b] * wi;
float ti = re[b] * wi + im[b] * wr;
re[b] = re[a] - tr; im[b] = im[a] - ti;
re[a] += tr; im[a] += ti;
}
}
}
}
static inline float nv_at(const beat_dsp_t *d, uint32_t i)
{
return d->nv[i & NV_MASK];
}
// Onsets can land a frame either side of the beat grid
static inline float nv_max3(const beat_dsp_t *d, uint32_t i, uint32_t cur)
{
float v = fmaxf(nv_at(d, i), nv_at(d, i - 1));
return i < cur ? fmaxf(v, nv_at(d, i + 1)) : v;
}
void beat_dsp_init(beat_dsp_t *d, float sample_rate, float gate_rms, float lead_s)
{
init_tables();
memset(d, 0, sizeof(*d));
d->frame_rate = sample_rate / BEAT_HOP;
d->gate_rms = gate_rms;
d->lead_frames = (int)lrintf(lead_s * d->frame_rate);
d->min_lag = (int)floorf(d->frame_rate * 60.0f / BEAT_MAX_BPM);
d->max_lag = (int)ceilf(d->frame_rate * 60.0f / BEAT_MIN_BPM);
// Start half a window in so the first frame comes after one hop
d->in_fill = BEAT_FFT_SIZE - BEAT_HOP;
d->meter = 4;
}
static float onset_strength(beat_dsp_t *d, bool *active, float *tempo_nv, float *bass_nv)
{
float sum_sq = 0.0f;
for (int i = 0; i < BEAT_FFT_SIZE; i++) {
float x = d->in[i];
sum_sq += x * x;
d->re[i] = x * s_window[i];
d->im[i] = 0.0f;
}
*active = sqrtf(sum_sq / BEAT_FFT_SIZE) >= d->gate_rms;
fft(d->re, d->im);
float flux = 0.0f, bass = 0.0f;
memset(d->band_now, 0, sizeof(d->band_now));
for (int k = 1; k <= FLUX_MAX_BIN; k++) {
float mag2 = d->re[k] * d->re[k] + d->im[k] * d->im[k];
float l = log1pf(LOG_GAMMA * sqrtf(mag2));
flux += fmaxf(l - d->prev_log[k], 0.0f);
d->prev_log[k] = l;
if (s_band[k] >= 0) {
d->band_now[s_band[k]] += l * s_band_w[s_band[k]];
}
if (k <= BASS_MAX_BIN) {
bass += mag2;
}
}
float bass_rise = fmaxf(bass - d->prev_bass, 0.0f);
d->prev_bass = bass;
if (!*active) {
flux = bass_rise = 0.0f;
}
// Each channel minus its ~0.5 s running mean, so sustained texture
// doesn't count, and over it, so neither channel's units dominate
const float a = 1.0f / (0.5f * d->frame_rate);
d->flux_mean += a * (flux - d->flux_mean);
d->bass_mean += a * (bass_rise - d->bass_mean);
float full = fmaxf(flux - d->flux_mean, 0.0f) / (d->flux_mean + 1e-6f);
*tempo_nv = full;
*bass_nv = fmaxf(bass_rise - d->bass_mean, 0.0f) / (d->bass_mean + 1e-12f);
return full + BASS_WEIGHT * *bass_nv;
}
static void estimate_tempo(beat_dsp_t *d)
{
int n = d->t < BEAT_NV_LEN ? (int)d->t : BEAT_NV_LEN;
int top = 2 * (d->max_lag + 1);
if (n < top + TEMPO_MIN_EXTRA || top >= BEAT_AC_LEN) {
return;
}
// Oldest-first, mean-removed copy of the history (re[] is free here)
float *x = d->re, mean = 0.0f;
for (int i = 0; i < n; i++) {
x[i] = d->tempo_nv[(d->t - n + i) & NV_MASK];
mean += x[i];
}
mean /= n;
// Fade older frames so a tempo change wins within a few seconds
const float fade = expf(-1.0f / (TEMPO_MEMORY_S * d->frame_rate));
float w = 1.0f;
for (int i = n - 1; i >= 0; i--) {
x[i] = (x[i] - mean) * w;
w *= fade;
}
for (int l = 0; l <= top; l++) {
float s = 0.0f;
for (int i = l; i < n; i++) {
s += x[i] * x[i - l];
}
d->ac[l] = s / (n - l);
}
if (d->ac[0] <= 1e-9f) {
d->confidence *= 0.5f;
return;
}
// score[l] for l in [min_lag-1, max_lag+1], kept in im[] for interpolation
float *score = d->im;
const float l0 = d->frame_rate * 60.0f / PRIOR_BPM;
int best = d->min_lag;
for (int l = d->min_lag - 1; l <= d->max_lag + 1; l++) {
float o = log2f((float)l / l0) / PRIOR_OCTAVES;
// The 2x lag backs up a beat but can't carry it: in 3/4, 2/3 of the
// beat is barely periodic yet its double is a whole bar
score[l] = expf(-0.5f * o * o) * (d->ac[l] + 0.5f * fminf(d->ac[2 * l], fmaxf(d->ac[l], 0.0f)));
if (l >= d->min_lag && l <= d->max_lag && score[l] > score[best]) {
best = l;
}
}
// Hold the current tempo unless another clearly beats it; real music
// often has a 3:2 or 2:1 alternative that is nearly as periodic
if (d->period > 0.0f) {
int lo = (int)fmaxf(floorf(d->period * (1.0f - TEMPO_TOL)), d->min_lag);
int hi = (int)fminf(ceilf(d->period * (1.0f + TEMPO_TOL)), d->max_lag);
int near = lo;
for (int l = lo + 1; l <= hi; l++) {
if (score[l] > score[near]) {
near = l;
}
}
if (score[near] > 0.0f && score[best] < TEMPO_MARGIN * score[near]) {
best = near;
}
}
float a = score[best - 1], b = score[best], c = score[best + 1];
float denom = a - 2.0f * b + c;
float period = best + (denom < 0.0f ? 0.5f * (a - c) / denom : 0.0f);
float conf = fminf(fmaxf(d->ac[best] / d->ac[0], 0.0f), 1.0f);
d->confidence += 0.3f * (conf - d->confidence);
if (d->period == 0.0f) {
d->period = period; // tentative; locking decides whether beats go out
} else if (fabsf(period / d->period - 1.0f) < TEMPO_TOL) {
d->period += 0.2f * (period - d->period);
d->pending_count = 0;
} else if (d->pending_count > 0 && fabsf(period / d->pending_period - 1.0f) < TEMPO_TOL) {
if (++d->pending_count >= TEMPO_SWITCH) {
d->period = period;
d->pending_count = 0;
}
} else {
d->pending_period = period;
d->pending_count = 1;
}
}
// Frames since the most recent beat according to the comb over past beats
static int best_phase(beat_dsp_t *d, uint32_t cur)
{
const float p = d->period;
const int np = (int)p;
const int expect = (d->prev_phase - d->lead_frames + 1 + 2 * np) % np;
int best = 0;
float best_score = -1.0f, total = 0.0f;
for (int phi = 0; phi < np; phi++) {
float s = 0.0f, w = 1.0f;
for (int k = 0; k < COMB_BEATS; k++) {
float back = phi + k * p;
if (back >= BEAT_NV_LEN - 2 || back > cur) {
break;
}
s += w * nv_max3(d, cur - (uint32_t)lrintf(back), cur);
w *= COMB_DECAY;
}
total += s;
if (abs(phi - expect) <= 1) {
s *= PHASE_STICK;
}
if (s > best_score) {
best_score = s;
best = phi;
}
}
// How much more onset energy sits on the beat grid than off it
float salience = total > 0.0f ? best_score * np / total : 0.0f;
// Plain running mean until the window fills, so locking isn't held back
float span = fminf(SALIENCE_S * d->frame_rate, (float)++d->salience_n);
d->salience += (salience - d->salience) / span;
return best;
}
// Add one cue value to the bar position of grid beat n, for every meter
static void bar_cue(beat_dsp_t *d, uint32_t n, float v)
{
for (int m = 0; m < BEAT_METERS; m++) {
float *s = &d->bar_score[m][n % s_meters[m]];
*s += BAR_RATE * (v - *s);
}
}
// Pick the downbeat position per meter, then the meter, with hysteresis
static void bar_decide(beat_dsp_t *d)
{
float contrast[BEAT_METERS];
for (int m = 0; m < BEAT_METERS; m++) {
const int len = s_meters[m];
const float *s = d->bar_score[m];
int best = 0;
float mean = 0.0f;
for (int i = 0; i < len; i++) {
mean += s[i] / len;
if (s[i] > s[best]) {
best = i;
}
}
// A tap holds the bar for a while; the audio only takes over after
if (d->tap_hold == 0 && s[best] > BAR_MARGIN * s[d->down_pos[m]]) {
d->down_pos[m] = best;
}
contrast[m] = mean > 0.0f ? s[d->down_pos[m]] / mean - 1.0f : 0.0f;
}
// Most music is in 4/4, so 3/4 has to make a stronger case
contrast[0] *= METER3_BIAS;
int cur = d->meter == 3 ? 0 : 1, other = 1 - cur;
if (d->tap_hold == 0 && contrast[other] > METER_MARGIN * contrast[cur]) {
cur = other;
}
d->meter = s_meters[cur];
d->bar_contrast = contrast[cur];
}
// Runs a couple of frames after grid beat pending_n landed
static void analyse_beat(beat_dsp_t *d)
{
uint32_t beat = d->pending_frame - 2;
float kick = 0.0f;
for (uint32_t i = beat - 1; i <= beat + 2; i++) {
kick = fmaxf(kick, d->bass_nv[i & NV_MASK]);
}
d->kick_mean += 0.1f * (kick - d->kick_mean);
bar_cue(d, d->pending_n, KICK_WEIGHT * kick / (d->kick_mean + 1e-6f));
bar_decide(d);
d->pending = false;
}
// A beat just landed: close the spectrum of the previous beat and score how
// much new energy it brought over the one before as a bar start
static void close_span(beat_dsp_t *d)
{
if (d->band_frames > 0) {
float change = 0.0f;
for (int b = 0; b < BEAT_BANDS; b++) {
float v = d->band_acc[b] / d->band_frames;
// Rises only: a chord fading out late in the bar isn't a change
change += fmaxf(v - d->prev_span[b], 0.0f);
d->prev_span[b] = v;
d->band_acc[b] = 0.0f;
}
d->band_frames = 0;
d->change_mean += 0.1f * (change - d->change_mean);
if (d->span_n > 0) { // the first span has nothing to compare with
bar_cue(d, d->span_n, CHANGE_WEIGHT * change / (d->change_mean + 1e-6f));
}
}
d->span_n = d->pending_n;
}
static int process_frame(beat_dsp_t *d)
{
int events = 0;
bool active;
float tempo_nv, bass_nv;
float nv = onset_strength(d, &active, &tempo_nv, &bass_nv);
uint32_t cur = d->t++;
d->nv[cur & NV_MASK] = nv;
d->tempo_nv[cur & NV_MASK] = tempo_nv;
d->bass_nv[cur & NV_MASK] = bass_nv;
if (d->pending && cur == d->pending_frame - 2) {
close_span(d);
}
if (d->period > 0.0f && cur - (d->pending_frame - 2) < SPAN_FRAC * d->period) {
for (int b = 0; b < BEAT_BANDS; b++) {
d->band_acc[b] += d->band_now[b];
}
d->band_frames++;
}
if (d->pending && cur >= d->pending_frame) {
analyse_beat(d);
}
if (active) {
d->last_active = cur;
}
// Onset: previous frame is a local peak above the adaptive threshold
if (cur >= 2) {
uint32_t c = cur - 1;
float v = nv_at(d, c);
if (v > nv_at(d, c - 1) && v >= nv && v > ONSET_K * d->nv_mean + 1e-3f &&
(d->last_onset == 0 || c - d->last_onset >= ONSET_GAP_S * d->frame_rate)) {
d->last_onset = c;
events |= BEAT_EV_ONSET;
}
}
d->nv_mean += (nv - d->nv_mean) / d->frame_rate;
if (d->t % TEMPO_EVERY == 0) {
estimate_tempo(d);
}
if (d->period == 0.0f) {
return events;
}
bool audible = cur - d->last_active < ACTIVE_HOLD_S * d->frame_rate;
// Speech and noise can score on one measure, music with a beat on both
float strength = d->confidence * d->salience;
d->locked = audible && strength >= (d->locked ? UNLOCK_STRENGTH : LOCK_STRENGTH);
// Shifting the phase by the lead makes it wrap that many frames early
int np = (int)d->period;
int phase = (best_phase(d, cur) + d->lead_frames) % np;
// Phase dropping by more than half a beat means it wrapped: beat due now
if (phase + d->period / 2 < d->prev_phase && cur - d->last_beat >= d->period / 2) {
if (d->pending) {
if (cur < d->pending_frame - 2) {
close_span(d);
}
analyse_beat(d);
}
uint32_t n = d->grid_n++;
int pos = (int)((n + 4 * 3 - (uint32_t)d->down_pos[d->meter == 3 ? 0 : 1]) % d->meter);
// Always offer a best guess, but only call downbeats when sure
if (d->tap_hold > 0) {
d->tap_hold--;
d->bar_beat = pos + 1;
d->bar_sure = true;
} else {
d->bar_beat = n >= BAR_WARMUP ? pos + 1 : 0;
d->bar_sure = d->bar_contrast >= (d->bar_sure ? BAR_SURE_OFF : BAR_SURE_ON);
}
if (d->locked) {
events |= BEAT_EV_BEAT;
if (d->bar_beat == 1 && d->bar_sure) {
events |= BEAT_EV_DOWNBEAT;
}
}
d->last_beat = cur;
// The beat lands lead_frames from now; look at it 2 frames after
d->pending_frame = cur + d->lead_frames + 2;
d->pending_n = n;
d->pending = true;
}
d->prev_phase = phase;
return events;
}
void beat_dsp_tap(beat_dsp_t *d, float frames_ago)
{
if (d->period <= 0.0f || d->grid_n == 0) {
return;
}
// Grid beat grid_n - 1 lands lead_frames after it was announced; snap the
// tap to that beat or the one either side, whichever is nearest
float tap = (float)d->t - frames_ago;
float last = (float)(d->last_beat + d->lead_frames);
int k = (int)lrintf((tap - last) / d->period);
k = k < -1 ? -1 : k > 1 ? 1 : k;
int32_t n = (int32_t)d->grid_n - 1 + k;
n = n < 0 ? 0 : n;
for (int m = 0; m < BEAT_METERS; m++) {
float top = 1e-3f;
for (int i = 0; i < s_meters[m]; i++) {
top = fmaxf(top, d->bar_score[m][i]);
}
int pos = n % s_meters[m];
d->bar_score[m][pos] = TAP_BOOST * top;
d->down_pos[m] = pos;
}
d->tap_hold = TAP_HOLD_BARS * d->meter;
d->bar_sure = true;
}
void beat_dsp_feed(beat_dsp_t *d, const float *x, size_t n, beat_dsp_cb_t cb, void *ctx)
{
while (n > 0) {
size_t take = BEAT_FFT_SIZE - d->in_fill;
take = take < n ? take : n;
memcpy(d->in + d->in_fill, x, take * sizeof(float));
d->in_fill += take;
x += take;
n -= take;
if (d->in_fill < BEAT_FFT_SIZE) {
break;
}
int events = process_frame(d);
memmove(d->in, d->in + BEAT_HOP, (BEAT_FFT_SIZE - BEAT_HOP) * sizeof(float));
d->in_fill = BEAT_FFT_SIZE - BEAT_HOP;
if (events && cb) {
cb(ctx, events, d);
}
}
}
+98
View File
@@ -0,0 +1,98 @@
#pragma once
/*
* Realtime beat tracker, plain C with no ESP-IDF dependencies so it can be
* tested on a PC. Spectral-flux onsets -> autocorrelation tempo -> comb-filter
* phase tracking that predicts beats from the last few bars -> bar position
* (downbeats and 3/4 vs 4/4) from bass hits and harmonic changes per beat.
*/
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#define BEAT_FFT_SIZE 512 // 32 ms window at 16 kHz
#define BEAT_HOP 256 // 16 ms between onset frames
#define BEAT_NV_LEN 512 // onset history (~8 s), power of two
#define BEAT_MIN_BPM 60.0f
#define BEAT_MAX_BPM 200.0f
#define BEAT_AC_LEN (BEAT_NV_LEN / 2) // autocorrelation lags kept
#define BEAT_BANDS 16 // log-spaced bands for harmonic change
#define BEAT_METERS 2 // 3/4 and 4/4
#define BEAT_EV_ONSET 0x1
#define BEAT_EV_BEAT 0x2
#define BEAT_EV_DOWNBEAT 0x4 // with BEAT_EV_BEAT, when the bar is sure
typedef struct {
// Settings (from beat_dsp_init)
float frame_rate; // onset frames per second
float gate_rms; // frames quieter than this are treated as silence
int min_lag, max_lag; // beat period search range, frames
int lead_frames; // emit predicted beats this early
// Onset detection
float in[BEAT_FFT_SIZE];
size_t in_fill;
float re[BEAT_FFT_SIZE], im[BEAT_FFT_SIZE]; // FFT work, reused as scratch
float prev_log[BEAT_FFT_SIZE / 2 + 1];
float prev_bass;
float flux_mean, bass_mean, nv_mean;
float nv[BEAT_NV_LEN]; // novelty (onset strength) ring, indexed by frame
float tempo_nv[BEAT_NV_LEN]; // log flux only, for the tempo estimate
float bass_nv[BEAT_NV_LEN]; // bass rise only, for downbeats
uint32_t t; // frames processed
uint32_t last_active, last_onset;
// Tempo
float ac[BEAT_AC_LEN];
float period; // frames per beat, 0 until found
float confidence; // 0..1 periodicity of the onset envelope
float pending_period;
int pending_count;
// Beat phase
float salience; // on-beat vs. average onset energy, 1 = no beat
uint32_t salience_n;
int prev_phase;
uint32_t last_beat;
bool locked;
// Bar position. Grid beats are numbered whether or not they are emitted;
// each one is analysed a couple of frames after it lands.
uint32_t grid_n; // grid beats so far
uint32_t pending_frame; // frame to analyse the latest beat at
uint32_t pending_n; // its grid number
bool pending;
float band_now[BEAT_BANDS]; // log band energy of the current frame
float band_acc[BEAT_BANDS]; // ...summed over the start of the latest beat
float prev_span[BEAT_BANDS]; // ...averaged over the start of the one before
int band_frames;
uint32_t span_n; // grid number of the beat band_acc belongs to
float kick_mean, change_mean;
float bar_score[BEAT_METERS][4]; // cue strength per meter and position
int down_pos[BEAT_METERS]; // grid_n % meter of the downbeat
int meter; // 3 or 4
float bar_contrast; // how clearly one position stands out
int bar_beat; // 1..meter of the last grid beat (best guess), 0 early on
bool bar_sure; // bar_beat is reliable; downbeats only go out then
uint32_t tap_hold; // grid beats left that a tap holds the bar for
} beat_dsp_t;
// lead_s fires predicted beats early to cover capture and output latency
void beat_dsp_init(beat_dsp_t *d, float sample_rate, float gate_rms, float lead_s);
// Feed mono samples scaled to +/-1. Calls cb once per frame that produced
// events (BEAT_EV_* bits). Beats are predicted, so they arrive lead_s ahead
// of the frame they belong to; onsets need one frame of lookahead.
typedef void (*beat_dsp_cb_t)(void *ctx, int events, const beat_dsp_t *d);
void beat_dsp_feed(beat_dsp_t *d, const float *x, size_t n, beat_dsp_cb_t cb, void *ctx);
// The user tapped beat 1 frames_ago frames back: make the nearest grid beat
// beat 1 and hold that for a while before the audio can move it again
void beat_dsp_tap(beat_dsp_t *d, float frames_ago);
static inline float beat_dsp_bpm(const beat_dsp_t *d)
{
return d->period > 0.0f ? 60.0f * d->frame_rate / d->period : 0.0f;
}
+241
View File
@@ -0,0 +1,241 @@
#include "bench.h"
#include <math.h>
#include <stdio.h>
#include <string.h>
#include "driver/gpio.h"
#include "esp_timer.h"
#include "espnow_tx.h"
#include "freertos/FreeRTOS.h"
#include "freertos/portmacro.h"
#include "freertos/queue.h"
#include "freertos/task.h"
#define RING 64
#define MAX_DRIVERS 8
typedef struct {
uint16_t idx;
int64_t tx_us;
int64_t first_us, last_us;
uint8_t echoes;
int fire_in_ms;
} beat_t;
typedef struct {
uint8_t mac[6];
uint32_t echoes;
} drv_t;
static portMUX_TYPE s_mux = portMUX_INITIALIZER_UNLOCKED;
static beat_t s_ring[RING];
static drv_t s_drv[MAX_DRIVERS];
static uint32_t s_sent, s_echoes, s_late_echoes;
static int64_t s_min_us, s_max_us, s_sum_us;
static int64_t s_spread_sum, s_spread_max;
static uint32_t s_spread_n;
static int s_remaining;
static bool s_running;
static float s_bpm;
#if CONFIG_BEAT_TEST_GPIO >= 0
static bool s_gpio_ready;
static int s_level;
#endif
static esp_timer_handle_t s_timer;
static QueueHandle_t s_logq;
// USB latency test: one "BT <idx> <esp_timer us>" line per synthetic beat, printed from a low-priority
// task so the beat path itself never waits on the console. tools/usb_latency.py reads these.
typedef struct {
uint16_t idx;
int64_t tx_us;
} beat_log_t;
static void log_task(void *arg)
{
beat_log_t l;
for (;;) {
if (xQueueReceive(s_logq, &l, portMAX_DELAY) == pdTRUE) {
printf("BT %u %lld\n", l.idx, (long long)l.tx_us);
}
}
}
static uint32_t s_gen_count;
static void gpio_mark(void)
{
#if CONFIG_BEAT_TEST_GPIO >= 0
if (!s_gpio_ready) {
gpio_set_direction(CONFIG_BEAT_TEST_GPIO, GPIO_MODE_OUTPUT);
s_gpio_ready = true;
}
s_level = !s_level;
gpio_set_level(CONFIG_BEAT_TEST_GPIO, s_level);
#endif
}
void bench_on_beat_tx(uint16_t idx, int64_t tx_us, int fire_in_ms)
{
gpio_mark(); // edge as the first copy goes out
if (s_running && s_logq) {
beat_log_t l = { .idx = idx, .tx_us = tx_us };
xQueueSend(s_logq, &l, 0);
}
portENTER_CRITICAL(&s_mux);
beat_t *b = &s_ring[idx % RING];
memset(b, 0, sizeof(*b));
b->idx = idx;
b->tx_us = tx_us;
b->fire_in_ms = fire_in_ms;
s_sent++;
portEXIT_CRITICAL(&s_mux);
}
void bench_on_echo(const uint8_t mac[6], uint16_t idx, int64_t rx_us)
{
portENTER_CRITICAL(&s_mux);
beat_t *b = &s_ring[idx % RING];
if (b->idx != idx || b->tx_us == 0) {
s_late_echoes++; // beat already overwritten in the ring
portEXIT_CRITICAL(&s_mux);
return;
}
// Round trip minus the deliberate fire_in wait: airtime out + driver work + airtime back
int64_t dt = rx_us - b->tx_us - (int64_t)b->fire_in_ms * 1000;
if (s_echoes == 0 || dt < s_min_us) {
s_min_us = dt;
}
if (s_echoes == 0 || dt > s_max_us) {
s_max_us = dt;
}
s_sum_us += dt;
s_echoes++;
if (b->echoes++ == 0) {
b->first_us = rx_us;
} else {
int64_t spread = rx_us - b->first_us;
if (spread > s_spread_max) {
s_spread_max = spread;
}
s_spread_n++; // one sample per extra driver that heard this beat
s_spread_sum += spread;
}
b->last_us = rx_us;
drv_t *d = NULL;
for (int i = 0; i < MAX_DRIVERS && !d; i++) {
if (memcmp(s_drv[i].mac, mac, 6) == 0 && s_drv[i].echoes) {
d = &s_drv[i];
}
}
for (int i = 0; i < MAX_DRIVERS && !d; i++) {
if (!s_drv[i].echoes) {
d = &s_drv[i];
memcpy(d->mac, mac, 6);
}
}
if (d) {
d->echoes++;
}
portEXIT_CRITICAL(&s_mux);
}
static void gen_cb(void *arg)
{
if (!s_running) {
return;
}
s_gen_count++;
// Downbeat on every fourth beat, like a 4/4 bar
espnow_tx_beat(s_bpm, (s_gen_count % 4) == 1, ((s_gen_count - 1) % 4) + 1);
if (s_remaining > 0 && --s_remaining == 0) {
bench_stop();
}
}
esp_err_t bench_start(float bpm, int count)
{
if (bpm < 30 || bpm > 300) {
return ESP_ERR_INVALID_ARG;
}
bench_stop();
if (!s_logq) {
s_logq = xQueueCreate(32, sizeof(beat_log_t));
if (s_logq) {
xTaskCreate(log_task, "bench_log", 3072, NULL, 2, NULL);
}
}
portENTER_CRITICAL(&s_mux);
memset(s_ring, 0, sizeof(s_ring));
memset(s_drv, 0, sizeof(s_drv));
s_sent = s_echoes = s_late_echoes = 0;
s_min_us = s_max_us = s_sum_us = 0;
s_spread_sum = s_spread_max = 0;
s_spread_n = 0;
portEXIT_CRITICAL(&s_mux);
if (!s_timer) {
const esp_timer_create_args_t ta = { .callback = gen_cb, .name = "bench_beat", .dispatch_method = ESP_TIMER_TASK };
esp_err_t err = esp_timer_create(&ta, &s_timer);
if (err != ESP_OK) {
return err;
}
}
s_bpm = bpm;
s_remaining = count;
s_gen_count = 0;
s_running = true;
return esp_timer_start_periodic(s_timer, (uint64_t)(60e6 / bpm));
}
bool bench_running(void)
{
return s_running;
}
void bench_stop(void)
{
s_running = false;
if (s_timer) {
esp_timer_stop(s_timer);
}
}
cJSON *bench_results(void)
{
cJSON *o = cJSON_CreateObject();
portENTER_CRITICAL(&s_mux);
uint32_t sent = s_sent, echoes = s_echoes, late = s_late_echoes, spread_n = s_spread_n;
int64_t mn = s_min_us, mx = s_max_us, sum = s_sum_us, ssum = s_spread_sum, smax = s_spread_max;
drv_t drv[MAX_DRIVERS];
memcpy(drv, s_drv, sizeof(drv));
portEXIT_CRITICAL(&s_mux);
int ndrv = 0;
cJSON *drivers = cJSON_AddObjectToObject(o, "drivers");
for (int i = 0; i < MAX_DRIVERS; i++) {
if (drv[i].echoes) {
char key[13];
snprintf(key, sizeof(key), "%02x%02x%02x%02x%02x%02x", drv[i].mac[0], drv[i].mac[1], drv[i].mac[2],
drv[i].mac[3], drv[i].mac[4], drv[i].mac[5]);
cJSON *d = cJSON_AddObjectToObject(drivers, key);
cJSON_AddNumberToObject(d, "echoes", drv[i].echoes);
cJSON_AddNumberToObject(d, "hit_pct", sent ? 100.0 * drv[i].echoes / sent : 0);
ndrv++;
}
}
cJSON_AddBoolToObject(o, "running", s_running);
cJSON_AddNumberToObject(o, "beats_sent", sent);
cJSON_AddNumberToObject(o, "echoes", echoes);
cJSON_AddNumberToObject(o, "late_echoes", late);
// Fraction of beats each driver acted on; ~100 with the double send even at moderate loss
cJSON_AddNumberToObject(o, "hit_pct_total", sent && ndrv ? 100.0 * echoes / ((double)sent * ndrv) : 0);
cJSON_AddNumberToObject(o, "rtt_minus_lead_min_us", mn);
cJSON_AddNumberToObject(o, "rtt_minus_lead_avg_us", echoes ? (double)sum / echoes : 0);
cJSON_AddNumberToObject(o, "rtt_minus_lead_max_us", mx);
// Arrival spread between drivers for the same beat (needs two or more drivers echoing)
cJSON_AddNumberToObject(o, "spread_avg_us", spread_n ? (double)ssum / spread_n : 0);
cJSON_AddNumberToObject(o, "spread_max_us", smax);
bool beats_lossy;
cJSON_AddNumberToObject(o, "loss_pct", espnow_tx_loss(&beats_lossy));
cJSON_AddBoolToObject(o, "loss_includes_beats", beats_lossy);
return o;
}
+24
View File
@@ -0,0 +1,24 @@
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include "cJSON.h"
#include "esp_err.h"
// Bench-test helpers: a synthetic beat generator, an echo-based latency and
// delivery measurement, and the optional GPIO marker for a logic analyzer.
// Called by espnow_tx for every beat (first copy time, and how long drivers wait before firing)
void bench_on_beat_tx(uint16_t idx, int64_t tx_us, int fire_in_ms);
// A driver echoed beat `idx` right after it fired (called from the Wi-Fi task)
void bench_on_echo(const uint8_t mac[6], uint16_t idx, int64_t rx_us);
// Send `count` synthetic beats at `bpm` (count 0 = until stopped); resets the results
esp_err_t bench_start(float bpm, int count);
void bench_stop(void);
// True while the synthetic generator runs; mic beats are muted meanwhile so they cannot mix in
bool bench_running(void);
// Results so far; caller owns the object
cJSON *bench_results(void);
+933
View File
@@ -0,0 +1,933 @@
#include "engine.h"
#include <ctype.h>
#include <strings.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "envelope.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "espnow_tx.h"
#include "rel.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "store.h"
static const char *TAG = "engine";
#define FRAME_REPEAT 2 // every state frame goes out twice; messages are idempotent
#define MAX_RUNNERS 8
#define JSON_MAX 232
/* ---------------------------------------------------------------- sending */
static esp_err_t tx(const uint8_t *mac, const void *data, size_t len, bool commit, int repeat)
{
// The bulk queue is bounded; wait for room instead of dropping state
for (int i = 0; i < 400; i++) {
esp_err_t err = rel_send(mac, data, len, commit, repeat);
if (err != ESP_ERR_NO_MEM) {
return err;
}
vTaskDelay(pdMS_TO_TICKS(5));
}
return ESP_ERR_TIMEOUT;
}
static bool parse_mac(const char *s, uint8_t mac[6])
{
if (strlen(s) != 12) {
return false;
}
for (int i = 0; i < 6; i++) {
if (!isxdigit((unsigned char)s[2 * i]) || !isxdigit((unsigned char)s[2 * i + 1])) {
return false;
}
char b[3] = { s[2 * i], s[2 * i + 1], 0 };
mac[i] = strtoul(b, NULL, 16);
}
return true;
}
// Broadcast (no targets): sent `repeat` times under one sequence number, never acked; the
// state version digest covers losses. With targets: unicast per MAC, acked and retransmitted.
// commit (broadcast only) tells drivers this frame completes a state change.
static char s_gid[16]; // zone being played; "" = plain CMD (all addressed drivers apply it)
static bool s_save; // append the CMD save byte (driver persists presets / brightness)
// Envelopes travel as 0x4C CMD (4C 03 env) or, for a zone, GROUP_CMD (4C 04 <len><group> env) so only
// drivers in that group apply them. JSON messages go as they are.
static size_t wrap_wire(uint8_t *out, const uint8_t *frame, size_t len)
{
if (len == 0 || frame[0] != 2) { // not a v2 envelope
memcpy(out, frame, len);
return len;
}
size_t off = 0;
out[off++] = 0x4C;
if (s_gid[0]) {
size_t gl = strlen(s_gid);
out[off++] = 0x04;
out[off++] = gl;
memcpy(out + off, s_gid, gl);
off += gl;
} else {
out[off++] = 0x03;
}
memcpy(out + off, frame, len);
off += len;
if (s_save) {
out[off++] = 1; // 4C 03 / 4C 04 carry an optional trailing save flag after the envelope
}
return off;
}
static esp_err_t emit_c(const cJSON *targets, const uint8_t *frame, size_t len, int repeat, bool commit)
{
uint8_t wire[REL_FRAG_MAX];
if (len + 3 + strlen(s_gid) + 1 > sizeof(wire)) {
return ESP_ERR_INVALID_SIZE;
}
len = wrap_wire(wire, frame, len);
frame = wire;
esp_err_t ret = ESP_OK;
int n = cJSON_IsArray(targets) ? cJSON_GetArraySize(targets) : 0;
if (n == 0) {
return tx(NULL, frame, len, commit, repeat);
}
for (int i = 0; i < n; i++) {
const cJSON *t = cJSON_GetArrayItem(targets, i);
uint8_t mac[6];
if (cJSON_IsString(t) && parse_mac(t->valuestring, mac)) {
esp_err_t e = tx(mac, frame, len, false, 1);
if (e != ESP_OK) {
ret = e;
}
}
}
return ret;
}
static esp_err_t emit(const cJSON *targets, const uint8_t *frame, size_t len, int repeat)
{
return emit_c(targets, frame, len, repeat, false);
}
/* --------------------------------------------------------------- presets */
// Preset record with palette references applied. Caller deletes the result.
static cJSON *preset_payload(const char *preset_id)
{
cJSON *rec = cJSON_GetObjectItem(store_coll("preset"), preset_id);
if (!rec) {
return NULL;
}
cJSON *out = cJSON_Duplicate(rec, true);
cJSON *refs = cJSON_GetObjectItem(out, "palette_refs");
cJSON *colors = cJSON_GetObjectItem(out, "colors");
if (!cJSON_IsArray(refs) || !cJSON_IsArray(colors)) {
return out;
}
cJSON *pid = cJSON_GetObjectItem(out, "profile_id");
char pidbuf[24] = "";
if (cJSON_IsString(pid)) {
snprintf(pidbuf, sizeof(pidbuf), "%s", pid->valuestring);
} else if (cJSON_IsNumber(pid)) {
snprintf(pidbuf, sizeof(pidbuf), "%d", (int)pid->valuedouble);
}
cJSON *profile = cJSON_GetObjectItem(store_coll("profile"), pidbuf);
cJSON *palid = cJSON_GetObjectItem(profile, "palette_id");
char palbuf[24] = "";
if (cJSON_IsString(palid)) {
snprintf(palbuf, sizeof(palbuf), "%s", palid->valuestring);
} else if (cJSON_IsNumber(palid)) {
snprintf(palbuf, sizeof(palbuf), "%d", (int)palid->valuedouble);
}
cJSON *pal = cJSON_GetObjectItem(store_coll("palette"), palbuf);
if (!cJSON_IsArray(pal)) {
return out;
}
int n = cJSON_GetArraySize(colors);
for (int i = 0; i < n; i++) {
cJSON *ref = cJSON_GetArrayItem(refs, i);
if (cJSON_IsNumber(ref)) {
int idx = (int)ref->valuedouble;
cJSON *c = cJSON_GetArrayItem(pal, idx);
if (idx >= 0 && c && (cJSON_IsString(c) ? c->valuestring[0] : true)) {
cJSON_ReplaceItemInArray(colors, i, cJSON_Duplicate(c, true));
}
}
}
return out;
}
/* ------------------------------------------------------------ zone play */
static const cJSON *zone_names(const char *zone_id)
{
cJSON *z = cJSON_GetObjectItem(store_coll("zone"), zone_id);
cJSON *names = cJSON_GetObjectItem(z, "names");
return cJSON_IsArray(names) ? names : NULL;
}
static bool name_seen(const cJSON *names, int upto, const char *name)
{
for (int i = 0; i < upto; i++) {
const cJSON *o = cJSON_GetArrayItem(names, i);
if (cJSON_IsString(o) && strcmp(o->valuestring, name) == 0) {
return true;
}
}
return false;
}
// Select a preset for the whole zone: one GROUP_CMD, applied by every driver in the zone's group.
// The select entry's key is ignored by drivers when it is the only entry.
static esp_err_t select_zone(const char *zone_id, const char *preset_name)
{
uint8_t frame[ENV_FRAME_MAX];
env_blob_t sel;
env_blob_init(&sel);
env_add_select(&sel, "*", preset_name, -1);
snprintf(s_gid, sizeof(s_gid), "%s", zone_id);
esp_err_t ret = emit_c(NULL, frame, env_frame(frame, -1, NULL, &sel), FRAME_REPEAT, true);
s_gid[0] = 0;
return ret;
}
/* What each zone last played, so a driver that missed it can be brought back in step */
typedef struct {
char zone[16];
char preset[24];
uint16_t ver;
} zone_cur_t;
static zone_cur_t s_cur[16];
static void zone_cur_set(const char *zone_id, const char *preset_id)
{
zone_cur_t *slot = NULL;
for (int i = 0; i < 16; i++) {
if (strcmp(s_cur[i].zone, zone_id) == 0) {
slot = &s_cur[i];
break;
}
if (!slot && !s_cur[i].zone[0]) {
slot = &s_cur[i];
}
}
if (slot) {
snprintf(slot->zone, sizeof(slot->zone), "%s", zone_id);
snprintf(slot->preset, sizeof(slot->preset), "%s", preset_id);
slot->ver = rel_ver();
}
}
static void runner_stop_zone(const char *zone_id);
static esp_err_t play_locked(const char *zone_id, const char *preset_id)
{
const cJSON *names = zone_names(zone_id);
if (!names) {
return ESP_ERR_NOT_FOUND;
}
cJSON *payload = preset_payload(preset_id);
if (!payload) {
return ESP_ERR_NOT_FOUND;
}
uint8_t frame[ENV_FRAME_MAX];
env_blob_t pb;
env_blob_init(&pb);
rel_bump_ver();
bool fit = env_add_preset(&pb, preset_id, payload);
cJSON_Delete(payload);
if (!fit) {
return ESP_ERR_INVALID_SIZE;
}
size_t len = env_frame(frame, -1, &pb, NULL);
snprintf(s_gid, sizeof(s_gid), "%s", zone_id);
esp_err_t ret = emit(NULL, frame, len, FRAME_REPEAT);
s_gid[0] = 0;
if (ret == ESP_OK) {
ret = select_zone(zone_id, preset_id);
}
if (ret == ESP_OK) {
zone_cur_set(zone_id, preset_id);
}
return ret;
}
esp_err_t engine_play(const char *zone_id, const char *preset_id)
{
store_lock();
runner_stop_zone(zone_id); // a manual pick ends that zone's sequence
esp_err_t ret = play_locked(zone_id, preset_id);
store_unlock();
return ret;
}
esp_err_t engine_stop(const char *zone_id)
{
store_lock();
runner_stop_zone(zone_id);
const cJSON *names = zone_names(zone_id);
rel_bump_ver();
esp_err_t ret = names ? select_zone(zone_id, "off") : ESP_ERR_NOT_FOUND;
if (names) {
zone_cur_set(zone_id, "off");
}
store_unlock();
return ret;
}
static const char *device_name_for(const uint8_t mac[6]);
/* ------------------------------------------------------------ push/send */
static bool only_binary_keys(const cJSON *m)
{
const cJSON *it;
cJSON_ArrayForEach(it, m)
{
const char *k = it->string;
if (strcmp(k, "v") && strcmp(k, "presets") && strcmp(k, "select") && strcmp(k, "b") && strcmp(k, "save")) {
return false;
}
}
return true;
}
static esp_err_t push_binary(const cJSON *m, const cJSON *targets)
{
uint8_t frame[ENV_FRAME_MAX];
esp_err_t ret = ESP_OK;
const cJSON *b = cJSON_GetObjectItem(m, "b");
int brightness = cJSON_IsNumber(b) ? (int)b->valuedouble : -1;
const cJSON *sv = cJSON_GetObjectItem(m, "save");
const bool save = cJSON_IsTrue(sv) || (cJSON_IsNumber(sv) && sv->valuedouble != 0);
bool sent_any = false;
const cJSON *presets = cJSON_GetObjectItem(m, "presets"), *it;
const cJSON *select_obj = cJSON_GetObjectItem(m, "select");
const bool has_select = cJSON_IsObject(select_obj) && select_obj->child;
env_blob_t pb;
env_blob_init(&pb);
cJSON_ArrayForEach(it, presets)
{
if (!env_add_preset(&pb, it->string, it)) {
size_t len = env_frame(frame, sent_any ? -1 : brightness, &pb, NULL);
ret = emit_c(targets, frame, len, FRAME_REPEAT, false);
sent_any = true;
env_blob_init(&pb);
if (!env_add_preset(&pb, it->string, it)) {
ESP_LOGW(TAG, "preset %s too large for one frame", it->string);
}
}
}
if (pb.data[0]) {
size_t len = env_frame(frame, sent_any ? -1 : brightness, &pb, NULL);
s_save = save; // only the last presets frame asks the driver to persist
ret = emit_c(targets, frame, len, FRAME_REPEAT, !has_select);
s_save = false;
sent_any = true;
}
const cJSON *select = cJSON_GetObjectItem(m, "select");
env_blob_t sb;
env_blob_init(&sb);
cJSON_ArrayForEach(it, select)
{
const char *pname = NULL;
int step = -1;
if (cJSON_IsArray(it) && cJSON_GetArraySize(it) > 0) {
const cJSON *p0 = cJSON_GetArrayItem(it, 0), *s1 = cJSON_GetArrayItem(it, 1);
pname = cJSON_IsString(p0) ? p0->valuestring : NULL;
if (cJSON_IsNumber(s1)) {
step = (int)s1->valuedouble;
}
} else if (cJSON_IsString(it)) {
pname = it->valuestring;
}
if (!pname) {
continue;
}
if (!env_add_select(&sb, it->string, pname, step)) {
size_t len = env_frame(frame, sent_any ? -1 : brightness, NULL, &sb);
ret = emit_c(targets, frame, len, FRAME_REPEAT, true);
sent_any = true;
env_blob_init(&sb);
env_add_select(&sb, it->string, pname, step);
}
}
if (sb.data[0]) {
size_t len = env_frame(frame, sent_any ? -1 : brightness, NULL, &sb);
ret = emit_c(targets, frame, len, FRAME_REPEAT, true);
sent_any = true;
}
if (!sent_any && brightness >= 0) { // brightness-only message
size_t len = env_frame(frame, brightness, NULL, NULL);
s_save = save;
ret = emit_c(targets, frame, len, FRAME_REPEAT, true);
s_save = false;
}
return ret;
}
// JSON text path for keys the binary envelope cannot carry (save, default, manifest, ...)
static esp_err_t push_json(const cJSON *m, const cJSON *targets)
{
char *s = cJSON_PrintUnformatted(m);
if (!s) {
return ESP_ERR_NO_MEM;
}
esp_err_t ret;
if (strlen(s) <= JSON_MAX) {
ret = emit_c(targets, (const uint8_t *)s, strlen(s), 1, true);
free(s);
return ret;
}
free(s);
// Too big: split the presets over several messages, the other keys go on the last one
const cJSON *presets = cJSON_GetObjectItem(m, "presets");
if (!cJSON_IsObject(presets)) {
return ESP_ERR_INVALID_SIZE;
}
const size_t base = strlen("{\"v\":\"1\",\"presets\":{}}");
const size_t room = JSON_MAX - 48; // keep space for save/default on the last message
ret = ESP_OK;
cJSON *batch = cJSON_CreateObject();
cJSON_AddStringToObject(batch, "v", "1");
cJSON *bp = cJSON_AddObjectToObject(batch, "presets");
size_t cur = base;
const cJSON *it;
cJSON_ArrayForEach(it, presets)
{
char *ps = cJSON_PrintUnformatted(it);
size_t need = (ps ? strlen(ps) : 0) + strlen(it->string) + 4;
free(ps);
if (bp->child && cur + need > room) {
char *out = cJSON_PrintUnformatted(batch);
ret = emit(targets, (const uint8_t *)out, strlen(out), 1);
free(out);
cJSON_Delete(batch);
batch = cJSON_CreateObject();
cJSON_AddStringToObject(batch, "v", "1");
bp = cJSON_AddObjectToObject(batch, "presets");
cur = base;
}
cJSON_AddItemReferenceToObject(bp, it->string, (cJSON *)it);
cur += need;
}
const cJSON *k;
cJSON_ArrayForEach(k, m)
{
if (strcmp(k->string, "v") && strcmp(k->string, "presets")) {
cJSON_AddItemReferenceToObject(batch, k->string, (cJSON *)k);
}
}
char *out = cJSON_PrintUnformatted(batch);
if (out) {
ret = emit_c(targets, (const uint8_t *)out, strlen(out), 1, true);
free(out);
}
cJSON_Delete(batch);
return ret;
}
esp_err_t engine_push(const cJSON *messages, const cJSON *targets)
{
esp_err_t ret = ESP_OK;
const cJSON *m;
store_lock();
cJSON_ArrayForEach(m, messages)
{
if (!cJSON_IsObject(m)) {
continue;
}
if (!cJSON_IsArray(targets) || cJSON_GetArraySize(targets) == 0) {
rel_bump_ver(); // a broadcast state change: drivers that miss it resync from the digest
}
esp_err_t e = only_binary_keys(m) ? push_binary(m, targets) : push_json(m, targets);
if (e != ESP_OK) {
ret = e;
}
}
store_unlock();
return ret;
}
esp_err_t engine_send_presets(const cJSON *ids, bool save, const char *def, const cJSON *targets, int *sent)
{
cJSON *msg = cJSON_CreateObject();
cJSON_AddStringToObject(msg, "v", "1");
cJSON *presets = cJSON_AddObjectToObject(msg, "presets");
int count = 0;
store_lock();
const cJSON *id;
cJSON_ArrayForEach(id, ids)
{
char key[24];
if (cJSON_IsNumber(id)) {
snprintf(key, sizeof(key), "%d", (int)id->valuedouble);
} else if (cJSON_IsString(id)) {
snprintf(key, sizeof(key), "%s", id->valuestring);
} else {
continue;
}
cJSON *p = preset_payload(key);
if (!p) {
continue;
}
cJSON_AddItemToObject(presets, key, p);
count++;
}
if (sent) {
*sent = count;
}
esp_err_t ret = ESP_ERR_NOT_FOUND;
if (count) {
if (save) {
cJSON_AddTrueToObject(msg, "save");
}
if (!cJSON_IsArray(targets) || cJSON_GetArraySize(targets) == 0) {
rel_bump_ver();
}
ret = push_binary(msg, targets);
// The startup preset needs the driver names (the driver checks it is addressed); targeted sends only
if (ret == ESP_OK && def && cJSON_GetObjectItem(presets, def) && cJSON_IsArray(targets)) {
cJSON *names = cJSON_CreateArray();
const cJSON *t;
cJSON_ArrayForEach(t, targets)
{
uint8_t mac[6];
const char *n = cJSON_IsString(t) && parse_mac(t->valuestring, mac) ? device_name_for(mac) : NULL;
if (n) {
cJSON_AddItemToArray(names, cJSON_CreateString(n));
}
}
if (cJSON_GetArraySize(names)) {
cJSON *d = cJSON_CreateObject();
cJSON_AddStringToObject(d, "v", "1");
cJSON_AddStringToObject(d, "default", def);
cJSON_AddItemToObject(d, "targets", names);
names = NULL;
ret = push_json(d, targets);
cJSON_Delete(d);
}
cJSON_Delete(names);
}
}
store_unlock();
cJSON_Delete(msg);
return ret;
}
/* ------------------------------------------------------------ sequencer */
typedef struct {
bool used;
char seq[16];
char zone[16];
int step;
int rounds;
int64_t deadline_us;
} runner_t;
static runner_t s_run[MAX_RUNNERS];
static TaskHandle_t s_task;
static void set_active(const char *seq_id, bool on)
{
cJSON *rec = cJSON_GetObjectItem(store_coll("sequence"), seq_id);
if (!rec) {
return;
}
cJSON_DeleteItemFromObject(rec, "active");
cJSON_AddBoolToObject(rec, "active", on);
store_save("sequence");
}
static void runner_free(runner_t *r)
{
r->used = false;
set_active(r->seq, false);
}
static void runner_stop_zone(const char *zone_id)
{
for (int i = 0; i < MAX_RUNNERS; i++) {
if (s_run[i].used && strcmp(s_run[i].zone, zone_id) == 0) {
runner_free(&s_run[i]);
}
}
}
static const cJSON *steps_of(const char *seq_id)
{
cJSON *rec = cJSON_GetObjectItem(store_coll("sequence"), seq_id);
cJSON *steps = cJSON_GetObjectItem(rec, "steps");
return cJSON_IsArray(steps) && cJSON_GetArraySize(steps) ? steps : NULL;
}
static int64_t step_duration_us(const cJSON *step)
{
double d = 1.0;
const cJSON *v = cJSON_GetObjectItem(step, "duration_s");
if (cJSON_IsNumber(v)) {
d = v->valuedouble;
}
d = d < 0.5 ? 0.5 : (d > 600 ? 600 : d);
return (int64_t)(d * 1e6);
}
// Play step r->step and move the deadline on from the previous deadline (no drift)
static void run_step(runner_t *r, bool first)
{
const cJSON *steps = steps_of(r->seq);
const cJSON *step = steps ? cJSON_GetArrayItem(steps, r->step) : NULL;
if (!step) {
runner_free(r);
return;
}
const cJSON *pid = cJSON_GetObjectItem(step, "preset_id");
char key[24] = "";
if (cJSON_IsString(pid)) {
snprintf(key, sizeof(key), "%s", pid->valuestring);
} else if (cJSON_IsNumber(pid)) {
snprintf(key, sizeof(key), "%d", (int)pid->valuedouble);
}
play_locked(r->zone, key);
r->deadline_us = (first ? esp_timer_get_time() : r->deadline_us) + step_duration_us(step);
}
static void runner_advance(runner_t *r)
{
cJSON *rec = cJSON_GetObjectItem(store_coll("sequence"), r->seq);
const cJSON *steps = steps_of(r->seq);
if (!rec || !steps) {
runner_free(r);
return;
}
if (++r->step >= cJSON_GetArraySize(steps)) {
r->step = 0;
r->rounds++;
const cJSON *loop = cJSON_GetObjectItem(rec, "loop");
const cJSON *rc = cJSON_GetObjectItem(rec, "repeat_count");
int repeat = cJSON_IsNumber(rc) ? (int)rc->valuedouble : 0;
if (!cJSON_IsTrue(loop) || (repeat > 0 && r->rounds >= repeat)) {
runner_free(r);
return;
}
}
run_step(r, false);
}
static void seq_task(void *arg)
{
for (;;) {
int64_t next = INT64_MAX;
store_lock();
int64_t now = esp_timer_get_time();
for (int i = 0; i < MAX_RUNNERS; i++) {
runner_t *r = &s_run[i];
if (r->used && now >= r->deadline_us) {
runner_advance(r);
}
if (r->used && r->deadline_us < next) {
next = r->deadline_us;
}
}
store_unlock();
TickType_t wait = portMAX_DELAY;
if (next != INT64_MAX) {
int64_t us = next - esp_timer_get_time();
wait = us <= 0 ? 0 : pdMS_TO_TICKS((us + 999) / 1000);
}
ulTaskNotifyTake(pdTRUE, wait);
}
}
esp_err_t engine_seq_play(const char *seq_id)
{
store_lock();
cJSON *rec = cJSON_GetObjectItem(store_coll("sequence"), seq_id);
cJSON *z = cJSON_GetObjectItem(rec, "zone_id");
char zone[16] = "";
if (cJSON_IsString(z)) {
snprintf(zone, sizeof(zone), "%s", z->valuestring);
} else if (cJSON_IsNumber(z)) {
snprintf(zone, sizeof(zone), "%d", (int)z->valuedouble);
}
esp_err_t ret = ESP_ERR_NOT_FOUND;
if (rec && zone[0] && steps_of(seq_id) && zone_names(zone)) {
runner_stop_zone(zone);
runner_t *slot = NULL;
for (int i = 0; i < MAX_RUNNERS && !slot; i++) {
slot = s_run[i].used ? NULL : &s_run[i];
}
if (!slot) {
ret = ESP_ERR_NO_MEM;
} else {
memset(slot, 0, sizeof(*slot));
slot->used = true;
snprintf(slot->seq, sizeof(slot->seq), "%s", seq_id);
snprintf(slot->zone, sizeof(slot->zone), "%s", zone);
set_active(seq_id, true);
run_step(slot, true);
ret = ESP_OK;
}
}
store_unlock();
if (s_task) {
xTaskNotifyGive(s_task);
}
return ret;
}
esp_err_t engine_seq_stop(const char *seq_id)
{
esp_err_t ret = ESP_ERR_NOT_FOUND;
store_lock();
for (int i = 0; i < MAX_RUNNERS; i++) {
if (s_run[i].used && strcmp(s_run[i].seq, seq_id) == 0) {
runner_free(&s_run[i]);
ret = ESP_OK;
}
}
set_active(seq_id, false);
store_unlock();
return ret;
}
static esp_err_t scene_each(const char *scene_id, bool play)
{
store_lock();
cJSON *scene = cJSON_GetObjectItem(store_coll("scene"), scene_id);
cJSON *seqs = cJSON_GetObjectItem(scene, "sequences");
esp_err_t ret = cJSON_IsArray(seqs) ? ESP_OK : ESP_ERR_NOT_FOUND;
const cJSON *id;
cJSON_ArrayForEach(id, seqs)
{
char key[16];
if (cJSON_IsNumber(id)) {
snprintf(key, sizeof(key), "%d", (int)id->valuedouble);
} else if (cJSON_IsString(id)) {
snprintf(key, sizeof(key), "%s", id->valuestring);
} else {
continue;
}
play ? engine_seq_play(key) : engine_seq_stop(key);
}
store_unlock();
return ret;
}
esp_err_t engine_scene_play(const char *scene_id) { return scene_each(scene_id, true); }
esp_err_t engine_scene_stop(const char *scene_id) { return scene_each(scene_id, false); }
cJSON *engine_status(void)
{
cJSON *o = cJSON_CreateObject(), *zones = cJSON_AddObjectToObject(o, "zones");
store_lock();
for (int i = 0; i < MAX_RUNNERS; i++) {
if (s_run[i].used) {
cJSON *z = cJSON_AddObjectToObject(zones, s_run[i].zone);
cJSON_AddStringToObject(z, "sequence_id", s_run[i].seq);
cJSON_AddNumberToObject(z, "step", s_run[i].step);
cJSON_AddNumberToObject(z, "round", s_run[i].rounds);
}
}
store_unlock();
return o;
}
static void resume_task(void *arg)
{
vTaskDelay(pdMS_TO_TICKS(2000));
store_lock();
const cJSON *rec;
cJSON_ArrayForEach(rec, store_coll("sequence"))
{
if (cJSON_IsTrue(cJSON_GetObjectItem(rec, "active"))) {
char key[16];
snprintf(key, sizeof(key), "%s", rec->string);
engine_seq_play(key);
}
}
store_unlock();
vTaskDelete(NULL);
}
/* A driver reported a stale state version: replay what its zone is playing, then commit the version */
static const char *device_name_for(const uint8_t mac[6])
{
char hex[13];
snprintf(hex, sizeof(hex), "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
const cJSON *d;
cJSON_ArrayForEach(d, store_coll("device"))
{
const cJSON *addr = cJSON_GetObjectItem(d, "address"), *name = cJSON_GetObjectItem(d, "name");
if (cJSON_IsString(name) && (strcasecmp(d->string, hex) == 0 || (cJSON_IsString(addr) && strcasecmp(addr->valuestring, hex) == 0))) {
return name->valuestring;
}
}
return NULL;
}
/* Unicast helpers: acked and retransmitted by the link */
static esp_err_t send_cmd(const uint8_t mac[6], const uint8_t *env, size_t len, bool commit)
{
uint8_t wire[REL_FRAG_MAX];
if (len + 2 > sizeof(wire)) {
return ESP_ERR_INVALID_SIZE;
}
wire[0] = 0x4C;
wire[1] = 0x03; // CMD
memcpy(wire + 2, env, len);
return rel_send(mac, wire, len + 2, commit, 1);
}
// GROUPS packet: the ids of every zone whose driver names include `name`. An empty list replaces
// whatever the driver stored, so it is only sent when allow_empty is set (a zone or device was edited);
// a driver that merely announced itself and is in no zone keeps the groups it already has.
static void send_groups(const uint8_t mac[6], const char *name, bool allow_empty)
{
uint8_t pkt[REL_FRAG_MAX];
size_t off = 3;
int count = 0;
const cJSON *z;
cJSON_ArrayForEach(z, store_coll("zone"))
{
const cJSON *names = cJSON_GetObjectItem(z, "names");
size_t gl = strlen(z->string);
if (cJSON_IsArray(names) && name_seen(names, cJSON_GetArraySize(names), name) && off + 1 + gl <= sizeof(pkt) &&
gl < 16) {
pkt[off++] = gl;
memcpy(pkt + off, z->string, gl);
off += gl;
count++;
}
}
if (count == 0 && !allow_empty) {
return;
}
pkt[0] = 0x4C;
pkt[1] = 0x02; // GROUPS
pkt[2] = count;
rel_send(mac, pkt, off, false, 1);
}
static bool hex_mac(const char *s, uint8_t mac[6])
{
return parse_mac(s, mac);
}
// Re-send group membership to every registered ESP-NOW driver (zones or devices changed)
void engine_groups_changed(void)
{
store_lock();
const cJSON *d;
cJSON_ArrayForEach(d, store_coll("device"))
{
const cJSON *name = cJSON_GetObjectItem(d, "name"), *addr = cJSON_GetObjectItem(d, "address");
const cJSON *tr = cJSON_GetObjectItem(d, "transport");
uint8_t mac[6];
const char *hex = cJSON_IsString(addr) ? addr->valuestring : d->string;
if (cJSON_IsString(name) && cJSON_IsString(tr) && !strcmp(tr->valuestring, "espnow") && hex_mac(hex, mac)) {
send_groups(mac, name->valuestring, true);
}
}
store_unlock();
}
// A driver said hello at boot: register it, then tell it which zones it belongs to
static void on_announce(const uint8_t mac[6], const uint8_t *pkt, int len)
{
char name[48] = "";
if (pkt[0] == '{') {
cJSON *j = cJSON_ParseWithLength((const char *)pkt, len);
const cJSON *n = cJSON_GetObjectItem(j, "name");
if (cJSON_IsString(n)) {
snprintf(name, sizeof(name), "%s", n->valuestring);
}
cJSON_Delete(j);
} else if (len > 3 && pkt[2] > 0 && 3 + pkt[2] <= len) { // 4C 01 <len><name> ...
snprintf(name, sizeof(name), "%.*s", pkt[2] < sizeof(name) - 1 ? pkt[2] : (int)sizeof(name) - 1, pkt + 3);
}
if (!name[0]) {
return;
}
char hex[13];
snprintf(hex, sizeof(hex), "%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
store_lock();
cJSON *devs = store_coll("device");
cJSON *rec = cJSON_GetObjectItem(devs, hex);
const cJSON *old = cJSON_GetObjectItem(rec, "name");
if (!rec) {
rec = cJSON_AddObjectToObject(devs, hex);
cJSON_AddStringToObject(rec, "id", hex);
cJSON_AddStringToObject(rec, "name", name);
cJSON_AddStringToObject(rec, "type", "led");
cJSON_AddStringToObject(rec, "transport", "espnow");
cJSON_AddStringToObject(rec, "address", hex);
store_save("device");
ESP_LOGI(TAG, "new driver %s (%s)", name, hex);
} else if (!cJSON_IsString(old) || strcmp(old->valuestring, name) != 0) {
cJSON_ReplaceItemInObject(rec, "name", cJSON_CreateString(name));
store_save("device");
}
send_groups(mac, name, false);
store_unlock();
}
/* A driver reported a stale state version: replay what its zone is playing, then commit the version */
static void resync_driver(const uint8_t mac[6])
{
uint8_t frame[ENV_FRAME_MAX];
store_lock();
const char *name = device_name_for(mac);
if (name) {
send_groups(mac, name, false); // membership first, in case the driver lost it
}
const zone_cur_t *best = NULL;
for (int i = 0; name && i < 16; i++) {
const cJSON *names = s_cur[i].zone[0] ? zone_names(s_cur[i].zone) : NULL;
if (names && name_seen(names, cJSON_GetArraySize(names), name) &&
(!best || (int16_t)(s_cur[i].ver - best->ver) > 0)) {
best = &s_cur[i];
}
}
bool sent = false;
if (best) {
if (strcmp(best->preset, "off") != 0) {
cJSON *payload = preset_payload(best->preset);
env_blob_t pb;
env_blob_init(&pb);
if (payload && env_add_preset(&pb, best->preset, payload)) {
send_cmd(mac, frame, env_frame(frame, -1, &pb, NULL), false);
}
cJSON_Delete(payload);
}
env_blob_t sb;
env_blob_init(&sb);
if (env_add_select(&sb, name, best->preset, -1)) {
sent = send_cmd(mac, frame, env_frame(frame, -1, NULL, &sb), true) == ESP_OK;
}
}
if (!sent) { // nothing to replay: an empty envelope still lets the driver adopt the version
send_cmd(mac, frame, env_frame(frame, -1, NULL, NULL), true);
}
store_unlock();
}
esp_err_t engine_init(void)
{
rel_set_resync_cb(resync_driver);
rel_set_announce_cb(on_announce);
if (xTaskCreate(seq_task, "sequencer", 6144, NULL, 4, &s_task) != pdPASS) {
return ESP_ERR_NO_MEM;
}
xTaskCreate(resume_task, "seq_resume", 4096, NULL, 3, NULL);
return ESP_OK;
}
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include <stdbool.h>
#include "cJSON.h"
#include "esp_err.h"
// Zone play/stop, preset push/send and the sequencer. Drivers run the patterns
// themselves; this builds preset + select frames and hands them to ESP-NOW.
// Start the sequencer task; sequences marked active resume after a short delay
esp_err_t engine_init(void);
// Select a preset on every driver named in the zone (broadcast, sent twice)
esp_err_t engine_play(const char *zone_id, const char *preset_id);
// Turn the zone's drivers off and stop its sequence
esp_err_t engine_stop(const char *zone_id);
// POST /presets/push: v1 messages for targets (MAC strings), or broadcast when targets is NULL
esp_err_t engine_push(const cJSON *messages, const cJSON *targets);
// POST /presets/send: presets from the current profile by id
esp_err_t engine_send_presets(const cJSON *ids, bool save, const char *def, const cJSON *targets, int *sent);
esp_err_t engine_seq_play(const char *seq_id);
esp_err_t engine_seq_stop(const char *seq_id);
esp_err_t engine_scene_play(const char *scene_id);
esp_err_t engine_scene_stop(const char *scene_id);
// Caller owns the result
cJSON *engine_status(void);
// Zones or devices changed: re-send group membership to every registered ESP-NOW driver
void engine_groups_changed(void);
+187
View File
@@ -0,0 +1,187 @@
#include "envelope.h"
#include <stdlib.h>
#include <string.h>
void env_blob_init(env_blob_t *b)
{
b->data[0] = 0;
b->len = 1;
}
static bool put(env_blob_t *b, const void *src, size_t n)
{
if (b->len + n > ENV_BLOB_MAX) {
return false;
}
memcpy(b->data + b->len, src, n);
b->len += n;
return true;
}
static bool put_u8(env_blob_t *b, unsigned v)
{
uint8_t x = v;
return put(b, &x, 1);
}
static bool put_le16(env_blob_t *b, unsigned v)
{
uint8_t x[2] = { v & 255, (v >> 8) & 255 };
return put(b, x, 2);
}
// Python truthiness of a JSON value
static bool truthy(const cJSON *v)
{
if (!v || cJSON_IsNull(v) || cJSON_IsFalse(v)) {
return false;
}
if (cJSON_IsNumber(v)) {
return v->valuedouble != 0;
}
if (cJSON_IsString(v)) {
return v->valuestring[0] != 0;
}
return true;
}
static const cJSON *get2(const cJSON *o, const char *a, const char *b)
{
const cJSON *v = cJSON_GetObjectItem(o, a);
return truthy(v) ? v : cJSON_GetObjectItem(o, b);
}
static int clamp(double v, int lo, int hi)
{
int i = (int)v;
return i < lo ? lo : (i > hi ? hi : i);
}
static int num_or(const cJSON *v, int dflt)
{
return cJSON_IsNumber(v) ? (int)v->valuedouble : (cJSON_IsBool(v) ? cJSON_IsTrue(v) : dflt);
}
// Same rule as the Python packer: 6+ hex digits or an [r,g,b] list; anything else is skipped
static bool color_rgb(const cJSON *c, uint8_t rgb[3])
{
if (cJSON_IsString(c)) {
const char *s = c->valuestring;
while (*s == ' ') {
s++;
}
while (*s == '#') {
s++;
}
if (strlen(s) < 6) {
return false;
}
char full[7];
memcpy(full, s, 6);
full[6] = 0;
char *end;
unsigned long v = strtoul(full, &end, 16);
if (*end) {
return false;
}
rgb[0] = v >> 16;
rgb[1] = v >> 8;
rgb[2] = v;
return true;
}
if (cJSON_IsArray(c) && cJSON_GetArraySize(c) >= 3) {
for (int i = 0; i < 3; i++) {
rgb[i] = (uint8_t)num_or(cJSON_GetArrayItem(c, i), 0);
}
return true;
}
return false;
}
bool env_add_preset(env_blob_t *b, const char *name, const cJSON *p)
{
size_t save_len = b->len;
uint8_t save_count = b->data[0];
const cJSON *pat = get2(p, "p", "pattern");
const char *pattern = cJSON_IsString(pat) ? pat->valuestring : "off";
const cJSON *cols = get2(p, "c", "colors");
int ncol = cJSON_IsArray(cols) ? cJSON_GetArraySize(cols) : 0;
size_t nl = strlen(name), pl = strlen(pattern);
if (nl > 250 || pl > 250 || ncol > 255) {
return false;
}
uint8_t rgbs[255][3];
int nvalid = 0;
for (int i = 0; i < ncol; i++) {
if (color_rgb(cJSON_GetArrayItem(cols, i), rgbs[nvalid])) {
nvalid++;
}
}
bool ok = put_u8(b, nl) && put(b, name, nl) && put_u8(b, pl) && put(b, pattern, pl) && put_u8(b, nvalid);
for (int i = 0; ok && i < nvalid; i++) {
ok = put(b, rgbs[i], 3);
}
const cJSON *d = get2(p, "d", "delay"), *br = get2(p, "b", "brightness");
const cJSON *a = cJSON_GetObjectItem(p, "a");
if (!a) {
a = cJSON_GetObjectItem(p, "auto");
}
int auto_ = a ? truthy(a) : 1;
ok = ok && put_le16(b, clamp(num_or(d, 100), 0, 65535)) && put_u8(b, clamp(num_or(br, 127), 0, 255)) &&
put_u8(b, auto_);
for (int i = 1; ok && i <= 6; i++) {
char key[4] = { 'n', '0' + i, 0 };
ok = put_le16(b, (uint16_t)(int16_t)clamp(num_or(cJSON_GetObjectItem(p, key), 0), -32768, 32767));
}
if (!ok) {
b->len = save_len;
b->data[0] = save_count;
return false;
}
b->data[0]++;
return true;
}
bool env_add_select(env_blob_t *b, const char *device, const char *preset, int step)
{
size_t save_len = b->len;
size_t dl = strlen(device), pl = strlen(preset);
if (dl > 250 || pl > 250 || (step > 65535)) {
return false;
}
bool ok = put_u8(b, dl) && put(b, device, dl) && put_u8(b, pl) && put(b, preset, pl) && put_u8(b, step >= 0);
if (ok && step >= 0) {
ok = put_le16(b, step);
}
if (!ok) {
b->len = save_len;
return false;
}
b->data[0]++;
return true;
}
size_t env_frame(uint8_t *out, int brightness, const env_blob_t *presets, const env_blob_t *select)
{
size_t lp = presets && presets->data[0] ? presets->len : 0;
size_t ls = select && select->data[0] ? select->len : 0;
int wire = 255;
if (brightness >= 0) {
wire = brightness > 255 ? 127 : (brightness * 127 + 127) / 255; // 0-127 scales to 0-255
}
out[0] = 2;
out[1] = wire;
out[2] = lp;
out[3] = ls;
out[4] = 0;
if (lp) {
memcpy(out + 5, presets->data, lp);
}
if (ls) {
memcpy(out + 5 + lp, select->data, ls);
}
return 5 + lp + ls;
}
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include "cJSON.h"
// Native binary (v2) driver envelope, byte-compatible with
// src/util/binary_envelope.py. Presets and select entries go in separate
// frames so each frame is 5 + blob <= ENV_FRAME_MAX (one ESP-NOW payload).
#define ENV_FRAME_MAX 224 // + 4C 04 <group> wrapper must fit REL_FRAG_MAX
#define ENV_BLOB_MAX (ENV_FRAME_MAX - 5)
typedef struct {
uint8_t data[ENV_BLOB_MAX + 1]; // data[0] is the entry count
size_t len;
} env_blob_t;
void env_blob_init(env_blob_t *b);
// Append one preset (short keys p,c,d,b,a,n1..n6 or long pattern/colors/...); false if it does not fit
bool env_add_preset(env_blob_t *b, const char *name, const cJSON *preset);
// Append one select entry; step < 0 means none
bool env_add_select(env_blob_t *b, const char *device, const char *preset, int step);
// Frame with either a presets blob or a select blob (the other empty);
// brightness < 0 leaves device brightness unchanged. Returns frame length.
size_t env_frame(uint8_t *out, int brightness, const env_blob_t *presets, const env_blob_t *select);
+231
View File
@@ -0,0 +1,231 @@
#include "espnow_tx.h"
#include <string.h>
#include "esp_check.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_now.h"
#include "esp_rom_sys.h"
#include "esp_random.h"
#include "esp_timer.h"
#include "bench.h"
#include "esp_wifi.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
#define BULK_MAX 250
#define BULK_RETRIES 3
#define BULK_QUEUE_LEN 32
static const char *TAG = "espnow_tx";
static const uint8_t BROADCAST[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
typedef struct {
uint8_t mac[6];
bool broadcast;
uint8_t len;
uint8_t data[BULK_MAX];
} bulk_t;
static QueueHandle_t s_bulk_q;
static SemaphoreHandle_t s_bulk_done;
static volatile esp_now_send_status_t s_bulk_status;
static volatile bool s_bulk_inflight;
static volatile int64_t s_last_beat_us;
static esp_timer_handle_t s_copy_timer;
static beat_frame_t s_pending;
static int s_copies_left;
static uint16_t s_beat_idx;
static uint8_t s_cur_peer[6];
static bool s_have_peer;
static espnow_stats_t s_stats;
static volatile int s_loss_pct;
static volatile bool s_loss_beats = true;
bool espnow_tx_drop(void)
{
return s_loss_pct > 0 && (int)(esp_random() % 100) < s_loss_pct;
}
void espnow_tx_set_loss(int percent, bool include_beats)
{
s_loss_pct = percent < 0 ? 0 : (percent > 100 ? 100 : percent);
s_loss_beats = include_beats;
}
int espnow_tx_loss(bool *include_beats)
{
if (include_beats) {
*include_beats = s_loss_beats;
}
return s_loss_pct;
}
static void IRAM_ATTR send_cb(const esp_now_send_info_t *info, esp_now_send_status_t status)
{
(void)info;
if (s_bulk_inflight) {
s_bulk_status = status;
BaseType_t woken = pdFALSE;
xSemaphoreGiveFromISR(s_bulk_done, &woken);
portYIELD_FROM_ISR(woken);
}
}
// Each copy carries a fire_in_ms reduced by the time already spent, so every
// copy points at the same instant.
static void send_beat_copy(void *arg)
{
(void)arg;
int sent = CONFIG_BEAT_TX_COPIES - s_copies_left;
int gap_ms = (sent * CONFIG_BEAT_TX_GAP_US) / 1000;
int fire = CONFIG_BEAT_LEAD_MS - gap_ms;
s_pending.fire_in_ms = fire < 0 ? 0 : (fire > 255 ? 255 : fire);
if (s_loss_beats && espnow_tx_drop()) {
s_stats.sim_dropped++; // lossy-link test: this copy never reaches the radio
} else if (esp_now_send(BROADCAST, (const uint8_t *)&s_pending, sizeof(s_pending)) != ESP_OK) {
s_stats.beat_send_fail++;
}
s_last_beat_us = esp_timer_get_time();
if (--s_copies_left > 0) {
esp_timer_start_once(s_copy_timer, CONFIG_BEAT_TX_GAP_US);
}
}
void espnow_tx_beat(float bpm, bool downbeat, int bar)
{
if (bpm < 30.0f) {
return;
}
esp_timer_stop(s_copy_timer); // a still-pending copy belongs to the previous beat
s_pending.magic = BEAT_FRAME_MAGIC;
s_pending.type = BEAT_FRAME_TYPE;
s_pending.flags = (downbeat ? BEAT_FLAG_DOWNBEAT : 0) | ((bar & 7) << BEAT_FLAG_BAR_SHIFT);
s_pending.beat_idx = ++s_beat_idx;
s_pending.period_ms = (uint16_t)(60000.0f / bpm);
s_copies_left = CONFIG_BEAT_TX_COPIES;
s_stats.beats_sent++;
bench_on_beat_tx(s_pending.beat_idx, esp_timer_get_time(), CONFIG_BEAT_LEAD_MS);
send_beat_copy(NULL);
}
// Runs in the audio task straight from the detector: no queue, no allocation.
static void on_beat(const beat_info_t *info, float bpm, bool downbeat)
{
if (bench_running()) {
return; // the bench generator owns the beat stream while it runs
}
espnow_tx_beat(bpm, downbeat, info->bar_sure ? info->bar_beat : 0);
}
static esp_err_t select_peer(const uint8_t *mac)
{
if (s_have_peer && memcmp(s_cur_peer, mac, 6) == 0) {
return ESP_OK;
}
// ESP-NOW holds 20 peers and there can be more drivers, so keep one
// rotating unicast peer plus the broadcast peer.
if (s_have_peer) {
esp_now_del_peer(s_cur_peer);
s_have_peer = false;
}
esp_now_peer_info_t p = { .channel = 0, .ifidx = WIFI_IF_STA, .encrypt = false };
memcpy(p.peer_addr, mac, 6);
ESP_RETURN_ON_ERROR(esp_now_add_peer(&p), TAG, "add peer");
memcpy(s_cur_peer, mac, 6);
s_have_peer = true;
return ESP_OK;
}
static void bulk_task(void *arg)
{
bulk_t b;
for (;;) {
xQueueReceive(s_bulk_q, &b, portMAX_DELAY);
// Keep the channel clear around beats
int64_t wait_us = CONFIG_BULK_HOLDOFF_US - (esp_timer_get_time() - s_last_beat_us);
if (wait_us > 0) {
esp_rom_delay_us(wait_us);
}
const uint8_t *dst = b.broadcast ? BROADCAST : b.mac;
if (!b.broadcast && select_peer(b.mac) != ESP_OK) {
s_stats.bulk_failed++;
continue;
}
int tries = b.broadcast ? 1 : BULK_RETRIES;
bool ok = false;
for (int t = 0; t < tries && !ok; t++) {
if (t) {
s_stats.bulk_retries++;
vTaskDelay(pdMS_TO_TICKS(5 << t));
}
xSemaphoreTake(s_bulk_done, 0);
s_bulk_inflight = true;
if (espnow_tx_drop()) {
s_stats.sim_dropped++; // lossy-link test: pretend the radio sent it
ok = true;
} else if (esp_now_send(dst, b.data, b.len) == ESP_OK &&
xSemaphoreTake(s_bulk_done, pdMS_TO_TICKS(30)) == pdTRUE) {
ok = s_bulk_status == ESP_NOW_SEND_SUCCESS || b.broadcast;
}
s_bulk_inflight = false;
}
s_stats.bulk_sent += ok;
s_stats.bulk_failed += !ok;
vTaskDelay(pdMS_TO_TICKS(3)); // inter-frame gap
}
}
esp_err_t espnow_tx_send(const uint8_t *mac, const void *data, size_t len)
{
if (len == 0 || len > BULK_MAX) {
return ESP_ERR_INVALID_SIZE;
}
bulk_t b = { .broadcast = mac == NULL, .len = len };
if (mac) {
memcpy(b.mac, mac, 6);
}
memcpy(b.data, data, len);
return xQueueSend(s_bulk_q, &b, 0) == pdTRUE ? ESP_OK : ESP_ERR_NO_MEM;
}
void espnow_tx_stats(espnow_stats_t *out)
{
*out = s_stats;
}
esp_err_t espnow_tx_init(void)
{
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_RETURN_ON_ERROR(esp_wifi_init(&cfg), TAG, "wifi init");
ESP_RETURN_ON_ERROR(esp_wifi_set_storage(WIFI_STORAGE_RAM), TAG, "storage");
ESP_RETURN_ON_ERROR(esp_wifi_set_mode(WIFI_MODE_STA), TAG, "mode");
ESP_RETURN_ON_ERROR(esp_wifi_start(), TAG, "start");
ESP_RETURN_ON_ERROR(esp_wifi_set_ps(WIFI_PS_NONE), TAG, "ps");
ESP_RETURN_ON_ERROR(esp_wifi_set_max_tx_power(80), TAG, "tx power"); // 20 dBm
ESP_RETURN_ON_ERROR(esp_wifi_set_channel(CONFIG_ESPNOW_CHANNEL, WIFI_SECOND_CHAN_NONE), TAG, "channel");
ESP_RETURN_ON_ERROR(esp_now_init(), TAG, "espnow init");
ESP_RETURN_ON_ERROR(esp_now_register_send_cb(send_cb), TAG, "send cb");
esp_now_peer_info_t bc = { .channel = 0, .ifidx = WIFI_IF_STA, .encrypt = false };
memcpy(bc.peer_addr, BROADCAST, 6);
ESP_RETURN_ON_ERROR(esp_now_add_peer(&bc), TAG, "broadcast peer");
s_bulk_q = xQueueCreate(BULK_QUEUE_LEN, sizeof(bulk_t));
s_bulk_done = xSemaphoreCreateBinary();
ESP_RETURN_ON_FALSE(s_bulk_q && s_bulk_done, ESP_ERR_NO_MEM, TAG, "alloc");
const esp_timer_create_args_t ta = { .callback = send_beat_copy, .name = "beat_copy",
.dispatch_method = ESP_TIMER_TASK };
ESP_RETURN_ON_ERROR(esp_timer_create(&ta, &s_copy_timer), TAG, "timer");
xTaskCreate(bulk_task, "espnow_bulk", 4096, NULL, 5, NULL);
beat_set_callback(on_beat);
ESP_LOGI(TAG, "ESP-NOW up on channel %d, %d beat copies", CONFIG_ESPNOW_CHANNEL, CONFIG_BEAT_TX_COPIES);
return ESP_OK;
}
+49
View File
@@ -0,0 +1,49 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include "esp_err.h"
#include "beat.h"
// Beat frame, broadcast. Little endian, 8 bytes.
#define BEAT_FRAME_MAGIC 0x4C // 0x4C wire protocol, message type 0x25
#define BEAT_FRAME_TYPE 0x25
#define BEAT_FLAG_DOWNBEAT 0x01
#define BEAT_FLAG_BAR_SHIFT 1 // bits 1-3: bar position 0..7 (0 = unknown)
typedef struct __attribute__((packed)) {
uint8_t magic;
uint8_t type;
uint8_t flags;
uint16_t beat_idx; // same for every copy of one beat
uint16_t period_ms; // beat period, drivers free-run on it
uint8_t fire_in_ms; // drivers fire this long after receipt
} beat_frame_t;
typedef struct {
uint32_t beats_sent;
uint32_t beat_send_fail;
uint32_t bulk_sent;
uint32_t bulk_retries;
uint32_t bulk_failed;
uint32_t sim_dropped; // frames discarded by the lossy-link test mode
} espnow_stats_t;
// Start Wi-Fi (no AP) on the configured channel and ESP-NOW; hooks beat_set_callback
esp_err_t espnow_tx_init(void);
// Queue a bulk frame (<= 240 bytes). mac NULL broadcasts. Unicast frames are
// retried; they never go out within the hold-off window after a beat.
esp_err_t espnow_tx_send(const uint8_t *mac, const void *data, size_t len);
void espnow_tx_stats(espnow_stats_t *out);
// Send one beat now (also used by the bench generator). bar 0 = unknown.
void espnow_tx_beat(float bpm, bool downbeat, int bar);
// Lossy-link test mode: discard this percentage of outgoing frames and of
// received acks/echoes. include_beats = false leaves beat copies alone.
void espnow_tx_set_loss(int percent, bool include_beats);
int espnow_tx_loss(bool *include_beats);
bool espnow_tx_drop(void);
+3
View File
@@ -0,0 +1,3 @@
dependencies:
joltwallet/littlefs: "^1.19.0"
espressif/mdns: "^1.4.0"
+378
View File
@@ -0,0 +1,378 @@
/*
* v2 controller: W5500 Ethernet, INMP441 beat detection, ESP-NOW master.
*/
#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "esp_check.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "esp_eth.h"
#include "esp_mac.h"
#include "nvs_flash.h"
#include "driver/gpio.h"
#include "driver/spi_master.h"
#include "esp_http_server.h"
#include "esp_timer.h"
#include "esp_system.h"
#include "mdns.h"
#include "lwip/ip4_addr.h"
#include "lwip/etharp.h"
#include "lwip/netif.h"
#include "lwip/sockets.h"
#include "esp_netif_net_stack.h"
#include "cJSON.h"
#include "mic.h"
#include "beat.h"
#include "espnow_tx.h"
#include "store.h"
#include "api.h"
#include "engine.h"
#include "rel.h"
#include "web.h"
#include "audio.h"
#include "ota.h"
static const char *TAG = "eth";
static httpd_handle_t s_server = NULL;
static esp_netif_t *s_eth_netif = NULL;
static esp_err_t status_get_handler(httpd_req_t *req)
{
beat_info_t bi;
mic_level_t level;
espnow_stats_t es;
rel_stats_t rs;
esp_netif_ip_info_t ip_info = { 0 };
uint8_t mac[6] = { 0 };
char ip[16], macs[18], buf[1024];
beat_get_info(&bi);
mic_get_level(&level);
espnow_tx_stats(&es);
rel_stats(&rs);
esp_netif_get_ip_info(s_eth_netif, &ip_info);
esp_netif_get_mac(s_eth_netif, mac);
snprintf(ip, sizeof(ip), IPSTR, IP2STR(&ip_info.ip));
snprintf(macs, sizeof(macs), MACSTR, MAC2STR(mac));
snprintf(buf, sizeof(buf),
"{\"ip\":\"%s\",\"mac\":\"%s\",\"uptime_s\":%lld,\"free_heap\":%lu,"
"\"mic_rms_dbfs\":%.1f,\"mic_peak_dbfs\":%.1f,\"mic_spl_db\":%.1f,"
"\"bpm\":%.1f,\"beat_confidence\":%.2f,\"beat_locked\":%s,\"beats\":%lu,\"onsets\":%lu,"
"\"meter\":%d,\"bar_beat\":%d,\"bar_sure\":%s,\"downbeats\":%lu,"
"\"espnow\":{\"beats_sent\":%lu,\"beat_send_fail\":%lu,\"bulk_sent\":%lu,"
"\"bulk_retries\":%lu,\"bulk_failed\":%lu,\"sim_dropped\":%lu},"
"\"link\":{\"ver\":%u,\"acked\":%lu,\"ack_timeouts\":%lu,\"retransmits\":%lu,\"resyncs\":%lu,\"digests\":%lu}}",
ip, macs, (long long)(esp_timer_get_time() / 1000000), (unsigned long)esp_get_free_heap_size(),
level.rms_dbfs, level.peak_dbfs, level.spl_db,
bi.bpm, bi.confidence, bi.locked ? "true" : "false", (unsigned long)bi.beat_count,
(unsigned long)bi.onset_count, bi.meter, bi.bar_beat, bi.bar_sure ? "true" : "false",
(unsigned long)bi.downbeat_count,
(unsigned long)es.beats_sent, (unsigned long)es.beat_send_fail, (unsigned long)es.bulk_sent,
(unsigned long)es.bulk_retries, (unsigned long)es.bulk_failed, (unsigned long)es.sim_dropped, rel_ver(),
(unsigned long)rs.acked, (unsigned long)rs.ack_timeouts, (unsigned long)rs.retransmits,
(unsigned long)rs.resyncs, (unsigned long)rs.digests);
httpd_resp_set_type(req, "application/json");
return httpd_resp_sendstr(req, buf);
}
#define DEFAULT_HOSTNAME "led-controller"
static const char *settings_str(const char *key)
{
cJSON *v = cJSON_GetObjectItem(store_settings(), key);
return cJSON_IsString(v) && v->valuestring[0] ? v->valuestring : NULL;
}
// "static_ips" setting: a list of {ip, netmask, gw, dns} tried in order on every link-up. The first whose
// gateway answers ARP is kept; if none does, the controller falls back to DHCP.
static bool parse_static(cJSON *e, esp_netif_ip_info_t *info, esp_netif_dns_info_t *dns)
{
const char *ip = NULL, *mask = "255.255.255.0", *gw = NULL, *d = NULL;
cJSON *v;
if (!cJSON_IsObject(e)) return false;
if (cJSON_IsString(v = cJSON_GetObjectItem(e, "ip"))) ip = v->valuestring;
if (cJSON_IsString(v = cJSON_GetObjectItem(e, "netmask"))) mask = v->valuestring;
if (cJSON_IsString(v = cJSON_GetObjectItem(e, "gw"))) gw = v->valuestring;
if (cJSON_IsString(v = cJSON_GetObjectItem(e, "dns"))) d = v->valuestring;
memset(info, 0, sizeof(*info));
memset(dns, 0, sizeof(*dns));
if (!ip || esp_netif_str_to_ip4(ip, &info->ip) != ESP_OK || esp_netif_str_to_ip4(mask, &info->netmask) != ESP_OK ||
(gw && esp_netif_str_to_ip4(gw, &info->gw) != ESP_OK)) {
return false;
}
if (d && esp_netif_str_to_ip4(d, &dns->ip.u_addr.ip4) == ESP_OK) {
dns->ip.type = ESP_IPADDR_TYPE_V4;
} else if (gw) {
dns->ip.u_addr.ip4 = info->gw;
dns->ip.type = ESP_IPADDR_TYPE_V4;
}
return true;
}
// Poke the gateway so lwIP ARPs for it, then wait for the entry to show up
static bool gateway_answers(esp_netif_t *netif, const esp_ip4_addr_t *gw)
{
struct netif *nif = esp_netif_get_netif_impl(netif);
ip4_addr_t g = { .addr = gw->addr };
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (!nif || sock < 0) {
if (sock >= 0) close(sock);
return false;
}
struct sockaddr_in to = { .sin_family = AF_INET, .sin_port = htons(9), .sin_addr.s_addr = gw->addr };
bool ok = false;
for (int i = 0; i < 15 && !ok; i++) {
sendto(sock, "", 0, 0, (struct sockaddr *)&to, sizeof(to));
vTaskDelay(pdMS_TO_TICKS(100));
struct eth_addr *eth = NULL;
const ip4_addr_t *ipr = NULL;
ok = etharp_find_addr(nif, &g, &eth, &ipr) >= 0;
}
close(sock);
return ok;
}
static void static_ip_task(void *arg)
{
static bool running;
if (running) {
vTaskDelete(NULL);
}
running = true;
cJSON *list = cJSON_GetObjectItem(store_settings(), "static_ips");
esp_netif_dhcpc_stop(s_eth_netif);
bool done = false;
cJSON *e;
cJSON_ArrayForEach(e, list) {
esp_netif_ip_info_t info;
esp_netif_dns_info_t dns;
if (!parse_static(e, &info, &dns)) {
ESP_LOGW(TAG, "static_ips: skipping an invalid entry");
continue;
}
if (esp_netif_set_ip_info(s_eth_netif, &info) != ESP_OK) {
continue;
}
if (dns.ip.type == ESP_IPADDR_TYPE_V4) {
esp_netif_set_dns_info(s_eth_netif, ESP_NETIF_DNS_MAIN, &dns);
}
if (info.gw.addr == 0 || gateway_answers(s_eth_netif, &info.gw)) {
ESP_LOGI(TAG, "Static IP " IPSTR " (gw " IPSTR ")", IP2STR(&info.ip), IP2STR(&info.gw));
done = true;
break;
}
ESP_LOGI(TAG, "Static IP " IPSTR ": gateway " IPSTR " did not answer", IP2STR(&info.ip), IP2STR(&info.gw));
}
if (!done) {
ESP_LOGW(TAG, "No static IP matched this network, using DHCP");
esp_netif_ip_info_t none = { 0 };
esp_netif_set_ip_info(s_eth_netif, &none);
esp_netif_dhcpc_start(s_eth_netif);
}
running = false;
vTaskDelete(NULL);
}
static bool have_static_ips(void)
{
cJSON *l = cJSON_GetObjectItem(store_settings(), "static_ips");
return cJSON_IsArray(l) && cJSON_GetArraySize(l) > 0;
}
static void start_mdns(void)
{
const char *host = settings_str("hostname");
if (!host) {
host = DEFAULT_HOSTNAME;
}
if (mdns_init() != ESP_OK) {
ESP_LOGE(TAG, "mDNS init failed");
return;
}
mdns_hostname_set(host);
mdns_instance_name_set("LED controller");
mdns_service_add(NULL, "_http", "_tcp", 80, NULL, 0);
ESP_LOGI(TAG, "mDNS: %s.local", host);
}
static void start_webserver(void)
{
if (s_server) {
return;
}
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
config.uri_match_fn = httpd_uri_match_wildcard;
config.max_uri_handlers = 64;
config.stack_size = 8192;
config.lru_purge_enable = true;
if (httpd_start(&s_server, &config) != ESP_OK) {
ESP_LOGE(TAG, "HTTP server start failed");
return;
}
const httpd_uri_t status_uri = { .uri = "/status", .method = HTTP_GET, .handler = status_get_handler };
httpd_register_uri_handler(s_server, &status_uri);
web_register(s_server);
audio_register(s_server);
ota_register(s_server);
api_register(s_server);
ESP_LOGI(TAG, "HTTP server started on port %d", config.server_port);
}
static void eth_event_handler(void *arg, esp_event_base_t event_base,
int32_t event_id, void *event_data)
{
esp_eth_handle_t eth_handle = *(esp_eth_handle_t *)event_data;
uint8_t mac[6] = {0};
switch (event_id) {
case ETHERNET_EVENT_CONNECTED: {
eth_speed_t speed;
eth_duplex_t duplex;
esp_eth_ioctl(eth_handle, ETH_CMD_G_MAC_ADDR, mac);
esp_eth_ioctl(eth_handle, ETH_CMD_G_SPEED, &speed);
esp_eth_ioctl(eth_handle, ETH_CMD_G_DUPLEX_MODE, &duplex);
ESP_LOGI(TAG, "Ethernet Link Up, MAC " MACSTR, MAC2STR(mac));
if (have_static_ips()) {
xTaskCreate(static_ip_task, "static_ip", 4096, NULL, 5, NULL);
}
ESP_LOGI(TAG, "%s Mbps %s Duplex",
speed == ETH_SPEED_100M ? "100" : "10",
duplex == ETH_DUPLEX_FULL ? "Full" : "Half");
break;
}
case ETHERNET_EVENT_DISCONNECTED:
ESP_LOGI(TAG, "Ethernet Link Down");
break;
case ETHERNET_EVENT_START:
ESP_LOGI(TAG, "Ethernet Started");
break;
case ETHERNET_EVENT_STOP:
ESP_LOGI(TAG, "Ethernet Stopped");
break;
default:
break;
}
}
static void got_ip_event_handler(void *arg, esp_event_base_t event_base,
int32_t event_id, void *event_data)
{
ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data;
const esp_netif_ip_info_t *ip = &event->ip_info;
ESP_LOGI(TAG, "Got IP: " IPSTR, IP2STR(&ip->ip));
ESP_LOGI(TAG, "Mask: " IPSTR, IP2STR(&ip->netmask));
ESP_LOGI(TAG, "GW: " IPSTR, IP2STR(&ip->gw));
// Server binds to all interfaces, so it keeps working across lease changes
start_webserver();
static bool mdns_started;
if (!mdns_started) {
mdns_started = true;
start_mdns();
}
}
static esp_err_t w5500_init(esp_eth_handle_t *eth_handle_out)
{
esp_err_t ret = ESP_OK;
esp_eth_mac_t *mac = NULL;
esp_eth_phy_t *phy = NULL;
esp_eth_handle_t eth_handle = NULL;
// INT pin uses a GPIO ISR
ESP_RETURN_ON_ERROR(gpio_install_isr_service(0), TAG, "GPIO ISR service install failed");
spi_bus_config_t buscfg = {
.miso_io_num = CONFIG_W5500_MISO_GPIO,
.mosi_io_num = CONFIG_W5500_MOSI_GPIO,
.sclk_io_num = CONFIG_W5500_SCLK_GPIO,
.quadwp_io_num = -1,
.quadhd_io_num = -1,
};
ESP_RETURN_ON_ERROR(spi_bus_initialize(CONFIG_W5500_SPI_HOST, &buscfg, SPI_DMA_CH_AUTO),
TAG, "SPI bus init failed");
spi_device_interface_config_t spi_devcfg = {
.mode = 0,
.clock_speed_hz = CONFIG_W5500_SPI_CLOCK_MHZ * 1000 * 1000,
.queue_size = 20,
.spics_io_num = CONFIG_W5500_CS_GPIO,
};
eth_w5500_config_t w5500_config = ETH_W5500_DEFAULT_CONFIG(CONFIG_W5500_SPI_HOST, &spi_devcfg);
w5500_config.int_gpio_num = CONFIG_W5500_INT_GPIO;
if (CONFIG_W5500_INT_GPIO < 0) {
w5500_config.poll_period_ms = CONFIG_W5500_POLL_PERIOD_MS;
}
eth_mac_config_t mac_config = ETH_MAC_DEFAULT_CONFIG();
eth_phy_config_t phy_config = ETH_PHY_DEFAULT_CONFIG();
phy_config.reset_gpio_num = CONFIG_W5500_RST_GPIO;
mac = esp_eth_mac_new_w5500(&w5500_config, &mac_config);
phy = esp_eth_phy_new_w5500(&phy_config);
ESP_GOTO_ON_FALSE(mac && phy, ESP_FAIL, err, TAG, "W5500 MAC/PHY create failed");
esp_eth_config_t eth_config = ETH_DEFAULT_CONFIG(mac, phy);
ESP_GOTO_ON_ERROR(esp_eth_driver_install(&eth_config, &eth_handle), err, TAG,
"Driver install failed (check W5500 wiring/power)");
// The W5500 has no factory MAC; use the ESP32's Ethernet MAC from eFuse
uint8_t eth_mac[6];
ESP_GOTO_ON_ERROR(esp_read_mac(eth_mac, ESP_MAC_ETH), err, TAG, "Read MAC failed");
ESP_GOTO_ON_ERROR(esp_eth_ioctl(eth_handle, ETH_CMD_S_MAC_ADDR, eth_mac), err, TAG, "Set MAC failed");
*eth_handle_out = eth_handle;
return ESP_OK;
err:
if (eth_handle) {
esp_eth_driver_uninstall(eth_handle);
}
if (mac) {
mac->del(mac);
}
if (phy) {
phy->del(phy);
}
spi_bus_free(CONFIG_W5500_SPI_HOST);
return ret;
}
void app_main(void)
{
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
ota_confirm_later();
ESP_ERROR_CHECK(store_init());
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
esp_eth_handle_t eth_handle = NULL;
ESP_ERROR_CHECK(w5500_init(&eth_handle));
esp_netif_config_t netif_cfg = ESP_NETIF_DEFAULT_ETH();
s_eth_netif = esp_netif_new(&netif_cfg);
ESP_ERROR_CHECK(esp_netif_attach(s_eth_netif, esp_eth_new_netif_glue(eth_handle)));
const char *host = settings_str("hostname");
esp_netif_set_hostname(s_eth_netif, host ? host : DEFAULT_HOSTNAME);
ESP_ERROR_CHECK(esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, &eth_event_handler, NULL));
ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &got_ip_event_handler, NULL));
ESP_ERROR_CHECK(esp_eth_start(eth_handle));
ESP_ERROR_CHECK(espnow_tx_init());
ESP_ERROR_CHECK(rel_init());
ESP_ERROR_CHECK(engine_init());
ESP_ERROR_CHECK(mic_start());
}
+179
View File
@@ -0,0 +1,179 @@
/*
* INMP441 I2S microphone: level meter plus a 16-bit PCM feed for streaming.
* Reads both I2S slots and uses whichever one the mic is driving (L/R pin to
* GND = left, to 3V3 = right), keeping a running RMS/peak for the last block.
* Every block also goes to the beat detector.
*/
#include <math.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/stream_buffer.h"
#include "esp_log.h"
#include "esp_check.h"
#include "driver/i2s_std.h"
#include "driver/gpio.h"
#include "mic.h"
#include "beat.h"
#define MIC_BLOCK_SAMPLES (MIC_SAMPLE_RATE / 50) // 20 ms per read, keeps stream latency low
#define LEVEL_BLOCKS 5 // 100 ms per level reading
#define FULL_SCALE_24BIT 8388608.0f
#define DBFS_FLOOR -120.0f
#define INMP441_SPL_OFFSET 120.0f // 94 dB SPL - (-26 dBFS)
static const char *TAG = "mic";
static i2s_chan_handle_t s_rx_chan;
static portMUX_TYPE s_level_lock = portMUX_INITIALIZER_UNLOCKED;
// 16-bit PCM for the HTTP stream; only fed while a listener is attached
#define STREAM_BUF_BYTES MIC_SAMPLE_RATE // 0.5 s of 16-bit mono
static StreamBufferHandle_t s_stream_buf;
static volatile bool s_stream_active;
static mic_level_t s_level = { DBFS_FLOOR, DBFS_FLOOR, DBFS_FLOOR + INMP441_SPL_OFFSET };
static float to_dbfs(float x)
{
return x > 0.0f ? fmaxf(20.0f * log10f(x), DBFS_FLOOR) : DBFS_FLOOR;
}
static void mic_task(void *arg)
{
static int32_t buf[MIC_BLOCK_SAMPLES * 2]; // interleaved L/R
static int16_t pcm[MIC_BLOCK_SAMPLES];
static float filtered[MIC_BLOCK_SAMPLES];
// One-pole high-pass to strip the INMP441's DC offset
float hp_prev_in = 0.0f, hp_prev_out = 0.0f;
// Level is accumulated over several short blocks so the meter stays steady
double level_sum_sq = 0.0;
float level_peak = 0.0f;
size_t level_frames = 0, level_blocks = 0;
int64_t log_count = 0;
while (true) {
size_t bytes_read = 0;
if (i2s_channel_read(s_rx_chan, buf, sizeof(buf), &bytes_read, portMAX_DELAY) != ESP_OK) {
continue;
}
size_t frames = bytes_read / (2 * sizeof(int32_t));
if (frames == 0) {
continue;
}
// The unused slot is tri-stated and reads as 0; pick the busier one
int32_t raw_min = INT32_MAX, raw_max = INT32_MIN;
size_t nonzero[2] = {0, 0};
for (size_t i = 0; i < frames; i++) {
for (int ch = 0; ch < 2; ch++) {
int32_t v = buf[i * 2 + ch];
nonzero[ch] += (v != 0);
raw_min = v < raw_min ? v : raw_min;
raw_max = v > raw_max ? v : raw_max;
}
}
int ch = nonzero[1] > nonzero[0] ? 1 : 0;
for (size_t i = 0; i < frames; i++) {
// 24-bit sample sits in the top bits of the 32-bit slot
float x = (float)(buf[i * 2 + ch] >> 8) / FULL_SCALE_24BIT;
float y = x - hp_prev_in + 0.995f * hp_prev_out;
hp_prev_in = x;
hp_prev_out = y;
filtered[i] = y;
level_sum_sq += (double)y * y;
level_peak = fmaxf(level_peak, fabsf(y));
pcm[i] = (int16_t)fmaxf(fminf(y * CONFIG_MIC_STREAM_GAIN * 32767.0f, 32767.0f), -32768.0f);
}
level_frames += frames;
beat_feed(filtered, frames);
if (s_stream_active) {
// Drop audio rather than block capture if the listener falls behind
xStreamBufferSend(s_stream_buf, pcm, frames * sizeof(int16_t), 0);
}
if (++level_blocks < LEVEL_BLOCKS) {
continue;
}
mic_level_t level;
level.rms_dbfs = to_dbfs(sqrtf((float)(level_sum_sq / level_frames)));
level.peak_dbfs = to_dbfs(level_peak);
level.spl_db = level.rms_dbfs + INMP441_SPL_OFFSET;
level_sum_sq = 0.0;
level_peak = 0.0f;
level_frames = level_blocks = 0;
portENTER_CRITICAL(&s_level_lock);
s_level = level;
portEXIT_CRITICAL(&s_level_lock);
if (++log_count % 50 == 0) { // every 5 s
ESP_LOGI(TAG, "%s slot: RMS %.1f dBFS, peak %.1f dBFS, ~%.0f dB SPL",
ch ? "right" : "left", level.rms_dbfs, level.peak_dbfs, level.spl_db);
ESP_LOGI(TAG, "raw min %ld max %ld, nonzero L %u R %u of %u",
(long)raw_min, (long)raw_max, (unsigned)nonzero[0], (unsigned)nonzero[1], (unsigned)frames);
}
}
}
esp_err_t mic_start(void)
{
s_stream_buf = xStreamBufferCreate(STREAM_BUF_BYTES, 1);
ESP_RETURN_ON_FALSE(s_stream_buf, ESP_ERR_NO_MEM, TAG, "Stream buffer alloc failed");
i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_MASTER);
ESP_RETURN_ON_ERROR(i2s_new_channel(&chan_cfg, NULL, &s_rx_chan), TAG, "I2S channel create failed");
i2s_std_config_t std_cfg = {
.clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(MIC_SAMPLE_RATE),
.slot_cfg = I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_32BIT, I2S_SLOT_MODE_STEREO),
.gpio_cfg = {
.mclk = I2S_GPIO_UNUSED,
.bclk = CONFIG_MIC_SCK_GPIO,
.ws = CONFIG_MIC_WS_GPIO,
.dout = I2S_GPIO_UNUSED,
.din = CONFIG_MIC_SD_GPIO,
},
};
ESP_RETURN_ON_ERROR(i2s_channel_init_std_mode(s_rx_chan, &std_cfg), TAG, "I2S std mode init failed");
// SD tri-states outside the mic's slot; the datasheet asks for a pull-down
gpio_pullup_dis(CONFIG_MIC_SD_GPIO);
gpio_pulldown_en(CONFIG_MIC_SD_GPIO);
ESP_RETURN_ON_ERROR(i2s_channel_enable(s_rx_chan), TAG, "I2S enable failed");
ESP_RETURN_ON_ERROR(beat_start(MIC_SAMPLE_RATE), TAG, "Beat detector start failed");
if (xTaskCreate(mic_task, "mic", 6144, NULL, 5, NULL) != pdPASS) {
return ESP_ERR_NO_MEM;
}
ESP_LOGI(TAG, "INMP441 started at %d Hz", MIC_SAMPLE_RATE);
return ESP_OK;
}
void mic_get_level(mic_level_t *out)
{
portENTER_CRITICAL(&s_level_lock);
*out = s_level;
portEXIT_CRITICAL(&s_level_lock);
}
esp_err_t mic_stream_open(void)
{
if (s_stream_active) {
return ESP_ERR_INVALID_STATE;
}
xStreamBufferReset(s_stream_buf);
s_stream_active = true;
return ESP_OK;
}
size_t mic_stream_read(void *buf, size_t len, TickType_t timeout)
{
return xStreamBufferReceive(s_stream_buf, buf, len, timeout);
}
void mic_stream_close(void)
{
s_stream_active = false;
}
+25
View File
@@ -0,0 +1,25 @@
#pragma once
#include <stddef.h>
#include "esp_err.h"
#include "freertos/FreeRTOS.h"
#define MIC_SAMPLE_RATE 16000
typedef struct {
float rms_dbfs; // RMS level over the last block, dB relative to full scale
float peak_dbfs; // Peak sample in the last block, dBFS
float spl_db; // Approximate dB SPL (INMP441: -26 dBFS @ 94 dB SPL)
} mic_level_t;
// Start the INMP441 I2S capture and the level-measuring task
esp_err_t mic_start(void);
// Latest level reading; returns -120 dBFS until the first block arrives
void mic_get_level(mic_level_t *out);
// Single-listener 16-bit mono PCM stream at MIC_SAMPLE_RATE.
// Returns ESP_ERR_INVALID_STATE if someone is already listening.
esp_err_t mic_stream_open(void);
size_t mic_stream_read(void *buf, size_t len, TickType_t timeout);
void mic_stream_close(void);
+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;
}
+14
View File
@@ -0,0 +1,14 @@
#pragma once
#include "esp_err.h"
#include "esp_http_server.h"
// 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);
+350
View File
@@ -0,0 +1,350 @@
#include "rel.h"
#include <stdlib.h>
#include <string.h>
#include "esp_check.h"
#include "esp_log.h"
#include "esp_now.h"
#include "esp_random.h"
#include "esp_timer.h"
#include "bench.h"
#include "espnow_tx.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
// Reliable-link frames live inside the existing 0x4C wire protocol as extra message types
#define WIRE_MAGIC 0x4C
#define M_ANNOUNCE 0x01
#define M_DATA 0x20
#define M_ACK 0x21
#define M_DIGEST 0x22
#define M_RESYNC 0x23
#define M_ECHO 0x24
#define F_ACK 1
#define F_COMMIT 2
#define HDR 9
#define MAX_PENDING 32
#define MAX_TRIES 4
#define FIRST_RETRY_MS 60
#define DIGEST_PERIOD_US 1500000
#define MAX_PEERS 32
static const char *TAG = "rel";
typedef struct {
bool used;
uint8_t mac[6];
uint16_t seq;
uint8_t cnt, flags, tries;
uint32_t mask;
uint16_t ver;
uint8_t *msg;
size_t len;
int64_t next_us;
} pend_t;
typedef struct {
uint8_t mac[6];
uint8_t len;
uint8_t data[96];
} rx_t;
typedef struct {
bool used;
uint8_t mac[6];
int64_t last_ack_us;
int fails;
} peer_t;
static pend_t s_pend[MAX_PENDING];
static peer_t s_peer[MAX_PEERS];
static SemaphoreHandle_t s_lock;
static QueueHandle_t s_rx;
static uint16_t s_seq;
static volatile uint16_t s_ver;
static rel_stats_t s_stats;
static rel_resync_cb_t s_resync_cb;
static uint32_t full_mask(int cnt)
{
return cnt >= 32 ? 0xFFFFFFFFu : ((1u << cnt) - 1);
}
static peer_t *peer_get(const uint8_t *mac, bool create)
{
peer_t *free_slot = NULL;
for (int i = 0; i < MAX_PEERS; i++) {
if (s_peer[i].used && memcmp(s_peer[i].mac, mac, 6) == 0) {
return &s_peer[i];
}
if (!s_peer[i].used && !free_slot) {
free_slot = &s_peer[i];
}
}
if (create && free_slot) {
memset(free_slot, 0, sizeof(*free_slot));
free_slot->used = true;
free_slot->last_ack_us = -1;
memcpy(free_slot->mac, mac, 6);
}
return create ? free_slot : NULL;
}
static esp_err_t send_frag(const uint8_t *mac, uint8_t flags, uint16_t seq, uint16_t ver, const uint8_t *msg,
size_t len, int idx, int cnt)
{
uint8_t frame[HDR + REL_FRAG_MAX];
size_t off = (size_t)idx * REL_FRAG_MAX;
size_t n = len - off > REL_FRAG_MAX ? REL_FRAG_MAX : len - off;
frame[0] = WIRE_MAGIC;
frame[1] = M_DATA;
frame[2] = flags;
frame[3] = seq & 255;
frame[4] = seq >> 8;
frame[5] = ver & 255;
frame[6] = ver >> 8;
frame[7] = idx;
frame[8] = cnt;
memcpy(frame + HDR, msg + off, n);
return espnow_tx_send(mac, frame, HDR + n);
}
esp_err_t rel_send(const uint8_t *mac, const void *data, size_t len, bool commit, int repeat)
{
if (len == 0) {
return ESP_ERR_INVALID_SIZE;
}
int cnt = (len + REL_FRAG_MAX - 1) / REL_FRAG_MAX;
if (cnt > REL_MAX_FRAGS) {
return ESP_ERR_INVALID_SIZE;
}
uint8_t flags = (mac ? F_ACK : 0) | (commit ? F_COMMIT : 0);
uint16_t ver = s_ver;
xSemaphoreTake(s_lock, portMAX_DELAY);
uint16_t seq = ++s_seq;
pend_t *slot = NULL;
if (mac) {
for (int i = 0; i < MAX_PENDING && !slot; i++) {
slot = s_pend[i].used ? NULL : &s_pend[i];
}
if (!slot) {
xSemaphoreGive(s_lock);
return ESP_ERR_NO_MEM;
}
uint8_t *copy = malloc(len);
if (!copy) {
xSemaphoreGive(s_lock);
return ESP_ERR_NO_MEM;
}
memcpy(copy, data, len);
memset(slot, 0, sizeof(*slot));
slot->used = true;
memcpy(slot->mac, mac, 6);
slot->seq = seq;
slot->cnt = cnt;
slot->flags = flags;
slot->ver = ver;
slot->msg = copy;
slot->len = len;
slot->next_us = esp_timer_get_time() + FIRST_RETRY_MS * 1000;
}
xSemaphoreGive(s_lock);
esp_err_t ret = ESP_OK;
for (int r = 0; r < (mac ? 1 : (repeat < 1 ? 1 : repeat)) && ret == ESP_OK; r++) {
for (int i = 0; i < cnt && ret == ESP_OK; i++) {
ret = send_frag(mac, flags, seq, ver, data, len, i, cnt);
}
}
if (ret != ESP_OK && slot) { // queue full: caller retries the whole message under a new sequence
xSemaphoreTake(s_lock, portMAX_DELAY);
free(slot->msg);
slot->used = false;
xSemaphoreGive(s_lock);
}
return ret;
}
void rel_bump_ver(void)
{
uint16_t v = s_ver + 1;
s_ver = v ? v : 1; // 0 means "no state" to drivers
}
uint16_t rel_ver(void)
{
return s_ver;
}
void rel_set_resync_cb(rel_resync_cb_t cb)
{
s_resync_cb = cb;
}
void rel_stats(rel_stats_t *out)
{
*out = s_stats;
}
int rel_peer_status(const uint8_t mac[6], int *fails)
{
int age = -1;
xSemaphoreTake(s_lock, portMAX_DELAY);
peer_t *p = peer_get(mac, false);
if (p) {
age = p->last_ack_us < 0 ? -1 : (int)((esp_timer_get_time() - p->last_ack_us) / 1000);
if (fails) {
*fails = p->fails;
}
} else if (fails) {
*fails = 0;
}
xSemaphoreGive(s_lock);
return age;
}
static rel_announce_cb_t s_announce_cb;
void rel_set_announce_cb(rel_announce_cb_t cb)
{
s_announce_cb = cb;
}
static void recv_cb(const esp_now_recv_info_t *info, const uint8_t *data, int len)
{
int64_t now = esp_timer_get_time(); // before anything else: echoes are timing measurements
if (len < 3 || len > (int)sizeof(((rx_t *)0)->data)) {
return;
}
// A driver's boot hello is either a 0x4C ANNOUNCE or a small JSON object; everything else we
// care about is a link reply inside 0x4C
bool announce = (data[0] == WIRE_MAGIC && data[1] == M_ANNOUNCE) || data[0] == '{';
bool reply = data[0] == WIRE_MAGIC && (data[1] == M_ACK || data[1] == M_RESYNC || data[1] == M_ECHO);
if (!announce && !reply) {
return;
}
if (reply && espnow_tx_drop()) { // lossy-link test: this reply never arrived
return;
}
if (reply && data[1] == M_ECHO) {
bench_on_echo(info->src_addr, data[2] | (data[3] << 8), now);
return;
}
rx_t rx = { .len = len };
memcpy(rx.mac, info->src_addr, 6);
memcpy(rx.data, data, len);
xQueueSend(s_rx, &rx, 0); // dropping an ack only costs a retransmit
}
static void handle_rx(const rx_t *rx)
{
if (rx->data[0] == '{' || rx->data[1] == M_ANNOUNCE) {
if (s_announce_cb) {
s_announce_cb(rx->mac, rx->data, rx->len);
}
return;
}
if (rx->data[1] == M_RESYNC) {
s_stats.resyncs++;
if (s_resync_cb) {
s_resync_cb(rx->mac);
}
return;
}
if (rx->len < 10) { // [4C][21][0][seq u16][cnt][mask u32]
return;
}
uint16_t seq = rx->data[3] | (rx->data[4] << 8);
uint32_t mask = rx->data[6] | (rx->data[7] << 8) | (rx->data[8] << 16) | ((uint32_t)rx->data[9] << 24);
xSemaphoreTake(s_lock, portMAX_DELAY);
for (int i = 0; i < MAX_PENDING; i++) {
pend_t *p = &s_pend[i];
if (p->used && p->seq == seq && memcmp(p->mac, rx->mac, 6) == 0) {
p->mask |= mask;
if ((p->mask & full_mask(p->cnt)) == full_mask(p->cnt)) {
peer_t *pe = peer_get(p->mac, true);
if (pe) {
pe->last_ack_us = esp_timer_get_time();
pe->fails = 0;
}
s_stats.acked++;
free(p->msg);
p->used = false;
}
break;
}
}
xSemaphoreGive(s_lock);
}
static void retry_pending(void)
{
int64_t now = esp_timer_get_time();
xSemaphoreTake(s_lock, portMAX_DELAY);
for (int i = 0; i < MAX_PENDING; i++) {
pend_t *p = &s_pend[i];
if (!p->used || now < p->next_us) {
continue;
}
if (p->tries >= MAX_TRIES) {
peer_t *pe = peer_get(p->mac, true);
if (pe) {
pe->fails++;
}
s_stats.ack_timeouts++;
free(p->msg);
p->used = false;
continue;
}
for (int f = 0; f < p->cnt; f++) {
if (!(p->mask & (1u << f))) {
if (send_frag(p->mac, p->flags, p->seq, p->ver, p->msg, p->len, f, p->cnt) != ESP_OK) {
break; // queue full; try again next round
}
s_stats.retransmits++;
}
}
p->tries++;
p->next_us = now + ((int64_t)(FIRST_RETRY_MS << p->tries)) * 1000;
}
xSemaphoreGive(s_lock);
}
static void rel_task(void *arg)
{
int64_t next_digest = 0;
for (;;) {
rx_t rx;
if (xQueueReceive(s_rx, &rx, pdMS_TO_TICKS(20)) == pdTRUE) {
handle_rx(&rx);
continue; // drain before retrying
}
retry_pending();
int64_t now = esp_timer_get_time();
if (now >= next_digest) {
uint16_t v = s_ver;
uint8_t d[4] = { WIRE_MAGIC, M_DIGEST, v & 255, v >> 8 };
if (espnow_tx_send(NULL, d, sizeof(d)) == ESP_OK) {
s_stats.digests++;
}
next_digest = now + DIGEST_PERIOD_US;
}
}
}
esp_err_t rel_init(void)
{
s_lock = xSemaphoreCreateMutex();
s_rx = xQueueCreate(16, sizeof(rx_t));
ESP_RETURN_ON_FALSE(s_lock && s_rx, ESP_ERR_NO_MEM, TAG, "alloc");
s_seq = esp_random() & 0xFFFF; // drivers remember recent (mac, seq); a restart must not reuse them
s_ver = (esp_random() % 0x7FFE) + 1; // new epoch per boot, so a rebooted controller never matches stale drivers
ESP_RETURN_ON_ERROR(esp_now_register_recv_cb(recv_cb), TAG, "recv cb");
xTaskCreate(rel_task, "rel", 4096, NULL, 6, NULL);
ESP_LOGI(TAG, "reliable link up, state version %u", s_ver);
return ESP_OK;
}
+49
View File
@@ -0,0 +1,49 @@
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "esp_err.h"
// Reliable bulk link on top of espnow_tx. Wire format is documented in
// led-driver/src/espnow_rx.py:
// All frames are 0x4C wire packets with extra message types (see led-driver/src/espnow_rx.py):
// data [4C][20][flags][seq u16][ver u16][idx][cnt] + fragment of an inner packet (<= 9 + 238)
// ack [4C][21][0][seq u16][cnt][mask u32] (driver -> us)
// digest [4C][22][ver u16] (broadcast)
// resync [4C][23][ver u16] (driver -> us)
// echo [4C][24][beat_idx u16] (driver -> us, bench)
#define REL_FRAG_MAX 238 // inner packet bytes per frame; 4C 03/04 wrappers plus an envelope fit in one
#define REL_MAX_FRAGS 32
typedef struct {
uint32_t acked;
uint32_t ack_timeouts;
uint32_t retransmits;
uint32_t resyncs;
uint32_t digests;
} rel_stats_t;
typedef void (*rel_resync_cb_t)(const uint8_t mac[6]);
esp_err_t rel_init(void);
// Send a message of any size up to REL_MAX_FRAGS * REL_FRAG_MAX.
// mac == NULL broadcasts it `repeat` times with one sequence number (no acks);
// otherwise it is unicast, acknowledged by the driver and retransmitted until
// acked or given up on. commit makes the driver adopt the current state version.
esp_err_t rel_send(const uint8_t *mac, const void *data, size_t len, bool commit, int repeat);
// A broadcast state change happened: advance the version drivers compare in digests
void rel_bump_ver(void);
uint16_t rel_ver(void);
void rel_set_resync_cb(rel_resync_cb_t cb);
// A driver announced itself at boot: a 0x4C ANNOUNCE packet or its JSON hello (called from the rel task)
typedef void (*rel_announce_cb_t)(const uint8_t mac[6], const uint8_t *pkt, int len);
void rel_set_announce_cb(rel_announce_cb_t cb);
void rel_stats(rel_stats_t *out);
// Milliseconds since the driver last acked; -1 if never. fails = consecutive unacked messages
int rel_peer_status(const uint8_t mac[6], int *fails);
+163
View File
@@ -0,0 +1,163 @@
#include "store.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "esp_check.h"
#include "esp_littlefs.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
static const char *TAG = "store";
static const char *const NAMES[] = {
"device", "zone", "preset", "profile", "palette", "pattern",
"sequence", "scene", "group", "output", "settings",
};
#define N_COLL (sizeof(NAMES) / sizeof(NAMES[0]))
static cJSON *s_coll[N_COLL];
static SemaphoreHandle_t s_lock;
static int index_of(const char *name)
{
for (size_t i = 0; i < N_COLL; i++) {
if (strcmp(NAMES[i], name) == 0) {
return (int)i;
}
}
return -1;
}
static esp_err_t mount(const char *label, const char *base)
{
esp_vfs_littlefs_conf_t conf = {
.base_path = base,
.partition_label = label,
.format_if_mount_failed = true,
.grow_on_mount = true, // the db partition spans the rest of the flash; an older, smaller filesystem is extended in place
};
return esp_vfs_littlefs_register(&conf);
}
static cJSON *load_file(const char *name)
{
char path[48];
snprintf(path, sizeof(path), "/db/%s.json", name);
FILE *f = fopen(path, "rb");
if (!f) {
return cJSON_CreateObject();
}
fseek(f, 0, SEEK_END);
long n = ftell(f);
fseek(f, 0, SEEK_SET);
char *buf = malloc(n + 1);
cJSON *obj = NULL;
if (buf) {
buf[fread(buf, 1, n, f)] = 0;
obj = cJSON_Parse(buf);
free(buf);
}
fclose(f);
if (!cJSON_IsObject(obj)) {
ESP_LOGW(TAG, "%s: unreadable, starting empty", path);
cJSON_Delete(obj);
obj = cJSON_CreateObject();
}
return obj;
}
esp_err_t store_init(void)
{
s_lock = xSemaphoreCreateRecursiveMutex();
ESP_RETURN_ON_FALSE(s_lock, ESP_ERR_NO_MEM, TAG, "mutex");
ESP_RETURN_ON_ERROR(mount("db", "/db"), TAG, "mount db");
for (size_t i = 0; i < N_COLL; i++) {
s_coll[i] = load_file(NAMES[i]);
ESP_LOGI(TAG, "%s: %d records", NAMES[i], cJSON_GetArraySize(s_coll[i]));
}
return ESP_OK;
}
bool store_known(const char *name)
{
return index_of(name) >= 0;
}
cJSON *store_coll(const char *name)
{
int i = index_of(name);
return i < 0 ? NULL : s_coll[i];
}
esp_err_t store_save(const char *name)
{
int i = index_of(name);
ESP_RETURN_ON_FALSE(i >= 0, ESP_ERR_NOT_FOUND, TAG, "unknown collection");
char *json = cJSON_PrintUnformatted(s_coll[i]);
ESP_RETURN_ON_FALSE(json, ESP_ERR_NO_MEM, TAG, "print");
char tmp[48], path[48];
snprintf(tmp, sizeof(tmp), "/db/%s.tmp", name);
snprintf(path, sizeof(path), "/db/%s.json", name);
FILE *f = fopen(tmp, "wb");
esp_err_t ret = ESP_FAIL;
if (f) {
size_t len = strlen(json);
bool ok = fwrite(json, 1, len, f) == len;
ok = fclose(f) == 0 && ok;
if (ok) {
remove(path); // littlefs rename-over is not guaranteed on every version
ok = rename(tmp, path) == 0;
}
ret = ok ? ESP_OK : ESP_FAIL;
}
free(json);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "saving %s failed", name);
}
return ret;
}
esp_err_t store_replace(const char *name, cJSON *obj)
{
int i = index_of(name);
if (i < 0 || !cJSON_IsObject(obj)) {
cJSON_Delete(obj);
return ESP_ERR_INVALID_ARG;
}
cJSON_Delete(s_coll[i]);
s_coll[i] = obj;
return store_save(name);
}
void store_next_id(const char *name, char *buf, size_t len)
{
long max = 0;
cJSON *c = store_coll(name), *it;
cJSON_ArrayForEach(it, c)
{
char *end;
long v = strtol(it->string, &end, 10);
if (*end == 0 && v > max) {
max = v;
}
}
snprintf(buf, len, "%ld", max + 1);
}
cJSON *store_settings(void)
{
return store_coll("settings");
}
void store_lock(void)
{
xSemaphoreTakeRecursive(s_lock, portMAX_DELAY);
}
void store_unlock(void)
{
xSemaphoreGiveRecursive(s_lock);
}
+30
View File
@@ -0,0 +1,30 @@
#pragma once
#include <stdbool.h>
#include "cJSON.h"
#include "esp_err.h"
// JSON "database": one file per collection under /db, each an object of
// id -> record, mirroring the Pi's db/*.json. Collections stay in memory and
// are written back (via a temp file and rename) whenever they change.
// Mount the db partition and load every collection
esp_err_t store_init(void);
// Borrowed pointer to the collection object (id -> record); never NULL for a known name
cJSON *store_coll(const char *name);
bool store_known(const char *name);
// Replace a whole collection with a parsed object (takes ownership) and persist it
esp_err_t store_replace(const char *name, cJSON *obj);
esp_err_t store_save(const char *name);
// Next numeric string id for a collection ("1" when empty); writes into buf
void store_next_id(const char *name, char *buf, size_t len);
// Settings are one flat object (the "settings" collection itself)
cJSON *store_settings(void);
// Recursive lock around every read or write of the collections (HTTP handlers and the sequencer)
void store_lock(void);
void store_unlock(void);
+138
View File
@@ -0,0 +1,138 @@
#include "web.h"
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include "esp_log.h"
static const char *TAG = "web";
static const struct {
const char *ext;
const char *type;
} MIME[] = {
{ ".html", "text/html; charset=utf-8" },
{ ".js", "application/javascript; charset=utf-8" },
{ ".css", "text/css; charset=utf-8" },
{ ".json", "application/json" },
{ ".svg", "image/svg+xml" },
{ ".png", "image/png" },
{ ".ico", "image/x-icon" },
{ ".woff2", "font/woff2" },
};
static const char *mime_for(const char *path)
{
const char *dot = strrchr(path, '.');
for (size_t i = 0; dot && i < sizeof(MIME) / sizeof(MIME[0]); i++) {
if (strcmp(dot, MIME[i].ext) == 0) {
return MIME[i].type;
}
}
return "application/octet-stream";
}
// The web UI is one blob linked into the app image (www_dist/www.pack, see tools/build_web.sh):
// "WWW1", then per file u16 name length, u32 data length, the name, the gzipped data; a zero name
// length ends it.
extern const uint8_t www_pack_start[] asm("_binary_www_pack_start");
extern const uint8_t www_pack_end[] asm("_binary_www_pack_end");
static bool find_file(const char *path, const uint8_t **data, uint32_t *len)
{
const uint8_t *p = www_pack_start, *end = www_pack_end;
if (end - p < 6 || memcmp(p, "WWW1", 4) != 0) {
return false;
}
p += 4;
size_t want = strlen(path);
while (end - p >= 2) {
uint16_t nlen;
memcpy(&nlen, p, 2);
if (nlen == 0 || end - p < 6 + nlen) {
return false;
}
uint32_t dlen;
memcpy(&dlen, p + 2, 4);
const uint8_t *name = p + 6, *body = name + nlen;
if (end - body < (ptrdiff_t)dlen) {
return false;
}
if (nlen == want && memcmp(name, path, want) == 0) {
*data = body;
*len = dlen;
return true;
}
p = body + dlen;
}
return false;
}
// path is the URL-relative name, e.g. "static/zones.js"
static esp_err_t send_gz(httpd_req_t *req, const char *path, bool immutable)
{
const uint8_t *data;
uint32_t len;
if (strstr(path, "..")) {
return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "bad path");
}
if (!find_file(path, &data, &len)) {
return httpd_resp_send_404(req);
}
httpd_resp_set_type(req, mime_for(path));
httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
httpd_resp_set_hdr(req, "Cache-Control", immutable ? "public, max-age=86400" : "no-cache");
return httpd_resp_send(req, (const char *)data, len);
}
esp_err_t web_send_page(httpd_req_t *req, const char *name)
{
return send_gz(req, name, false);
}
static esp_err_t index_handler(httpd_req_t *req)
{
return send_gz(req, "index.html", false);
}
static esp_err_t audio_page_handler(httpd_req_t *req)
{
return send_gz(req, "audio.html", false);
}
static esp_err_t static_handler(httpd_req_t *req)
{
char path[96];
const char *uri = req->uri + 1; // drop the leading '/'
size_t n = strcspn(uri, "?");
if (n >= sizeof(path)) {
return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "uri too long");
}
memcpy(path, uri, n);
path[n] = 0;
return send_gz(req, path, true);
}
static esp_err_t favicon_handler(httpd_req_t *req)
{
httpd_resp_set_status(req, "204 No Content");
return httpd_resp_send(req, NULL, 0);
}
esp_err_t web_register(httpd_handle_t server)
{
const httpd_uri_t uris[] = {
{ .uri = "/", .method = HTTP_GET, .handler = index_handler },
{ .uri = "/audio", .method = HTTP_GET, .handler = audio_page_handler },
{ .uri = "/static/*", .method = HTTP_GET, .handler = static_handler },
{ .uri = "/favicon.ico", .method = HTTP_GET, .handler = favicon_handler },
};
for (size_t i = 0; i < sizeof(uris) / sizeof(uris[0]); i++) {
esp_err_t err = httpd_register_uri_handler(server, &uris[i]);
if (err != ESP_OK) {
ESP_LOGE(TAG, "register %s: %s", uris[i].uri, esp_err_to_name(err));
return err;
}
}
return ESP_OK;
}
+11
View File
@@ -0,0 +1,11 @@
#pragma once
#include "esp_err.h"
#include "esp_http_server.h"
// Register /, /audio, /static/* and /favicon.ico. Files come from the web UI blob embedded in the
// firmware (gzipped, sent with Content-Encoding: gzip).
esp_err_t web_register(httpd_handle_t server);
// Send one of the top-level pages (e.g. "settings.html")
esp_err_t web_send_page(httpd_req_t *req, const char *name);