Files
jimmyandClaude Haiku 5.5 f0615dc1b7 feat: users, roles and per-area permissions, production demo image
The controller checks every route against the signed-in user's role, with
levels none, view, control and edit per area. Guests get the permissions
of a built-in guest role. Auth stays off until the first user exists;
LED_ADMIN_USER and LED_ADMIN_PASSWORD create the first admin.

Sessions are cookies, passwords are PBKDF2-SHA256, and logins lock per
username after five failures. The simulator's WebSocket checks the view
permission at handshake and per frame; /ws needs devices control. The web
UI gets a sign-in button, a sign-in prompt on refused changes, and a users
and roles screen.

Also: the device build gets the bridge include path and forward type it
was missing, Dockerfile.sim runs non-root, and Dockerfile.prod with
docker-compose.prod.yml runs the controller on an internal network behind
Caddy for HTTPS.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-11-17 00:29:04 +13:00

1008 lines
37 KiB
C

/*
* The simulated rig, served by the host build: see sim_rig.h.
*
* GET /sim/ the rig page; /sim/gallery the pattern gallery; /sim/<file> its files
* (sim.pack, embedded: led-simulator/web and the built wasm). The drivers run
* without threads, so the page needs no cross-origin isolation: any address works
* WS /sim/ws the page's radio. One page at a time: a new one takes over.
* page -> here binary src_mac(6) + ESP-NOW packet a driver transmitted (bridge_browser_rx)
* here -> page binary dst_mac(6) + ESP-NOW packet the controller transmitted (sim_rig_tx)
* page -> here text {"t":"flash","mac":"..","data":"<NVS JSON>"} a driver committed its flash
* here -> page text {"t":"takeover"} another page opened the rig
* GET /sim/api/config the active room, its strips, the room list and the bridge
* GET /sim/api/flash/<mac> a strip's NVS store, brought in line with its room (num_leds, channel)
* GET /sim/api/rooms {current, rooms}
* POST /sim/api/rooms {name, width, depth, copy_from?}: a new room
* GET|PUT|DELETE /sim/api/rooms/<name>
* POST /sim/api/room {name}: switch the rig to that room
* GET /sim/api/next-mac?taken= a MAC no room uses
*
* Rooms follow the stage maps of the qlcplus simulator: one JSON file per room in <db>/sim/rooms/, a size in
* metres, strip types ("definitions") and "fixtures" keyed by id, each one LED bar: x, y (metres) is pixel 0,
* "direction" the way it runs (degrees clockwise from +y), "mac" the driver. Each bar's flash is
* <db>/sim/flash/<mac>.json, so a bar keeps its presets in every room it appears in.
*/
#include "auth.h"
#include "sim_rig.h"
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include "api_util.h"
#include "bridge.h"
#include "cJSON.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "store.h"
static const char *TAG = "sim_rig";
#define MAX_FIXTURES 64
#define MAX_LEDS 512 // FX_LEDS_MAX in led-driver/main/effects.h
#define FLASH_MAX (512 * 1024)
#define FRAME_MAX (FLASH_MAX + 1024)
#define DEFAULT_PITCH_M (1.0 / 60) // 60 LEDs per metre
#define BRIDGE_SIM_MAC "02:51:4d:00:00:00"
#define MAC_PREFIX "02:51:4d"
#define ORIGIN_TEXT "X=0 at the room centre, +X right; Y=0 at the front edge, +Y up the screen; headings clockwise from +Y"
#define WIFI_CHANNEL 5
/* ------------------------------------------------------------------ the embedded page */
// sim.pack: the same format as www.pack (see main/web.c): "WWW1", then per file u16 name length, u32 data
// length, the name, the gzipped data; a zero name length ends it. Built by tools/build_sim_web.sh.
extern const uint8_t sim_pack_start[] asm("_binary_sim_pack_start");
extern const uint8_t sim_pack_end[] asm("_binary_sim_pack_end");
static bool find_file(const char *path, const uint8_t **data, uint32_t *len)
{
const uint8_t *p = sim_pack_start, *end = sim_pack_end;
if (end - p < 6 || memcmp(p, "WWW1", 4) != 0) {
return false;
}
p += 4;
size_t want = strlen(path);
while (end - p >= 6) {
uint16_t nlen;
uint32_t dlen;
memcpy(&nlen, p, 2);
memcpy(&dlen, p + 2, 4);
if (nlen == 0 || end - p < 6 + nlen + (ptrdiff_t)dlen) {
return false;
}
const uint8_t *name = p + 6, *body = name + nlen;
if (nlen == want && memcmp(name, path, want) == 0) {
*data = body;
*len = dlen;
return true;
}
p = body + dlen;
}
return false;
}
static const char *mime_for(const char *path)
{
static const struct {
const char *ext, *type;
} M[] = {
{ ".html", "text/html; charset=utf-8" }, { ".mjs", "text/javascript; charset=utf-8" },
{ ".js", "text/javascript; charset=utf-8" }, { ".css", "text/css; charset=utf-8" },
{ ".wasm", "application/wasm" }, { ".json", "application/json" },
};
const char *dot = strrchr(path, '.');
for (size_t i = 0; dot && i < sizeof(M) / sizeof(M[0]); i++) {
if (!strcmp(dot, M[i].ext)) {
return M[i].type;
}
}
return "application/octet-stream";
}
static esp_err_t send_file(httpd_req_t *req, const char *path)
{
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)) {
if (!find_file("index.html", &data, &len)) {
httpd_resp_set_type(req, "text/plain");
return httpd_resp_sendstr(req, "The simulated rig is not in this build: run `make sim-wasm`, then rebuild "
"(make sim-web, or make desktop).");
}
return httpd_resp_send_404(req);
}
httpd_resp_set_hdr(req, "Cache-Control", "no-cache");
httpd_resp_set_type(req, mime_for(path));
httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
return httpd_resp_send(req, (const char *)data, len);
}
static esp_err_t page_handler(httpd_req_t *req)
{
if (!strcmp(req->uri, "/sim")) {
httpd_resp_set_status(req, "302 Found");
httpd_resp_set_hdr(req, "Location", "/sim/");
return httpd_resp_send(req, NULL, 0);
}
char path[96];
const char *rel = req->uri + 5; // after "/sim/"
size_t n = strcspn(rel, "?");
if (n >= sizeof(path) - 6) {
return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "uri too long");
}
memcpy(path, rel, n);
path[n] = 0;
if (!path[0]) {
snprintf(path, sizeof(path), "index.html");
} else if (!strcmp(path, "gallery")) {
snprintf(path, sizeof(path), "gallery.html");
}
return send_file(req, path);
}
/* ------------------------------------------------------------------ files under <db>/sim */
static SemaphoreHandle_t s_mu; // rooms, flash files, the active room
static const char *db_root(void)
{
const char *d = getenv("LED_SIM_DB");
return d && d[0] ? d : "/db";
}
static void sim_path(char *out, size_t n, const char *sub, const char *name, const char *ext)
{
snprintf(out, n, "%s/sim/%s%s%s%s", db_root(), sub, sub[0] ? "/" : "", name, ext);
}
static void ensure_dirs(void)
{
char p[300];
snprintf(p, sizeof(p), "%s/sim", db_root());
mkdir(p, 0755);
snprintf(p, sizeof(p), "%s/sim/rooms", db_root());
mkdir(p, 0755);
snprintf(p, sizeof(p), "%s/sim/flash", db_root());
mkdir(p, 0755);
}
static char *read_text(const char *path, size_t max)
{
FILE *f = fopen(path, "rb");
if (!f) {
return NULL;
}
fseek(f, 0, SEEK_END);
long size = ftell(f);
fseek(f, 0, SEEK_SET);
char *buf = NULL;
if (size >= 0 && (size_t)size <= max && (buf = malloc((size_t)size + 1))) {
size_t got = fread(buf, 1, (size_t)size, f);
buf[got] = 0;
}
fclose(f);
return buf;
}
static cJSON *read_json(const char *path)
{
char *t = read_text(path, FLASH_MAX);
cJSON *o = t ? cJSON_Parse(t) : NULL;
free(t);
if (!cJSON_IsObject(o)) {
cJSON_Delete(o);
return NULL;
}
return o;
}
static bool write_text(const char *path, const char *text)
{
char tmp[310];
snprintf(tmp, sizeof(tmp), "%s.tmp", path);
FILE *f = fopen(tmp, "wb");
if (!f) {
return false;
}
size_t len = strlen(text);
bool ok = fwrite(text, 1, len, f) == len;
ok = fclose(f) == 0 && ok;
return ok && rename(tmp, path) == 0;
}
static bool write_json(const char *path, const cJSON *o, bool pretty)
{
char *t = pretty ? cJSON_Print(o) : cJSON_PrintUnformatted(o);
bool ok = t && write_text(path, t);
free(t);
return ok;
}
/* ------------------------------------------------------------------ rooms */
static bool name_ok(const char *s, size_t max, const char *extra)
{
size_t n = s ? strlen(s) : 0;
if (n == 0 || n > max) {
return false;
}
for (size_t i = 0; i < n; i++) {
if (!isalnum((unsigned char)s[i]) && !strchr(extra, s[i])) {
return false;
}
}
return true;
}
static bool room_name_ok(const char *s)
{
return name_ok(s, 40, "-_");
}
static bool id_ok(const char *s)
{
return name_ok(s, 40, "-_.#");
}
static bool mac_ok(const char *s)
{
if (!s || strlen(s) != 17) {
return false;
}
for (int i = 0; i < 17; i++) {
if (i % 3 == 2 ? s[i] != ':' : !isxdigit((unsigned char)s[i])) {
return false;
}
}
return strcasecmp(s, "ff:ff:ff:ff:ff:ff") && strcasecmp(s, BRIDGE_SIM_MAC);
}
static double round_to(double v, double step)
{
return round(v / step) * step;
}
static double wrap_deg(double d)
{
d = fmod(d, 360.0);
if (d <= -180) {
d += 360;
} else if (d > 180) {
d -= 360;
}
return d;
}
// The number at key in o, within lo..hi; else *err is set
static double num_in(const cJSON *o, const char *key, double def, double lo, double hi, const char *what,
char *err, size_t errn)
{
const cJSON *v = cJSON_GetObjectItem(o, key);
if (!v || cJSON_IsNull(v)) {
return def;
}
if (!cJSON_IsNumber(v) || !isfinite(v->valuedouble) || v->valuedouble < lo || v->valuedouble > hi) {
if (!err[0]) {
snprintf(err, errn, "%s must be a number from %g to %g", what, lo, hi);
}
return def;
}
return v->valuedouble;
}
// The room in canonical form (a new object), or NULL with the reason in err
static cJSON *validate_room(const cJSON *raw, const char *name, char *err, size_t errn)
{
err[0] = 0;
if (!cJSON_IsObject(raw)) {
snprintf(err, errn, "a room is a JSON object");
return NULL;
}
cJSON *room = cJSON_CreateObject();
const cJSON *nm = cJSON_GetObjectItem(raw, "name");
cJSON_AddStringToObject(room, "name", cJSON_IsString(nm) && nm->valuestring[0] ? nm->valuestring : name);
cJSON_AddStringToObject(room, "units", "metres");
cJSON_AddNumberToObject(room, "width", round_to(num_in(raw, "width", 6, 0.5, 200, "width", err, errn), 0.001));
cJSON_AddNumberToObject(room, "depth", round_to(num_in(raw, "depth", 4, 0.5, 200, "depth", err, errn), 0.001));
const cJSON *org = cJSON_GetObjectItem(raw, "origin");
cJSON_AddStringToObject(room, "origin",
cJSON_IsString(org) && org->valuestring[0] && strlen(org->valuestring) < 300 ? org->valuestring
: ORIGIN_TEXT);
const cJSON *defs_in = cJSON_GetObjectItem(raw, "definitions"), *d;
cJSON *defs = cJSON_AddObjectToObject(room, "definitions");
if (!cJSON_IsObject(defs_in) || !cJSON_GetArraySize(defs_in)) {
snprintf(err, errn, "a room needs at least one strip type in definitions");
}
cJSON_ArrayForEach(d, defs_in)
{
if (err[0]) {
break;
}
if (!id_ok(d->string) || !cJSON_IsObject(d)) {
snprintf(err, errn, "strip type names are 1-40 letters, digits or -_.#, each an object");
break;
}
char what[80];
snprintf(what, sizeof(what), "%s leds", d->string);
double leds = num_in(d, "leds", -1, 1, MAX_LEDS, what, err, errn);
if (leds < 0 && !err[0]) {
snprintf(err, errn, "%s needs leds", d->string);
}
snprintf(what, sizeof(what), "%s pitch_m", d->string);
double pitch = num_in(d, "pitch_m", DEFAULT_PITCH_M, 0.001, 1, what, err, errn);
cJSON *o = cJSON_AddObjectToObject(defs, d->string);
cJSON_AddNumberToObject(o, "leds", (int)leds);
cJSON_AddNumberToObject(o, "pitch_m", round_to(pitch, 0.00001));
}
const cJSON *fx_in = cJSON_GetObjectItem(raw, "fixtures"), *f;
cJSON *fixtures = cJSON_AddObjectToObject(room, "fixtures");
if (!err[0] && fx_in && !cJSON_IsObject(fx_in)) {
snprintf(err, errn, "fixtures must be an object keyed by id");
}
if (!err[0] && cJSON_GetArraySize(fx_in) > MAX_FIXTURES) {
snprintf(err, errn, "at most %d strips in a room", MAX_FIXTURES);
}
cJSON_ArrayForEach(f, fx_in)
{
if (err[0]) {
break;
}
const char *fid = f->string;
if (!id_ok(fid) || !cJSON_IsObject(f)) {
snprintf(err, errn, "strip ids are 1-40 letters, digits or -_.#, each an object");
break;
}
const cJSON *def = cJSON_GetObjectItem(f, "def"), *mac = cJSON_GetObjectItem(f, "mac");
const cJSON *label = cJSON_GetObjectItem(f, "label");
if (!cJSON_IsString(def) || !cJSON_GetObjectItem(defs, def->valuestring)) {
snprintf(err, errn, "strip %s: unknown strip type", fid);
break;
}
if (!cJSON_IsString(mac) || !mac_ok(mac->valuestring)) {
snprintf(err, errn, "strip %s: mac must be like 02:51:4d:00:00:01", fid);
break;
}
char m[18];
snprintf(m, sizeof(m), "%s", mac->valuestring);
for (char *c = m; *c; c++) {
*c = (char)tolower((unsigned char)*c);
}
const cJSON *other;
cJSON_ArrayForEach(other, fixtures)
{
const cJSON *om = cJSON_GetObjectItem(other, "mac");
if (cJSON_IsString(om) && !strcmp(om->valuestring, m)) {
snprintf(err, errn, "strip %s: mac %s is used twice in this room", fid, m);
}
}
if (err[0]) {
break;
}
char what[80];
cJSON *o = cJSON_AddObjectToObject(fixtures, fid);
char lab[48];
snprintf(lab, sizeof(lab), "%s", cJSON_IsString(label) && label->valuestring[0] ? label->valuestring : fid);
cJSON_AddStringToObject(o, "label", lab);
cJSON_AddStringToObject(o, "def", def->valuestring);
cJSON_AddStringToObject(o, "mac", m);
snprintf(what, sizeof(what), "%s x", fid);
cJSON_AddNumberToObject(o, "x", round_to(num_in(f, "x", 0, -1000, 1000, what, err, errn), 0.001));
snprintf(what, sizeof(what), "%s y", fid);
cJSON_AddNumberToObject(o, "y", round_to(num_in(f, "y", 0, -1000, 1000, what, err, errn), 0.001));
snprintf(what, sizeof(what), "%s direction", fid);
cJSON_AddNumberToObject(o, "direction",
round_to(wrap_deg(num_in(f, "direction", 90, -3600, 3600, what, err, errn)), 0.1));
const cJSON *leds = cJSON_GetObjectItem(f, "leds");
if (leds && !cJSON_IsNull(leds)) {
snprintf(what, sizeof(what), "%s leds", fid);
cJSON_AddNumberToObject(o, "leds", (int)num_in(f, "leds", 1, 1, MAX_LEDS, what, err, errn));
}
}
if (err[0]) {
cJSON_Delete(room);
return NULL;
}
return room;
}
// The original rig: 16 bars of 119 LEDs in 2 columns x 8 rows, pixel 0 at the centre line (see the loop below)
static cJSON *default_room(void)
{
const int rows = 8, cols = 2, leds = 119;
const double pitch = DEFAULT_PITCH_M, length = leds * pitch, gap = 0.2, row_h = 0.3;
const double span = cols * length + (cols - 1) * gap;
const double width = round_to(span + 1.0, 0.01), depth = round_to(rows * row_h + 0.6, 0.01);
cJSON *raw = cJSON_CreateObject();
cJSON_AddStringToObject(raw, "name", "default");
cJSON_AddNumberToObject(raw, "width", width);
cJSON_AddNumberToObject(raw, "depth", depth);
cJSON *defs = cJSON_AddObjectToObject(raw, "definitions");
cJSON *def = cJSON_AddObjectToObject(defs, "bar-119");
cJSON_AddNumberToObject(def, "leds", leds);
cJSON_AddNumberToObject(def, "pitch_m", pitch);
cJSON *fx = cJSON_AddObjectToObject(raw, "fixtures");
for (int i = 0; i < rows * cols; i++) {
// Bars 1-8 are the left column, top to bottom; 9-16 the right column. Pixel 0 sits at the centre line
// and the bar runs outwards from it: the left column leftwards, the right column rightwards.
int row = i % rows, col = i / rows;
bool left_col = col == 0;
char label[16], mac[18];
snprintf(label, sizeof(label), "sim-%02d", i + 1);
snprintf(mac, sizeof(mac), MAC_PREFIX ":00:00:%02x", i + 1);
cJSON *f = cJSON_AddObjectToObject(fx, label);
cJSON_AddStringToObject(f, "label", label);
cJSON_AddStringToObject(f, "def", "bar-119");
cJSON_AddStringToObject(f, "mac", mac);
cJSON_AddNumberToObject(f, "x", left_col ? -gap / 2 : gap / 2);
cJSON_AddNumberToObject(f, "y", depth - 0.3 - (row + 0.5) * row_h);
cJSON_AddNumberToObject(f, "direction", left_col ? -90 : 90);
}
char err[160];
cJSON *room = validate_room(raw, "default", err, sizeof(err));
cJSON_Delete(raw);
return room;
}
// Room names, sorted, as a new JSON array
static cJSON *room_names(void)
{
char dir[300];
snprintf(dir, sizeof(dir), "%s/sim/rooms", db_root());
char names[64][41];
int n = 0;
DIR *dp = opendir(dir);
struct dirent *e;
while (dp && (e = readdir(dp)) && n < 64) {
size_t len = strlen(e->d_name);
if (len > 5 && len - 5 <= 40 && !strcmp(e->d_name + len - 5, ".json")) {
memcpy(names[n], e->d_name, len - 5);
names[n][len - 5] = 0;
if (room_name_ok(names[n])) {
n++;
}
}
}
if (dp) {
closedir(dp);
}
qsort(names, (size_t)n, sizeof(names[0]), (int (*)(const void *, const void *))strcmp);
cJSON *a = cJSON_CreateArray();
for (int i = 0; i < n; i++) {
cJSON_AddItemToArray(a, cJSON_CreateString(names[i]));
}
return a;
}
static bool room_exists(const char *name)
{
char p[300];
sim_path(p, sizeof(p), "rooms", name, ".json");
struct stat st;
return stat(p, &st) == 0;
}
static cJSON *load_room(const char *name, char *err, size_t errn)
{
char p[300];
sim_path(p, sizeof(p), "rooms", name, ".json");
cJSON *raw = read_json(p);
if (!raw) {
snprintf(err, errn, "no room named %s", name);
return NULL;
}
cJSON *room = validate_room(raw, name, err, errn);
cJSON_Delete(raw);
return room;
}
static bool save_room(const char *name, const cJSON *room)
{
char p[300];
sim_path(p, sizeof(p), "rooms", name, ".json");
return write_json(p, room, true);
}
static char s_room[41] = "default"; // the active room
static void save_active(void)
{
char p[300];
sim_path(p, sizeof(p), "", "sim", ".json");
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "room", s_room);
write_json(p, o, true);
cJSON_Delete(o);
}
// First use: the default room; then the saved active room if it still exists, else the first one
static void load_active(void)
{
ensure_dirs();
cJSON *names = room_names();
if (!cJSON_GetArraySize(names)) {
cJSON *room = default_room();
if (room && save_room("default", room)) {
ESP_LOGI(TAG, "made the default room (16 bars)");
}
cJSON_Delete(room);
cJSON_Delete(names);
names = room_names();
}
char p[300];
sim_path(p, sizeof(p), "", "sim", ".json");
cJSON *st = read_json(p);
const cJSON *r = st ? cJSON_GetObjectItem(st, "room") : NULL;
if (cJSON_IsString(r) && room_name_ok(r->valuestring) && room_exists(r->valuestring)) {
snprintf(s_room, sizeof(s_room), "%s", r->valuestring);
} else if (cJSON_GetArraySize(names)) {
snprintf(s_room, sizeof(s_room), "%s", cJSON_GetArrayItem(names, 0)->valuestring);
}
cJSON_Delete(st);
cJSON_Delete(names);
}
static int fixture_leds(const cJSON *room, const cJSON *f)
{
const cJSON *l = cJSON_GetObjectItem(f, "leds");
if (cJSON_IsNumber(l)) {
return l->valueint;
}
const cJSON *def = cJSON_GetObjectItem(cJSON_GetObjectItem(room, "definitions"),
cJSON_GetObjectItem(f, "def")->valuestring);
return cJSON_GetObjectItem(def, "leds")->valueint;
}
// The strip with this MAC in the room, or NULL
static const cJSON *fixture_by_mac(const cJSON *room, const char *mac12)
{
const cJSON *f;
cJSON_ArrayForEach(f, cJSON_GetObjectItem(room, "fixtures"))
{
const char *m = cJSON_GetObjectItem(f, "mac")->valuestring;
char h[13];
int k = 0;
for (const char *c = m; *c && k < 12; c++) {
if (*c != ':') {
h[k++] = *c;
}
}
h[k] = 0;
if (!strcmp(h, mac12)) {
return f;
}
}
return NULL;
}
/* ------------------------------------------------------------------ the page's link */
static httpd_handle_t s_hd;
static int s_page_fd = -1;
static SemaphoreHandle_t s_tx_mu; // one frame at a time to the page
static bool page_open_locked(void)
{
if (s_page_fd >= 0 && httpd_ws_get_fd_info(s_hd, s_page_fd) != HTTPD_WS_CLIENT_WEBSOCKET) {
s_page_fd = -1;
}
return s_page_fd >= 0;
}
bool sim_rig_page_open(void)
{
if (!s_tx_mu) {
return false;
}
xSemaphoreTake(s_tx_mu, portMAX_DELAY);
bool open = page_open_locked();
xSemaphoreGive(s_tx_mu);
return open;
}
static bool send_frame(int fd, httpd_ws_type_t type, const uint8_t *data, size_t len)
{
httpd_ws_frame_t f = { .type = type, .payload = (uint8_t *)data, .len = len, .final = true };
return httpd_ws_send_frame_async(s_hd, fd, &f) == ESP_OK;
}
// Called by bridge.c for the "browser" bridge: dst_mac(6) + packet
bool sim_rig_tx(const uint8_t *frame, size_t len)
{
if (!s_tx_mu) {
return false;
}
xSemaphoreTake(s_tx_mu, portMAX_DELAY);
bool ok = page_open_locked() && send_frame(s_page_fd, HTTPD_WS_TYPE_BINARY, frame, len);
if (!ok) {
s_page_fd = page_open_locked() ? s_page_fd : -1;
}
xSemaphoreGive(s_tx_mu);
return ok;
}
static esp_err_t ws_open(httpd_req_t *req)
{
if (auth_ws_admit(req, "sim", AUTH_VIEW) != ESP_OK) {
return ESP_FAIL;
}
int fd = httpd_req_to_sockfd(req);
xSemaphoreTake(s_tx_mu, portMAX_DELAY);
int old = page_open_locked() ? s_page_fd : -1;
s_page_fd = fd;
if (old >= 0 && old != fd) {
static const char msg[] = "{\"t\":\"takeover\"}";
send_frame(old, HTTPD_WS_TYPE_TEXT, (const uint8_t *)msg, sizeof(msg) - 1);
httpd_sess_trigger_close(s_hd, old);
}
xSemaphoreGive(s_tx_mu);
ESP_LOGI(TAG, "rig page connected");
return ESP_OK;
}
static void save_flash(const char *text)
{
cJSON *m = cJSON_Parse(text);
const cJSON *t = cJSON_GetObjectItem(m, "t"), *mac = cJSON_GetObjectItem(m, "mac"), *d = cJSON_GetObjectItem(m, "data");
char h[13];
if (cJSON_IsString(t) && !strcmp(t->valuestring, "flash") && api_mac(mac, h) && cJSON_IsString(d)) {
cJSON *nvs = cJSON_Parse(d->valuestring);
if (cJSON_IsObject(nvs)) {
char p[300];
sim_path(p, sizeof(p), "flash", h, ".json");
xSemaphoreTake(s_mu, portMAX_DELAY);
write_text(p, d->valuestring);
xSemaphoreGive(s_mu);
}
cJSON_Delete(nvs);
}
cJSON_Delete(m);
}
static esp_err_t ws_handler(httpd_req_t *req)
{
if (req->method == HTTP_GET) { // only a plain GET gets here; the upgrade is answered by httpd
httpd_resp_set_status(req, "426 Upgrade Required");
return httpd_resp_sendstr(req, "websocket only");
}
httpd_ws_frame_t f = { 0 };
esp_err_t err = httpd_ws_recv_frame(req, &f, 0);
if (err != ESP_OK) {
return err;
}
if (f.len == 0 || (f.type != HTTPD_WS_TYPE_BINARY && f.type != HTTPD_WS_TYPE_TEXT)) {
return ESP_OK;
}
if (f.len > FRAME_MAX) {
return ESP_FAIL;
}
uint8_t *buf = malloc(f.len + 1);
if (!buf) {
return ESP_ERR_NO_MEM;
}
f.payload = buf;
err = httpd_ws_recv_frame(req, &f, f.len);
if (err == ESP_OK && !auth_ws_allowed(httpd_req_to_sockfd(req), "sim", AUTH_VIEW)) {
err = ESP_FAIL; // closes the socket: the socket was not admitted at its handshake
}
if (err == ESP_OK) {
buf[f.len] = 0;
if (f.type == HTTPD_WS_TYPE_BINARY) {
if (f.len > 6 && f.len <= 6 + 250) {
bridge_browser_rx(buf, (int)f.len);
}
} else {
save_flash((const char *)buf);
}
}
free(buf);
return err;
}
/* ------------------------------------------------------------------ the API */
static cJSON *config_json(void)
{
char err[160];
cJSON *o = cJSON_CreateObject();
cJSON *b = cJSON_AddObjectToObject(o, "bridge");
cJSON_AddStringToObject(b, "name", "rig");
cJSON_AddStringToObject(b, "mac", BRIDGE_SIM_MAC);
cJSON_AddBoolToObject(b, "running", bridge_has_browser());
cJSON *d = cJSON_AddObjectToObject(o, "drivers");
cJSON_AddStringToObject(d, "name", "sim-{n:02d}");
cJSON_AddNumberToObject(d, "fps", 30);
cJSON_AddNumberToObject(d, "boot_concurrency", 4);
cJSON_AddStringToObject(o, "room_name", s_room);
cJSON_AddItemToObject(o, "rooms", room_names());
cJSON *room = load_room(s_room, err, sizeof(err));
if (!room) {
room = default_room();
}
cJSON_AddItemToObject(o, "room", room);
return o;
}
// GET /sim/api/flash/<mac>: the bar's NVS store, created on first boot and kept in line with the room
static esp_err_t flash_get(httpd_req_t *req, const char *mac_in)
{
cJSON *k = cJSON_CreateString(mac_in);
char h[13];
bool ok = api_mac(k, h);
cJSON_Delete(k);
if (!ok) {
return api_error(req, "400 Bad Request", "not a MAC");
}
char err[160], p[300];
sim_path(p, sizeof(p), "flash", h, ".json");
cJSON *room = load_room(s_room, err, sizeof(err));
const cJSON *f = room ? fixture_by_mac(room, h) : NULL;
cJSON *nvs = read_json(p);
if (!nvs) {
nvs = cJSON_CreateObject();
}
cJSON *led = cJSON_GetObjectItem(nvs, "led");
if (!cJSON_IsObject(led)) {
cJSON_DeleteItemFromObject(nvs, "led");
led = cJSON_AddObjectToObject(nvs, "led");
}
// NVS keys and types as led-driver/main/settings.cpp writes them: [type, value]
#define NVS_SET(key, type, val) \
do { \
cJSON *pair = cJSON_CreateArray(); \
cJSON_AddItemToArray(pair, cJSON_CreateString(type)); \
cJSON_AddItemToArray(pair, val); \
cJSON_DeleteItemFromObject(led, key); \
cJSON_AddItemToObject(led, key, pair); \
} while (0)
const cJSON *host = cJSON_GetObjectItem(led, "hostname");
if (!(cJSON_IsArray(host) && cJSON_IsString(cJSON_GetArrayItem(host, 1)))) {
NVS_SET("hostname", "str", cJSON_CreateString(f ? cJSON_GetObjectItem(f, "label")->valuestring : "led"));
}
if (f) {
NVS_SET("num_leds", "i32", cJSON_CreateNumber(fixture_leds(room, f))); // physical: the room decides it
}
NVS_SET("espnow_ch", "i64", cJSON_CreateNumber(WIFI_CHANNEL));
NVS_SET("espnow", "str", cJSON_CreateString("on"));
#undef NVS_SET
xSemaphoreTake(s_mu, portMAX_DELAY);
write_json(p, nvs, false);
xSemaphoreGive(s_mu);
cJSON_Delete(room);
return api_json(req, "200 OK", nvs, true);
}
static void next_mac(const char *taken, char out[18])
{
cJSON *names = room_names(), *n;
char err[160];
// every MAC any room uses, plus the ones the page has not saved yet
size_t cap = 4096, len = 0;
char *all = calloc(1, cap);
cJSON_ArrayForEach(n, names)
{
cJSON *room = load_room(n->valuestring, err, sizeof(err));
const cJSON *f, *fixtures = room ? cJSON_GetObjectItem(room, "fixtures") : NULL;
cJSON_ArrayForEach(f, fixtures)
{
const char *m = cJSON_GetObjectItem(f, "mac")->valuestring;
if (all && len + 20 < cap) {
len += (size_t)snprintf(all + len, cap - len, "%s,", m);
}
}
cJSON_Delete(room);
}
cJSON_Delete(names);
for (int i = 1; i < 0xFFFF; i++) {
snprintf(out, 18, MAC_PREFIX ":00:%02x:%02x", i >> 8, i & 0xFF);
if ((!all || !strstr(all, out)) && (!taken || !strstr(taken, out))) {
break;
}
}
free(all);
}
static esp_err_t rooms_info(httpd_req_t *req)
{
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "current", s_room);
cJSON_AddItemToObject(o, "rooms", room_names());
return api_json(req, "200 OK", o, true);
}
static esp_err_t api_handler(httpd_req_t *req)
{
// /sim/api/<a>/<b>
char a[32] = "", b[64] = "";
const char *rest = req->uri + strlen("/sim/api/");
size_t na = strcspn(rest, "/?");
if (na >= sizeof(a)) {
return api_error(req, "404 Not Found", "no such endpoint");
}
memcpy(a, rest, na);
if (rest[na] == '/') {
size_t nb = strcspn(rest + na + 1, "/?");
if (nb >= sizeof(b) || rest[na + 1 + nb] == '/') {
return api_error(req, "404 Not Found", "no such endpoint");
}
memcpy(b, rest + na + 1, nb);
}
const int m = req->method;
char err[200];
esp_err_t ret;
xSemaphoreTake(s_mu, portMAX_DELAY);
if (!strcmp(a, "config") && !b[0] && m == HTTP_GET) {
ret = api_json(req, "200 OK", config_json(), true);
} else if (!strcmp(a, "flash") && b[0] && m == HTTP_GET) {
xSemaphoreGive(s_mu); // flash_get takes it for the write
return flash_get(req, b);
} else if (!strcmp(a, "next-mac") && m == HTTP_GET) {
char q[600] = "", taken[600] = "", mac[18];
if (httpd_req_get_url_query_str(req, q, sizeof(q)) == ESP_OK) {
httpd_query_key_value(q, "taken", taken, sizeof(taken));
}
for (char *c = taken; *c; c++) { // %3A and %2C from encodeURIComponent; MACs compare in lower case
*c = (char)tolower((unsigned char)*c);
if (c[0] == '%' && c[1] == '3' && (c[2] == 'A' || c[2] == 'a')) {
c[0] = ':';
memmove(c + 1, c + 3, strlen(c + 3) + 1);
} else if (c[0] == '%' && c[1] == '2' && (c[2] == 'C' || c[2] == 'c')) {
c[0] = ',';
memmove(c + 1, c + 3, strlen(c + 3) + 1);
}
}
next_mac(taken, mac);
cJSON *o = cJSON_CreateObject();
cJSON_AddStringToObject(o, "mac", mac);
ret = api_json(req, "200 OK", o, true);
} else if (!strcmp(a, "rooms") && !b[0] && m == HTTP_GET) {
ret = rooms_info(req);
} else if (!strcmp(a, "rooms") && !b[0] && m == HTTP_POST) {
cJSON *body = api_body(req);
if (!body) {
ret = ESP_OK;
} else {
const cJSON *nm = cJSON_GetObjectItem(body, "name"), *src = cJSON_GetObjectItem(body, "copy_from");
cJSON *room = NULL;
if (!cJSON_IsString(nm) || !room_name_ok(nm->valuestring)) {
ret = api_error(req, "400 Bad Request", "room names are 1-40 letters, digits, - or _");
} else if (room_exists(nm->valuestring)) {
ret = api_error(req, "409 Conflict", "a room with that name already exists");
} else if (cJSON_IsString(src) && !(room_name_ok(src->valuestring) &&
(room = load_room(src->valuestring, err, sizeof(err))))) {
ret = api_error(req, "400 Bad Request", "no room to copy with that name");
} else {
if (!room) {
room = cJSON_CreateObject();
cJSON *defs = cJSON_AddObjectToObject(room, "definitions");
cJSON *d = cJSON_AddObjectToObject(defs, "bar-119");
cJSON_AddNumberToObject(d, "leds", 119);
cJSON_AddNumberToObject(d, "pitch_m", DEFAULT_PITCH_M);
cJSON_AddObjectToObject(room, "fixtures");
}
api_set(room, "name", cJSON_CreateString(nm->valuestring));
const cJSON *w = cJSON_GetObjectItem(body, "width"), *dp = cJSON_GetObjectItem(body, "depth");
if (cJSON_IsNumber(w)) {
api_set(room, "width", cJSON_CreateNumber(w->valuedouble));
}
if (cJSON_IsNumber(dp)) {
api_set(room, "depth", cJSON_CreateNumber(dp->valuedouble));
}
cJSON *ok = validate_room(room, nm->valuestring, err, sizeof(err));
if (!ok) {
ret = api_error(req, "400 Bad Request", err);
} else if (!save_room(nm->valuestring, ok)) {
ret = api_error(req, "500 Internal Server Error", "could not write the room");
cJSON_Delete(ok);
} else {
cJSON *o = cJSON_CreateObject();
cJSON_AddItemToObject(o, "room", ok);
cJSON_AddStringToObject(o, "current", s_room);
cJSON_AddItemToObject(o, "rooms", room_names());
ret = api_json(req, "200 OK", o, true);
}
}
cJSON_Delete(room);
cJSON_Delete(body);
}
} else if (!strcmp(a, "rooms") && b[0]) {
if (!room_name_ok(b)) {
ret = api_error(req, "400 Bad Request", "room names are 1-40 letters, digits, - or _");
} else if (!room_exists(b)) {
ret = api_error(req, "404 Not Found", "no room with that name");
} else if (m == HTTP_GET) {
cJSON *room = load_room(b, err, sizeof(err));
ret = room ? api_json(req, "200 OK", room, true) : api_error(req, "500 Internal Server Error", err);
} else if (m == HTTP_PUT) {
cJSON *body = api_body(req);
cJSON *room = body ? validate_room(body, b, err, sizeof(err)) : NULL;
if (!body) {
ret = ESP_OK;
} else if (!room) {
ret = api_error(req, "400 Bad Request", err);
} else if (!save_room(b, room)) {
ret = api_error(req, "500 Internal Server Error", "could not write the room");
cJSON_Delete(room);
} else {
cJSON *o = cJSON_CreateObject();
cJSON_AddItemToObject(o, "room", room);
ret = api_json(req, "200 OK", o, true);
}
cJSON_Delete(body);
} else if (m == HTTP_DELETE) {
char p[300];
sim_path(p, sizeof(p), "rooms", b, ".json");
if (!strcmp(b, s_room)) {
ret = api_error(req, "409 Conflict", "switch to another room before deleting this one");
} else if (remove(p) != 0) {
ret = api_error(req, "500 Internal Server Error", "could not delete the room");
} else {
ret = rooms_info(req);
}
} else {
ret = api_error(req, "405 Method Not Allowed", "GET, PUT or DELETE");
}
} else if (!strcmp(a, "room") && !b[0] && m == HTTP_POST) {
cJSON *body = api_body(req);
const cJSON *nm = body ? cJSON_GetObjectItem(body, "name") : NULL;
if (!body) {
ret = ESP_OK;
} else if (!cJSON_IsString(nm) || !room_name_ok(nm->valuestring) || !room_exists(nm->valuestring)) {
ret = api_error(req, "400 Bad Request", "no room with that name");
} else {
snprintf(s_room, sizeof(s_room), "%s", nm->valuestring);
save_active();
ESP_LOGI(TAG, "room: %s", s_room);
ret = api_json(req, "200 OK", config_json(), true);
}
cJSON_Delete(body);
} else {
ret = api_error(req, "404 Not Found", "no such endpoint");
}
xSemaphoreGive(s_mu);
return ret;
}
/* ------------------------------------------------------------------ registration */
esp_err_t sim_rig_register(httpd_handle_t server)
{
s_hd = server;
s_mu = xSemaphoreCreateMutex();
s_tx_mu = xSemaphoreCreateMutex();
if (!s_mu || !s_tx_mu) {
return ESP_ERR_NO_MEM;
}
load_active();
const httpd_uri_t ws = { .uri = "/sim/ws", .method = HTTP_GET, .handler = ws_handler, .is_websocket = true,
.handle_ws_control_frames = false, .ws_post_handshake_cb = ws_open };
esp_err_t err = httpd_register_uri_handler(server, &ws);
static const httpd_method_t METHODS[] = { HTTP_GET, HTTP_POST, HTTP_PUT, HTTP_DELETE };
for (size_t i = 0; i < 4 && err == ESP_OK; i++) {
const httpd_uri_t u = { .uri = "/sim/api/*", .method = METHODS[i], .handler = api_handler };
err = auth_register_uri(server, &u);
}
const httpd_uri_t root = { .uri = "/sim", .method = HTTP_GET, .handler = page_handler };
const httpd_uri_t files = { .uri = "/sim/*", .method = HTTP_GET, .handler = page_handler };
if (err == ESP_OK) {
err = auth_register_uri(server, &root);
}
if (err == ESP_OK) {
err = auth_register_uri(server, &files);
}
if (err != ESP_OK) {
ESP_LOGE(TAG, "register: %s", esp_err_to_name(err));
} else {
ESP_LOGI(TAG, "simulated rig on /sim/ (room %s)", s_room);
}
return err;
}