feat: browser simulator served by the controller, desktop build, browser bridge

- led-simulator: the rig runs the C++ led-driver as WebAssembly (sim-driver/),
  one single-threaded worker per bar, no cross-origin isolation needed. Rooms
  (one JSON per room) with an on-page editor, and a pattern gallery. The
  Python server, Pyodide boot and ring buffer are removed.
- sim-controller sim_rig.c: serves /sim/ from an embedded pack, the page's
  WebSocket and the rooms/flash API. The desktop build embeds it too.
- bridge.c: a "browser" bridge kind that carries ESP-NOW frames to the page;
  devices announced through it are marked sim.
- UI: Simulator in the Menu, split view with resize and pop-out, swipe
  between controller and rig on phones; SIM/REAL badges in Devices.
- Fades: preset pushes and Wi-Fi driver bodies always carry fade and
  beat_time, so "off" no longer inherits an earlier fade.
- Also the sequences-v2 work in progress: desktop port, bridge firmware,
  serial bridge, Wi-Fi drivers, sequence timeline, audio and API changes.
- led-driver: ESP-NOW link, beat sync, control messages, sim hooks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jimmyandClaude Opus 5.5 committed 2026-11-16 19:32:46 +13:00
1 parent 698c1463c0
commit 581b751904
506 files changed
+42336 -3599

No files matched your search

+86
View File
@@ -0,0 +1,86 @@
# sim-driver: the C++ led-driver built for the browser (led-simulator's strips and pattern gallery) with Emscripten (build.sh runs this in Docker).
# led_driver one whole driver per strip, for web/driver-worker.js. No threads: the worker runs the pattern frame
# and the ESP-NOW link pass from a timer (sim_tick), so the page needs no SharedArrayBuffer and
# works on any address (a phone on the LAN), not only on a cross-origin isolated one
# led_fx the pattern engine alone, no threads, stepped by the page, for web/gallery.js
# The driver sources are led-driver/main's, unchanged; the platform comes from desktop/port and src/.
cmake_minimum_required(VERSION 3.16)
project(led_simulator_wasm C CXX)
set(ROOT ${CMAKE_CURRENT_SOURCE_DIR}/..)
set(DRIVER ${ROOT}/led-driver/main)
set(DESK ${ROOT}/desktop)
set(OUT ${ROOT}/led-simulator/web/wasm)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_C_STANDARD 11)
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE Release)
endif()
set(ENGINE_SRC
${DRIVER}/patterns.cpp
${DRIVER}/effects_a.cpp
${DRIVER}/effects_b.cpp
${DRIVER}/effects_rig.cpp
${DRIVER}/effects_util.cpp
${DRIVER}/beat_sync.cpp
${DRIVER}/presets.cpp
${DRIVER}/settings.cpp
${DESK}/port/src/freertos.c
${DESK}/third_party/cjson/cJSON.c
src/sim_glue.c
src/nvs_sim.cpp
src/ws2812_sim.cpp)
# musl (Emscripten's libc) has no static initializer for a recursive mutex; its type word is the first int
set_source_files_properties(${DESK}/port/src/freertos.c PROPERTIES
COMPILE_DEFINITIONS "PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP={{{PTHREAD_MUTEX_RECURSIVE}}}")
set(INCLUDES
${CMAKE_CURRENT_SOURCE_DIR}/src
${CMAKE_CURRENT_SOURCE_DIR}/include
${DESK}/port/include
${DESK}/third_party/cjson
${DRIVER})
set(COMMON_LINK
-sMODULARIZE=1
-sEXPORT_ES6=1
-sALLOW_MEMORY_GROWTH=1
-sEXPORTED_RUNTIME_METHODS=HEAPU8,UTF8ToString,stringToNewUTF8)
function(sim_target name)
target_include_directories(${name} PRIVATE ${INCLUDES})
# ESP-IDF force-includes sdkconfig.h into every source; so does the desktop port
# (SHELL: keeps each -include with its file: CMake would merge the repeated flag)
target_compile_options(${name} PRIVATE "SHELL:-include ${DESK}/port/include/sdkconfig.h"
-Wall -Wno-unused-function -Wno-missing-field-initializers
"$<$<COMPILE_LANGUAGE:CXX>:SHELL:-include ${CMAKE_CURRENT_SOURCE_DIR}/include/sim_prelude.h>")
set_target_properties(${name} PROPERTIES SUFFIX ".mjs" RUNTIME_OUTPUT_DIRECTORY ${OUT})
endfunction()
# ---- one driver ----------------------------------------------------------------------------------
add_executable(led_driver ${ENGINE_SRC}
${DRIVER}/ctrl_msg.cpp
${DRIVER}/espnow_link.cpp
src/espnow_sim.cpp
src/sim_main.cpp)
sim_target(led_driver)
target_link_options(led_driver PRIVATE ${COMMON_LINK}
-sENVIRONMENT=worker
-sEXPORT_NAME=LedDriver
-sINITIAL_MEMORY=4MB
-sSTACK_SIZE=256KB
-sEXPORTED_FUNCTIONS=_sim_boot,_sim_tick,_sim_rx,_sim_frame,_malloc,_free)
# ---- pattern gallery -----------------------------------------------------------------------------
add_executable(led_fx ${ENGINE_SRC} src/gallery_main.cpp)
sim_target(led_fx)
target_compile_definitions(led_fx PRIVATE SIM_MANUAL_CLOCK=1)
target_link_options(led_fx PRIVATE ${COMMON_LINK}
-sENVIRONMENT=web
-sEXPORT_NAME=LedFx
-sINITIAL_MEMORY=2MB
-sSTACK_SIZE=256KB
-sEXPORTED_FUNCTIONS=_fx_count,_fx_name,_fx_init,_fx_defaults_json,_fx_select_json,_fx_step,_sim_frame,_malloc,_free)
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
# Build the browser driver (led-simulator/web/wasm/led_driver.*) and the pattern gallery engine (led_fx.*)
# with Emscripten in Docker: nothing to install on the host. Runs as the container's root, like the Makefile's
# DOCKER_RUN (on rootless Docker that is you on the host).
set -euo pipefail
IMAGE="${EMSDK_IMAGE:-emscripten/emsdk:4.0.12}"
here="$(cd "$(dirname "$0")" && pwd)"
root="$(cd "$here/.." && pwd)" # led-controller: the build reads led-driver/ and desktop/
rel="${here#"$root"/}"
docker run --rm -v "$root:/src" -w "/src/$rel" "$IMAGE" \
bash -c 'emcmake cmake -S . -B build -DCMAKE_BUILD_TYPE=Release >/dev/null && cmake --build build -j"$(nproc)"'
ls -l "$root/led-simulator/web/wasm"
+3
View File
@@ -0,0 +1,3 @@
/* sim-driver: GPIO numbers only (the strip's data pin is a setting with no effect here). */
#pragma once
typedef int gpio_num_t;
+3
View File
@@ -0,0 +1,3 @@
/* sim-driver: see driver/rmt_tx.h */
#pragma once
typedef struct rmt_encoder_t *rmt_encoder_handle_t;
+6
View File
@@ -0,0 +1,6 @@
/* sim-driver: the RMT types ws2812.h names; src/ws2812_sim.cpp never uses them. */
#pragma once
typedef struct rmt_channel_t *rmt_channel_handle_t;
typedef struct {
int loop_count;
} rmt_transmit_config_t;
+50
View File
@@ -0,0 +1,50 @@
/* sim-driver: ESP-NOW goes to the page (src/espnow_sim.cpp), which is the radio between strips and the bridge. */
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include "esp_err.h"
#include "esp_wifi.h"
#ifdef __cplusplus
extern "C" {
#endif
#define ESP_NOW_ETH_ALEN 6
#define ESP_NOW_MAX_DATA_LEN 250
#define ESP_ERR_ESPNOW_BASE 0x3066
#define ESP_ERR_ESPNOW_NOT_INIT (ESP_ERR_ESPNOW_BASE + 1)
#define ESP_ERR_ESPNOW_ARG (ESP_ERR_ESPNOW_BASE + 2)
#define ESP_ERR_ESPNOW_NO_MEM (ESP_ERR_ESPNOW_BASE + 3)
#define ESP_ERR_ESPNOW_FULL (ESP_ERR_ESPNOW_BASE + 4)
#define ESP_ERR_ESPNOW_NOT_FOUND (ESP_ERR_ESPNOW_BASE + 5)
#define ESP_ERR_ESPNOW_INTERNAL (ESP_ERR_ESPNOW_BASE + 6)
#define ESP_ERR_ESPNOW_EXIST (ESP_ERR_ESPNOW_BASE + 7)
typedef struct {
uint8_t peer_addr[ESP_NOW_ETH_ALEN];
uint8_t lmk[16];
uint8_t channel;
wifi_interface_t ifidx;
bool encrypt;
void *priv;
} esp_now_peer_info_t;
typedef struct {
uint8_t *src_addr;
uint8_t *des_addr;
void *rx_ctrl;
} esp_now_recv_info_t;
typedef void (*esp_now_recv_cb_t)(const esp_now_recv_info_t *info, const uint8_t *data, int len);
esp_err_t esp_now_init(void);
esp_err_t esp_now_deinit(void);
esp_err_t esp_now_register_recv_cb(esp_now_recv_cb_t cb);
esp_err_t esp_now_add_peer(const esp_now_peer_info_t *peer);
bool esp_now_is_peer_exist(const uint8_t *mac);
esp_err_t esp_now_send(const uint8_t *mac, const uint8_t *data, size_t len);
#ifdef __cplusplus
}
#endif
+19
View File
@@ -0,0 +1,19 @@
/* sim-driver: the radio is always up, on the channel from the strip's settings. */
#pragma once
#include <stdint.h>
#include "esp_err.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum { WIFI_IF_STA = 0, WIFI_IF_AP = 1 } wifi_interface_t;
typedef enum { WIFI_SECOND_CHAN_NONE = 0, WIFI_SECOND_CHAN_ABOVE, WIFI_SECOND_CHAN_BELOW } wifi_second_chan_t;
typedef enum { WIFI_MODE_NULL = 0, WIFI_MODE_STA, WIFI_MODE_AP, WIFI_MODE_APSTA } wifi_mode_t;
esp_err_t esp_wifi_get_channel(uint8_t *primary, wifi_second_chan_t *second);
#ifdef __cplusplus
}
#endif
+10
View File
@@ -0,0 +1,10 @@
/* sim-driver: the Wi-Fi types net.h names (net.cpp itself is not built: the rig has no Wi-Fi). */
#pragma once
#include <stdint.h>
typedef struct {
uint8_t bssid[6];
uint8_t ssid[33];
uint8_t primary;
int8_t rssi;
int authmode;
} wifi_ap_record_t;
+47
View File
@@ -0,0 +1,47 @@
/* sim-driver: NVS in memory (src/nvs_sim.cpp). The store is loaded from JSON at boot and handed back
* to the page on every commit, which keeps it as the strip's flash. */
#pragma once
#include <stddef.h>
#include <stdint.h>
#include "esp_err.h"
#ifdef __cplusplus
extern "C" {
#endif
#define ESP_ERR_NVS_BASE 0x1100
#define ESP_ERR_NVS_NOT_INITIALIZED (ESP_ERR_NVS_BASE + 0x01)
#define ESP_ERR_NVS_NOT_FOUND (ESP_ERR_NVS_BASE + 0x02)
#define ESP_ERR_NVS_TYPE_MISMATCH (ESP_ERR_NVS_BASE + 0x03)
#define ESP_ERR_NVS_READ_ONLY (ESP_ERR_NVS_BASE + 0x04)
#define ESP_ERR_NVS_INVALID_HANDLE (ESP_ERR_NVS_BASE + 0x07)
#define ESP_ERR_NVS_INVALID_LENGTH (ESP_ERR_NVS_BASE + 0x0c)
#define ESP_ERR_NVS_NO_FREE_PAGES (ESP_ERR_NVS_BASE + 0x0d)
#define ESP_ERR_NVS_NEW_VERSION_FOUND (ESP_ERR_NVS_BASE + 0x10)
typedef uint32_t nvs_handle_t;
typedef enum { NVS_READONLY, NVS_READWRITE } nvs_open_mode_t;
esp_err_t nvs_open(const char *ns, nvs_open_mode_t mode, nvs_handle_t *out);
void nvs_close(nvs_handle_t h);
esp_err_t nvs_commit(nvs_handle_t h);
esp_err_t nvs_erase_key(nvs_handle_t h, const char *key);
esp_err_t nvs_erase_all(nvs_handle_t h);
esp_err_t nvs_set_str(nvs_handle_t h, const char *key, const char *value);
esp_err_t nvs_get_str(nvs_handle_t h, const char *key, char *out, size_t *len);
esp_err_t nvs_set_blob(nvs_handle_t h, const char *key, const void *value, size_t len);
esp_err_t nvs_get_blob(nvs_handle_t h, const char *key, void *out, size_t *len);
esp_err_t nvs_set_u8(nvs_handle_t h, const char *key, uint8_t v);
esp_err_t nvs_get_u8(nvs_handle_t h, const char *key, uint8_t *v);
esp_err_t nvs_set_i32(nvs_handle_t h, const char *key, int32_t v);
esp_err_t nvs_get_i32(nvs_handle_t h, const char *key, int32_t *v);
esp_err_t nvs_set_u32(nvs_handle_t h, const char *key, uint32_t v);
esp_err_t nvs_get_u32(nvs_handle_t h, const char *key, uint32_t *v);
esp_err_t nvs_set_i64(nvs_handle_t h, const char *key, int64_t v);
esp_err_t nvs_get_i64(nvs_handle_t h, const char *key, int64_t *v);
#ifdef __cplusplus
}
#endif
+14
View File
@@ -0,0 +1,14 @@
/* sim-driver: flash init is a no-op; the NVS store is loaded by sim_boot(). */
#pragma once
#include "esp_err.h"
#include "nvs.h"
#ifdef __cplusplus
extern "C" {
#endif
esp_err_t nvs_flash_init(void);
esp_err_t nvs_flash_erase(void);
#ifdef __cplusplus
}
#endif
+35
View File
@@ -0,0 +1,35 @@
/* sim-driver: force-included into every C++ source (the driver's and src/'s).
*
* - The desktop port's headers (desktop/port/include) were written for C and have no extern "C" guards, so they
* are included here once inside extern "C"; their #pragma once makes the sources' own includes no-ops.
* The C library headers they use come first, outside the block, so the C++ library's versions stay intact.
* - On the board ESP-IDF's headers also bring in stdio and esp_system, which the driver relies on.
*/
#pragma once
#include <errno.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
extern "C" {
#include "esp_err.h"
#include "esp_log.h"
#include "esp_check.h"
#include "esp_heap_caps.h"
#include "esp_mac.h"
#include "esp_random.h"
#include "esp_rom_sys.h"
#include "esp_system.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/semphr.h"
#include "freertos/task.h"
}
+84
View File
@@ -0,0 +1,84 @@
/* sim-driver: ESP-NOW through the page. Sends go to Module.simTx (dest MAC + packet); the page delivers
* received frames with sim_rx (src MAC + packet), which runs the driver's receive callback as the radio would. */
#include <cstdlib>
#include <cstring>
#include <emscripten.h>
#include "esp_mac.h"
#include "esp_now.h"
#include "esp_wifi.h"
#include "settings.h"
static esp_now_recv_cb_t s_cb;
static bool s_init;
extern "C" {
esp_err_t esp_now_init(void)
{
s_init = true;
return ESP_OK;
}
esp_err_t esp_now_deinit(void)
{
s_init = false;
s_cb = nullptr;
return ESP_OK;
}
esp_err_t esp_now_register_recv_cb(esp_now_recv_cb_t cb)
{
s_cb = cb;
return ESP_OK;
}
esp_err_t esp_now_add_peer(const esp_now_peer_info_t *peer)
{
(void)peer;
return ESP_OK;
}
bool esp_now_is_peer_exist(const uint8_t *mac)
{
(void)mac;
return true; // every peer is reachable through the page
}
esp_err_t esp_now_send(const uint8_t *mac, const uint8_t *data, size_t len)
{
if (!s_init) return ESP_ERR_ESPNOW_NOT_INIT;
if (len == 0 || len > ESP_NOW_MAX_DATA_LEN) return ESP_ERR_ESPNOW_ARG;
uint8_t *buf = (uint8_t *)malloc(6 + len);
if (!buf) return ESP_ERR_ESPNOW_NO_MEM;
memcpy(buf, mac, 6);
memcpy(buf + 6, data, len);
MAIN_THREAD_ASYNC_EM_ASM({
if (Module.simTx) Module.simTx(HEAPU8.slice($0, $0 + $1));
_free($0);
}, buf, (int)(6 + len));
return ESP_OK;
}
esp_err_t esp_wifi_get_channel(uint8_t *primary, wifi_second_chan_t *second)
{
net_cfg_t n;
settings_load_net(&n);
*primary = n.espnow_channel;
if (second) *second = WIFI_SECOND_CHAN_NONE;
return ESP_OK;
}
/** A frame the radio received: src MAC (6) + packet. */
EMSCRIPTEN_KEEPALIVE void sim_rx(const uint8_t *frame, int len)
{
if (!s_cb || len < 7) return;
uint8_t src[6], dst[6];
memcpy(src, frame, 6);
esp_read_mac(dst, ESP_MAC_WIFI_STA);
esp_now_recv_info_t info = { src, dst, nullptr };
s_cb(&info, frame + 6, len - 6);
}
} // extern "C"
+96
View File
@@ -0,0 +1,96 @@
/* led-simulator pattern gallery: the pattern engine alone, with no task. The page instantiates one module per
* pattern and steps each with its own clock (fx_step), so every pattern runs exactly as on the strip. */
#include <cstdlib>
#include <cstring>
#include <emscripten.h>
#include "cJSON.h"
#include "patterns.h"
#include "presets.h"
#include "settings.h"
#include "sim.h"
static hw_cfg_t s_hw;
static bool s_started;
extern "C" {
EMSCRIPTEN_KEEPALIVE int fx_count(void)
{
return patterns_count();
}
EMSCRIPTEN_KEEPALIVE const char *fx_name(int i)
{
return patterns_name(i);
}
/** Start (or resize) the strip with n LEDs at full brightness. */
EMSCRIPTEN_KEEPALIVE void fx_init(int n)
{
strncpy(s_hw.order, "rgb", sizeof(s_hw.order));
s_hw.max_brightness = 255;
s_hw.num_leds = n;
s_hw.pin = 10;
s_hw.global_brightness = 255;
s_hw.master_brightness = 255;
if (!s_started) {
sim_nvs_load("{}");
patterns_start(s_hw); // the pattern task cannot start without threads: fx_step runs the frames
presets_init(); // empty flash: the driver's default presets, the starting point for their patterns
s_started = true;
} else {
patterns_set_hardware(s_hw);
}
}
/** A starting preset for pattern i as JSON: the driver's default preset for it if it has one, else the
* pattern's bare defaults. The caller frees it. */
EMSCRIPTEN_KEEPALIVE char *fx_defaults_json(int i)
{
preset_t p;
preset_defaults(&p, i);
for (size_t k = 0; k < presets_count(); k++) {
if (presets_at(k)->pattern == i) {
p = *presets_at(k);
break;
}
}
cJSON *o = preset_to_json(&p);
char *s = cJSON_PrintUnformatted(o);
cJSON_Delete(o);
return s;
}
/** Select a preset given as JSON (the driver's field names), restarting its pattern. 1 if it applied. */
EMSCRIPTEN_KEEPALIVE int fx_select_json(const char *json, int restart)
{
cJSON *o = cJSON_Parse(json);
if (!cJSON_IsObject(o)) {
cJSON_Delete(o);
return 0;
}
preset_t p;
patterns_get(&p);
const cJSON *pat = cJSON_GetObjectItem(o, "pattern");
if (cJSON_IsString(pat)) { // a new pattern starts from its defaults
int idx = patterns_index(pat->valuestring);
if (idx >= 0) preset_defaults(&p, idx);
}
bool ok = preset_from_json(o, &p);
cJSON_Delete(o);
if (!ok) return 0;
if (restart) patterns_select(p);
else patterns_set(p);
return 1;
}
/** Run one frame at now_ms (the page's clock for this pattern). */
EMSCRIPTEN_KEEPALIVE void fx_step(double now_ms)
{
sim_clock_set_us((int64_t)(now_ms * 1000.0));
patterns_frame();
}
} // extern "C"
+272
View File
@@ -0,0 +1,272 @@
/* sim-driver: NVS in memory. Keys are typed as on the board: a get with another type is not found.
* Each commit hands the whole store to the page (Module.simFlash), which saves it as the strip's flash. */
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <mutex>
#include <string>
#include <emscripten.h>
#include "cJSON.h"
#include "nvs.h"
#include "nvs_flash.h"
#include "sim.h"
namespace {
enum Type { T_STR, T_BLOB, T_U8, T_I32, T_U32, T_I64 };
const char *kTypeNames[] = { "str", "blob", "u8", "i32", "u32", "i64" };
struct Value {
Type type;
std::string bytes; // str (without the NUL) or blob
int64_t num = 0;
};
using Space = std::map<std::string, Value>;
std::recursive_mutex s_mu;
std::map<std::string, Space> s_store;
std::map<nvs_handle_t, std::pair<std::string, bool>> s_handles; // handle -> namespace, writable
nvs_handle_t s_next = 1;
Space *space_of(nvs_handle_t h, bool write)
{
auto it = s_handles.find(h);
if (it == s_handles.end()) return nullptr;
if (write && !it->second.second) return nullptr;
return &s_store[it->second.first];
}
esp_err_t set_value(nvs_handle_t h, const char *key, Value v)
{
std::lock_guard<std::recursive_mutex> g(s_mu);
auto it = s_handles.find(h);
if (it == s_handles.end()) return ESP_ERR_NVS_INVALID_HANDLE;
if (!it->second.second) return ESP_ERR_NVS_READ_ONLY;
s_store[it->second.first][key] = std::move(v);
return ESP_OK;
}
esp_err_t get_num(nvs_handle_t h, const char *key, Type t, int64_t *out)
{
std::lock_guard<std::recursive_mutex> g(s_mu);
Space *s = space_of(h, false);
if (!s) return ESP_ERR_NVS_INVALID_HANDLE;
auto it = s->find(key);
if (it == s->end() || it->second.type != t) return ESP_ERR_NVS_NOT_FOUND;
*out = it->second.num;
return ESP_OK;
}
esp_err_t get_bytes(nvs_handle_t h, const char *key, Type t, void *out, size_t *len)
{
std::lock_guard<std::recursive_mutex> g(s_mu);
Space *s = space_of(h, false);
if (!s) return ESP_ERR_NVS_INVALID_HANDLE;
auto it = s->find(key);
if (it == s->end() || it->second.type != t) return ESP_ERR_NVS_NOT_FOUND;
size_t need = it->second.bytes.size() + (t == T_STR ? 1 : 0);
if (!out) {
*len = need;
return ESP_OK;
}
if (*len < need) return ESP_ERR_NVS_INVALID_LENGTH;
memcpy(out, it->second.bytes.data(), it->second.bytes.size());
if (t == T_STR) ((char *)out)[need - 1] = '\0';
*len = need;
return ESP_OK;
}
std::string to_hex(const std::string &b)
{
static const char d[] = "0123456789abcdef";
std::string o;
for (unsigned char c : b) {
o += d[c >> 4];
o += d[c & 15];
}
return o;
}
std::string from_hex(const char *s)
{
std::string o;
for (size_t i = 0; s[i] && s[i + 1]; i += 2) {
char pair[3] = { s[i], s[i + 1], 0 };
o += (char)strtol(pair, nullptr, 16);
}
return o;
}
} // namespace
extern "C" {
esp_err_t nvs_flash_init(void)
{
return ESP_OK;
}
esp_err_t nvs_flash_erase(void)
{
std::lock_guard<std::recursive_mutex> g(s_mu);
s_store.clear();
return ESP_OK;
}
esp_err_t nvs_open(const char *ns, nvs_open_mode_t mode, nvs_handle_t *out)
{
std::lock_guard<std::recursive_mutex> g(s_mu);
if (mode == NVS_READONLY && s_store.find(ns) == s_store.end()) {
return ESP_ERR_NVS_NOT_FOUND; // as the board: a namespace nothing was written to does not exist
}
if (mode == NVS_READWRITE) s_store[ns];
nvs_handle_t h = s_next++;
s_handles[h] = { ns, mode == NVS_READWRITE };
*out = h;
return ESP_OK;
}
void nvs_close(nvs_handle_t h)
{
std::lock_guard<std::recursive_mutex> g(s_mu);
s_handles.erase(h);
}
esp_err_t nvs_commit(nvs_handle_t h)
{
char *json;
{
std::lock_guard<std::recursive_mutex> g(s_mu);
if (s_handles.find(h) == s_handles.end()) return ESP_ERR_NVS_INVALID_HANDLE;
json = sim_nvs_dump();
}
if (json) {
// The page saves it; the main runtime thread frees the copy once the hook has run
MAIN_THREAD_ASYNC_EM_ASM({
if (Module.simFlash) Module.simFlash(UTF8ToString($0));
_free($0);
}, json);
}
return ESP_OK;
}
esp_err_t nvs_erase_key(nvs_handle_t h, const char *key)
{
std::lock_guard<std::recursive_mutex> g(s_mu);
Space *s = space_of(h, true);
if (!s) return ESP_ERR_NVS_INVALID_HANDLE;
return s->erase(key) ? ESP_OK : ESP_ERR_NVS_NOT_FOUND;
}
esp_err_t nvs_erase_all(nvs_handle_t h)
{
std::lock_guard<std::recursive_mutex> g(s_mu);
Space *s = space_of(h, true);
if (!s) return ESP_ERR_NVS_INVALID_HANDLE;
s->clear();
return ESP_OK;
}
esp_err_t nvs_set_str(nvs_handle_t h, const char *key, const char *value)
{
Value v{ T_STR, value, 0 };
return set_value(h, key, v);
}
esp_err_t nvs_get_str(nvs_handle_t h, const char *key, char *out, size_t *len)
{
return get_bytes(h, key, T_STR, out, len);
}
esp_err_t nvs_set_blob(nvs_handle_t h, const char *key, const void *value, size_t len)
{
Value v{ T_BLOB, std::string((const char *)value, len), 0 };
return set_value(h, key, v);
}
esp_err_t nvs_get_blob(nvs_handle_t h, const char *key, void *out, size_t *len)
{
return get_bytes(h, key, T_BLOB, out, len);
}
#define NUM_ACCESSORS(suffix, ctype, tag) \
esp_err_t nvs_set_##suffix(nvs_handle_t h, const char *key, ctype value) \
{ \
Value v{ tag, "", (int64_t)value }; \
return set_value(h, key, v); \
} \
esp_err_t nvs_get_##suffix(nvs_handle_t h, const char *key, ctype *out) \
{ \
int64_t n; \
esp_err_t e = get_num(h, key, tag, &n); \
if (e == ESP_OK) *out = (ctype)n; \
return e; \
}
NUM_ACCESSORS(u8, uint8_t, T_U8)
NUM_ACCESSORS(i32, int32_t, T_I32)
NUM_ACCESSORS(u32, uint32_t, T_U32)
NUM_ACCESSORS(i64, int64_t, T_I64)
int sim_nvs_load(const char *json)
{
cJSON *root = cJSON_Parse(json ? json : "{}");
if (!cJSON_IsObject(root)) {
cJSON_Delete(root);
return 0;
}
std::lock_guard<std::recursive_mutex> g(s_mu);
s_store.clear();
const cJSON *ns;
cJSON_ArrayForEach(ns, root)
{
if (!cJSON_IsObject(ns)) continue;
Space &space = s_store[ns->string];
const cJSON *kv;
cJSON_ArrayForEach(kv, ns)
{
const cJSON *t = cJSON_GetArrayItem(kv, 0), *val = cJSON_GetArrayItem(kv, 1);
if (!cJSON_IsString(t) || !val) continue;
for (int i = 0; i < 6; i++) {
if (strcmp(t->valuestring, kTypeNames[i]) != 0) continue;
Value v{ (Type)i, "", 0 };
if (i == T_STR && cJSON_IsString(val)) v.bytes = val->valuestring;
else if (i == T_BLOB && cJSON_IsString(val)) v.bytes = from_hex(val->valuestring);
else if (cJSON_IsNumber(val)) v.num = (int64_t)val->valuedouble;
else if (cJSON_IsString(val)) v.num = strtoll(val->valuestring, nullptr, 10);
else break;
space[kv->string] = v;
break;
}
}
}
cJSON_Delete(root);
return 1;
}
char *sim_nvs_dump(void)
{
std::lock_guard<std::recursive_mutex> g(s_mu);
cJSON *root = cJSON_CreateObject();
for (auto &ns : s_store) {
cJSON *o = cJSON_AddObjectToObject(root, ns.first.c_str());
for (auto &kv : ns.second) {
cJSON *pair = cJSON_CreateArray();
const Value &v = kv.second;
cJSON_AddItemToArray(pair, cJSON_CreateString(kTypeNames[v.type]));
if (v.type == T_STR) cJSON_AddItemToArray(pair, cJSON_CreateString(v.bytes.c_str()));
else if (v.type == T_BLOB) cJSON_AddItemToArray(pair, cJSON_CreateString(to_hex(v.bytes).c_str()));
else cJSON_AddItemToArray(pair, cJSON_CreateNumber((double)v.num));
cJSON_AddItemToObject(o, kv.first.c_str(), pair);
}
}
char *out = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
return out;
}
} // extern "C"
+26
View File
@@ -0,0 +1,26 @@
/* sim-driver: calls between the sim port's files (and the page, through the exported functions). */
#pragma once
#include <stddef.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
void sim_set_mac(const uint8_t mac[6]);
#ifdef SIM_MANUAL_CLOCK
void sim_clock_set_us(int64_t us);
#endif
/** Load the NVS store from JSON ({"ns": {"key": ["str", "v"], ...}}). False if the text is not valid. */
int sim_nvs_load(const char *json);
/** The NVS store as JSON. The caller frees it. */
char *sim_nvs_dump(void);
/** Copy the strip's last written frame (RGB, pixel 0 first) into out. Returns the LED count. */
int sim_frame(uint8_t *out, int cap);
#ifdef __cplusplus
}
#endif
+157
View File
@@ -0,0 +1,157 @@
/* sim-driver: the ESP-IDF runtime calls the driver makes (logging, errors, random, MAC, clock, restart),
* in place of desktop/port/src/esp_glue.c. Output goes to the page as the strip's serial log. */
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <emscripten.h>
#include "esp_err.h"
#include "esp_log.h"
#include "esp_mac.h"
#include "esp_random.h"
#include "esp_rom_sys.h"
#include "esp_system.h"
#include "esp_timer.h"
#include "nvs.h"
#include "sim.h"
static esp_log_level_t s_level = ESP_LOG_INFO;
static vprintf_like_t s_vprintf;
static uint8_t s_mac[6] = { 0x02, 0x51, 0x4d, 0x00, 0x00, 0x01 };
/* ---- clock --------------------------------------------------------------------------------- */
#ifdef SIM_MANUAL_CLOCK
static int64_t s_now_us;
void sim_clock_set_us(int64_t us)
{
s_now_us = us;
}
int64_t esp_timer_get_time(void)
{
return s_now_us;
}
#else
static int64_t s_t0_us = -1;
int64_t esp_timer_get_time(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
int64_t us = (int64_t)ts.tv_sec * 1000000 + ts.tv_nsec / 1000;
if (s_t0_us < 0) {
s_t0_us = us; // like the board: time since boot
}
return us - s_t0_us;
}
#endif
/* ---- logging ------------------------------------------------------------------------------- */
void esp_log_level_set(const char *tag, esp_log_level_t level)
{
(void)tag;
s_level = level;
}
vprintf_like_t esp_log_set_vprintf(vprintf_like_t fn)
{
vprintf_like_t old = s_vprintf;
s_vprintf = fn;
return old;
}
uint32_t esp_log_timestamp(void)
{
return (uint32_t)(esp_timer_get_time() / 1000);
}
void esp_log_write(esp_log_level_t level, const char *tag, const char *fmt, ...)
{
if (level > s_level) return;
static const char letters[] = " EWIDV";
char text[512];
va_list args;
va_start(args, fmt);
vsnprintf(text, sizeof(text), fmt, args);
va_end(args);
printf("%c (%u) %s: %s\n", letters[level], esp_log_timestamp(), tag, text);
}
const char *esp_err_to_name(esp_err_t code)
{
switch (code) {
case ESP_OK: return "ESP_OK";
case ESP_FAIL: return "ESP_FAIL";
case ESP_ERR_NO_MEM: return "ESP_ERR_NO_MEM";
case ESP_ERR_INVALID_ARG: return "ESP_ERR_INVALID_ARG";
case ESP_ERR_INVALID_STATE: return "ESP_ERR_INVALID_STATE";
case ESP_ERR_INVALID_SIZE: return "ESP_ERR_INVALID_SIZE";
case ESP_ERR_NOT_FOUND: return "ESP_ERR_NOT_FOUND";
case ESP_ERR_NOT_SUPPORTED: return "ESP_ERR_NOT_SUPPORTED";
case ESP_ERR_TIMEOUT: return "ESP_ERR_TIMEOUT";
case ESP_ERR_NVS_NOT_FOUND: return "ESP_ERR_NVS_NOT_FOUND";
default: return "ESP_ERR_UNKNOWN";
}
}
/* ---- random, MAC, heap, restart ------------------------------------------------------------ */
uint32_t esp_random(void)
{
uint32_t v;
esp_fill_random(&v, sizeof(v));
return v;
}
void esp_fill_random(void *buf, size_t len)
{
uint8_t *p = (uint8_t *)buf;
while (len) {
size_t n = len > 256 ? 256 : len; // getentropy takes at most 256 bytes
if (getentropy(p, n) != 0) {
for (size_t i = 0; i < n; i++) p[i] = (uint8_t)rand();
}
p += n;
len -= n;
}
}
void esp_rom_delay_us(uint32_t us)
{
usleep(us);
}
void sim_set_mac(const uint8_t mac[6])
{
memcpy(s_mac, mac, 6);
}
esp_err_t esp_read_mac(uint8_t mac[6], esp_mac_type_t type)
{
memcpy(mac, s_mac, 6);
if (type == ESP_MAC_WIFI_SOFTAP) mac[5] += 1; // as the board: the AP MAC is the station's + 1
return ESP_OK;
}
uint32_t esp_get_free_heap_size(void)
{
return 256 * 1024;
}
uint32_t esp_get_minimum_free_heap_size(void)
{
return 200 * 1024;
}
void esp_restart(void)
{
// The page terminates this worker and boots a fresh one with the flash the driver last committed
MAIN_THREAD_ASYNC_EM_ASM({
if (Module.simRestart) Module.simRestart();
});
for (;;) {
usleep(1000000);
}
}
+65
View File
@@ -0,0 +1,65 @@
/* sim-driver: one led-driver. sim_boot() starts what led-driver/main/main.cpp starts, less the parts with no
* meaning in the rig (Wi-Fi, HTTP, DDP, USB, OTA): strip, presets, startup preset, ESP-NOW link. There are no
* threads, so the board's two tasks do not start: the worker calls sim_tick() every few ms instead, which runs what
* they run, a pass of the ESP-NOW link and, every 10 ms, a pattern frame. */
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <emscripten.h>
#include "esp_log.h"
#include "esp_timer.h"
#include "espnow_link.h"
#include "patterns.h"
#include "presets.h"
#include "settings.h"
#include "sim.h"
static const char *TAG = "sim";
extern "C" {
/** Boot the driver: mac_hex is 12 hex digits, nvs_json the strip's flash. Returns 0, or -1 on bad input. */
EMSCRIPTEN_KEEPALIVE int sim_boot(const char *mac_hex, const char *nvs_json)
{
uint8_t mac[6];
if (!mac_hex || strlen(mac_hex) != 12) return -1;
for (int i = 0; i < 6; i++) {
char pair[3] = { mac_hex[2 * i], mac_hex[2 * i + 1], 0 };
mac[i] = (uint8_t)strtol(pair, nullptr, 16);
}
sim_set_mac(mac);
if (!sim_nvs_load(nvs_json)) {
ESP_LOGW(TAG, "flash is not valid JSON: starting with it erased");
sim_nvs_load("{}");
}
hw_cfg_t hw;
settings_load_hw(&hw);
patterns_start(hw);
if (presets_init() != ESP_OK) {
ESP_LOGE(TAG, "presets_init failed");
}
presets_apply_startup();
espnow_link_start();
net_cfg_t n;
settings_load_net(&n);
ESP_LOGI(TAG, "Ready: %s (%02x:%02x:%02x:%02x:%02x:%02x), %d LEDs, %d patterns", n.hostname, mac[0], mac[1],
mac[2], mac[3], mac[4], mac[5], hw.num_leds, patterns_count());
return 0;
}
/** Run what the board's tasks run: the ESP-NOW link (received frames, announces), and a pattern frame every 10 ms
* (FRAME_MS in patterns.cpp). The worker calls it every few ms. */
EMSCRIPTEN_KEEPALIVE void sim_tick(void)
{
static int64_t next_frame;
espnow_link_poll();
int64_t now = esp_timer_get_time();
if (now >= next_frame) {
patterns_frame();
next_frame = (now - next_frame > 50000 ? now : next_frame) + 10000; // catch up no more than a few frames
}
}
} // extern "C"
+81
View File
@@ -0,0 +1,81 @@
/* sim-driver: the WS2812 class with the board's API. write() publishes the frame for the page instead of
* driving the RMT peripheral. Colours stay RGB (the strip's byte order only matters on the wire). */
#include "ws2812.h"
#include <cstring>
#include <mutex>
#include <vector>
#include "sim.h"
namespace {
std::mutex s_mu;
std::vector<uint8_t> s_frame; // RGB, pixel 0 first
}
WS2812::WS2812(gpio_num_t gpio, size_t num_leds, uint32_t resolution_hz) : num_leds_(num_leds)
{
(void)gpio;
(void)resolution_hz;
pixels_.assign(num_leds * 3, 0);
tx_pixels_.assign(num_leds * 3, 0);
}
WS2812::~WS2812() = default;
void WS2812::set(size_t index, uint8_t r, uint8_t g, uint8_t b)
{
if (index >= num_leds_) return;
uint8_t *p = &pixels_[index * 3];
p[0] = r;
p[1] = g;
p[2] = b;
}
void WS2812::fill(uint8_t r, uint8_t g, uint8_t b)
{
for (size_t i = 0; i < num_leds_; i++) set(i, r, g, b);
}
esp_err_t WS2812::write()
{
for (size_t i = 0; i < pixels_.size(); i++) {
tx_pixels_[i] = (uint8_t)(pixels_[i] * brightness_ / 255);
}
std::lock_guard<std::mutex> g(s_mu);
s_frame = tx_pixels_;
return ESP_OK;
}
void WS2812::setOrder(const char *order)
{
(void)order;
}
void WS2812::hsv2rgb(uint32_t h, uint32_t s, uint32_t v, uint32_t *r, uint32_t *g, uint32_t *b)
{
// Same as led-driver/main/ws2812.cpp
h %= 360;
uint32_t rgb_max = v * 2.55f;
uint32_t rgb_min = rgb_max * (100 - s) / 100.0f;
uint32_t i = h / 60;
uint32_t diff = h % 60;
uint32_t rgb_adj = (rgb_max - rgb_min) * diff / 60;
switch (i) {
case 0: *r = rgb_max; *g = rgb_min + rgb_adj; *b = rgb_min; break;
case 1: *r = rgb_max - rgb_adj; *g = rgb_max; *b = rgb_min; break;
case 2: *r = rgb_min; *g = rgb_max; *b = rgb_min + rgb_adj; break;
case 3: *r = rgb_min; *g = rgb_max - rgb_adj; *b = rgb_max; break;
case 4: *r = rgb_min + rgb_adj; *g = rgb_min; *b = rgb_max; break;
default: *r = rgb_max; *g = rgb_min; *b = rgb_max - rgb_adj; break;
}
}
extern "C" int sim_frame(uint8_t *out, int cap)
{
std::lock_guard<std::mutex> g(s_mu);
int n = (int)(s_frame.size() / 3);
if (n * 3 > cap) n = cap / 3;
memcpy(out, s_frame.data(), (size_t)n * 3);
return n;
}