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

+24
View File
@@ -0,0 +1,24 @@
{
"version": "0.0.1",
"configurations": [
{
"name": "led-controller",
"url": "http://localhost:8080",
"port": 8080
},
{
"name": "led-controller-lan",
"url": "http://10.1.1.223:8080",
"port": 8080
},
{
"name": "led-controller-sim",
"runtimeExecutable": "bash",
"runtimeArgs": [
"-c",
"mkdir -p sim-controller/data && LED_SIM_DB=$PWD/sim-controller/data LED_SIM_BRIDGE=browser LED_SIM_HTTP_PORT=8081 exec sim-controller/build/led_controller_sim.elf"
],
"port": 8081
}
]
}
+8
View File
@@ -0,0 +1,8 @@
.git
**/build
managed_components
led-driver/managed_components
graphify-out
sim-controller/data
*.elf
*.bin
+7
View File
@@ -38,3 +38,10 @@ sdkconfig
sdkconfig.old
managed_components/
www_dist/
# desktop build (make desktop) and its data
build-desktop/
desktop-data/
desktop-data-test/
bridge/build-*/
sim-driver/build/
+5
View File
@@ -8,3 +8,8 @@ Rules:
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
- After modifying code, run `graphify update .` to keep the graph current (AST-only, no API cost).
- A committed graphify-out/graph.json is rewritten whole on every build, so a large diff to it in a pull request is expected. Do not flag it as churn or suggest skipping the graph rebuild or its hooks.
## ESP-IDF
- Build ESP-IDF firmware with ESP-IDF v6.1 only: the `espressif/idf:v6.1` Docker image (the Makefile's `IDF_IMAGE`), or the same v6.1 install. Do not build with the host install at `~/esp/esp-idf` (v5.5.1), and do not use the v5.5.5 image.
- Build in a fresh build directory created by the v6.1 image. A `build/` folder made outside it fails CMake with a cache mismatch, so delete it first if it is host-made.
+21
View File
@@ -0,0 +1,21 @@
# Desktop image of the controller firmware built for ESP-IDF's linux target: no hardware, no LAN.
# The web UI is embedded in the binary (main/CMakeLists.txt packs www_dist/www.pack), so no Node is needed.
# Build from the repo root: docker build -f Dockerfile.sim -t led-controller-sim .
# Run: docker run --rm -p 8080:8080 -v led-sim-data:/data led-controller-sim
FROM espressif/idf:v6.1 AS build
WORKDIR /project
COPY . .
RUN bash -c ". /opt/esp/idf/export.sh && cd sim-controller && idf.py build"
FROM debian:trixie
# The two shared libraries the binary needs, taken from the build image (no package install needed)
COPY --from=build /usr/lib/x86_64-linux-gnu/libbsd.so.0.12.1 /usr/lib/x86_64-linux-gnu/libbsd.so.0
COPY --from=build /usr/lib/x86_64-linux-gnu/libmd.so.0.1.0 /usr/lib/x86_64-linux-gnu/libmd.so.0
COPY --from=build /project/sim-controller/build/led_controller_sim.elf /usr/local/bin/led_controller_sim
ENV LED_SIM_DB=/data \
LED_SIM_HTTP_PORT=8080 \
LED_SIM_BRIDGE=127.0.0.1:8766
VOLUME ["/data"]
EXPOSE 8080
ENTRYPOINT ["/usr/local/bin/led_controller_sim"]
+94 -7
View File
@@ -23,7 +23,7 @@ TTY := $(shell [ -t 0 ] && echo -it)
OWNER := $(shell docker info --format '{{.SecurityOptions}}' 2>/dev/null | grep -q rootless && echo 0:0 || echo $$(id -u):$$(id -g))
FIX_OWNER = chown -R $(OWNER) /project
.PHONY: all help web build flash ota monitor flash-monitor log size menuconfig clean fullclean erase test test-driver test-envelope test-api test-browser sim-build sim sim-web test-sim
.PHONY: all help web build flash ota monitor flash-monitor log size menuconfig clean fullclean erase test test-driver test-envelope test-api test-browser sim-build sim sim-wasm sim-pack sim-web test-sim
# Default target: build, flash, then open the console (run in order, so not with make -j)
all: build flash monitor
@@ -50,7 +50,9 @@ help:
@echo "Simulated rig (no hardware): the controller built for linux + led-simulator's 16 drivers over a UDP bridge"
@echo " make sim-build build the controller for the host (sim-controller/build/led_controller_sim.elf)"
@echo " make sim build, then run the headless rig and the controller (http://localhost:8080/)"
@echo " make sim-web build, then run the browser rig (http://localhost:8765/) and the controller"
@echo " make sim-wasm build the browser drivers: led-driver (C++) to WebAssembly, with Emscripten in Docker"
@echo " make sim-web build all of it and run one program: the controller on http://localhost:8080/ with the"
@echo " simulated rig (rooms, every bar a driver) on /sim/ and the pattern gallery on /sim/gallery"
@echo " make test-sim rig tests (groups, field patterns, sequences) + the API tests against make sim"
@echo "variables: PORT=$(PORT) IDF_IMAGE=$(IDF_IMAGE)"
@@ -124,19 +126,104 @@ test-envelope:
else echo "envelope: MISMATCH"; diff $$tmp/py.txt $$tmp/c.txt; rm -rf $$tmp; exit 1; fi
# --- simulated rig --------------------------------------------------------
# The firmware built for ESP-IDF's linux target runs on this computer; its ESP-NOW frames go over UDP to
# led-simulator (bridge_sim.py headless, or server.py in the browser), whose drivers run led-driver/src.
# The firmware built for ESP-IDF's linux target runs on this computer and serves the simulated rig itself at
# /sim/ (sim-controller/components/sim/sim_rig.c): every bar is led-driver's C++ firmware built to WebAssembly
# (sim-driver/, `make sim-wasm`), laid out in a room, and gets the controller's ESP-NOW frames over the page's
# WebSocket (the "browser" bridge). bridge_sim.py is the older headless rig over UDP, whose drivers ran the
# MicroPython led-driver/src (since removed).
SIM_DB ?= $(CURDIR)/sim-controller/data
SIM_RUN = mkdir -p $(SIM_DB) && LED_SIM_DB=$(SIM_DB) LED_SIM_BRIDGE=127.0.0.1:8766 sim-controller/build/led_controller_sim.elf
sim-build: web
# The rig's page and drivers for the host builds to embed (www_dist/sim.pack; empty without `make sim-wasm`)
sim-pack:
tools/build_sim_web.sh
sim-build: web sim-pack
$(DOCKER_RUN) $(IDF_IMAGE) bash -c 'cd sim-controller && idf.py build; rc=$$?; $(FIX_OWNER); exit $$rc'
sim: sim-build
@trap 'kill 0' INT TERM EXIT; python3 led-simulator/bridge_sim.py & $(SIM_RUN)
sim-web: sim-build
@trap 'kill 0' INT TERM EXIT; python3 led-simulator/server.py & $(SIM_RUN)
# Emscripten in Docker (sim-driver/build.sh): led_driver (one strip) and led_fx (the pattern gallery)
EMSDK_IMAGE ?= emscripten/emsdk:4.0.12
sim-wasm:
EMSDK_IMAGE=$(EMSDK_IMAGE) sim-driver/build.sh
sim-web: sim-wasm sim-build
mkdir -p $(SIM_DB) && LED_SIM_DB=$(SIM_DB) LED_SIM_BRIDGE=browser sim-controller/build/led_controller_sim.elf
test-sim:
python3 -m pytest test/api -q --host localhost:8080
# --- desktop image (no hardware): the sim controller in Docker, web UI on localhost:8080 ----
# DOCKER_PULL=--pull=false (default) uses the local espressif/idf:v6.1 and debian:trixie images; set DOCKER_PULL= to refresh them
DOCKER_PULL ?= --pull=false
docker-sim:
DOCKER_BUILDKIT=0 docker build $(DOCKER_PULL) -f Dockerfile.sim -t led-controller-sim .
docker-sim-run:
docker run --rm -p 8080:8080 -v led-sim-data:/data led-controller-sim
# --- USB ESP-NOW bridge board (bridge/): ESP-NOW for a computer with no radio ------------------
# Two chips: ESP32-S3 (bridge-*-s3, with the I2S microphone) and ESP32-C3 (bridge-*-c3, no mic). Each has its own
# build dir (bridge/build-s3, bridge/build-c3). Flash with BRIDGE=<port>, e.g. make bridge-flash-s3 BRIDGE=/dev/ttyACM2.
# BRIDGE=/dev/ttyACM1 is the default for `make rig`, which runs the sim-controller build against it (no simulator).
BRIDGE ?= /dev/ttyACM1
define BRIDGE_BUILD
$(DOCKER_RUN) $(IDF_IMAGE) bash -c 'cd bridge; if [ ! -f build-$(1)/CMakeCache.txt ]; then idf.py -B build-$(1) -D SDKCONFIG=build-$(1)/sdkconfig set-target $(2); fi; idf.py -B build-$(1) -D SDKCONFIG=build-$(1)/sdkconfig build; rc=$$?; $(FIX_OWNER); exit $$rc'
endef
bridge-build-s3:
$(call BRIDGE_BUILD,s3,esp32s3)
bridge-build-c3:
$(call BRIDGE_BUILD,c3,esp32c3)
bridge-build: bridge-build-s3 bridge-build-c3
bridge-flash-s3: bridge-build-s3
$(DOCKER_RUN) --device=$(BRIDGE) $(IDF_IMAGE) bash -c 'cd bridge && idf.py -B build-s3 -D SDKCONFIG=build-s3/sdkconfig -p $(BRIDGE) flash; rc=$$?; $(FIX_OWNER); exit $$rc'
bridge-flash-c3: bridge-build-c3
$(DOCKER_RUN) --device=$(BRIDGE) $(IDF_IMAGE) bash -c 'cd bridge && idf.py -B build-c3 -D SDKCONFIG=build-c3/sdkconfig -p $(BRIDGE) flash; rc=$$?; $(FIX_OWNER); exit $$rc'
rig: sim-build
@test -n "$(BRIDGE)" || { echo "usage: make rig BRIDGE=/dev/ttyACM1"; exit 1; }
mkdir -p $(SIM_DB) && LED_SIM_DB=$(SIM_DB) LED_SIM_BRIDGE=$(BRIDGE) sim-controller/build/led_controller_sim.elf
# --- desktop: led-controller as a program, no ESP-IDF (desktop/); make deb for a headless install ---
DESKTOP_BUILD ?= build-desktop
DESKTOP_DATA ?= $(CURDIR)/desktop-data
DESKTOP_PORT ?= 8080
# Rebuilt when any web source changes
WEB_SRC := $(wildcard web/static/* web/templates/* web/*.html) tools/build_web.sh
www_dist/www.pack: $(WEB_SRC)
tools/build_web.sh
desktop: www_dist/www.pack sim-pack
cmake -S desktop -B $(DESKTOP_BUILD) -DCMAKE_BUILD_TYPE=Release
cmake --build $(DESKTOP_BUILD) -j$(shell nproc)
# The web UI is on http://localhost:$(DESKTOP_PORT)/; the bridges are set there (Settings > Network > Bridges), not here
desktop-run: desktop
$(DESKTOP_BUILD)/led-controller --db $(DESKTOP_DATA) --port $(DESKTOP_PORT)
test-desktop: desktop
mkdir -p $(DESKTOP_DATA)-test
$(DESKTOP_BUILD)/led-controller --db $(DESKTOP_DATA)-test --port 8081 > $(DESKTOP_DATA)-test/server.log 2>&1 & pid=$$!; sleep 2; python3 -m pytest test/api -q --host localhost:8081 --ignore=test/api/test_rig_sim.py; rc=$$?; kill $$pid 2>/dev/null; wait $$pid 2>/dev/null; exit $$rc
# led-cli (led-tool/) and the driver firmware image (led-driver/, built by its ESP-IDF v6.1 image) go into the .deb
LED_CLI_BIN := led-tool/dist/led-cli
LED_DRIVER_BIN := led-driver/build-v61/led_driver.bin
LED_TOOL_SRC := $(wildcard led-tool/*.py led-tool/lib/*.py)
led-cli: $(LED_CLI_BIN)
$(LED_CLI_BIN): $(LED_TOOL_SRC) led-tool/led-cli.spec
cd led-tool && pipenv run pyinstaller --clean --onefile --name led-cli --paths lib cli.py
deb: www_dist/www.pack $(LED_CLI_BIN)
@test -f $(LED_DRIVER_BIN) || { echo "missing $(LED_DRIVER_BIN): build led-driver with the espressif/idf:v6.1 image first"; exit 1; }
cmake -S desktop -B $(DESKTOP_BUILD) -DCMAKE_BUILD_TYPE=Release -DLED_BUNDLE_TOOLS=ON
cmake --build $(DESKTOP_BUILD) -j$(shell nproc)
cd $(DESKTOP_BUILD) && cpack -G DEB
.PHONY: desktop desktop-run test-desktop deb led-cli bridge-build bridge-build-s3 bridge-build-c3 bridge-flash-s3 bridge-flash-c3 rig
+4
View File
@@ -18,6 +18,10 @@ make test-browser HOST=<ip> # Selenium UI tests (needs selenium and chromedriv
`make` lists every target. The web UI sources are in `web/` (`static/`, `templates/`, `audio.html`); `tools/build_web.sh` also packs the led-driver pattern files into the firmware, so the controller can send them to drivers.
## Desktop
The same controller runs as a program on Linux, with no ESP-IDF: `make desktop-run` (then add the bridge under Settings > Network > Bridges), or a `.deb` with a systemd service (`make deb`). See [`desktop/README.md`](desktop/README.md). The USB ESP-NOW bridge board that gives a computer its radio is in [`bridge/`](bridge/README.md).
## Other directories
- `led-driver/` (submodule): MicroPython firmware for the ESP32 LED drivers.
+4
View File
@@ -0,0 +1,4 @@
# USB ESP-NOW bridge: lets a computer run led-controller against ESP-NOW drivers. See README.md.
cmake_minimum_required(VERSION 3.16)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(led_bridge)
+80
View File
@@ -0,0 +1,80 @@
# USB ESP-NOW bridge
An ESP32 board that gives a computer an ESP-NOW radio. Two builds: an ESP32-S3 (the one with an I2S
microphone, below) and an ESP32-C3 (ESP-NOW only). `led-controller` running on the computer
sends its ESP-NOW frames to the board over USB, and the board puts them on the air; frames from the
drivers come back the same way.
```
led-controller (host) --SLIP over USB-Serial-JTAG--> bridge board --ESP-NOW--> LED drivers
<------------------------------- <--------
```
## Build and flash
Built with ESP-IDF v6.1 (`espressif/idf:v6.1`), one build directory per chip (`bridge/build-s3`,
`bridge/build-c3`):
```bash
make bridge-build-s3 # or bridge-build-c3, or bridge-build for both
make bridge-flash-s3 BRIDGE=/dev/ttyACM2 # overwrites the board's firmware
make bridge-flash-c3 BRIDGE=/dev/ttyACM1
```
Flash only the board you mean: the flash targets overwrite whatever is on the port.
## Running the controller against it
```bash
make rig BRIDGE=/dev/ttyACM1 # the sim-controller build, web UI on http://localhost:8080/
```
Or set the bridge in settings (`"bridge": "/dev/ttyACM1"`), or `LED_SIM_BRIDGE=/dev/ttyACM1` for the sim.
The controller reconnects if the board is unplugged. Its status (`GET /status`, field `bridge_links`, one entry per bridge) shows
whether the board is linked, its MAC and channel, and the counters.
## Microphone (S3)
The S3 build reads an I2S microphone (an INMP441 wired as on the controller's XIAO ESP32-S3:
SCK GPIO 5, WS GPIO 6, SD GPIO 43, configurable under "Bridge microphone (I2S)" in menuconfig). While the
desktop records from it, the board sends 10 ms blocks of 16 kHz mono audio (AUDIO frames, below).
The desktop lists it in the audio input list as "I2S microphone on the bridge board". The C3 build has no
microphone and reports that in INFO.
## Channel
ESP-NOW runs on one Wi-Fi channel, and the drivers and the bridge must share it. The bridge starts on
channel 6. Set the channel the drivers use (the access point's, or the router's when a driver is joined to
one), either by a SET_CHANNEL frame (`bridge_serial_set_channel`) or by changing it on the board's NVS.
## Protocol
SLIP frames, each `[type][body][crc16 LE]` (CRC-16/CCITT-FALSE over type and body). The single source is
[`main/bridge_proto.h`](main/bridge_proto.h), shared by the firmware and the host
(`main/bridge_serial.c`).
| type | direction | body |
| --- | --- | --- |
| `00` PKT | host → board | `dst_mac(6) + packet` → ESP-NOW |
| `00` PKT | board → host | `src_mac(6) + packet` for every ESP-NOW frame received |
| `10` HELLO | host → board | (empty); answered with INFO |
| `11` INFO | board → host | version, MAC, channel, tx, tx_fail, rx, drop counters |
| `12` SET_CHANNEL | host → board | channel (1-13); answered with INFO |
| `13` SET_MIC | host → board | on (1) or off (0): send microphone audio |
| `40` AUDIO | board → host | 160 16-bit little-endian mono samples at 16 kHz, while the mic is on |
| `30` LOG | board → host | a log line |
INFO's last byte is capabilities: bit 0 is set when the board has a microphone.
The board sends one PKT at a time and waits for each send's result, so a burst cannot overrun the radio.
## Ethernet (W5500)
The S3 board also has a W5500 on SPI (XIAO pins by default: SCLK 7, MISO 8, MOSI 9, CS 2, INT 3, RST 1; change them in
`make menuconfig` under "Bridge Ethernet (W5500)"). It takes DHCP and answers UDP on port 8766, with the same datagrams as
the simulator's bridge: send `dst_mac + packet` and the board puts it on ESP-NOW; each frame it hears comes back to the last
sender as `src_mac + packet`.
The board's address is in INFO (bytes 25-28, with the Ethernet-up bit in byte 24), so the desktop shows it under the board's
status (`ip`). Add it as a network bridge with `<ip>:8766`. Don't use the USB and the UDP path for the same board at once:
each frame would go out over the air twice.
+34
View File
@@ -0,0 +1,34 @@
dependencies:
espressif/w5500:
component_hash: f76a95ce7a6029cf93aa39d47067588b24263852031f11c71e5d192ad915ec07
dependencies:
- name: espressif/wiznet_common
registry_url: https://components.espressif.com
require: private
version: ^1.1.0
- name: idf
require: private
version: '>=6.0'
source:
registry_url: https://components.espressif.com/
type: service
version: 2.0.1
espressif/wiznet_common:
component_hash: c32814cb872f0dca09f0c97ab231f9264a65bacc13fab6baf65f71959269a73d
dependencies:
- name: idf
require: private
version: '>=5.3'
source:
registry_url: https://components.espressif.com
type: service
version: 1.1.0
idf:
source:
type: idf
version: 6.1.0
direct_dependencies:
- espressif/w5500
manifest_hash: 37980d62fb7704a9cc50f484fba5b42932d4093c4bd83087951ae502d64f97c2
target: esp32s3
version: 3.0.0
+5
View File
@@ -0,0 +1,5 @@
idf_component_register(SRCS "bridge_main.c" "bridge_eth.c"
INCLUDE_DIRS "."
REQUIRES esp_wifi esp_netif esp_event nvs_flash esp_driver_usb_serial_jtag esp_timer esp_hw_support
esp_driver_i2s esp_driver_gpio esp_driver_spi esp_eth lwip
w5500)
+85
View File
@@ -0,0 +1,85 @@
menu "Bridge Ethernet (W5500)"
config BRIDGE_ETH
bool "W5500 Ethernet with a UDP bridge"
default y if IDF_TARGET_ESP32S3
default n
help
The board has a W5500 on SPI, wired to the network. It takes UDP datagrams on BRIDGE_ETH_PORT
(dst_mac + packet, sent on ESP-NOW) and sends frames it hears back to the last sender (src_mac + packet).
Its address is logged over the USB link once DHCP answers.
config BRIDGE_ETH_PORT
int "UDP port"
depends on BRIDGE_ETH
default 8766
config BRIDGE_ETH_AUDIO_PORT
int "UDP control port (microphone audio and HELLO)"
depends on BRIDGE_ETH
default 8767
config BRIDGE_ETH_SPI_CLOCK_MHZ
int "SPI clock (MHz)"
depends on BRIDGE_ETH
range 5 80
default 20
config BRIDGE_ETH_SCLK_GPIO
int "SCLK GPIO (XIAO D8)"
depends on BRIDGE_ETH
default 7
config BRIDGE_ETH_MISO_GPIO
int "MISO GPIO (XIAO D9)"
depends on BRIDGE_ETH
default 8
config BRIDGE_ETH_MOSI_GPIO
int "MOSI GPIO (XIAO D10)"
depends on BRIDGE_ETH
default 9
config BRIDGE_ETH_CS_GPIO
int "CS GPIO (XIAO D1)"
depends on BRIDGE_ETH
default 2
config BRIDGE_ETH_INT_GPIO
int "INT GPIO (XIAO D2), -1 to poll"
depends on BRIDGE_ETH
default 3
config BRIDGE_ETH_RST_GPIO
int "RST GPIO (XIAO D0), -1 if not wired"
depends on BRIDGE_ETH
default 1
endmenu
menu "Bridge microphone (I2S)"
config BRIDGE_MIC
bool "Stream an I2S microphone to the host"
default y if IDF_TARGET_ESP32S3
default n
help
The host (led-controller on the desktop) can record from an I2S mic on this board
(INMP441 wiring, as on the controller's XIAO ESP32-S3). Off on boards without one.
config BRIDGE_MIC_SCK_GPIO
int "I2S SCK (bit clock) GPIO"
depends on BRIDGE_MIC
default 5
config BRIDGE_MIC_WS_GPIO
int "I2S WS (word select) GPIO"
depends on BRIDGE_MIC
default 6
config BRIDGE_MIC_SD_GPIO
int "I2S SD (data) GPIO"
depends on BRIDGE_MIC
default 43
endmenu
+123
View File
@@ -0,0 +1,123 @@
#include "bridge_eth.h"
#include <string.h>
#include "driver/gpio.h"
#include "driver/spi_master.h"
#include "esp_eth.h"
#include "esp_eth_mac_w5500.h"
#include "esp_eth_phy_w5500.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_mac.h"
#include "esp_netif.h"
#include "sdkconfig.h"
static const char *TAG = "bridge_eth";
static volatile bool s_up;
static uint8_t s_ip[4];
static void on_got_ip(void *arg, esp_event_base_t base, int32_t id, void *data)
{
(void)arg;
(void)base;
(void)id;
const ip_event_got_ip_t *e = data;
s_up = true;
esp_ip4_addr_t a = e->ip_info.ip;
s_ip[0] = esp_ip4_addr1_16(&a);
s_ip[1] = esp_ip4_addr2_16(&a);
s_ip[2] = esp_ip4_addr3_16(&a);
s_ip[3] = esp_ip4_addr4_16(&a);
ESP_LOGI(TAG, "Ethernet address " IPSTR "/" IPSTR, IP2STR(&e->ip_info.ip), IP2STR(&e->ip_info.netmask));
}
static void on_eth_down(void *arg, esp_event_base_t base, int32_t id, void *data)
{
(void)arg;
(void)base;
(void)id;
(void)data;
s_up = false;
}
bool bridge_eth_up(void)
{
return s_up;
}
bool bridge_eth_ip(uint8_t ip[4])
{
if (!s_up) {
return false;
}
memcpy(ip, s_ip, 4);
return true;
}
esp_err_t bridge_eth_start(void)
{
// The INT pin uses a GPIO interrupt; the service may already be installed by another driver
esp_err_t isr = gpio_install_isr_service(0);
if (isr != ESP_OK && isr != ESP_ERR_INVALID_STATE) {
ESP_LOGE(TAG, "GPIO ISR service: %s", esp_err_to_name(isr));
return ESP_FAIL;
}
const spi_host_device_t host = SPI2_HOST;
spi_bus_config_t buscfg = {
.miso_io_num = CONFIG_BRIDGE_ETH_MISO_GPIO,
.mosi_io_num = CONFIG_BRIDGE_ETH_MOSI_GPIO,
.sclk_io_num = CONFIG_BRIDGE_ETH_SCLK_GPIO,
.quadwp_io_num = -1,
.quadhd_io_num = -1,
};
if (spi_bus_initialize(host, &buscfg, SPI_DMA_CH_AUTO) != ESP_OK) {
ESP_LOGE(TAG, "SPI bus init failed");
return ESP_FAIL;
}
spi_device_interface_config_t devcfg = {
.mode = 0,
.clock_speed_hz = CONFIG_BRIDGE_ETH_SPI_CLOCK_MHZ * 1000 * 1000,
.queue_size = 20,
.spics_io_num = CONFIG_BRIDGE_ETH_CS_GPIO,
};
eth_w5500_config_t wcfg = ETH_W5500_DEFAULT_CONFIG(host, &devcfg);
wcfg.base.int_gpio_num = CONFIG_BRIDGE_ETH_INT_GPIO;
if (CONFIG_BRIDGE_ETH_INT_GPIO < 0) {
wcfg.base.poll_period_ms = 10; // no INT wire: poll the chip
}
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_BRIDGE_ETH_RST_GPIO;
esp_eth_mac_t *mac = esp_eth_mac_new_w5500(&wcfg, &mac_config);
esp_eth_phy_t *phy = esp_eth_phy_new_w5500(&phy_config);
if (!mac || !phy) {
ESP_LOGE(TAG, "W5500 MAC/PHY create failed");
return ESP_FAIL;
}
esp_eth_config_t ecfg = ETH_DEFAULT_CONFIG(mac, phy);
esp_eth_handle_t eth = NULL;
if (esp_eth_driver_install(&ecfg, &eth) != ESP_OK) {
ESP_LOGE(TAG, "W5500 not found: check its wiring and power");
spi_bus_free(host);
return ESP_FAIL;
}
// The W5500 has no factory address: use the board's Ethernet MAC from eFuse
uint8_t eth_mac[6];
esp_read_mac(eth_mac, ESP_MAC_ETH);
esp_eth_ioctl(eth, ETH_CMD_S_MAC_ADDR, eth_mac);
esp_netif_config_t ncfg = ESP_NETIF_DEFAULT_ETH();
esp_netif_t *netif = esp_netif_new(&ncfg);
if (!netif || esp_netif_attach(netif, esp_eth_new_netif_glue(eth)) != ESP_OK) {
ESP_LOGE(TAG, "Ethernet netif failed");
return ESP_FAIL;
}
esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, on_got_ip, NULL);
esp_event_handler_register(ETH_EVENT, ETHERNET_EVENT_DISCONNECTED, on_eth_down, NULL);
if (esp_eth_start(eth) != ESP_OK) {
ESP_LOGE(TAG, "Ethernet start failed");
return ESP_FAIL;
}
ESP_LOGI(TAG, "W5500 on SPI, waiting for DHCP");
return ESP_OK;
}
+15
View File
@@ -0,0 +1,15 @@
#pragma once
// Ethernet for the bridge board: a W5500 on SPI, DHCP. The UDP bridge (bridge_main.c) runs on it: a host sends
// dst_mac + packet to this board's port and gets src_mac + packet back, the same as the simulator's bridge.
#include <stdbool.h>
#include <stdint.h>
#include "esp_err.h"
// Start the W5500 (pins from Kconfig). Its address is logged once DHCP answers. ESP_FAIL when there is no
// W5500 on the board; the USB bridge works without it.
esp_err_t bridge_eth_start(void);
bool bridge_eth_up(void);
// The board's IPv4 address (a.b.c.d) once DHCP has answered; false until then
bool bridge_eth_ip(uint8_t ip[4]);
+597
View File
@@ -0,0 +1,597 @@
/*
* USB ESP-NOW bridge. A computer talks to it over the USB-Serial-JTAG port in SLIP frames
* (bridge_proto.h); it sends each PKT's dst_mac + packet on ESP-NOW and returns every received frame
* as src_mac + packet. ESP-NOW runs on one Wi-Fi channel with no access point and no router.
*/
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "driver/gpio.h"
#include "driver/i2s_std.h"
#include "driver/usb_serial_jtag.h"
#include "esp_log.h"
#include "esp_mac.h"
#include "esp_netif.h"
#include "esp_event.h"
#include "esp_now.h"
#include "esp_wifi.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/semphr.h"
#include "esp_timer.h"
#include "freertos/task.h"
#include "lwip/sockets.h"
#include "nvs.h"
#include "nvs_flash.h"
#include "bridge_proto.h"
#include "sdkconfig.h"
#if CONFIG_BRIDGE_ETH
#include "bridge_eth.h"
#endif
static const char *TAG = "bridge";
#define DEFAULT_CHANNEL 6 // the controller's CONFIG_ESPNOW_CHANNEL
#define PEERS_MAX 19 // ESP-NOW allows 20 peers: 19 unicast and the broadcast one
#define TX_QUEUE_LEN 32
#define RX_QUEUE_LEN 32
#define SEND_WAIT_MS 100
typedef struct {
uint8_t mac[6];
uint8_t len;
uint8_t data[BRIDGE_PKT_MAX];
} pkt_t;
static const uint8_t BROADCAST[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
static QueueHandle_t s_txq;
static QueueHandle_t s_rxq;
static SemaphoreHandle_t s_sent; // given by the ESP-NOW send callback
static SemaphoreHandle_t s_usb_lock;
static volatile esp_now_send_status_t s_last_status;
static volatile bool s_usb_ready;
static uint8_t s_mac[6];
static uint8_t s_channel = DEFAULT_CHANNEL;
static uint8_t s_peers[PEERS_MAX][6]; // most recently used first
static int s_npeers;
static uint32_t s_tx, s_tx_fail, s_rx, s_drop;
static volatile bool s_mic_on; // the host asked for microphone audio (SET_MIC)
#if CONFIG_BRIDGE_ETH
// The UDP bridge: the host that sent the last datagram gets every frame the radio hears
static int s_udp = -1;
static SemaphoreHandle_t s_udp_lock;
static struct sockaddr_in s_udp_peer;
static bool s_udp_have_peer;
// The control port (BRIDGE_ETH_AUDIO_PORT): HELLO gets INFO back; SET_MIC 1 from a host makes this board send it
// microphone audio (AUDIO datagrams) until SET_MIC 1 stops arriving for MIC_UDP_TIMEOUT_MS
#define MIC_UDP_TIMEOUT_MS 2000
static int s_ctl = -1;
static struct sockaddr_in s_ctl_peer;
static bool s_ctl_mic;
static int64_t s_ctl_mic_ms;
#endif
/* ---- USB link ---------------------------------------------------------------------------------- */
// One whole frame per call, under the lock so frames from different tasks never interleave
#define USB_WRITE_PIECE 64
static void usb_send_frame(uint8_t type, const uint8_t *body, size_t n)
{
static uint8_t out[BRIDGE_ENC_MAX];
if (!s_usb_ready) {
return;
}
size_t len = bridge_encode(out, sizeof(out), type, body, n);
if (!len) {
return;
}
xSemaphoreTake(s_usb_lock, portMAX_DELAY);
size_t off = 0;
while (off < len) {
// The driver's TX ring takes a write only as a whole, so a frame longer than its ring is written in pieces
size_t piece = len - off < USB_WRITE_PIECE ? len - off : USB_WRITE_PIECE;
int w = usb_serial_jtag_write_bytes(out + off, piece, pdMS_TO_TICKS(200));
if (w <= 0) {
break; // host not reading: drop the rest rather than stall the radio
}
off += (size_t)w;
}
xSemaphoreGive(s_usb_lock);
}
// Log lines travel as LOG frames, so nothing but frames ever reaches the USB port
static int log_hook(const char *fmt, va_list args)
{
char line[200];
int n = vsnprintf(line, sizeof(line), fmt, args);
if (n > 0) {
size_t len = (size_t)n < sizeof(line) ? (size_t)n : sizeof(line) - 1;
usb_send_frame(BRIDGE_MSG_LOG, (const uint8_t *)line, len);
}
return n;
}
#if CONFIG_BRIDGE_MIC
#define BRIDGE_CAP_MIC_BOARD BRIDGE_CAP_MIC
#else
#define BRIDGE_CAP_MIC_BOARD 0
#endif
static void put_u32(uint8_t *p, uint32_t v)
{
p[0] = v & 0xFF;
p[1] = (v >> 8) & 0xFF;
p[2] = (v >> 16) & 0xFF;
p[3] = (v >> 24) & 0xFF;
}
// The INFO body (see bridge_proto.h), the same over USB and over the UDP control port
static void build_info(uint8_t *b)
{
b[0] = BRIDGE_PROTO_VERSION;
memcpy(b + 1, s_mac, 6);
b[7] = s_channel;
put_u32(b + 8, s_tx);
put_u32(b + 12, s_tx_fail);
put_u32(b + 16, s_rx);
put_u32(b + 20, s_drop);
uint8_t ip[4] = { 0, 0, 0, 0 };
uint8_t eth_cap = 0;
#if CONFIG_BRIDGE_ETH
if (bridge_eth_ip(ip)) {
eth_cap = BRIDGE_CAP_ETH;
}
#endif
b[24] = BRIDGE_CAP_MIC_BOARD | eth_cap;
memcpy(b + 25, ip, 4);
}
static void send_info(void)
{
uint8_t b[BRIDGE_INFO_LEN];
build_info(b);
usb_send_frame(BRIDGE_MSG_INFO, b, sizeof(b));
}
/* ---- ESP-NOW ----------------------------------------------------------------------------------- */
static void on_sent(const esp_now_send_info_t *info, esp_now_send_status_t status)
{
(void)info;
s_last_status = status;
xSemaphoreGive(s_sent);
}
static void on_recv(const esp_now_recv_info_t *info, const uint8_t *data, int len)
{
if (len <= 0 || len > BRIDGE_PKT_MAX) {
return;
}
pkt_t p;
memcpy(p.mac, info->src_addr, 6);
p.len = (uint8_t)len;
memcpy(p.data, data, len);
if (xQueueSend(s_rxq, &p, 0) == pdTRUE) {
s_rx++;
} else {
s_drop++;
}
}
// Keep the peer table within the ESP-NOW limit, least recently used dropped first
static void ensure_peer(const uint8_t *mac)
{
if (memcmp(mac, BROADCAST, 6) == 0) {
if (!esp_now_is_peer_exist(BROADCAST)) {
esp_now_peer_info_t p = { .channel = s_channel, .ifidx = WIFI_IF_STA, .encrypt = false };
memcpy(p.peer_addr, BROADCAST, 6);
esp_now_add_peer(&p);
}
return;
}
for (int i = 0; i < s_npeers; i++) {
if (memcmp(s_peers[i], mac, 6) == 0) {
uint8_t hit[6];
memcpy(hit, mac, 6);
memmove(s_peers[1], s_peers[0], i * 6);
memcpy(s_peers[0], hit, 6);
return;
}
}
if (s_npeers == PEERS_MAX) {
esp_now_del_peer(s_peers[PEERS_MAX - 1]);
s_npeers--;
}
esp_now_peer_info_t p = { .channel = s_channel, .ifidx = WIFI_IF_STA, .encrypt = false };
memcpy(p.peer_addr, mac, 6);
if (esp_now_add_peer(&p) != ESP_OK) {
return;
}
memmove(s_peers[1], s_peers[0], s_npeers * 6);
memcpy(s_peers[0], mac, 6);
s_npeers++;
}
static void drop_unicast_peers(void)
{
for (int i = 0; i < s_npeers; i++) {
esp_now_del_peer(s_peers[i]);
}
s_npeers = 0;
}
static void set_channel(uint8_t ch)
{
drop_unicast_peers(); // peers were added on the old channel
s_channel = ch;
esp_wifi_set_channel(ch, WIFI_SECOND_CHAN_NONE);
nvs_handle_t h;
if (nvs_open("bridge", NVS_READWRITE, &h) == ESP_OK) {
nvs_set_u8(h, "channel", ch);
nvs_commit(h);
nvs_close(h);
}
ESP_LOGI(TAG, "ESP-NOW channel %u", ch);
}
// One frame at a time, waiting for each send callback, so the radio is never overrun
static void tx_task(void *arg)
{
(void)arg;
pkt_t p;
for (;;) {
if (xQueueReceive(s_txq, &p, portMAX_DELAY) != pdTRUE) {
continue;
}
ensure_peer(p.mac);
if (esp_now_send(p.mac, p.data, p.len) != ESP_OK) {
s_tx_fail++;
continue;
}
if (xSemaphoreTake(s_sent, pdMS_TO_TICKS(SEND_WAIT_MS)) == pdTRUE && s_last_status == ESP_NOW_SEND_SUCCESS) {
s_tx++;
} else {
s_tx_fail++;
}
}
}
#if CONFIG_BRIDGE_ETH
static void udp_send_up(const uint8_t *body, size_t n);
#endif
// Received frames go to the host as src_mac + packet
static void rx_task(void *arg)
{
(void)arg;
pkt_t p;
uint8_t body[6 + BRIDGE_PKT_MAX];
for (;;) {
if (xQueueReceive(s_rxq, &p, portMAX_DELAY) != pdTRUE) {
continue;
}
memcpy(body, p.mac, 6);
memcpy(body + 6, p.data, p.len);
usb_send_frame(BRIDGE_MSG_PKT, body, 6 + p.len);
#if CONFIG_BRIDGE_ETH
udp_send_up(body, 6 + p.len);
#endif
}
}
#if CONFIG_BRIDGE_ETH
// Frames heard on ESP-NOW go to the last UDP sender as src_mac + packet
static void udp_send_up(const uint8_t *body, size_t n)
{
xSemaphoreTake(s_udp_lock, portMAX_DELAY);
if (s_udp_have_peer && s_udp >= 0) {
sendto(s_udp, body, n, 0, (const struct sockaddr *)&s_udp_peer, sizeof(s_udp_peer));
}
xSemaphoreGive(s_udp_lock);
}
// Datagrams from a host are dst_mac + packet, queued like a USB PKT frame. The sender becomes the peer.
static void udp_task(void *arg)
{
(void)arg;
uint8_t buf[6 + BRIDGE_PKT_MAX];
for (;;) {
struct sockaddr_in from;
socklen_t fl = sizeof(from);
int n = recvfrom(s_udp, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fl);
if (n <= 6) {
continue;
}
xSemaphoreTake(s_udp_lock, portMAX_DELAY);
s_udp_peer = from;
s_udp_have_peer = true;
xSemaphoreGive(s_udp_lock);
pkt_t p;
memcpy(p.mac, buf, 6);
p.len = (uint8_t)(n - 6);
memcpy(p.data, buf + 6, p.len);
if (xQueueSend(s_txq, &p, 0) != pdTRUE) {
s_drop++;
}
}
}
#if CONFIG_BRIDGE_ETH
static void ctl_task(void *arg)
{
(void)arg;
uint8_t buf[32];
for (;;) {
struct sockaddr_in from;
socklen_t fl = sizeof(from);
int n = recvfrom(s_ctl, buf, sizeof(buf), 0, (struct sockaddr *)&from, &fl);
if (n < 1) {
vTaskDelay(pdMS_TO_TICKS(10));
continue;
}
if (buf[0] == BRIDGE_MSG_HELLO) {
uint8_t out[1 + BRIDGE_INFO_LEN];
out[0] = BRIDGE_MSG_INFO;
build_info(out + 1);
sendto(s_ctl, out, sizeof(out), 0, (struct sockaddr *)&from, fl);
} else if (buf[0] == BRIDGE_MSG_SET_MIC && n >= 2) {
xSemaphoreTake(s_udp_lock, portMAX_DELAY);
s_ctl_peer = from;
s_ctl_mic = buf[1] != 0;
s_ctl_mic_ms = esp_timer_get_time() / 1000;
xSemaphoreGive(s_udp_lock);
}
}
}
static void ctl_open(void)
{
s_ctl = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(CONFIG_BRIDGE_ETH_AUDIO_PORT), .sin_addr.s_addr = htonl(INADDR_ANY) };
if (s_ctl < 0 || bind(s_ctl, (struct sockaddr *)&a, sizeof(a)) != 0) {
ESP_LOGE(TAG, "UDP control port %d not open", CONFIG_BRIDGE_ETH_AUDIO_PORT);
return;
}
xTaskCreate(ctl_task, "udp_ctl", 4096, NULL, 5, NULL);
ESP_LOGI(TAG, "UDP control on port %d", CONFIG_BRIDGE_ETH_AUDIO_PORT);
}
#endif
static void udp_open(void)
{
ESP_LOGI(TAG, "udp: opening");
s_udp = socket(AF_INET, SOCK_DGRAM, 0);
ESP_LOGI(TAG, "udp: socket %d", s_udp);
struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(CONFIG_BRIDGE_ETH_PORT), .sin_addr.s_addr = htonl(INADDR_ANY) };
if (s_udp < 0 || bind(s_udp, (struct sockaddr *)&a, sizeof(a)) != 0) {
ESP_LOGE(TAG, "UDP port %d not open", CONFIG_BRIDGE_ETH_PORT);
return;
}
xTaskCreate(udp_task, "udp_rx", 4096, NULL, 5, NULL);
ESP_LOGI(TAG, "UDP bridge on port %d", CONFIG_BRIDGE_ETH_PORT);
ctl_open();
}
#endif
/* ---- host commands ----------------------------------------------------------------------------- */
static void handle_frame(const uint8_t *msg, size_t len)
{
if (len < 1) {
return;
}
const uint8_t *body = msg + 1;
size_t n = len - 1;
switch (msg[0]) {
case BRIDGE_MSG_PKT: {
if (n < 7 || n > 6 + BRIDGE_PKT_MAX) {
return;
}
pkt_t p;
memcpy(p.mac, body, 6);
p.len = (uint8_t)(n - 6);
memcpy(p.data, body + 6, p.len);
if (xQueueSend(s_txq, &p, 0) != pdTRUE) {
s_drop++;
}
break;
}
case BRIDGE_MSG_HELLO:
send_info();
break;
case BRIDGE_MSG_SET_CHANNEL:
if (n >= 1 && body[0] >= 1 && body[0] <= 13) {
set_channel(body[0]);
}
send_info();
break;
case BRIDGE_MSG_SET_MIC:
if (n >= 1) {
s_mic_on = body[0] != 0;
ESP_LOGI(TAG, "microphone %s", s_mic_on ? "on" : "off");
}
break;
default:
break;
}
}
static void host_rx_task(void *arg)
{
(void)arg;
uint8_t buf[64];
bridge_decoder_t dec = { 0 };
for (;;) {
int n = usb_serial_jtag_read_bytes(buf, sizeof(buf), pdMS_TO_TICKS(50));
for (int i = 0; i < n; i++) {
if (bridge_decode_feed(&dec, buf[i])) {
handle_frame(dec.buf, dec.frame_len);
}
}
}
}
/* ---- microphone (boards with BRIDGE_MIC) ------------------------------------------------------- */
#if CONFIG_BRIDGE_MIC
#define MIC_RATE 16000
static i2s_chan_handle_t s_mic_chan;
// Reads the I2S mic all the time (so the bus never stalls) and sends 10 ms of 16-bit mono while the host wants it.
// The mic drives one of the two slots and the other reads 0: the busier slot is the one kept.
static void mic_task(void *arg)
{
(void)arg;
static int32_t raw[BRIDGE_AUDIO_SAMPLES * 2];
uint8_t out[BRIDGE_AUDIO_BYTES];
uint8_t dg[1 + BRIDGE_AUDIO_BYTES]; // a UDP audio datagram: AUDIO, then the samples
for (;;) {
size_t got = 0;
esp_err_t err = i2s_channel_read(s_mic_chan, raw, sizeof(raw), &got, portMAX_DELAY);
if (err != ESP_OK || got == 0) {
continue;
}
size_t frames = got / (2 * sizeof(int32_t));
size_t nonzero[2] = { 0, 0 };
for (size_t i = 0; i < frames; i++) {
nonzero[0] += raw[2 * i] != 0;
nonzero[1] += raw[2 * i + 1] != 0;
}
int ch = nonzero[1] > nonzero[0] ? 1 : 0;
bool want_usb = s_mic_on;
bool want_udp = false;
struct sockaddr_in peer;
#if CONFIG_BRIDGE_ETH
xSemaphoreTake(s_udp_lock, portMAX_DELAY);
want_udp = s_ctl_mic && esp_timer_get_time() / 1000 - s_ctl_mic_ms < MIC_UDP_TIMEOUT_MS;
peer = s_ctl_peer;
xSemaphoreGive(s_udp_lock);
#endif
if (!want_usb && !want_udp) {
continue;
}
for (size_t i = 0; i < frames; i++) {
int16_t s = (int16_t)(raw[2 * i + ch] >> 16); // 24-bit sample in the top of the 32-bit slot
out[2 * i] = (uint8_t)(s & 0xFF);
out[2 * i + 1] = (uint8_t)((uint16_t)s >> 8);
}
if (want_usb) {
usb_send_frame(BRIDGE_MSG_AUDIO, out, 2 * frames);
}
#if CONFIG_BRIDGE_ETH
if (want_udp) {
dg[0] = BRIDGE_MSG_AUDIO;
memcpy(dg + 1, out, 2 * frames);
sendto(s_ctl, dg, 1 + 2 * frames, 0, (struct sockaddr *)&peer, sizeof(peer));
}
#endif
}
}
static void mic_start(void)
{
i2s_chan_config_t chan = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_MASTER);
if (i2s_new_channel(&chan, NULL, &s_mic_chan) != ESP_OK) {
ESP_LOGE(TAG, "I2S channel create failed: no microphone");
return;
}
i2s_std_config_t std = {
.clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(MIC_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_BRIDGE_MIC_SCK_GPIO,
.ws = CONFIG_BRIDGE_MIC_WS_GPIO,
.dout = I2S_GPIO_UNUSED,
.din = CONFIG_BRIDGE_MIC_SD_GPIO,
},
};
if (i2s_channel_init_std_mode(s_mic_chan, &std) != ESP_OK || i2s_channel_enable(s_mic_chan) != ESP_OK) {
ESP_LOGE(TAG, "I2S mic init failed: no microphone");
return;
}
gpio_pulldown_en(CONFIG_BRIDGE_MIC_SD_GPIO); // SD tri-states outside the mic's slot
xTaskCreate(mic_task, "mic", 4096, NULL, 5, NULL);
ESP_LOGI(TAG, "I2S mic on SCK %d WS %d SD %d at %d Hz",
CONFIG_BRIDGE_MIC_SCK_GPIO, CONFIG_BRIDGE_MIC_WS_GPIO, CONFIG_BRIDGE_MIC_SD_GPIO, MIC_RATE);
}
#else
static void mic_start(void)
{
}
#endif
/* ---- start-up ---------------------------------------------------------------------------------- */
static void load_channel(void)
{
nvs_handle_t h;
if (nvs_open("bridge", NVS_READONLY, &h) == ESP_OK) {
uint8_t ch = 0;
if (nvs_get_u8(h, "channel", &ch) == ESP_OK && ch >= 1 && ch <= 13) {
s_channel = ch;
}
nvs_close(h);
}
}
void app_main(void)
{
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
nvs_flash_erase();
err = nvs_flash_init();
}
ESP_ERROR_CHECK(err);
load_channel();
s_txq = xQueueCreate(TX_QUEUE_LEN, sizeof(pkt_t));
s_rxq = xQueueCreate(RX_QUEUE_LEN, sizeof(pkt_t));
s_sent = xSemaphoreCreateBinary();
s_usb_lock = xSemaphoreCreateMutex();
#if CONFIG_BRIDGE_ETH
s_udp_lock = xSemaphoreCreateMutex(); // the microphone task uses it from the start
#endif
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
wifi_init_config_t wcfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&wcfg));
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_start());
ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE));
ESP_ERROR_CHECK(esp_wifi_set_channel(s_channel, WIFI_SECOND_CHAN_NONE));
ESP_ERROR_CHECK(esp_wifi_get_mac(WIFI_IF_STA, s_mac));
ESP_ERROR_CHECK(esp_now_init());
ESP_ERROR_CHECK(esp_now_register_send_cb(on_sent));
ESP_ERROR_CHECK(esp_now_register_recv_cb(on_recv));
ensure_peer(BROADCAST);
usb_serial_jtag_driver_config_t ucfg = USB_SERIAL_JTAG_DRIVER_CONFIG_DEFAULT();
ESP_ERROR_CHECK(usb_serial_jtag_driver_install(&ucfg));
s_usb_ready = true;
esp_log_set_vprintf(log_hook);
xTaskCreate(tx_task, "espnow_tx", 4096, NULL, 6, NULL);
xTaskCreate(rx_task, "espnow_rx", 4096, NULL, 6, NULL);
xTaskCreate(host_rx_task, "usb_rx", 4096, NULL, 5, NULL);
mic_start();
#if CONFIG_BRIDGE_ETH
ESP_LOGI(TAG, "eth: starting");
esp_err_t eth_err = bridge_eth_start();
ESP_LOGI(TAG, "eth: %s", esp_err_to_name(eth_err));
if (eth_err == ESP_OK) {
udp_open();
}
#endif
ESP_LOGI(TAG, "bridge %02x:%02x:%02x:%02x:%02x:%02x on ESP-NOW channel %u",
s_mac[0], s_mac[1], s_mac[2], s_mac[3], s_mac[4], s_mac[5], s_channel);
}
+149
View File
@@ -0,0 +1,149 @@
/*
* USB ESP-NOW bridge framing, shared by bridge/ (ESP32-C3 firmware) and main/bridge_serial.c (host).
*
* Each message is one SLIP frame (END-delimited, ESC-escaped) holding [type][body][crc16 LE], where the
* CRC-16/CCITT-FALSE covers type and body. Bytes outside frames are ignored by the host.
*
* 00 PKT host -> bridge dst_mac(6) + packet sent on ESP-NOW to dst_mac
* 00 PKT bridge -> host src_mac(6) + packet every frame received on ESP-NOW
* 10 HELLO host -> bridge (empty) answered with INFO
* 11 INFO bridge -> host see bridge_info below
* 12 SET_CHANNEL host -> bridge channel(1) sets the ESP-NOW channel, answered with INFO
* 13 SET_MIC host -> bridge on(1) start (1) or stop (0) streaming the microphone
* 40 AUDIO bridge -> host BRIDGE_AUDIO_SAMPLES 16-bit LE mono samples at 16 kHz, while the mic is on
* 30 LOG bridge -> host text the bridge's log lines
*
* INFO: byte 24 is capabilities (bit 0 = a microphone, BRIDGE_CAP_MIC; bit 1 = Ethernet up, BRIDGE_CAP_ETH),
* bytes 25-28 the board's Ethernet IPv4 address (0.0.0.0 while it has none).
*/
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#define BRIDGE_PROTO_VERSION 1
#define BRIDGE_PKT_MAX 250 // ESP-NOW payload limit
#define BRIDGE_AUDIO_SAMPLES 160 // 10 ms at 16 kHz
#define BRIDGE_AUDIO_BYTES (2 * BRIDGE_AUDIO_SAMPLES)
#define BRIDGE_PKT_BODY (6 + BRIDGE_PKT_MAX)
#define BRIDGE_BODY_MAX (BRIDGE_PKT_BODY > BRIDGE_AUDIO_BYTES ? BRIDGE_PKT_BODY : BRIDGE_AUDIO_BYTES)
#define BRIDGE_FRAME_MAX (BRIDGE_BODY_MAX + 3) // type + body + crc
#define BRIDGE_ENC_MAX (2 * BRIDGE_FRAME_MAX + 2)
#define BRIDGE_INFO_LEN 29
#define BRIDGE_CAP_MIC 0x01
#define BRIDGE_CAP_ETH 0x02
enum {
BRIDGE_MSG_PKT = 0x00,
BRIDGE_MSG_HELLO = 0x10,
BRIDGE_MSG_INFO = 0x11,
BRIDGE_MSG_SET_CHANNEL = 0x12,
BRIDGE_MSG_SET_MIC = 0x13,
BRIDGE_MSG_AUDIO = 0x40,
BRIDGE_MSG_LOG = 0x30,
};
#define SLIP_END 0xC0
#define SLIP_ESC 0xDB
#define SLIP_ESC_END 0xDC
#define SLIP_ESC_ESC 0xDD
static inline uint16_t bridge_crc16_update(uint16_t crc, uint8_t b)
{
crc ^= (uint16_t)b << 8;
for (int i = 0; i < 8; i++) {
crc = (crc & 0x8000) ? (uint16_t)((crc << 1) ^ 0x1021) : (uint16_t)(crc << 1);
}
return crc;
}
/* Encode one message into out (capacity cap). Returns the frame length, or 0 if it does not fit. */
static inline size_t bridge_encode(uint8_t *out, size_t cap, uint8_t type, const uint8_t *body, size_t n)
{
size_t off = 0;
uint16_t crc = 0xFFFF;
if (cap < 2) {
return 0;
}
out[off++] = SLIP_END;
/* the type and body bytes, then the CRC, each escaped as they go out */
for (size_t i = 0; i < n + 3; i++) {
uint8_t b;
if (i == 0) {
b = type;
crc = bridge_crc16_update(crc, b);
} else if (i <= n) {
b = body[i - 1];
crc = bridge_crc16_update(crc, b);
} else {
b = (i == n + 1) ? (uint8_t)(crc & 0xFF) : (uint8_t)(crc >> 8);
}
if (b == SLIP_END) {
if (off + 2 >= cap) return 0;
out[off++] = SLIP_ESC;
out[off++] = SLIP_ESC_END;
} else if (b == SLIP_ESC) {
if (off + 2 >= cap) return 0;
out[off++] = SLIP_ESC;
out[off++] = SLIP_ESC_ESC;
} else {
if (off + 1 >= cap) return 0;
out[off++] = b;
}
}
if (off + 1 > cap) return 0;
out[off++] = SLIP_END;
return off;
}
/* Incremental decoder. Feed bytes; when bridge_decode_feed returns true, d->buf holds [type][body] of
* length d->frame_len, valid until the next call. */
typedef struct {
uint8_t buf[BRIDGE_FRAME_MAX];
size_t len;
size_t frame_len;
bool esc;
bool overflow;
} bridge_decoder_t;
static inline bool bridge_decode_feed(bridge_decoder_t *d, uint8_t b)
{
if (b == SLIP_END) {
bool ok = false;
if (!d->overflow && d->len >= 3) {
uint16_t crc = 0xFFFF;
for (size_t i = 0; i < d->len - 2; i++) {
crc = bridge_crc16_update(crc, d->buf[i]);
}
uint16_t got = (uint16_t)(d->buf[d->len - 2] | (d->buf[d->len - 1] << 8));
ok = crc == got;
if (ok) {
d->frame_len = d->len - 2;
}
}
d->len = 0;
d->esc = false;
d->overflow = false;
return ok;
}
if (d->esc) {
d->esc = false;
if (b == SLIP_ESC_END) {
b = SLIP_END;
} else if (b == SLIP_ESC_ESC) {
b = SLIP_ESC;
} else {
d->overflow = true; // not valid SLIP: drop the frame
}
} else if (b == SLIP_ESC) {
d->esc = true;
return false;
}
if (d->len < sizeof(d->buf)) {
d->buf[d->len++] = b;
} else {
d->overflow = true;
}
return false;
}
+3
View File
@@ -0,0 +1,3 @@
dependencies:
espressif/w5500:
version: "^2.0.1"
+7
View File
@@ -0,0 +1,7 @@
# The USB-Serial-JTAG port carries the SLIP link to the host, so the console must not write to it
CONFIG_ESP_CONSOLE_NONE=y
CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=n
CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=10
CONFIG_ESP_WIFI_DYNAMIC_RX_BUFFER_NUM=32
CONFIG_ETH_USE_SPI_ETHERNET=y
CONFIG_ETH_SPI_ETHERNET_W5500=y
+39 -3
View File
@@ -1,4 +1,14 @@
dependencies:
espressif/cjson:
component_hash: e788323270d90738662d66fffa910bfe1fba019bba087f01557e70c40485b469
dependencies:
- name: idf
require: private
version: '>=5.0'
source:
registry_url: https://components.espressif.com/
type: service
version: 1.7.19~2
espressif/mdns:
component_hash: ef0766474b37459f6ad22461e453a8713e780e831a7c993b16919d817988dff6
dependencies:
@@ -9,10 +19,34 @@ dependencies:
registry_url: https://components.espressif.com/
type: service
version: 1.14.1
espressif/w5500:
component_hash: f76a95ce7a6029cf93aa39d47067588b24263852031f11c71e5d192ad915ec07
dependencies:
- name: espressif/wiznet_common
registry_url: https://components.espressif.com
require: private
version: ^1.1.0
- name: idf
require: private
version: '>=6.0'
source:
registry_url: https://components.espressif.com/
type: service
version: 2.0.1
espressif/wiznet_common:
component_hash: c32814cb872f0dca09f0c97ab231f9264a65bacc13fab6baf65f71959269a73d
dependencies:
- name: idf
require: private
version: '>=5.3'
source:
registry_url: https://components.espressif.com
type: service
version: 1.1.0
idf:
source:
type: idf
version: 5.5.5
version: 6.1.0
joltwallet/littlefs:
component_hash: e1a0f4a6adf821759cb34703a91107bbdce5d7ff6f4728f40ab012bb87842974
dependencies:
@@ -24,8 +58,10 @@ dependencies:
type: service
version: 1.23.1
direct_dependencies:
- espressif/cjson
- espressif/mdns
- espressif/w5500
- joltwallet/littlefs
manifest_hash: a5329d49f0154685d9701ccb399916a87107b77ddfe802c911aa2bb41ed5bab0
manifest_hash: d66adeab020ae08629bcb8999b623eb65117c51257a671ab53bd5dc8e8045975
target: esp32s3
version: 2.0.0
version: 3.0.0
+129
View File
@@ -0,0 +1,129 @@
# led-controller for the desktop: the firmware's sources built with a plain C compiler, no ESP-IDF.
# Build from the repository root with `make desktop`, or here:
# cmake -S desktop -B build-desktop && cmake --build build-desktop
# Needs www_dist/www.pack (tools/build_web.sh). Third-party code is vendored: desktop/tools/vendor.sh.
cmake_minimum_required(VERSION 3.16)
project(led_controller_desktop VERSION 0.1.0 LANGUAGES C)
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS ON)
find_package(Threads REQUIRED)
set(ROOT ${CMAKE_CURRENT_SOURCE_DIR}/..)
set(WWW_PACK ${ROOT}/www_dist/www.pack)
if(NOT EXISTS ${WWW_PACK})
message(FATAL_ERROR "www_dist/www.pack is missing: run tools/build_web.sh (make web)")
endif()
# The simulated rig at /sim/ (tools/build_sim_web.sh). Optional: an empty pack when it is not built.
set(SIM_PACK ${ROOT}/www_dist/sim.pack)
if(NOT EXISTS ${SIM_PACK})
file(WRITE ${SIM_PACK} "WWW1")
endif()
execute_process(COMMAND git -C ${ROOT} describe --tags --always --dirty
OUTPUT_VARIABLE LED_VERSION OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
if(NOT LED_VERSION)
set(LED_VERSION "desktop")
endif()
# The firmware's app sources (the same list as main/CMakeLists.txt's linux branch, plus the bridge transport)
set(MAIN_SRC
beat.c beat_dsp.c espnow_tx.c bridge.c store.c api.c web.c envelope.c engine.c rel.c bench.c audio.c
res_profile.c res_misc.c res_device.c res_group.c seqplay.c res_bundle.c audio_api.c patterns.c outputs.c
ws.c ws_client.c wifi_drv.c bridge_serial.c)
list(TRANSFORM MAIN_SRC PREPEND ${ROOT}/main/)
# The host stand-ins for the board's hardware (mic, OTA, littlefs, timers) and the app_main that starts it
set(SIM_SRC sim_main.c sim_stubs.c sim_timer.c sim_rig.c)
list(TRANSFORM SIM_SRC PREPEND ${ROOT}/sim-controller/components/sim/)
set(THIRD_PARTY
third_party/esp_http_server/src/httpd_main.c
third_party/esp_http_server/src/httpd_parse.c
third_party/esp_http_server/src/httpd_sess.c
third_party/esp_http_server/src/httpd_txrx.c
third_party/esp_http_server/src/httpd_uri.c
third_party/esp_http_server/src/httpd_ws.c
third_party/esp_http_server/src/util/ctrl_sock.c
third_party/http_parser/http_parser.c
third_party/cjson/cJSON.c)
set(PORT
port/src/freertos.c
port/src/esp_glue.c
port/src/desktop_crypto.c
port/src/www_pack.c
port/src/sim_pack.c
port/src/mdns_host.c
port/src/mic_alsa.c)
add_executable(led-controller desktop_main.c ${MAIN_SRC} ${SIM_SRC} ${THIRD_PARTY} ${PORT})
# www_pack.c embeds the pack with .incbin, which CMake can't see: rebuild it when the pack changes
set_source_files_properties(port/src/www_pack.c PROPERTIES OBJECT_DEPENDS ${WWW_PACK})
set_source_files_properties(port/src/sim_pack.c PROPERTIES OBJECT_DEPENDS ${SIM_PACK})
target_include_directories(led-controller PRIVATE
port/include
${ROOT}/main
${ROOT}/bridge/main
${ROOT}/sim-controller/components/sim
${ROOT}/sim-controller/components/sim/include
third_party/esp_http_server/include
third_party/esp_http_server/src
third_party/esp_http_server/src/util
third_party/http_parser
third_party/cjson)
target_compile_definitions(led-controller PRIVATE
_GNU_SOURCE
LED_DESKTOP_MDNS
LED_DESKTOP_ALSA
LED_APP_VERSION="${LED_VERSION}"
WWW_PACK="${WWW_PACK}"
SIM_PACK="${SIM_PACK}")
# ESP-IDF force-includes the build's sdkconfig.h into every source; the desktop port has the same file
target_compile_options(led-controller PRIVATE -include ${CMAKE_CURRENT_SOURCE_DIR}/port/include/sdkconfig.h
-Wall -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter)
find_library(ASOUND_LIB asound REQUIRED) # ALSA capture for the microphone (libasound2-dev at build time)
target_link_libraries(led-controller PRIVATE Threads::Threads m rt ${ASOUND_LIB})
install(TARGETS led-controller RUNTIME DESTINATION bin)
# Headless install: a .deb with the program, a systemd service and its default settings (`make deb`).
# The service runs as a dynamic user with its store in /var/lib/led-controller.
set(CPACK_PACKAGING_INSTALL_PREFIX /usr)
set(CMAKE_INSTALL_PREFIX /usr)
install(FILES packaging/led-controller.service DESTINATION lib/systemd/system)
install(FILES packaging/led-controller.default DESTINATION /etc/default RENAME led-controller)
install(FILES packaging/led-bridge.udev.example DESTINATION share/doc/led-controller)
install(FILES ${ROOT}/README.md DESTINATION share/doc/led-controller RENAME README.md OPTIONAL)
install(FILES ${ROOT}/bridge/README.md DESTINATION share/doc/led-controller RENAME bridge-README.md OPTIONAL)
# The command-line tool (led-tool, a PyInstaller binary) and the LED driver firmware image (led-driver, built with
# ESP-IDF v6.1). Both are bundled into the .deb when LED_BUNDLE_TOOLS is on (`make deb` turns it on).
option(LED_BUNDLE_TOOLS "Install led-cli and the led-driver firmware image into the package" OFF)
set(LED_CLI_BIN ${ROOT}/led-tool/dist/led-cli)
set(LED_DRIVER_BIN ${ROOT}/led-driver/build-v61/led_driver.bin)
if(LED_BUNDLE_TOOLS)
if(NOT EXISTS ${LED_CLI_BIN})
message(FATAL_ERROR "led-tool/dist/led-cli is missing: run make led-cli")
endif()
if(NOT EXISTS ${LED_DRIVER_BIN})
message(FATAL_ERROR "led-driver/build-v61/led_driver.bin is missing: build the driver with the ESP-IDF v6.1 image")
endif()
install(PROGRAMS ${LED_CLI_BIN} DESTINATION bin)
install(FILES ${LED_DRIVER_BIN} DESTINATION share/led-controller/firmware)
endif()
set(CPACK_PACKAGE_NAME "led-controller")
set(CPACK_PACKAGE_VERSION "${PROJECT_VERSION}")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "LED rig controller: web UI, presets, sequences and ESP-NOW to the LED drivers")
set(CPACK_PACKAGE_CONTACT "led-controller packagers <packaging@localhost>")
set(CPACK_GENERATOR "DEB")
set(CPACK_DEBIAN_PACKAGE_SECTION "misc")
set(CPACK_DEBIAN_PACKAGE_PRIORITY "optional")
set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON)
set(CPACK_DEBIAN_FILE_NAME DEB-DEFAULT)
set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA ${CMAKE_CURRENT_SOURCE_DIR}/packaging/postinst
${CMAKE_CURRENT_SOURCE_DIR}/packaging/prerm
${CMAKE_CURRENT_SOURCE_DIR}/packaging/postrm
${CMAKE_CURRENT_SOURCE_DIR}/packaging/conffiles)
include(CPack)
+69
View File
@@ -0,0 +1,69 @@
# led-controller on a desktop
The controller firmware (`main/`) built as a program for Linux: no ESP-IDF, no Docker, no board. The web
UI and API are the same as the board's. ESP-NOW goes through a bridge: the USB bridge board (`bridge/`)
or a UDP bridge such as `led-simulator`.
## Build and run
Needs `cmake`, a C compiler, and `www_dist/www.pack` (`make web` builds it with `node`).
```bash
make desktop # builds build-desktop/led-controller
make desktop-run # the web UI on http://localhost:8080/
make test-desktop # starts the program and runs the API tests against it
```
Or run it directly:
```bash
build-desktop/led-controller --db ./data --port 8080
```
| option | environment | meaning |
| --- | --- | --- |
| `--db DIR` | `LED_CONTROLLER_DB` | the store (default `/db`) |
| `--port N` | `LED_CONTROLLER_HTTP_PORT` | web UI and API port (default 8080) |
`LED_LOG_LEVEL=error|warn|info|debug|verbose` sets how much is logged (default `info`).
## Install as a service (.deb)
```bash
make deb # build-desktop/led-controller_0.1.0_<arch>.deb
sudo apt install ./build-desktop/led-controller_0.1.0_*.deb
```
The package installs `/usr/bin/led-controller`, the `led-cli` command-line tool (`/usr/bin/led-cli`), the LED driver
firmware image (`/usr/share/led-controller/firmware/led_driver.bin`), a systemd unit (`led-controller.service`) that runs it as a
dynamic user with its store in `/var/lib/led-controller`, and `/etc/default/led-controller` for the port. The service starts at install and restarts after a restart from
the web UI. The bridges are kept in the controller's settings, so set them in the web UI under Settings > Network >
Bridges. Change the port in `/etc/default/led-controller`, then `sudo systemctl restart led-controller`. The bridge's serial port is
owned by `dialout`, which the service joins.
`packaging/led-bridge.udev.example` (installed in `/usr/share/doc/led-controller/`) gives the bridge board a
stable name, `/dev/led-bridge`, by its serial number.
## How it is built
`desktop/CMakeLists.txt` compiles the firmware's own sources (`main/`, and the host stand-ins in
`sim-controller/components/sim/`: mic, OTA, littlefs and the timers) with a small port of the ESP-IDF APIs
they use:
- `port/src/freertos.c`: tasks, queues, semaphores, stream buffers and event groups on POSIX threads.
- `port/src/esp_glue.c`: logging, error names, random numbers, the MAC (from the first real network
interface), restart (an exit, for the service manager), and the app description.
- `port/src/desktop_crypto.c`: SHA-1 and base64 for the WebSocket handshake.
- `port/src/www_pack.c`: the web UI pack (`www_dist/www.pack`) embedded in the program.
- `port/include/`: the headers. `sdkconfig.h` is the config the sim's build generated.
Third-party code is vendored in `third_party/`: the HTTP server and `http_parser` from ESP-IDF v6.1, and cJSON.
`tools/vendor.sh` refreshes them (it runs `espressif/idf:v6.1` to copy the httpd sources). Its patch
(`tools/patch_vendor.py`) swaps the handshake's mbedTLS and PSA calls for `desktop_crypto.c`.
## Limits
- ESP-NOW needs the bridge. Without one the program runs, and its ESP-NOW frames go nowhere.
- The Wi-Fi drivers are not discovered automatically: their mDNS discovery is not in the desktop build yet.
- Firmware OTA is not available (the API answers 501, as in the simulator).
- The mic is simulated: beats come from the BPM clock, as in the simulator.
+56
View File
@@ -0,0 +1,56 @@
/*
* led-controller as a desktop program: the firmware's app_main (sim-controller/components/sim/sim_main.c)
* with its settings from the command line or the environment. No ESP-IDF is needed to build or run it.
*
* led-controller [--db DIR] [--port N]
*
* The bridges (the USB bridge board, /dev/ttyACM1, or host:port over UDP such as led-simulator) are kept in
* the store's settings: set them in the web UI under Settings > Network > Bridges. The environment works
* too: LED_CONTROLLER_DB, LED_CONTROLLER_HTTP_PORT. Without a bridge the program runs, but its ESP-NOW frames
* go nowhere.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void app_main(void);
static void set_from_env(const char *from, const char *to)
{
const char *v = getenv(from);
if (v && v[0] && !(getenv(to) && getenv(to)[0])) {
setenv(to, v, 1);
}
}
static void usage(FILE *out)
{
fprintf(out,
"usage: led-controller [--db DIR] [--port N]\n"
" --db DIR store directory (default /db)\n"
" --port N web UI and API port (default 8080)\n"
" bridges are set in the web UI (Settings > Network > Bridges)\n");
}
int main(int argc, char **argv)
{
for (int i = 1; i < argc; i++) {
const char *a = argv[i];
if (!strcmp(a, "-h") || !strcmp(a, "--help")) {
usage(stdout);
return 0;
}
if ((!strcmp(a, "--db") || !strcmp(a, "--port")) && i + 1 < argc) {
const char *val = argv[++i];
setenv(!strcmp(a, "--db") ? "LED_SIM_DB" : "LED_SIM_HTTP_PORT", val, 1);
continue;
}
fprintf(stderr, "led-controller: unknown option %s\n", a);
usage(stderr);
return 2;
}
set_from_env("LED_CONTROLLER_DB", "LED_SIM_DB");
set_from_env("LED_CONTROLLER_HTTP_PORT", "LED_SIM_HTTP_PORT");
app_main(); // runs until the process is stopped
return 0;
}
+1
View File
@@ -0,0 +1 @@
/etc/default/led-controller
@@ -0,0 +1,4 @@
# Optional: a stable name for the USB ESP-NOW bridge board, so its bridge in the web UI can be /dev/led-bridge.
# Replace the serial with the board's (the MAC printed by `make bridge-build`'s HELLO, or `udevadm info -q property -n /dev/ttyACM1`).
# Copy to /etc/udev/rules.d/99-led-bridge.rules, then: sudo udevadm control --reload && sudo udevadm trigger
SUBSYSTEM=="tty", ATTRS{idVendor}=="303a", ATTRS{idProduct}=="1001", ATTRS{serial}=="7C:4F:AD:20:AF:58", SYMLINK+="led-bridge", GROUP="dialout", MODE="0660"
+8
View File
@@ -0,0 +1,8 @@
# led-controller settings, read by /lib/systemd/system/led-controller.service. Restart the service after a change:
# sudo systemctl restart led-controller
# Web UI and API port
LED_CONTROLLER_HTTP_PORT=8080
# The ESP-NOW bridges (the USB bridge board, or host:port of a UDP bridge such as led-simulator) are kept in
# the controller's settings: set them in the web UI under Settings > Network > Bridges.
+27
View File
@@ -0,0 +1,27 @@
[Unit]
Description=led-controller: LED rig controller and web UI
Documentation=file:///usr/share/doc/led-controller/README.md
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
# Settings from /etc/default/led-controller: LED_CONTROLLER_HTTP_PORT (the bridges are set in the web UI)
EnvironmentFile=-/etc/default/led-controller
ExecStart=/usr/bin/led-controller --db /var/lib/led-controller
# A restart from the web UI exits the program (esp_restart), so always bring it back
Restart=always
RestartSec=2
# The USB bridge board is a serial port, owned by the dialout group on Debian and Ubuntu
SupplementaryGroups=dialout
DynamicUser=yes
StateDirectory=led-controller
# Port 80 without root, when LED_CONTROLLER_HTTP_PORT=80
AmbientCapabilities=CAP_NET_BIND_SERVICE
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
PrivateTmp=yes
[Install]
WantedBy=multi-user.target
+21
View File
@@ -0,0 +1,21 @@
#!/bin/sh
set -e
case "$1" in
configure)
if [ -d /run/systemd/system ]; then
systemctl daemon-reload >/dev/null 2>&1 || true
fi
if command -v deb-systemd-helper >/dev/null 2>&1; then
deb-systemd-helper unmask led-controller.service >/dev/null || true
deb-systemd-helper enable led-controller.service >/dev/null || true
fi
if command -v deb-systemd-invoke >/dev/null 2>&1; then
if [ -n "$2" ]; then
deb-systemd-invoke restart led-controller.service >/dev/null || true
else
deb-systemd-invoke start led-controller.service >/dev/null || true
fi
fi
;;
esac
exit 0
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
set -e
case "$1" in
purge)
if command -v deb-systemd-helper >/dev/null 2>&1; then
deb-systemd-helper purge led-controller.service >/dev/null || true
deb-systemd-helper unmask led-controller.service >/dev/null || true
fi
;;
esac
if [ -d /run/systemd/system ]; then
systemctl daemon-reload >/dev/null 2>&1 || true
fi
exit 0
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
set -e
case "$1" in
remove|deconfigure|upgrade)
if command -v deb-systemd-invoke >/dev/null 2>&1; then
deb-systemd-invoke stop led-controller.service >/dev/null || true
fi
;;
esac
exit 0
+9
View File
@@ -0,0 +1,9 @@
/* SHA-1 and base64 for the WebSocket handshake (desktop/port/src/desktop_crypto.c) */
#pragma once
#include <stddef.h>
#include <stdint.h>
void desktop_sha1(const uint8_t *data, size_t len, uint8_t out[20]);
// Writes the NUL-terminated base64 of in; returns the length without the NUL, 0 if out is too small
size_t desktop_base64_encode(char *out, size_t cap, const uint8_t *in, size_t n);
+16
View File
@@ -0,0 +1,16 @@
#pragma once
#include <stdint.h>
typedef struct {
uint32_t magic_word;
uint32_t secure_version;
char version[32];
char project_name[32];
char time[16];
char date[16];
char idf_ver[32];
uint8_t app_elf_sha256[32];
} esp_app_desc_t;
const esp_app_desc_t *esp_app_get_description(void);
+39
View File
@@ -0,0 +1,39 @@
#pragma once
#include <stdlib.h>
#include "esp_err.h"
#include "esp_log.h"
#define ESP_RETURN_ON_ERROR(x, tag, fmt, ...) \
do { \
esp_err_t err_rc_ = (x); \
if (err_rc_ != ESP_OK) { \
ESP_LOGE(tag, "%s(%d): " fmt, __func__, (int)err_rc_, ##__VA_ARGS__); \
return err_rc_; \
} \
} while (0)
#define ESP_RETURN_ON_FALSE(cond, err, tag, fmt, ...) \
do { \
if (!(cond)) { \
ESP_LOGE(tag, "%s(%d): " fmt, __func__, (int)(err), ##__VA_ARGS__); \
return (err); \
} \
} while (0)
#define ESP_ERROR_CHECK(x) \
do { \
esp_err_t err_rc_ = (x); \
if (err_rc_ != ESP_OK) { \
ESP_LOGE("check", "%s:%d: %s", __FILE__, __LINE__, esp_err_to_name(err_rc_)); \
abort(); \
} \
} while (0)
#define ESP_ERROR_CHECK_WITHOUT_ABORT(x) \
do { \
esp_err_t err_rc_ = (x); \
if (err_rc_ != ESP_OK) { \
ESP_LOGE("check", "%s:%d: %s", __FILE__, __LINE__, esp_err_to_name(err_rc_)); \
} \
} while (0)
+65
View File
@@ -0,0 +1,65 @@
/* Desktop port: the ESP-IDF error codes the firmware uses (same values as ESP-IDF). */
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include "esp_log.h"
typedef int32_t esp_err_t;
#define ESP_OK 0
#define ESP_FAIL -1
#define ESP_ERR_NO_MEM 0x101
#define ESP_ERR_INVALID_ARG 0x102
#define ESP_ERR_INVALID_STATE 0x103
#define ESP_ERR_INVALID_SIZE 0x104
#define ESP_ERR_NOT_FOUND 0x105
#define ESP_ERR_NOT_SUPPORTED 0x106
#define ESP_ERR_TIMEOUT 0x107
#define ESP_ERR_INVALID_RESPONSE 0x108
#define ESP_ERR_INVALID_CRC 0x109
#define ESP_ERR_INVALID_VERSION 0x10A
#define ESP_ERR_INVALID_MAC 0x10B
#define ESP_ERR_NOT_FINISHED 0x10C
const char *esp_err_to_name(esp_err_t code);
// ESP-IDF's compiler pragmas around a known false-positive warning: nothing to do on the desktop
#define ESP_COMPILER_DIAGNOSTIC_PUSH_IGNORE(x)
#define ESP_COMPILER_DIAGNOSTIC_POP(x)
// ESP-IDF keeps these in esp_err.h; esp_check.h has the same macros
#define ESP_RETURN_ON_ERROR(x, tag, fmt, ...) \
do { \
esp_err_t err_rc_ = (x); \
if (err_rc_ != ESP_OK) { \
ESP_LOGE(tag, "%s(%d): " fmt, __func__, (int)err_rc_, ##__VA_ARGS__); \
return err_rc_; \
} \
} while (0)
#define ESP_RETURN_ON_FALSE(cond, err, tag, fmt, ...) \
do { \
if (!(cond)) { \
ESP_LOGE(tag, "%s(%d): " fmt, __func__, (int)(err), ##__VA_ARGS__); \
return (err); \
} \
} while (0)
#define ESP_ERROR_CHECK(x) \
do { \
esp_err_t err_rc_ = (x); \
if (err_rc_ != ESP_OK) { \
ESP_LOGE("check", "%s:%d: %s", __FILE__, __LINE__, esp_err_to_name(err_rc_)); \
abort(); \
} \
} while (0)
#define ESP_ERROR_CHECK_WITHOUT_ABORT(x) \
do { \
esp_err_t err_rc_ = (x); \
if (err_rc_ != ESP_OK) { \
ESP_LOGE("check", "%s:%d: %s", __FILE__, __LINE__, esp_err_to_name(err_rc_)); \
} \
} while (0)
+18
View File
@@ -0,0 +1,18 @@
/* Desktop port: no Wi-Fi events on the host, so the event loop is a stub. The base macros let the vendored
* esp_http_server declare its (unused) event base. */
#pragma once
#include <stddef.h>
#include <stdint.h>
#include "esp_err.h"
typedef const char *esp_event_base_t;
typedef void (*esp_event_handler_t)(void *handler_arg, esp_event_base_t base, int32_t id, void *event_data);
#define ESP_EVENT_DECLARE_BASE(id) extern const esp_event_base_t id
#define ESP_EVENT_DEFINE_BASE(id) const esp_event_base_t id = #id
#define ESP_EVENT_ANY_ID (-1)
#define portMAX_DELAY_EVENT 0xFFFFFFFFu
esp_err_t esp_event_loop_create_default(void);
esp_err_t esp_event_post(esp_event_base_t base, int32_t id, const void *data, size_t data_size, uint32_t ticks);
+3
View File
@@ -0,0 +1,3 @@
#pragma once
#include "esp_event.h"
+27
View File
@@ -0,0 +1,27 @@
/* Desktop port: there is one heap, so the capability flags are accepted and ignored */
#pragma once
#include <stddef.h>
#include <stdlib.h>
#define MALLOC_CAP_8BIT (1u << 2)
#define MALLOC_CAP_SPIRAM (1u << 10)
#define MALLOC_CAP_INTERNAL (1u << 11)
#define MALLOC_CAP_DEFAULT (1u << 12)
static inline void *heap_caps_malloc(size_t size, unsigned caps)
{
(void)caps;
return malloc(size);
}
static inline void *heap_caps_calloc(size_t n, size_t size, unsigned caps)
{
(void)caps;
return calloc(n, size);
}
static inline void heap_caps_free(void *p)
{
free(p);
}
+32
View File
@@ -0,0 +1,32 @@
/* Desktop port of ESP-IDF's logging: lines go to stderr with the same level letters and tags. */
#pragma once
#include <stdarg.h>
#include <stdint.h>
typedef enum {
ESP_LOG_NONE,
ESP_LOG_ERROR,
ESP_LOG_WARN,
ESP_LOG_INFO,
ESP_LOG_DEBUG,
ESP_LOG_VERBOSE
} esp_log_level_t;
typedef int (*vprintf_like_t)(const char *, va_list);
void esp_log_write(esp_log_level_t level, const char *tag, const char *fmt, ...) __attribute__((format(printf, 3, 4)));
void esp_log_level_set(const char *tag, esp_log_level_t level);
vprintf_like_t esp_log_set_vprintf(vprintf_like_t fn);
uint32_t esp_log_timestamp(void);
#define ESP_LOGE(tag, fmt, ...) esp_log_write(ESP_LOG_ERROR, tag, fmt, ##__VA_ARGS__)
#define ESP_LOGW(tag, fmt, ...) esp_log_write(ESP_LOG_WARN, tag, fmt, ##__VA_ARGS__)
#define ESP_LOGI(tag, fmt, ...) esp_log_write(ESP_LOG_INFO, tag, fmt, ##__VA_ARGS__)
#define ESP_LOGD(tag, fmt, ...) esp_log_write(ESP_LOG_DEBUG, tag, fmt, ##__VA_ARGS__)
#define ESP_LOGV(tag, fmt, ...) esp_log_write(ESP_LOG_VERBOSE, tag, fmt, ##__VA_ARGS__)
#define ESP_EARLY_LOGE(tag, fmt, ...) ESP_LOGE(tag, fmt, ##__VA_ARGS__)
#define ESP_EARLY_LOGW(tag, fmt, ...) ESP_LOGW(tag, fmt, ##__VA_ARGS__)
#define ESP_EARLY_LOGI(tag, fmt, ...) ESP_LOGI(tag, fmt, ##__VA_ARGS__)
#define ESP_EARLY_LOGD(tag, fmt, ...) ESP_LOGD(tag, fmt, ##__VA_ARGS__)
#define ESP_EARLY_LOGV(tag, fmt, ...) ESP_LOGV(tag, fmt, ##__VA_ARGS__)
+14
View File
@@ -0,0 +1,14 @@
/* Desktop port: the device MAC is the first real network interface's, so it is stable across runs */
#pragma once
#include <stdint.h>
#include "esp_err.h"
typedef enum {
ESP_MAC_WIFI_STA,
ESP_MAC_WIFI_SOFTAP,
ESP_MAC_BT,
ESP_MAC_ETH,
} esp_mac_type_t;
esp_err_t esp_read_mac(uint8_t mac[6], esp_mac_type_t type);
+24
View File
@@ -0,0 +1,24 @@
/* Desktop stand-in for ESP-IDF's esp_netif_ip_addr.h: the IPv4 address types the app uses. */
#pragma once
#include <stdint.h>
typedef struct {
uint32_t addr; /* network byte order, as the bytes sit in memory */
} esp_ip4_addr_t;
typedef enum {
ESP_IPADDR_TYPE_V4 = 0,
ESP_IPADDR_TYPE_V6 = 6,
ESP_IPADDR_TYPE_ANY = 46,
} esp_ip_addr_type_t;
typedef struct {
esp_ip_addr_type_t type;
union {
esp_ip4_addr_t ip4;
} u_addr;
} esp_ip_addr_t;
#define IPSTR "%d.%d.%d.%d"
#define IP2STR(p) ((const uint8_t *)(p))[0], ((const uint8_t *)(p))[1], ((const uint8_t *)(p))[2], ((const uint8_t *)(p))[3]
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
uint32_t esp_random(void);
void esp_fill_random(void *buf, size_t len);
+5
View File
@@ -0,0 +1,5 @@
#pragma once
#include <stdint.h>
void esp_rom_delay_us(uint32_t us);
+9
View File
@@ -0,0 +1,9 @@
#pragma once
#include <stdint.h>
#include "esp_err.h"
// Desktop: restart means exit, and systemd (or the user's shell) starts the program again
void esp_restart(void) __attribute__((noreturn));
uint32_t esp_get_free_heap_size(void);
uint32_t esp_get_minimum_free_heap_size(void);
+27
View File
@@ -0,0 +1,27 @@
/* Desktop port: esp_timer on the host clock (implemented in sim-controller/components/sim/sim_timer.c) */
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include "esp_err.h"
typedef void (*esp_timer_cb_t)(void *arg);
typedef enum { ESP_TIMER_TASK } esp_timer_dispatch_t;
typedef struct {
esp_timer_cb_t callback;
void *arg;
esp_timer_dispatch_t dispatch_method;
const char *name;
bool skip_unhandled_events;
} esp_timer_create_args_t;
struct esp_timer;
typedef struct esp_timer *esp_timer_handle_t;
int64_t esp_timer_get_time(void);
esp_err_t esp_timer_create(const esp_timer_create_args_t *args, esp_timer_handle_t *out);
esp_err_t esp_timer_start_once(esp_timer_handle_t t, uint64_t timeout_us);
esp_err_t esp_timer_start_periodic(esp_timer_handle_t t, uint64_t period);
esp_err_t esp_timer_stop(esp_timer_handle_t t);
bool esp_timer_is_active(esp_timer_handle_t t);
+22
View File
@@ -0,0 +1,22 @@
/* Desktop port: the FreeRTOS subset the firmware uses, on POSIX threads (desktop/port/src/freertos.c). */
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "portmacro.h"
typedef int BaseType_t;
typedef unsigned int UBaseType_t;
typedef uint32_t TickType_t;
#define pdTRUE ((BaseType_t)1)
#define pdFALSE ((BaseType_t)0)
#define pdPASS pdTRUE
#define pdFAIL pdFALSE
#define portMAX_DELAY ((TickType_t)0xFFFFFFFFUL)
#define pdMS_TO_TICKS(ms) ((TickType_t)(ms)) /* a tick is 1 ms */
#define portTICK_PERIOD_MS ((TickType_t)1)
#define configTICK_RATE_HZ 1000
#define portYIELD_FROM_ISR(x) ((void)(x))
@@ -0,0 +1,13 @@
#pragma once
#include "FreeRTOS.h"
typedef struct desk_events *EventGroupHandle_t;
typedef uint32_t EventBits_t;
EventGroupHandle_t xEventGroupCreate(void);
void vEventGroupDelete(EventGroupHandle_t g);
EventBits_t xEventGroupSetBits(EventGroupHandle_t g, EventBits_t bits);
EventBits_t xEventGroupClearBits(EventGroupHandle_t g, EventBits_t bits);
EventBits_t xEventGroupWaitBits(EventGroupHandle_t g, EventBits_t bits, BaseType_t clear_on_exit,
BaseType_t wait_all, TickType_t ticks);
+16
View File
@@ -0,0 +1,16 @@
/* Desktop port: critical sections are one process-wide recursive lock (desktop/port/src/freertos.c). */
#pragma once
#include <stdint.h>
typedef struct {
int unused;
} portMUX_TYPE;
#define portMUX_INITIALIZER_UNLOCKED {0}
void desk_critical_enter(void);
void desk_critical_exit(void);
#define portENTER_CRITICAL(mux) ((void)(mux), desk_critical_enter())
#define portEXIT_CRITICAL(mux) ((void)(mux), desk_critical_exit())
#define taskENTER_CRITICAL() desk_critical_enter()
#define taskEXIT_CRITICAL() desk_critical_exit()
+12
View File
@@ -0,0 +1,12 @@
#pragma once
#include "FreeRTOS.h"
typedef struct desk_queue *QueueHandle_t;
QueueHandle_t xQueueCreate(UBaseType_t length, UBaseType_t item_size);
void vQueueDelete(QueueHandle_t q);
BaseType_t xQueueSend(QueueHandle_t q, const void *item, TickType_t ticks);
BaseType_t xQueueSendToBack(QueueHandle_t q, const void *item, TickType_t ticks);
BaseType_t xQueueReceive(QueueHandle_t q, void *item, TickType_t ticks);
UBaseType_t uxQueueMessagesWaiting(QueueHandle_t q);
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include "FreeRTOS.h"
typedef struct desk_sem *SemaphoreHandle_t;
SemaphoreHandle_t xSemaphoreCreateMutex(void);
SemaphoreHandle_t xSemaphoreCreateRecursiveMutex(void);
SemaphoreHandle_t xSemaphoreCreateBinary(void);
SemaphoreHandle_t xSemaphoreCreateCounting(UBaseType_t max, UBaseType_t initial);
void vSemaphoreDelete(SemaphoreHandle_t s);
BaseType_t xSemaphoreTake(SemaphoreHandle_t s, TickType_t ticks);
BaseType_t xSemaphoreTakeRecursive(SemaphoreHandle_t s, TickType_t ticks);
BaseType_t xSemaphoreGive(SemaphoreHandle_t s);
BaseType_t xSemaphoreGiveRecursive(SemaphoreHandle_t s);
BaseType_t xSemaphoreGiveFromISR(SemaphoreHandle_t s, BaseType_t *woken);
#define xSemaphoreTakeFromISR(s, w) xSemaphoreTake((s), 0)
@@ -0,0 +1,12 @@
#pragma once
#include "FreeRTOS.h"
typedef struct desk_stream *StreamBufferHandle_t;
StreamBufferHandle_t xStreamBufferCreate(size_t size, size_t trigger_level);
void vStreamBufferDelete(StreamBufferHandle_t sb);
size_t xStreamBufferSend(StreamBufferHandle_t sb, const void *data, size_t len, TickType_t ticks);
size_t xStreamBufferReceive(StreamBufferHandle_t sb, void *data, size_t len, TickType_t ticks);
BaseType_t xStreamBufferReset(StreamBufferHandle_t sb);
size_t xStreamBufferBytesAvailable(StreamBufferHandle_t sb);
+15
View File
@@ -0,0 +1,15 @@
#pragma once
#include "FreeRTOS.h"
#define tskIDLE_PRIORITY ((UBaseType_t)0)
#define tskNO_AFFINITY 0x7FFFFFFF
typedef struct desk_task *TaskHandle_t;
typedef void (*TaskFunction_t)(void *);
BaseType_t xTaskCreate(TaskFunction_t fn, const char *name, uint32_t stack_words, void *arg, UBaseType_t prio,
TaskHandle_t *handle);
void vTaskDelete(TaskHandle_t task);
void vTaskDelay(TickType_t ticks);
TaskHandle_t xTaskGetCurrentTaskHandle(void);
+34
View File
@@ -0,0 +1,34 @@
/* Desktop stand-in for ESP-IDF's mdns component: the query API the controller uses (wifi_drv.c).
* The browser is in port/src/mdns_host.c. */
#pragma once
#include <stddef.h>
#include <stdint.h>
#include "esp_err.h"
#include "esp_netif_ip_addr.h"
typedef struct {
char *key;
char *value;
} mdns_txt_item_t;
typedef struct mdns_ip_addr_s {
esp_ip_addr_t addr;
struct mdns_ip_addr_s *next;
} mdns_ip_addr_t;
typedef struct mdns_result_s {
struct mdns_result_s *next;
char *instance_name;
char *hostname; /* without the .local suffix */
mdns_txt_item_t *txt;
size_t txt_count;
mdns_ip_addr_t *addr;
} mdns_result_t;
/* Browse for service._proto.local (for example "_http", "_tcp") for timeout_ms. Results are IN_ADDR answers
* with their TXT items; free them with mdns_query_results_free. ESP_ERR_NOT_FOUND when nothing answered. */
esp_err_t mdns_query_ptr(const char *service, const char *proto, uint32_t timeout_ms, size_t max_results,
mdns_result_t **results);
void mdns_query_results_free(mdns_result_t *results);
+37
View File
@@ -0,0 +1,37 @@
/* Desktop port of the httpd thread wrappers (replaces ESP-IDF's src/port/esp32/osal.h) */
#pragma once
#include <stdint.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_err.h"
#define OS_SUCCESS ESP_OK
#define OS_FAIL ESP_FAIL
typedef TaskHandle_t othread_t;
static inline int httpd_os_thread_create(othread_t *thread, const char *name, uint16_t stacksize, int prio,
void (*thread_routine)(void *arg), void *arg, BaseType_t core_id,
uint32_t caps)
{
(void)core_id;
(void)caps;
return xTaskCreate(thread_routine, name, stacksize, arg, (UBaseType_t)prio, thread) == pdPASS ? OS_SUCCESS : OS_FAIL;
}
// Only the calling task can delete itself
static inline void httpd_os_thread_delete(void)
{
vTaskDelete(NULL);
}
static inline void httpd_os_thread_sleep(int msecs)
{
vTaskDelay(msecs / portTICK_PERIOD_MS);
}
static inline othread_t httpd_os_thread_handle(void)
{
return xTaskGetCurrentTaskHandle();
}
+403
View File
@@ -0,0 +1,403 @@
/*
* Automatically generated file. DO NOT EDIT.
* Espressif IoT Development Framework (ESP-IDF) 6.1.0 Configuration Header
*/
#pragma once
#define CONFIG_SOC_EFUSE_SUPPORTED 1
#define CONFIG_SOC_EFUSE_KEY_PURPOSE_FIELD 1
#define CONFIG_SOC_CPU_CORES_NUM 1
#define CONFIG_SOC_GPIO_IN_RANGE_MAX 65535
#define CONFIG_SOC_GPIO_OUT_RANGE_MAX 65535
#define CONFIG_SOC_I2C_SUPPORT_SLAVE 1
#define CONFIG_SOC_I2C_SUPPORT_10BIT_ADDR 1
#define CONFIG_SOC_EFUSE_DIS_DOWNLOAD_ICACHE 1
#define CONFIG_SOC_EFUSE_DIS_DOWNLOAD_DCACHE 1
#define CONFIG_SOC_EFUSE_HARD_DIS_JTAG 1
#define CONFIG_SOC_EFUSE_DIS_USB_JTAG 1
#define CONFIG_SOC_EFUSE_SOFT_DIS_JTAG 1
#define CONFIG_SOC_EFUSE_DIS_DIRECT_BOOT 1
#define CONFIG_SOC_EFUSE_DIS_ICACHE 1
#define CONFIG_SOC_SECURE_BOOT_V2_RSA 1
#define CONFIG_SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS 3
#define CONFIG_SOC_EFUSE_REVOKE_BOOT_KEY_DIGESTS 1
#define CONFIG_SOC_SUPPORT_SECURE_BOOT_REVOKE_KEY 1
#define CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES 1
#define CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_OPTIONS 1
#define CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_128 1
#define CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_256 1
#define CONFIG_IDF_CMAKE 1
#define CONFIG_IDF_TOOLCHAIN ""
#define CONFIG_IDF_TARGET "linux"
#define CONFIG_IDF_INIT_VERSION "5.5.5"
#define CONFIG_IDF_TARGET_LINUX 1
#define CONFIG_IDF_FIRMWARE_CHIP_ID 0xFFFF
#define CONFIG_APP_BUILD_TYPE_RAM 1
#define CONFIG_APP_BUILD_GENERATE_BINARIES 1
#define CONFIG_APP_COMPILE_TIME_DATE 1
#define CONFIG_APP_RETRIEVE_LEN_ELF_SHA 9
#define CONFIG_ESP_ROM_USB_OTG_NUM -1
#define CONFIG_ESP_ROM_USB_SERIAL_DEVICE_NUM -1
#define CONFIG_ESP_ROM_HAS_ETS_PRINTF_BUG 1
#define CONFIG_ESP_ROM_HAS_OUTPUT_PUTC_FUNC 1
#define CONFIG_ESP_ROM_BOOTLOADER_OFFSET_FLASH 0x0
#define CONFIG_BOOT_ROM_LOG_ALWAYS_ON 1
#define CONFIG_W5500_SPI_HOST 1
#define CONFIG_W5500_SPI_CLOCK_MHZ 10
#define CONFIG_W5500_SCLK_GPIO 7
#define CONFIG_W5500_MISO_GPIO 8
#define CONFIG_W5500_MOSI_GPIO 9
#define CONFIG_W5500_CS_GPIO 2
#define CONFIG_W5500_INT_GPIO 3
#define CONFIG_W5500_POLL_PERIOD_MS 10
#define CONFIG_W5500_RST_GPIO 1
#define CONFIG_MIC_SCK_GPIO 5
#define CONFIG_MIC_WS_GPIO 6
#define CONFIG_MIC_SD_GPIO 43
#define CONFIG_MIC_STREAM_GAIN 16
#define CONFIG_BEAT_LED_GPIO 21
#define CONFIG_BEAT_LED_ACTIVE_LOW 1
#define CONFIG_BEAT_LED_PULSE_MS 60
#define CONFIG_BEAT_LED_DOWNBEAT_MS 200
#define CONFIG_BEAT_GATE_DBFS -75
#define CONFIG_BEAT_LEAD_MS 30
#define CONFIG_AP_BUTTON_GPIO 44
#define CONFIG_AP_HOLD_MS 1000
#define CONFIG_ESPNOW_CHANNEL 5
#define CONFIG_BEAT_TX_COPIES 2
#define CONFIG_BEAT_TX_GAP_US 2000
#define CONFIG_BEAT_TEST_GPIO -1
#define CONFIG_BULK_HOLDOFF_US 3000
#define CONFIG_COMPILER_OPTIMIZATION_DEBUG 1
#define CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE 1
#define CONFIG_COMPILER_ASSERT_NDEBUG_EVALUATE 1
#define CONFIG_COMPILER_FLOAT_LIB_FROM_GCCLIB 1
#define CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL 2
#define CONFIG_COMPILER_HIDE_PATHS_MACROS 1
#define CONFIG_COMPILER_STACK_CHECK_MODE_NONE 1
#define CONFIG_COMPILER_DISABLE_DEFAULT_ERRORS 1
#define CONFIG_COMPILER_RT_LIB_HOST 1
#define CONFIG_COMPILER_RT_LIB_NAME ""
#define CONFIG_ESP_ERR_TO_NAME_LOOKUP 1
#define CONFIG_ESP_EVENT_POST_FROM_ISR 1
#define CONFIG_ESP_EVENT_POST_FROM_ISR_SIZE 4
#define CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR 1
#define CONFIG_HTTPD_MAX_REQ_HDR_LEN 1024
#define CONFIG_HTTPD_MAX_URI_LEN 512
#define CONFIG_HTTPD_ERR_RESP_NO_DELAY 1
#define CONFIG_HTTPD_PURGE_BUF_LEN 32
#define CONFIG_HTTPD_WS_SUPPORT 1
#define CONFIG_HTTPD_ENABLE_EVENTS 1
#define CONFIG_HTTPD_SERVER_EVENT_POST_TIMEOUT 2000
#define CONFIG_HTTPD_WS_POST_HANDSHAKE_CB_SUPPORT 1
#define CONFIG_ESP_HW_SUPPORT_FUNC_IN_IRAM 1
#define CONFIG_ESP_REV_MIN_FULL 0
#define CONFIG_ESP_REV_MAX_FULL 999
#define CONFIG_ESP_EFUSE_BLOCK_REV_MIN_FULL 0
#define CONFIG_ESP_EFUSE_BLOCK_REV_MAX_FULL 999
#define CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND 1
#define CONFIG_ESP_SLEEP_GPIO_RESET_WORKAROUND 1
#define CONFIG_ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY 0
#define CONFIG_ESP_SLEEP_GPIO_ENABLE_INTERNAL_RESISTORS 1
#define CONFIG_RTC_CLK_FUNC_IN_IRAM 1
#define CONFIG_RTC_TIME_FUNC_IN_IRAM 1
#define CONFIG_ESP_PERIPH_CTRL_FUNC_IN_IRAM 1
#define CONFIG_ESP_REGI2C_CTRL_FUNC_IN_IRAM 1
#define CONFIG_ESP_BRINGUP_BYPASS_CPU_CLK_SETTING 1
#define CONFIG_ESP_BRINGUP_BYPASS_RANDOM_SETTING 1
#define CONFIG_ESP_INTR_IN_IRAM 1
#define CONFIG_ESP_ROM_PRINT_IN_IRAM 1
#define CONFIG_ESP_CONSOLE_UART_DEFAULT 1
#define CONFIG_ESP_CONSOLE_UART 1
#define CONFIG_ESP_CONSOLE_UART_NUM 0
#define CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM 0
#define CONFIG_ESP_CONSOLE_UART_BAUDRATE 115200
#define CONFIG_ESP_SYSTEM_IN_IRAM 1
#define CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT 1
#define CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS 0
#define CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE 1
#define CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE 32
#define CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE 2304
#define CONFIG_ESP_MAIN_TASK_STACK_SIZE 3584
#define CONFIG_ESP_MAIN_TASK_AFFINITY_CPU0 1
#define CONFIG_ESP_MAIN_TASK_AFFINITY 0x0
#define CONFIG_ESP_MINIMAL_SHARED_STACK_SIZE 2048
#define CONFIG_ESP_DEBUG_OCDAWARE 1
#define CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL_4 1
#define CONFIG_ESP_IPC_TASK_STACK_SIZE 1024
#define CONFIG_ESP_TIMER_IN_IRAM 1
#define CONFIG_ESP_TIMER_TASK_STACK_SIZE 3584
#define CONFIG_ESP_TIMER_INTERRUPT_LEVEL 1
#define CONFIG_ESP_TIMER_TASK_AFFINITY 0x0
#define CONFIG_ESP_TIMER_TASK_AFFINITY_CPU0 1
#define CONFIG_ESP_TIMER_ISR_AFFINITY_CPU0 1
#define CONFIG_ESP_TIMER_IMPL_SYSTIMER 1
#define CONFIG_FREERTOS_UNICORE 1
#define CONFIG_FREERTOS_HZ 1000
#define CONFIG_FREERTOS_OPTIMIZED_SCHEDULER 1
#define CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY 1
#define CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS 1
#define CONFIG_FREERTOS_IDLE_TASK_STACKSIZE 1536
#define CONFIG_FREERTOS_MAX_TASK_NAME_LEN 16
#define CONFIG_FREERTOS_USE_TIMERS 1
#define CONFIG_FREERTOS_TIMER_SERVICE_TASK_NAME "Tmr Svc"
#define CONFIG_FREERTOS_TIMER_TASK_NO_AFFINITY 1
#define CONFIG_FREERTOS_TIMER_SERVICE_TASK_CORE_AFFINITY 0x7FFFFFFF
#define CONFIG_FREERTOS_TIMER_TASK_PRIORITY 1
#define CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH 2053
#define CONFIG_FREERTOS_TIMER_QUEUE_LENGTH 10
#define CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE 0
#define CONFIG_FREERTOS_TASK_NOTIFICATION_ARRAY_ENTRIES 1
#define CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER 1
#define CONFIG_FREERTOS_TLSP_DELETION_CALLBACKS 1
#define CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER 1
#define CONFIG_FREERTOS_ISR_STACKSIZE 1536
#define CONFIG_FREERTOS_INTERRUPT_BACKTRACE 1
#define CONFIG_FREERTOS_TICK_SUPPORT_SYSTIMER 1
#define CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL1 1
#define CONFIG_FREERTOS_SYSTICK_USES_SYSTIMER 1
#define CONFIG_FREERTOS_IN_IRAM 1
#define CONFIG_FREERTOS_PORT 1
#define CONFIG_FREERTOS_NO_AFFINITY 0x7FFFFFFF
#define CONFIG_FREERTOS_SUPPORT_STATIC_ALLOCATION 1
#define CONFIG_FREERTOS_DEBUG_OCDAWARE 1
#define CONFIG_FREERTOS_NUMBER_OF_CORES 1
#define CONFIG_HAL_ASSERTION_EQUALS_SYSTEM 1
#define CONFIG_HAL_DEFAULT_ASSERTION_LEVEL 2
#define CONFIG_HAL_GPIO_USE_ROM_IMPL 1
#define CONFIG_HEAP_HAS_EXEC_HEAP 1
#define CONFIG_HEAP_POISONING_DISABLED 1
#define CONFIG_HEAP_TRACING_OFF 1
#define CONFIG_LOG_VERSION_1 1
#define CONFIG_LOG_VERSION 1
#define CONFIG_LOG_DEFAULT_LEVEL_INFO 1
#define CONFIG_LOG_DEFAULT_LEVEL 3
#define CONFIG_LOG_MAXIMUM_EQUALS_DEFAULT 1
#define CONFIG_LOG_MAXIMUM_LEVEL 3
#define CONFIG_LOG_DYNAMIC_LEVEL_CONTROL 1
#define CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_AND_LINKED_LIST 1
#define CONFIG_LOG_TAG_LEVEL_CACHE_BINARY_MIN_HEAP 1
#define CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_SIZE 31
#define CONFIG_LOG_TIMESTAMP_SOURCE_RTOS 1
#define CONFIG_LOG_MODE_TEXT_EN 1
#define CONFIG_LOG_MODE_TEXT 1
#define CONFIG_LOG_IN_IRAM 1
#define CONFIG_LWIP_LOCAL_HOSTNAME "espressif"
#define CONFIG_LWIP_TCPIP_TASK_PRIO 18
#define CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES 1
#define CONFIG_LWIP_TIMERS_ONDEMAND 1
#define CONFIG_LWIP_ND6 1
#define CONFIG_LWIP_MAX_SOCKETS 60
#define CONFIG_LWIP_SO_REUSE 1
#define CONFIG_LWIP_SO_REUSE_RXTOALL 1
#define CONFIG_LWIP_IP_DEFAULT_TTL 64
#define CONFIG_LWIP_IP4_FRAG 1
#define CONFIG_LWIP_IP6_FRAG 1
#define CONFIG_LWIP_IP_REASS_MAX_PBUFS 10
#define CONFIG_LWIP_IPV6_DUP_DETECT_ATTEMPTS 1
#define CONFIG_LWIP_ESP_GRATUITOUS_ARP 1
#define CONFIG_LWIP_GARP_TMR_INTERVAL 60
#define CONFIG_LWIP_ESP_MLDV6_REPORT 1
#define CONFIG_LWIP_MLDV6_TMR_INTERVAL 40
#define CONFIG_LWIP_TCPIP_RECVMBOX_SIZE 32
#define CONFIG_LWIP_DHCP_DOES_ARP_CHECK 1
#define CONFIG_LWIP_DHCP_DISABLE_VENDOR_CLASS_ID 1
#define CONFIG_LWIP_DHCP_OPTIONS_LEN 69
#define CONFIG_LWIP_NUM_NETIF_CLIENT_DATA 0
#define CONFIG_LWIP_DHCP_COARSE_TIMER_SECS 1
#define CONFIG_LWIP_DHCPS 1
#define CONFIG_LWIP_DHCPS_REPORT_CLIENT_HOSTNAME 1
#define CONFIG_LWIP_DHCPS_LEASE_UNIT 60
#define CONFIG_LWIP_DHCPS_MAX_STATION_NUM 8
#define CONFIG_LWIP_DHCPS_MAX_HOSTNAME_LEN 64
#define CONFIG_LWIP_DHCPS_STATIC_ENTRIES 1
#define CONFIG_LWIP_IPV4 1
#define CONFIG_LWIP_IPV6 1
#define CONFIG_LWIP_IPV6_NUM_ADDRESSES 3
#define CONFIG_LWIP_NETIF_LOOPBACK 1
#define CONFIG_LWIP_LOOPBACK_MAX_PBUFS 8
#define CONFIG_LWIP_MAX_ACTIVE_TCP 16
#define CONFIG_LWIP_MAX_LISTENING_TCP 16
#define CONFIG_LWIP_TCP_HIGH_SPEED_RETRANSMISSION 1
#define CONFIG_LWIP_TCP_MAXRTX 12
#define CONFIG_LWIP_TCP_SYNMAXRTX 12
#define CONFIG_LWIP_TCP_MSS 1440
#define CONFIG_LWIP_TCP_TMR_INTERVAL 250
#define CONFIG_LWIP_TCP_MSL 60000
#define CONFIG_LWIP_TCP_FIN_WAIT_TIMEOUT 20000
#define CONFIG_LWIP_TCP_SND_BUF_DEFAULT 5760
#define CONFIG_LWIP_TCP_WND_DEFAULT 5760
#define CONFIG_LWIP_TCP_RECVMBOX_SIZE 6
#define CONFIG_LWIP_TCP_ACCEPTMBOX_SIZE 6
#define CONFIG_LWIP_TCP_QUEUE_OOSEQ 1
#define CONFIG_LWIP_TCP_OOSEQ_TIMEOUT 6
#define CONFIG_LWIP_TCP_OOSEQ_MAX_PBUFS 4
#define CONFIG_LWIP_TCP_OVERSIZE_MSS 1
#define CONFIG_LWIP_TCP_RTO_TIME 1500
#define CONFIG_LWIP_MAX_UDP_PCBS 16
#define CONFIG_LWIP_UDP_RECVMBOX_SIZE 6
#define CONFIG_LWIP_CHECKSUM_CHECK_ICMP 1
#define CONFIG_LWIP_TCPIP_TASK_STACK_SIZE 3072
#define CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY 1
#define CONFIG_LWIP_TCPIP_TASK_AFFINITY 0x7FFFFFFF
#define CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE 3
#define CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS 5
#define CONFIG_LWIP_IPV6_ND6_NUM_PREFIXES 5
#define CONFIG_LWIP_IPV6_ND6_NUM_ROUTERS 3
#define CONFIG_LWIP_IPV6_ND6_NUM_DESTINATIONS 10
#define CONFIG_LWIP_ICMP 1
#define CONFIG_LWIP_MAX_RAW_PCBS 16
#define CONFIG_LWIP_SNTP_MAX_SERVERS 1
#define CONFIG_LWIP_SNTP_UPDATE_DELAY 3600000
#define CONFIG_LWIP_SNTP_STARTUP_DELAY 1
#define CONFIG_LWIP_SNTP_MAXIMUM_STARTUP_DELAY 5000
#define CONFIG_LWIP_DNS_MAX_HOST_IP 1
#define CONFIG_LWIP_DNS_MAX_SERVERS 3
#define CONFIG_LWIP_BRIDGEIF_MAX_PORTS 7
#define CONFIG_LWIP_ESP_LWIP_ASSERT 1
#define CONFIG_LWIP_HOOK_TCP_ISN_DEFAULT 1
#define CONFIG_LWIP_HOOK_IP6_ROUTE_NONE 1
#define CONFIG_LWIP_HOOK_ND6_GET_GW_NONE 1
#define CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_NONE 1
#define CONFIG_LWIP_HOOK_DHCP_EXTRA_OPTION_NONE 1
#define CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE 1
#define CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_NONE 1
#define CONFIG_LWIP_HOOK_IP6_INPUT_DEFAULT 1
#define CONFIG_MBEDTLS_VER_4_X_SUPPORT 1
#define CONFIG_MBEDTLS_COMPILER_OPTIMIZATION_SIZE 1
#define CONFIG_MBEDTLS_FS_IO 1
#define CONFIG_MBEDTLS_ERROR_STRINGS 1
#define CONFIG_MBEDTLS_VERSION_C 1
#define CONFIG_MBEDTLS_HAVE_TIME 1
#define CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC 1
#define CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN 1
#define CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN 16384
#define CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN 4096
#define CONFIG_MBEDTLS_SELF_TEST 1
#define CONFIG_MBEDTLS_X509_USE_C 1
#define CONFIG_MBEDTLS_PEM_PARSE_C 1
#define CONFIG_MBEDTLS_PEM_WRITE_C 1
#define CONFIG_MBEDTLS_PK_C 1
#define CONFIG_MBEDTLS_PK_PARSE_C 1
#define CONFIG_MBEDTLS_PK_WRITE_C 1
#define CONFIG_MBEDTLS_X509_CRL_PARSE_C 1
#define CONFIG_MBEDTLS_X509_CRT_PARSE_C 1
#define CONFIG_MBEDTLS_X509_CSR_PARSE_C 1
#define CONFIG_MBEDTLS_X509_RSASSA_PSS_SUPPORT 1
#define CONFIG_MBEDTLS_ASN1_PARSE_C 1
#define CONFIG_MBEDTLS_ASN1_WRITE_C 1
#define CONFIG_MBEDTLS_CERTIFICATE_BUNDLE 1
#define CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL 1
#define CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS 200
#define CONFIG_MBEDTLS_TLS_ENABLED 1
#define CONFIG_MBEDTLS_SSL_PROTO_TLS1_2 1
#define CONFIG_MBEDTLS_TLS_SERVER 1
#define CONFIG_MBEDTLS_TLS_CLIENT 1
#define CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT 1
#define CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE 1
#define CONFIG_MBEDTLS_SSL_CACHE_C 1
#define CONFIG_MBEDTLS_SSL_ALL_ALERT_MESSAGES 1
#define CONFIG_MBEDTLS_KEY_EXCHANGE_RSA 1
#define CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE 1
#define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA 1
#define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA 1
#define CONFIG_MBEDTLS_SSL_SERVER_NAME_INDICATION 1
#define CONFIG_MBEDTLS_SSL_ALPN 1
#define CONFIG_MBEDTLS_SSL_MAX_FRAGMENT_LENGTH 1
#define CONFIG_MBEDTLS_SSL_RENEGOTIATION 1
#define CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS 1
#define CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS 1
#define CONFIG_MBEDTLS_AES_C 1
#define CONFIG_MBEDTLS_CCM_C 1
#define CONFIG_MBEDTLS_CIPHER_MODE_CBC 1
#define CONFIG_MBEDTLS_CIPHER_MODE_CFB 1
#define CONFIG_MBEDTLS_CIPHER_MODE_CTR 1
#define CONFIG_MBEDTLS_CIPHER_MODE_OFB 1
#define CONFIG_MBEDTLS_CIPHER_MODE_XTS 1
#define CONFIG_MBEDTLS_GCM_C 1
#define CONFIG_MBEDTLS_AES_ROM_TABLES 1
#define CONFIG_MBEDTLS_RSA_C 1
#define CONFIG_MBEDTLS_ECP_C 1
#define CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED 1
#define CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED 1
#define CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED 1
#define CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED 1
#define CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED 1
#define CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED 1
#define CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED 1
#define CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED 1
#define CONFIG_MBEDTLS_ECP_NIST_OPTIM 1
#define CONFIG_MBEDTLS_ECDH_C 1
#define CONFIG_MBEDTLS_ECDSA_C 1
#define CONFIG_MBEDTLS_PK_PARSE_EC_EXTENDED 1
#define CONFIG_MBEDTLS_PK_PARSE_EC_COMPRESSED 1
#define CONFIG_MBEDTLS_ECDSA_DETERMINISTIC 1
#define CONFIG_MBEDTLS_MD_C 1
#define CONFIG_MBEDTLS_MD5_C 1
#define CONFIG_MBEDTLS_SHA1_C 1
#define CONFIG_MBEDTLS_SHA256_C 1
#define CONFIG_MBEDTLS_SHA384_C 1
#define CONFIG_MBEDTLS_SHA512_C 1
#define CONFIG_MBEDTLS_ROM_MD5 1
#define CONFIG_MBEDTLS_CTR_DRBG_C 1
#define CONFIG_MBEDTLS_HMAC_DRBG_C 1
#define CONFIG_MBEDTLS_BASE64_C 1
#define CONFIG_MBEDTLS_PKCS5_C 1
#define CONFIG_MBEDTLS_PKCS7_C 1
#define CONFIG_MBEDTLS_PKCS1_V15 1
#define CONFIG_MBEDTLS_PKCS1_V21 1
#define CONFIG_MMU_PAGE_SIZE_64KB 1
#define CONFIG_MMU_PAGE_MODE "64KB"
#define CONFIG_MMU_PAGE_SIZE 0x10000
#define CONFIG_SPI_FLASH_BROWNOUT_RESET_XMC 1
#define CONFIG_SPI_FLASH_BROWNOUT_RESET 1
#define CONFIG_SPI_FLASH_SUSPEND_TSUS_VAL_US 50
#define CONFIG_SPI_FLASH_PLACE_FUNCTIONS_IN_IRAM 1
#define CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED 1
#define CONFIG_SPI_FLASH_YIELD_DURING_ERASE 1
#define CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS 20
#define CONFIG_SPI_FLASH_ERASE_YIELD_TICKS 1
#define CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE 8192
#define CONFIG_SPI_FLASH_ENABLE_ENCRYPTED_READ_WRITE 1
#define CONFIG_CJSON_NESTING_LIMIT 1000
#define CONFIG_CJSON_CIRCULAR_LIMIT 10000
/* List of deprecated options */
#define CONFIG_APP_BUILD_TYPE_ELF_RAM CONFIG_APP_BUILD_TYPE_RAM
#define CONFIG_COMPILER_OPTIMIZATION_DEFAULT CONFIG_COMPILER_OPTIMIZATION_DEBUG
#define CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG CONFIG_COMPILER_OPTIMIZATION_DEBUG
#define CONFIG_CONSOLE_UART CONFIG_ESP_CONSOLE_UART
#define CONFIG_CONSOLE_UART_BAUDRATE CONFIG_ESP_CONSOLE_UART_BAUDRATE
#define CONFIG_CONSOLE_UART_DEFAULT CONFIG_ESP_CONSOLE_UART_DEFAULT
#define CONFIG_CONSOLE_UART_NUM CONFIG_ESP_CONSOLE_UART_NUM
#define CONFIG_ESP_GRATUITOUS_ARP CONFIG_LWIP_ESP_GRATUITOUS_ARP
#define CONFIG_GARP_TMR_INTERVAL CONFIG_LWIP_GARP_TMR_INTERVAL
#define CONFIG_IPC_TASK_STACK_SIZE CONFIG_ESP_IPC_TASK_STACK_SIZE
#define CONFIG_MAIN_TASK_STACK_SIZE CONFIG_ESP_MAIN_TASK_STACK_SIZE
#define CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE
#define CONFIG_OPTIMIZATION_ASSERTION_LEVEL CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL
#define CONFIG_OPTIMIZATION_LEVEL_DEBUG CONFIG_COMPILER_OPTIMIZATION_DEBUG
#define CONFIG_PERIPH_CTRL_FUNC_IN_IRAM CONFIG_ESP_PERIPH_CTRL_FUNC_IN_IRAM
#define CONFIG_POST_EVENTS_FROM_IRAM_ISR CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR
#define CONFIG_POST_EVENTS_FROM_ISR CONFIG_ESP_EVENT_POST_FROM_ISR
#define CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ALLOWED CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED
#define CONFIG_STACK_CHECK_NONE CONFIG_COMPILER_STACK_CHECK_MODE_NONE
#define CONFIG_SYSTEM_EVENT_QUEUE_SIZE CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE
#define CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE
#define CONFIG_TCPIP_RECVMBOX_SIZE CONFIG_LWIP_TCPIP_RECVMBOX_SIZE
#define CONFIG_TCPIP_TASK_AFFINITY CONFIG_LWIP_TCPIP_TASK_AFFINITY
#define CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY
#define CONFIG_TCPIP_TASK_STACK_SIZE CONFIG_LWIP_TCPIP_TASK_STACK_SIZE
#define CONFIG_TCP_MAXRTX CONFIG_LWIP_TCP_MAXRTX
#define CONFIG_TCP_MSL CONFIG_LWIP_TCP_MSL
#define CONFIG_TCP_MSS CONFIG_LWIP_TCP_MSS
#define CONFIG_TCP_OVERSIZE_MSS CONFIG_LWIP_TCP_OVERSIZE_MSS
#define CONFIG_TCP_QUEUE_OOSEQ CONFIG_LWIP_TCP_QUEUE_OOSEQ
#define CONFIG_TCP_RECVMBOX_SIZE CONFIG_LWIP_TCP_RECVMBOX_SIZE
#define CONFIG_TCP_SND_BUF_DEFAULT CONFIG_LWIP_TCP_SND_BUF_DEFAULT
#define CONFIG_TCP_SYNMAXRTX CONFIG_LWIP_TCP_SYNMAXRTX
#define CONFIG_TCP_WND_DEFAULT CONFIG_LWIP_TCP_WND_DEFAULT
#define CONFIG_TIMER_QUEUE_LENGTH CONFIG_FREERTOS_TIMER_QUEUE_LENGTH
#define CONFIG_TIMER_TASK_PRIORITY CONFIG_FREERTOS_TIMER_TASK_PRIORITY
#define CONFIG_TIMER_TASK_STACK_DEPTH CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH
#define CONFIG_TIMER_TASK_STACK_SIZE CONFIG_ESP_TIMER_TASK_STACK_SIZE
#define CONFIG_UDP_RECVMBOX_SIZE CONFIG_LWIP_UDP_RECVMBOX_SIZE
+91
View File
@@ -0,0 +1,91 @@
/* SHA-1 (FIPS 180-1) and base64 (RFC 4648) for the WebSocket handshake: no TLS library on the desktop */
#include "desktop_crypto.h"
#include <string.h>
static uint32_t rol(uint32_t v, int n)
{
return (v << n) | (v >> (32 - n));
}
static void sha1_block(uint32_t h[5], const uint8_t blk[64])
{
uint32_t w[80];
for (int i = 0; i < 16; i++) {
w[i] = ((uint32_t)blk[i * 4] << 24) | ((uint32_t)blk[i * 4 + 1] << 16) |
((uint32_t)blk[i * 4 + 2] << 8) | blk[i * 4 + 3];
}
for (int i = 16; i < 80; i++) {
w[i] = rol(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
}
uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4];
for (int i = 0; i < 80; i++) {
uint32_t f, k;
if (i < 20) { f = (b & c) | (~b & d); k = 0x5A827999; }
else if (i < 40) { f = b ^ c ^ d; k = 0x6ED9EBA1; }
else if (i < 60) { f = (b & c) | (b & d) | (c & d); k = 0x8F1BBCDC; }
else { f = b ^ c ^ d; k = 0xCA62C1D6; }
uint32_t t = rol(a, 5) + f + e + k + w[i];
e = d;
d = c;
c = rol(b, 30);
b = a;
a = t;
}
h[0] += a;
h[1] += b;
h[2] += c;
h[3] += d;
h[4] += e;
}
void desktop_sha1(const uint8_t *data, size_t len, uint8_t out[20])
{
uint32_t h[5] = { 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0 };
size_t i = 0;
for (; i + 64 <= len; i += 64) {
sha1_block(h, data + i);
}
// the tail: the rest, a 0x80 byte, zeros, and the message length in bits, in one or two blocks
uint8_t tail[128];
memset(tail, 0, sizeof(tail));
size_t rest = len - i;
memcpy(tail, data + i, rest);
tail[rest] = 0x80;
size_t tail_len = rest < 56 ? 64 : 128;
uint64_t bits = (uint64_t)len * 8;
for (int k = 0; k < 8; k++) {
tail[tail_len - 1 - k] = (uint8_t)(bits >> (8 * k));
}
sha1_block(h, tail);
if (tail_len == 128) {
sha1_block(h, tail + 64);
}
for (int k = 0; k < 5; k++) {
out[k * 4] = (uint8_t)(h[k] >> 24);
out[k * 4 + 1] = (uint8_t)(h[k] >> 16);
out[k * 4 + 2] = (uint8_t)(h[k] >> 8);
out[k * 4 + 3] = (uint8_t)h[k];
}
}
size_t desktop_base64_encode(char *out, size_t cap, const uint8_t *in, size_t n)
{
static const char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
size_t need = ((n + 2) / 3) * 4;
if (cap < need + 1) {
return 0;
}
size_t o = 0;
for (size_t i = 0; i < n; i += 3) {
uint32_t v = (uint32_t)in[i] << 16;
if (i + 1 < n) v |= (uint32_t)in[i + 1] << 8;
if (i + 2 < n) v |= in[i + 2];
out[o++] = tbl[(v >> 18) & 63];
out[o++] = tbl[(v >> 12) & 63];
out[o++] = (i + 1 < n) ? tbl[(v >> 6) & 63] : '=';
out[o++] = (i + 2 < n) ? tbl[v & 63] : '=';
}
out[o] = '\0';
return o;
}
+205
View File
@@ -0,0 +1,205 @@
/* Desktop port: the ESP-IDF runtime calls the firmware makes (logging, errors, random, MAC, restart) */
#define _GNU_SOURCE
#include <dirent.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/random.h>
#include <time.h>
#include <unistd.h>
#include "esp_app_desc.h"
#include "esp_err.h"
#include "esp_event.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"
#ifndef LED_APP_VERSION
#define LED_APP_VERSION "desktop"
#endif
static esp_log_level_t s_level = ESP_LOG_INFO;
static vprintf_like_t s_vprintf;
// LED_LOG_LEVEL=error|warn|info|debug|verbose (default info)
static void init_level(void)
{
static bool done;
if (done) return;
done = true;
const char *env = getenv("LED_LOG_LEVEL");
if (!env) return;
if (!strcmp(env, "error")) s_level = ESP_LOG_ERROR;
else if (!strcmp(env, "warn")) s_level = ESP_LOG_WARN;
else if (!strcmp(env, "debug")) s_level = ESP_LOG_DEBUG;
else if (!strcmp(env, "verbose")) s_level = ESP_LOG_VERBOSE;
else s_level = ESP_LOG_INFO;
}
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, ...)
{
init_level();
if (level > s_level) return;
static const char letters[] = " EWIDV";
char text[512];
va_list args;
va_start(args, fmt);
if (s_vprintf) {
// a hook (the bridge firmware's LOG frames) formats the line itself
s_vprintf(fmt, args);
va_end(args);
return;
}
vsnprintf(text, sizeof(text), fmt, args);
va_end(args);
fprintf(stderr, "%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_INVALID_RESPONSE: return "ESP_ERR_INVALID_RESPONSE";
case ESP_ERR_INVALID_CRC: return "ESP_ERR_INVALID_CRC";
case ESP_ERR_INVALID_VERSION: return "ESP_ERR_INVALID_VERSION";
case ESP_ERR_INVALID_MAC: return "ESP_ERR_INVALID_MAC";
case ESP_ERR_NOT_FINISHED: return "ESP_ERR_NOT_FINISHED";
default: return "ESP_ERR_UNKNOWN";
}
}
uint32_t esp_random(void)
{
uint32_t v = 0;
esp_fill_random(&v, sizeof(v));
return v;
}
void esp_fill_random(void *buf, size_t len)
{
uint8_t *p = buf;
while (len) {
ssize_t n = getrandom(p, len, 0);
if (n <= 0) {
// getrandom can be interrupted: fall back to the clock rather than returning zeros
for (size_t i = 0; i < len; i++) p[i] = (uint8_t)(esp_timer_get_time() >> (i % 8));
return;
}
p += n;
len -= (size_t)n;
}
}
void esp_rom_delay_us(uint32_t us)
{
usleep(us);
}
// The first real network interface's MAC (not loopback), so a driver keeps its identity across runs
esp_err_t esp_read_mac(uint8_t mac[6], esp_mac_type_t type)
{
(void)type;
DIR *d = opendir("/sys/class/net");
if (d) {
struct dirent *e;
char best[256] = "";
while ((e = readdir(d))) {
if (e->d_name[0] == '.' || !strcmp(e->d_name, "lo")) continue;
if (!best[0] || strcmp(e->d_name, best) < 0) snprintf(best, sizeof(best), "%s", e->d_name);
}
closedir(d);
if (best[0]) {
char path[320];
snprintf(path, sizeof(path), "/sys/class/net/%s/address", best);
FILE *f = fopen(path, "r");
if (f) {
unsigned v[6];
int n = fscanf(f, "%x:%x:%x:%x:%x:%x", &v[0], &v[1], &v[2], &v[3], &v[4], &v[5]);
fclose(f);
if (n == 6) {
for (int i = 0; i < 6; i++) mac[i] = (uint8_t)v[i];
return ESP_OK;
}
}
}
}
const uint8_t fallback[6] = { 0x02, 0x51, 0x4d, 0x00, 0x00, 0x01 }; // locally administered
memcpy(mac, fallback, 6);
return ESP_OK;
}
// On the desktop a restart is an exit: the service manager starts the program again
void esp_restart(void)
{
fprintf(stderr, "restart requested: exiting for the service manager to start us again\n");
fflush(stderr);
_exit(0);
}
uint32_t esp_get_free_heap_size(void)
{
return 64u * 1024u * 1024u; // the host heap is not limited the way the board's is
}
uint32_t esp_get_minimum_free_heap_size(void)
{
return esp_get_free_heap_size();
}
esp_err_t esp_event_loop_create_default(void)
{
return ESP_OK;
}
esp_err_t esp_event_post(esp_event_base_t base, int32_t id, const void *data, size_t data_size, uint32_t ticks)
{
(void)base;
(void)id;
(void)data;
(void)data_size;
(void)ticks;
return ESP_OK; // nobody listens on the desktop
}
const esp_app_desc_t *esp_app_get_description(void)
{
static esp_app_desc_t desc;
static bool init;
if (!init) {
init = true;
snprintf(desc.version, sizeof(desc.version), "%s", LED_APP_VERSION);
snprintf(desc.project_name, sizeof(desc.project_name), "led_controller_desktop");
snprintf(desc.idf_ver, sizeof(desc.idf_ver), "none");
}
return &desc;
}
+522
View File
@@ -0,0 +1,522 @@
/*
* Desktop port: the FreeRTOS calls the firmware makes, on POSIX threads.
* task a detached pthread; the handle is kept so a task can be named, and vTaskDelete(NULL) exits it
* queue a ring of fixed-size items, blocking send and receive with a deadline
* semaphore counting, binary and (recursive) mutex, with the owner and depth for recursive takes
* critical one process-wide recursive lock
* A tick is 1 ms. Timeouts are real: a blocked task sleeps in the kernel, so the others run.
*/
#define _GNU_SOURCE
#include <errno.h>
#include <pthread.h>
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "freertos/queue.h"
#include "freertos/semphr.h"
#include "freertos/stream_buffer.h"
#include "freertos/task.h"
static pthread_mutex_t s_crit = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
void desk_critical_enter(void)
{
pthread_mutex_lock(&s_crit);
}
void desk_critical_exit(void)
{
pthread_mutex_unlock(&s_crit);
}
// Absolute deadline for a timeout in ticks (ms), on the realtime clock
static void make_deadline(TickType_t ticks, struct timespec *dl)
{
clock_gettime(CLOCK_REALTIME, dl);
dl->tv_sec += ticks / 1000;
dl->tv_nsec += (long)(ticks % 1000) * 1000000L;
if (dl->tv_nsec >= 1000000000L) {
dl->tv_sec++;
dl->tv_nsec -= 1000000000L;
}
}
// Wait on c (with m held) until signalled. Returns 0 when signalled, ETIMEDOUT when the deadline passed.
// ticks == portMAX_DELAY waits without a deadline.
static int wait_on(pthread_cond_t *c, pthread_mutex_t *m, TickType_t ticks, const struct timespec *dl)
{
if (ticks == portMAX_DELAY) {
return pthread_cond_wait(c, m);
}
return pthread_cond_timedwait(c, m, dl);
}
/* ---- tasks ------------------------------------------------------------------------------------ */
struct desk_task {
pthread_t th;
char name[16];
TaskFunction_t fn;
void *arg;
};
static __thread struct desk_task *t_self;
static struct desk_task t_main = { .name = "main" };
static void *task_entry(void *p)
{
struct desk_task *t = p;
t_self = t;
t->fn(t->arg);
return NULL; // a FreeRTOS task must not return; here it ends its thread
}
BaseType_t xTaskCreate(TaskFunction_t fn, const char *name, uint32_t stack_words, void *arg, UBaseType_t prio,
TaskHandle_t *handle)
{
(void)prio; // scheduling is the host's
struct desk_task *t = calloc(1, sizeof(*t));
if (!t) {
return pdFAIL;
}
snprintf(t->name, sizeof(t->name), "%s", name ? name : "task");
t->fn = fn;
t->arg = arg;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
size_t want = (size_t)stack_words * 16; // firmware stacks are in words; give the host plenty
if (want < (size_t)512 * 1024) {
want = (size_t)512 * 1024;
}
pthread_attr_setstacksize(&attr, want);
int err = pthread_create(&t->th, &attr, task_entry, t);
pthread_attr_destroy(&attr);
if (err != 0) {
free(t);
return pdFAIL;
}
if (handle) {
*handle = t;
}
return pdPASS;
}
void vTaskDelete(TaskHandle_t task)
{
if (task == NULL || task == t_self) {
pthread_exit(NULL); // self-delete: the thread ends, the handle is not reused
}
pthread_cancel(task->th);
}
void vTaskDelay(TickType_t ticks)
{
if (ticks == 0) {
sched_yield();
return;
}
struct timespec ts = { .tv_sec = ticks / 1000, .tv_nsec = (long)(ticks % 1000) * 1000000L };
while (nanosleep(&ts, &ts) != 0 && errno == EINTR) {
}
}
TaskHandle_t xTaskGetCurrentTaskHandle(void)
{
if (!t_self) {
t_self = &t_main;
}
return t_self;
}
/* ---- queues ----------------------------------------------------------------------------------- */
struct desk_queue {
pthread_mutex_t m;
pthread_cond_t not_empty;
pthread_cond_t not_full;
uint8_t *buf;
UBaseType_t len;
UBaseType_t item;
UBaseType_t head;
UBaseType_t count;
};
QueueHandle_t xQueueCreate(UBaseType_t length, UBaseType_t item_size)
{
QueueHandle_t q = calloc(1, sizeof(*q));
if (!q) {
return NULL;
}
q->buf = calloc(length ? length : 1, item_size ? item_size : 1);
if (!q->buf) {
free(q);
return NULL;
}
q->len = length;
q->item = item_size;
pthread_mutex_init(&q->m, NULL);
pthread_cond_init(&q->not_empty, NULL);
pthread_cond_init(&q->not_full, NULL);
return q;
}
void vQueueDelete(QueueHandle_t q)
{
if (!q) return;
pthread_mutex_destroy(&q->m);
pthread_cond_destroy(&q->not_empty);
pthread_cond_destroy(&q->not_full);
free(q->buf);
free(q);
}
static BaseType_t queue_send(QueueHandle_t q, const void *item, TickType_t ticks)
{
struct timespec dl;
if (ticks != portMAX_DELAY) make_deadline(ticks, &dl);
pthread_mutex_lock(&q->m);
while (q->count == q->len) {
if (ticks == 0 || wait_on(&q->not_full, &q->m, ticks, &dl) != 0) {
pthread_mutex_unlock(&q->m);
return pdFAIL;
}
}
UBaseType_t slot = (q->head + q->count) % q->len;
memcpy(q->buf + (size_t)slot * q->item, item, q->item);
q->count++;
pthread_cond_signal(&q->not_empty);
pthread_mutex_unlock(&q->m);
return pdTRUE;
}
BaseType_t xQueueSend(QueueHandle_t q, const void *item, TickType_t ticks)
{
return queue_send(q, item, ticks);
}
BaseType_t xQueueSendToBack(QueueHandle_t q, const void *item, TickType_t ticks)
{
return queue_send(q, item, ticks);
}
BaseType_t xQueueReceive(QueueHandle_t q, void *item, TickType_t ticks)
{
struct timespec dl;
if (ticks != portMAX_DELAY) make_deadline(ticks, &dl);
pthread_mutex_lock(&q->m);
while (q->count == 0) {
if (ticks == 0 || wait_on(&q->not_empty, &q->m, ticks, &dl) != 0) {
pthread_mutex_unlock(&q->m);
return pdFAIL;
}
}
memcpy(item, q->buf + (size_t)q->head * q->item, q->item);
q->head = (q->head + 1) % q->len;
q->count--;
pthread_cond_signal(&q->not_full);
pthread_mutex_unlock(&q->m);
return pdTRUE;
}
UBaseType_t uxQueueMessagesWaiting(QueueHandle_t q)
{
pthread_mutex_lock(&q->m);
UBaseType_t n = q->count;
pthread_mutex_unlock(&q->m);
return n;
}
/* ---- semaphores ------------------------------------------------------------------------------- */
struct desk_sem {
pthread_mutex_t m;
pthread_cond_t c;
UBaseType_t count; // free "tokens"
UBaseType_t max;
int recursive; // the owning task may take it again
pthread_t owner;
UBaseType_t depth; // takes by the owner not yet given back
};
static SemaphoreHandle_t sem_new(UBaseType_t init, UBaseType_t max, int recursive)
{
SemaphoreHandle_t s = calloc(1, sizeof(*s));
if (!s) return NULL;
s->count = init;
s->max = max;
s->recursive = recursive;
pthread_mutex_init(&s->m, NULL);
pthread_cond_init(&s->c, NULL);
return s;
}
SemaphoreHandle_t xSemaphoreCreateMutex(void)
{
return sem_new(1, 1, 0);
}
SemaphoreHandle_t xSemaphoreCreateRecursiveMutex(void)
{
return sem_new(1, 1, 1);
}
SemaphoreHandle_t xSemaphoreCreateBinary(void)
{
return sem_new(0, 1, 0);
}
SemaphoreHandle_t xSemaphoreCreateCounting(UBaseType_t max, UBaseType_t initial)
{
return sem_new(initial, max, 0);
}
void vSemaphoreDelete(SemaphoreHandle_t s)
{
if (!s) return;
pthread_mutex_destroy(&s->m);
pthread_cond_destroy(&s->c);
free(s);
}
static BaseType_t sem_take(SemaphoreHandle_t s, TickType_t ticks)
{
pthread_t me = pthread_self();
struct timespec dl;
if (ticks != portMAX_DELAY) make_deadline(ticks, &dl);
pthread_mutex_lock(&s->m);
if (s->recursive && s->depth > 0 && pthread_equal(s->owner, me)) {
s->depth++;
pthread_mutex_unlock(&s->m);
return pdTRUE;
}
while (s->count == 0) {
if (ticks == 0 || wait_on(&s->c, &s->m, ticks, &dl) != 0) {
pthread_mutex_unlock(&s->m);
return pdFAIL;
}
}
s->count--;
s->owner = me;
s->depth = 1;
pthread_mutex_unlock(&s->m);
return pdTRUE;
}
static BaseType_t sem_give(SemaphoreHandle_t s)
{
pthread_mutex_lock(&s->m);
if (s->recursive && s->depth > 1 && pthread_equal(s->owner, pthread_self())) {
s->depth--;
pthread_mutex_unlock(&s->m);
return pdTRUE;
}
if (s->count >= s->max) {
pthread_mutex_unlock(&s->m);
return pdFAIL;
}
s->count++;
s->depth = 0;
pthread_cond_signal(&s->c);
pthread_mutex_unlock(&s->m);
return pdTRUE;
}
BaseType_t xSemaphoreTake(SemaphoreHandle_t s, TickType_t ticks)
{
return sem_take(s, ticks);
}
BaseType_t xSemaphoreTakeRecursive(SemaphoreHandle_t s, TickType_t ticks)
{
return sem_take(s, ticks);
}
BaseType_t xSemaphoreGive(SemaphoreHandle_t s)
{
return sem_give(s);
}
BaseType_t xSemaphoreGiveRecursive(SemaphoreHandle_t s)
{
return sem_give(s);
}
BaseType_t xSemaphoreGiveFromISR(SemaphoreHandle_t s, BaseType_t *woken)
{
if (woken) *woken = pdFALSE;
return sem_give(s);
}
/* ---- stream buffers --------------------------------------------------------------------------- */
struct desk_stream {
pthread_mutex_t m;
pthread_cond_t not_empty;
pthread_cond_t not_full;
uint8_t *buf;
size_t cap;
size_t head;
size_t count;
};
StreamBufferHandle_t xStreamBufferCreate(size_t size, size_t trigger_level)
{
(void)trigger_level;
StreamBufferHandle_t sb = calloc(1, sizeof(*sb));
if (!sb) return NULL;
sb->buf = malloc(size ? size : 1);
if (!sb->buf) {
free(sb);
return NULL;
}
sb->cap = size;
pthread_mutex_init(&sb->m, NULL);
pthread_cond_init(&sb->not_empty, NULL);
pthread_cond_init(&sb->not_full, NULL);
return sb;
}
void vStreamBufferDelete(StreamBufferHandle_t sb)
{
if (!sb) return;
pthread_mutex_destroy(&sb->m);
pthread_cond_destroy(&sb->not_empty);
pthread_cond_destroy(&sb->not_full);
free(sb->buf);
free(sb);
}
size_t xStreamBufferSend(StreamBufferHandle_t sb, const void *data, size_t len, TickType_t ticks)
{
struct timespec dl;
if (ticks != portMAX_DELAY) make_deadline(ticks, &dl);
pthread_mutex_lock(&sb->m);
while (sb->count == sb->cap) {
if (ticks == 0 || wait_on(&sb->not_full, &sb->m, ticks, &dl) != 0) {
pthread_mutex_unlock(&sb->m);
return 0;
}
}
size_t room = sb->cap - sb->count;
size_t n = len < room ? len : room;
for (size_t i = 0; i < n; i++) {
sb->buf[(sb->head + sb->count + i) % sb->cap] = ((const uint8_t *)data)[i];
}
sb->count += n;
pthread_cond_signal(&sb->not_empty);
pthread_mutex_unlock(&sb->m);
return n;
}
size_t xStreamBufferReceive(StreamBufferHandle_t sb, void *data, size_t len, TickType_t ticks)
{
struct timespec dl;
if (ticks != portMAX_DELAY) make_deadline(ticks, &dl);
pthread_mutex_lock(&sb->m);
while (sb->count == 0) {
if (ticks == 0 || wait_on(&sb->not_empty, &sb->m, ticks, &dl) != 0) {
pthread_mutex_unlock(&sb->m);
return 0;
}
}
size_t n = len < sb->count ? len : sb->count;
for (size_t i = 0; i < n; i++) {
((uint8_t *)data)[i] = sb->buf[(sb->head + i) % sb->cap];
}
sb->head = (sb->head + n) % sb->cap;
sb->count -= n;
pthread_cond_signal(&sb->not_full);
pthread_mutex_unlock(&sb->m);
return n;
}
BaseType_t xStreamBufferReset(StreamBufferHandle_t sb)
{
pthread_mutex_lock(&sb->m);
sb->head = 0;
sb->count = 0;
pthread_cond_broadcast(&sb->not_full);
pthread_mutex_unlock(&sb->m);
return pdTRUE;
}
size_t xStreamBufferBytesAvailable(StreamBufferHandle_t sb)
{
pthread_mutex_lock(&sb->m);
size_t n = sb->count;
pthread_mutex_unlock(&sb->m);
return n;
}
/* ---- event groups ----------------------------------------------------------------------------- */
struct desk_events {
pthread_mutex_t m;
pthread_cond_t c;
EventBits_t bits;
};
EventGroupHandle_t xEventGroupCreate(void)
{
EventGroupHandle_t g = calloc(1, sizeof(*g));
if (!g) return NULL;
pthread_mutex_init(&g->m, NULL);
pthread_cond_init(&g->c, NULL);
return g;
}
void vEventGroupDelete(EventGroupHandle_t g)
{
if (!g) return;
pthread_mutex_destroy(&g->m);
pthread_cond_destroy(&g->c);
free(g);
}
EventBits_t xEventGroupSetBits(EventGroupHandle_t g, EventBits_t bits)
{
pthread_mutex_lock(&g->m);
g->bits |= bits;
EventBits_t now = g->bits;
pthread_cond_broadcast(&g->c);
pthread_mutex_unlock(&g->m);
return now;
}
EventBits_t xEventGroupClearBits(EventGroupHandle_t g, EventBits_t bits)
{
pthread_mutex_lock(&g->m);
g->bits &= ~bits;
EventBits_t now = g->bits;
pthread_mutex_unlock(&g->m);
return now;
}
EventBits_t xEventGroupWaitBits(EventGroupHandle_t g, EventBits_t bits, BaseType_t clear_on_exit,
BaseType_t wait_all, TickType_t ticks)
{
struct timespec dl;
if (ticks != portMAX_DELAY) make_deadline(ticks, &dl);
pthread_mutex_lock(&g->m);
for (;;) {
EventBits_t got = g->bits & bits;
bool ok = wait_all ? got == bits : got != 0;
if (ok) {
if (clear_on_exit) {
g->bits &= ~bits;
}
pthread_mutex_unlock(&g->m);
return got;
}
if (ticks == 0 || wait_on(&g->c, &g->m, ticks, &dl) != 0) {
EventBits_t now = g->bits;
pthread_mutex_unlock(&g->m);
return now;
}
}
}
+371
View File
@@ -0,0 +1,371 @@
/*
* Minimal mDNS browser for the desktop build, behind the ESP-IDF mdns API used by wifi_drv.c.
* It sends a PTR query for _service._proto.local from an ephemeral port, so responders answer unicast,
* then reads PTR, SRV, TXT and A answers until the timeout. Only the parts of RFC 6762/1035 these need.
*/
#include <arpa/inet.h>
#include <stdbool.h>
#include <netinet/in.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
#include "esp_err.h"
#include "esp_log.h"
#include "mdns.h"
#define MDNS_PORT 5353
#define MAX_RECS 64
#define NAME_MAX_LEN 256
typedef struct { char name[NAME_MAX_LEN]; char target[NAME_MAX_LEN]; } srv_rec_t;
typedef struct { char name[NAME_MAX_LEN]; char items[8][80]; int n; } txt_rec_t;
typedef struct { char name[NAME_MAX_LEN]; uint8_t ip[4]; } a_rec_t;
typedef struct { char name[NAME_MAX_LEN]; } ptr_rec_t;
typedef struct {
ptr_rec_t ptr[MAX_RECS];
int nptr;
srv_rec_t srv[MAX_RECS];
int nsrv;
txt_rec_t txt[MAX_RECS];
int ntxt;
a_rec_t a[MAX_RECS];
int na;
} browse_t;
static uint16_t rd16(const uint8_t *p)
{
return (uint16_t)((p[0] << 8) | p[1]);
}
/* Decode a (possibly compressed) name at off. Sets *next to the byte after the name in place. */
static bool decode_name(const uint8_t *m, size_t len, size_t off, char *out, size_t cap, size_t *next)
{
size_t o = off, n = 0, after = 0;
bool jumped = false;
int hops = 0;
out[0] = '\0';
for (;;) {
if (o >= len || ++hops > 64) {
return false;
}
uint8_t l = m[o];
if ((l & 0xC0) == 0xC0) {
if (o + 1 >= len) {
return false;
}
if (!jumped) {
after = o + 2;
}
jumped = true;
o = (size_t)(((l & 0x3F) << 8) | m[o + 1]);
continue;
}
if (l == 0) {
o++;
break;
}
if (l > 63 || o + 1 + l > len) {
return false;
}
if (n) {
if (n + 1 >= cap) {
return false;
}
out[n++] = '.';
}
if (n + l >= cap) {
return false;
}
memcpy(out + n, m + o + 1, l);
n += l;
o += 1 + l;
}
out[n] = '\0';
if (next) {
*next = jumped ? after : o;
}
return true;
}
static void add_ptr(browse_t *b, const char *name)
{
if (b->nptr < MAX_RECS) {
snprintf(b->ptr[b->nptr++].name, NAME_MAX_LEN, "%s", name);
}
}
static void handle_rr(browse_t *b, const uint8_t *m, size_t len, const char *name, uint16_t type, size_t rd, uint16_t rdlen)
{
char tmp[NAME_MAX_LEN];
switch (type) {
case 12: /* PTR */
if (decode_name(m, len, rd, tmp, sizeof(tmp), NULL)) {
if (!strcmp(name, "_http._tcp.local") && b->nptr < MAX_RECS) {
add_ptr(b, tmp);
}
}
break;
case 33: /* SRV: priority, weight, port, target */
if (rdlen > 6 && b->nsrv < MAX_RECS && decode_name(m, len, rd + 6, tmp, sizeof(tmp), NULL)) {
srv_rec_t *s = &b->srv[b->nsrv++];
snprintf(s->name, NAME_MAX_LEN, "%s", name);
snprintf(s->target, NAME_MAX_LEN, "%s", tmp);
}
break;
case 16: { /* TXT: length-prefixed strings */
if (b->ntxt >= MAX_RECS) {
break;
}
txt_rec_t *t = &b->txt[b->ntxt];
snprintf(t->name, NAME_MAX_LEN, "%s", name);
t->n = 0;
size_t p = rd, end = rd + rdlen;
while (p < end && t->n < 8) {
size_t l = m[p];
if (p + 1 + l > end) {
break;
}
size_t copy = l < sizeof(t->items[0]) - 1 ? l : sizeof(t->items[0]) - 1;
memcpy(t->items[t->n], m + p + 1, copy);
t->items[t->n][copy] = '\0';
t->n++;
p += 1 + l;
}
b->ntxt++;
break;
}
case 1: /* A */
if (rdlen == 4 && b->na < MAX_RECS) {
a_rec_t *a = &b->a[b->na++];
snprintf(a->name, NAME_MAX_LEN, "%s", name);
memcpy(a->ip, m + rd, 4);
}
break;
default:
break;
}
}
static void parse_packet(browse_t *b, const uint8_t *m, size_t len)
{
if (len < 12) {
return;
}
uint16_t qd = rd16(m + 4), an = rd16(m + 6), ns = rd16(m + 8), ar = rd16(m + 10);
size_t o = 12;
char name[NAME_MAX_LEN];
for (int i = 0; i < qd; i++) {
if (!decode_name(m, len, o, name, sizeof(name), &o) || o + 4 > len) {
return;
}
o += 4;
}
int total = an + ns + ar;
for (int i = 0; i < total; i++) {
if (!decode_name(m, len, o, name, sizeof(name), &o) || o + 10 > len) {
return;
}
uint16_t type = rd16(m + o);
uint16_t rdlen = rd16(m + o + 8);
size_t rd = o + 10;
if (rd + rdlen > len) {
return;
}
handle_rr(b, m, len, name, type, rd, rdlen);
o = rd + rdlen;
}
}
/* DNS query for PTR _service._proto.local */
static size_t build_query(uint8_t *buf, size_t cap, const char *name)
{
size_t o = 12;
memset(buf, 0, 12);
buf[5] = 1; /* one question */
const char *p = name;
while (*p) {
const char *dot = strchr(p, '.');
size_t l = dot ? (size_t)(dot - p) : strlen(p);
if (l == 0 || l > 63 || o + 1 + l + 6 > cap) {
return 0;
}
buf[o++] = (uint8_t)l;
memcpy(buf + o, p, l);
o += l;
if (!dot) {
break;
}
p = dot + 1;
}
buf[o++] = 0;
buf[o++] = 0; /* PTR */
buf[o++] = 12;
buf[o++] = 0; /* IN, not unicast-response */
buf[o++] = 1;
return o;
}
static char *mdns_dup(const char *s)
{
return strdup(s ? s : "");
}
esp_err_t mdns_query_ptr(const char *service, const char *proto, uint32_t timeout_ms, size_t max_results,
mdns_result_t **results)
{
*results = NULL;
char qname[160];
snprintf(qname, sizeof(qname), "%s.%s.local", service, proto); /* the caller gives "_http", "_tcp" */
/* the query is not sent to the app's own names, so the search is only for the given service */
uint8_t q[256];
size_t qlen = build_query(q, sizeof(q), qname);
if (!qlen) {
return ESP_ERR_INVALID_ARG;
}
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) {
return ESP_FAIL;
}
struct sockaddr_in dst = { .sin_family = AF_INET, .sin_port = htons(MDNS_PORT) };
inet_pton(AF_INET, "224.0.0.251", &dst.sin_addr);
browse_t *b = calloc(1, sizeof(*b));
if (!b) {
close(fd);
return ESP_ERR_NO_MEM;
}
struct timespec t0;
clock_gettime(CLOCK_MONOTONIC, &t0);
int64_t start = (int64_t)t0.tv_sec * 1000 + t0.tv_nsec / 1000000;
int64_t sent_at = -1000000;
uint8_t pkt[2048];
for (;;) {
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
int64_t now = (int64_t)t.tv_sec * 1000 + t.tv_nsec / 1000000;
int64_t elapsed = now - start;
if (elapsed >= (int64_t)timeout_ms) {
break;
}
if (now - sent_at >= (int64_t)timeout_ms / 2 + 1 && elapsed < (int64_t)timeout_ms / 2) {
sendto(fd, q, qlen, 0, (struct sockaddr *)&dst, sizeof(dst)); /* a second query, for lost packets */
sent_at = now;
} else if (sent_at < 0) {
sendto(fd, q, qlen, 0, (struct sockaddr *)&dst, sizeof(dst));
sent_at = now;
}
struct pollfd pfd = { .fd = fd, .events = POLLIN };
int wait = (int)((int64_t)timeout_ms - elapsed);
if (wait > 100) {
wait = 100;
}
if (poll(&pfd, 1, wait) > 0 && (pfd.revents & POLLIN)) {
ssize_t n = recv(fd, pkt, sizeof(pkt), 0);
if (n > 0) {
parse_packet(b, pkt, (size_t)n);
}
}
}
close(fd);
/* Build one result per instance that has a PTR, an SRV and an A record for its target */
mdns_result_t *head = NULL, **tail = &head;
size_t count = 0;
for (int i = 0; i < b->nptr && count < max_results; i++) {
const char *inst = b->ptr[i].name;
const srv_rec_t *srv = NULL;
for (int k = 0; k < b->nsrv && !srv; k++) {
if (!strcmp(b->srv[k].name, inst)) {
srv = &b->srv[k];
}
}
if (!srv) {
continue;
}
mdns_result_t *r = calloc(1, sizeof(*r));
if (!r) {
break;
}
r->instance_name = mdns_dup(inst);
/* the SRV target is host.local: the hostname without the suffix */
char host[NAME_MAX_LEN];
snprintf(host, sizeof(host), "%s", srv->target);
size_t hl = strlen(host);
if (hl > 6 && !strcmp(host + hl - 6, ".local")) {
host[hl - 6] = '\0';
}
r->hostname = mdns_dup(host);
for (int k = 0; k < b->ntxt; k++) {
if (!strcmp(b->txt[k].name, inst)) {
r->txt_count = (size_t)b->txt[k].n;
r->txt = calloc(r->txt_count ? r->txt_count : 1, sizeof(mdns_txt_item_t));
for (size_t j = 0; r->txt && j < r->txt_count; j++) {
char *eq = strchr(b->txt[k].items[j], '=');
if (eq) {
*eq = '\0';
r->txt[j].key = mdns_dup(b->txt[k].items[j]);
r->txt[j].value = mdns_dup(eq + 1);
*eq = '=';
} else {
r->txt[j].key = mdns_dup(b->txt[k].items[j]);
r->txt[j].value = mdns_dup("");
}
}
break;
}
}
mdns_ip_addr_t **at = &r->addr;
for (int k = 0; k < b->na; k++) {
if (!strcmp(b->a[k].name, srv->target)) {
mdns_ip_addr_t *a = calloc(1, sizeof(*a));
if (a) {
a->addr.type = ESP_IPADDR_TYPE_V4;
memcpy(&a->addr.u_addr.ip4.addr, b->a[k].ip, 4);
*at = a;
at = &a->next;
}
}
}
*tail = r;
tail = &r->next;
count++;
}
free(b);
if (!head) {
return ESP_ERR_NOT_FOUND;
}
*results = head;
return ESP_OK;
}
void mdns_query_results_free(mdns_result_t *results)
{
while (results) {
mdns_result_t *next = results->next;
free(results->instance_name);
free(results->hostname);
for (size_t i = 0; i < results->txt_count && results->txt; i++) {
free(results->txt[i].key);
free(results->txt[i].value);
}
free(results->txt);
mdns_ip_addr_t *a = results->addr;
while (a) {
mdns_ip_addr_t *an = a->next;
free(a);
a = an;
}
free(results);
results = next;
}
}
+440
View File
@@ -0,0 +1,440 @@
/*
* Desktop microphone: captures from a Linux ALSA capture device (a USB mic such as the Blue Snowball) and feeds
* the same level meter, beat detector and /audio.wav stream as the board's I2S mic.c. Only the devices named by
* mic_list_devices() are selectable: plughw:CARD=... capture devices, which convert to 16 kHz mono for us.
*/
#include <alsa/asoundlib.h>
#include <errno.h>
#include <math.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "cJSON.h"
#include "esp_log.h"
#include "beat.h"
#include "bridge.h"
#include "mic.h"
#define BRIDGE_DEVICE "bridge:mic" // the microphone of a bridge board (bridge/, ESP32-S3), see bridge_serial.h
#define BLOCK_FRAMES (MIC_SAMPLE_RATE / 50) // 20 ms per read
#define LEVEL_BLOCKS 5 // 100 ms per level reading
#define RING_SAMPLES MIC_SAMPLE_RATE // 1 s of 16-bit mono for the stream
#define DBFS_FLOOR -120.0f
#define SPL_OFFSET 120.0f // same nominal offset as the I2S mic; not calibrated for USB mics
#define DEVICE_NAME_MAX 128
static const char *TAG = "mic_alsa";
static pthread_mutex_t s_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t s_cond = PTHREAD_COND_INITIALIZER;
static bool s_open; // capture wanted (set by mic_open / mic_close)
static uint64_t s_gen; // bumped by mic_open so the capture thread reopens the device
static char s_device[DEVICE_NAME_MAX] = "default";
static mic_level_t s_level = { DBFS_FLOOR, DBFS_FLOOR, DBFS_FLOOR + SPL_OFFSET };
static char s_error[160]; // why the last open failed, "" when it works
static bool s_streaming;
static int16_t s_ring[RING_SAMPLES];
static size_t s_ring_fill; // samples waiting in the ring, oldest first from s_ring_head
static size_t s_ring_head;
static float to_dbfs(float x)
{
return x > 0.0f ? fmaxf(20.0f * log10f(x), DBFS_FLOOR) : DBFS_FLOOR;
}
// Called with s_lock held: a block of 16-bit samples for the stream listener, dropped when it is full
static void ring_push_locked(const int16_t *pcm, size_t n)
{
if (!s_streaming || s_ring_fill + n > RING_SAMPLES) {
return;
}
for (size_t i = 0; i < n; i++) {
s_ring[(s_ring_head + s_ring_fill + i) % RING_SAMPLES] = pcm[i];
}
s_ring_fill += n;
pthread_cond_broadcast(&s_cond);
}
static void reset_level_locked(void)
{
s_level.rms_dbfs = DBFS_FLOOR;
s_level.peak_dbfs = DBFS_FLOOR;
s_level.spl_db = DBFS_FLOOR + SPL_OFFSET;
}
// Per-stream state of the level meter and high-pass filter, see process_block
typedef struct {
float hp_in, hp_out;
double sum_sq;
float peak;
size_t frames;
size_t blocks;
} proc_t;
// One block of 16-bit mono at MIC_SAMPLE_RATE: level meter, beat detector and the stream listener's copy
static void process_block(proc_t *p, const int16_t *raw, size_t frames)
{
static float filtered[BLOCK_FRAMES];
static int16_t pcm_out[BLOCK_FRAMES];
const float gain = CONFIG_MIC_STREAM_GAIN;
for (size_t i = 0; i < frames; i++) {
float x = (float)raw[i] / 32768.0f;
float y = x - p->hp_in + 0.995f * p->hp_out; // one-pole high-pass, as in mic.c
p->hp_in = x;
p->hp_out = y;
filtered[i] = y;
p->sum_sq += (double)y * y;
p->peak = fmaxf(p->peak, fabsf(y));
pcm_out[i] = (int16_t)fmaxf(fminf(y * gain * 32767.0f, 32767.0f), -32768.0f);
}
p->frames += frames;
beat_feed(filtered, frames);
pthread_mutex_lock(&s_lock);
ring_push_locked(pcm_out, frames);
if (++p->blocks >= LEVEL_BLOCKS) {
s_level.rms_dbfs = to_dbfs(sqrtf((float)(p->sum_sq / p->frames)));
s_level.peak_dbfs = to_dbfs(p->peak);
s_level.spl_db = s_level.rms_dbfs + SPL_OFFSET;
p->sum_sq = 0.0;
p->peak = 0.0f;
p->frames = p->blocks = 0;
}
pthread_mutex_unlock(&s_lock);
}
// Read blocks from one open device until it fails or mic_open/mic_close changes the request
static void capture_loop(snd_pcm_t *pcm, uint64_t gen)
{
static int16_t raw[BLOCK_FRAMES];
proc_t p = { 0 };
for (;;) {
pthread_mutex_lock(&s_lock);
bool keep = s_open && s_gen == gen;
pthread_mutex_unlock(&s_lock);
if (!keep) {
return;
}
snd_pcm_sframes_t n = snd_pcm_readi(pcm, raw, BLOCK_FRAMES);
if (n < 0) {
if (snd_pcm_recover(pcm, (int)n, 1) < 0) {
ESP_LOGW(TAG, "capture read failed: %s", snd_strerror((int)n));
return;
}
continue;
}
process_block(&p, raw, (size_t)n);
}
}
// Audio from a bridge board: the bridge's link task calls this while the bridge device is selected
static proc_t s_bridge_proc;
static void on_bridge_audio(const int16_t *pcm, size_t n)
{
pthread_mutex_lock(&s_lock);
bool mine = s_open && !strcmp(s_device, BRIDGE_DEVICE);
pthread_mutex_unlock(&s_lock);
if (mine) {
process_block(&s_bridge_proc, pcm, n);
}
}
static void *capture_thread(void *arg)
{
(void)arg;
for (;;) {
pthread_mutex_lock(&s_lock);
bool open = s_open;
uint64_t gen = s_gen;
char name[DEVICE_NAME_MAX];
memcpy(name, s_device, sizeof(name));
pthread_mutex_unlock(&s_lock);
if (!open || !strcmp(name, BRIDGE_DEVICE)) {
usleep(100 * 1000); // idle: a bridge device is fed by on_bridge_audio
continue;
}
// "pulse:<source>" is a PipeWire/PulseAudio source, opened through the pulse ALSA plugin
const char *pcm_name = name;
if (!strncmp(name, "pulse:", 6)) {
setenv("PULSE_SOURCE", name + 6, 1);
pcm_name = "pulse";
}
snd_pcm_t *pcm = NULL;
int err = snd_pcm_open(&pcm, pcm_name, SND_PCM_STREAM_CAPTURE, 0);
if (err < 0) {
ESP_LOGW(TAG, "cannot open %s: %s", name, snd_strerror(err));
pthread_mutex_lock(&s_lock);
snprintf(s_error, sizeof(s_error), "Cannot open %s: %s", name, snd_strerror(err));
pthread_mutex_unlock(&s_lock);
sleep(1);
continue;
}
err = snd_pcm_set_params(pcm, SND_PCM_FORMAT_S16_LE, SND_PCM_ACCESS_RW_INTERLEAVED, 1,
MIC_SAMPLE_RATE, 1, 500000);
if (err < 0) {
ESP_LOGW(TAG, "cannot set %s to %d Hz mono: %s", name, MIC_SAMPLE_RATE, snd_strerror(err));
snd_pcm_close(pcm);
sleep(1);
continue;
}
ESP_LOGI(TAG, "capturing from %s", name);
pthread_mutex_lock(&s_lock);
s_error[0] = '\0';
pthread_mutex_unlock(&s_lock);
capture_loop(pcm, gen);
snd_pcm_drop(pcm);
snd_pcm_close(pcm);
pthread_mutex_lock(&s_lock);
if (s_gen == gen) {
reset_level_locked();
}
pthread_mutex_unlock(&s_lock);
}
return NULL;
}
esp_err_t mic_start(void)
{
esp_err_t err = beat_start(MIC_SAMPLE_RATE);
if (err != ESP_OK) {
return err;
}
bridge_set_audio_cb(on_bridge_audio);
pthread_t t;
if (pthread_create(&t, NULL, capture_thread, NULL) != 0) {
return ESP_ERR_NO_MEM;
}
pthread_detach(t);
return ESP_OK;
}
void mic_get_level(mic_level_t *out)
{
pthread_mutex_lock(&s_lock);
*out = s_level;
pthread_mutex_unlock(&s_lock);
}
esp_err_t mic_open(const char *device)
{
if (!device || !device[0]) {
device = "default";
}
if (strlen(device) >= DEVICE_NAME_MAX) {
return ESP_ERR_INVALID_ARG;
}
bool bridge = !strcmp(device, BRIDGE_DEVICE);
if (bridge && !bridge_has_mic()) {
pthread_mutex_lock(&s_lock);
snprintf(s_error, sizeof(s_error), "No bridge board with a microphone is connected");
pthread_mutex_unlock(&s_lock);
return ESP_ERR_NOT_FOUND;
}
if (bridge && bridge_mic(true) != ESP_OK) {
pthread_mutex_lock(&s_lock);
snprintf(s_error, sizeof(s_error), "The bridge microphone did not start");
pthread_mutex_unlock(&s_lock);
return ESP_ERR_NOT_SUPPORTED;
}
pthread_mutex_lock(&s_lock);
strcpy(s_device, device);
s_open = true;
s_gen++;
s_ring_fill = 0;
s_bridge_proc = (proc_t){ 0 };
s_error[0] = '\0';
reset_level_locked();
pthread_mutex_unlock(&s_lock);
return ESP_OK;
}
void mic_close(void)
{
pthread_mutex_lock(&s_lock);
s_open = false;
s_gen++;
reset_level_locked();
pthread_mutex_unlock(&s_lock);
bridge_mic(false); // harmless when no bridge is attached
}
void mic_error(char *out, size_t len)
{
pthread_mutex_lock(&s_lock);
snprintf(out, len, "%s", s_error);
pthread_mutex_unlock(&s_lock);
}
bool mic_is_open(void)
{
pthread_mutex_lock(&s_lock);
bool open = s_open;
pthread_mutex_unlock(&s_lock);
return open;
}
esp_err_t mic_stream_open(void)
{
pthread_mutex_lock(&s_lock);
if (s_streaming) {
pthread_mutex_unlock(&s_lock);
return ESP_ERR_INVALID_STATE;
}
s_streaming = true;
s_ring_fill = 0;
pthread_mutex_unlock(&s_lock);
return ESP_OK;
}
size_t mic_stream_read(void *buf, size_t len, TickType_t timeout)
{
struct timespec deadline;
clock_gettime(CLOCK_REALTIME, &deadline);
long ms = (long)(timeout * portTICK_PERIOD_MS);
deadline.tv_sec += ms / 1000;
deadline.tv_nsec += (ms % 1000) * 1000000L;
if (deadline.tv_nsec >= 1000000000L) {
deadline.tv_sec++;
deadline.tv_nsec -= 1000000000L;
}
pthread_mutex_lock(&s_lock);
while (s_ring_fill == 0) {
if (pthread_cond_timedwait(&s_cond, &s_lock, &deadline) == ETIMEDOUT) {
break;
}
}
size_t want = len / sizeof(int16_t);
size_t n = want < s_ring_fill ? want : s_ring_fill;
uint8_t *out = buf;
for (size_t i = 0; i < n; i++) {
int16_t v = s_ring[(s_ring_head + i) % RING_SAMPLES];
out[2 * i] = (uint8_t)(v & 0xFF);
out[2 * i + 1] = (uint8_t)((uint16_t)v >> 8);
}
s_ring_head = (s_ring_head + n) % RING_SAMPLES;
s_ring_fill -= n;
pthread_mutex_unlock(&s_lock);
return n * sizeof(int16_t);
}
void mic_stream_close(void)
{
pthread_mutex_lock(&s_lock);
s_streaming = false;
pthread_mutex_unlock(&s_lock);
}
// Input sources the desktop can record from. On a PipeWire/PulseAudio desktop the USB mic is shared through the
// sound server, so it is listed as a pulse source (pactl). Otherwise the raw ALSA plughw:CARD=... inputs are used.
static int list_alsa_devices(mic_device_t *out, int max);
static int list_pulse_sources(mic_device_t *out, int max)
{
FILE *p = popen("pactl -f json list sources 2>/dev/null", "r");
if (!p) {
return 0;
}
char *buf = NULL;
size_t cap = 0, len = 0;
for (;;) {
if (len + 4096 > cap) {
cap = cap ? cap * 2 : 8192;
buf = realloc(buf, cap);
if (!buf) {
pclose(p);
return 0;
}
}
size_t got = fread(buf + len, 1, cap - len - 1, p);
if (got == 0) {
break;
}
len += got;
}
pclose(p);
buf[len] = '\0';
int count = 0;
cJSON *list = cJSON_Parse(buf);
free(buf);
for (const cJSON *src = list ? list->child : NULL; src && count < max; src = src->next) {
const cJSON *name = cJSON_GetObjectItem(src, "name");
const cJSON *desc = cJSON_GetObjectItem(src, "description");
if (!cJSON_IsString(name) || strncmp(name->valuestring, "alsa_input.", 11) != 0) {
continue; // monitors and other sources
}
mic_device_t *d = &out[count];
if (strlen(name->valuestring) + 6 >= sizeof(d->id)) {
continue;
}
snprintf(d->id, sizeof(d->id), "pulse:%s", name->valuestring);
snprintf(d->name, sizeof(d->name), "%s", cJSON_IsString(desc) ? desc->valuestring : name->valuestring);
snprintf(d->label, sizeof(d->label), "%s", name->valuestring);
count++;
}
cJSON_Delete(list);
return count;
}
int mic_list_devices(mic_device_t *out, int max)
{
int count = 0;
if (bridge_has_mic() && max > 0) {
mic_device_t *d = &out[count++];
snprintf(d->id, sizeof(d->id), "%s", BRIDGE_DEVICE);
snprintf(d->name, sizeof(d->name), "I2S microphone on the bridge board");
snprintf(d->label, sizeof(d->label), "%s", BRIDGE_DEVICE);
}
int more = list_pulse_sources(out + count, max - count);
if (more == 0) {
more = list_alsa_devices(out + count, max - count);
}
return count + more;
}
// Raw ALSA capture devices: each plughw:CARD=... input (ALSA converts to our format)
static int list_alsa_devices(mic_device_t *out, int max)
{
void **hints = NULL;
int count = 0;
if (snd_device_name_hint(-1, "pcm", &hints) < 0) {
return 0;
}
for (void **h = hints; *h && count < max; h++) {
char *name = snd_device_name_get_hint(*h, "NAME");
char *desc = snd_device_name_get_hint(*h, "DESC");
char *ioid = snd_device_name_get_hint(*h, "IOID");
bool input = !ioid || !strcmp(ioid, "Input");
if (name && input && !strncmp(name, "plughw:CARD=", 12) && strlen(name) < sizeof(out[count].id)) {
mic_device_t *d = &out[count];
strcpy(d->id, name);
strcpy(d->label, name);
// The description runs over several lines; the first is the device's name
const char *first = desc ? desc : name;
size_t len = strcspn(first, "\n");
if (len >= sizeof(d->name)) {
len = sizeof(d->name) - 1;
}
memcpy(d->name, first, len);
d->name[len] = '\0';
count++;
}
free(name);
free(desc);
free(ioid);
}
snd_device_name_free_hint(hints);
return count;
}
+21
View File
@@ -0,0 +1,21 @@
/* The simulated rig's page and drivers (www_dist/sim.pack, built by tools/build_sim_web.sh), embedded in the
* program and served at /sim/ (sim-controller/components/sim/sim_rig.c). SIM_PACK is the path, set by CMake. */
#include <stdint.h>
#ifndef SIM_PACK
#error "SIM_PACK must name www_dist/sim.pack"
#endif
#define STR2(x) #x
#define STR(x) STR2(x)
__asm__(
".section .rodata\n"
".balign 16\n"
".global _binary_sim_pack_start\n"
"_binary_sim_pack_start:\n"
".incbin " STR(SIM_PACK) "\n"
".global _binary_sim_pack_end\n"
"_binary_sim_pack_end:\n"
".byte 0\n"
".previous\n");
+21
View File
@@ -0,0 +1,21 @@
/* The gzipped web UI (www_dist/www.pack, built by tools/build_web.sh), embedded in the program: the same
* symbols the firmware's web.c reads on the board. WWW_PACK is the file's path, set by CMake. */
#include <stdint.h>
#ifndef WWW_PACK
#error "WWW_PACK must name www_dist/www.pack"
#endif
#define STR2(x) #x
#define STR(x) STR2(x)
__asm__(
".section .rodata\n"
".balign 16\n"
".global _binary_www_pack_start\n"
"_binary_www_pack_start:\n"
".incbin " STR(WWW_PACK) "\n"
".global _binary_www_pack_end\n"
"_binary_www_pack_end:\n"
".byte 0\n"
".previous\n");
+20
View File
@@ -0,0 +1,20 @@
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+3206
View File
File diff suppressed because it is too large. Load diff
+306
View File
@@ -0,0 +1,306 @@
/*
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef cJSON__h
#define cJSON__h
#ifdef __cplusplus
extern "C"
{
#endif
#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32))
#define __WINDOWS__
#endif
#ifdef __WINDOWS__
/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options:
CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols
CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default)
CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol
For *nix builds that support visibility attribute, you can define similar behavior by
setting default visibility to hidden by adding
-fvisibility=hidden (for gcc)
or
-xldscope=hidden (for sun cc)
to CFLAGS
then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does
*/
#define CJSON_CDECL __cdecl
#define CJSON_STDCALL __stdcall
/* export symbols by default, this is necessary for copy pasting the C and header file */
#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_EXPORT_SYMBOLS
#endif
#if defined(CJSON_HIDE_SYMBOLS)
#define CJSON_PUBLIC(type) type CJSON_STDCALL
#elif defined(CJSON_EXPORT_SYMBOLS)
#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL
#elif defined(CJSON_IMPORT_SYMBOLS)
#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL
#endif
#else /* !__WINDOWS__ */
#define CJSON_CDECL
#define CJSON_STDCALL
#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY)
#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type
#else
#define CJSON_PUBLIC(type) type
#endif
#endif
/* project version */
#define CJSON_VERSION_MAJOR 1
#define CJSON_VERSION_MINOR 7
#define CJSON_VERSION_PATCH 19
#include <stddef.h>
/* cJSON Types: */
#define cJSON_Invalid (0)
#define cJSON_False (1 << 0)
#define cJSON_True (1 << 1)
#define cJSON_NULL (1 << 2)
#define cJSON_Number (1 << 3)
#define cJSON_String (1 << 4)
#define cJSON_Array (1 << 5)
#define cJSON_Object (1 << 6)
#define cJSON_Raw (1 << 7) /* raw json */
#define cJSON_IsReference 256
#define cJSON_StringIsConst 512
/* The cJSON structure: */
typedef struct cJSON
{
/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON *next;
struct cJSON *prev;
/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
struct cJSON *child;
/* The type of the item, as above. */
int type;
/* The item's string, if type==cJSON_String and type == cJSON_Raw */
char *valuestring;
/* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
int valueint;
/* The item's number, if type==cJSON_Number */
double valuedouble;
/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
char *string;
} cJSON;
typedef struct cJSON_Hooks
{
/* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */
void *(CJSON_CDECL *malloc_fn)(size_t sz);
void (CJSON_CDECL *free_fn)(void *ptr);
} cJSON_Hooks;
typedef int cJSON_bool;
/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them.
* This is to prevent stack overflows. */
#ifndef CJSON_NESTING_LIMIT
#define CJSON_NESTING_LIMIT 1000
#endif
/* Limits the length of circular references can be before cJSON rejects to parse them.
* This is to prevent stack overflows. */
#ifndef CJSON_CIRCULAR_LIMIT
#define CJSON_CIRCULAR_LIMIT 10000
#endif
/* returns the version of cJSON as a string */
CJSON_PUBLIC(const char*) cJSON_Version(void);
/* Supply malloc, realloc and free functions to cJSON */
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks);
/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length);
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated);
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated);
/* Render a cJSON entity to text for transfer/storage. */
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. */
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);
/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt);
/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */
/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format);
/* Delete a cJSON entity and all subentities. */
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item);
/* Returns the number of items in an array (or object). */
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
/* Get item "string" from object. Case insensitive. */
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string);
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);
/* Check item type and return its value */
CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item);
CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item);
/* These functions check the type of an item */
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item);
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item);
/* These calls create a cJSON item of the appropriate type. */
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
/* raw json */
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);
/* Create a string where valuestring references a string so
* it will not be freed by cJSON_Delete */
CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string);
/* Create an object/array that only references it's elements so
* they will not be freed by cJSON_Delete */
CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child);
CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);
/* These utilities create an Array of count items.
* The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count);
/* Append item to the specified array/object. */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object.
* WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before
* writing to `item->string` */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
/* Remove/Detach items from Arrays/Objects. */
CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);
/* Update array items. */
CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement);
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem);
/* Duplicate a cJSON item */
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse);
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
* need to be released. With recurse!=0, it will duplicate any children connected to the item.
* The item->next and ->prev pointers are always zero on return from Duplicate. */
/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal.
* case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */
CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive);
/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings.
* The input pointer json cannot point to a read-only address area, such as a string constant,
* but should point to a readable and writable address area. */
CJSON_PUBLIC(void) cJSON_Minify(char *json);
/* Helper functions for creating and adding items to an object at the same time.
* They return the added item or NULL on failure. */
CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean);
CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);
CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);
CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw);
CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name);
CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name);
/* When assigning an integer value, it needs to be propagated to valuedouble too. */
#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
/* helper for the cJSON_SetNumberValue macro */
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))
/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */
CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring);
/* If the object is not a boolean type this does nothing and returns cJSON_Invalid else it returns the new type*/
#define cJSON_SetBoolValue(object, boolValue) ( \
(object != NULL && ((object)->type & (cJSON_False|cJSON_True))) ? \
(object)->type=((object)->type &(~(cJSON_False|cJSON_True)))|((boolValue)?cJSON_True:cJSON_False) : \
cJSON_Invalid\
)
/* Macro for iterating over an array or object */
#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)
/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */
CJSON_PUBLIC(void *) cJSON_malloc(size_t size);
CJSON_PUBLIC(void) cJSON_free(void *object);
#ifdef __cplusplus
}
#endif
#endif
File diff suppressed because it is too large. Load diff
+609
View File
@@ -0,0 +1,609 @@
/*
* SPDX-FileCopyrightText: 2018-2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef _HTTPD_PRIV_H_
#define _HTTPD_PRIV_H_
#include <stdbool.h>
#include <sys/socket.h>
#include <sys/param.h>
#include <netinet/in.h>
#include <esp_log.h>
#include <esp_err.h>
#include <esp_http_server.h>
#include "osal.h"
#include "freertos/semphr.h"
#include "sdkconfig.h"
#ifdef __cplusplus
extern "C" {
#endif
#if CONFIG_LIBC_NEWLIB_NANO_FORMAT
#define NEWLIB_NANO_COMPAT_FORMAT PRIu32
#define NEWLIB_NANO_COMPAT_CAST(size_t_var) (uint32_t)size_t_var
#else
#define NEWLIB_NANO_COMPAT_FORMAT "zu"
#define NEWLIB_NANO_COMPAT_CAST(size_t_var) size_t_var
#endif
/* Size of request data block/chunk (not to be confused with chunked encoded data)
* that is received and parsed in one turn of the parsing process. */
#define PARSER_BLOCK_SIZE 128
/* Formats a log string to prepend context function name */
#define LOG_FMT(x) "%s: " x, __func__
/**
* @brief Control message data structure for internal use. Sent to control socket.
*/
struct httpd_ctrl_data {
enum httpd_ctrl_msg {
HTTPD_CTRL_SHUTDOWN,
HTTPD_CTRL_WORK,
HTTPD_CTRL_MAX,
} hc_msg;
httpd_work_fn_t hc_work;
void *hc_work_arg;
};
/**
* @brief Thread related data for internal use
*/
struct thread_data {
othread_t handle; /*!< Handle to thread/task */
enum {
THREAD_IDLE = 0,
THREAD_RUNNING,
THREAD_STOPPING,
THREAD_STOPPED,
} status; /*!< State of the thread */
};
/**
* @brief A database of all the open sockets in the system.
*/
struct sock_db {
int fd; /*!< The file descriptor for this socket */
void *ctx; /*!< A custom context for this socket */
bool ignore_sess_ctx_changes; /*!< Flag indicating if session context changes should be ignored */
void *transport_ctx; /*!< A custom 'transport' context for this socket, to be used by send/recv/pending */
httpd_handle_t handle; /*!< Server handle */
httpd_free_ctx_fn_t free_ctx; /*!< Function for freeing the context */
httpd_free_ctx_fn_t free_transport_ctx; /*!< Function for freeing the 'transport' context */
httpd_send_func_t send_fn; /*!< Send function for this socket */
httpd_recv_func_t recv_fn; /*!< Receive function for this socket */
httpd_pending_func_t pending_fn; /*!< Pending function for this socket */
uint64_t lru_counter; /*!< LRU Counter indicating when the socket was last used */
bool lru_socket; /*!< Flag indicating LRU socket */
char pending_data[PARSER_BLOCK_SIZE]; /*!< Buffer for pending data to be received */
size_t pending_len; /*!< Length of pending data to be received */
bool for_async_req; /*!< If true, the socket will not be LRU purged */
#ifdef CONFIG_HTTPD_WS_SUPPORT
bool ws_handshake_done; /*!< True if it has done WebSocket handshake (if this socket is a valid WS) */
bool ws_close; /*!< Set to true to close the socket later (when WS Close frame received) */
esp_err_t (*ws_handler)(httpd_req_t *r); /*!< WebSocket handler, leave to null if it's not WebSocket */
bool ws_control_frames; /*!< WebSocket flag indicating that control frames should be passed to user handlers */
void *ws_user_ctx; /*!< Pointer to user context data which will be available to handler for websocket*/
#endif
};
/**
* @brief Auxiliary data structure for use during reception and processing
* of requests and temporarily keeping responses
*/
struct httpd_req_aux {
struct sock_db *sd; /*!< Pointer to socket database */
char *scratch; /*!< Temporary buffer for our operations (1 byte extra for null termination) */
size_t scratch_size_limit; /*!< Scratch buffer size limit (By default this value is set to CONFIG_HTTPD_MAX_REQ_HDR_LEN, overwrite is possible) */
size_t scratch_cur_size; /*!< Scratch buffer cur size (By default this value is set to CONFIG_HTTPD_MAX_URI_LEN, overwrite is possible) */
size_t max_req_hdr_len; /*!< Header buffer size limit */
size_t max_uri_len; /*!< URI buffer size limit */
size_t remaining_len; /*!< Amount of data remaining to be fetched */
char *status; /*!< HTTP response's status code */
char *content_type; /*!< HTTP response's content type */
bool first_chunk_sent; /*!< Used to indicate if first chunk sent */
unsigned req_hdrs_count; /*!< Count of total headers in request packet */
unsigned resp_hdrs_count; /*!< Count of additional headers in response packet */
struct resp_hdr {
const char *field;
const char *value;
} *resp_hdrs; /*!< Additional headers in response packet */
struct http_parser_url url_parse_res; /*!< URL parsing result, used for retrieving URL elements */
#ifdef CONFIG_HTTPD_WS_SUPPORT
bool ws_handshake_detect; /*!< WebSocket handshake detection flag */
httpd_ws_type_t ws_type; /*!< WebSocket frame type */
bool ws_final; /*!< WebSocket FIN bit (final frame or not) */
uint8_t mask_key[4]; /*!< WebSocket mask key for this payload */
#endif
};
/**
* @brief Server data for each instance. This is exposed publicly as
* httpd_handle_t but internal structure/members are kept private.
*/
struct httpd_data {
httpd_config_t config; /*!< HTTPD server configuration */
int listen_fd; /*!< Server listener FD */
int ctrl_fd; /*!< Ctrl message receiver FD */
SemaphoreHandle_t ctrl_sock_semaphore; /*!< Ctrl mbox slot reservation (sized to LWIP_UDP_RECVMBOX_SIZE) */
int msg_fd; /*!< Ctrl message sender FD */
struct thread_data hd_td; /*!< Information for the HTTPD thread */
struct sock_db *hd_sd; /*!< The socket database */
int hd_sd_active_count; /*!< The number of the active sockets */
httpd_uri_t **hd_calls; /*!< Registered URI handlers */
struct httpd_req hd_req; /*!< The current HTTPD request */
struct httpd_req_aux hd_req_aux; /*!< Additional data about the HTTPD request kept unexposed */
uint64_t lru_counter; /*!< LRU counter */
esp_http_server_event_id_t http_server_state; /*!< HTTPD server state */
/* Array of registered error handler functions */
httpd_err_handler_func_t *err_handler_fns;
};
/**
* @brief Options for receiving HTTP request data
*/
typedef enum {
HTTPD_RECV_OPT_NONE = 0,
HTTPD_RECV_OPT_HALT_AFTER_PENDING = 1, /*!< Halt immediately after receiving from pending buffer */
HTTPD_RECV_OPT_BLOCKING = 2, /*!< Receive blocking (don't return partial length) */
} httpd_recv_opt_t;
/******************* Group : Session Management ********************/
/** @name Session Management
* Functions related to HTTP session management
* @{
*/
// Enum function, which will be called for each session
typedef int (*httpd_session_enum_function)(struct sock_db *session, void *context);
/**
* @brief Enumerates all sessions
*
* @param[in] hd Server instance data
* @param[in] enum_function Enumeration function, which will be called for each session
* @param[in] context Context, which will be passed to the enumeration function
*/
void httpd_sess_enum(struct httpd_data *hd, httpd_session_enum_function enum_function, void *context);
/**
* @brief Returns next free session slot (fd<0)
*
* @param[in] hd Server instance data
*
* @return
* - +VE : Free session slot
* - NULL: End of iteration
*/
struct sock_db *httpd_sess_get_free(struct httpd_data *hd);
/**
* @brief Retrieve a session by its descriptor
*
* @param[in] hd Server instance data
* @param[in] sockfd Socket FD
* @return pointer into the socket DB, or NULL if not found
*/
struct sock_db *httpd_sess_get(struct httpd_data *hd, int sockfd);
/**
* @brief Delete sessions whose FDs have became invalid.
* This is a recovery strategy e.g. after select() fails.
*
* @param[in] hd Server instance data
*/
void httpd_sess_delete_invalid(struct httpd_data *hd);
/**
* @brief Initializes an http session by resetting the sockets database.
*
* @param[in] hd Server instance data
*/
void httpd_sess_init(struct httpd_data *hd);
/**
* @brief Starts a new session for client requesting connection and adds
* it's descriptor to the socket database.
*
* @param[in] hd Server instance data
* @param[in] newfd Descriptor of the new client to be added to the session.
*
* @return
* - ESP_OK : on successfully queuing the work
* - ESP_FAIL : in case of control socket error while sending
*/
esp_err_t httpd_sess_new(struct httpd_data *hd, int newfd);
/**
* @brief Processes incoming HTTP requests
*
* @param[in] hd Server instance data
* @param[in] session Session
*
* @return
* - ESP_OK : on successfully receiving, parsing and responding to a request
* - ESP_FAIL : in case of failure in any of the stages of processing
*/
esp_err_t httpd_sess_process(struct httpd_data *hd, struct sock_db *session);
/**
* @brief Remove client descriptor from the session / socket database
* and close the connection for this client.
*
* @param[in] hd Server instance data
* @param[in] session Session
*/
void httpd_sess_delete(struct httpd_data *hd, struct sock_db *session);
/**
* @brief Free session context
*
* @param[in] ctx Pointer to session context
* @param[in] free_fn Free function to call on session context
*/
void httpd_sess_free_ctx(void **ctx, httpd_free_ctx_fn_t free_fn);
/**
* @brief Add descriptors present in the socket database to an fdset and
* update the value of maxfd which are needed by the select function
* for looking through all available sockets for incoming data.
*
* @param[in] hd Server instance data
* @param[out] fdset File descriptor set to be updated.
* @param[out] maxfd Maximum value among all file descriptors.
*/
void httpd_sess_set_descriptors(struct httpd_data *hd, fd_set *fdset, int *maxfd);
/**
* @brief Checks if session can accept another connection from new client.
* If sockets database is full then this returns false.
*
* @param[in] hd Server instance data
*
* @return True if session can accept new clients
*/
bool httpd_is_sess_available(struct httpd_data *hd);
/**
* @brief Checks if session has any pending data/packets
* for processing
*
* This is needed as httpd_unrecv may un-receive next
* packet in the stream. If only partial packet was
* received then select() would mark the fd for processing
* as remaining part of the packet would still be in socket
* recv queue. But if a complete packet got unreceived
* then it would not be processed until further data is
* received on the socket. This is when this function
* comes in use, as it checks the socket's pending data
* buffer.
*
* @param[in] hd Server instance data
* @param[in] session Session
*
* @return True if there is any pending data
*/
bool httpd_sess_pending(struct httpd_data *hd, struct sock_db *session);
/**
* @brief Removes the least recently used client from the session
*
* This may be useful if new clients are requesting for connection but
* max number of connections is reached, in which case the client which
* is inactive for the longest will be removed from the session.
*
* @param[in] hd Server instance data
*
* @return
* - ESP_OK : if session closure initiated successfully
* - ESP_FAIL : if failed
*/
esp_err_t httpd_sess_close_lru(struct httpd_data *hd);
/**
* @brief Closes all sessions
*
* @param[in] hd Server instance data
*
*/
void httpd_sess_close_all(struct httpd_data *hd);
/** End of Group : Session Management
* @}
*/
/****************** Group : URI Handling ********************/
/** @name URI Handling
* Methods for accessing URI handlers
* @{
*/
/**
* @brief For an HTTP request, searches through all the registered URI handlers
* and invokes the appropriate one if found
*
* @param[in] hd Server instance data for which handler needs to be invoked
*
* @return
* - ESP_OK : if handler found and executed successfully
* - ESP_FAIL : otherwise
*/
esp_err_t httpd_uri(struct httpd_data *hd);
/**
* @brief Unregister all URI handlers
*
* @param[in] hd Server instance data
*/
void httpd_unregister_all_uri_handlers(struct httpd_data *hd);
/**
* @brief Validates the request to prevent users from calling APIs, that are to
* be called only inside a URI handler, outside the handler context
*
* @param[in] req Pointer to HTTP request that needs to be validated
*
* @return
* - true : if valid request
* - false : otherwise
*/
bool httpd_validate_req_ptr(httpd_req_t *r);
/* httpd_validate_req_ptr() adds some overhead to frequently used APIs,
* and is useful mostly for debugging, so it's preferable to disable
* the check by default and enable it only if necessary */
#ifdef CONFIG_HTTPD_VALIDATE_REQ
#define httpd_valid_req(r) httpd_validate_req_ptr(r)
#else
#define httpd_valid_req(r) true
#endif
/** End of Group : URI Handling
* @}
*/
/****************** Group : Processing ********************/
/** @name Processing
* Methods for processing HTTP requests
* @{
*/
/**
* @brief Initiates the processing of HTTP request
*
* Receives incoming TCP packet on a socket, then parses the packet as
* HTTP request and fills httpd_req_t data structure with the extracted
* URI, headers are ready to be fetched from scratch buffer and calling
* http_recv() after this reads the body of the request.
*
* @param[in] hd Server instance data
* @param[in] sd Pointer to socket which is needed for receiving TCP packets.
*
* @return
* - ESP_OK : if request packet is valid
* - ESP_FAIL : otherwise
*/
esp_err_t httpd_req_new(struct httpd_data *hd, struct sock_db *sd);
/**
* @brief For an HTTP request, resets the resources allocated for it and
* purges any data left to be received
*
* @param[in] hd Server instance data
*
* @return
* - ESP_OK : if request packet deleted and resources cleaned.
* - ESP_FAIL : otherwise.
*/
esp_err_t httpd_req_delete(struct httpd_data *hd);
/** End of Group : Parsing
* @}
*/
/****************** Group : Send/Receive ********************/
/** @name Send and Receive
* Methods for transmitting and receiving HTTP requests and responses
* @{
*/
/**
* @brief For sending out data in response to an HTTP request.
*
* @param[in] req Pointer to the HTTP request for which the response needs to be sent
* @param[in] buf Pointer to the buffer from where the body of the response is taken
* @param[in] buf_len Length of the buffer
*
* @return
* - Length of data : if successful
* - ESP_FAIL : if failed
*/
int httpd_send(httpd_req_t *req, const char *buf, size_t buf_len);
/**
* @brief For receiving HTTP request data
*
* @note The exposed API httpd_recv() is simply this function with last parameter
* set as false. This function is used internally during reception and
* processing of a new request.
*
* There are 2 options available that affect the behavior of the function:
* - HTTPD_RECV_OPT_HALT_AFTER_PENDING
* The option to halt after receiving pending data prevents the server from
* requesting more data than is needed for completing a packet in case when
* all the remaining part of the packet is in the pending buffer.
*
* - HTTPD_RECV_OPT_BLOCKING
* The option to not return until the `buf_len` bytes have been read.
*
* @param[in] req Pointer to new HTTP request which only has the socket descriptor
* @param[out] buf Pointer to the buffer which will be filled with the received data
* @param[in] buf_len Length of the buffer
* @param[in] opt Receive option
*
* @return
* - Length of data : if successful
* - ESP_FAIL : if failed
*/
int httpd_recv_with_opt(httpd_req_t *r, char *buf, size_t buf_len, httpd_recv_opt_t opt);
/**
* @brief For un-receiving HTTP request data
*
* This function copies data into internal buffer pending_data so that
* when httpd_recv is called, it first fetches this pending data and
* then only starts receiving from the socket
*
* @note If data is too large for the internal buffer then only
* part of the data is unreceived, reflected in the returned
* length. Make sure that such truncation is checked for and
* handled properly.
*
* @param[in] req Pointer to new HTTP request which only has the socket descriptor
* @param[in] buf Pointer to the buffer from where data needs to be un-received
* @param[in] buf_len Length of the buffer
*
* @return Length of data copied into pending buffer
*/
size_t httpd_unrecv(struct httpd_req *r, const char *buf, size_t buf_len);
/**
* @brief This is the low level default send function of the HTTPD. This should
* NEVER be called directly. The semantics of this is exactly similar to
* send() of the BSD socket API.
*
* @param[in] hd Server instance data
* @param[in] sockfd Socket descriptor for sending data
* @param[in] buf Pointer to the buffer from where the body of the response is taken
* @param[in] buf_len Length of the buffer
* @param[in] flags Flags for mode selection
*
* @return
* - Length of data : if successful
* - -1 : if failed (appropriate errno is set)
*/
int httpd_default_send(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags);
/**
* @brief This is the low level default recv function of the HTTPD. This should
* NEVER be called directly. The semantics of this is exactly similar to
* recv() of the BSD socket API.
*
* @param[in] hd Server instance data
* @param[in] sockfd Socket descriptor for sending data
* @param[out] buf Pointer to the buffer which will be filled with the received data
* @param[in] buf_len Length of the buffer
* @param[in] flags Flags for mode selection
*
* @return
* - Length of data : if successful
* - -1 : if failed (appropriate errno is set)
*/
int httpd_default_recv(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags);
/** End of Group : Send and Receive
* @}
*/
/* ************** Group: WebSocket ************** */
/** @name WebSocket
* Functions for WebSocket header parsing
* @{
*/
/**
* @brief This function is for responding a WebSocket handshake
*
* @param[in] req Pointer to handshake request that will be handled
* @param[in] supported_subprotocol Pointer to the subprotocol supported by this URI
* @return
* - ESP_OK : When handshake is successful
* - ESP_ERR_NOT_FOUND : When some headers (Sec-WebSocket-*) are not found
* - ESP_ERR_INVALID_VERSION : The WebSocket version is not "13"
* - ESP_ERR_INVALID_STATE : Handshake was done beforehand
* - ESP_ERR_INVALID_ARG : Argument is invalid (null or non-WebSocket)
* - ESP_FAIL : Socket failures
*/
esp_err_t httpd_ws_respond_server_handshake(httpd_req_t *req, const char *supported_subprotocol);
/**
* @brief This function is for getting a frame type
* and responding a WebSocket control frame automatically
*
* @param[in] req Pointer to handshake request that will be handled
* @return
* - ESP_OK : When handshake is successful
* - ESP_ERR_INVALID_ARG : Argument is invalid (null or non-WebSocket)
* - ESP_ERR_INVALID_STATE : Received only some parts of a control frame
* - ESP_FAIL : Socket failures
*/
esp_err_t httpd_ws_get_frame_type(httpd_req_t *req);
/**
* @brief Trigger an httpd session close externally
*
* @note Calling this API is only required in special circumstances wherein
* some application requires to close an httpd client session asynchronously.
*
* @param[in] handle Handle to server returned by httpd_start
* @param[in] session Session to be closed
*
* @return
* - ESP_OK : On successfully initiating closure
* - ESP_FAIL : Failure to queue work
* - ESP_ERR_NOT_FOUND : Socket fd not found
* - ESP_ERR_INVALID_ARG : Null arguments
*/
esp_err_t httpd_sess_trigger_close_(httpd_handle_t handle, struct sock_db *session);
/**
* @brief Directly closes the least recently used session
*
* @param[in] hd Server instance data
*
* @return
* - ESP_OK : if session closed successfully
*/
esp_err_t httpd_sess_close_lru_direct(struct httpd_data *hd);
/** End of WebSocket related functions
* @}
*/
#ifdef CONFIG_HTTPD_ENABLE_EVENTS
#if CONFIG_HTTPD_SERVER_EVENT_POST_TIMEOUT == -1
#define ESP_HTTP_SERVER_EVENT_POST_TIMEOUT portMAX_DELAY
#else
#define ESP_HTTP_SERVER_EVENT_POST_TIMEOUT pdMS_TO_TICKS(CONFIG_HTTPD_SERVER_EVENT_POST_TIMEOUT)
#endif
/**
* @brief Function to dispatch events in default event loop
*
*/
void esp_http_server_dispatch_event(int32_t event_id, const void* event_data, size_t event_data_size);
#else // CONFIG_HTTPD_ENABLE_EVENTS
static inline void esp_http_server_dispatch_event(int32_t event_id, const void* event_data, size_t event_data_size)
{
// Events disabled, do nothing
(void) event_id;
(void) event_data;
(void) event_data_size;
}
#endif // CONFIG_HTTPD_ENABLE_EVENTS
#ifdef __cplusplus
}
#endif
#endif /* ! _HTTPD_PRIV_H_ */
+645
View File
@@ -0,0 +1,645 @@
/*
* SPDX-FileCopyrightText: 2018-2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <string.h>
#include <sys/socket.h>
#include <sys/param.h>
#include <errno.h>
#include <esp_log.h>
#include <esp_err.h>
#include <assert.h>
#include <netinet/tcp.h>
#include <net/if.h>
#include <esp_http_server.h>
#include "esp_httpd_priv.h"
#include "ctrl_sock.h"
#if CONFIG_HTTPD_QUEUE_WORK_BLOCKING
#include "freertos/semphr.h"
#endif
#if defined(CONFIG_LWIP_MAX_SOCKETS)
#define HTTPD_MAX_SOCKETS CONFIG_LWIP_MAX_SOCKETS
#else
/* LwIP component is not included into the build, use a default value */
#define HTTPD_MAX_SOCKETS 15
#endif
static const int DEFAULT_KEEP_ALIVE_IDLE = 5;
static const int DEFAULT_KEEP_ALIVE_INTERVAL= 5;
static const int DEFAULT_KEEP_ALIVE_COUNT= 3;
typedef struct {
fd_set *fdset;
struct httpd_data *hd;
} process_session_context_t;
static const char *TAG = "httpd";
#ifdef CONFIG_HTTPD_ENABLE_EVENTS
ESP_EVENT_DEFINE_BASE(ESP_HTTP_SERVER_EVENT);
void esp_http_server_dispatch_event(int32_t event_id, const void* event_data, size_t event_data_size)
{
esp_err_t err = esp_event_post(ESP_HTTP_SERVER_EVENT, event_id, event_data, event_data_size, ESP_HTTP_SERVER_EVENT_POST_TIMEOUT);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to post esp_http_server event: %s", esp_err_to_name(err));
}
}
#endif // CONFIG_HTTPD_ENABLE_EVENTS
static esp_err_t httpd_accept_conn(struct httpd_data *hd)
{
/* If no space is available for new session, close the least recently used one */
if (hd->config.lru_purge_enable == true) {
if (!httpd_is_sess_available(hd)) {
/* Queue asynchronous closure of the least recently used session */
#if CONFIG_HTTPD_QUEUE_WORK_BLOCKING
/* In case of blocking mode, close the least recently used session directly */
return httpd_sess_close_lru_direct(hd);
#else
return httpd_sess_close_lru(hd);
#endif /* CONFIG_HTTPD_QUEUE_WORK_BLOCKING */
/* Returning from this allows the main server thread to process
* the queued asynchronous control message for closing LRU session.
* Since connection request hasn't been addressed yet using accept()
* therefore httpd_accept_conn() will be called again, but this time
* with space available for one session
*/
}
}
struct sockaddr_storage addr_from;
socklen_t addr_from_len = sizeof(addr_from);
int new_fd = accept(hd->listen_fd, (struct sockaddr *)&addr_from, &addr_from_len);
if (new_fd < 0) {
ESP_LOGE(TAG, LOG_FMT("error in accept (%d)"), errno);
return ESP_FAIL;
}
ESP_LOGD(TAG, LOG_FMT("newfd = %d"), new_fd);
struct timeval tv;
/* Set recv timeout of this fd as per config */
tv.tv_sec = hd->config.recv_wait_timeout;
tv.tv_usec = 0;
if (setsockopt(new_fd, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tv, sizeof(tv)) < 0) {
ESP_LOGE(TAG, LOG_FMT("error in setsockopt SO_RCVTIMEO (%d)"), errno);
goto exit;
}
/* Set send timeout of this fd as per config */
tv.tv_sec = hd->config.send_wait_timeout;
tv.tv_usec = 0;
if (setsockopt(new_fd, SOL_SOCKET, SO_SNDTIMEO, (const char *)&tv, sizeof(tv)) < 0) {
ESP_LOGE(TAG, LOG_FMT("error in setsockopt SO_SNDTIMEO (%d)"), errno);
goto exit;
}
if (hd->config.keep_alive_enable) {
int keep_alive_enable = 1;
int keep_alive_idle = hd->config.keep_alive_idle ? hd->config.keep_alive_idle : DEFAULT_KEEP_ALIVE_IDLE;
int keep_alive_interval = hd->config.keep_alive_interval ? hd->config.keep_alive_interval : DEFAULT_KEEP_ALIVE_INTERVAL;
int keep_alive_count = hd->config.keep_alive_count ? hd->config.keep_alive_count : DEFAULT_KEEP_ALIVE_COUNT;
ESP_LOGD(TAG, "Enable TCP keep alive. idle: %d, interval: %d, count: %d", keep_alive_idle, keep_alive_interval, keep_alive_count);
if (setsockopt(new_fd, SOL_SOCKET, SO_KEEPALIVE, &keep_alive_enable, sizeof(keep_alive_enable)) < 0) {
ESP_LOGE(TAG, LOG_FMT("error in setsockopt SO_KEEPALIVE (%d)"), errno);
goto exit;
}
#ifndef __APPLE__
if (setsockopt(new_fd, IPPROTO_TCP, TCP_KEEPIDLE, &keep_alive_idle, sizeof(keep_alive_idle)) < 0) {
ESP_LOGE(TAG, LOG_FMT("error in setsockopt TCP_KEEPIDLE (%d)"), errno);
goto exit;
}
if (setsockopt(new_fd, IPPROTO_TCP, TCP_KEEPINTVL, &keep_alive_interval, sizeof(keep_alive_interval)) < 0) {
ESP_LOGE(TAG, LOG_FMT("error in setsockopt TCP_KEEPINTVL (%d)"), errno);
goto exit;
}
if (setsockopt(new_fd, IPPROTO_TCP, TCP_KEEPCNT, &keep_alive_count, sizeof(keep_alive_count)) < 0) {
ESP_LOGE(TAG, LOG_FMT("error in setsockopt TCP_KEEPCNT (%d)"), errno);
goto exit;
}
#else // __APPLE__
if (setsockopt(new_fd, IPPROTO_TCP, TCP_KEEPALIVE, &keep_alive_idle, sizeof(keep_alive_idle)) < 0) {
ESP_LOGE(TAG, LOG_FMT("error in setsockopt TCP_KEEPALIVE (%d)"), errno);
goto exit;
}
#endif // __APPLE__
}
if (ESP_OK != httpd_sess_new(hd, new_fd)) {
ESP_LOGE(TAG, LOG_FMT("session creation failed"));
goto exit;
}
ESP_LOGD(TAG, LOG_FMT("complete"));
hd->http_server_state = HTTP_SERVER_EVENT_ON_CONNECTED;
esp_http_server_dispatch_event(HTTP_SERVER_EVENT_ON_CONNECTED, &new_fd, sizeof(int));
return ESP_OK;
exit:
close(new_fd);
return ESP_FAIL;
}
esp_err_t httpd_queue_work(httpd_handle_t handle, httpd_work_fn_t work, void *arg)
{
if (handle == NULL || work == NULL) {
return ESP_ERR_INVALID_ARG;
}
struct httpd_data *hd = (struct httpd_data *) handle;
struct httpd_ctrl_data msg = {
.hc_msg = HTTPD_CTRL_WORK,
.hc_work = work,
.hc_work_arg = arg,
};
/* Reserve a slot in the control mbox before sending. In blocking mode
* the caller waits for a slot; in the default non-blocking mode we
* fail fast so the caller knows the work was not queued. */
#if CONFIG_HTTPD_QUEUE_WORK_BLOCKING
const TickType_t wait = portMAX_DELAY;
#else
const TickType_t wait = 0;
#endif
if (xSemaphoreTake(hd->ctrl_sock_semaphore, wait) != pdTRUE) {
ESP_LOGW(TAG, LOG_FMT("ctrl socket queue full, work not queued"));
return ESP_FAIL;
}
int ret = cs_send_to_ctrl_sock(hd->msg_fd, hd->config.ctrl_port, &msg, sizeof(msg));
if (ret < 0) {
ESP_LOGW(TAG, LOG_FMT("failed to queue work"));
xSemaphoreGive(hd->ctrl_sock_semaphore);
return ESP_FAIL;
}
return ESP_OK;
}
esp_err_t httpd_get_client_list(httpd_handle_t handle, size_t *fds, int *client_fds)
{
struct httpd_data *hd = (struct httpd_data *) handle;
if (hd == NULL || fds == NULL || *fds == 0 || client_fds == NULL) {
return ESP_ERR_INVALID_ARG;
}
size_t max_fds = *fds;
*fds = 0;
for (int i = 0; i < hd->config.max_open_sockets; ++i) {
if (hd->hd_sd[i].fd != -1) {
if (*fds < max_fds) {
client_fds[(*fds)++] = hd->hd_sd[i].fd;
} else {
return ESP_ERR_INVALID_ARG;
}
}
}
return ESP_OK;
}
void *httpd_get_global_user_ctx(httpd_handle_t handle)
{
return ((struct httpd_data *)handle)->config.global_user_ctx;
}
void *httpd_get_global_transport_ctx(httpd_handle_t handle)
{
return ((struct httpd_data *)handle)->config.global_transport_ctx;
}
static void httpd_process_ctrl_msg(struct httpd_data *hd)
{
struct httpd_ctrl_data msg;
int ret = recv(hd->ctrl_fd, &msg, sizeof(msg), 0);
if (ret <= 0) {
ESP_LOGW(TAG, LOG_FMT("error in recv (%d)"), errno);
/* No packet was actually consumed from the mbox here, so this give
* is unbalanced. It's tolerated because the counting semaphore is
* capped at its max — excess gives become no-ops. Spurious recv
* errors after select() are rare in practice. */
xSemaphoreGive(hd->ctrl_sock_semaphore);
return;
}
if (ret != sizeof(msg)) {
ESP_LOGW(TAG, LOG_FMT("incomplete msg"));
xSemaphoreGive(hd->ctrl_sock_semaphore);
return;
}
switch (msg.hc_msg) {
case HTTPD_CTRL_WORK:
if (msg.hc_work) {
ESP_LOGD(TAG, LOG_FMT("work"));
(*msg.hc_work)(msg.hc_work_arg);
}
break;
case HTTPD_CTRL_SHUTDOWN:
ESP_LOGD(TAG, LOG_FMT("shutdown"));
hd->hd_td.status = THREAD_STOPPING;
break;
default:
break;
}
xSemaphoreGive(hd->ctrl_sock_semaphore);
}
// Called for each session from httpd_server
static int httpd_process_session(struct sock_db *session, void *context)
{
if ((!session) || (!context)) {
return 0;
}
if (session->fd < 0) {
return 1;
}
// session is busy in an async task, do not process here.
if (session->for_async_req) {
return 1;
}
process_session_context_t *ctx = (process_session_context_t *)context;
int fd = session->fd;
if (FD_ISSET(fd, ctx->fdset) || httpd_sess_pending(ctx->hd, session)) {
ESP_LOGD(TAG, LOG_FMT("processing socket %d"), fd);
if (httpd_sess_process(ctx->hd, session) != ESP_OK) {
httpd_sess_delete(ctx->hd, session); // Delete session
}
}
return 1;
}
/* Manage in-coming connection or data requests */
static esp_err_t httpd_server(struct httpd_data *hd)
{
fd_set read_set;
FD_ZERO(&read_set);
if (hd->config.lru_purge_enable || httpd_is_sess_available(hd)) {
/* Only listen for new connections if server has capacity to
* handle more (or when LRU purge is enabled, in which case
* older connections will be closed) */
FD_SET(hd->listen_fd, &read_set);
}
FD_SET(hd->ctrl_fd, &read_set);
int tmp_max_fd;
httpd_sess_set_descriptors(hd, &read_set, &tmp_max_fd);
int maxfd = MAX(hd->listen_fd, tmp_max_fd);
tmp_max_fd = maxfd;
maxfd = MAX(hd->ctrl_fd, tmp_max_fd);
ESP_LOGD(TAG, LOG_FMT("doing select maxfd+1 = %d"), maxfd + 1);
int active_cnt = select(maxfd + 1, &read_set, NULL, NULL, NULL);
if (active_cnt < 0) {
ESP_LOGE(TAG, LOG_FMT("error in select (%d)"), errno);
httpd_sess_delete_invalid(hd);
return ESP_OK;
}
/* Case0: Do we have a control message? */
if (FD_ISSET(hd->ctrl_fd, &read_set)) {
ESP_LOGD(TAG, LOG_FMT("processing ctrl message"));
httpd_process_ctrl_msg(hd);
if (hd->hd_td.status == THREAD_STOPPING) {
ESP_LOGD(TAG, LOG_FMT("stopping thread"));
return ESP_FAIL;
}
}
/* Case1: Do we have any activity on the current data
* sessions? */
process_session_context_t context = {
.fdset = &read_set,
.hd = hd
};
httpd_sess_enum(hd, httpd_process_session, &context);
/* Case2: Do we have any incoming connection requests to
* process? */
if (FD_ISSET(hd->listen_fd, &read_set)) {
ESP_LOGD(TAG, LOG_FMT("processing listen socket %d"), hd->listen_fd);
if (httpd_accept_conn(hd) != ESP_OK) {
ESP_LOGW(TAG, LOG_FMT("error accepting new connection"));
}
}
return ESP_OK;
}
/* The main HTTPD thread */
static void httpd_thread(void *arg)
{
int ret;
struct httpd_data *hd = (struct httpd_data *) arg;
hd->hd_td.status = THREAD_RUNNING;
ESP_LOGD(TAG, LOG_FMT("web server started"));
while (1) {
ret = httpd_server(hd);
if (ret != ESP_OK) {
break;
}
}
ESP_LOGD(TAG, LOG_FMT("web server exiting"));
close(hd->msg_fd);
cs_free_ctrl_sock(hd->ctrl_fd);
httpd_sess_close_all(hd);
close(hd->listen_fd);
hd->hd_td.status = THREAD_STOPPED;
httpd_os_thread_delete();
}
static esp_err_t httpd_server_init(struct httpd_data *hd)
{
#if CONFIG_LWIP_IPV6
int fd = socket(PF_INET6, SOCK_STREAM, 0);
#else
int fd = socket(PF_INET, SOCK_STREAM, 0);
#endif
if (fd < 0) {
ESP_LOGE(TAG, LOG_FMT("error in socket (%d)"), errno);
return ESP_FAIL;
}
#if CONFIG_LWIP_IPV6
struct in6_addr inaddr_any = IN6ADDR_ANY_INIT;
struct sockaddr_in6 serv_addr = {
.sin6_family = PF_INET6,
.sin6_addr = inaddr_any,
.sin6_port = htons(hd->config.server_port)
};
#else
struct sockaddr_in serv_addr = {
.sin_family = PF_INET,
.sin_addr = {
.s_addr = htonl(INADDR_ANY)
},
.sin_port = htons(hd->config.server_port)
};
#endif
/* Enable SO_REUSEADDR to allow binding to the same
* address and port when restarting the server */
int enable = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) < 0) {
/* This will fail if CONFIG_LWIP_SO_REUSE is not enabled. But
* it does not affect the normal working of the HTTP Server */
ESP_LOGW(TAG, LOG_FMT("error in setsockopt SO_REUSEADDR (%d)"), errno);
}
/* Bind to specific network interface if configured */
if (hd->config.if_name && hd->config.if_name->ifr_name[0] != 0) {
ESP_LOGI(TAG, LOG_FMT("Binding server to interface: %s"), hd->config.if_name->ifr_name);
#ifndef __APPLE__
if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, hd->config.if_name, sizeof(struct ifreq)) < 0) {
#else
int idx = if_nametoindex(hd->config.if_name->ifr_name);
if (idx == 0) {
ESP_LOGE(TAG, LOG_FMT("Invalid interface name %s"), hd->config.if_name->ifr_name);
close(fd);
return ESP_FAIL;
}
if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &idx, sizeof(idx)) < 0) {
#endif
ESP_LOGE(TAG, LOG_FMT("Failed to bind to interface %s (%d)"), hd->config.if_name->ifr_name, errno);
close(fd);
return ESP_FAIL;
}
}
int ret = bind(fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
if (ret < 0) {
ESP_LOGE(TAG, LOG_FMT("error in bind (%d)"), errno);
close(fd);
return ESP_FAIL;
}
ret = listen(fd, hd->config.backlog_conn);
if (ret < 0) {
ESP_LOGE(TAG, LOG_FMT("error in listen (%d)"), errno);
close(fd);
return ESP_FAIL;
}
int ctrl_fd = cs_create_ctrl_sock(hd->config.ctrl_port);
if (ctrl_fd < 0) {
ESP_LOGE(TAG, LOG_FMT("error in creating ctrl socket (%d)"), errno);
close(fd);
return ESP_FAIL;
}
int msg_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (msg_fd < 0) {
ESP_LOGE(TAG, LOG_FMT("error in creating msg socket (%d)"), errno);
close(fd);
close(ctrl_fd);
return ESP_FAIL;
}
hd->listen_fd = fd;
hd->ctrl_fd = ctrl_fd;
hd->msg_fd = msg_fd;
return ESP_OK;
}
static struct httpd_data *httpd_create(const httpd_config_t *config)
{
/* Allocate memory for httpd instance data */
struct httpd_data *hd = calloc(1, sizeof(struct httpd_data));
if (!hd) {
ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP server instance"));
return NULL;
}
hd->hd_calls = calloc(config->max_uri_handlers, sizeof(httpd_uri_t *));
if (!hd->hd_calls) {
ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP URI handlers"));
free(hd);
return NULL;
}
hd->hd_sd = calloc(config->max_open_sockets, sizeof(struct sock_db));
if (!hd->hd_sd) {
ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP session data"));
free(hd->hd_calls);
free(hd);
return NULL;
}
struct httpd_req_aux *ra = &hd->hd_req_aux;
ra->resp_hdrs = calloc(config->max_resp_headers, sizeof(struct resp_hdr));
if (!ra->resp_hdrs) {
ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP response headers"));
free(hd->hd_sd);
free(hd->hd_calls);
free(hd);
return NULL;
}
hd->err_handler_fns = calloc(HTTPD_ERR_CODE_MAX, sizeof(httpd_err_handler_func_t));
if (!hd->err_handler_fns) {
ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP error handlers"));
free(ra->resp_hdrs);
free(hd->hd_sd);
free(hd->hd_calls);
free(hd);
return NULL;
}
/* Save the configuration for this instance */
hd->config = *config;
return hd;
}
static void httpd_delete(struct httpd_data *hd)
{
struct httpd_req_aux *ra = &hd->hd_req_aux;
/* Free memory of httpd instance data */
free(hd->err_handler_fns);
free(ra->resp_hdrs);
free(hd->hd_sd);
if (hd->ctrl_sock_semaphore) {
vSemaphoreDelete(hd->ctrl_sock_semaphore);
hd->ctrl_sock_semaphore = NULL;
}
/* Free registered URI handlers */
httpd_unregister_all_uri_handlers(hd);
free(hd->hd_calls);
free(hd);
}
esp_err_t httpd_start(httpd_handle_t *handle, const httpd_config_t *config)
{
if (handle == NULL || config == NULL) {
return ESP_ERR_INVALID_ARG;
}
/* Sanity check about whether LWIP is configured for providing the
* maximum number of open sockets sufficient for the server. Though,
* this check doesn't guarantee that many sockets will actually be
* available at runtime as other processes may use up some sockets.
* Note that server also uses 3 sockets for its internal use :
* 1) listening for new TCP connections
* 2) for sending control messages over UDP
* 3) for receiving control messages over UDP
* So the total number of required sockets is max_open_sockets + 3
*/
if (HTTPD_MAX_SOCKETS < config->max_open_sockets + 3) {
ESP_LOGE(TAG, "Config option max_open_sockets is too large (max allowed %d, 3 sockets used by HTTP server internally)\n\t"
"Either decrease this or configure LWIP_MAX_SOCKETS to a larger value",
HTTPD_MAX_SOCKETS - 3);
return ESP_ERR_INVALID_ARG;
}
struct httpd_data *hd = httpd_create(config);
if (hd == NULL) {
/* Failed to allocate memory */
return ESP_ERR_HTTPD_ALLOC_MEM;
}
/* Counting semaphore sized to the UDP control-socket recv mbox. Each
* httpd_queue_work() take reserves one mbox slot; httpd_process_ctrl_msg()
* gives one back per drain. This bounds the producer to the mbox capacity
* and prevents silent lwIP-mbox overflow drops that would otherwise leak
* the caller's async-send context. Always created so the default
* (non-blocking) httpd_queue_work() path can also rely on it. */
hd->ctrl_sock_semaphore = xSemaphoreCreateCounting(CONFIG_LWIP_UDP_RECVMBOX_SIZE, CONFIG_LWIP_UDP_RECVMBOX_SIZE);
if (hd->ctrl_sock_semaphore == NULL) {
ESP_LOGE(TAG, "Failed to create Semaphore");
httpd_delete(hd);
return ESP_ERR_HTTPD_ALLOC_MEM;
}
if (httpd_server_init(hd) != ESP_OK) {
httpd_delete(hd);
return ESP_FAIL;
}
httpd_sess_init(hd);
if (httpd_os_thread_create(&hd->hd_td.handle, "httpd",
hd->config.stack_size,
hd->config.task_priority,
httpd_thread, hd,
hd->config.core_id,
hd->config.task_caps) != ESP_OK) {
/* Close the open socket */
close(hd->listen_fd);
/* Close the control socket */
cs_free_ctrl_sock(hd->ctrl_fd);
/* Close the message socket */
close(hd->msg_fd);
/* Failed to launch task */
httpd_delete(hd);
return ESP_ERR_HTTPD_TASK;
}
*handle = (httpd_handle_t)hd;
hd->http_server_state = HTTP_SERVER_EVENT_START;
esp_http_server_dispatch_event(HTTP_SERVER_EVENT_START, NULL, 0);
return ESP_OK;
}
esp_err_t httpd_stop(httpd_handle_t handle)
{
struct httpd_data *hd = (struct httpd_data *) handle;
if (hd == NULL) {
return ESP_ERR_INVALID_ARG;
}
struct httpd_ctrl_data msg;
memset(&msg, 0, sizeof(msg));
msg.hc_msg = HTTPD_CTRL_SHUTDOWN;
/* Reserve a slot in the ctrl mbox before sending so we never push past
* its capacity. Blocking is safe: the httpd task is the consumer and
* keeps draining the mbox until it observes HTTPD_CTRL_SHUTDOWN. */
if (xSemaphoreTake(hd->ctrl_sock_semaphore, portMAX_DELAY) != pdTRUE) {
ESP_LOGE(TAG, "Failed to acquire ctrl socket semaphore");
return ESP_FAIL;
}
int ret = cs_send_to_ctrl_sock(hd->msg_fd, hd->config.ctrl_port, &msg, sizeof(msg));
if (ret < 0) {
ESP_LOGE(TAG, "Failed to send shutdown signal err=%d", ret);
xSemaphoreGive(hd->ctrl_sock_semaphore);
return ESP_FAIL;
}
ESP_LOGD(TAG, LOG_FMT("sent control msg to stop server"));
while (hd->hd_td.status != THREAD_STOPPED) {
httpd_os_thread_sleep(100);
}
/* Release global user context, if not NULL */
if (hd->config.global_user_ctx) {
if (hd->config.global_user_ctx_free_fn) {
hd->config.global_user_ctx_free_fn(hd->config.global_user_ctx);
} else {
free(hd->config.global_user_ctx);
}
hd->config.global_user_ctx = NULL;
}
/* Release global transport context, if not NULL */
if (hd->config.global_transport_ctx) {
if (hd->config.global_transport_ctx_free_fn) {
hd->config.global_transport_ctx_free_fn(hd->config.global_transport_ctx);
} else {
free(hd->config.global_transport_ctx);
}
hd->config.global_transport_ctx = NULL;
}
ESP_LOGD(TAG, LOG_FMT("server stopped"));
httpd_delete(hd);
esp_http_server_dispatch_event(HTTP_SERVER_EVENT_STOP, NULL, 0);
return ESP_OK;
}
esp_http_server_event_id_t httpd_get_server_state(httpd_handle_t handle)
{
struct httpd_data *hd = (struct httpd_data *) handle;
if (hd == NULL) {
return HTTP_SERVER_EVENT_ERROR;
}
return hd->http_server_state;
}
File diff suppressed because it is too large. Load diff
+520
View File
@@ -0,0 +1,520 @@
/*
* SPDX-FileCopyrightText: 2018-2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdlib.h>
#include <esp_log.h>
#include <esp_err.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <esp_http_server.h>
#include "esp_httpd_priv.h"
static const char *TAG = "httpd_sess";
typedef enum {
HTTPD_TASK_NONE = 0,
HTTPD_TASK_INIT, // Init session
HTTPD_TASK_GET_ACTIVE, // Get active session (fd!=-1)
HTTPD_TASK_GET_FREE, // Get free session slot (fd<0)
HTTPD_TASK_FIND_FD, // Find session with specific fd
HTTPD_TASK_SET_DESCRIPTOR, // Set descriptor
HTTPD_TASK_DELETE_INVALID, // Delete invalid session
HTTPD_TASK_FIND_LOWEST_LRU, // Find session with lowest lru
HTTPD_TASK_CLOSE // Close session
} task_t;
typedef struct {
task_t task;
int fd;
fd_set *fdset;
int max_fd;
struct httpd_data *hd;
uint64_t lru_counter;
struct sock_db *session;
} enum_context_t;
void httpd_sess_enum(struct httpd_data *hd, httpd_session_enum_function enum_function, void *context)
{
if ((!hd) || (!hd->hd_sd) || (!hd->config.max_open_sockets)) {
return;
}
struct sock_db *current = hd->hd_sd;
struct sock_db *end = hd->hd_sd + hd->config.max_open_sockets - 1;
while (current <= end) {
if (enum_function && (!enum_function(current, context))) {
break;
}
current++;
}
}
// Check if a FD is valid
static int fd_is_valid(int fd)
{
return fcntl(fd, F_GETFD) != -1 || errno != EBADF;
}
static int enum_function(struct sock_db *session, void *context)
{
if ((!session) || (!context)) {
return 0;
}
enum_context_t *ctx = (enum_context_t *) context;
int found = 0;
switch (ctx->task) {
// Initialize session
case HTTPD_TASK_INIT:
session->fd = -1;
session->ctx = NULL;
session->for_async_req = false;
break;
// Get active session
case HTTPD_TASK_GET_ACTIVE:
found = (session->fd != -1);
break;
// Get free slot
case HTTPD_TASK_GET_FREE:
found = (session->fd < 0);
break;
// Find fd
case HTTPD_TASK_FIND_FD:
found = (session->fd == ctx->fd);
break;
// Set descriptor
case HTTPD_TASK_SET_DESCRIPTOR:
if (session->fd != -1 && !session->for_async_req) {
FD_SET(session->fd, ctx->fdset);
if (session->fd > ctx->max_fd) {
ctx->max_fd = session->fd;
}
}
break;
// Delete invalid session
case HTTPD_TASK_DELETE_INVALID:
if (!fd_is_valid(session->fd)) {
ESP_LOGW(TAG, LOG_FMT("Closing invalid socket %d"), session->fd);
httpd_sess_delete(ctx->hd, session);
}
break;
// Find lowest lru
case HTTPD_TASK_FIND_LOWEST_LRU:
// Found free slot - no need to check other sessions
if (session->fd == -1) {
return 0;
}
// Only close sockets that are not in use
if (session->for_async_req == false) {
// Check/update lowest lru
if (session->lru_counter < ctx->lru_counter) {
ctx->lru_counter = session->lru_counter;
ctx->session = session;
}
}
break;
case HTTPD_TASK_CLOSE:
if (session->fd != -1) {
ESP_LOGD(TAG, LOG_FMT("cleaning up socket %d"), session->fd);
httpd_sess_delete(ctx->hd, session);
}
break;
default:
return 0;
}
if (found) {
ctx->session = session;
return 0;
}
return 1;
}
static void httpd_sess_close(void *arg)
{
struct sock_db *sock_db = (struct sock_db *) arg;
if (!sock_db) {
return;
}
if (!sock_db->lru_counter && !sock_db->lru_socket) {
ESP_LOGD(TAG, "Skipping session close for %d as it seems to be a race condition", sock_db->fd);
return;
}
sock_db->lru_socket = false;
struct httpd_data *hd = (struct httpd_data *) sock_db->handle;
hd->http_server_state = HTTP_SERVER_EVENT_DISCONNECTED;
httpd_sess_delete(hd, sock_db);
}
struct sock_db *httpd_sess_get_free(struct httpd_data *hd)
{
if ((!hd) || (hd->hd_sd_active_count == hd->config.max_open_sockets)) {
return NULL;
}
enum_context_t context = {
.task = HTTPD_TASK_GET_FREE
};
httpd_sess_enum(hd, enum_function, &context);
return context.session;
}
bool httpd_is_sess_available(struct httpd_data *hd)
{
return httpd_sess_get_free(hd) ? true : false;
}
struct sock_db *httpd_sess_get(struct httpd_data *hd, int sockfd)
{
if ((!hd) || (!hd->hd_sd) || (!hd->config.max_open_sockets)) {
return NULL;
}
// Check if called inside a request handler, and the session sockfd in use is same as the parameter
// => Just return the pointer to the sock_db corresponding to the request
if ((hd->hd_req_aux.sd) && (hd->hd_req_aux.sd->fd == sockfd)) {
return hd->hd_req_aux.sd;
}
enum_context_t context = {
.task = HTTPD_TASK_FIND_FD,
.fd = sockfd
};
httpd_sess_enum(hd, enum_function, &context);
return context.session;
}
esp_err_t httpd_sess_new(struct httpd_data *hd, int newfd)
{
ESP_LOGD(TAG, LOG_FMT("fd = %d"), newfd);
if (httpd_sess_get(hd, newfd)) {
ESP_LOGE(TAG, LOG_FMT("session already exists with fd = %d"), newfd);
return ESP_FAIL;
}
struct sock_db *session = httpd_sess_get_free(hd);
if (!session) {
ESP_LOGD(TAG, LOG_FMT("unable to launch session for fd = %d"), newfd);
return ESP_FAIL;
}
// Clear session data
memset(session, 0, sizeof (struct sock_db));
session->fd = newfd;
session->handle = (httpd_handle_t) hd;
session->send_fn = httpd_default_send;
session->recv_fn = httpd_default_recv;
session->lru_counter = hd->lru_counter;
// increment number of sessions
hd->hd_sd_active_count++;
// Call user-defined session opening function
if (hd->config.open_fn) {
esp_err_t ret = hd->config.open_fn(hd, session->fd);
if (ret != ESP_OK) {
httpd_sess_delete(hd, session);
ESP_LOGD(TAG, LOG_FMT("open_fn failed for fd = %d"), newfd);
return ret;
}
}
ESP_LOGD(TAG, LOG_FMT("active sockets: %d"), hd->hd_sd_active_count);
return ESP_OK;
}
void httpd_sess_free_ctx(void **ctx, httpd_free_ctx_fn_t free_fn)
{
if ((!ctx) || (!*ctx)) {
return;
}
if (free_fn) {
free_fn(*ctx);
} else {
free(*ctx);
}
*ctx = NULL;
}
void httpd_sess_clear_ctx(struct sock_db *session)
{
if ((!session) || ((!session->ctx) && (!session->transport_ctx))) {
return;
}
// free user ctx
if (session->ctx) {
httpd_sess_free_ctx(&session->ctx, session->free_ctx);
session->free_ctx = NULL;
}
// Free 'transport' context
if (session->transport_ctx) {
httpd_sess_free_ctx(&session->transport_ctx, session->free_transport_ctx);
session->free_transport_ctx = NULL;
}
}
void *httpd_sess_get_ctx(httpd_handle_t handle, int sockfd)
{
struct sock_db *session = httpd_sess_get(handle, sockfd);
if (!session) {
return NULL;
}
// Check if the function has been called from inside a
// request handler, in which case fetch the context from
// the httpd_req_t structure
struct httpd_data *hd = (struct httpd_data *) handle;
if (hd->hd_req_aux.sd == session) {
return hd->hd_req.sess_ctx;
}
return session->ctx;
}
void httpd_sess_set_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t free_fn)
{
struct sock_db *session = httpd_sess_get(handle, sockfd);
if (!session) {
return;
}
// Check if the function has been called from inside a
// request handler, in which case set the context inside
// the httpd_req_t structure
struct httpd_data *hd = (struct httpd_data *) handle;
if (hd->hd_req_aux.sd == session) {
if (hd->hd_req.sess_ctx != ctx) {
// Don't free previous context if it is in sockdb
// as it will be freed inside httpd_req_cleanup()
if (session->ctx != hd->hd_req.sess_ctx) {
httpd_sess_free_ctx(&hd->hd_req.sess_ctx, hd->hd_req.free_ctx); // Free previous context
}
hd->hd_req.sess_ctx = ctx;
}
hd->hd_req.free_ctx = free_fn;
return;
}
// Else set the context inside the sock_db structure
if (session->ctx != ctx) {
// Free previous context
httpd_sess_free_ctx(&session->ctx, session->free_ctx);
session->ctx = ctx;
}
session->free_ctx = free_fn;
}
void *httpd_sess_get_transport_ctx(httpd_handle_t handle, int sockfd)
{
struct sock_db *session = httpd_sess_get(handle, sockfd);
return session ? session->transport_ctx : NULL;
}
void httpd_sess_set_transport_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t free_fn)
{
struct sock_db *session = httpd_sess_get(handle, sockfd);
if (!session) {
return;
}
if (session->transport_ctx != ctx) {
// Free previous transport context
httpd_sess_free_ctx(&session->transport_ctx, session->free_transport_ctx);
session->transport_ctx = ctx;
}
session->free_transport_ctx = free_fn;
}
void httpd_sess_set_descriptors(struct httpd_data *hd, fd_set *fdset, int *maxfd)
{
enum_context_t context = {
.task = HTTPD_TASK_SET_DESCRIPTOR,
.max_fd = -1,
.fdset = fdset
};
httpd_sess_enum(hd, enum_function, &context);
if (maxfd) {
*maxfd = context.max_fd;
}
}
void httpd_sess_delete_invalid(struct httpd_data *hd)
{
enum_context_t context = {
.task = HTTPD_TASK_DELETE_INVALID,
.hd = hd
};
httpd_sess_enum(hd, enum_function, &context);
}
void httpd_sess_delete(struct httpd_data *hd, struct sock_db *session)
{
if ((!hd) || (!session) || (session->fd < 0)) {
return;
}
ESP_LOGD(TAG, LOG_FMT("fd = %d"), session->fd);
if (hd->config.enable_so_linger) {
struct linger so_linger = {
.l_onoff = true,
.l_linger = hd->config.linger_timeout,
};
if (setsockopt(session->fd, SOL_SOCKET, SO_LINGER, &so_linger, sizeof(struct linger)) < 0) {
ESP_LOGW(TAG, LOG_FMT("error enabling SO_LINGER (%d)"), errno);
}
}
// Call close function if defined
if (hd->config.close_fn) {
hd->config.close_fn(hd, session->fd);
} else {
close(session->fd);
}
hd->http_server_state = HTTP_SERVER_EVENT_DISCONNECTED;
esp_http_server_dispatch_event(HTTP_SERVER_EVENT_DISCONNECTED, &session->fd, sizeof(int));
// clear all contexts
httpd_sess_clear_ctx(session);
// mark session slot as available
session->fd = -1;
// decrement number of sessions
hd->hd_sd_active_count--;
ESP_LOGD(TAG, LOG_FMT("active sockets: %d"), hd->hd_sd_active_count);
if (!hd->hd_sd_active_count) {
hd->lru_counter = 0;
}
}
void httpd_sess_init(struct httpd_data *hd)
{
enum_context_t context = {
.task = HTTPD_TASK_INIT
};
httpd_sess_enum(hd, enum_function, &context);
}
bool httpd_sess_pending(struct httpd_data *hd, struct sock_db *session)
{
if (!session) {
return false;
}
if (session->pending_fn) {
// test if there's any data to be read (besides read() function, which is handled by select() in the main httpd loop)
// this should check e.g. for the SSL data buffer
if (session->pending_fn(hd, session->fd) > 0) {
return true;
}
}
return (session->pending_len != 0);
}
/* This MUST return ESP_OK on successful execution. If any other
* value is returned, everything related to this socket will be
* cleaned up and the socket will be closed.
*/
esp_err_t httpd_sess_process(struct httpd_data *hd, struct sock_db *session)
{
if ((!hd) || (!session)) {
return ESP_FAIL;
}
ESP_LOGD(TAG, LOG_FMT("httpd_req_new"));
if (httpd_req_new(hd, session) != ESP_OK) {
return ESP_FAIL;
}
ESP_LOGD(TAG, LOG_FMT("httpd_req_delete"));
if (httpd_req_delete(hd) != ESP_OK) {
return ESP_FAIL;
}
ESP_LOGD(TAG, LOG_FMT("success"));
session->lru_counter = ++hd->lru_counter;
return ESP_OK;
}
esp_err_t httpd_sess_update_lru_counter(httpd_handle_t handle, int sockfd)
{
if (handle == NULL) {
return ESP_ERR_INVALID_ARG;
}
struct httpd_data *hd = (struct httpd_data *) handle;
enum_context_t context = {
.task = HTTPD_TASK_FIND_FD,
.fd = sockfd
};
httpd_sess_enum(hd, enum_function, &context);
if (context.session) {
context.session->lru_counter = ++hd->lru_counter;
return ESP_OK;
}
return ESP_ERR_NOT_FOUND;
}
esp_err_t httpd_sess_close_lru(struct httpd_data *hd)
{
enum_context_t context = {
.task = HTTPD_TASK_FIND_LOWEST_LRU,
.lru_counter = UINT64_MAX,
.fd = -1
};
httpd_sess_enum(hd, enum_function, &context);
if (!context.session) {
return ESP_OK;
}
ESP_LOGD(TAG, LOG_FMT("Closing session with fd %d"), context.session->fd);
context.session->lru_socket = true;
return httpd_sess_trigger_close_(hd, context.session);
}
esp_err_t httpd_sess_trigger_close_(httpd_handle_t handle, struct sock_db *session)
{
if (!session) {
return ESP_ERR_NOT_FOUND;
}
return httpd_queue_work(handle, httpd_sess_close, session);
}
esp_err_t httpd_sess_trigger_close(httpd_handle_t handle, int sockfd)
{
struct sock_db *session = httpd_sess_get(handle, sockfd);
if (!session) {
return ESP_ERR_NOT_FOUND;
}
return httpd_sess_trigger_close_(handle, session);
}
void httpd_sess_close_all(struct httpd_data *hd)
{
enum_context_t context = {
.task = HTTPD_TASK_CLOSE,
.hd = hd
};
httpd_sess_enum(hd, enum_function, &context);
}
esp_err_t httpd_sess_close_lru_direct(struct httpd_data *hd)
{
enum_context_t context = {
.task = HTTPD_TASK_FIND_LOWEST_LRU,
.lru_counter = UINT64_MAX,
.fd = -1
};
httpd_sess_enum(hd, enum_function, &context);
if (!context.session) {
return ESP_OK;
}
ESP_LOGD(TAG, LOG_FMT("Directly closing session with fd %d"), context.session->fd);
// Call httpd_sess_delete directly instead of going through work queue
httpd_sess_delete(hd, context.session);
return ESP_OK;
}
+848
View File
@@ -0,0 +1,848 @@
/*
* SPDX-FileCopyrightText: 2018-2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <errno.h>
#include <esp_log.h>
#include <esp_err.h>
#include <esp_http_server.h>
#include "esp_httpd_priv.h"
#include <netinet/tcp.h>
#include "ctrl_sock.h"
static const char *TAG = "httpd_txrx";
esp_err_t httpd_sess_set_send_override(httpd_handle_t hd, int sockfd, httpd_send_func_t send_func)
{
struct sock_db *sess = httpd_sess_get(hd, sockfd);
if (!sess) {
return ESP_ERR_INVALID_ARG;
}
sess->send_fn = send_func;
return ESP_OK;
}
esp_err_t httpd_sess_set_recv_override(httpd_handle_t hd, int sockfd, httpd_recv_func_t recv_func)
{
struct sock_db *sess = httpd_sess_get(hd, sockfd);
if (!sess) {
return ESP_ERR_INVALID_ARG;
}
sess->recv_fn = recv_func;
return ESP_OK;
}
esp_err_t httpd_sess_set_pending_override(httpd_handle_t hd, int sockfd, httpd_pending_func_t pending_func)
{
struct sock_db *sess = httpd_sess_get(hd, sockfd);
if (!sess) {
return ESP_ERR_INVALID_ARG;
}
sess->pending_fn = pending_func;
return ESP_OK;
}
int httpd_send(httpd_req_t *r, const char *buf, size_t buf_len)
{
if (r == NULL || buf == NULL) {
return HTTPD_SOCK_ERR_INVALID;
}
if (!httpd_valid_req(r)) {
return HTTPD_SOCK_ERR_INVALID;
}
struct httpd_req_aux *ra = r->aux;
int ret = ra->sd->send_fn(ra->sd->handle, ra->sd->fd, buf, buf_len, 0);
if (ret < 0) {
ESP_LOGD(TAG, LOG_FMT("error in send_fn"));
return ret;
}
return ret;
}
static esp_err_t httpd_send_all(httpd_req_t *r, const char *buf, size_t buf_len)
{
struct httpd_req_aux *ra = r->aux;
int ret;
while (buf_len > 0) {
ret = ra->sd->send_fn(ra->sd->handle, ra->sd->fd, buf, buf_len, 0);
if (ret < 0) {
ESP_LOGD(TAG, LOG_FMT("error in send_fn"));
return ESP_FAIL;
}
ESP_LOGD(TAG, LOG_FMT("sent = %d"), ret);
buf += ret;
buf_len -= ret;
}
return ESP_OK;
}
static size_t httpd_recv_pending(httpd_req_t *r, char *buf, size_t buf_len)
{
struct httpd_req_aux *ra = r->aux;
size_t offset = sizeof(ra->sd->pending_data) - ra->sd->pending_len;
/* buf_len must not be greater than remaining_len */
buf_len = MIN(ra->sd->pending_len, buf_len);
memcpy(buf, ra->sd->pending_data + offset, buf_len);
ra->sd->pending_len -= buf_len;
return buf_len;
}
int httpd_recv_with_opt(httpd_req_t *r, char *buf, size_t buf_len, httpd_recv_opt_t opt)
{
ESP_LOGD(TAG, LOG_FMT("requested length = %"NEWLIB_NANO_COMPAT_FORMAT), NEWLIB_NANO_COMPAT_CAST(buf_len));
size_t pending_len = 0;
struct httpd_req_aux *ra = r->aux;
/* First fetch pending data from local buffer */
if (ra->sd->pending_len > 0) {
ESP_LOGD(TAG, LOG_FMT("pending length = %"NEWLIB_NANO_COMPAT_FORMAT), NEWLIB_NANO_COMPAT_CAST(ra->sd->pending_len));
pending_len = httpd_recv_pending(r, buf, buf_len);
buf += pending_len;
buf_len -= pending_len;
/* If buffer filled then no need to recv.
* If asked to halt after receiving pending data then
* return with received length */
if (!buf_len || opt == HTTPD_RECV_OPT_HALT_AFTER_PENDING) {
return pending_len;
}
}
/* Receive data of remaining length */
size_t recv_len = pending_len;
do {
int ret = ra->sd->recv_fn(ra->sd->handle, ra->sd->fd, buf, buf_len, 0);
if (ret <= 0) {
ESP_LOGD(TAG, LOG_FMT("error in recv_fn"));
if ((ret == HTTPD_SOCK_ERR_TIMEOUT) && (pending_len != 0)) {
/* If recv() timeout occurred, but pending data is
* present, return length of pending data.
* This behavior is similar to that of socket recv()
* function, which, in case has only partially read the
* requested length, due to timeout, returns with read
* length, rather than error */
return pending_len;
}
return ret;
}
recv_len += ret;
buf += ret;
buf_len -= ret;
} while (buf_len > 0 && opt == HTTPD_RECV_OPT_BLOCKING);
ESP_LOGD(TAG, LOG_FMT("received length = %"NEWLIB_NANO_COMPAT_FORMAT), NEWLIB_NANO_COMPAT_CAST(recv_len));
return recv_len;
}
int httpd_recv(httpd_req_t *r, char *buf, size_t buf_len)
{
return httpd_recv_with_opt(r, buf, buf_len, HTTPD_RECV_OPT_NONE);
}
size_t httpd_unrecv(struct httpd_req *r, const char *buf, size_t buf_len)
{
struct httpd_req_aux *ra = r->aux;
/* Truncate if external buf_len is greater than pending_data buffer size */
ra->sd->pending_len = MIN(sizeof(ra->sd->pending_data), buf_len);
/* Copy data into internal pending_data buffer with the exact offset
* such that it is right aligned inside the buffer */
size_t offset = sizeof(ra->sd->pending_data) - ra->sd->pending_len;
memcpy(ra->sd->pending_data + offset, buf, ra->sd->pending_len);
ESP_LOGD(TAG, LOG_FMT("length = %"NEWLIB_NANO_COMPAT_FORMAT), NEWLIB_NANO_COMPAT_CAST(ra->sd->pending_len));
return ra->sd->pending_len;
}
/**
* This API appends an additional header field-value pair in the HTTP response.
* But the header isn't sent out until any of the send APIs is executed.
*/
esp_err_t httpd_resp_set_hdr(httpd_req_t *r, const char *field, const char *value)
{
if (r == NULL || field == NULL || value == NULL) {
return ESP_ERR_INVALID_ARG;
}
if (!httpd_valid_req(r)) {
return ESP_ERR_HTTPD_INVALID_REQ;
}
/* Reject CRLF in header field or value */
if (strpbrk(field, "\r\n") || strpbrk(value, "\r\n")) {
ESP_LOGW(TAG, LOG_FMT("rejecting header with CRLF: %.32s"), field);
return ESP_ERR_INVALID_ARG;
}
struct httpd_req_aux *ra = r->aux;
struct httpd_data *hd = (struct httpd_data *) r->handle;
/* Number of additional headers is limited */
if (ra->resp_hdrs_count >= hd->config.max_resp_headers) {
return ESP_ERR_HTTPD_RESP_HDR;
}
/* Assign header field-value pair */
ra->resp_hdrs[ra->resp_hdrs_count].field = field;
ra->resp_hdrs[ra->resp_hdrs_count].value = value;
ra->resp_hdrs_count++;
ESP_LOGD(TAG, LOG_FMT("new header = %s: %s"), field, value);
return ESP_OK;
}
/**
* This API sets the status of the HTTP response to the value specified.
* But the status isn't sent out until any of the send APIs is executed.
*/
esp_err_t httpd_resp_set_status(httpd_req_t *r, const char *status)
{
if (r == NULL || status == NULL) {
return ESP_ERR_INVALID_ARG;
}
if (!httpd_valid_req(r)) {
return ESP_ERR_HTTPD_INVALID_REQ;
}
/* Reject CRLF in status */
if (strpbrk(status, "\r\n")) {
ESP_LOGW(TAG, LOG_FMT("rejecting status with CRLF: %.32s"), status);
return ESP_ERR_INVALID_ARG;
}
struct httpd_req_aux *ra = r->aux;
ra->status = (char *)status;
return ESP_OK;
}
/**
* This API sets the method/type of the HTTP response to the value specified.
* But the method isn't sent out until any of the send APIs is executed.
*/
esp_err_t httpd_resp_set_type(httpd_req_t *r, const char *type)
{
if (r == NULL || type == NULL) {
return ESP_ERR_INVALID_ARG;
}
if (!httpd_valid_req(r)) {
return ESP_ERR_HTTPD_INVALID_REQ;
}
/* Reject CRLF in content type */
if (strpbrk(type, "\r\n")) {
ESP_LOGW(TAG, LOG_FMT("rejecting content type with CRLF: %.32s"), type);
return ESP_ERR_INVALID_ARG;
}
struct httpd_req_aux *ra = r->aux;
ra->content_type = (char *)type;
return ESP_OK;
}
esp_err_t httpd_resp_send(httpd_req_t *r, const char *buf, ssize_t buf_len)
{
if (r == NULL) {
return ESP_ERR_INVALID_ARG;
}
if (!httpd_valid_req(r)) {
return ESP_ERR_HTTPD_INVALID_REQ;
}
struct httpd_req_aux *ra = r->aux;
const char *httpd_hdr_str = "HTTP/1.1 %s\r\nContent-Type: %s\r\nContent-Length: %d\r\n";
const char *colon_separator = ": ";
const char *cr_lf_seperator = "\r\n";
if (buf_len == HTTPD_RESP_USE_STRLEN) {
buf_len = strlen(buf);
}
/* Request headers are no longer available */
ra->req_hdrs_count = 0;
/* Calculate the size of the headers. +1 for the null terminator */
size_t required_size = snprintf(NULL, 0, httpd_hdr_str, ra->status, ra->content_type, buf_len) + 1;
if (required_size > ra->max_req_hdr_len) {
return ESP_ERR_HTTPD_RESP_HDR;
}
char *res_buf = malloc(required_size); /* Temporary buffer to store the headers */
if (res_buf == NULL) {
ESP_LOGE(TAG, "Unable to allocate httpd send buffer");
return ESP_ERR_HTTPD_ALLOC_MEM;
}
esp_err_t ret = snprintf(res_buf, required_size, httpd_hdr_str, ra->status, ra->content_type, buf_len);
if (ret < 0 || ret >= required_size) {
free(res_buf);
return ESP_ERR_HTTPD_RESP_HDR;
}
ESP_LOGD(TAG, "httpd send buffer size = %d", strlen(res_buf));
ret = httpd_send_all(r, res_buf, strlen(res_buf));
free(res_buf);
if (ret != ESP_OK) {
return ESP_ERR_HTTPD_RESP_SEND;
}
/* Sending additional headers based on set_header */
for (unsigned i = 0; i < ra->resp_hdrs_count; i++) {
/* Send header field */
if (httpd_send_all(r, ra->resp_hdrs[i].field, strlen(ra->resp_hdrs[i].field)) != ESP_OK) {
return ESP_ERR_HTTPD_RESP_SEND;
}
/* Send ': ' */
if (httpd_send_all(r, colon_separator, strlen(colon_separator)) != ESP_OK) {
return ESP_ERR_HTTPD_RESP_SEND;
}
/* Send header value */
if (httpd_send_all(r, ra->resp_hdrs[i].value, strlen(ra->resp_hdrs[i].value)) != ESP_OK) {
return ESP_ERR_HTTPD_RESP_SEND;
}
/* Send CR + LF */
if (httpd_send_all(r, cr_lf_seperator, strlen(cr_lf_seperator)) != ESP_OK) {
return ESP_ERR_HTTPD_RESP_SEND;
}
}
/* End header section */
if (httpd_send_all(r, cr_lf_seperator, strlen(cr_lf_seperator)) != ESP_OK) {
return ESP_ERR_HTTPD_RESP_SEND;
}
struct httpd_data *hd = (struct httpd_data *) r->handle;
hd->http_server_state = HTTP_SERVER_EVENT_HEADERS_SENT;
esp_http_server_dispatch_event(HTTP_SERVER_EVENT_HEADERS_SENT, &(ra->sd->fd), sizeof(int));
/* Sending content */
if (buf && buf_len) {
if (httpd_send_all(r, buf, buf_len) != ESP_OK) {
return ESP_ERR_HTTPD_RESP_SEND;
}
}
esp_http_server_event_data evt_data = {
.fd = ra->sd->fd,
.data_len = buf_len,
};
hd->http_server_state = HTTP_SERVER_EVENT_SENT_DATA;
esp_http_server_dispatch_event(HTTP_SERVER_EVENT_SENT_DATA, &evt_data, sizeof(esp_http_server_event_data));
return ESP_OK;
}
esp_err_t httpd_resp_send_chunk(httpd_req_t *r, const char *buf, ssize_t buf_len)
{
if (r == NULL) {
return ESP_ERR_INVALID_ARG;
}
if (!httpd_valid_req(r)) {
return ESP_ERR_HTTPD_INVALID_REQ;
}
if (buf_len == HTTPD_RESP_USE_STRLEN) {
buf_len = strlen(buf);
}
struct httpd_req_aux *ra = r->aux;
struct httpd_data *hd = (struct httpd_data *) r->handle;
const char *httpd_chunked_hdr_str = "HTTP/1.1 %s\r\nContent-Type: %s\r\nTransfer-Encoding: chunked\r\n";
const char *colon_separator = ": ";
const char *cr_lf_seperator = "\r\n";
/* Request headers are no longer available */
ra->req_hdrs_count = 0;
if (!ra->first_chunk_sent) {
/* Calculate the size of the headers. +1 for the null terminator */
size_t required_size = snprintf(NULL, 0, httpd_chunked_hdr_str, ra->status, ra->content_type) + 1;
if (required_size > ra->max_req_hdr_len) {
return ESP_ERR_HTTPD_RESP_HDR;
}
char *res_buf = malloc(required_size); /* Temporary buffer to store the headers */
if (res_buf == NULL) {
ESP_LOGE(TAG, "Unable to allocate httpd send chunk buffer");
return ESP_ERR_HTTPD_ALLOC_MEM;
}
esp_err_t ret = snprintf(res_buf, required_size, httpd_chunked_hdr_str, ra->status, ra->content_type);
if (ret < 0 || ret >= required_size) {
free(res_buf);
return ESP_ERR_HTTPD_RESP_HDR;
}
ESP_LOGD(TAG, "httpd send chunk buffer size = %d", strlen(res_buf));
/* Size of essential headers is limited by scratch buffer size */
ret = httpd_send_all(r, res_buf, strlen(res_buf));
free(res_buf);
if (ret != ESP_OK) {
return ESP_ERR_HTTPD_RESP_SEND;
}
/* Sending additional headers based on set_header */
for (unsigned i = 0; i < ra->resp_hdrs_count; i++) {
/* Send header field */
if (httpd_send_all(r, ra->resp_hdrs[i].field, strlen(ra->resp_hdrs[i].field)) != ESP_OK) {
return ESP_ERR_HTTPD_RESP_SEND;
}
/* Send ': ' */
if (httpd_send_all(r, colon_separator, strlen(colon_separator)) != ESP_OK) {
return ESP_ERR_HTTPD_RESP_SEND;
}
/* Send header value */
if (httpd_send_all(r, ra->resp_hdrs[i].value, strlen(ra->resp_hdrs[i].value)) != ESP_OK) {
return ESP_ERR_HTTPD_RESP_SEND;
}
/* Send CR + LF */
if (httpd_send_all(r, cr_lf_seperator, strlen(cr_lf_seperator)) != ESP_OK) {
return ESP_ERR_HTTPD_RESP_SEND;
}
}
/* End header section */
if (httpd_send_all(r, cr_lf_seperator, strlen(cr_lf_seperator)) != ESP_OK) {
return ESP_ERR_HTTPD_RESP_SEND;
}
ra->first_chunk_sent = true;
}
/* Sending chunked content */
char len_str[10];
snprintf(len_str, sizeof(len_str), "%lx\r\n", (long)buf_len);
if (httpd_send_all(r, len_str, strlen(len_str)) != ESP_OK) {
return ESP_ERR_HTTPD_RESP_SEND;
}
if (buf) {
if (httpd_send_all(r, buf, (size_t) buf_len) != ESP_OK) {
return ESP_ERR_HTTPD_RESP_SEND;
}
}
/* Indicate end of chunk */
if (httpd_send_all(r, "\r\n", strlen("\r\n")) != ESP_OK) {
return ESP_ERR_HTTPD_RESP_SEND;
}
esp_http_server_event_data evt_data = {
.fd = ra->sd->fd,
.data_len = buf_len,
};
hd->http_server_state = HTTP_SERVER_EVENT_SENT_DATA;
esp_http_server_dispatch_event(HTTP_SERVER_EVENT_SENT_DATA, &evt_data, sizeof(esp_http_server_event_data));
return ESP_OK;
}
esp_err_t httpd_resp_send_err(httpd_req_t *req, httpd_err_code_t error, const char *usr_msg)
{
esp_err_t ret;
const char *msg;
const char *status;
switch (error) {
case HTTPD_501_METHOD_NOT_IMPLEMENTED:
status = "501 Method Not Implemented";
msg = "Server does not support this method";
break;
case HTTPD_505_VERSION_NOT_SUPPORTED:
status = "505 Version Not Supported";
msg = "HTTP version not supported by server";
break;
case HTTPD_400_BAD_REQUEST:
status = "400 Bad Request";
msg = "Bad request syntax";
break;
case HTTPD_401_UNAUTHORIZED:
status = "401 Unauthorized";
msg = "No permission -- see authorization schemes";
break;
case HTTPD_403_FORBIDDEN:
status = "403 Forbidden";
msg = "Request forbidden -- authorization will not help";
break;
case HTTPD_404_NOT_FOUND:
status = "404 Not Found";
msg = "Nothing matches the given URI";
break;
case HTTPD_405_METHOD_NOT_ALLOWED:
status = "405 Method Not Allowed";
msg = "Specified method is invalid for this resource";
break;
case HTTPD_408_REQ_TIMEOUT:
status = "408 Request Timeout";
msg = "Server closed this connection";
break;
case HTTPD_414_URI_TOO_LONG:
status = "414 URI Too Long";
msg = "URI is too long";
break;
case HTTPD_411_LENGTH_REQUIRED:
status = "411 Length Required";
msg = "Client must specify Content-Length";
break;
case HTTPD_413_CONTENT_TOO_LARGE:
status = "413 Content Too Large";
msg = "Content is too large";
break;
case HTTPD_431_REQ_HDR_FIELDS_TOO_LARGE:
status = "431 Request Header Fields Too Large";
msg = "Header fields are too long";
break;
case HTTPD_500_INTERNAL_SERVER_ERROR:
default:
status = "500 Internal Server Error";
msg = "Server has encountered an unexpected error";
}
/* If user has provided custom message, override default message */
msg = usr_msg ? usr_msg : msg;
ESP_LOGW(TAG, LOG_FMT("%s - %s"), status, msg);
/* Set error code in HTTP response */
httpd_resp_set_status(req, status);
httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
#ifdef CONFIG_HTTPD_ERR_RESP_NO_DELAY
/* Use TCP_NODELAY option to force socket to send data in buffer
* This ensures that the error message is sent before the socket
* is closed */
struct httpd_req_aux *ra = req->aux;
int nodelay = 1;
if (setsockopt(ra->sd->fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)) < 0) {
/* If failed to turn on TCP_NODELAY, throw warning and continue */
ESP_LOGW(TAG, LOG_FMT("error calling setsockopt : %d"), errno);
nodelay = 0;
}
#endif
/* Send HTTP error message */
ret = httpd_resp_send(req, msg, HTTPD_RESP_USE_STRLEN);
#ifdef CONFIG_HTTPD_ERR_RESP_NO_DELAY
/* If TCP_NODELAY was set successfully above, time to disable it */
if (nodelay == 1) {
nodelay = 0;
if (setsockopt(ra->sd->fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)) < 0) {
/* If failed to turn off TCP_NODELAY, throw error and
* return failure to signal for socket closure */
ESP_LOGE(TAG, LOG_FMT("error calling setsockopt : %d"), errno);
return ESP_ERR_INVALID_STATE;
}
}
#endif
esp_http_server_dispatch_event(HTTP_SERVER_EVENT_ERROR, &error, sizeof(httpd_err_code_t));
return ret;
}
esp_err_t httpd_resp_send_custom_err(httpd_req_t *req, const char *status, const char *msg)
{
ESP_LOGW(TAG, LOG_FMT("%s - %s"), status, msg);
/* Set error code in HTTP response */
httpd_resp_set_status(req, status);
httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
#ifdef CONFIG_HTTPD_ERR_RESP_NO_DELAY
/* Use TCP_NODELAY option to force socket to send data in buffer
* This ensures that the error message is sent before the socket
* is closed */
struct httpd_req_aux *ra = req->aux;
int nodelay = 1;
if (setsockopt(ra->sd->fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)) < 0) {
/* If failed to turn on TCP_NODELAY, throw warning and continue */
ESP_LOGW(TAG, LOG_FMT("error calling setsockopt : %d"), errno);
nodelay = 0;
}
#endif
/* Send HTTP error message */
esp_err_t ret = httpd_resp_send(req, msg, HTTPD_RESP_USE_STRLEN);
#ifdef CONFIG_HTTPD_ERR_RESP_NO_DELAY
/* If TCP_NODELAY was set successfully above, time to disable it */
if (nodelay == 1) {
nodelay = 0;
if (setsockopt(ra->sd->fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)) < 0) {
/* If failed to turn off TCP_NODELAY, throw error and
* return failure to signal for socket closure */
ESP_LOGE(TAG, LOG_FMT("error calling setsockopt : %d"), errno);
return ESP_ERR_INVALID_STATE;
}
}
#endif
return ret;
}
esp_err_t httpd_register_err_handler(httpd_handle_t handle,
httpd_err_code_t error,
httpd_err_handler_func_t err_handler_fn)
{
if (handle == NULL || error >= HTTPD_ERR_CODE_MAX) {
return ESP_ERR_INVALID_ARG;
}
struct httpd_data *hd = (struct httpd_data *) handle;
hd->err_handler_fns[error] = err_handler_fn;
return ESP_OK;
}
esp_err_t httpd_req_handle_err(httpd_req_t *req, httpd_err_code_t error)
{
struct httpd_data *hd = (struct httpd_data *) req->handle;
esp_err_t ret;
/* Invoke custom error handler if configured */
if (hd->err_handler_fns[error]) {
ret = hd->err_handler_fns[error](req, error);
/* If error code is 500, force return failure
* irrespective of the handler's return value */
ret = (error == HTTPD_500_INTERNAL_SERVER_ERROR ? ESP_FAIL : ret);
} else {
/* If no handler is registered for this error default
* behavior is to send the HTTP error response and
* return failure for closure of underlying socket */
httpd_resp_send_err(req, error, NULL);
ret = ESP_FAIL;
}
return ret;
}
int httpd_req_recv(httpd_req_t *r, char *buf, size_t buf_len)
{
if (r == NULL || buf == NULL) {
return HTTPD_SOCK_ERR_INVALID;
}
if (!httpd_valid_req(r)) {
ESP_LOGW(TAG, LOG_FMT("invalid request"));
return HTTPD_SOCK_ERR_INVALID;
}
struct httpd_req_aux *ra = r->aux;
ESP_LOGD(TAG, LOG_FMT("remaining length = %"NEWLIB_NANO_COMPAT_FORMAT), NEWLIB_NANO_COMPAT_CAST(ra->remaining_len));
if (buf_len > ra->remaining_len) {
buf_len = ra->remaining_len;
}
if (buf_len == 0) {
return buf_len;
}
int ret = httpd_recv(r, buf, buf_len);
if (ret < 0) {
ESP_LOGD(TAG, LOG_FMT("error in httpd_recv"));
return ret;
}
ra->remaining_len -= ret;
ESP_LOGD(TAG, LOG_FMT("received length = %d"), ret);
struct httpd_data *hd = (struct httpd_data *) r->handle;
hd->http_server_state = HTTP_SERVER_EVENT_ON_DATA;
esp_http_server_event_data evt_data = {
.fd = ra->sd->fd,
.data_len = ret,
};
esp_http_server_dispatch_event(HTTP_SERVER_EVENT_ON_DATA, &evt_data, sizeof(esp_http_server_event_data));
return ret;
}
esp_err_t httpd_req_async_handler_begin(httpd_req_t *r, httpd_req_t **out)
{
if (r == NULL || out == NULL) {
return ESP_ERR_INVALID_ARG;
}
// alloc async req
httpd_req_t *async = malloc(sizeof(httpd_req_t));
if (async == NULL) {
return ESP_ERR_NO_MEM;
}
memcpy(async, r, sizeof(httpd_req_t));
// alloc async aux
async->aux = malloc(sizeof(struct httpd_req_aux));
if (async->aux == NULL) {
free(async);
return ESP_ERR_NO_MEM;
}
memcpy(async->aux, r->aux, sizeof(struct httpd_req_aux));
// Copy response header block
struct httpd_data *hd = (struct httpd_data *) r->handle;
struct httpd_req_aux *async_aux = (struct httpd_req_aux *) async->aux;
struct httpd_req_aux *r_aux = (struct httpd_req_aux *) r->aux;
if (r_aux->scratch) {
async_aux->scratch = malloc(r_aux->scratch_cur_size);
if (async_aux->scratch == NULL) {
free(async_aux);
free(async);
return ESP_ERR_NO_MEM;
}
memcpy(async_aux->scratch, r_aux->scratch, r_aux->scratch_cur_size);
} else {
async_aux->scratch = NULL;
}
async_aux->resp_hdrs = calloc(hd->config.max_resp_headers, sizeof(struct resp_hdr));
if (async_aux->resp_hdrs == NULL) {
free(async_aux->scratch);
free(async_aux);
free(async);
return ESP_ERR_NO_MEM;
}
memcpy(async_aux->resp_hdrs, r_aux->resp_hdrs, hd->config.max_resp_headers * sizeof(struct resp_hdr));
// Prevent the main thread from reading the rest of the request after the handler returns.
r_aux->remaining_len = 0;
// mark socket as "in use"
r_aux->sd->for_async_req = true;
*out = async;
return ESP_OK;
}
esp_err_t httpd_req_async_handler_complete(httpd_req_t *r)
{
if (r == NULL) {
return ESP_ERR_INVALID_ARG;
}
// Get server handle and control socket info before freeing the request
struct httpd_data *hd = (struct httpd_data *) r->handle;
int msg_fd = hd->msg_fd;
int port = hd->config.ctrl_port;
struct httpd_req_aux *ra = r->aux;
ra->sd->for_async_req = false;
free(ra->scratch);
ra->scratch = NULL;
ra->scratch_cur_size = 0;
ra->scratch_size_limit = 0;
free(ra->resp_hdrs);
free(r->aux);
free(r);
// Send a dummy control message(httpd_ctrl_data) to unblock the main HTTP server task from the select() call.
// Since the current connection FD was marked as inactive for async requests, the main task
// will now re-add this FD to its select() descriptor list. This ensures that subsequent requests
// on the same FD are processed correctly
struct httpd_ctrl_data msg = {.hc_msg = HTTPD_CTRL_MAX};
/* Reserve an mbox slot so we don't overrun ctrl_sock_semaphore's
* accounting and starve concurrent httpd_queue_work() producers. The
* httpd main task is the consumer and will drain the mbox shortly. */
if (xSemaphoreTake(hd->ctrl_sock_semaphore, portMAX_DELAY) != pdTRUE) {
ESP_LOGW(TAG, LOG_FMT("failed to acquire ctrl socket semaphore"));
return ESP_FAIL;
}
int ret = cs_send_to_ctrl_sock(msg_fd, port, &msg, sizeof(msg));
if (ret < 0) {
ESP_LOGW(TAG, LOG_FMT("failed to send socket notification"));
xSemaphoreGive(hd->ctrl_sock_semaphore);
return ESP_FAIL;
}
ESP_LOGD(TAG, LOG_FMT("socket notification sent"));
return ESP_OK;
}
int httpd_req_to_sockfd(httpd_req_t *r)
{
if (r == NULL) {
return -1;
}
if (!httpd_valid_req(r)) {
ESP_LOGW(TAG, LOG_FMT("invalid request"));
return -1;
}
struct httpd_req_aux *ra = r->aux;
return ra->sd->fd;
}
static int httpd_sock_err(const char *ctx, int sockfd)
{
int errval;
ESP_LOGW(TAG, LOG_FMT("error in %s : %d"), ctx, errno);
switch (errno) {
case EAGAIN:
case EINTR:
errval = HTTPD_SOCK_ERR_TIMEOUT;
break;
case EINVAL:
case EBADF:
case EFAULT:
case ENOTSOCK:
errval = HTTPD_SOCK_ERR_INVALID;
break;
default:
errval = HTTPD_SOCK_ERR_FAIL;
}
return errval;
}
int httpd_default_send(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags)
{
(void)hd;
if (buf == NULL) {
return HTTPD_SOCK_ERR_INVALID;
}
int ret = send(sockfd, buf, buf_len, flags);
if (ret < 0) {
return httpd_sock_err("send", sockfd);
}
return ret;
}
int httpd_default_recv(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags)
{
(void)hd;
if (buf == NULL) {
return HTTPD_SOCK_ERR_INVALID;
}
int ret = recv(sockfd, buf, buf_len, flags);
if (ret < 0) {
return httpd_sock_err("recv", sockfd);
}
return ret;
}
int httpd_socket_send(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags)
{
struct sock_db *sess = httpd_sess_get(hd, sockfd);
if (!sess) {
return HTTPD_SOCK_ERR_INVALID;
}
if (!sess->send_fn) {
return HTTPD_SOCK_ERR_INVALID;
}
return sess->send_fn(hd, sockfd, buf, buf_len, flags);
}
int httpd_socket_recv(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags)
{
struct sock_db *sess = httpd_sess_get(hd, sockfd);
if (!sess) {
return HTTPD_SOCK_ERR_INVALID;
}
if (!sess->recv_fn) {
return HTTPD_SOCK_ERR_INVALID;
}
return sess->recv_fn(hd, sockfd, buf, buf_len, flags);
}
+375
View File
@@ -0,0 +1,375 @@
/*
* SPDX-FileCopyrightText: 2018-2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <errno.h>
#include <esp_log.h>
#include <esp_err.h>
#include <http_parser.h>
#include <esp_http_server.h>
#include "esp_httpd_priv.h"
static const char *TAG = "httpd_uri";
static bool httpd_uri_match_simple(const char *uri1, const char *uri2, size_t len2)
{
return strlen(uri1) == len2 && // First match lengths
(strncmp(uri1, uri2, len2) == 0); // Then match actual URIs
}
bool httpd_uri_match_wildcard(const char *template, const char *uri, size_t len)
{
const size_t tpl_len = strlen(template);
size_t exact_match_chars = tpl_len;
/* Check for trailing question mark and asterisk */
const char last = (const char) (tpl_len > 0 ? template[tpl_len - 1] : 0);
const char prevlast = (const char) (tpl_len > 1 ? template[tpl_len - 2] : 0);
const bool asterisk = last == '*' || (prevlast == '*' && last == '?');
const bool quest = last == '?' || (prevlast == '?' && last == '*');
/* Minimum template string length must be:
* 0 : if neither of '*' and '?' are present
* 1 : if only '*' is present
* 2 : if only '?' is present
* 3 : if both are present
*
* The expression (asterisk + quest*2) serves as a
* case wise generator of these length values
*/
/* abort in cases such as "?" with no preceding character (invalid template) */
if (exact_match_chars < asterisk + quest*2) {
return false;
}
/* account for special characters and the optional character if "?" is used */
exact_match_chars -= asterisk + quest*2;
if (len < exact_match_chars) {
return false;
}
if (!quest) {
if (!asterisk && len != exact_match_chars) {
/* no special characters and different length - strncmp would return false */
return false;
}
/* asterisk allows arbitrary trailing characters, we ignore these using
* exact_match_chars as the length limit */
return (strncmp(template, uri, exact_match_chars) == 0);
} else {
/* question mark present */
if (len > exact_match_chars && template[exact_match_chars] != uri[exact_match_chars]) {
/* the optional character is present, but different */
return false;
}
if (strncmp(template, uri, exact_match_chars) != 0) {
/* the mandatory part differs */
return false;
}
/* Now we know the URI is longer than the required part of template,
* the mandatory part matches, and if the optional character is present, it is correct.
* Match is OK if we have asterisk, i.e. any trailing characters are OK, or if
* there are no characters beyond the optional character. */
return asterisk || len <= exact_match_chars + 1;
}
}
/* Find handler with matching URI and method, and set
* appropriate error code if URI or method not found */
static httpd_uri_t* httpd_find_uri_handler(struct httpd_data *hd,
const char *uri, size_t uri_len,
httpd_method_t method,
httpd_err_code_t *err)
{
if (err) {
*err = HTTPD_404_NOT_FOUND;
}
for (int i = 0; i < hd->config.max_uri_handlers; i++) {
if (!hd->hd_calls[i]) {
break;
}
ESP_LOGD(TAG, LOG_FMT("[%d] = %s"), i, hd->hd_calls[i]->uri);
/* Check if custom URI matching function is set,
* else use simple string compare */
if (hd->config.uri_match_fn ?
hd->config.uri_match_fn(hd->hd_calls[i]->uri, uri, uri_len) :
httpd_uri_match_simple(hd->hd_calls[i]->uri, uri, uri_len)) {
/* URIs match. Now check if method is supported */
if (hd->hd_calls[i]->method == method || hd->hd_calls[i]->method == HTTP_ANY) {
/* Match found! */
if (err) {
/* Unset any error that may
* have been set earlier */
*err = 0;
}
return hd->hd_calls[i];
}
/* URI found but method not allowed.
* If URI is found later then this
* error must be set to 0 */
if (err) {
*err = HTTPD_405_METHOD_NOT_ALLOWED;
}
}
}
return NULL;
}
esp_err_t httpd_register_uri_handler(httpd_handle_t handle,
const httpd_uri_t *uri_handler)
{
if (handle == NULL || uri_handler == NULL) {
return ESP_ERR_INVALID_ARG;
}
struct httpd_data *hd = (struct httpd_data *) handle;
/* Make sure another handler with matching URI and method
* is not already registered. This will also catch cases
* when a registered URI wildcard pattern already accounts
* for the new URI being registered */
if (httpd_find_uri_handler(handle, uri_handler->uri,
strlen(uri_handler->uri),
uri_handler->method, NULL) != NULL) {
ESP_LOGW(TAG, LOG_FMT("handler %s with method %d already registered"),
uri_handler->uri, uri_handler->method);
return ESP_ERR_HTTPD_HANDLER_EXISTS;
}
for (int i = 0; i < hd->config.max_uri_handlers; i++) {
if (hd->hd_calls[i] == NULL) {
ESP_COMPILER_DIAGNOSTIC_PUSH_IGNORE("-Wanalyzer-malloc-leak") // False-positive detection. TODO GCC-366
hd->hd_calls[i] = malloc(sizeof(httpd_uri_t));
if (hd->hd_calls[i] == NULL) {
/* Failed to allocate memory */
return ESP_ERR_HTTPD_ALLOC_MEM;
}
ESP_COMPILER_DIAGNOSTIC_POP("-Wanalyzer-malloc-leak")
/* Copy URI string */
hd->hd_calls[i]->uri = strdup(uri_handler->uri);
if (hd->hd_calls[i]->uri == NULL) {
/* Failed to allocate memory */
free(hd->hd_calls[i]);
hd->hd_calls[i] = NULL;
return ESP_ERR_HTTPD_ALLOC_MEM;
}
/* Copy remaining members */
hd->hd_calls[i]->method = uri_handler->method;
hd->hd_calls[i]->handler = uri_handler->handler;
hd->hd_calls[i]->user_ctx = uri_handler->user_ctx;
#ifdef CONFIG_HTTPD_WS_PRE_HANDSHAKE_CB_SUPPORT
hd->hd_calls[i]->ws_pre_handshake_cb = uri_handler->ws_pre_handshake_cb;
#endif
#ifdef CONFIG_HTTPD_WS_POST_HANDSHAKE_CB_SUPPORT
hd->hd_calls[i]->ws_post_handshake_cb = uri_handler->ws_post_handshake_cb;
#endif
#ifdef CONFIG_HTTPD_WS_SUPPORT
hd->hd_calls[i]->is_websocket = uri_handler->is_websocket;
hd->hd_calls[i]->handle_ws_control_frames = uri_handler->handle_ws_control_frames;
if (uri_handler->supported_subprotocol) {
hd->hd_calls[i]->supported_subprotocol = strdup(uri_handler->supported_subprotocol);
if (hd->hd_calls[i]->supported_subprotocol == NULL) {
/* Failed to allocate memory */
free((void *)hd->hd_calls[i]->uri);
free(hd->hd_calls[i]);
hd->hd_calls[i] = NULL;
return ESP_ERR_HTTPD_ALLOC_MEM;
}
} else {
hd->hd_calls[i]->supported_subprotocol = NULL;
}
#endif
ESP_LOGD(TAG, LOG_FMT("[%d] installed %s"), i, uri_handler->uri);
return ESP_OK;
}
ESP_LOGD(TAG, LOG_FMT("[%d] exists %s"), i, hd->hd_calls[i]->uri);
}
ESP_LOGW(TAG, LOG_FMT("no slots left for registering handler"));
return ESP_ERR_HTTPD_HANDLERS_FULL;
}
esp_err_t httpd_unregister_uri_handler(httpd_handle_t handle,
const char *uri, httpd_method_t method)
{
if (handle == NULL || uri == NULL) {
return ESP_ERR_INVALID_ARG;
}
struct httpd_data *hd = (struct httpd_data *) handle;
for (int i = 0; i < hd->config.max_uri_handlers; i++) {
if (!hd->hd_calls[i]) {
break;
}
if ((hd->hd_calls[i]->method == method) && // First match methods
(strcmp(hd->hd_calls[i]->uri, uri) == 0)) { // Then match URI string
ESP_LOGD(TAG, LOG_FMT("[%d] removing %s"), i, hd->hd_calls[i]->uri);
free((char*)hd->hd_calls[i]->uri);
#ifdef CONFIG_HTTPD_WS_SUPPORT
free((char*)hd->hd_calls[i]->supported_subprotocol);
#endif // CONFIG_HTTPD_WS_SUPPORT
free(hd->hd_calls[i]);
hd->hd_calls[i] = NULL;
/* Shift the remaining non null handlers in the array
* forward by 1 so that order of insertion is maintained */
for (i += 1; i < hd->config.max_uri_handlers; i++) {
if (!hd->hd_calls[i]) {
break;
}
hd->hd_calls[i-1] = hd->hd_calls[i];
}
/* Nullify the following non null entry */
hd->hd_calls[i-1] = NULL;
return ESP_OK;
}
}
ESP_LOGW(TAG, LOG_FMT("handler %s with method %d not found"), uri, method);
return ESP_ERR_NOT_FOUND;
}
esp_err_t httpd_unregister_uri(httpd_handle_t handle, const char *uri)
{
if (handle == NULL || uri == NULL) {
return ESP_ERR_INVALID_ARG;
}
struct httpd_data *hd = (struct httpd_data *) handle;
bool found = false;
int i = 0, j = 0; // For keeping count of removed entries
for (; i < hd->config.max_uri_handlers; i++) {
if (!hd->hd_calls[i]) {
break;
}
if (strcmp(hd->hd_calls[i]->uri, uri) == 0) { // Match URI strings
ESP_LOGD(TAG, LOG_FMT("[%d] removing %s"), i, uri);
free((char*)hd->hd_calls[i]->uri);
#ifdef CONFIG_HTTPD_WS_SUPPORT
free((char*)hd->hd_calls[i]->supported_subprotocol);
#endif // CONFIG_HTTPD_WS_SUPPORT
free(hd->hd_calls[i]);
hd->hd_calls[i] = NULL;
found = true;
j++; // Update count of removed entries
} else {
/* Shift the remaining non null handlers in the array
* forward by j so that order of insertion is maintained */
hd->hd_calls[i-j] = hd->hd_calls[i];
}
}
/* Nullify the following non null entries */
for (int k = (i - j); k < i; k++) {
hd->hd_calls[k] = NULL;
}
if (!found) {
ESP_LOGW(TAG, LOG_FMT("no handler found for URI %s"), uri);
}
return (found ? ESP_OK : ESP_ERR_NOT_FOUND);
}
void httpd_unregister_all_uri_handlers(struct httpd_data *hd)
{
for (unsigned i = 0; i < hd->config.max_uri_handlers; i++) {
if (!hd->hd_calls[i]) {
break;
}
ESP_LOGD(TAG, LOG_FMT("[%d] removing %s"), i, hd->hd_calls[i]->uri);
free((char*)hd->hd_calls[i]->uri);
#ifdef CONFIG_HTTPD_WS_SUPPORT
free((char*)hd->hd_calls[i]->supported_subprotocol);
#endif // CONFIG_HTTPD_WS_SUPPORT
free(hd->hd_calls[i]);
hd->hd_calls[i] = NULL;
}
}
esp_err_t httpd_uri(struct httpd_data *hd)
{
httpd_uri_t *uri = NULL;
httpd_req_t *req = &hd->hd_req;
struct http_parser_url *res = &hd->hd_req_aux.url_parse_res;
/* For conveying URI not found/method not allowed */
httpd_err_code_t err = 0;
ESP_LOGD(TAG, LOG_FMT("request for %s with type %d"), req->uri, req->method);
/* URL parser result contains offset and length of path string */
if (res->field_set & (1 << UF_PATH)) {
uri = httpd_find_uri_handler(hd, req->uri + res->field_data[UF_PATH].off,
res->field_data[UF_PATH].len, req->method, &err);
}
/* If URI with method not found, respond with error code */
if (uri == NULL) {
switch (err) {
case HTTPD_404_NOT_FOUND:
ESP_LOGW(TAG, LOG_FMT("URI '%s' not found"), req->uri);
return httpd_req_handle_err(req, HTTPD_404_NOT_FOUND);
case HTTPD_405_METHOD_NOT_ALLOWED:
ESP_LOGW(TAG, LOG_FMT("Method '%d' not allowed for URI '%s'"),
req->method, req->uri);
return httpd_req_handle_err(req, HTTPD_405_METHOD_NOT_ALLOWED);
default:
return ESP_FAIL;
}
}
/* Attach user context data (passed during URI registration) into request */
req->user_ctx = uri->user_ctx;
/* Final step for a WebSocket handshake verification */
#ifdef CONFIG_HTTPD_WS_SUPPORT
struct httpd_req_aux *aux = req->aux;
if (uri->is_websocket && aux->ws_handshake_detect && uri->method == HTTP_GET) {
#ifdef CONFIG_HTTPD_WS_PRE_HANDSHAKE_CB_SUPPORT
if (uri->ws_pre_handshake_cb && uri->ws_pre_handshake_cb(req) != ESP_OK) {
ESP_LOGW(TAG, LOG_FMT("ws_pre_handshake_cb failed"));
return ESP_FAIL;
}
#endif /* CONFIG_HTTPD_WS_PRE_HANDSHAKE_CB_SUPPORT */
ESP_LOGD(TAG, LOG_FMT("Responding WS handshake to sock %d"), aux->sd->fd);
esp_err_t ret = httpd_ws_respond_server_handshake(&hd->hd_req, uri->supported_subprotocol);
if (ret != ESP_OK) {
return ret;
}
aux->sd->ws_handshake_done = true;
aux->sd->ws_handler = uri->handler;
aux->sd->ws_control_frames = uri->handle_ws_control_frames;
aux->sd->ws_user_ctx = uri->user_ctx;
#ifdef CONFIG_HTTPD_WS_POST_HANDSHAKE_CB_SUPPORT
if (uri->ws_post_handshake_cb && uri->ws_post_handshake_cb(req) != ESP_OK) {
ESP_LOGW(TAG, LOG_FMT("ws_post_handshake_cb failed"));
return ESP_FAIL;
}
#endif /* CONFIG_HTTPD_WS_POST_HANDSHAKE_CB_SUPPORT */
/* If the request is websocket handshake, then do not call the uri->handler */
return ESP_OK;
}
#endif /* CONFIG_HTTPD_WS_SUPPORT */
/* Invoke handler */
if (uri->handler(req) != ESP_OK) {
/* Handler returns error, this socket should be closed */
ESP_LOGW(TAG, LOG_FMT("uri handler execution failed"));
return ESP_FAIL;
}
return ESP_OK;
}
+624
View File
@@ -0,0 +1,624 @@
/*
* SPDX-FileCopyrightText: 2020-2026 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdlib.h>
#include <string.h>
#include <sys/random.h>
#include <esp_log.h>
#include <esp_err.h>
#include "desktop_crypto.h"
#include <esp_http_server.h>
#include "esp_httpd_priv.h"
#include "freertos/event_groups.h"
#include "sdkconfig.h"
#ifdef CONFIG_HTTPD_WS_SUPPORT
#define WS_SEND_OK (1 << 0)
#define WS_SEND_FAILED (1 << 1)
typedef struct {
httpd_ws_frame_t frame;
httpd_handle_t handle;
int socket;
transfer_complete_cb callback;
void *arg;
bool blocking;
EventGroupHandle_t transfer_done;
} async_transfer_t;
static const char *TAG="httpd_ws";
/*
* Bit masks for WebSocket frames.
* Please refer to RFC6455 Section 5.2 for more details.
*/
#define HTTPD_WS_CONTINUE 0x00U
#define HTTPD_WS_FIN_BIT 0x80U
#define HTTPD_WS_OPCODE_BITS 0x0fU
#define HTTPD_WS_MASK_BIT 0x80U
#define HTTPD_WS_LENGTH_BITS 0x7fU
/*
* The magic GUID string used for handshake
* Please refer to RFC6455 Section 1.3 for more details.
*/
static const char ws_magic_uuid[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
/* Checks if any subprotocols from the comma separated list matches the supported one
*
* Returns true if the response should contain a protocol field
*/
/**
* @brief Checks if any subprotocols from the comma separated list matches the supported one
*
* @param supported_subprotocol[in] The subprotocol supported by the URI
* @param subprotocol[in], [in]: A comma separate list of subprotocols requested
* @param buf_len Length of the buffer
* @return true: found a matching subprotocol
* @return false
*/
static bool httpd_ws_get_response_subprotocol(const char *supported_subprotocol, char *subprotocol, size_t buf_len)
{
/* Request didn't contain any subprotocols */
if (strnlen(subprotocol, buf_len) == 0) {
return false;
}
if (supported_subprotocol == NULL) {
ESP_LOGW(TAG, "Sec-WebSocket-Protocol %s not supported, URI do not support any subprotocols", subprotocol);
return false;
}
/* Get first subprotocol from comma separated list */
char *rest = NULL;
char *s = strtok_r(subprotocol, ", ", &rest);
int supported_subprotocol_len = strlen(supported_subprotocol);
while (s != NULL) {
if (strlen(s) == supported_subprotocol_len &&
strncmp(s, supported_subprotocol, supported_subprotocol_len) == 0) {
ESP_LOGD(TAG, "Requested subprotocol supported: %s", s);
return true;
}
s = strtok_r(NULL, ", ", &rest);
}
ESP_LOGW(TAG, "Sec-WebSocket-Protocol %s not supported, supported subprotocol is %s", subprotocol, supported_subprotocol);
/* No matches */
return false;
}
esp_err_t httpd_ws_respond_server_handshake(httpd_req_t *req, const char *supported_subprotocol)
{
/* Probe if input parameters are valid or not */
if (!req || !req->aux) {
ESP_LOGW(TAG, LOG_FMT("Argument is invalid"));
return ESP_ERR_INVALID_ARG;
}
/* Detect handshake - reject if handshake was ALREADY performed */
struct httpd_req_aux *req_aux = req->aux;
if (req_aux->sd->ws_handshake_done) {
ESP_LOGW(TAG, LOG_FMT("State is invalid - Handshake has been performed"));
return ESP_ERR_INVALID_STATE;
}
/* Detect WS version existence */
char version_val[3] = { '\0' };
if (httpd_req_get_hdr_value_str(req, "Sec-WebSocket-Version", version_val, sizeof(version_val)) != ESP_OK) {
ESP_LOGW(TAG, LOG_FMT("\"Sec-WebSocket-Version\" is not found"));
return ESP_ERR_NOT_FOUND;
}
/* Detect if WS version is "13" or not.
* WS version must be 13 for now. Please refer to RFC6455 Section 4.1, Page 18 for more details. */
if (strcasecmp(version_val, "13") != 0) {
ESP_LOGW(TAG, LOG_FMT("\"Sec-WebSocket-Version\" is not \"13\", it is: %s"), version_val);
return ESP_ERR_INVALID_VERSION;
}
/* Grab Sec-WebSocket-Key (client key) from the header */
/* Size of base64 coded string is equal '((input_size * 4) / 3) + (input_size / 96) + 6' including Z-term */
char sec_key_encoded[28] = { '\0' };
if (httpd_req_get_hdr_value_str(req, "Sec-WebSocket-Key", sec_key_encoded, sizeof(sec_key_encoded)) != ESP_OK) {
ESP_LOGW(TAG, LOG_FMT("Cannot find client key"));
return ESP_ERR_NOT_FOUND;
}
/* Prepare server key (Sec-WebSocket-Accept), concat the string */
char server_key_encoded[33] = { '\0' };
uint8_t server_key_hash[20] = { 0 };
char server_raw_text[sizeof(sec_key_encoded) + sizeof(ws_magic_uuid) + 1] = { '\0' };
strcpy(server_raw_text, sec_key_encoded);
strcat(server_raw_text, ws_magic_uuid);
ESP_LOGD(TAG, LOG_FMT("Server key before encoding: %s"), server_raw_text);
/* Generate SHA-1 hash, then base64 (desktop build: desktop_crypto.c) */
desktop_sha1((const uint8_t *)server_raw_text, strlen(server_raw_text), server_key_hash);
size_t encoded_len = desktop_base64_encode(server_key_encoded, sizeof(server_key_encoded),
server_key_hash, sizeof(server_key_hash));
ESP_LOGD(TAG, LOG_FMT("Generated server key: %s"), server_key_encoded);
char subprotocol[50] = { '\0' };
if (httpd_req_get_hdr_value_str(req, "Sec-WebSocket-Protocol", subprotocol, sizeof(subprotocol) - 1) == ESP_ERR_HTTPD_RESULT_TRUNC) {
ESP_LOGW(TAG, "Sec-WebSocket-Protocol length exceeded buffer size of %"NEWLIB_NANO_COMPAT_FORMAT", was truncated", NEWLIB_NANO_COMPAT_CAST(sizeof(subprotocol)));
}
/* Prepare the Switching Protocol response */
char tx_buf[192] = { '\0' };
int fmt_len = snprintf(tx_buf, sizeof(tx_buf),
"HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: %s\r\n", server_key_encoded);
if (fmt_len < 0 || fmt_len > sizeof(tx_buf)) {
ESP_LOGW(TAG, LOG_FMT("Failed to prepare Tx buffer"));
return ESP_FAIL;
}
if ( httpd_ws_get_response_subprotocol(supported_subprotocol, subprotocol, sizeof(subprotocol))) {
ESP_LOGD(TAG, "subprotocol: %s", subprotocol);
int r = snprintf(tx_buf + fmt_len, sizeof(tx_buf) - fmt_len, "Sec-WebSocket-Protocol: %s\r\n", supported_subprotocol);
if (r <= 0) {
ESP_LOGE(TAG, "Error in response generation"
"(snprintf of subprotocol returned %d, buffer size: %"NEWLIB_NANO_COMPAT_FORMAT, r, NEWLIB_NANO_COMPAT_CAST(sizeof(tx_buf)));
return ESP_FAIL;
}
fmt_len += r;
if (fmt_len >= sizeof(tx_buf)) {
ESP_LOGE(TAG, "Error in response generation"
"(snprintf of subprotocol returned %d, desired response len: %d, buffer size: %"NEWLIB_NANO_COMPAT_FORMAT, r, fmt_len, NEWLIB_NANO_COMPAT_CAST(sizeof(tx_buf)));
return ESP_FAIL;
}
}
int r = snprintf(tx_buf + fmt_len, sizeof(tx_buf) - fmt_len, "\r\n");
if (r <= 0) {
ESP_LOGE(TAG, "Error in response generation"
"(snprintf of subprotocol returned %d, buffer size: %"NEWLIB_NANO_COMPAT_FORMAT, r, NEWLIB_NANO_COMPAT_CAST(sizeof(tx_buf)));
return ESP_FAIL;
}
fmt_len += r;
if (fmt_len >= sizeof(tx_buf)) {
ESP_LOGE(TAG, "Error in response generation"
"(snprintf of header terminal returned %d, desired response len: %d, buffer size: %"NEWLIB_NANO_COMPAT_FORMAT, r, fmt_len, NEWLIB_NANO_COMPAT_CAST(sizeof(tx_buf)));
return ESP_FAIL;
}
/* Send off the response */
if (httpd_send(req, tx_buf, fmt_len) < 0) {
ESP_LOGW(TAG, LOG_FMT("Failed to send the response"));
return ESP_FAIL;
}
return ESP_OK;
}
static esp_err_t httpd_ws_check_req(httpd_req_t *req)
{
/* Probe if input parameters are valid or not */
if (!req || !req->aux) {
ESP_LOGW(TAG, LOG_FMT("Argument is null"));
return ESP_ERR_INVALID_ARG;
}
/* Detect handshake - reject if handshake was NOT YET performed */
struct httpd_req_aux *req_aux = req->aux;
if (!req_aux->sd->ws_handshake_done) {
ESP_LOGW(TAG, LOG_FMT("State is invalid - No handshake performed"));
return ESP_ERR_INVALID_STATE;
}
return ESP_OK;
}
static esp_err_t httpd_ws_unmask_payload(uint8_t *payload, size_t len, const uint8_t *mask_key, size_t mask_offset)
{
if (len < 1 || !payload) {
ESP_LOGW(TAG, LOG_FMT("Invalid payload provided"));
return ESP_ERR_INVALID_ARG;
}
for (size_t idx = 0; idx < len; idx++) {
payload[idx] = (payload[idx] ^ mask_key[(idx + mask_offset) % 4]);
}
return ESP_OK;
}
static esp_err_t httpd_ws_recv_frame_internal(httpd_req_t *req, httpd_ws_frame_t *frame, size_t max_len, bool partial)
{
esp_err_t ret = httpd_ws_check_req(req);
if (ret != ESP_OK) {
return ret;
}
struct httpd_req_aux *aux = req->aux;
if (aux == NULL) {
ESP_LOGW(TAG, LOG_FMT("Invalid Aux pointer"));
return ESP_ERR_INVALID_ARG;
}
if (!frame) {
ESP_LOGW(TAG, LOG_FMT("Frame pointer is invalid"));
return ESP_ERR_INVALID_ARG;
}
/* If frame len is 0, will get frame len from req. Otherwise regard frame len already achieved by calling httpd_ws_recv_frame before */
if (frame->len == 0) {
/* Assign the frame info from the previous reading */
frame->type = aux->ws_type;
frame->final = aux->ws_final;
/* Grab the second byte */
uint8_t second_byte = 0;
int recv_ret = httpd_recv_with_opt(req, (char *)&second_byte, sizeof(second_byte), HTTPD_RECV_OPT_BLOCKING);
if (recv_ret != (int)sizeof(second_byte)) {
ESP_LOGW(TAG, LOG_FMT("Failed to receive the second byte"));
return ESP_FAIL;
}
/* Parse the second byte */
/* Please refer to RFC6455 Section 5.2 for more details */
bool masked = (second_byte & HTTPD_WS_MASK_BIT) != 0;
/* Interpret length */
uint8_t init_len = second_byte & HTTPD_WS_LENGTH_BITS;
if (init_len < 126) {
/* Case 1: If length is 0-125, then this length bit is 7 bits */
frame->len = init_len;
} else if (init_len == 126) {
/* Case 2: If length byte is 126, then this frame's length bit is 16 bits */
uint8_t length_bytes[2] = { 0 };
recv_ret = httpd_recv_with_opt(req, (char *)length_bytes, sizeof(length_bytes), HTTPD_RECV_OPT_BLOCKING);
if (recv_ret != (int)sizeof(length_bytes)) {
ESP_LOGW(TAG, LOG_FMT("Failed to receive 2 bytes length"));
return ESP_FAIL;
}
frame->len = ((uint32_t)(length_bytes[0] << 8U) | (length_bytes[1]));
} else if (init_len == 127) {
/* Case 3: If length is byte 127, then this frame's length bit is 64 bits */
uint8_t length_bytes[8] = { 0 };
recv_ret = httpd_recv_with_opt(req, (char *)length_bytes, sizeof(length_bytes), HTTPD_RECV_OPT_BLOCKING);
if (recv_ret != (int)sizeof(length_bytes)) {
ESP_LOGW(TAG, LOG_FMT("Failed to receive 8 bytes length"));
return ESP_FAIL;
}
frame->len = (((uint64_t)length_bytes[0] << 56U) |
((uint64_t)length_bytes[1] << 48U) |
((uint64_t)length_bytes[2] << 40U) |
((uint64_t)length_bytes[3] << 32U) |
((uint64_t)length_bytes[4] << 24U) |
((uint64_t)length_bytes[5] << 16U) |
((uint64_t)length_bytes[6] << 8U) |
((uint64_t)length_bytes[7]));
}
frame->left_len = frame->len;
/* If this frame is masked, dump the mask as well */
if (masked) {
recv_ret = httpd_recv_with_opt(req, (char *)aux->mask_key, sizeof(aux->mask_key), HTTPD_RECV_OPT_BLOCKING);
if (recv_ret != (int)sizeof(aux->mask_key)) {
ESP_LOGW(TAG, LOG_FMT("Failed to receive mask key"));
return ESP_FAIL;
}
} else {
/* If the WS frame from client to server is not masked, it should be rejected.
* Please refer to RFC6455 Section 5.2 for more details. */
ESP_LOGW(TAG, LOG_FMT("WS frame is not properly masked."));
return ESP_ERR_INVALID_STATE;
}
}
/* If max_len is 0, regard it OK for userspace to get frame len */
if (max_len == 0) {
ESP_LOGD(TAG, "regard max_len == 0 is OK for user to get frame len");
return ESP_OK;
}
if (frame->len > max_len) {
/* When reading entire packet at once, we only accept the incoming packet length that is smaller than the max_len (or it will overflow the buffer!) */
if (!partial) {
ESP_LOGW(TAG, LOG_FMT("WS Message too long"));
return ESP_ERR_INVALID_SIZE;
}
ESP_LOGD(TAG, LOG_FMT("WS Message too long. User will have to call read again"));
}
/* Receive buffer */
/* If there's nothing to receive, return and stop here. */
if (frame->left_len == 0) {
return ESP_OK;
}
if (frame->payload == NULL) {
ESP_LOGW(TAG, LOG_FMT("Payload buffer is null"));
return ESP_FAIL;
}
size_t left_len = (max_len < frame->left_len) ? max_len : frame->left_len;
size_t offset = 0;
while (left_len > 0) {
int read_len = httpd_recv_with_opt(req, (char *)frame->payload + offset, left_len, HTTPD_RECV_OPT_NONE);
if (read_len <= 0) {
ESP_LOGW(TAG, LOG_FMT("Failed to receive payload"));
return ESP_FAIL;
}
offset += read_len;
left_len -= read_len;
ESP_LOGD(TAG, "Frame length: %"NEWLIB_NANO_COMPAT_FORMAT", Bytes Read: %"NEWLIB_NANO_COMPAT_FORMAT, NEWLIB_NANO_COMPAT_CAST(frame->len), NEWLIB_NANO_COMPAT_CAST(offset));
}
size_t mask_offset = frame->len - frame->left_len;
frame->left_len -= offset;
/* Unmask payload */
httpd_ws_unmask_payload(frame->payload, offset, aux->mask_key, mask_offset);
return ESP_OK;
}
esp_err_t httpd_ws_recv_frame(httpd_req_t *req, httpd_ws_frame_t *frame, size_t max_len) {
return httpd_ws_recv_frame_internal(req, frame, max_len, false);
}
esp_err_t httpd_ws_recv_frame_part(httpd_req_t *req, httpd_ws_frame_t *frame, size_t max_len) {
return httpd_ws_recv_frame_internal(req, frame, max_len, true);
}
esp_err_t httpd_ws_send_frame(httpd_req_t *req, httpd_ws_frame_t *frame)
{
esp_err_t ret = httpd_ws_check_req(req);
if (ret != ESP_OK) {
return ret;
}
return httpd_ws_send_frame_async(req->handle, httpd_req_to_sockfd(req), frame);
}
esp_err_t httpd_ws_send_frame_async(httpd_handle_t hd, int fd, httpd_ws_frame_t *frame)
{
if (!frame) {
ESP_LOGW(TAG, LOG_FMT("Argument is invalid"));
return ESP_ERR_INVALID_ARG;
}
/* Prepare Tx buffer - maximum length is 14, which includes 2 bytes header, 8 bytes length, 4 bytes mask key */
uint8_t tx_len = 0;
uint8_t header_buf[10] = {0 };
/* Set the `FIN` bit by default if message is not fragmented. Else, set it as per the `final` field */
header_buf[0] |= (!frame->fragmented) ? HTTPD_WS_FIN_BIT : (frame->final? HTTPD_WS_FIN_BIT: HTTPD_WS_CONTINUE);
header_buf[0] |= frame->type; /* Type (opcode): 4 bits */
if (frame->len <= 125) {
header_buf[1] = frame->len & 0x7fU; /* Length for 7 bits */
tx_len = 2;
} else if (frame->len > 125 && frame->len < UINT16_MAX) {
header_buf[1] = 126; /* Length for 16 bits */
header_buf[2] = (frame->len >> 8U) & 0xffU;
header_buf[3] = frame->len & 0xffU;
tx_len = 4;
} else {
header_buf[1] = 127; /* Length for 64 bits */
uint8_t shift_idx = sizeof(uint64_t) - 1; /* Shift index starts at 7 */
uint64_t len64 = frame->len; /* Raise variable size to make sure we won't shift by more bits
* than the length has (to avoid undefined behaviour) */
for (int8_t idx = 2; idx <= 9; idx++) {
/* Now do shifting (be careful of endianness, i.e. when buffer index is 2, frame length shift index is 7) */
header_buf[idx] = (len64 >> (shift_idx * 8)) & 0xffU;
shift_idx--;
}
tx_len = 10;
}
/* WebSocket server does not required to mask response payload, so leave the MASK bit as 0. */
header_buf[1] &= (~HTTPD_WS_MASK_BIT);
struct sock_db *sess = httpd_sess_get(hd, fd);
if (!sess) {
return ESP_ERR_INVALID_ARG;
}
/* Send off header */
if (sess->send_fn(hd, fd, (const char *)header_buf, tx_len, 0) < 0) {
ESP_LOGW(TAG, LOG_FMT("Failed to send WS header"));
return ESP_FAIL;
}
/* Send off payload */
if(frame->len > 0 && frame->payload != NULL) {
if (sess->send_fn(hd, fd, (const char *)frame->payload, frame->len, 0) < 0) {
ESP_LOGW(TAG, LOG_FMT("Failed to send WS payload"));
return ESP_FAIL;
}
}
return ESP_OK;
}
esp_err_t httpd_ws_get_frame_type(httpd_req_t *req)
{
esp_err_t ret = httpd_ws_check_req(req);
if (ret != ESP_OK) {
return ret;
}
struct httpd_req_aux *aux = req->aux;
if (aux == NULL) {
ESP_LOGW(TAG, LOG_FMT("Invalid Aux pointer"));
return ESP_ERR_INVALID_ARG;
}
struct sock_db *sd = aux->sd;
if (sd == NULL) {
ESP_LOGW(TAG, LOG_FMT("Invalid sd pointer"));
return ESP_ERR_INVALID_ARG;
}
/* Read the first byte from the frame to get the FIN flag and Opcode */
/* Please refer to RFC6455 Section 5.2 for more details */
uint8_t first_byte = 0;
int recv_ret = httpd_recv_with_opt(req, (char *)&first_byte, sizeof(first_byte), HTTPD_RECV_OPT_BLOCKING);
if (recv_ret != (int)sizeof(first_byte)) {
/* If we fail to read exactly one byte, this socket FD is invalid or the frame header is incomplete. */
/* Here we mark it as a Close message and close it later. */
ESP_LOGW(TAG, LOG_FMT("Failed to read header byte (socket FD invalid), closing socket now"));
aux->ws_final = true;
aux->ws_type = HTTPD_WS_TYPE_CLOSE;
return ESP_OK;
}
ESP_LOGD(TAG, LOG_FMT("First byte received: 0x%02X"), first_byte);
/* Decode the FIN flag and Opcode from the byte */
aux->ws_final = (first_byte & HTTPD_WS_FIN_BIT) != 0;
aux->ws_type = (first_byte & HTTPD_WS_OPCODE_BITS);
/* If userspace requests control frames, do not deal with the control frames */
if (!sd->ws_control_frames) {
ESP_LOGD(TAG, LOG_FMT("Handler not requests control frames"));
/* Reply to PING. For PONG and CLOSE, it will be handled elsewhere. */
if (aux->ws_type == HTTPD_WS_TYPE_PING) {
ESP_LOGD(TAG, LOG_FMT("Got a WS PING frame, Replying PONG..."));
/* Read the rest of the PING frame, for PONG to reply back. */
/* Please refer to RFC6455 Section 5.5.2 for more details */
httpd_ws_frame_t frame;
uint8_t frame_buf[128] = { 0 };
memset(&frame, 0, sizeof(httpd_ws_frame_t));
frame.payload = frame_buf;
if (httpd_ws_recv_frame(req, &frame, 126) != ESP_OK) {
ESP_LOGD(TAG, LOG_FMT("Cannot receive the full PING frame"));
return ESP_ERR_INVALID_STATE;
}
/* Now turn the frame to PONG */
frame.type = HTTPD_WS_TYPE_PONG;
return httpd_ws_send_frame(req, &frame);
} else if (aux->ws_type == HTTPD_WS_TYPE_CLOSE) {
ESP_LOGD(TAG, LOG_FMT("Got a WS CLOSE frame, Replying CLOSE..."));
/* Read the rest of the CLOSE frame and response */
/* Please refer to RFC6455 Section 5.5.1 for more details */
httpd_ws_frame_t frame;
uint8_t frame_buf[128] = { 0 };
memset(&frame, 0, sizeof(httpd_ws_frame_t));
frame.payload = frame_buf;
if (httpd_ws_recv_frame(req, &frame, 126) != ESP_OK) {
ESP_LOGD(TAG, LOG_FMT("Cannot receive the full CLOSE frame"));
return ESP_ERR_INVALID_STATE;
}
frame.len = 0;
frame.type = HTTPD_WS_TYPE_CLOSE;
frame.payload = NULL;
return httpd_ws_send_frame(req, &frame);
}
}
return ESP_OK;
}
httpd_ws_client_info_t httpd_ws_get_fd_info(httpd_handle_t hd, int fd)
{
struct sock_db *sess = httpd_sess_get(hd, fd);
if (sess == NULL) {
return HTTPD_WS_CLIENT_INVALID;
}
bool is_active_ws = sess->ws_handshake_done && (!sess->ws_close);
return is_active_ws ? HTTPD_WS_CLIENT_WEBSOCKET : HTTPD_WS_CLIENT_HTTP;
}
static void httpd_ws_send_cb(void *arg)
{
async_transfer_t *trans = arg;
esp_err_t err = httpd_ws_send_frame_async(trans->handle, trans->socket, &trans->frame);
if (trans->blocking) {
xEventGroupSetBits(trans->transfer_done, err ? WS_SEND_FAILED : WS_SEND_OK);
} else if (trans->callback) {
trans->callback(err, trans->socket, trans->arg);
}
free(trans);
}
esp_err_t httpd_ws_send_data(httpd_handle_t handle, int socket, httpd_ws_frame_t *frame)
{
async_transfer_t *transfer = calloc(1, sizeof(async_transfer_t));
if (transfer == NULL) {
return ESP_ERR_NO_MEM;
}
EventGroupHandle_t transfer_done = xEventGroupCreate();
if (!transfer_done) {
free(transfer);
return ESP_ERR_NO_MEM;
}
transfer->blocking = true;
transfer->handle = handle;
transfer->socket = socket;
transfer->transfer_done = transfer_done;
memcpy(&transfer->frame, frame, sizeof(httpd_ws_frame_t));
esp_err_t err = httpd_queue_work(handle, httpd_ws_send_cb, transfer);
if (err != ESP_OK) {
vEventGroupDelete(transfer_done);
free(transfer);
return err;
}
EventBits_t status = xEventGroupWaitBits(transfer_done, WS_SEND_OK | WS_SEND_FAILED,
pdTRUE, pdFALSE, portMAX_DELAY);
vEventGroupDelete(transfer_done);
return (status & WS_SEND_OK) ? ESP_OK : ESP_FAIL;
}
esp_err_t httpd_ws_send_data_async(httpd_handle_t handle, int socket, httpd_ws_frame_t *frame,
transfer_complete_cb callback, void *arg)
{
async_transfer_t *transfer = calloc(1, sizeof(async_transfer_t));
if (transfer == NULL) {
return ESP_ERR_NO_MEM;
}
transfer->arg = arg;
transfer->callback = callback;
transfer->handle = handle;
transfer->socket = socket;
memcpy(&transfer->frame, frame, sizeof(httpd_ws_frame_t));
esp_err_t err = httpd_queue_work(handle, httpd_ws_send_cb, transfer);
if (err) {
free(transfer);
return err;
}
return ESP_OK;
}
#endif /* CONFIG_HTTPD_WS_SUPPORT */
+106
View File
@@ -0,0 +1,106 @@
/*
* SPDX-FileCopyrightText: 2018-2025 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "sdkconfig.h"
#include "esp_log.h"
#include "ctrl_sock.h"
#if CONFIG_IDF_TARGET_LINUX
#define IPV4_ENABLED 1
#define IPV6_ENABLED 1
#define LOOPBACK_ENABLED 1
#else // CONFIG_IDF_TARGET_LINUX
#define IPV4_ENABLED CONFIG_LWIP_IPV4
#define IPV6_ENABLED CONFIG_LWIP_IPV6
#define LOOPBACK_ENABLED CONFIG_LWIP_NETIF_LOOPBACK
#endif // !CONFIG_IDF_TARGET_LINUX
/* Control socket, because in some network stacks select can't be woken up any
* other way
*/
int cs_create_ctrl_sock(int port)
{
#if !LOOPBACK_ENABLED
ESP_LOGE("esp_http_server", "Please enable LWIP_NETIF_LOOPBACK for %s API", __func__);
return -1;
#endif
int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (fd < 0) {
return -1;
}
int ret;
struct sockaddr_storage addr = {};
socklen_t addr_len = 0;
#if IPV4_ENABLED
struct sockaddr_in *addr4 = (struct sockaddr_in *)&addr;
addr4->sin_family = AF_INET;
addr4->sin_port = htons(port);
inet_aton("127.0.0.1", &addr4->sin_addr);
addr_len = sizeof(struct sockaddr_in);
#else
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&addr;
addr6->sin6_family = AF_INET6;
addr6->sin6_port = htons(port);
inet6_aton("::1", &addr6->sin6_addr);
addr_len = sizeof(struct sockaddr_in6);
#endif
ret = bind(fd, (struct sockaddr *)&addr, addr_len);
if (ret < 0) {
close(fd);
return -1;
}
return fd;
}
void cs_free_ctrl_sock(int fd)
{
close(fd);
}
int cs_send_to_ctrl_sock(int send_fd, int port, void *data, unsigned int data_len)
{
int ret;
struct sockaddr_storage to_addr = {};
socklen_t addr_len = 0;
#if IPV4_ENABLED
struct sockaddr_in *addr4 = (struct sockaddr_in *)&to_addr;
addr4->sin_family = AF_INET;
addr4->sin_port = htons(port);
inet_aton("127.0.0.1", &addr4->sin_addr);
addr_len = sizeof(struct sockaddr_in);
#else
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&to_addr;
addr6->sin6_family = AF_INET6;
addr6->sin6_port = htons(port);
inet6_aton("::1", &addr6->sin6_addr);
addr_len = sizeof(struct sockaddr_in6);
#endif
ret = sendto(send_fd, data, data_len, 0, (struct sockaddr *)&to_addr, addr_len);
if (ret < 0) {
return -1;
}
return ret;
}
int cs_recv_from_ctrl_sock(int fd, void *data, unsigned int data_len)
{
int ret;
ret = recvfrom(fd, data, data_len, 0, NULL, NULL);
if (ret < 0) {
return -1;
}
return ret;
}
@@ -0,0 +1,91 @@
/*
* SPDX-FileCopyrightText: 2018-2021 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
/**
* \file ctrl_sock.h
* \brief Control Socket for select() wakeup
*
* LWIP doesn't allow an easy mechanism to on-demand wakeup a thread
* sleeping on select. This is a common requirement for sending
* control commands to a network server. This control socket API
* facilitates the same.
*/
#ifndef _CTRL_SOCK_H_
#define _CTRL_SOCK_H_
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Create a control socket
*
* LWIP doesn't allow an easy mechanism to on-demand wakeup a thread
* sleeping on select. This is a common requirement for sending
* control commands to a network server. This control socket API
* facilitates the same.
*
* This API will create a UDP control socket on the specified port. It
* will return a socket descriptor that can then be added to your
* fd_set in select()
*
* @param[in] port the local port on which the control socket will listen
*
* @return - the socket descriptor that can be added to the fd_set in select.
* - an error code if less than zero
*/
int cs_create_ctrl_sock(int port);
/**
* @brief Free the control socket
*
* This frees up the control socket that was earlier created using
* cs_create_ctrl_sock()
*
* @param[in] fd the socket descriptor associated with this control socket
*/
void cs_free_ctrl_sock(int fd);
/**
* @brief Send data to control socket
*
* This API sends data to the control socket. If a server is blocked
* on select() with the control socket, this call will wake up that
* server.
*
* @param[in] send_fd the socket for sending ctrl messages
* @param[in] port the port on which the control socket was created
* @param[in] data pointer to a buffer that contains data to send on the socket
* @param[in] data_len the length of the data contained in the buffer pointed to be data
*
* @return - the number of bytes sent to the control socket
* - an error code if less than zero
*/
int cs_send_to_ctrl_sock(int send_fd, int port, void *data, unsigned int data_len);
/**
* @brief Receive data from control socket
*
* This API receives any data that was sent to the control
* socket. This will be typically called from the server thread to
* process any commands on this socket.
*
* @param[in] fd the socket descriptor of the control socket
* @param[in] data pointer to a buffer that will be used to store
* received from the control socket
* @param[in] data_len the maximum length of the data that can be
* stored in the buffer pointed by data
*
* @return - the number of bytes received from the control socket
* - an error code if less than zero
*/
int cs_recv_from_ctrl_sock(int fd, void *data, unsigned int data_len);
#ifdef __cplusplus
}
#endif
#endif /* ! _CTRL_SOCK_H_ */
+23
View File
@@ -0,0 +1,23 @@
/* Based on src/http/ngx_http_parse.c from NGINX copyright Igor Sysoev
*
* Additional changes are licensed under the same terms as NGINX and
* copyright Joyent, Inc. and other Node contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
File diff suppressed because it is too large. Load diff
+362
View File
@@ -0,0 +1,362 @@
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef http_parser_h
#define http_parser_h
#ifdef __cplusplus
extern "C" {
#endif
/* Also update SONAME in the Makefile whenever you change these. */
#define HTTP_PARSER_VERSION_MAJOR 2
#define HTTP_PARSER_VERSION_MINOR 7
#define HTTP_PARSER_VERSION_PATCH 0
#include <sys/types.h>
#if defined(_WIN32) && !defined(__MINGW32__) && \
(!defined(_MSC_VER) || _MSC_VER<1600) && !defined(__WINE__)
#include <BaseTsd.h>
#include <stddef.h>
typedef __int8 int8_t;
typedef unsigned __int8 uint8_t;
typedef __int16 int16_t;
typedef unsigned __int16 uint16_t;
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
#include <stdint.h>
#endif
/* Compile with -DHTTP_PARSER_STRICT=0 to make less checks, but run
* faster
*/
#ifndef HTTP_PARSER_STRICT
# define HTTP_PARSER_STRICT 1
#endif
/* Maximium header size allowed. If the macro is not defined
* before including this header then the default is used. To
* change the maximum header size, define the macro in the build
* environment (e.g. -DHTTP_MAX_HEADER_SIZE=<value>). To remove
* the effective limit on the size of the header, define the macro
* to a very large number (e.g. -DHTTP_MAX_HEADER_SIZE=0x7fffffff)
*/
#ifndef HTTP_MAX_HEADER_SIZE
# define HTTP_MAX_HEADER_SIZE (80*1024)
#endif
typedef struct http_parser http_parser;
typedef struct http_parser_settings http_parser_settings;
/* Callbacks should return non-zero to indicate an error. The parser will
* then halt execution.
*
* The one exception is on_headers_complete. In a HTTP_RESPONSE parser
* returning '1' from on_headers_complete will tell the parser that it
* should not expect a body. This is used when receiving a response to a
* HEAD request which may contain 'Content-Length' or 'Transfer-Encoding:
* chunked' headers that indicate the presence of a body.
*
* Returning `2` from on_headers_complete will tell parser that it should not
* expect neither a body nor any futher responses on this connection. This is
* useful for handling responses to a CONNECT request which may not contain
* `Upgrade` or `Connection: upgrade` headers.
*
* http_data_cb does not return data chunks. It will be called arbitrarily
* many times for each string. E.G. you might get 10 callbacks for "on_url"
* each providing just a few characters more data.
*/
typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);
typedef int (*http_cb) (http_parser*);
/* Request Methods */
#define HTTP_METHOD_MAP(XX) \
XX(0, DELETE, DELETE) \
XX(1, GET, GET) \
XX(2, HEAD, HEAD) \
XX(3, POST, POST) \
XX(4, PUT, PUT) \
/* pathological */ \
XX(5, CONNECT, CONNECT) \
XX(6, OPTIONS, OPTIONS) \
XX(7, TRACE, TRACE) \
/* WebDAV */ \
XX(8, COPY, COPY) \
XX(9, LOCK, LOCK) \
XX(10, MKCOL, MKCOL) \
XX(11, MOVE, MOVE) \
XX(12, PROPFIND, PROPFIND) \
XX(13, PROPPATCH, PROPPATCH) \
XX(14, SEARCH, SEARCH) \
XX(15, UNLOCK, UNLOCK) \
XX(16, BIND, BIND) \
XX(17, REBIND, REBIND) \
XX(18, UNBIND, UNBIND) \
XX(19, ACL, ACL) \
/* subversion */ \
XX(20, REPORT, REPORT) \
XX(21, MKACTIVITY, MKACTIVITY) \
XX(22, CHECKOUT, CHECKOUT) \
XX(23, MERGE, MERGE) \
/* upnp */ \
XX(24, MSEARCH, M-SEARCH) \
XX(25, NOTIFY, NOTIFY) \
XX(26, SUBSCRIBE, SUBSCRIBE) \
XX(27, UNSUBSCRIBE, UNSUBSCRIBE) \
/* RFC-5789 */ \
XX(28, PATCH, PATCH) \
XX(29, PURGE, PURGE) \
/* CalDAV */ \
XX(30, MKCALENDAR, MKCALENDAR) \
/* RFC-2068, section 19.6.1.2 */ \
XX(31, LINK, LINK) \
XX(32, UNLINK, UNLINK) \
enum http_method
{
#define XX(num, name, string) HTTP_##name = num,
HTTP_METHOD_MAP(XX)
#undef XX
};
enum http_parser_type { HTTP_REQUEST, HTTP_RESPONSE, HTTP_BOTH };
/* Flag values for http_parser.flags field */
enum flags
{ F_CHUNKED = 1 << 0
, F_CONNECTION_KEEP_ALIVE = 1 << 1
, F_CONNECTION_CLOSE = 1 << 2
, F_CONNECTION_UPGRADE = 1 << 3
, F_TRAILING = 1 << 4
, F_UPGRADE = 1 << 5
, F_SKIPBODY = 1 << 6
, F_CONTENTLENGTH = 1 << 7
};
/* Map for errno-related constants
*
* The provided argument should be a macro that takes 2 arguments.
*/
#define HTTP_ERRNO_MAP(XX) \
/* No error */ \
XX(OK, "success") \
\
/* Callback-related errors */ \
XX(CB_message_begin, "the on_message_begin callback failed") \
XX(CB_url, "the on_url callback failed") \
XX(CB_header_field, "the on_header_field callback failed") \
XX(CB_header_value, "the on_header_value callback failed") \
XX(CB_headers_complete, "the on_headers_complete callback failed") \
XX(CB_body, "the on_body callback failed") \
XX(CB_message_complete, "the on_message_complete callback failed") \
XX(CB_status, "the on_status callback failed") \
XX(CB_chunk_header, "the on_chunk_header callback failed") \
XX(CB_chunk_complete, "the on_chunk_complete callback failed") \
\
/* Parsing-related errors */ \
XX(INVALID_EOF_STATE, "stream ended at an unexpected time") \
XX(HEADER_OVERFLOW, \
"too many header bytes seen; overflow detected") \
XX(CLOSED_CONNECTION, \
"data received after completed connection: close message") \
XX(INVALID_VERSION, "invalid HTTP version") \
XX(INVALID_STATUS, "invalid HTTP status code") \
XX(INVALID_METHOD, "invalid HTTP method") \
XX(INVALID_URL, "invalid URL") \
XX(INVALID_HOST, "invalid host") \
XX(INVALID_PORT, "invalid port") \
XX(INVALID_PATH, "invalid path") \
XX(INVALID_QUERY_STRING, "invalid query string") \
XX(INVALID_FRAGMENT, "invalid fragment") \
XX(LF_EXPECTED, "LF character expected") \
XX(INVALID_HEADER_TOKEN, "invalid character in header") \
XX(INVALID_CONTENT_LENGTH, \
"invalid character in content-length header") \
XX(UNEXPECTED_CONTENT_LENGTH, \
"unexpected content-length header") \
XX(INVALID_CHUNK_SIZE, \
"invalid character in chunk size header") \
XX(INVALID_CONSTANT, "invalid constant string") \
XX(INVALID_INTERNAL_STATE, "encountered unexpected internal state")\
XX(STRICT, "strict mode assertion failed") \
XX(PAUSED, "parser is paused") \
XX(UNKNOWN, "an unknown error occurred")
/* Define HPE_* values for each errno value above */
#define HTTP_ERRNO_GEN(n, s) HPE_##n,
enum http_errno {
HTTP_ERRNO_MAP(HTTP_ERRNO_GEN)
};
#undef HTTP_ERRNO_GEN
/* Get an http_errno value from an http_parser */
#define HTTP_PARSER_ERRNO(p) ((enum http_errno) (p)->http_errno)
struct http_parser {
/** PRIVATE **/
unsigned int type : 2; /* enum http_parser_type */
unsigned int flags : 8; /* F_* values from 'flags' enum; semi-public */
unsigned int state : 7; /* enum state from http_parser.c */
unsigned int header_state : 7; /* enum header_state from http_parser.c */
unsigned int index : 7; /* index into current matcher */
unsigned int lenient_http_headers : 1;
uint32_t nread; /* # bytes read in various scenarios */
uint64_t content_length; /* # bytes in body (0 if no Content-Length header) */
/** READ-ONLY **/
unsigned short http_major;
unsigned short http_minor;
unsigned int status_code : 16; /* responses only */
unsigned int method : 8; /* requests only */
unsigned int http_errno : 7;
/* 1 = Upgrade header was present and the parser has exited because of that.
* 0 = No upgrade header present.
* Should be checked when http_parser_execute() returns in addition to
* error checking.
*/
unsigned int upgrade : 1;
/** PUBLIC **/
void *data; /* A pointer to get hook to the "connection" or "socket" object */
};
struct http_parser_settings {
http_cb on_message_begin;
http_data_cb on_url;
http_data_cb on_status;
http_data_cb on_header_field;
http_data_cb on_header_value;
http_cb on_headers_complete;
http_data_cb on_body;
http_cb on_message_complete;
/* When on_chunk_header is called, the current chunk length is stored
* in parser->content_length.
*/
http_cb on_chunk_header;
http_cb on_chunk_complete;
};
enum http_parser_url_fields
{ UF_SCHEMA = 0
, UF_HOST = 1
, UF_PORT = 2
, UF_PATH = 3
, UF_QUERY = 4
, UF_FRAGMENT = 5
, UF_USERINFO = 6
, UF_MAX = 7
};
/* Result structure for http_parser_parse_url().
*
* Callers should index into field_data[] with UF_* values iff field_set
* has the relevant (1 << UF_*) bit set. As a courtesy to clients (and
* because we probably have padding left over), we convert any port to
* a uint16_t.
*/
struct http_parser_url {
uint16_t field_set; /* Bitmask of (1 << UF_*) values */
uint16_t port; /* Converted UF_PORT string */
struct {
uint16_t off; /* Offset into buffer in which field starts */
uint16_t len; /* Length of run in buffer */
} field_data[UF_MAX];
};
/* Returns the library version. Bits 16-23 contain the major version number,
* bits 8-15 the minor version number and bits 0-7 the patch level.
* Usage example:
*
* unsigned long version = http_parser_version();
* unsigned major = (version >> 16) & 255;
* unsigned minor = (version >> 8) & 255;
* unsigned patch = version & 255;
* printf("http_parser v%u.%u.%u\n", major, minor, patch);
*/
unsigned long http_parser_version(void);
void http_parser_init(http_parser *parser, enum http_parser_type type);
/* Initialize http_parser_settings members to 0
*/
void http_parser_settings_init(http_parser_settings *settings);
/* Executes the parser. Returns number of parsed bytes. Sets
* `parser->http_errno` on error. */
size_t http_parser_execute(http_parser *parser,
const http_parser_settings *settings,
const char *data,
size_t len);
/* If http_should_keep_alive() in the on_headers_complete or
* on_message_complete callback returns 0, then this should be
* the last message on the connection.
* If you are the server, respond with the "Connection: close" header.
* If you are the client, close the connection.
*/
int http_should_keep_alive(const http_parser *parser);
/* Returns a string version of the HTTP method. */
const char *http_method_str(enum http_method m);
/* Return a string name of the given error */
const char *http_errno_name(enum http_errno err);
/* Return a string description of the given error */
const char *http_errno_description(enum http_errno err);
/* Initialize all http_parser_url members to 0 */
void http_parser_url_init(struct http_parser_url *u);
/* Parse a URL; return nonzero on failure */
int http_parser_parse_url(const char *buf, size_t buflen,
int is_connect,
struct http_parser_url *u);
/* Pause or un-pause the parser; a nonzero value pauses */
void http_parser_pause(http_parser *parser, int paused);
/* Checks if this is the final chunk of the body. */
int http_body_is_final(const http_parser *parser);
#ifdef __cplusplus
}
#endif
#endif
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Patch the vendored ESP-IDF httpd so it needs no mbedTLS or PSA.
The WebSocket handshake hashes the client key with SHA-1 and base64-encodes it. The desktop build uses its
own SHA-1 and base64 (desktop/port/src/desktop_crypto.c), so only that block changes. Idempotent.
"""
import re
import sys
from pathlib import Path
root = Path(sys.argv[1])
# esp_http_server.h uses the heap capability flags without including their header (ESP-IDF gets them
# from its own include order), so include it here
hdr = root / "esp_http_server" / "include" / "esp_http_server.h"
h = hdr.read_text()
if '#include "esp_heap_caps.h"' not in h:
h = h.replace("#include ", '#include "esp_heap_caps.h"\n#include ', 1)
hdr.write_text(h)
print("patched", hdr)
ws = root / "esp_http_server" / "src" / "httpd_ws.c"
s = ws.read_text()
if "desktop_crypto.h" not in s:
s = s.replace("#include <psa/crypto.h>\n", "")
s = s.replace("#include <mbedtls/base64.h>\n", '#include "desktop_crypto.h"\n')
s = s.replace("#include <mbedtls/error.h>\n", "")
start = s.index(" /* Generate SHA-1 hash */")
end_marker = "server_key_hash, sizeof(server_key_hash));\n"
end = s.index(end_marker, start) + len(end_marker)
s = s[:start] + (
" /* Generate SHA-1 hash, then base64 (desktop build: desktop_crypto.c) */\n"
" desktop_sha1((const uint8_t *)server_raw_text, strlen(server_raw_text), server_key_hash);\n"
" size_t encoded_len = desktop_base64_encode(server_key_encoded, sizeof(server_key_encoded),\n"
" server_key_hash, sizeof(server_key_hash));\n"
) + s[end:]
ws.write_text(s)
print("patched", ws)
else:
print("already patched", ws)
if "mbedtls" in s or "psa_" in s:
print("WARNING: mbedTLS/PSA still referenced in", ws, file=sys.stderr)
sys.exit(1)
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env bash
# Vendor the third-party sources the desktop build needs, from ESP-IDF (espressif/idf:v6.1) and the cJSON
# managed component, then patch the two spots that use mbedTLS/PSA (see patch_vendor.py).
# Run from the repository root after changing the IDF version: desktop/tools/vendor.sh
set -euo pipefail
cd "$(dirname "$0")/../.."
IDF_IMAGE=${IDF_IMAGE:-espressif/idf:v6.1}
OUT=desktop/third_party
rm -rf "$OUT/esp_http_server" "$OUT/http_parser" "$OUT/cjson"
mkdir -p "$OUT/esp_http_server/src/util" "$OUT/esp_http_server/include" "$OUT/http_parser" "$OUT/cjson"
docker run --rm -v "$PWD/$OUT:/out" "$IDF_IMAGE" bash -c '
set -e; S=/opt/esp/idf/components
cp $S/esp_http_server/src/*.c $S/esp_http_server/src/esp_httpd_priv.h /out/esp_http_server/src/
cp $S/esp_http_server/src/util/* /out/esp_http_server/src/util/
cp $S/esp_http_server/include/esp_http_server.h /out/esp_http_server/include/
cp $S/http_parser/http_parser.c $S/http_parser/http_parser.h $S/http_parser/LICENSE.txt /out/http_parser/
cp $S/esp_http_server/LICENSE /out/esp_http_server/ 2>/dev/null || true
chown -R 0:0 /out
'
# cJSON: the managed component the board and the sim already use (version pinned in dependencies.lock)
CJSON=sim-controller/managed_components/espressif__cjson/cJSON
cp "$CJSON/cJSON.c" "$CJSON/cJSON.h" "$CJSON/LICENSE" "$OUT/cjson/"
python3 desktop/tools/patch_vendor.py "$OUT"
# sdkconfig.h: the config the sim's ESP-IDF linux build generated (the same CONFIG_* values the firmware reads)
if [ -f sim-controller/build/config/sdkconfig.h ]; then
cp sim-controller/build/config/sdkconfig.h desktop/port/include/sdkconfig.h
fi
echo "vendored into $OUT"
+16 -16
View File
@@ -63,7 +63,7 @@ Keys with meaning on the controller (others are stored as they are):
|-----|---------|---------|
| `ap_enabled` | | Wi-Fi access point (open, SSID = hostname, `192.168.5.1`); default `true`; applies after a restart. Holding the D3 button at boot forces it on |
| `ap_password` | | AP password, 8-63 characters (WPA2); empty (default) is an open network; applies after a restart |
| `bridge` | string under 64 characters | `host:port` (UDP, default port 8766) of led-simulator: every ESP-NOW frame goes there as `dst_mac + packet` instead of over the radio, and frames from it (`src_mac + packet`) count as received. Empty or missing: the radio. Applies after a restart. The host build (`sim-controller/`) always uses a bridge (`LED_SIM_BRIDGE`, default `127.0.0.1:8766`) |
| `bridges` | list of strings | Bridges the ESP-NOW frames go to instead of the radio, each up to 79 characters: `/dev/ttyACM1` (a USB bridge board, or `serial:/dev/...`) or `host:port` (UDP: led-simulator, or a network bridge board, default port 8766). Every frame goes to each; a frame several bridges hear arrives once. Empty or missing: the radio. The host applies changes at once (`GET`/`PUT /settings/bridge`); a device applies them after a restart. `bridge` (one address) is still read when `bridges` is missing. |
| `hostname` | | mDNS name (`<hostname>.local`, default `led-controller`); applies after a restart |
| `static_ips` | | List of `{ip, netmask?, gw, dns?}` tried in order when the Ethernet link comes up; the first whose gateway answers ARP is used, else DHCP, else `192.168.4.1/24` for a direct PC cable. Applies after a restart |
| `global_brightness` | integer 0–255 | Global factor of each driver's brightness (see Groups). Stored only: the UI pushes each driver its combined value |
@@ -118,7 +118,7 @@ A preset has `name`, `pattern`, `colors` (`#RRGGBB`), `brightness`, `delay`, `n1
## Zones — `/zones`
A zone has `name`, `names` (driver names, the older way to target drivers), `group_ids` (groups it plays to), `presets` (rows of preset ids), `presets_flat`, `default_preset`, `preset_group_ids`, `sequence_ids`, `animation_ids` (animations shown as one-shot tiles), `content_kind` (`presets` or `sequences`) and `brightness` (0–255, the zone slider).
A zone has `name`, `names` (driver names, the older way to target drivers), `group_ids` (groups it plays to), `presets` (rows of preset ids), `presets_flat`, `default_preset`, `preset_group_ids`, `sequence_ids` (its sequences, looping and one-shot, as tiles; older zones kept one-shots apart in `animation_ids`, which loading and bundle imports fold into `sequence_ids`), `content_kind` (`presets` or `sequences`) and `brightness` (0–255, the zone slider).
| Method | Path | Description |
|--------|------|-------------|
@@ -131,7 +131,7 @@ A zone has `name`, `names` (driver names, the older way to target drivers), `gro
| POST | `/zones/<id>/set-current` | Set the `current_zone` cookie |
| POST | `/zones/<id>/clone` | Copy into the current profile. Body: optional `name` (default `<name> Copy`). 201 |
| GET | `/zones/<id>/content-fragment` | With `HX-Request`: the zone's tab content (HTML); otherwise the main page |
| POST | `/zones/<id>/play` | Body `{"preset_id", "drivers"?}`: upload the preset to the zone's groups and select it (`drivers: false` skips sending). 404 for an unknown zone or preset |
| POST | `/zones/<id>/play` | Body `{"preset_id", "drivers"?}`: upload the preset to the zone's groups and select it (`drivers: false` skips sending, when the UI has sent it). Either way the preset becomes what the zone loops: a looping sequence playing in the zone ends (its drivers are not cleared), and a one-shot comes back to this preset when it ends. 404 for an unknown zone or preset |
| POST | `/zones/<id>/stop` | Select `off` on the zone's groups. `{"stopped": bool}` |
| GET | `/zones/engine/status` | Sequence playback status (as `/sequences/status`) |
@@ -174,9 +174,9 @@ A device is `{id: MAC, name, type: "led", transport: "espnow" | "wifi", address,
## Sequences — `/sequences`
A sequence is `{name, profile_id, kind?, targets?, lanes: [[step, ...], ...], lane_opts?, lanes_group_ids: [[group ids], ...], group_ids, loop (default true), advance_mode: "beats" | "time", steps, step_duration_ms, sequence_transition}`. Every field marked `?` is optional; a sequence without them plays as it always has.
A sequence is `{name, profile_id, targets?, lanes: [[step, ...], ...], lane_opts?, lanes_group_ids: [[group ids], ...], group_ids, loop (default true), advance_mode: "beats" | "time", steps, step_duration_ms, sequence_transition}`. Every field marked `?` is optional; a sequence without them plays as it always has.
- `kind`: `"sequence"` (default) or `"animation"`: a clip that is fired once over whatever runs (see Animations). Both are stored here.
- `loop` (default true): with it off the sequence is a **one-shot** (see One-shots). A one-shot is always timed in seconds: its steps' `seconds` count, and `advance_mode` and lane `mode` are ignored. Older records marked one-shots `kind: "animation"`; one of those without `loop` still plays once.
- `targets`: the drivers the sequence plays to, in order (up to 32): `[{name, group_ids: [group ids], devices: [MACs]}]`. A target reaches every driver in its groups plus each listed driver (by its own group `d<mac>`, see Driver groups). Lanes and steps name targets by index.
- `lane_opts`: one object per lane (same index as `lanes`):
- `mode`: `"beats"` or `"time"`, overriding `advance_mode` for this lane, so beat lanes and time lanes run side by side.
@@ -189,7 +189,7 @@ A sequence is `{name, profile_id, kind?, targets?, lanes: [[step, ...], ...], la
- `targets`: indexes of the lane's targets this step lights (default: all of the lane's, or the chase position).
- `others: "off"`: the lane's other targets go off for this step.
- `rest: true`: nothing lit; the lane's targets go off.
- `animation_id`: fire that animation instead of a preset. With `length: "animation"` the step lasts as long as the animation (at the current tempo).
- `animation_id`: play that sequence once over the zone (a one-shot clip) instead of a preset, for the step's `beats`/`seconds`. With `length: "animation"` the step lasts one pass of it (at the current tempo).
| Method | Path | Description |
|--------|------|-------------|
@@ -198,10 +198,10 @@ A sequence is `{name, profile_id, kind?, targets?, lanes: [[step, ...], ...], la
| POST | `/sequences` | Create in the current profile. A non-empty `steps` without lanes becomes lane 0. Reply `{"<id>": sequence}`, 201 |
| PUT | `/sequences/<id>` | Merge fields; stops it when it is playing |
| DELETE | `/sequences/<id>` | Delete; stops it when it is playing |
| POST | `/sequences/<id>/play` | Body `{"zone_id"}` (required). Reply `{"ok": true, "pending": bool, ...}`. 400 for a missing zone, a sequence without steps or one from another profile |
| POST | `/sequences/stop` | Stop playback (and any animation) and clear the presets on the zone's groups. `{"ok": true}` |
| POST | `/sequences/<id>/fire` | Play it once as an animation over whatever runs. Body `{"zone_id"?, "wait"?: "now" (default) \| "beat" \| "downbeat"}`; without `zone_id`, the playing sequence's zone. Reply `{"ok": true, "wait"}`. 404 for another profile's, 400 without a zone or steps |
| POST | `/sequences/overlay/stop` | End the animation now; its drivers go back (as when it ends). `{"ok": true}` |
| POST | `/sequences/<id>/play` | Body `{"zone_id"}` (required). A one-shot (`loop` off) plays as `/fire` with `wait: "now"`. Reply `{"ok": true, "pending": bool, ...}`. 400 for a missing zone, a sequence without steps or one from another profile |
| POST | `/sequences/stop` | Stop playback (and any one-shot) and clear the presets on the zone's groups. `{"ok": true}` |
| POST | `/sequences/<id>/fire` | Play it once (a one-shot) over whatever runs. Body `{"zone_id"?, "wait"?: "now" (default) \| "beat" \| "downbeat"}`; without `zone_id`, the playing sequence's zone. Reply `{"ok": true, "wait"}`. 404 for another profile's, 400 without a zone or steps |
| POST | `/sequences/overlay/stop` | End the one-shot now; its drivers go back (as when it ends). `{"ok": true}` |
| POST | `/sequences/sync-phase` | Body `{"mode": "step" | "pass"}`: `step` restarts the current step's beat count, `pass` restarts the sequence. Also makes this beat bar beat 1. 409 when nothing plays |
| GET | `/sequences/status` | Playback status (below) |
| GET | `/sequences/<id>/export` | Sequence bundle (the sequence and its presets) |
@@ -210,18 +210,18 @@ A sequence is `{name, profile_id, kind?, targets?, lanes: [[step, ...], ...], la
**Playback.** One sequence plays at a time, in one zone.
- **Start.** Each lane's first preset is uploaded to the lane's groups and selected, then the lane's other presets are uploaded, and every driver in the zone gets its combined brightness with the zone slider.
- **Advancing.** A time lane moves on when its step's `seconds` are up, whatever the beat. When lane 0 is a time lane, the status has `lane0_step_elapsed_ms` and `lane0_step_duration_ms` and `beat_readout` is empty. A beat lane counts quarter beats (the controller ticks between beats from the last beat interval) towards its step's `beats` ÷ `rate`, then moves on. Each step's preset is uploaded to all of the lane's targets (unless already there), then selected on the targets the step lights.
- **End.** Without `loop` the sequence ends after one pass. Its presets are cleared from the zone's groups, and the readout keeps `n/n`.
- **End.** A looping sequence plays until stopped or replaced. A one-shot never starts as the zone's sequence (see One-shots).
- **Switching.** Starting another sequence while one plays waits for the next beat. It waits for the next downbeat only when `sequence_switch_wait` is `downbeat` and the mic is timing. The current sequence holds meanwhile.
- **Animations.** `/sequences/<id>/fire` (or a step's `animation_id`) plays a sequence once in a second player over the running one. An animation loops only with `loop: true`.
- While it plays, the sequence keeps time, but its sends leave out the drivers the animation's lanes reach: groups are split into those drivers' own groups.
- **One-shots.** A one-shot (`loop` off) played on a zone (`/play` or `/fire`), or as a step's `animation_id`, plays once in a second player over whatever runs, then the zone goes back to its last looping preset or sequence. Played over the zone, any sequence plays once.
- While it plays, the looping sequence keeps time, but its sends leave out the drivers the one-shot's lanes reach: groups are split into those drivers' own groups.
- When it ends (or `/sequences/overlay/stop`), those drivers get the sequence's current step again. With no sequence playing they get the zone's last played preset, else off.
- Firing another animation replaces the one playing. Drivers the new one doesn't reach go back.
- A sequence that ends while an animation plays clears the zone once the animation is over.
- Another one-shot replaces the one playing. Drivers the new one doesn't reach go back.
- A sequence stopped while a one-shot plays clears the zone once the one-shot is over.
- **Beat source.** Beats come from the mic's beat detector while audio timing is on (`/api/audio/start`) and it has a tempo lock. Otherwise they come from a clock at `audio_simulated_bpm`, whose beats also go to the drivers. Beats closer than 0.3 s (200 BPM) are dropped.
Status: `{"active": false, "beat_readout": "", overlay}` when idle, else `{active, advance_mode, sequence_id, zone_id, num_lanes, total_sequence_steps, lane0_current_step, lane0_lane_length, lane0_beat_in_step, lane0_beats_per_step, lane0_preset_id, lane0_preset_name, sequence_beat_at, sequence_beats_per_pass, sequence_loop_beat, beat_readout, lanes, overlay}`.
- `lanes`: one entry per playing lane, `{step (0-based), steps, mode, started, done, pos? (chase: the target index lit first), beat_in_step and beats_in_step (beat lanes) or elapsed_ms and duration_ms (time lanes)}`.
- `overlay`: `{active, pending, pending_id?}`, plus `{sequence_id, zone_id, drivers, progress (0–1), lanes}` while an animation plays.
- `overlay`: `{active, pending, pending_id?}`, plus `{sequence_id, zone_id, drivers, progress (0–1), lanes}` while a one-shot plays.
## Audio — `/api/audio`
+1 -1
View File
@@ -1 +1 @@
{"ambiguous_scale": "", "code_only": false, "epoch": "v0.9.101-s36-g1339418af9f9", "excludes": [], "follow_symlinks": false, "full_clean": true, "gitignore": true, "graph_mtime_ns": 1794434468032040137, "graph_size": 3355638, "html_present": true, "no_cluster": false, "rcfile": "", "scan_digest": "9eaa77f8bb2f8dbadf43cb5d942b4c65", "scan_root": "/home/jimmy/projects/led-controller", "viz_node_limit": ""}
{"ambiguous_scale": "", "code_only": false, "epoch": "v0.9.101-s36-g1339418af9f9", "excludes": [], "follow_symlinks": false, "full_clean": true, "gitignore": true, "graph_mtime_ns": 1794810394542523020, "graph_size": 5226482, "html_present": true, "no_cluster": false, "rcfile": "", "scan_digest": "79c37028c2fa169bb543b5193bebcca5", "scan_root": "/home/jimmy/projects/led-controller", "viz_node_limit": ""}
-9
View File
@@ -2,7 +2,6 @@
"1": "htmx Library",
"3": "Browser Tests & Mockup Images",
"4": "Audio UI (JS)",
"5": "ESP-NOW TX & DMX Pulse",
"7": "led-tool Device CLI",
"10": "Spec: Pi Animation Engine",
"12": "Presets UI (JS)",
@@ -19,8 +18,6 @@
"49": "Chromium Colour Picker JS",
"51": "API Tests: Devices",
"53": "mpremote Transport",
"54": "Outputs Config (C)",
"60": "mpremote Serial Transport",
"61": "API Test Fixtures & Audio",
"62": "Microdot Request (dmx)",
"63": "Help: Zones & Palette",
@@ -28,16 +25,11 @@
"73": "Microdot WebSocket (dmx)",
"76": "Controller Overview & OTA Docs",
"79": "Audio Monitor Page",
"80": "Art-Net DMX Tests",
"81": "DMX Output Manager",
"85": "ESP-NOW Sender Bridge",
"87": "Microdot Async IO (dmx)",
"88": "DMX Settings",
"91": "Microdot Routing (dmx)",
"92": "Bench Test Plan",
"95": "Microdot Auth (dmx)",
"96": "Serial DMX & WiFi",
"97": "DMX Pattern Player",
"98": "DMX Preset Model",
"101": "Groups UI (JS)",
"103": "Help: Mobile Menu Image",
@@ -46,7 +38,6 @@
"109": "Driver Message API Docs",
"111": "led_strip Manifest",
"113": "Outputs UI (JS)",
"114": "DMX Driver Docs",
"115": "Help PDF: Overview",
"116": "Mockups Index Image",
"118": "Help: Header Toolbar Image",
+1 -1
View File
@@ -1 +1 @@
{"0": "5a6fe369b1e9eab9", "1": "2d791c43bb8436ec", "2": "b549e617825efc45", "3": "658093cbc50e95df", "4": "7221607390cbf8f4", "5": "b441bdea17ad6297", "6": "f3e3f8fa8f323411", "7": "f1cd30037a4aa8fa", "8": "c7753eeed86c8002", "9": "5e6bedc1d8578bcb", "10": "ba809033c2ac79db", "11": "1cdb300036b95f18", "12": "cd9a1302e31a16be", "13": "38e3459e42de82ae", "14": "907a7a5a980e7ee9", "15": "55f791413a3c65b8", "16": "7dd1b08d3601a3f4", "17": "b4be1705befe2c85", "18": "be98f7b72ea43b2c", "19": "36e64b70bd3252ce", "20": "8fef51c59e728cbb", "21": "f3f303832b603793", "22": "b25a5c67c6b80682", "23": "afa2c3d7d54293f1", "24": "90c916e427b5ebfd", "25": "9521502a76e3926d", "26": "08c17760b6a78441", "27": "27e4c3eb54733fed", "28": "f55b318ce2ea37bf", "29": "a5cce0735423723c", "30": "8c465f3df9b2ddbd", "31": "b63da06d6ca05666", "32": "0a565e66eafdd7eb", "33": "944011bf47895ae9", "34": "3f0d61a8871fc63a", "35": "4f79d9f75a50cf01", "36": "503896ae7591c77b", "37": "2edd892aa6e5eaa8", "38": "312ff5e741d2a39f", "39": "d0ff09e1589219cc", "40": "0cbacf6eb12d6315", "41": "64b6c5772748a82d", "42": "01dfdff7dbabb88c", "43": "56a6f4b36b77038f", "44": "bf21d11ea6c4fadf", "45": "5be380e898e13324", "46": "471f838c9f9faeb9", "47": "d5845e875703cccd", "48": "46b84e04c8a769a1", "49": "01bb51d3946bc98b", "50": "dbf9e50467c11779", "51": "fc3745c70cad6065", "52": "7e5187509e0145be", "53": "141393a45638779c", "54": "b761f45a82eacec9", "55": "5e6521bb93696132", "56": "8a68d6ebf88e07ea", "57": "b17e4e22dfe31a3d", "58": "973ac14a32bd0435", "59": "8ae951b21941381b", "60": "4899a61ba741a2f8", "61": "3a757a4e17e2cc29", "62": "88ecf3d949c8bbdc", "63": "3f32204f50610f42", "64": "6852de7c708dba55", "65": "81c20c6e0d0187d4", "66": "dc8e43fa499882ac", "67": "bd20a78a99f60228", "68": "e1fe5116ee8ce485", "69": "aef962d800518446", "70": "9affb95b7a8926f7", "71": "551d7508ae9dc04a", "72": "375c9adb2b24179c", "73": "298efcf42a95f405", "74": "9dd9fa4b945a0f59", "75": "6f7f2eba3df89704", "76": "6e5f52cb9e7a3080", "77": "689536a1995dc379", "78": "f2f70696e107cc5c", "79": "0aadcaffca2fec2f", "80": "b44b759b294e7fb1", "81": "2a44adbbdb7b2cc2", "82": "d48cec59dd722fd4", "83": "dd61dba571aab679", "84": "238401c059f27744", "85": "67e8988d64ef02c3", "86": "c7a4d2e3858a9eeb", "87": "186dd13162172b05", "88": "281e8bde953022f8", "89": "b2ccf867707890e2", "90": "6f2dd301866c484e", "91": "8726692dfc1a3d69", "92": "fe3f7fa17b6e9140", "93": "1c9c389e7ea7dd32", "94": "a9147a14f38d1bad", "95": "84c30b82ce45e85f", "96": "f71d81296b66decd", "97": "1ff181597dc9980c", "98": "7f4284e17bf23520", "99": "3d6b7edec8e513d8", "100": "50b0e31410e284e6", "101": "e8c3d507c7523478", "102": "729a2de1ab6b12b5", "103": "89850ee47c9ca738", "104": "6b44fd779534127a", "105": "98b16b4bcf978a30", "106": "aeb73082ae7eab1a", "107": "f4f2630b6fbd48ca", "108": "50ea206ca32f8368", "109": "62dfdb23b2c54d82", "110": "7d5b56eb98869909", "111": "66b50b0357357d62", "112": "f07f0a842de7350e", "113": "66e63867ee9ac604", "114": "b87bf40ea7db9bd2", "115": "f3b1e77b5ff745de", "116": "2d5d657b0cb526af", "117": "9a63ee4db57902d7", "118": "4b507a629ac7f04f", "119": "c394c3d1e26256c8", "120": "8059a64174d9729b", "121": "b77edb57c9058871", "122": "9b758d47bd1a6c69", "123": "3757904e987193d1", "127": "682784ef7eb6ab79", "129": "93fc8b4ad7c9ca62", "130": "8363eed2536a6846", "131": "fe6e422923b8d6ef", "134": "692d38c636992a64", "135": "a7796e8a95a7935c", "138": "513f0c5816361dda", "140": "7f4e0effc09d9671", "141": "ab64084e0052dd1b", "142": "01c470ad572a2a84", "143": "9767524947f5d239", "144": "a7a26633381cc935", "145": "8fc084b6564c04cd", "146": "cb4b693c8a2db3d0", "149": "79da6ef18a0fc9bb", "150": "e7d4ba7c2a13b959", "155": "59ee4fee36503aee", "156": "f7b8f6a932f020e1", "157": "2baed17a20d35d4e", "158": "1496a7273bd8cbf0", "159": "70c38a287cac17ff", "166": "884b25ce5534ca30", "167": "8c903324815075bf", "170": "ca0193e69e1cf4c6", "171": "c8052f332c3d2369", "172": "ffa84e66ab7f2c83", "173": "9bcf4d1a57c0ba2a", "174": "6ca582b7df7276a1", "175": "de377ed03b71265f", "176": "1fb6d892ae8678c7", "180": "5ae949a86bd02dd3", "181": "040c831fbc62df23", "182": "09fe188418c42b7a", "183": "90b339bb352b5f47", "185": "ced44d681e2ec183", "186": "ff963270b8878129", "187": "bb41b7312f4e3083", "188": "a08753a73e0ca7d5", "189": "0cadf82de76cac0c", "190": "f40e0095eef0a2a1", "191": "2427a73600db473c", "192": "ae89d1eb8e024c9a", "193": "25a3de734ba30abf", "194": "6d34a1978e2935a7", "195": "8ae29623c3cfc6a6", "196": "32051c55a4723b9c", "197": "227d5082400af4ff", "199": "37b8871950bf5c3b", "201": "d2369c4cd0208ca6", "204": "54defa1f3d2a9a86", "209": "5fd8f1c618642991", "210": "363020d929127998", "211": "24c2db367e0711da", "214": "d651aa39cd803275", "227": "cc359b28b621fe98", "229": "83c733c01acff1c0", "231": "92b69d5dfa1439e0", "235": "dbe9ebef6953c86b", "236": "2b8491e23b3448a8", "237": "97756402288d8dbd"}
{"0": "7a92372f79629cba", "1": "2d791c43bb8436ec", "2": "1d6661269ee7ddec", "3": "658093cbc50e95df", "4": "7221607390cbf8f4", "5": "6ad0205b25376215", "6": "3f9c3996c2f91db5", "7": "c7c87e8c1669ebc3", "8": "e7e52a26e954e7ce", "9": "5e6bedc1d8578bcb", "10": "ba809033c2ac79db", "11": "15e440b773c9b1c1", "12": "cd9a1302e31a16be", "13": "38e3459e42de82ae", "14": "c430d980c0aa5400", "15": "5701d88bd0246098", "16": "72d4d367b9ad97c1", "17": "66823a2611e5de9a", "18": "156c5f743b028d1e", "19": "36e64b70bd3252ce", "20": "67a9e5cbf438aa81", "21": "4bb89f02eded6ed5", "22": "1447570e824fc4d5", "23": "62f89b153a7f074c", "24": "57a09027a46a37a4", "25": "e8bcfe2daf9c27fd", "26": "af92d1a97a660495", "27": "0c6a31b43c1528f4", "28": "f55b318ce2ea37bf", "29": "a5cce0735423723c", "30": "8c465f3df9b2ddbd", "31": "b63da06d6ca05666", "32": "6f1eb1b9b88ae70a", "33": "3225016905fc064c", "34": "3f2d040dbfab55b5", "35": "93e0f20aa2bb640b", "36": "6bc1e46289a61a87", "37": "bf9c16fdf5186711", "38": "438001396563b41e", "39": "d0ff09e1589219cc", "40": "d4ca824fee2fddbb", "41": "93b15b1e0802094d", "42": "ca5f38fabb644c68", "43": "6dc5a3d228885f0c", "44": "00eedb34d6d4d758", "45": "fd63a12ba730288d", "46": "e25101c697775651", "47": "232a8ec7bde4f06c", "48": "46b84e04c8a769a1", "49": "01bb51d3946bc98b", "50": "669d36e44980ad3b", "51": "c3eef28729a94247", "52": "f87e676751367882", "53": "141393a45638779c", "54": "13dd9e2842ab4a0c", "56": "973ac14a32bd0435", "57": "2ecebdcf40a907d5", "58": "b717d60767a4742a", "59": "d66ddb7b8d0e5377", "60": "4d82a4233c9bc88f", "61": "06de387944b6f979", "62": "50e29eb032567d0a", "63": "3f32204f50610f42", "64": "b099f2f64c3d1121", "65": "2b595be0fe1c1cf4", "66": "383b151eb4411452", "67": "0c75e37d14ea4be0", "68": "05aa41461f77a88a", "69": "5ea357e009193aee", "70": "9affb95b7a8926f7", "71": "05a210a1976248a2", "72": "1d9bb939049a306e", "73": "298efcf42a95f405", "74": "a50c316144a6002a", "75": "fe3f7fa17b6e9140", "76": "fae5563ac3b5ad8d", "77": "6006b6cc4bb17d38", "78": "74c26c47a62b8460", "79": "0aadcaffca2fec2f", "80": "b44b759b294e7fb1", "81": "2a44adbbdb7b2cc2", "82": "7d5560702e41f10c", "83": "57dfcce26469d644", "84": "49ada2108278ec5e", "85": "67e8988d64ef02c3", "86": "17b22093dfd4008f", "87": "186dd13162172b05", "88": "281e8bde953022f8", "89": "58ef71533f93a12a", "90": "4bc03d14d36cb508", "91": "8726692dfc1a3d69", "92": "3fa05329c52e7a31", "93": "c2ce778772ae9284", "94": "0d97fe007c3a0936", "95": "9dbeb95e43dc6aec", "96": "d11013acb5d45e73", "97": "38f7187e95766e7e", "98": "dc0fda9a9c5206f5", "99": "c46f05b1d5aad36d", "100": "8a68d6ebf88e07ea", "101": "e8c3d507c7523478", "102": "5e7048115c96c435", "103": "89850ee47c9ca738", "104": "6b44fd779534127a", "105": "98b16b4bcf978a30", "106": "002738beed77ef74", "107": "01172c7d40a936d1", "108": "fbdcfbea69ac263a", "109": "62dfdb23b2c54d82", "110": "05419fa6a91533bf", "111": "66b50b0357357d62", "112": "496a0a14d2f3f063", "113": "66e63867ee9ac604", "114": "fab5dd214febb09b", "115": "f3b1e77b5ff745de", "116": "2d5d657b0cb526af", "117": "1b4c47d15d2142f0", "118": "4b507a629ac7f04f", "119": "c394c3d1e26256c8", "120": "8059a64174d9729b", "121": "b77edb57c9058871", "122": "9b758d47bd1a6c69", "123": "3757904e987193d1", "124": "da462741dfe87d17", "125": "6da62559e5213a9e", "126": "198cf8c4d314f85d", "127": "682784ef7eb6ab79", "128": "24d10974d4bcceb3", "129": "93fc8b4ad7c9ca62", "130": "8363eed2536a6846", "131": "3d3f3acc7c0f77f0", "132": "95ef3791087ae3cb", "133": "4bf9ae36ecae2a53", "134": "692d38c636992a64", "135": "d8f24f323e8fd32f", "136": "69e80d35078aa3e0", "137": "bb459edeb899b14f", "138": "513f0c5816361dda", "139": "fe6e422923b8d6ef", "140": "7f4e0effc09d9671", "141": "bb477038ab0c5e8e", "142": "01c470ad572a2a84", "143": "9767524947f5d239", "144": "a7a26633381cc935", "145": "8fc084b6564c04cd", "146": "cb4b693c8a2db3d0", "147": "b031133b75382475", "148": "73b79ac1f6ea0d0f", "149": "7b4f76be902aa451", "150": "535ff56fa874156d", "151": "82887211cf2bedf5", "152": "d7b01ac313a993bf", "153": "a1afbf3a5362e984", "154": "7ab2338abe50e2d2", "155": "f1c77269c52723e7", "156": "f7b8f6a932f020e1", "157": "278ab211ccdf5147", "158": "1496a7273bd8cbf0", "159": "70c38a287cac17ff", "160": "1b3167ce48880094", "161": "d9b95efbe9a3ca0a", "162": "79347942af0064f9", "163": "ee9ad33fb556ea89", "164": "ff462f4575171eb0", "165": "5be380e898e13324", "166": "03cf19cd58994715", "167": "68a0452a8a24cf5d", "168": "c33017b892148689", "169": "3d3f4c5f67647202", "170": "982c977c10761a5f", "171": "c8052f332c3d2369", "172": "ffa84e66ab7f2c83", "173": "9bcf4d1a57c0ba2a", "174": "6ca582b7df7276a1", "175": "de377ed03b71265f", "176": "1fb6d892ae8678c7", "177": "580e0924c1fb2e8e", "178": "34be047eea580b62", "179": "84fca3c51ff10cc5", "180": "5ae949a86bd02dd3", "181": "040c831fbc62df23", "182": "09fe188418c42b7a", "183": "90b339bb352b5f47", "184": "01f3fbb5f39b9987", "185": "ced44d681e2ec183", "186": "ff963270b8878129", "187": "bb41b7312f4e3083", "188": "a08753a73e0ca7d5", "189": "0cadf82de76cac0c", "190Line truncated
+110 -66
View File
@@ -1,92 +1,136 @@
{
"0": "IdfDevice",
"2": "machine.py",
"6": "audio.c",
"5": "cJSON",
"6": "create_app",
"8": "ab",
"9": "Compiler",
"11": "led-driver/main/ota.c",
"14": "patterns.c",
"11": "seq_timeline.js",
"14": "sim_rig.c",
"15": "new_id",
"17": "server.py",
"18": "main/main.c",
"21": "main/main.c",
"22": "esp_log",
"23": "engine.c",
"24": "ws.c",
"17": "SerialTransport",
"18": "esp_err.h",
"21": "freertos.c",
"22": "LedSimulatorApp",
"23": "cJSON_IsString",
"24": "cJSON_Delete",
"25": "Microdot",
"26": "led_strip_rmt_dev.c",
"26": "ctrl_msg.cpp",
"27": "seqplay.c",
"29": "binary_envelope.py",
"31": "PyboardCommand",
"32": "beat.c",
"33": "web.cpp",
"32": "cJSON_CreateObject",
"33": "httpd_parse.c",
"34": "test_sequences.py",
"35": "microdot.py",
"37": "led_strip_spi_dev.c",
"38": "store_save",
"40": "audio_api.c",
"41": "sim_stubs.c",
"35": "cJSON_Delete",
"37": "http_parser",
"38": "socket",
"40": "xSemaphoreGive",
"41": "WS2812",
"42": "run_all",
"43": "ws_client.cpp",
"44": "time",
"45": "test_presets.py",
"46": "BridgeSim",
"50": "WS2812",
"52": "Transport",
"55": "patterns.cpp",
"56": "test_routes.py",
"57": "ESPNow",
"58": "test_outputs.py",
"59": "microdot.py",
"43": "usb_cfg.cpp",
"44": "httpd_handle_t",
"45": "http_parser.h",
"46": "http_parser.c",
"50": "exchange",
"52": "sys",
"54": "httpd_sess.c",
"56": "test_outputs.py",
"57": "httpd_config",
"58": "gallery.js",
"59": "mic_alsa.c",
"60": "nvs_sim.cpp",
"64": "ddp_test.py",
"65": "test_audio.py",
"66": "esp_timer_get_time",
"67": "os",
"68": "build_app",
"69": "main/ota.c",
"71": "NeoPixel",
"72": "_simlink.py",
"74": "store_lock",
"75": "json",
"77": "usb_cfg.cpp",
"78": "urandom.py",
"82": "bridge_sim.py",
"83": "LedSimulatorApp",
"65": "ESPNow",
"66": "httpd_handle_t",
"67": "BridgeSim",
"68": "httpd_uri.c",
"69": "led_strip_rmt_encoder.c",
"71": "rel.c",
"72": "httpd_data",
"74": "presets.cpp",
"75": "Bench test: S3 controller and one LED driver",
"77": "espnow_link.cpp",
"78": "sim_split.js",
"80": "artnet_dmx.py",
"81": "OutputManager",
"82": "events",
"83": "web.c",
"84": "unique",
"86": "net.cpp",
"89": "Rig",
"90": "packet",
"93": "envelope.c",
"94": "api_call_t",
"99": "status_get_handler",
"100": "ddp.cpp",
"102": "rig_seed.py",
"106": "._loop_main",
"107": "find_devices",
"108": "esp_timer_get_time",
"110": "engine_init",
"112": "ws_slot_t",
"117": "read_serial",
"131": "sim_demo.py",
"135": "store_coll",
"141": "machine.py",
"89": "api_call_t",
"90": "Sender",
"92": "bridge_serial.c",
"93": "events",
"94": "Type",
"96": "esp_timer_create",
"97": "v1 driver messages (long/short keys)",
"99": "httpd_txrx.c",
"100": "test_routes.py",
"102": "httpd_req_aux",
"106": "USB ESP-NOW bridge",
"107": "main",
"108": "rig_seed.py",
"110": "run_soak",
"112": "test_patterns.py",
"114": "dependencies",
"117": "outputs.c",
"124": "esp_httpd_priv.h",
"125": "led_strip_spi_dev.c",
"126": "esp_http_server_dispatch_event",
"128": "httpd_ctrl_data",
"131": "flags",
"132": "microdot.py",
"133": "http_parser_url_fields",
"135": "PatternPlayer",
"136": "HttpDevice",
"137": "time",
"139": "sim_demo.py",
"141": "DMX Driver Art-Net and serial gateway",
"143": "test_rig_sim.py",
"144": "settings_editor.js",
"149": "res_device.c",
"150": "api_error",
"147": "bootloader/CMakeFiles/4.0.3/CompilerIdC/CMakeCCompilerId.c",
"148": "postinst",
"149": "api_error",
"150": "postrm",
"151": "prerm",
"152": "vendor.sh",
"153": "bootloader/CMakeFiles/4.0.3/CompilerIdCXX/CMakeCXXCompilerId.cpp",
"154": "build-v61/CMakeFiles/4.0.3/CompilerIdC/CMakeCCompilerId.c",
"155": "app.js",
"159": "led-driver/web/app.js",
"166": "sequences_route",
"167": "api_id",
"160": "build-v61/CMakeFiles/4.0.3/CompilerIdCXX/CMakeCXXCompilerId.cpp",
"161": "bootloader/config/sdkconfig.h",
"162": "bootloader/project_elf_src_esp32c3.c",
"163": "build-v61/config/sdkconfig.h",
"164": "build-v61/project_elf_src_esp32c3.c",
"165": "test_presets.py",
"166": "mdns_host.c",
"167": "SerialDMX",
"168": "NeoPixel",
"169": "build_sim_web.sh",
"170": "dependencies",
"197": "presets.cpp",
"199": "res_group.c",
"201": "_simlink_web.py",
"177": "espnow_tx.c",
"178": "mac_str",
"179": "load_config",
"184": "beat.c",
"197": "cJSON_GetObjectItem",
"198": "Transport",
"199": "httpd_req",
"200": "HTTPException",
"201": "http_parser_type",
"202": "json",
"203": "desktop_main.c",
"204": "_simlink_proc.py",
"205": "esp_http_server.h",
"207": "relay_forward",
"209": "WLAN",
"210": "fetch_cache.js",
"211": "NoCaseDict",
"214": "SimRing",
"211": "MultiDict",
"212": "random",
"214": "workspace/patterns/__init__.py",
"224": "build.sh",
"225": "sim-driver/include/driver/gpio.h",
"227": "dependencies",
"229": "examples/blink.py",
"231": "led_driver_sim_hook.py",
@@ -0,0 +1,92 @@
{
"1": "htmx Library",
"3": "Browser Tests & Mockup Images",
"4": "Audio UI (JS)",
"5": "ESP-NOW TX & DMX Pulse",
"7": "led-tool Device CLI",
"10": "Spec: Pi Animation Engine",
"12": "Presets UI (JS)",
"13": "Zones UI (JS)",
"16": "Sequences UI (JS)",
"19": "led_strip Component Docs",
"20": "Art-Net Output",
"28": "Devices UI (JS)",
"30": "Colour Picker Mockups",
"36": "API Docs: Outputs & Audio",
"39": "Beat Detection DSP (C)",
"47": "USB Latency Tools",
"48": "Colour Picker JS",
"49": "Chromium Colour Picker JS",
"51": "API Tests: Devices",
"53": "mpremote Transport",
"54": "Outputs Config (C)",
"60": "mpremote Serial Transport",
"61": "API Test Fixtures & Audio",
"62": "Microdot Request (dmx)",
"63": "Help: Zones & Palette",
"70": "Index Page Modals",
"73": "Microdot WebSocket (dmx)",
"76": "Controller Overview & OTA Docs",
"79": "Audio Monitor Page",
"80": "Art-Net DMX Tests",
"81": "DMX Output Manager",
"85": "ESP-NOW Sender Bridge",
"87": "Microdot Async IO (dmx)",
"88": "DMX Settings",
"91": "Microdot Routing (dmx)",
"92": "Bench Test Plan",
"95": "Microdot Auth (dmx)",
"96": "Serial DMX & WiFi",
"97": "DMX Pattern Player",
"98": "DMX Preset Model",
"101": "Groups UI (JS)",
"103": "Help: Mobile Menu Image",
"104": "Pattern Selector Mockup Image",
"105": "Driver Pattern Docs",
"109": "Driver Message API Docs",
"111": "led_strip Manifest",
"113": "Outputs UI (JS)",
"114": "DMX Driver Docs",
"115": "Help PDF: Overview",
"116": "Mockups Index Image",
"118": "Help: Header Toolbar Image",
"119": "Help: Preset Editor Image",
"120": "Dashboard Mockup Image",
"121": "Device Management Mockup Image",
"122": "Presets Mockup Image",
"123": "Pattern Contract",
"127": "Numpad Shortcuts (JS)",
"129": "Colour Picker Demo Image",
"130": "Settings Mockup Image",
"134": "API Tests: Settings",
"138": "Help: Colour Palette Image",
"140": "LED Driver README",
"142": "SPI Example Manifest",
"145": "Help PDF: Modes",
"146": "Help: Tab Preset Strip Image",
"156": "RMT Example Manifest",
"157": "Help Tab JS",
"158": "Settings Page Template",
"171": "List Search (JS)",
"172": "DMX Solid Pattern",
"173": "led-test Manifest",
"174": "VPN Autoconnect Script",
"175": "Zone Devices Panel",
"176": "graphify Instructions",
"180": "Device Mockup Modals",
"181": "bulk.sh Script",
"182": "deploy.sh Script",
"183": "Driver install.sh",
"185": "led-tool install.sh",
"186": "Help PDF Build Script",
"187": "Web Build Script",
"188": "Patterns UI (JS)",
"189": "DMX Patterns Init",
"190": "Mockup Tab Switch",
"191": "Spec: Pattern Selector UI",
"192": "mpremote Package",
"193": "Bundle Import/Export (JS)",
"194": "Colour Palette (JS)",
"195": "Profiles UI (JS)",
"196": "Zone Palette (JS)"
}
+762
View File
@@ -0,0 +1,762 @@
# Graph Report - led-controller (2026-11-12)
## Corpus Check
- 262 files · ~238,926 words
- Verdict: corpus is large enough that graph structure adds value.
- Unclassified: 52 file(s) not represented in the graph (top: (none) 26, .mdc 6, .css 6)
## Summary
- 3524 nodes · 8659 edges · 184 communities (125 shown, 59 thin omitted)
- Extraction: 84% EXTRACTED · 16% INFERRED · 0% AMBIGUOUS · INFERRED: 1379 edges (avg confidence: 0.85)
- Token cost: 0 input · 0 output
## Graph Freshness
- Built from commit: `93e986b2`
- Run `git rev-parse HEAD` and compare to check if the graph is stale.
- Run `graphify update .` after code changes (no API cost).
## Community Hubs (Navigation)
- IdfDevice
- htmx Library
- machine.py
- Browser Tests & Mockup Images
- Audio UI (JS)
- ESP-NOW TX & DMX Pulse
- audio.c
- led-tool Device CLI
- ab
- Compiler
- Spec: Pi Animation Engine
- led-driver/main/ota.c
- Presets UI (JS)
- Zones UI (JS)
- patterns.c
- new_id
- Sequences UI (JS)
- server.py
- led_strip Component Docs
- Art-Net Output
- main/main.c
- esp_log
- engine.c
- ws.c
- Microdot
- led_strip_rmt_dev.c
- seqplay.c
- Devices UI (JS)
- binary_envelope.py
- Colour Picker Mockups
- PyboardCommand
- beat.c
- web.cpp
- test_sequences.py
- microdot.py
- API Docs: Outputs & Audio
- led_strip_spi_dev.c
- store_save
- Beat Detection DSP (C)
- audio_api.c
- sim_stubs.c
- run_all
- ws_client.cpp
- time
- test_presets.py
- BridgeSim
- USB Latency Tools
- Colour Picker JS
- Chromium Colour Picker JS
- WS2812
- API Tests: Devices
- Transport
- mpremote Transport
- Outputs Config (C)
- patterns.cpp
- test_routes.py
- ESPNow
- test_outputs.py
- microdot.py
- mpremote Serial Transport
- API Test Fixtures & Audio
- Microdot Request (dmx)
- Help: Zones & Palette
- ddp_test.py
- test_audio.py
- esp_timer_get_time
- os
- build_app
- main/ota.c
- Index Page Modals
- NeoPixel
- Microdot WebSocket (dmx)
- store_lock
- json
- Controller Overview & OTA Docs
- usb_cfg.cpp
- Audio Monitor Page
- Art-Net DMX Tests
- DMX Output Manager
- bridge_sim.py
- LedSimulatorApp
- unique
- ESP-NOW Sender Bridge
- net.cpp
- Microdot Async IO (dmx)
- DMX Settings
- Rig
- packet
- Microdot Routing (dmx)
- Bench Test Plan
- envelope.c
- api_call_t
- Microdot Auth (dmx)
- Serial DMX & WiFi
- DMX Pattern Player
- DMX Preset Model
- status_get_handler
- ddp.cpp
- Groups UI (JS)
- rig_seed.py
- Help: Mobile Menu Image
- Pattern Selector Mockup Image
- Driver Pattern Docs
- ._loop_main
- find_devices
- esp_timer_get_time
- Driver Message API Docs
- engine_init
- led_strip Manifest
- ws_slot_t
- Outputs UI (JS)
- DMX Driver Docs
- Help PDF: Overview
- Mockups Index Image
- read_serial
- Help: Header Toolbar Image
- Help: Preset Editor Image
- Dashboard Mockup Image
- Device Management Mockup Image
- Presets Mockup Image
- Pattern Contract
- Numpad Shortcuts (JS)
- Colour Picker Demo Image
- Settings Mockup Image
- sim_demo.py
- store_coll
- Help: Colour Palette Image
- LED Driver README
- machine.py
- SPI Example Manifest
- test_rig_sim.py
- settings_editor.js
- Help PDF: Modes
- Help: Tab Preset Strip Image
- res_device.c
- api_error
- app.js
- RMT Example Manifest
- Help Tab JS
- Settings Page Template
- led-driver/web/app.js
- sequences_route
- api_id
- dependencies
- List Search (JS)
- DMX Solid Pattern
- led-test Manifest
- VPN Autoconnect Script
- graphify Instructions
- bulk.sh Script
- deploy.sh Script
- Driver install.sh
- led-tool install.sh
- Help PDF Build Script
- Web Build Script
- Spec: Pattern Selector UI
- presets.cpp
- res_group.c
- _simlink_web.py
- _simlink_proc.py
- WLAN
- NoCaseDict
- SimRing
- dependencies
- examples/blink.py
- README.md
## God Nodes (most connected - your core abstractions)
1. `store_coll()` - 69 edges
2. `api_error()` - 51 edges
3. `api_json()` - 47 edges
4. `unique()` - 43 edges
5. `ab()` - 42 edges
6. `api_set()` - 41 edges
7. `new_id()` - 41 edges
8. `get_colours()` - 39 edges
9. `store_save()` - 39 edges
10. `esp_timer_get_time()` - 36 edges
## Surprising Connections (you probably didn't know these)
- `Preset editor modal` --semantically_similar_to--> `Preset fields (pattern, colors, delay, brightness, auto, n1-n6)` [INFERRED] [semantically similar]
web/templates/index.html → led-driver/docs/API.md
- `led-driver-style pattern engine (Preset object)` --semantically_similar_to--> `led-driver MicroPython firmware (submodule)` [INFERRED] [semantically similar]
dmx-driver/README.md → README.md
- `espnow-sender Microdot WebSocket receiver` --semantically_similar_to--> `WebSocket /ws driver message relay` [INFERRED] [semantically similar]
espnow-sender/README.md → docs/API.md
- `Art-Net output (UDP 6454)` --semantically_similar_to--> `Outputs (DDP, Art-Net, sACN, DMX serial pixel fixtures)` [INFERRED] [semantically similar]
dmx-driver/README.md → docs/API.md
- `POST /patterns/upload (led-driver parity)` --semantically_similar_to--> `Patterns resource /patterns` [INFERRED] [semantically similar]
dmx-driver/README.md → docs/API.md
## Import Cycles
- None detected.
## Hyperedges (group relationships)
- **Audio page live endpoints** — web_audio_status, web_audio_beats, web_audio_audio_wav, web_audio_time, web_audio_tap_ep [EXTRACTED 1.00]
- **Beat latency measurement methods** — docs_api_bench_endpoints, docs_bench_test_usb_latency, docs_bench_test_logic_analyzer, docs_bench_test_beat_lead [EXTRACTED 1.00]
- **Combined brightness factors** — docs_api_combined_brightness, docs_api_settings, docs_api_groups, docs_api_devices, docs_api_zones [EXTRACTED 1.00]
- **Color picker feature set** — docs_mockups_images_color_picker_demo_hsb_color_model, docs_mockups_images_color_picker_demo_hex_rgb_input, docs_mockups_images_color_picker_demo_keyboard_accessibility, docs_mockups_images_color_picker_demo_cross_platform_consistency [EXTRACTED 1.00]
- **Edit-mode-only management features** — docs_help_edit_mode, docs_help_zones_modal, docs_help_send_presets, docs_help_patterns_dialog, docs_help_colour_palette, docs_help_presets_list [EXTRACTED 1.00]
- **Preset editor actions (Try, Default, Save & Send, Remove from zone)** — docs_help_try_action, docs_help_default_preset, docs_help_save_and_send, docs_help_remove_from_zone [EXTRACTED 1.00]
- **Header actions aggregated in mobile Menu** — docs_images_help_mobile_menu_run_mode, docs_images_help_mobile_menu_profiles, docs_images_help_mobile_menu_tabs, docs_images_help_mobile_menu_presets, docs_images_help_mobile_menu_help [EXTRACTED 1.00]
- **Device/Group Modal Flow** — docs_mockups_device_management_showadddevicemodal, docs_mockups_device_management_showaddgroupmodal, docs_mockups_device_management_closemodal, docs_mockups_device_management_savedevice [EXTRACTED 1.00]
- **LED Driver UI Mockup Set** — docs_mockups_images_index_dashboard_mockup, docs_mockups_images_index_pattern_selector_mockup, docs_mockups_images_index_device_management_mockup, docs_mockups_images_index_settings_mockup, docs_mockups_images_index_presets_mockup [EXTRACTED 1.00]
- **Selectable LED Patterns** — docs_mockups_images_pattern_selector_on, docs_mockups_images_pattern_selector_off, docs_mockups_images_pattern_selector_blink, docs_mockups_images_pattern_selector_chase, docs_mockups_images_pattern_selector_circle, docs_mockups_images_pattern_selector_pulse, docs_mockups_images_pattern_selector_rainbow, docs_mockups_images_pattern_selector_transition [EXTRACTED 1.00]
- **Preset/pattern configuration schema (pattern, colors, delay, step increment, N1-N8)** — docs_mockups_presets_led_patterns, docs_mockups_presets_delay, docs_mockups_presets_step_increment, docs_mockups_presets_n_parameters, docs_mockups_presets_step_offset [EXTRACTED 1.00]
- **Device settings sections** — docs_mockups_settings_basic_settings, docs_mockups_settings_pattern_settings, docs_mockups_settings_advanced_settings, docs_mockups_settings_network_settings [EXTRACTED 1.00]
- **LED Driver UI Mockup Suite** — docs_mockups_index, docs_mockups_dashboard, docs_mockups_pattern_selector, docs_mockups_device_management, docs_mockups_readme_settings_mockup, docs_mockups_color_picker_readme_presets_mockup [EXTRACTED 1.00]
- **Pi-to-ESP32 Command Paths** — docs_specification_serial_espnow_bridge, docs_specification_wifi_driver_tcp, docs_specification_espnow, docs_specification_pi_controller [EXTRACTED 1.00]
- **led_strip backend choice (RMT vs SPI, DMA)** — scripts_led_test_managed_components_espressif__led_strip_readme_rmt_backend, scripts_led_test_managed_components_espressif__led_strip_readme_spi_backend, scripts_led_test_managed_components_espressif__led_strip_readme_dma_support, scripts_led_test_managed_components_espressif__led_strip_readme_backend_selection_flowchart [EXTRACTED 1.00]
- **led_strip pixel write and flush flow** — scripts_led_test_managed_components_espressif__led_strip_api_led_strip_set_pixel, scripts_led_test_managed_components_espressif__led_strip_api_led_strip_set_pixel_hsv, scripts_led_test_managed_components_espressif__led_strip_api_led_strip_set_pixel_rgbw, scripts_led_test_managed_components_espressif__led_strip_api_led_strip_refresh, scripts_led_test_managed_components_espressif__led_strip_api_led_strip_clear [EXTRACTED 1.00]
- **Dynamic pattern contract** — led_driver_docs_pattern_contract_class_shape, led_driver_docs_pattern_contract_run_generator_rules, led_driver_docs_pattern_contract_drawing_brightness, led_driver_docs_pattern_contract_step_semantics, led_driver_docs_pattern_contract_error_handling [EXTRACTED 1.00]
- **Pi Animation Engine Output Pipeline** — docs_specification_pixel_generator, docs_specification_output_drivers, docs_specification_output_record, docs_specification_zone_playback, docs_specification_sequencer [EXTRACTED 1.00]
- **Beat-Driven Scene Activation** — docs_specification_beat_detection_device, docs_specification_bpm_sync, docs_specification_beat_counter_phases, docs_specification_scene_queue [INFERRED 0.85]
- **Fields defining an LED preset (name, pattern, colours, parameters)** — docs_images_help_preset_editor_preset_name_field, docs_images_help_preset_editor_pattern_selector, docs_images_help_preset_editor_palette_linked_colour, docs_images_help_preset_editor_preset_parameters [INFERRED 0.85]
- **Pattern settings composed and applied to devices** — docs_mockups_images_dashboard_pattern_selection, docs_mockups_images_dashboard_brightness_speed, docs_mockups_images_dashboard_colors, docs_mockups_images_dashboard_apply_settings [INFERRED 0.85]
- **Preset lifecycle actions (create, apply, sync)** — docs_mockups_images_presets_create_preset, docs_mockups_images_presets_apply_preset, docs_mockups_images_presets_sync_presets_to_all_devices [INFERRED 0.85]
- **ESP-NOW driver delivery layers** — docs_api_binary_envelope, docs_api_delivery_digest, docs_bench_test_reliable_link, docs_bench_test_beat_double_send [INFERRED 0.85]
- **v1 message handling on driver** — led_driver_docs_api_v1_message, led_driver_docs_patterns_process_data_flow, led_driver_docs_patterns_pattern_registry, led_driver_docs_patterns_preset_short_keys, led_driver_docs_api_select_message [INFERRED 0.85]
## Communities (184 total, 59 thin omitted)
### Community 0 - "IdfDevice"
Cohesion: 0.10
Nodes (7): _idf_post(), _idf_show(), print_settings(), run_idf(), IdfDevice, IdfError, probe()
### Community 1 - "htmx Library"
Cohesion: 0.08
Nodes (101): a(), Ae(), an(), at(), B(), be(), bn(), bt() (+93 more)
### Community 3 - "Browser Tests & Mockup Images"
Cohesion: 0.06
Nodes (17): generate_image(), generate_with_html2image(), generate_with_playwright(), generate_with_selenium(), main(), browser(), _browser_sleep(), BrowserTest (+9 more)
### Community 4 - "Audio UI (JS)"
Cohesion: 0.11
Nodes (58): applyAudioStatus(), applyServerAudioUiFields(), audioRunPreferredDeviceId(), beatSyncButtonTitle(), bind(), clampLiveBpm(), clampSimulatedBpm(), clearBeatPhaseTimers() (+50 more)
### Community 5 - "ESP-NOW TX & DMX Pulse"
Cohesion: 0.09
Nodes (16): bench_on_echo(), bridge_active(), bridge_send(), bridge_start(), ap_event(), bulk_task(), espnow_tx_drop(), espnow_tx_init() (+8 more)
### Community 6 - "audio.c"
Cohesion: 0.08
Nodes (17): Pulse, audio_get_handler(), audio_register(), audio_stream_task(), beats_get_handler(), send_all(), tap_post_handler(), time_get_handler() (+9 more)
### Community 7 - "led-tool Device CLI"
Cohesion: 0.08
Nodes (12): download_presets(), download_settings(), _get_ordered_actions(), main(), resolve_flash_binary(), upload_presets(), upload_settings(), copy_file() (+4 more)
### Community 8 - "ab"
Cohesion: 0.12
Nodes (84): chase_draw(), ease_t(), first_call(), fx_aurora(), fx_bar_graph(), fx_blink(), fx_blizzard(), fx_candle_glow() (+76 more)
### Community 9 - "Compiler"
Cohesion: 0.07
Nodes (5): Template, Loader, Loader, Compiler, Loader
### Community 10 - "Spec: Pi Animation Engine"
Cohesion: 0.07
Nodes (46): Pi Animation Engine (src/engine), docs/API.md, Beat Counter and Phases, Beat Detection Device, Binary Message Protocol, BPM Sync, Dashboard UI (dashboard.html), usqlite Database Schema (presets, profiles, scenes, scene_groups) (+38 more)
### Community 11 - "led-driver/main/ota.c"
Cohesion: 0.20
Nodes (10): fail(), ota_get_handler(), ota_post_handler(), ota_preflight_handler(), ota_register(), reboot_post_handler(), add_uri(), open_nodelay() (+2 more)
### Community 12 - "Presets UI (JS)"
Cohesion: 0.09
Nodes (42): arrayToGrid(), coerceManualBeatN(), coercePresetAuto(), coercePresetBackground(), coercePresetInt(), createPresetButton(), deviceNamesForPresetOnCurrentZone(), editPresetFromTab() (+34 more)
### Community 13 - "Zones UI (JS)"
Cohesion: 0.10
Nodes (42): applyBrightnessSliders(), applyZoneContentKindEditModal(), clamp255(), computeZoneNamesTargets(), computeZonePresetUnionTargets(), computeZoneTargets(), createZone(), effectiveGroupIdsForZonePreset() (+34 more)
### Community 14 - "patterns.c"
Cohesion: 0.12
Nodes (31): fn, add_name(), all_patterns(), base_name(), builtin(), create_pattern(), exists(), file_names() (+23 more)
### Community 15 - "new_id"
Cohesion: 0.08
Nodes (13): new_id(), test_preset_round_trip(), test_profile_round_trip(), test_sequence_round_trip(), test_play_needs_steps(), test_play_needs_zone(), test_scoped_to_profile(), test_clone() (+5 more)
### Community 16 - "Sequences UI (JS)"
Cohesion: 0.08
Nodes (55): addSeqTarget(), addSequenceToTab(), addTargetsPerDriver(), appendZoneSequenceTiles(), applySequenceEditorMode(), applySequenceKindUi(), applySequenceSwitchWaitFromServer(), buildLaneGroupIdsForEditor() (+47 more)
### Community 17 - "server.py"
Cohesion: 0.14
Nodes (12): normalise_layout(), _reversed_for_column(), rig_placements(), side_name(), strip_count(), strip_places(), StripPlace, lan_ip() (+4 more)
### Community 19 - "led_strip Component Docs"
Cohesion: 0.10
Nodes (36): led_test ESP-IDF project, led_test main component (main.c), led_strip API Reference, led_model_t (WS2812/SK6812), led_pixel_format_t (GRB/GRBW), led_strip_clear(), led_strip_config_t, led_strip_del() (+28 more)
### Community 20 - "Art-Net Output"
Cohesion: 0.10
Nodes (10): ArtNet, as_channels(), build_artdmx(), _ip_bytes(), _pad(), port_lo(), sleep_ms(), ticks_diff() (+2 more)
### Community 21 - "main/main.c"
Cohesion: 0.10
Nodes (15): app_main(), dhcp_settled(), eth_event_handler(), gateway_answers(), got_ip_event_handler(), have_static_ips(), link_up_task(), parse_static() (+7 more)
### Community 22 - "esp_log"
Cohesion: 0.12
Nodes (20): app_main(), app_main(), configure_led(), app_main(), configure_led(), led_strip_rmt_config_t, led_strip_spi_config_t, led_model_t (+12 more)
### Community 23 - "engine.c"
Cohesion: 0.15
Nodes (39): build_groups(), compact(), compact_preset(), device_name_for(), driver_in_zone(), emit_c(), emit_json(), emit_zone() (+31 more)
### Community 24 - "ws.c"
Cohesion: 0.44
Nodes (5): forward(), on_open(), send_text(), ws_handler(), ws_register()
### Community 26 - "led_strip_rmt_dev.c"
Cohesion: 0.16
Nodes (10): led_strip_rmt_clear(), led_strip_rmt_del(), led_strip_rmt_refresh(), led_strip_rmt_set_pixel(), led_strip_rmt_set_pixel_rgbw(), led_strip_encoder_config_t, rmt_del_led_strip_encoder(), rmt_encode_led_strip() (+2 more)
### Community 27 - "seqplay.c"
Cohesion: 0.12
Nodes (50): engine_zone_current(), add_id(), advance_time(), anchor_bar(), audio_drives(), beat_task(), bit(), chase_mask() (+42 more)
### Community 28 - "Devices UI (JS)"
Cohesion: 0.10
Nodes (32): applyEspnowPingAggregateToDots(), applyEspnowPingToDeviceRows(), applyTcpSnapshot(), applyTransportVisibility(), collectDeviceEditPayload(), createDeviceFromModal(), createDeviceIdentifyButton(), DEVICE_DOT_CLASSES (+24 more)
### Community 29 - "binary_envelope.py"
Cohesion: 0.15
Nodes (18): brightness_0_255_from_wire(), brightness_wire_from_0_255(), _clamp_i16(), _colors_to_rgb_list(), _decode_default_blob(), _decode_preset_record(), _decode_presets_blob(), _decode_select_blob() (+10 more)
### Community 30 - "Colour Picker Mockups"
Cohesion: 0.11
Nodes (25): Chromium-style Color Picker Demo, ColorPickerChromium Component, updateColors() (Chromium demo), Custom Color Picker Demo, updateColors() (standard demo), Custom Colour Picker README, POST /api/colors (example), ColorPicker Component (+17 more)
### Community 32 - "beat.c"
Cohesion: 0.07
Nodes (23): beats_stream_task(), beat_reset(), beat_set_callback(), beat_start(), beat_subscribe(), beat_unsubscribe(), beat_dsp_bpm(), dsp_event() (+15 more)
### Community 33 - "web.cpp"
Cohesion: 0.11
Nodes (53): api_call_work(), api_fn_t, api_http_entry(), api_req_t, api_route_t, app_js_get(), brightness_post(), ddp_get() (+45 more)
### Community 34 - "test_sequences.py"
Cohesion: 0.19
Nodes (19): clock(), make(), presets(), test_animation_over_sequence_keeps_time(), test_animation_plays_once_alone(), test_animation_step_fires_overlay(), test_beat_and_time_lanes_together(), test_chase_moves_and_bounces() (+11 more)
### Community 35 - "microdot.py"
Cohesion: 0.10
Nodes (5): HTTPException, iscoroutine(), Response, aclose(), __anext__()
### Community 36 - "API Docs: Outputs & Audio"
Cohesion: 0.14
Nodes (23): Art-Net output (UDP 6454), Audio API /api/audio and /audio page routes, Profile/preset/sequence JSON bundles (import/export), Combined brightness (global x groups x device x zone), /db collection export and replace, Devices resource /devices, Driver group membership lists (group ids, z<zone id>), Device groups resource /groups (+15 more)
### Community 37 - "led_strip_spi_dev.c"
Cohesion: 0.14
Nodes (13): led_strip_t, led_strip_rmt_clear(), led_strip_rmt_del(), led_strip_rmt_refresh(), led_strip_rmt_set_pixel(), ws2812_rmt_adapter(), led_strip_new_spi_device(), __led_strip_spi_bit() (+5 more)
### Community 38 - "store_save"
Cohesion: 0.23
Nodes (12): api_register(), api_settings_defaults(), db_root(), index_of(), load_file(), mount(), store_init(), store_known() (+4 more)
### Community 39 - "Beat Detection DSP (C)"
Cohesion: 0.27
Nodes (16): beat_feed(), analyse_beat(), bar_cue(), bar_decide(), beat_dsp_feed(), beat_dsp_init(), beat_dsp_tap(), best_phase() (+8 more)
### Community 40 - "audio_api.c"
Cohesion: 0.23
Nodes (14): audio_api_register(), audio_handler(), audio_run(), events(), events_task(), ok_with_status(), send_all(), send_event() (+6 more)
### Community 41 - "sim_stubs.c"
Cohesion: 0.11
Nodes (11): espnow_tx_set_bridge(), app_main(), settings_str(), start_webserver(), esp_vfs_littlefs_register(), mic_get_level(), mic_start(), mic_stream_open() (+3 more)
### Community 42 - "run_all"
Cohesion: 0.10
Nodes (19): dim(), expected(), frame(), frame_sum(), get(), local_prefix(), main(), mismatch_detail() (+11 more)
### Community 43 - "ws_client.cpp"
Cohesion: 0.22
Nodes (6): read_handshake(), read_n(), ws_client_close(), ws_client_connect(), ws_client_recv_text(), ws_client_send_text()
### Community 44 - "time"
Cohesion: 0.17
Nodes (9): Blink, sleep(), sleep_ms(), sleep_us(), ticks_diff(), ticks_ms(), ticks_us(), time() (+1 more)
### Community 45 - "test_presets.py"
Cohesion: 0.13
Nodes (4): preset(), test_create_belongs_to_current_profile(), test_create_fills_defaults(), test_presets_scoped_to_profile()
### Community 46 - "BridgeSim"
Cohesion: 0.14
Nodes (4): BridgeSim, mac_str(), _read_json(), Strip
### Community 47 - "USB Latency Tools"
Cohesion: 0.16
Nodes (10): analyze(), edges(), main(), pct(), read(), fit_clock(), main(), pct() (+2 more)
### Community 50 - "WS2812"
Cohesion: 0.08
Nodes (13): new_ws2812_encoder(), rmt_del_ws2812_encoder(), rmt_encode_ws2812(), rmt_ws2812_encoder_reset(), rmt_ws2812_encoder_t, WS2812, channel_, encoder_ (+5 more)
### Community 52 - "Transport"
Cohesion: 0.23
Nodes (3): _convert_filesystem_error(), stdout_write_bytes(), Transport
### Community 53 - "mpremote Transport"
Cohesion: 0.12
Nodes (20): Presets Mockup Page, addColorPicker() / initializeColorPickers(), ColorPicker component (color-picker.js / color-picker.css), Preset Delay (animation speed, 10-1000 ms), ESPNow preset distribution, filterPresets() / sortPresets() search, filter and sort, LED Patterns (on, off, blink, chase, circle, pulse, rainbow, transition), Pattern Parameters N1-N8 (+12 more)
### Community 54 - "Outputs Config (C)"
Cohesion: 0.20
Nodes (17): defaults(), fail(), fill(), int_field(), num(), one_of(), put16(), resolve() (+9 more)
### Community 55 - "patterns.cpp"
Cohesion: 0.11
Nodes (28): clamp_leds(), ddp_show(), frame_alloc(), fx_fn, now_ms(), output(), pattern_def_t, name (+20 more)
### Community 59 - "microdot.py"
Cohesion: 0.14
Nodes (4): invoke_handler(), mro(), urldecode_bytes(), urldecode_str()
### Community 60 - "mpremote Serial Transport"
Cohesion: 0.13
Nodes (3): SerialIntercept, SerialTransport, TransportError
### Community 61 - "API Test Fixtures & Audio"
Cohesion: 0.16
Nodes (5): base_url(), c(), Client, profile(), restore_db()
### Community 63 - "Help: Zones & Palette"
Cohesion: 0.13
Nodes (18): Colour Palette (per profile), Zone default preset (default hint), DJ zone starter option, From Palette linked colours, LED driver JSON (presets, select, save, default, manifest), Patterns dialog, POST /presets/send, Preset editor (Try, Save, Send, Manual) (+10 more)
### Community 64 - "ddp_test.py"
Cohesion: 0.08
Nodes (24): hsv(), rig_mid(), rig_rows(), rig_xy(), set_fps(), soak_rig_bounce(), soak_rig_checker(), soak_rig_columns() (+16 more)
### Community 66 - "esp_timer_get_time"
Cohesion: 0.19
Nodes (14): espnow_tx_send(), full_mask(), handle_rx(), peer_get(), record_done(), rel_init(), rel_send(), rel_send_seq() (+6 more)
### Community 67 - "os"
Cohesion: 0.07
Nodes (7): mpremote_base(), main(), boot(), firmware_default_device_name(), TransportExecError, info(), upload()
### Community 68 - "build_app"
Cohesion: 0.24
Nodes (4): build_app(), index(), static(), web()
### Community 69 - "main/ota.c"
Cohesion: 0.12
Nodes (19): ap_switch_later(), apply_client_ip(), net_save_network(), on_ip_event(), on_wifi_event(), reconnect_cb(), ota_confirm_later(), bench_start() (+11 more)
### Community 70 - "Index Page Modals"
Cohesion: 0.11
Nodes (19): Audio Beat Detection modal, Header BPM / beat sync indicator, Colour Palette modal, Devices modal, Edit device modal, Edit Zone modal, Device groups modal, Header global brightness slider (+11 more)
### Community 74 - "store_lock"
Cohesion: 0.31
Nodes (13): engine_groups_push_all(), engine_play(), on_announce(), espnow_tx_set_mic_beats(), seqplay_init(), seqplay_overlay_stop(), seqplay_set_audio(), seqplay_stop() (+5 more)
### Community 75 - "json"
Cohesion: 0.14
Nodes (9): _default_image(), _info(), ota_update(), _default_image(), _info(), ota_update(), handle_action(), index() (+1 more)
### Community 76 - "Controller Overview & OTA Docs"
Cohesion: 0.17
Nodes (16): led_controller ESP-IDF project, POST /patterns/upload (led-driver parity), Driver app update /drivers/ota (staged files, sha, commit/abort), Firmware OTA /ota (idle slot, rollback), Patterns resource /patterns, Driver app update over ESP-NOW test (tools/driver_ota.py), led-simulator, led-tool / led-cli serial device CLI (+8 more)
### Community 77 - "usb_cfg.cpp"
Cohesion: 0.29
Nodes (5): handle_api(), handle_line(), log_vprintf(), usb_cfg_task(), write_line()
### Community 79 - "Audio Monitor Page"
Cohesion: 0.16
Nodes (16): /audio.wav live PCM stream, bar() bar-position renderer, /beats SSE event stream, draw() timeline canvas, Listen button (WAV stream playback via AudioContext), median(), Audio and beats page (/audio), stats() tap vs computer agreement (+8 more)
### Community 80 - "Art-Net DMX Tests"
Cohesion: 0.26
Nodes (9): parse(), _assert_eq(), main(), test_artnet_send_loopback(), test_build_artdmx(), test_fixture_patch(), test_pattern_blink_and_select(), test_pattern_upload() (+1 more)
### Community 82 - "bridge_sim.py"
Cohesion: 0.14
Nodes (7): driver_mac(), lan_ip(), load_config(), _merge(), sync_patterns(), _hex(), main()
### Community 84 - "unique"
Cohesion: 0.06
Nodes (15): find_id_by_field(), missing(), unique(), test_scenes(), device(), group(), test_crud(), test_group_identify_needs_devices() (+7 more)
### Community 85 - "ESP-NOW Sender Bridge"
Cohesion: 0.20
Nodes (10): ap(), _broadcast_ws(), _espnow_receive_loop(), _init_espnow(), main(), _send_espnow(), _validate_envelope(), ws() (+2 more)
### Community 86 - "net.cpp"
Cohesion: 0.08
Nodes (23): ddp_start(), app_main(), ap_timer_cb(), apply_ap(), apply_sta_config(), net_ap_on(), net_ap_ssid(), net_scan() (+15 more)
### Community 89 - "Rig"
Cohesion: 0.15
Nodes (4): bridge_downlink(), driver_mac(), mac_str(), Rig
### Community 90 - "packet"
Cohesion: 0.14
Nodes (3): packet(), send_frame(), send_sync()
### Community 92 - "Bench Test Plan"
Cohesion: 0.23
Nodes (9): Bench endpoints /test/loss and /test/beats, 30 ms beat lead (CONFIG_BEAT_LEAD_MS), Bench test: S3 controller and one LED driver, ESP32-C3 vs S3 driver comparison, Logic analyzer latency (marker GPIO, tools/analyze_edges.py), Lossy-link test (simulated loss, retries, resync), Reliable link (rel: acked unicast, retransmits, ack timeouts), Bench troubleshooting (serial ports, channel mismatch, blank UI) (+1 more)
### Community 93 - "envelope.c"
Cohesion: 0.33
Nodes (12): clamp(), color_rgb(), env_add_preset(), env_add_select(), get2(), num_or(), put(), put_le16() (+4 more)
### Community 94 - "api_call_t"
Cohesion: 0.33
Nodes (5): api_call_t, cap, done, msg, out
### Community 95 - "Microdot Auth (dmx)"
Cohesion: 0.21
Nodes (6): wraps(), print_exception(), websocket_upgrade(), websocket_wrapper(), wrapper(), with_websocket()
### Community 97 - "DMX Pattern Player"
Cohesion: 0.15
Nodes (3): main(), output_tick(), PatternPlayer
### Community 98 - "DMX Preset Model"
Cohesion: 0.08
Nodes (12): _expand(), _preset_from_map(), process_data(), _select_entries(), _targets_for_key(), create_app(), play(), serial_ports() (+4 more)
### Community 99 - "status_get_handler"
Cohesion: 0.16
Nodes (9): beat_get_info(), bridge_addr(), espnow_tx_ap_clients(), espnow_tx_stats(), reset_reason(), status_get_handler(), rel_stats(), rel_ver() (+1 more)
### Community 100 - "ddp.cpp"
Cohesion: 0.15
Nodes (5): be16(), be32(), ddp_set_enabled(), ddp_sync_task(), ddp_task()
### Community 101 - "Groups UI (JS)"
Cohesion: 0.29
Nodes (9): fetchDevicesMapForGroups(), fetchGroupsMap(), identifyGroupById(), loadGroupsModal(), loadWifiFieldsFromGroup(), openEditGroupModal(), renderGroupDevicesEditor(), renderGroupsList() (+1 more)
### Community 102 - "rig_seed.py"
Cohesion: 0.29
Nodes (6): controller_url(), _get(), _post(), seed(), seed_soon(), api_seed_layout()
### Community 103 - "Help: Mobile Menu Image"
Cohesion: 0.24
Nodes (10): Mobile Menu Help Illustration (narrow screen), Content Area (preset buttons), Menu Dropdown (Run mode, Profiles, Tabs, Presets, Help), Header Tab Buttons, Help, Menu Button (header dropdown trigger), Presets, Profiles (+2 more)
### Community 104 - "Pattern Selector Mockup Image"
Cohesion: 0.20
Nodes (11): Pattern Selector Mockup (Select LED Pattern), Apply Pattern / Cancel Actions, Blink Pattern, Chase Pattern, Circle Pattern, Off Pattern, On Pattern (solid color), Pattern Card Grid Layout (+3 more)
### Community 105 - "Driver Pattern Docs"
Cohesion: 0.24
Nodes (11): Message processing order (version, presets upsert, colour, selection), Auto vs manual (a) and manual chase flush, Built-in off / on patterns, Patterns and presets on the LED driver, MAX_PRESETS = 32, Pattern OTA via manifest / POST /patterns/upload, Pattern registry (Presets.reload_patterns), Preset short keys (p, c, d, b, a, bg, n1-n6) (+3 more)
### Community 108 - "esp_timer_get_time"
Cohesion: 0.24
Nodes (9): bench_running(), skip_unresponsive(), espnow_tx_beat(), on_beat(), send_beat_copy(), rel_peer_status(), on_ping_rsp(), esp_timer_get_time() (+1 more)
### Community 109 - "Driver Message API Docs"
Cohesion: 0.38
Nodes (10): Auto vs manual mode, Beat (re-select same preset restarts generator), Hex colour conversion and colour-order reordering, LED Driver API (message format), Pattern-specific parameters (rainbow, pulse, transition, chase, circle), Preset fields (pattern, colors, delay, brightness, auto, n1-n6), Select message (device -> [preset, step]), Step synchronization (+2 more)
### Community 110 - "engine_init"
Cohesion: 0.40
Nodes (3): engine_init(), rel_set_announce_cb(), rel_set_resync_cb()
### Community 111 - "led_strip Manifest"
Cohesion: 0.20
Nodes (9): dependencies, idf, description, repository, repository_info, commit_sha, path, url (+1 more)
### Community 112 - "ws_slot_t"
Cohesion: 0.67
Nodes (3): ws_slot_t, fd, host
### Community 113 - "Outputs UI (JS)"
Cohesion: 0.33
Nodes (8): fetchOutputs(), loadOutputsModal(), openOutputEditor(), OUTPUT_PROTOCOL_LABELS, outputSummary(), renderOutputsList(), setOutputField(), syncOutputProtocolFields()
### Community 114 - "DMX Driver Docs"
Cohesion: 0.25
Nodes (9): Controller WebSocket /ws (v1 presets/select), DMX Driver Art-Net and serial gateway, DMX fixture (output, start channel, role map; parcan/mover profiles), led-driver-style pattern engine (Preset object), Serial DMX512 output (250000 8N2), Binary envelope (main/envelope.c, test/binary_envelope.py), v1 driver messages (long/short keys), WebSocket /ws driver message relay (+1 more)
### Community 115 - "Help PDF: Overview"
Cohesion: 0.25
Nodes (9): API.md, LED controller user guide, Main web UI (Raspberry Pi app), Pattern OTA install over HTTP (/patterns/ota, upload, driver, send), Pattern parameters n1-n8, README, Serial to ESP-NOW bridge transport, WebSocket /ws (+1 more)
### Community 116 - "Mockups Index Image"
Cohesion: 0.31
Nodes (9): LED Driver UI Mockups Index (screenshot), Dashboard Mockup, Device Groups, Device Management Mockup, LED Patterns (On, Off, Blink, Chase, Circle, Pulse, Rainbow, Transition), N1-N8 Pattern Parameters, Pattern Selector Mockup, Presets Mockup (+1 more)
### Community 118 - "Help: Header Toolbar Image"
Cohesion: 0.29
Nodes (8): Header Toolbar Help Image, Edit Mode Action Bar, Run/Edit Mode Toggle Button, Patterns Action, Presets Action, Profiles Action, Header Tab Buttons, Tabs Action
### Community 119 - "Help: Preset Editor Image"
Cohesion: 0.29
Nodes (5): Default Action, Preset Pattern Selector, Preset Editor Modal (help illustration), Preset Name Field, Brightness, Delay and n1-n8 Parameters (0-255)
### Community 120 - "Dashboard Mockup Image"
Cohesion: 0.32
Nodes (8): LED Driver Control Panel Dashboard Mockup, Apply Settings Action, Brightness & Speed Card (Brightness % and Delay ms sliders), Colors Card (color swatches palette, Add Color), Connected Devices Card (devices with group and online status), Device Groups, Pattern Selection Card (On, Off, Blink, Chase, Circle, Pulse, Rainbow, Transition), Save to Device Action
### Community 121 - "Device Management Mockup Image"
Cohesion: 0.32
Nodes (8): + Add Device Button, Connected Devices List, Device Group, Device & Group Management Screen (mockup), Device Row Actions (edit, settings, stop), Online/Offline Status Badge, Devices / Groups Tab Switcher, LED Device (MAC, group, pattern)
### Community 122 - "Presets Mockup Image"
Cohesion: 0.32
Nodes (8): Preset Management UI Mockup, Apply Preset Action, Create Preset Action, LED Pattern Types (Rainbow, Pulse, Chase, Circle, Blink, Transition), Preset Card (name, pattern badge, color swatches, delay, n1, apply/edit/delete), Preset Search/Filter/Sort Toolbar (pattern filter, sort by name, grid/list toggle), Preset Parameters (colors, delay ms, n1), Sync Presets to All Devices
### Community 123 - "Pattern Contract"
Cohesion: 0.29
Nodes (6): Pattern Contract, Drawing via driver.n and apply_brightness, Pattern error handling (Presets.tick catches), Presets._load_dynamic_patterns(), Shared driver.step semantics, Global vs per-preset brightness
### Community 129 - "Colour Picker Demo Image"
Cohesion: 0.33
Nodes (6): Custom Color Picker Demo (screenshot), Hex and RGB input support, HSB (Hue, Saturation, Brightness) color model, Keyboard accessible, customizable styling, Multiple Color Pickers for LED Patterns, Single Color Picker
### Community 130 - "Settings Mockup Image"
Cohesion: 0.33
Nodes (7): Advanced Settings (Step Counter, Step Increment, Device ID, Debug Mode), Basic Settings (Device Name, LED Pin, Number of LEDs), Color Order Selector (RGB/RBG/GRB/GBR/BRG/BGR), Device Settings Page Mockup, Network Settings (Access Point Name, Password, Enable AP), Pattern Parameters N1-N6, Pattern Settings (Pattern, Brightness, Delay)
### Community 131 - "sim_demo.py"
Cohesion: 0.26
Nodes (7): Api, main(), group(), preset(), sequence(), new_id(), rig_bars()
### Community 135 - "store_coll"
Cohesion: 0.21
Nodes (30): engine_groups_changed(), api_migrate_zones(), api_preset_defaults(), api_seed_defaults(), clone_profile(), clone_zone(), content_fragment(), create_profile() (+22 more)
### Community 138 - "Help: Colour Palette Image"
Cohesion: 0.40
Nodes (6): Colour Palette modal mockup (help image), Add Swatch (+) Button, Colour Palette Modal, Palette Colour Swatches, Preset Editor 'From Palette', Profile (palette owner)
### Community 140 - "LED Driver README"
Cohesion: 0.47
Nodes (6): dev.py deploy/sync script, LED Driver README (MicroPython ESP32), Optional HTTP polling (http_poll.py), Wi-Fi TCP transport to Pi (port 8765), transport_type setting (wifi / espnow), UDP discovery (port 8766)
### Community 142 - "SPI Example Manifest"
Cohesion: 0.33
Nodes (5): dependencies, espressif/led_strip, idf, override_path, version
### Community 143 - "test_rig_sim.py"
Cohesion: 0.10
Nodes (28): all_dark(), col_of(), frames(), led_x(), lit(), mac(), make_preset(), need_sim() (+20 more)
### Community 145 - "Help PDF: Modes"
Cohesion: 0.40
Nodes (4): Edit mode, Mobile layout Menu, Run mode, Zones modal
### Community 146 - "Help: Tab Preset Strip Image"
Cohesion: 0.60
Nodes (5): Help image: Main area brightness and preset tiles, Edit Mode: drag tiles to reorder, Global Brightness Slider, Preset Tile (gradient swatch, click to select on tab devices), Tab (e.g. lounge)
### Community 149 - "res_device.c"
Cohesion: 0.18
Nodes (30): api_apply_driver_cfg(), api_effective_brightness(), api_identify_group(), clamp255(), create_device(), device_brightness(), device_config_from(), device_driver_config() (+22 more)
### Community 150 - "api_error"
Cohesion: 0.23
Nodes (21): api_body(), api_error(), api_json(), api_merge(), api_message(), api_preset_in_profile(), api_result(), api_split() (+13 more)
### Community 155 - "app.js"
Cohesion: 0.16
Nodes (35): addLog(), banner(), colourAt(), connectBridge(), deliver(), drawLabel(), drawPlaced(), drawStrip() (+27 more)
### Community 156 - "RMT Example Manifest"
Cohesion: 0.40
Nodes (4): dependencies, espressif/led_strip, override_path, version
### Community 157 - "Help Tab JS"
Cohesion: 0.36
Nodes (5): addStaticIpRow(), loadDeviceSettings(), loadNetworkStatus(), setApToggle(), switchSettingsTab()
### Community 158 - "Settings Page Template"
Cohesion: 0.50
Nodes (4): Settings modal (device, network), loadEspnowChannel(), Device Settings page (ESP-NOW channel), wifi_channel setting (1-11)
### Community 159 - "led-driver/web/app.js"
Cohesion: 0.10
Nodes (49): api(), applyMode(), attachDrag(), closeEditor(), closeSock(), deviceChoices(), direct(), discoverDevices() (+41 more)
### Community 166 - "sequences_route"
Cohesion: 0.24
Nodes (15): api_body_opt(), api_current_profile(), api_migrate_sequences(), api_sequence_defaults(), apply_update(), colors_from(), fire_sequence(), has_steps() (+7 more)
### Community 167 - "api_id"
Cohesion: 0.24
Nodes (25): api_add(), api_id(), api_set(), add_ref(), bundle(), bundle_of(), bundles_route(), export_profile() (+17 more)
### Community 170 - "dependencies"
Cohesion: 0.25
Nodes (8): dependencies, espressif/mdns, joltwallet/littlefs, rules, version, rules, version, if
### Community 171 - "List Search (JS)"
Cohesion: 0.83
Nodes (3): applyListSearch(), initListSearch(), rowSearchText()
### Community 197 - "presets.cpp"
Cohesion: 0.20
Nodes (21): patterns_index(), build_defaults(), find(), preset_from_json(), preset_to_json(), presets_add_defaults(), presets_apply_startup(), presets_at() (+13 more)
### Community 199 - "res_group.c"
Cohesion: 0.31
Nodes (15): add_error(), api_driver_config(), api_mac(), api_migrate_groups(), brightness(), driver_config(), find(), groups_route() (+7 more)
### Community 201 - "_simlink_web.py"
Cohesion: 0.16
Nodes (11): _check_flash(), on_feed(), push_pixels(), real_sleep(), recv(), recv_nowait(), _run_jobs(), _send_pixels() (+3 more)
### Community 204 - "_simlink_proc.py"
Cohesion: 0.16
Nodes (5): connect(), on_feed(), push_pixels(), _reader(), _send_pixels()
### Community 227 - "dependencies"
Cohesion: 0.33
Nodes (5): dependencies, espressif/cjson, espressif/mdns, version, version
## Knowledge Gaps
- **113 isolated node(s):** `name`, `host`, `cl`, `host`, `fd` (+108 more)
These have ≤1 connection - possible missing edges or undocumented components. (Counts symbols only; 922 node(s) total have ≤1 connection when file, concept and rationale nodes are included.)
- **59 thin communities (<3 nodes) omitted from report** — run `graphify query` to explore isolated nodes.
## Suggested Questions
_Questions this graph is uniquely positioned to answer:_
- **Why does `new_id()` connect `new_id` to `test_sequences.py`, `test_presets.py`, `test_rig_sim.py`, `unique`, `API Test Fixtures & Audio`?**
_High betweenness centrality (0.022) - this node is a cross-community bridge._
- **Are the 64 inferred relationships involving `store_coll()` (e.g. with `api_add()` and `api_current_profile()`) actually correct?**
_`store_coll()` has 64 INFERRED edges - model-reasoned connections that need verification._
- **What connects `name`, `host`, `cl` to the rest of the system?**
_113 weakly-connected nodes found - possible documentation gaps or missing edges._
- **Should `IdfDevice` be split into smaller, more focused modules?**
_Cohesion score 0.09915966386554621 - nodes in this community are weakly interconnected._
- **Why does `PyboardCommand` connect `PyboardCommand` to `os`, `mpremote Serial Transport`?**
_High betweenness centrality (0.019) - this node is a cross-community bridge._
- **Are the 40 inferred relationships involving `api_error()` (e.g. with `outputs_route()` and `test_output()`) actually correct?**
_`api_error()` has 40 INFERRED edges - model-reasoned connections that need verification._
- **Should `htmx Library` be split into smaller, more focused modules?**
_Cohesion score 0.07897684839432412 - nodes in this community are weakly interconnected._
+12
View File
@@ -0,0 +1,12 @@
{
"runs": [
{
"date": "2026-11-03T12:13:15.159050+00:00",
"input_tokens": 1267015,
"output_tokens": 0,
"files": 332
}
],
"total_input_tokens": 1267015,
"total_output_tokens": 0
}
+1
View File
@@ -0,0 +1 @@
{"directed":false,"multigraph":false,"graph":{"hyperedges":[{"id":"audio_page_endpoints","label":"Audio page live endpoints","nodes":["web_audio_status","web_audio_beats","web_audio_audio_wav","web_audio_time","web_audio_tap_ep"],"relation":"participate_in","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"web/audio.html"},{"id":"beat_latency_measurement","label":"Beat latency measurement methods","nodes":["docs_api_bench_endpoints","docs_bench_test_usb_latency","docs_bench_test_logic_analyzer","docs_bench_test_beat_lead"],"relation":"participate_in","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/BENCH_TEST.md"},{"id":"brightness_combination","label":"Combined brightness factors","nodes":["docs_api_combined_brightness","docs_api_settings","docs_api_groups","docs_api_devices","docs_api_zones"],"relation":"participate_in","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/API.md"},{"id":"color_picker_feature_set","label":"Color picker feature set","nodes":["docs_mockups_images_color_picker_demo_hsb_color_model","docs_mockups_images_color_picker_demo_hex_rgb_input","docs_mockups_images_color_picker_demo_keyboard_accessibility","docs_mockups_images_color_picker_demo_cross_platform_consistency"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/mockups/images/color-picker-demo.png"},{"id":"docs_help_edit_mode_management","label":"Edit-mode-only management features","nodes":["docs_help_edit_mode","docs_help_zones_modal","docs_help_send_presets","docs_help_patterns_dialog","docs_help_colour_palette","docs_help_presets_list"],"relation":"participate_in","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/help.pdf"},{"id":"docs_help_preset_editor_actions","label":"Preset editor actions (Try, Default, Save & Send, Remove from zone)","nodes":["docs_help_try_action","docs_help_default_preset","docs_help_save_and_send","docs_help_remove_from_zone"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/help.pdf"},{"id":"docs_images_help_mobile_menu_header_actions","label":"Header actions aggregated in mobile Menu","nodes":["docs_images_help_mobile_menu_run_mode","docs_images_help_mobile_menu_profiles","docs_images_help_mobile_menu_tabs","docs_images_help_mobile_menu_presets","docs_images_help_mobile_menu_help"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/images/help/mobile-menu.svg"},{"id":"docs_mockups_device_modal_flow","label":"Device/Group Modal Flow","nodes":["docs_mockups_device_management_showadddevicemodal","docs_mockups_device_management_showaddgroupmodal","docs_mockups_device_management_closemodal","docs_mockups_device_management_savedevice"],"relation":"participate_in","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/mockups/device-management.html"},{"id":"docs_mockups_images_index_ui_mockup_set","label":"LED Driver UI Mockup Set","nodes":["docs_mockups_images_index_dashboard_mockup","docs_mockups_images_index_pattern_selector_mockup","docs_mockups_images_index_device_management_mockup","docs_mockups_images_index_settings_mockup","docs_mockups_images_index_presets_mockup"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/mockups/images/index.png"},{"id":"docs_mockups_images_pattern_selector_led_patterns","label":"Selectable LED Patterns","nodes":["docs_mockups_images_pattern_selector_on","docs_mockups_images_pattern_selector_off","docs_mockups_images_pattern_selector_blink","docs_mockups_images_pattern_selector_chase","docs_mockups_images_pattern_selector_circle","docs_mockups_images_pattern_selector_pulse","docs_mockups_images_pattern_selector_rainbow","docs_mockups_images_pattern_selector_transition"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/mockups/images/pattern-selector.png"},{"id":"docs_mockups_preset_schema","label":"Preset/pattern configuration schema (pattern, colors, delay, step increment, N1-N8)","nodes":["docs_mockups_presets_led_patterns","docs_mockups_presets_delay","docs_mockups_presets_step_increment","docs_mockups_presets_n_parameters","docs_mockups_presets_step_offset"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/mockups/presets.html"},{"id":"docs_mockups_settings_sections","label":"Device settings sections","nodes":["docs_mockups_settings_basic_settings","docs_mockups_settings_pattern_settings","docs_mockups_settings_advanced_settings","docs_mockups_settings_network_settings"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/mockups/settings.html"},{"id":"docs_mockups_ui_mockup_suite","label":"LED Driver UI Mockup Suite","nodes":["docs_mockups_index","docs_mockups_dashboard","docs_mockups_pattern_selector","docs_mockups_device_management","docs_mockups_readme_settings_mockup","docs_mockups_color_picker_readme_presets_mockup"],"relation":"foLine truncated
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,89 @@
{
"1": "htmx Library",
"3": "Browser Tests & Mockup Images",
"4": "Audio UI (JS)",
"7": "led-tool Device CLI",
"10": "Spec: Pi Animation Engine",
"12": "Presets UI (JS)",
"13": "Zones UI (JS)",
"16": "Sequences UI (JS)",
"19": "led_strip Component Docs",
"20": "Art-Net Output",
"28": "Devices UI (JS)",
"30": "Colour Picker Mockups",
"36": "API Docs: Outputs & Audio",
"39": "Beat Detection DSP (C)",
"47": "USB Latency Tools",
"48": "Colour Picker JS",
"49": "Chromium Colour Picker JS",
"51": "API Tests: Devices",
"53": "mpremote Transport",
"60": "mpremote Serial Transport",
"61": "API Test Fixtures & Audio",
"62": "Microdot Request (dmx)",
"63": "Help: Zones & Palette",
"70": "Index Page Modals",
"73": "Microdot WebSocket (dmx)",
"76": "Controller Overview & OTA Docs",
"79": "Audio Monitor Page",
"80": "Art-Net DMX Tests",
"81": "DMX Output Manager",
"85": "ESP-NOW Sender Bridge",
"87": "Microdot Async IO (dmx)",
"88": "DMX Settings",
"91": "Microdot Routing (dmx)",
"92": "Bench Test Plan",
"95": "Microdot Auth (dmx)",
"96": "Serial DMX & WiFi",
"97": "DMX Pattern Player",
"98": "DMX Preset Model",
"101": "Groups UI (JS)",
"103": "Help: Mobile Menu Image",
"104": "Pattern Selector Mockup Image",
"105": "Driver Pattern Docs",
"109": "Driver Message API Docs",
"111": "led_strip Manifest",
"113": "Outputs UI (JS)",
"115": "Help PDF: Overview",
"116": "Mockups Index Image",
"118": "Help: Header Toolbar Image",
"119": "Help: Preset Editor Image",
"120": "Dashboard Mockup Image",
"121": "Device Management Mockup Image",
"122": "Presets Mockup Image",
"123": "Pattern Contract",
"127": "Numpad Shortcuts (JS)",
"129": "Colour Picker Demo Image",
"130": "Settings Mockup Image",
"134": "API Tests: Settings",
"138": "Help: Colour Palette Image",
"140": "LED Driver README",
"142": "SPI Example Manifest",
"145": "Help PDF: Modes",
"146": "Help: Tab Preset Strip Image",
"156": "RMT Example Manifest",
"157": "Help Tab JS",
"158": "Settings Page Template",
"171": "List Search (JS)",
"172": "DMX Solid Pattern",
"173": "led-test Manifest",
"174": "VPN Autoconnect Script",
"175": "Zone Devices Panel",
"176": "graphify Instructions",
"180": "Device Mockup Modals",
"181": "bulk.sh Script",
"182": "deploy.sh Script",
"183": "Driver install.sh",
"185": "led-tool install.sh",
"186": "Help PDF Build Script",
"187": "Web Build Script",
"188": "Patterns UI (JS)",
"189": "DMX Patterns Init",
"190": "Mockup Tab Switch",
"191": "Spec: Pattern Selector UI",
"192": "mpremote Package",
"193": "Bundle Import/Export (JS)",
"194": "Colour Palette (JS)",
"195": "Profiles UI (JS)",
"196": "Zone Palette (JS)"
}
+790
View File
@@ -0,0 +1,790 @@
# Graph Report - led-controller (2026-11-14)
## Corpus Check
- 353 files · ~637,567 words
- Verdict: corpus is large enough that graph structure adds value.
- Unclassified: 1301 file(s) not represented in the graph (top: .obj 884, .cmake 160, .a 104)
## Summary
- 4411 nodes · 12438 edges · 196 communities (131 shown, 65 thin omitted)
- Extraction: 75% EXTRACTED · 25% INFERRED · 0% AMBIGUOUS · INFERRED: 3124 edges (avg confidence: 0.85)
- Token cost: 0 input · 0 output
## Graph Freshness
- Built from commit: `cf390284`
- Run `git rev-parse HEAD` and compare to check if the graph is stale.
- Run `graphify update .` after code changes (no API cost).
## Community Hubs (Navigation)
- IdfDevice
- htmx Library
- machine.py
- Browser Tests & Mockup Images
- Audio UI (JS)
- cJSON.c
- bench.c
- led-tool Device CLI
- ab
- Compiler
- Spec: Pi Animation Engine
- espnow_link.cpp
- Presets UI (JS)
- Zones UI (JS)
- web.cpp
- new_id
- Sequences UI (JS)
- layout.py
- main/main.c
- led_strip Component Docs
- Art-Net Output
- freertos.c
- cJSON_GetObjectItem
- cJSON_IsString
- web.cpp
- Microdot
- HTTPException
- seqplay.c
- Devices UI (JS)
- binary_envelope.py
- Colour Picker Mockups
- PyboardCommand
- groups_route
- httpd_parse.c
- test_sequences.py
- microdot.py
- API Docs: Outputs & Audio
- store_init
- socket
- Beat Detection DSP (C)
- test_presets.py
- esp_http_server.h
- run_all
- outputs.c
- move_bars.py
- http_parser.h
- BridgeSim
- USB Latency Tools
- Colour Picker JS
- Chromium Colour Picker JS
- WS2812
- API Tests: Devices
- Transport
- mpremote Transport
- web.c
- test_routes.py
- httpd_config
- test_outputs.py
- mpremote Serial Transport
- API Test Fixtures & Audio
- Microdot Request (dmx)
- Help: Zones & Palette
- ddp_test.py
- test_audio.py
- esp_timer_get_time
- os
- build_app
- httpd_handle_t
- Index Page Modals
- httpd_main.c
- httpd_data
- Microdot WebSocket (dmx)
- create_app
- esp_glue.c
- Controller Overview & OTA Docs
- bridge_main.c
- HttpDevice
- Audio Monitor Page
- Art-Net DMX Tests
- DMX Output Manager
- events
- httpd_req_t
- unique
- ESP-NOW Sender Bridge
- ctrl_msg.cpp
- Microdot Async IO (dmx)
- DMX Settings
- Rig
- Sender
- Microdot Routing (dmx)
- Bench Test Plan
- events
- api_call_t
- Microdot Auth (dmx)
- Serial DMX & WiFi
- DMX Pattern Player
- DMX Preset Model
- esp_err.h
- patterns.cpp
- Groups UI (JS)
- httpd_req_aux
- Help: Mobile Menu Image
- Pattern Selector Mockup Image
- Driver Pattern Docs
- led-controller ESP32-S3 firmware
- main
- LedSimulatorApp
- Driver Message API Docs
- Missing
- led_strip Manifest
- Outputs UI (JS)
- DMX Driver Art-Net and serial gateway
- Help PDF: Overview
- Mockups Index Image
- bridge_sim.py
- Help: Header Toolbar Image
- Help: Preset Editor Image
- Dashboard Mockup Image
- Device Management Mockup Image
- Presets Mockup Image
- Pattern Contract
- httpd_ws.c
- Numpad Shortcuts (JS)
- httpd_ctrl_data
- Colour Picker Demo Image
- Settings Mockup Image
- sim_demo.py
- mac_str
- httpd_req_t
- time
- Help: Colour Palette Image
- httpd_req
- LED Driver README
- machine.py
- SPI Example Manifest
- test_rig_sim.py
- settings_editor.js
- Help PDF: Modes
- Help: Tab Preset Strip Image
- res_device.c
- vendor.sh
- app.js
- RMT Example Manifest
- Help Tab JS
- Settings Page Template
- led-driver/web/app.js
- led_strip_rmt_encoder.c
- dependencies
- List Search (JS)
- DMX Solid Pattern
- led-test Manifest
- VPN Autoconnect Script
- graphify Instructions
- usb_cfg.cpp
- LED controller web UI user guide
- bulk.sh Script
- deploy.sh Script
- Driver install.sh
- led-tool install.sh
- Help PDF Build Script
- Web Build Script
- Spec: Pattern Selector UI
- _simlink_web.py
- _simlink_proc.py
- WLAN
- NoCaseDict
- SimRing
- dependencies
- examples/blink.py
- README.md
## God Nodes (most connected - your core abstractions)
1. `cJSON` - 241 edges
2. `cJSON_GetObjectItem()` - 170 edges
3. `httpd_req_t` - 146 edges
4. `cJSON_Delete()` - 119 edges
5. `cJSON_CreateObject()` - 116 edges
6. `cJSON_IsString()` - 92 edges
7. `cJSON_AddStringToObject()` - 86 edges
8. `store_coll()` - 75 edges
9. `cJSON_AddItemToObject()` - 53 edges
10. `api_json()` - 53 edges
## Surprising Connections (you probably didn't know these)
- `Preset editor modal` --semantically_similar_to--> `Preset fields (pattern, colors, delay, brightness, auto, n1-n6)` [INFERRED] [semantically similar]
web/templates/index.html → led-driver/docs/API.md
- `Channel` --references--> `bridge_serial_set_channel()` [INFERRED]
bridge/README.md → main/bridge_serial.c
- `Build and run` --references--> `info()` [INFERRED]
desktop/README.md → tools/ota.py
- `log_task()` --calls--> `xQueueReceive()` [INFERRED]
main/bench.c → desktop/port/src/freertos.c
- `How it is built` --references--> `http_parser` [INFERRED]
desktop/README.md → desktop/third_party/http_parser/http_parser.h
## Import Cycles
- None detected.
## Hyperedges (group relationships)
- **Audio page live endpoints** — web_audio_status, web_audio_beats, web_audio_audio_wav, web_audio_time, web_audio_tap_ep [EXTRACTED 1.00]
- **Beat latency measurement methods** — docs_api_bench_endpoints, docs_bench_test_usb_latency, docs_bench_test_logic_analyzer, docs_bench_test_beat_lead [EXTRACTED 1.00]
- **Combined brightness factors** — docs_api_combined_brightness, docs_api_settings, docs_api_groups, docs_api_devices, docs_api_zones [EXTRACTED 1.00]
- **Color picker feature set** — docs_mockups_images_color_picker_demo_hsb_color_model, docs_mockups_images_color_picker_demo_hex_rgb_input, docs_mockups_images_color_picker_demo_keyboard_accessibility, docs_mockups_images_color_picker_demo_cross_platform_consistency [EXTRACTED 1.00]
- **Edit-mode-only management features** — docs_help_edit_mode, docs_help_zones_modal, docs_help_send_presets, docs_help_patterns_dialog, docs_help_colour_palette, docs_help_presets_list [EXTRACTED 1.00]
- **Preset editor actions (Try, Default, Save & Send, Remove from zone)** — docs_help_try_action, docs_help_default_preset, docs_help_save_and_send, docs_help_remove_from_zone [EXTRACTED 1.00]
- **Header actions aggregated in mobile Menu** — docs_images_help_mobile_menu_run_mode, docs_images_help_mobile_menu_profiles, docs_images_help_mobile_menu_tabs, docs_images_help_mobile_menu_presets, docs_images_help_mobile_menu_help [EXTRACTED 1.00]
- **Device/Group Modal Flow** — docs_mockups_device_management_showadddevicemodal, docs_mockups_device_management_showaddgroupmodal, docs_mockups_device_management_closemodal, docs_mockups_device_management_savedevice [EXTRACTED 1.00]
- **LED Driver UI Mockup Set** — docs_mockups_images_index_dashboard_mockup, docs_mockups_images_index_pattern_selector_mockup, docs_mockups_images_index_device_management_mockup, docs_mockups_images_index_settings_mockup, docs_mockups_images_index_presets_mockup [EXTRACTED 1.00]
- **Selectable LED Patterns** — docs_mockups_images_pattern_selector_on, docs_mockups_images_pattern_selector_off, docs_mockups_images_pattern_selector_blink, docs_mockups_images_pattern_selector_chase, docs_mockups_images_pattern_selector_circle, docs_mockups_images_pattern_selector_pulse, docs_mockups_images_pattern_selector_rainbow, docs_mockups_images_pattern_selector_transition [EXTRACTED 1.00]
- **Preset/pattern configuration schema (pattern, colors, delay, step increment, N1-N8)** — docs_mockups_presets_led_patterns, docs_mockups_presets_delay, docs_mockups_presets_step_increment, docs_mockups_presets_n_parameters, docs_mockups_presets_step_offset [EXTRACTED 1.00]
- **Device settings sections** — docs_mockups_settings_basic_settings, docs_mockups_settings_pattern_settings, docs_mockups_settings_advanced_settings, docs_mockups_settings_network_settings [EXTRACTED 1.00]
- **LED Driver UI Mockup Suite** — docs_mockups_index, docs_mockups_dashboard, docs_mockups_pattern_selector, docs_mockups_device_management, docs_mockups_readme_settings_mockup, docs_mockups_color_picker_readme_presets_mockup [EXTRACTED 1.00]
- **Pi-to-ESP32 Command Paths** — docs_specification_serial_espnow_bridge, docs_specification_wifi_driver_tcp, docs_specification_espnow, docs_specification_pi_controller [EXTRACTED 1.00]
- **led_strip backend choice (RMT vs SPI, DMA)** — scripts_led_test_managed_components_espressif__led_strip_readme_rmt_backend, scripts_led_test_managed_components_espressif__led_strip_readme_spi_backend, scripts_led_test_managed_components_espressif__led_strip_readme_dma_support, scripts_led_test_managed_components_espressif__led_strip_readme_backend_selection_flowchart [EXTRACTED 1.00]
- **led_strip pixel write and flush flow** — scripts_led_test_managed_components_espressif__led_strip_api_led_strip_set_pixel, scripts_led_test_managed_components_espressif__led_strip_api_led_strip_set_pixel_hsv, scripts_led_test_managed_components_espressif__led_strip_api_led_strip_set_pixel_rgbw, scripts_led_test_managed_components_espressif__led_strip_api_led_strip_refresh, scripts_led_test_managed_components_espressif__led_strip_api_led_strip_clear [EXTRACTED 1.00]
- **Dynamic pattern contract** — led_driver_docs_pattern_contract_class_shape, led_driver_docs_pattern_contract_run_generator_rules, led_driver_docs_pattern_contract_drawing_brightness, led_driver_docs_pattern_contract_step_semantics, led_driver_docs_pattern_contract_error_handling [EXTRACTED 1.00]
- **Pi Animation Engine Output Pipeline** — docs_specification_pixel_generator, docs_specification_output_drivers, docs_specification_output_record, docs_specification_zone_playback, docs_specification_sequencer [EXTRACTED 1.00]
- **Beat-Driven Scene Activation** — docs_specification_beat_detection_device, docs_specification_bpm_sync, docs_specification_beat_counter_phases, docs_specification_scene_queue [INFERRED 0.85]
- **Fields defining an LED preset (name, pattern, colours, parameters)** — docs_images_help_preset_editor_preset_name_field, docs_images_help_preset_editor_pattern_selector, docs_images_help_preset_editor_palette_linked_colour, docs_images_help_preset_editor_preset_parameters [INFERRED 0.85]
- **Pattern settings composed and applied to devices** — docs_mockups_images_dashboard_pattern_selection, docs_mockups_images_dashboard_brightness_speed, docs_mockups_images_dashboard_colors, docs_mockups_images_dashboard_apply_settings [INFERRED 0.85]
- **Preset lifecycle actions (create, apply, sync)** — docs_mockups_images_presets_create_preset, docs_mockups_images_presets_apply_preset, docs_mockups_images_presets_sync_presets_to_all_devices [INFERRED 0.85]
- **ESP-NOW driver delivery layers** — docs_api_binary_envelope, docs_api_delivery_digest, docs_bench_test_reliable_link, docs_bench_test_beat_double_send [INFERRED 0.85]
- **v1 message handling on driver** — led_driver_docs_api_v1_message, led_driver_docs_patterns_process_data_flow, led_driver_docs_patterns_pattern_registry, led_driver_docs_patterns_preset_short_keys, led_driver_docs_api_select_message [INFERRED 0.85]
## Communities (196 total, 65 thin omitted)
### Community 0 - "IdfDevice"
Cohesion: 0.09
Nodes (8): _hex_rgb(), _idf_post(), _idf_show(), _preset_content(), print_settings(), run_idf(), IdfDevice, probe()
### Community 1 - "htmx Library"
Cohesion: 0.08
Nodes (101): a(), Ae(), an(), at(), B(), be(), bn(), bt() (+93 more)
### Community 3 - "Browser Tests & Mockup Images"
Cohesion: 0.06
Nodes (17): generate_image(), generate_with_html2image(), generate_with_playwright(), generate_with_selenium(), main(), browser(), _browser_sleep(), BrowserTest (+9 more)
### Community 4 - "Audio UI (JS)"
Cohesion: 0.11
Nodes (58): applyAudioStatus(), applyServerAudioUiFields(), audioRunPreferredDeviceId(), beatSyncButtonTitle(), bind(), clampLiveBpm(), clampSimulatedBpm(), clearBeatPhaseTimers() (+50 more)
### Community 5 - "cJSON.c"
Cohesion: 0.07
Nodes (63): add_item_to_array(), add_item_to_object(), buffer_skip_whitespace(), case_insensitive_strcmp(), cast_away_const(), cJSON_AddItemReferenceToArray(), cJSON_AddItemToObjectCS(), cJSON_AddRawToObject() (+55 more)
### Community 6 - "bench.c"
Cohesion: 0.13
Nodes (15): bench_on_beat_tx(), bench_running(), bench_start(), bench_stop(), gen_cb(), gpio_mark(), log_task(), espnow_tx_beat() (+7 more)
### Community 7 - "led-tool Device CLI"
Cohesion: 0.07
Nodes (16): download_presets(), download_settings(), _get_ordered_actions(), main(), resolve_flash_binary(), upload_presets(), upload_settings(), copy_file() (+8 more)
### Community 8 - "ab"
Cohesion: 0.11
Nodes (86): chase_draw(), ease_t(), first_call(), fx_aurora(), fx_bar_graph(), fx_blink(), fx_blizzard(), fx_candle_glow() (+78 more)
### Community 9 - "Compiler"
Cohesion: 0.07
Nodes (5): Template, Loader, Loader, Compiler, Loader
### Community 10 - "Spec: Pi Animation Engine"
Cohesion: 0.07
Nodes (46): Pi Animation Engine (src/engine), docs/API.md, Beat Counter and Phases, Beat Detection Device, Binary Message Protocol, BPM Sync, Dashboard UI (dashboard.html), usqlite Database Schema (presets, profiles, scenes, scene_groups) (+38 more)
### Community 11 - "espnow_link.cpp"
Cohesion: 0.08
Nodes (36): esp_random(), beat_on_frame(), beat_period_ms(), Asm, buf, cnt, asm_find(), flags (+28 more)
### Community 12 - "Presets UI (JS)"
Cohesion: 0.09
Nodes (42): arrayToGrid(), coerceManualBeatN(), coercePresetAuto(), coercePresetBackground(), coercePresetInt(), createPresetButton(), deviceNamesForPresetOnCurrentZone(), editPresetFromTab() (+34 more)
### Community 13 - "Zones UI (JS)"
Cohesion: 0.10
Nodes (42): applyBrightnessSliders(), applyZoneContentKindEditModal(), clamp255(), computeZoneNamesTargets(), computeZonePresetUnionTargets(), computeZoneTargets(), createZone(), effectiveGroupIdsForZonePreset() (+34 more)
### Community 14 - "web.cpp"
Cohesion: 0.04
Nodes (38): drop_unicast_peers(), ensure_peer(), handle_frame(), host_rx_task(), log_hook(), on_recv(), on_sent(), put_u32() (+30 more)
### Community 15 - "new_id"
Cohesion: 0.08
Nodes (13): new_id(), test_preset_round_trip(), test_profile_round_trip(), test_sequence_round_trip(), test_play_needs_steps(), test_play_needs_zone(), test_scoped_to_profile(), test_clone() (+5 more)
### Community 16 - "Sequences UI (JS)"
Cohesion: 0.08
Nodes (55): addSeqTarget(), addSequenceToTab(), addTargetsPerDriver(), appendZoneSequenceTiles(), applySequenceEditorMode(), applySequenceKindUi(), applySequenceSwitchWaitFromServer(), buildLaneGroupIdsForEditor() (+47 more)
### Community 17 - "layout.py"
Cohesion: 0.27
Nodes (6): normalise_layout(), _reversed_for_column(), side_name(), strip_count(), strip_places(), StripPlace
### Community 18 - "main/main.c"
Cohesion: 0.08
Nodes (8): cJSON_Hooks, dhcp_settled(), link_up_task(), mount(), esp_vfs_littlefs_register(), mic_get_level(), mic_start(), mic_stream_open()
### Community 19 - "led_strip Component Docs"
Cohesion: 0.10
Nodes (36): led_test ESP-IDF project, led_test main component (main.c), led_strip API Reference, led_model_t (WS2812/SK6812), led_pixel_format_t (GRB/GRBW), led_strip_clear(), led_strip_config_t, led_strip_del() (+28 more)
### Community 20 - "Art-Net Output"
Cohesion: 0.09
Nodes (10): ArtNet, as_channels(), build_artdmx(), _ip_bytes(), _pad(), port_lo(), ticks_diff(), ticks_ms() (+2 more)
### Community 21 - "freertos.c"
Cohesion: 0.06
Nodes (48): rx_task(), make_deadline(), queue_send(), sem_give(), sem_new(), sem_take(), uxQueueMessagesWaiting(), vEventGroupDelete() (+40 more)
### Community 22 - "cJSON_GetObjectItem"
Cohesion: 0.17
Nodes (32): cJSON_CreateNull(), cJSON_Duplicate(), cJSON_GetObjectItem(), api_id(), api_set(), api_settings_defaults(), add_ref(), export_profile() (+24 more)
### Community 23 - "cJSON_IsString"
Cohesion: 0.06
Nodes (116): cJSON, child, cJSON_DeleteItemFromArray(), cJSON_DetachItemFromArray(), cJSON_DetachItemFromObject(), cJSON_DetachItemViaPointer(), cJSON_GetArrayItem(), cJSON_GetArraySize() (+108 more)
### Community 24 - "web.cpp"
Cohesion: 0.09
Nodes (84): cJSON_AddArrayToObject(), cJSON_AddBoolToObject(), cJSON_AddFalseToObject(), cJSON_AddItemToArray(), cJSON_AddItemToObject(), cJSON_AddNullToObject(), cJSON_AddNumberToObject(), cJSON_AddObjectToObject() (+76 more)
### Community 27 - "seqplay.c"
Cohesion: 0.09
Nodes (62): cJSON_IsFalse(), api_register(), engine_zone_targets(), on_announce(), espnow_tx_set_mic_beats(), add_id(), advance_time(), anchor_bar() (+54 more)
### Community 28 - "Devices UI (JS)"
Cohesion: 0.10
Nodes (32): applyEspnowPingAggregateToDots(), applyEspnowPingToDeviceRows(), applyTcpSnapshot(), applyTransportVisibility(), collectDeviceEditPayload(), createDeviceFromModal(), createDeviceIdentifyButton(), DEVICE_DOT_CLASSES (+24 more)
### Community 29 - "binary_envelope.py"
Cohesion: 0.15
Nodes (18): brightness_0_255_from_wire(), brightness_wire_from_0_255(), _clamp_i16(), _colors_to_rgb_list(), _decode_default_blob(), _decode_preset_record(), _decode_presets_blob(), _decode_select_blob() (+10 more)
### Community 30 - "Colour Picker Mockups"
Cohesion: 0.11
Nodes (25): Chromium-style Color Picker Demo, ColorPickerChromium Component, updateColors() (Chromium demo), Custom Color Picker Demo, updateColors() (standard demo), Custom Colour Picker README, POST /api/colors (example), ColorPicker Component (+17 more)
### Community 32 - "groups_route"
Cohesion: 0.21
Nodes (20): cJSON_CreateArray(), cJSON_CreateDoubleArray(), cJSON_CreateFloatArray(), cJSON_CreateIntArray(), cJSON_CreateNumber(), cJSON_CreateStringArray(), suffix_object(), rgb_json() (+12 more)
### Community 33 - "httpd_parse.c"
Cohesion: 0.06
Nodes (55): cb_header_field(), cb_header_value(), cb_headers_complete(), cb_no_body(), cb_on_body(), cb_url(), continue_parsing(), httpd_cookie_key_value() (+47 more)
### Community 34 - "test_sequences.py"
Cohesion: 0.19
Nodes (19): clock(), make(), presets(), test_animation_over_sequence_keeps_time(), test_animation_plays_once_alone(), test_animation_step_fires_overlay(), test_beat_and_time_lanes_together(), test_chase_moves_and_bounces() (+11 more)
### Community 35 - "microdot.py"
Cohesion: 0.10
Nodes (5): invoke_handler(), iscoroutine(), Response, aclose(), __anext__()
### Community 36 - "API Docs: Outputs & Audio"
Cohesion: 0.18
Nodes (19): Controller WebSocket /ws (v1 presets/select), Binary envelope (main/envelope.c, test/binary_envelope.py), Profile/preset/sequence JSON bundles (import/export), /db collection export and replace, Devices resource /devices, Driver group membership lists (group ids, z<zone id>), Device groups resource /groups, LED Controller HTTP/JSON API (+11 more)
### Community 37 - "store_init"
Cohesion: 0.67
Nodes (4): cJSON_InitHooks(), db_root(), load_file(), store_init()
### Community 38 - "socket"
Cohesion: 0.20
Nodes (6): discover(), _expand(), _ip(), local_subnet(), ota_drivers(), parse_targets()
### Community 39 - "Beat Detection DSP (C)"
Cohesion: 0.27
Nodes (16): beat_feed(), analyse_beat(), bar_cue(), bar_decide(), beat_dsp_feed(), beat_dsp_init(), beat_dsp_tap(), best_phase() (+8 more)
### Community 40 - "test_presets.py"
Cohesion: 0.13
Nodes (4): preset(), test_create_belongs_to_current_profile(), test_create_fills_defaults(), test_presets_scoped_to_profile()
### Community 41 - "esp_http_server.h"
Cohesion: 0.06
Nodes (30): esp_http_server_event_data, http_method, httpd_close_func_t, httpd_err_code_t, httpd_method_t, httpd_open_func_t, httpd_resp_send_404(), httpd_resp_send_408() (+22 more)
### Community 42 - "run_all"
Cohesion: 0.13
Nodes (12): dim(), expected(), frame(), frame_sum(), mismatch_detail(), packet(), read_serial(), run_all() (+4 more)
### Community 43 - "outputs.c"
Cohesion: 0.19
Nodes (16): fail(), fill(), one_of(), put16(), resolve(), run_test(), send_artnet(), send_ddp() (+8 more)
### Community 44 - "move_bars.py"
Cohesion: 0.39
Nodes (4): call(), main(), switch(), wifi_state()
### Community 45 - "http_parser.h"
Cohesion: 0.05
Nodes (42): flags, F_CHUNKED, F_CONNECTION_CLOSE, F_CONNECTION_KEEP_ALIVE, F_CONNECTION_UPGRADE, F_CONTENTLENGTH, F_SKIPBODY, F_TRAILING (+34 more)
### Community 46 - "BridgeSim"
Cohesion: 0.14
Nodes (4): BridgeSim, mac_str(), _read_json(), Strip
### Community 47 - "USB Latency Tools"
Cohesion: 0.12
Nodes (13): discover(), local_subnet(), main(), analyze(), edges(), main(), pct(), read() (+5 more)
### Community 50 - "WS2812"
Cohesion: 0.08
Nodes (13): new_ws2812_encoder(), rmt_del_ws2812_encoder(), rmt_encode_ws2812(), rmt_ws2812_encoder_reset(), rmt_ws2812_encoder_t, WS2812, channel_, encoder_ (+5 more)
### Community 52 - "Transport"
Cohesion: 0.23
Nodes (3): _convert_filesystem_error(), stdout_write_bytes(), Transport
### Community 53 - "mpremote Transport"
Cohesion: 0.12
Nodes (20): Presets Mockup Page, addColorPicker() / initializeColorPickers(), ColorPicker component (color-picker.js / color-picker.css), Preset Delay (animation speed, 10-1000 ms), ESPNow preset distribution, filterPresets() / sortPresets() search, filter and sort, LED Patterns (on, off, blink, chase, circle, pulse, rainbow, transition), Pattern Parameters N1-N8 (+12 more)
### Community 54 - "web.c"
Cohesion: 0.15
Nodes (24): esp_err_to_name(), httpd_register_uri_handler(), ota_register(), add_uri(), web_start(), audio_api_register(), audio_register(), start_webserver() (+16 more)
### Community 57 - "httpd_config"
Cohesion: 0.06
Nodes (30): httpd_config, backlog_conn, close_fn, core_id, ctrl_port, enable_so_linger, global_transport_ctx, global_transport_ctx_free_fn (+22 more)
### Community 60 - "mpremote Serial Transport"
Cohesion: 0.14
Nodes (3): SerialIntercept, SerialTransport, TransportError
### Community 61 - "API Test Fixtures & Audio"
Cohesion: 0.16
Nodes (5): base_url(), c(), Client, profile(), restore_db()
### Community 62 - "Microdot Request (dmx)"
Cohesion: 0.15
Nodes (4): Request, G, urldecode_bytes(), urldecode_str()
### Community 63 - "Help: Zones & Palette"
Cohesion: 0.13
Nodes (18): Colour Palette (per profile), Zone default preset (default hint), DJ zone starter option, From Palette linked colours, LED driver JSON (presets, select, save, default, manifest), Patterns dialog, POST /presets/send, Preset editor (Try, Save, Send, Manual) (+10 more)
### Community 64 - "ddp_test.py"
Cohesion: 0.08
Nodes (23): hsv(), rig_mid(), rig_rows(), rig_xy(), soak_rig_bounce(), soak_rig_checker(), soak_rig_columns(), soak_rig_converge() (+15 more)
### Community 66 - "esp_timer_get_time"
Cohesion: 0.05
Nodes (55): httpd_os_thread_sleep(), esp_rom_delay_us(), vTaskDelay(), beat_get_info(), beat_set_callback(), beat_tap(), bench_on_echo(), bridge_active() (+47 more)
### Community 67 - "os"
Cohesion: 0.08
Nodes (4): mpremote_base(), main(), boot(), TransportExecError
### Community 68 - "build_app"
Cohesion: 0.22
Nodes (5): build_app(), api_seed_layout(), index(), static(), web()
### Community 69 - "httpd_handle_t"
Cohesion: 0.07
Nodes (43): httpd_free_ctx_fn_t, httpd_handle_t, httpd_pending_func_t, httpd_recv_func_t, httpd_send_func_t, httpd_recv_opt_t, sock_db, ctx (+35 more)
### Community 70 - "Index Page Modals"
Cohesion: 0.11
Nodes (19): Audio Beat Detection modal, Header BPM / beat sync indicator, Colour Palette modal, Devices modal, Edit device modal, Edit Zone modal, Device groups modal, Header global brightness slider (+11 more)
### Community 71 - "httpd_main.c"
Cohesion: 0.06
Nodes (44): httpd_os_thread_delete(), vSemaphoreDelete(), httpd_config_t, httpd_req, httpd_session_enum_function, thread_data, handle, status (+36 more)
### Community 72 - "httpd_data"
Cohesion: 0.11
Nodes (18): esp_http_server_event_id_t, httpd_err_handler_func_t, httpd_data, config, ctrl_fd, ctrl_sock_semaphore, err_handler_fns, hd_calls (+10 more)
### Community 74 - "create_app"
Cohesion: 0.12
Nodes (6): create_app(), serial_ports(), ws_handler(), list_serial_ports(), main(), output_tick()
### Community 75 - "esp_glue.c"
Cohesion: 0.07
Nodes (26): app_main(), load_channel(), esp_event_loop_create_default(), esp_event_post(), esp_get_free_heap_size(), esp_get_minimum_free_heap_size(), esp_log_level_set(), esp_log_set_vprintf() (+18 more)
### Community 76 - "Controller Overview & OTA Docs"
Cohesion: 0.20
Nodes (11): led_controller ESP-IDF project, Driver app update /drivers/ota (staged files, sha, commit/abort), Firmware OTA /ota (idle slot, rollback), Driver app update over ESP-NOW test (tools/driver_ota.py), led-tool / led-cli serial device CLI, led-cli --ota controller update over Ethernet, driver settings.json (mpremote download/merge/upload), main ESP-IDF component (firmware sources) (+3 more)
### Community 77 - "bridge_main.c"
Cohesion: 0.15
Nodes (11): bridge_crc16_update(), bridge_decode_feed(), bridge_encode(), bridge_serial_send(), bridge_serial_set_channel(), bridge_serial_start(), get_u32(), handle_frame() (+3 more)
### Community 79 - "Audio Monitor Page"
Cohesion: 0.16
Nodes (16): /audio.wav live PCM stream, bar() bar-position renderer, /beats SSE event stream, draw() timeline canvas, Listen button (WAV stream playback via AudioContext), median(), Audio and beats page (/audio), stats() tap vs computer agreement (+8 more)
### Community 80 - "Art-Net DMX Tests"
Cohesion: 0.26
Nodes (9): parse(), _assert_eq(), main(), test_artnet_send_loopback(), test_build_artdmx(), test_fixture_patch(), test_pattern_blink_and_select(), test_pattern_upload() (+1 more)
### Community 82 - "events"
Cohesion: 0.09
Nodes (21): cached, exitCode, stdout, variable, CMAKE_C_FLAGS, CMAKE_C_FLAGS_DEBUG, CMAKE_CXX_FLAGS, CMAKE_CXX_FLAGS_DEBUG (+13 more)
### Community 83 - "httpd_req_t"
Cohesion: 0.09
Nodes (41): esp_app_get_description(), esp_restart(), httpd_resp_sendstr(), httpd_req_async_handler_begin(), httpd_req_async_handler_complete(), httpd_req_recv(), httpd_resp_send(), httpd_resp_send_chunk() (+33 more)
### Community 84 - "unique"
Cohesion: 0.06
Nodes (15): find_id_by_field(), missing(), unique(), test_scenes(), device(), group(), test_crud(), test_group_identify_needs_devices() (+7 more)
### Community 85 - "ESP-NOW Sender Bridge"
Cohesion: 0.20
Nodes (10): ap(), _broadcast_ws(), _espnow_receive_loop(), _init_espnow(), main(), _send_espnow(), _validate_envelope(), ws() (+2 more)
### Community 86 - "ctrl_msg.cpp"
Cohesion: 0.05
Nodes (60): apply_device_config(), apply_presets(), clear_all_presets(), cstr(), ctrl_build_announce(), ctrl_handle(), ctrl_init(), expand_v1() (+52 more)
### Community 89 - "Rig"
Cohesion: 0.10
Nodes (10): lan_ip(), bridge_downlink(), driver_mac(), lan_ip(), load_config(), mac_str(), main(), _merge() (+2 more)
### Community 90 - "Sender"
Cohesion: 0.09
Nodes (10): get(), output_scale(), run_interactive(), handle(), show_menu(), run_soak(), sample(), send_sync() (+2 more)
### Community 92 - "Bench Test Plan"
Cohesion: 0.23
Nodes (9): Bench endpoints /test/loss and /test/beats, 30 ms beat lead (CONFIG_BEAT_LEAD_MS), Bench test: S3 controller and one LED driver, ESP32-C3 vs S3 driver comparison, Logic analyzer latency (marker GPIO, tools/analyze_edges.py), Lossy-link test (simulated loss, retries, resync), Reliable link (rel: acked unicast, retransmits, ack timeouts), Bench troubleshooting (serial ports, channel mismatch, blank UI) (+1 more)
### Community 93 - "events"
Cohesion: 0.09
Nodes (21): cached, exitCode, stdout, variable, CMAKE_C_FLAGS, CMAKE_C_FLAGS_DEBUG, CMAKE_CXX_FLAGS, CMAKE_CXX_FLAGS_DEBUG (+13 more)
### Community 94 - "api_call_t"
Cohesion: 0.33
Nodes (5): api_call_t, cap, done, msg, out
### Community 95 - "Microdot Auth (dmx)"
Cohesion: 0.19
Nodes (6): wraps(), print_exception(), websocket_upgrade(), websocket_wrapper(), wrapper(), with_websocket()
### Community 96 - "Serial DMX & WiFi"
Cohesion: 0.28
Nodes (3): sleep_ms(), SerialDMX, sleep()
### Community 98 - "DMX Preset Model"
Cohesion: 0.13
Nodes (8): _expand(), _preset_from_map(), process_data(), _select_entries(), _targets_for_key(), play(), _parse_colour(), Preset
### Community 99 - "esp_err.h"
Cohesion: 0.04
Nodes (49): main(), set_from_env(), usage(), heap_caps_calloc(), heap_caps_malloc(), be16(), be32(), ddp_set_enabled() (+41 more)
### Community 100 - "patterns.cpp"
Cohesion: 0.07
Nodes (49): usb_send_frame(), xSemaphoreGive(), xSemaphoreTake(), clamp_leds(), ddp_show(), frame_alloc(), fx_fn, now_ms() (+41 more)
### Community 101 - "Groups UI (JS)"
Cohesion: 0.29
Nodes (9): fetchDevicesMapForGroups(), fetchGroupsMap(), identifyGroupById(), loadGroupsModal(), loadWifiFieldsFromGroup(), openEditGroupModal(), renderGroupDevicesEditor(), renderGroupsList() (+1 more)
### Community 102 - "httpd_req_aux"
Cohesion: 0.11
Nodes (18): httpd_req_aux, content_type, first_chunk_sent, max_req_hdr_len, max_uri_len, remaining_len, req_hdrs_count, resp_hdrs (+10 more)
### Community 103 - "Help: Mobile Menu Image"
Cohesion: 0.24
Nodes (10): Mobile Menu Help Illustration (narrow screen), Content Area (preset buttons), Menu Dropdown (Run mode, Profiles, Tabs, Presets, Help), Header Tab Buttons, Help, Menu Button (header dropdown trigger), Presets, Profiles (+2 more)
### Community 104 - "Pattern Selector Mockup Image"
Cohesion: 0.20
Nodes (11): Pattern Selector Mockup (Select LED Pattern), Apply Pattern / Cancel Actions, Blink Pattern, Chase Pattern, Circle Pattern, Off Pattern, On Pattern (solid color), Pattern Card Grid Layout (+3 more)
### Community 105 - "Driver Pattern Docs"
Cohesion: 0.24
Nodes (11): Message processing order (version, presets upsert, colour, selection), Auto vs manual (a) and manual chase flush, Built-in off / on patterns, Patterns and presets on the LED driver, MAX_PRESETS = 32, Pattern OTA via manifest / POST /patterns/upload, Pattern registry (Presets.reload_patterns), Preset short keys (p, c, d, b, a, bg, n1-n6) (+3 more)
### Community 106 - "led-controller ESP32-S3 firmware"
Cohesion: 0.13
Nodes (12): Build and flash, Channel, Protocol, Running the controller against it, USB ESP-NOW bridge, Build and run, How it is built, Install as a service (.deb) (+4 more)
### Community 107 - "main"
Cohesion: 0.18
Nodes (8): find_devices(), probe(), sweep(), load_rig(), local_prefix(), main(), neighbours(), set_fps()
### Community 108 - "LedSimulatorApp"
Cohesion: 0.13
Nodes (3): _hex(), LedSimulatorApp, main()
### Community 109 - "Driver Message API Docs"
Cohesion: 0.38
Nodes (10): Auto vs manual mode, Beat (re-select same preset restarts generator), Hex colour conversion and colour-order reordering, LED Driver API (message format), Pattern-specific parameters (rainbow, pulse, transition, chase, circle), Preset fields (pattern, colors, delay, brightness, auto, n1-n6), Select message (device -> [preset, step]), Step synchronization (+2 more)
### Community 111 - "led_strip Manifest"
Cohesion: 0.20
Nodes (9): dependencies, idf, description, repository, repository_info, commit_sha, path, url (+1 more)
### Community 113 - "Outputs UI (JS)"
Cohesion: 0.33
Nodes (8): fetchOutputs(), loadOutputsModal(), openOutputEditor(), OUTPUT_PROTOCOL_LABELS, outputSummary(), renderOutputsList(), setOutputField(), syncOutputProtocolFields()
### Community 114 - "DMX Driver Art-Net and serial gateway"
Cohesion: 0.28
Nodes (9): Art-Net output (UDP 6454), DMX Driver Art-Net and serial gateway, DMX fixture (output, start channel, role map; parcan/mover profiles), led-driver-style pattern engine (Preset object), POST /patterns/upload (led-driver parity), Serial DMX512 output (250000 8N2), Outputs (DDP, Art-Net, sACN, DMX serial pixel fixtures), Patterns resource /patterns (+1 more)
### Community 115 - "Help PDF: Overview"
Cohesion: 0.25
Nodes (9): API.md, LED controller user guide, Main web UI (Raspberry Pi app), Pattern OTA install over HTTP (/patterns/ota, upload, driver, send), Pattern parameters n1-n8, README, Serial to ESP-NOW bridge transport, WebSocket /ws (+1 more)
### Community 116 - "Mockups Index Image"
Cohesion: 0.31
Nodes (9): LED Driver UI Mockups Index (screenshot), Dashboard Mockup, Device Groups, Device Management Mockup, LED Patterns (On, Off, Blink, Chase, Circle, Pulse, Rainbow, Transition), N1-N8 Pattern Parameters, Pattern Selector Mockup, Presets Mockup (+1 more)
### Community 117 - "bridge_sim.py"
Cohesion: 0.12
Nodes (11): driver_mac(), load_config(), main(), _merge(), sync_patterns(), rig_placements(), controller_url(), _get() (+3 more)
### Community 118 - "Help: Header Toolbar Image"
Cohesion: 0.29
Nodes (8): Header Toolbar Help Image, Edit Mode Action Bar, Run/Edit Mode Toggle Button, Patterns Action, Presets Action, Profiles Action, Header Tab Buttons, Tabs Action
### Community 119 - "Help: Preset Editor Image"
Cohesion: 0.29
Nodes (5): Default Action, Preset Pattern Selector, Preset Editor Modal (help illustration), Preset Name Field, Brightness, Delay and n1-n8 Parameters (0-255)
### Community 120 - "Dashboard Mockup Image"
Cohesion: 0.32
Nodes (8): LED Driver Control Panel Dashboard Mockup, Apply Settings Action, Brightness & Speed Card (Brightness % and Delay ms sliders), Colors Card (color swatches palette, Add Color), Connected Devices Card (devices with group and online status), Device Groups, Pattern Selection Card (On, Off, Blink, Chase, Circle, Pulse, Rainbow, Transition), Save to Device Action
### Community 121 - "Device Management Mockup Image"
Cohesion: 0.32
Nodes (8): + Add Device Button, Connected Devices List, Device Group, Device & Group Management Screen (mockup), Device Row Actions (edit, settings, stop), Online/Offline Status Badge, Devices / Groups Tab Switcher, LED Device (MAC, group, pattern)
### Community 122 - "Presets Mockup Image"
Cohesion: 0.32
Nodes (8): Preset Management UI Mockup, Apply Preset Action, Create Preset Action, LED Pattern Types (Rainbow, Pulse, Chase, Circle, Blink, Transition), Preset Card (name, pattern badge, color swatches, delay, n1, apply/edit/delete), Preset Search/Filter/Sort Toolbar (pattern filter, sort by name, grid/list toggle), Preset Parameters (colors, delay ms, n1), Sync Presets to All Devices
### Community 123 - "Pattern Contract"
Cohesion: 0.29
Nodes (6): Pattern Contract, Drawing via driver.n and apply_brightness, Pattern error handling (Presets.tick catches), Presets._load_dynamic_patterns(), Shared driver.step semantics, Global vs per-preset brightness
### Community 124 - "httpd_ws.c"
Cohesion: 0.16
Nodes (23): desktop_base64_encode(), desktop_sha1(), rol(), sha1_block(), httpd_ws_frame_t, transfer_complete_cb, httpd_send(), httpd_ws_check_req() (+15 more)
### Community 128 - "httpd_ctrl_data"
Cohesion: 0.22
Nodes (9): httpd_work_fn_t, httpd_ctrl_data, hc_msg, hc_work, hc_work_arg, httpd_ctrl_msg, HTTPD_CTRL_MAX, HTTPD_CTRL_SHUTDOWN (+1 more)
### Community 129 - "Colour Picker Demo Image"
Cohesion: 0.33
Nodes (6): Custom Color Picker Demo (screenshot), Hex and RGB input support, HSB (Hue, Saturation, Brightness) color model, Keyboard accessible, customizable styling, Multiple Color Pickers for LED Patterns, Single Color Picker
### Community 130 - "Settings Mockup Image"
Cohesion: 0.33
Nodes (7): Advanced Settings (Step Counter, Step Increment, Device ID, Debug Mode), Basic Settings (Device Name, LED Pin, Number of LEDs), Color Order Selector (RGB/RBG/GRB/GBR/BRG/BGR), Device Settings Page Mockup, Network Settings (Access Point Name, Password, Enable AP), Pattern Parameters N1-N6, Pattern Settings (Pattern, Brightness, Delay)
### Community 131 - "sim_demo.py"
Cohesion: 0.26
Nodes (7): Api, main(), group(), preset(), sequence(), new_id(), rig_bars()
### Community 135 - "httpd_req_t"
Cohesion: 0.09
Nodes (88): cJSON_AddItemReferenceToObject(), cJSON_CreateString(), cJSON_Delete(), cJSON_DeleteItemFromObject(), cJSON_Parse(), httpd_req_t, api_add(), api_body() (+80 more)
### Community 137 - "time"
Cohesion: 0.08
Nodes (17): Blink, Pulse, _default_image(), _info(), ota_update(), sleep(), sleep_ms(), sleep_us() (+9 more)
### Community 138 - "Help: Colour Palette Image"
Cohesion: 0.40
Nodes (6): Colour Palette modal mockup (help image), Add Swatch (+) Button, Colour Palette Modal, Palette Colour Swatches, Preset Editor 'From Palette', Profile (palette owner)
### Community 139 - "httpd_req"
Cohesion: 0.20
Nodes (10): httpd_req, aux, content_len, free_ctx, handle, ignore_sess_ctx_changes, method, sess_ctx (+2 more)
### Community 140 - "LED Driver README"
Cohesion: 0.47
Nodes (6): dev.py deploy/sync script, LED Driver README (MicroPython ESP32), Optional HTTP polling (http_poll.py), Wi-Fi TCP transport to Pi (port 8765), transport_type setting (wifi / espnow), UDP discovery (port 8766)
### Community 142 - "SPI Example Manifest"
Cohesion: 0.33
Nodes (5): dependencies, espressif/led_strip, idf, override_path, version
### Community 143 - "test_rig_sim.py"
Cohesion: 0.10
Nodes (28): all_dark(), col_of(), frames(), led_x(), lit(), mac(), make_preset(), need_sim() (+20 more)
### Community 145 - "Help PDF: Modes"
Cohesion: 0.40
Nodes (4): Edit mode, Mobile layout Menu, Run mode, Zones modal
### Community 146 - "Help: Tab Preset Strip Image"
Cohesion: 0.60
Nodes (5): Help image: Main area brightness and preset tiles, Edit Mode: drag tiles to reorder, Global Brightness Slider, Preset Tile (gradient swatch, click to select on tab devices), Tab (e.g. lounge)
### Community 149 - "res_device.c"
Cohesion: 0.17
Nodes (28): cJSON_AddTrueToObject(), cJSON_IsNull(), setting_int(), api_effective_brightness(), api_identify_group(), clamp255(), device_brightness(), device_config_from() (+20 more)
### Community 155 - "app.js"
Cohesion: 0.16
Nodes (35): addLog(), banner(), colourAt(), connectBridge(), deliver(), drawLabel(), drawPlaced(), drawStrip() (+27 more)
### Community 156 - "RMT Example Manifest"
Cohesion: 0.40
Nodes (4): dependencies, espressif/led_strip, override_path, version
### Community 157 - "Help Tab JS"
Cohesion: 0.36
Nodes (5): addStaticIpRow(), loadDeviceSettings(), loadNetworkStatus(), setApToggle(), switchSettingsTab()
### Community 158 - "Settings Page Template"
Cohesion: 0.50
Nodes (4): Settings modal (device, network), loadEspnowChannel(), Device Settings page (ESP-NOW channel), wifi_channel setting (1-11)
### Community 159 - "led-driver/web/app.js"
Cohesion: 0.10
Nodes (49): api(), applyMode(), attachDrag(), closeEditor(), closeSock(), deviceChoices(), direct(), discoverDevices() (+41 more)
### Community 166 - "led_strip_rmt_encoder.c"
Cohesion: 0.22
Nodes (5): led_strip_encoder_config_t, rmt_del_led_strip_encoder(), rmt_encode_led_strip(), rmt_led_strip_encoder_reset(), rmt_new_led_strip_encoder()
### Community 170 - "dependencies"
Cohesion: 0.16
Nodes (13): dependencies, espressif/cjson, espressif/mdns, espressif/w5500, joltwallet/littlefs, version, rules, version (+5 more)
### Community 171 - "List Search (JS)"
Cohesion: 0.83
Nodes (3): applyListSearch(), initListSearch(), rowSearchText()
### Community 177 - "usb_cfg.cpp"
Cohesion: 0.10
Nodes (16): esp_fill_random(), handle_line(), usb_cfg_task(), write_line(), ws_fast_call(), ws_slot_drop(), ws_slot_t, fd (+8 more)
### Community 178 - "LED controller web UI user guide"
Cohesion: 0.36
Nodes (7): Audio API /api/audio and /audio page routes, Combined brightness (global x groups x device x zone), Sequence playback (lanes, beat advance, switching), Settings resource /settings, Run mode and Edit mode, Sequence sync button (S / BPM), LED controller web UI user guide
### Community 201 - "_simlink_web.py"
Cohesion: 0.05
Nodes (13): ESPNow, NeoPixel, _check_flash(), on_feed(), push_pixels(), real_sleep(), recv(), recv_nowait() (+5 more)
### Community 204 - "_simlink_proc.py"
Cohesion: 0.15
Nodes (5): connect(), on_feed(), push_pixels(), _reader(), _send_pixels()
### Community 227 - "dependencies"
Cohesion: 0.33
Nodes (5): dependencies, espressif/cjson, espressif/mdns, version, version
## Knowledge Gaps
- **289 isolated node(s):** `next`, `prev`, `child`, `type`, `valuestring` (+284 more)
These have ≤1 connection - possible missing edges or undocumented components. (Counts symbols only; 1223 node(s) total have ≤1 connection when file, concept and rationale nodes are included.)
- **65 thin communities (<3 nodes) omitted from report** — run `graphify query` to explore isolated nodes.
## Suggested Questions
_Questions this graph is uniquely positioned to answer:_
- **Why does `BridgeSim` connect `BridgeSim` to `mac_str`, `Microdot WebSocket (dmx)`, `LedSimulatorApp`, `layout.py`, `bridge_sim.py`, `Microdot`?**
_High betweenness centrality (0.036) - this node is a cross-community bridge._
- **Are the 165 inferred relationships involving `cJSON_GetObjectItem()` (e.g. with `apply_default()` and `apply_device_config()`) actually correct?**
_`cJSON_GetObjectItem()` has 165 INFERRED edges - model-reasoned connections that need verification._
- **What connects `next`, `prev`, `child` to the rest of the system?**
_289 weakly-connected nodes found - possible documentation gaps or missing edges._
- **Should `IdfDevice` be split into smaller, more focused modules?**
_Cohesion score 0.09411764705882353 - nodes in this community are weakly interconnected._
- **Why does `led-controller ESP32-S3 firmware` connect `led-controller ESP32-S3 firmware` to `API Docs: Outputs & Audio`, `Controller Overview & OTA Docs`, `LED controller web UI user guide`, `DMX Driver Art-Net and serial gateway`, `Bench Test Plan`?**
_High betweenness centrality (0.024) - this node is a cross-community bridge._
- **Are the 94 inferred relationships involving `cJSON_Delete()` (e.g. with `ctrl_handle()` and `decode_presets()`) actually correct?**
_`cJSON_Delete()` has 94 INFERRED edges - model-reasoned connections that need verification._
- **Should `htmx Library` be split into smaller, more focused modules?**
_Cohesion score 0.07897684839432412 - nodes in this community are weakly interconnected._
+12
View File
@@ -0,0 +1,12 @@
{
"runs": [
{
"date": "2026-11-03T12:13:15.159050+00:00",
"input_tokens": 1267015,
"output_tokens": 0,
"files": 332
}
],
"total_input_tokens": 1267015,
"total_output_tokens": 0
}
+1
View File
@@ -0,0 +1 @@
{"directed":false,"multigraph":false,"graph":{"hyperedges":[{"id":"audio_page_endpoints","label":"Audio page live endpoints","nodes":["web_audio_status","web_audio_beats","web_audio_audio_wav","web_audio_time","web_audio_tap_ep"],"relation":"participate_in","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"web/audio.html"},{"id":"beat_latency_measurement","label":"Beat latency measurement methods","nodes":["docs_api_bench_endpoints","docs_bench_test_usb_latency","docs_bench_test_logic_analyzer","docs_bench_test_beat_lead"],"relation":"participate_in","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/BENCH_TEST.md"},{"id":"brightness_combination","label":"Combined brightness factors","nodes":["docs_api_combined_brightness","docs_api_settings","docs_api_groups","docs_api_devices","docs_api_zones"],"relation":"participate_in","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/API.md"},{"id":"color_picker_feature_set","label":"Color picker feature set","nodes":["docs_mockups_images_color_picker_demo_hsb_color_model","docs_mockups_images_color_picker_demo_hex_rgb_input","docs_mockups_images_color_picker_demo_keyboard_accessibility","docs_mockups_images_color_picker_demo_cross_platform_consistency"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/mockups/images/color-picker-demo.png"},{"id":"docs_help_edit_mode_management","label":"Edit-mode-only management features","nodes":["docs_help_edit_mode","docs_help_zones_modal","docs_help_send_presets","docs_help_patterns_dialog","docs_help_colour_palette","docs_help_presets_list"],"relation":"participate_in","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/help.pdf"},{"id":"docs_help_preset_editor_actions","label":"Preset editor actions (Try, Default, Save & Send, Remove from zone)","nodes":["docs_help_try_action","docs_help_default_preset","docs_help_save_and_send","docs_help_remove_from_zone"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/help.pdf"},{"id":"docs_images_help_mobile_menu_header_actions","label":"Header actions aggregated in mobile Menu","nodes":["docs_images_help_mobile_menu_run_mode","docs_images_help_mobile_menu_profiles","docs_images_help_mobile_menu_tabs","docs_images_help_mobile_menu_presets","docs_images_help_mobile_menu_help"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/images/help/mobile-menu.svg"},{"id":"docs_mockups_device_modal_flow","label":"Device/Group Modal Flow","nodes":["docs_mockups_device_management_showadddevicemodal","docs_mockups_device_management_showaddgroupmodal","docs_mockups_device_management_closemodal","docs_mockups_device_management_savedevice"],"relation":"participate_in","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/mockups/device-management.html"},{"id":"docs_mockups_images_index_ui_mockup_set","label":"LED Driver UI Mockup Set","nodes":["docs_mockups_images_index_dashboard_mockup","docs_mockups_images_index_pattern_selector_mockup","docs_mockups_images_index_device_management_mockup","docs_mockups_images_index_settings_mockup","docs_mockups_images_index_presets_mockup"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/mockups/images/index.png"},{"id":"docs_mockups_images_pattern_selector_led_patterns","label":"Selectable LED Patterns","nodes":["docs_mockups_images_pattern_selector_on","docs_mockups_images_pattern_selector_off","docs_mockups_images_pattern_selector_blink","docs_mockups_images_pattern_selector_chase","docs_mockups_images_pattern_selector_circle","docs_mockups_images_pattern_selector_pulse","docs_mockups_images_pattern_selector_rainbow","docs_mockups_images_pattern_selector_transition"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/mockups/images/pattern-selector.png"},{"id":"docs_mockups_preset_schema","label":"Preset/pattern configuration schema (pattern, colors, delay, step increment, N1-N8)","nodes":["docs_mockups_presets_led_patterns","docs_mockups_presets_delay","docs_mockups_presets_step_increment","docs_mockups_presets_n_parameters","docs_mockups_presets_step_offset"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/mockups/presets.html"},{"id":"docs_mockups_settings_sections","label":"Device settings sections","nodes":["docs_mockups_settings_basic_settings","docs_mockups_settings_pattern_settings","docs_mockups_settings_advanced_settings","docs_mockups_settings_network_settings"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/mockups/settings.html"},{"id":"docs_mockups_ui_mockup_suite","label":"LED Driver UI Mockup Suite","nodes":["docs_mockups_index","docs_mockups_dashboard","docs_mockups_pattern_selector","docs_mockups_device_management","docs_mockups_readme_settings_mockup","docs_mockups_color_picker_readme_presets_mockup"],"relation":"foLine truncated
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,83 @@
{
"1": "htmx Library",
"3": "Browser Tests & Mockup Images",
"4": "Audio UI (JS)",
"7": "led-tool Device CLI",
"10": "Spec: Pi Animation Engine",
"12": "Presets UI (JS)",
"13": "Zones UI (JS)",
"16": "Sequences UI (JS)",
"19": "led_strip Component Docs",
"20": "Art-Net Output",
"28": "Devices UI (JS)",
"30": "Colour Picker Mockups",
"36": "API Docs: Outputs & Audio",
"39": "Beat Detection DSP (C)",
"47": "USB Latency Tools",
"48": "Colour Picker JS",
"49": "Chromium Colour Picker JS",
"51": "API Tests: Devices",
"53": "mpremote Transport",
"61": "API Test Fixtures & Audio",
"62": "Microdot Request (dmx)",
"63": "Help: Zones & Palette",
"70": "Index Page Modals",
"73": "Microdot WebSocket (dmx)",
"76": "Controller Overview & OTA Docs",
"79": "Audio Monitor Page",
"85": "ESP-NOW Sender Bridge",
"87": "Microdot Async IO (dmx)",
"88": "DMX Settings",
"91": "Microdot Routing (dmx)",
"95": "Microdot Auth (dmx)",
"98": "DMX Preset Model",
"101": "Groups UI (JS)",
"103": "Help: Mobile Menu Image",
"104": "Pattern Selector Mockup Image",
"105": "Driver Pattern Docs",
"109": "Driver Message API Docs",
"111": "led_strip Manifest",
"113": "Outputs UI (JS)",
"115": "Help PDF: Overview",
"116": "Mockups Index Image",
"118": "Help: Header Toolbar Image",
"119": "Help: Preset Editor Image",
"120": "Dashboard Mockup Image",
"121": "Device Management Mockup Image",
"122": "Presets Mockup Image",
"123": "Pattern Contract",
"127": "Numpad Shortcuts (JS)",
"129": "Colour Picker Demo Image",
"130": "Settings Mockup Image",
"134": "API Tests: Settings",
"138": "Help: Colour Palette Image",
"140": "LED Driver README",
"142": "SPI Example Manifest",
"145": "Help PDF: Modes",
"146": "Help: Tab Preset Strip Image",
"156": "RMT Example Manifest",
"157": "Help Tab JS",
"158": "Settings Page Template",
"171": "List Search (JS)",
"172": "DMX Solid Pattern",
"173": "led-test Manifest",
"174": "VPN Autoconnect Script",
"175": "Zone Devices Panel",
"176": "graphify Instructions",
"180": "Device Mockup Modals",
"181": "bulk.sh Script",
"182": "deploy.sh Script",
"183": "Driver install.sh",
"185": "led-tool install.sh",
"186": "Help PDF Build Script",
"187": "Web Build Script",
"188": "Patterns UI (JS)",
"189": "DMX Patterns Init",
"190": "Mockup Tab Switch",
"191": "Spec: Pattern Selector UI",
"192": "mpremote Package",
"193": "Bundle Import/Export (JS)",
"194": "Colour Palette (JS)",
"195": "Profiles UI (JS)",
"196": "Zone Palette (JS)"
}
+876
View File
@@ -0,0 +1,876 @@
# Graph Report - led-controller (2026-11-15)
## Corpus Check
- 360 files · ~658,275 words
- Verdict: corpus is large enough that graph structure adds value.
- Unclassified: 1316 file(s) not represented in the graph (top: .obj 884, .cmake 160, .a 104)
## Summary
- 4531 nodes · 12916 edges · 214 communities (148 shown, 66 thin omitted)
- Extraction: 74% EXTRACTED · 26% INFERRED · 0% AMBIGUOUS · INFERRED: 3302 edges (avg confidence: 0.85)
- Token cost: 0 input · 0 output
## Graph Freshness
- Built from commit: `cf390284`
- Run `git rev-parse HEAD` and compare to check if the graph is stale.
- Run `graphify update .` after code changes (no API cost).
## Community Hubs (Navigation)
- IdfDevice
- htmx Library
- machine.py
- Browser Tests & Mockup Images
- Audio UI (JS)
- cJSON
- beat.c
- led-tool Device CLI
- ab
- Compiler
- Spec: Pi Animation Engine
- Asm
- Presets UI (JS)
- Zones UI (JS)
- patterns.c
- new_id
- Sequences UI (JS)
- SerialTransport
- main/main.c
- led_strip Component Docs
- Art-Net Output
- freertos.c
- httpd_txrx.c
- cJSON_IsString
- cJSON_Delete
- Microdot
- ctrl_msg.cpp
- seqplay.c
- Devices UI (JS)
- binary_envelope.py
- Colour Picker Mockups
- PyboardCommand
- httpd_sess.c
- httpd_parse.c
- test_sequences.py
- esp_http_server.h
- API Docs: Outputs & Audio
- esp_timer_get_time
- socket
- Beat Detection DSP (C)
- cJSON_IsNumber
- bridge_serial.c
- run_all
- outputs.c
- httpd_req
- http_parser.h
- BridgeSim
- USB Latency Tools
- Colour Picker JS
- Chromium Colour Picker JS
- WS2812
- API Tests: Devices
- Transport
- mpremote Transport
- httpd_main.c
- cJSON_CreateString
- test_routes.py
- httpd_config
- test_outputs.py
- mic_alsa.c
- create_app
- API Test Fixtures & Audio
- Microdot Request (dmx)
- Help: Zones & Palette
- ddp_test.py
- pytest
- http_parser.c
- sys
- sock_db
- test_patterns.py
- Index Page Modals
- string
- httpd_data
- Microdot WebSocket (dmx)
- presets.cpp
- Bench test: S3 controller and one LED driver
- Controller Overview & OTA Docs
- espnow_link.cpp
- httpd_register_uri_handler
- Audio Monitor Page
- artnet_dmx.py
- OutputManager
- events
- httpd_resp_set_type
- unique
- ESP-NOW Sender Bridge
- net.cpp
- Microdot Async IO (dmx)
- DMX Settings
- api_call_t
- Sender
- Microdot Routing (dmx)
- http_parser
- events
- groups_route
- Microdot Auth (dmx)
- cJSON_CreateObject
- v1 driver messages (long/short keys)
- DMX Preset Model
- status_get
- xSemaphoreGive
- Groups UI (JS)
- httpd_req_aux
- Help: Mobile Menu Image
- Pattern Selector Mockup Image
- Driver Pattern Docs
- USB ESP-NOW bridge
- main
- bridge_sim.py
- Driver Message API Docs
- Missing
- led_strip Manifest
- led_strip_handle_t
- Outputs UI (JS)
- dependencies
- Help PDF: Overview
- Mockups Index Image
- HTTPException
- Help: Header Toolbar Image
- Help: Preset Editor Image
- Dashboard Mockup Image
- Device Management Mockup Image
- Presets Mockup Image
- Pattern Contract
- esp_httpd_priv.h
- led_strip_spi_dev.c
- sim_demo.py
- Numpad Shortcuts (JS)
- httpd_ctrl_data
- Colour Picker Demo Image
- Settings Mockup Image
- store_settings
- Response
- build_app
- PatternPlayer
- HttpDevice
- time
- Help: Colour Palette Image
- espnow_link_stats
- LED Driver README
- machine.py
- SPI Example Manifest
- test_rig_sim.py
- settings_editor.js
- Help PDF: Modes
- Help: Tab Preset Strip Image
- httpd_req_t
- vendor.sh
- app.js
- RMT Example Manifest
- Help Tab JS
- Settings Page Template
- led-driver/web/app.js
- test_presets.py
- mdns_host.c
- SerialDMX
- led_strip_rmt_dev_idf4.c
- led_strip_rmt_encoder.c
- dependencies
- List Search (JS)
- DMX Solid Pattern
- led-test Manifest
- VPN Autoconnect Script
- graphify Instructions
- esp_glue.c
- flags
- http_parser_url_fields
- bulk.sh Script
- deploy.sh Script
- Driver install.sh
- led_strip_types.h
- led-tool install.sh
- Help PDF Build Script
- Web Build Script
- Spec: Pattern Selector UI
- led_strip_rmt_dev.c
- rmt_encode_ws2812
- led-controller on a desktop
- http_parser_url
- _simlink_web.py
- relay_forward
- _simlink_proc.py
- WLAN
- NoCaseDict
- SimRing
- dependencies
- examples/blink.py
- README.md
## God Nodes (most connected - your core abstractions)
1. `cJSON` - 244 edges
2. `cJSON_GetObjectItem()` - 182 edges
3. `httpd_req_t` - 148 edges
4. `cJSON_Delete()` - 125 edges
5. `cJSON_CreateObject()` - 120 edges
6. `cJSON_IsString()` - 101 edges
7. `cJSON_AddStringToObject()` - 89 edges
8. `store_coll()` - 80 edges
9. `xSemaphoreTake()` - 59 edges
10. `xSemaphoreGive()` - 59 edges
## Surprising Connections (you probably didn't know these)
- `Channel` --references--> `bridge_serial_set_channel()` [INFERRED]
bridge/README.md → main/bridge_serial.c
- `Preset editor modal` --semantically_similar_to--> `Preset fields (pattern, colors, delay, brightness, auto, n1-n6)` [INFERRED] [semantically similar]
web/templates/index.html → led-driver/docs/API.md
- `Build and run` --references--> `info()` [INFERRED]
desktop/README.md → tools/ota.py
- `led-driver-style pattern engine (Preset object)` --semantically_similar_to--> `led-driver MicroPython firmware (submodule)` [INFERRED] [semantically similar]
dmx-driver/README.md → README.md
- `restart_cb()` --calls--> `esp_restart()` [INFERRED]
led-driver/main/net.cpp → desktop/port/src/esp_glue.c
## Import Cycles
- None detected.
## Hyperedges (group relationships)
- **Audio page live endpoints** — web_audio_status, web_audio_beats, web_audio_audio_wav, web_audio_time, web_audio_tap_ep [EXTRACTED 1.00]
- **Beat latency measurement methods** — docs_api_bench_endpoints, docs_bench_test_usb_latency, docs_bench_test_logic_analyzer, docs_bench_test_beat_lead [EXTRACTED 1.00]
- **Combined brightness factors** — docs_api_combined_brightness, docs_api_settings, docs_api_groups, docs_api_devices, docs_api_zones [EXTRACTED 1.00]
- **Color picker feature set** — docs_mockups_images_color_picker_demo_hsb_color_model, docs_mockups_images_color_picker_demo_hex_rgb_input, docs_mockups_images_color_picker_demo_keyboard_accessibility, docs_mockups_images_color_picker_demo_cross_platform_consistency [EXTRACTED 1.00]
- **Edit-mode-only management features** — docs_help_edit_mode, docs_help_zones_modal, docs_help_send_presets, docs_help_patterns_dialog, docs_help_colour_palette, docs_help_presets_list [EXTRACTED 1.00]
- **Preset editor actions (Try, Default, Save & Send, Remove from zone)** — docs_help_try_action, docs_help_default_preset, docs_help_save_and_send, docs_help_remove_from_zone [EXTRACTED 1.00]
- **Header actions aggregated in mobile Menu** — docs_images_help_mobile_menu_run_mode, docs_images_help_mobile_menu_profiles, docs_images_help_mobile_menu_tabs, docs_images_help_mobile_menu_presets, docs_images_help_mobile_menu_help [EXTRACTED 1.00]
- **Device/Group Modal Flow** — docs_mockups_device_management_showadddevicemodal, docs_mockups_device_management_showaddgroupmodal, docs_mockups_device_management_closemodal, docs_mockups_device_management_savedevice [EXTRACTED 1.00]
- **LED Driver UI Mockup Set** — docs_mockups_images_index_dashboard_mockup, docs_mockups_images_index_pattern_selector_mockup, docs_mockups_images_index_device_management_mockup, docs_mockups_images_index_settings_mockup, docs_mockups_images_index_presets_mockup [EXTRACTED 1.00]
- **Selectable LED Patterns** — docs_mockups_images_pattern_selector_on, docs_mockups_images_pattern_selector_off, docs_mockups_images_pattern_selector_blink, docs_mockups_images_pattern_selector_chase, docs_mockups_images_pattern_selector_circle, docs_mockups_images_pattern_selector_pulse, docs_mockups_images_pattern_selector_rainbow, docs_mockups_images_pattern_selector_transition [EXTRACTED 1.00]
- **Preset/pattern configuration schema (pattern, colors, delay, step increment, N1-N8)** — docs_mockups_presets_led_patterns, docs_mockups_presets_delay, docs_mockups_presets_step_increment, docs_mockups_presets_n_parameters, docs_mockups_presets_step_offset [EXTRACTED 1.00]
- **Device settings sections** — docs_mockups_settings_basic_settings, docs_mockups_settings_pattern_settings, docs_mockups_settings_advanced_settings, docs_mockups_settings_network_settings [EXTRACTED 1.00]
- **LED Driver UI Mockup Suite** — docs_mockups_index, docs_mockups_dashboard, docs_mockups_pattern_selector, docs_mockups_device_management, docs_mockups_readme_settings_mockup, docs_mockups_color_picker_readme_presets_mockup [EXTRACTED 1.00]
- **Pi-to-ESP32 Command Paths** — docs_specification_serial_espnow_bridge, docs_specification_wifi_driver_tcp, docs_specification_espnow, docs_specification_pi_controller [EXTRACTED 1.00]
- **led_strip backend choice (RMT vs SPI, DMA)** — scripts_led_test_managed_components_espressif__led_strip_readme_rmt_backend, scripts_led_test_managed_components_espressif__led_strip_readme_spi_backend, scripts_led_test_managed_components_espressif__led_strip_readme_dma_support, scripts_led_test_managed_components_espressif__led_strip_readme_backend_selection_flowchart [EXTRACTED 1.00]
- **led_strip pixel write and flush flow** — scripts_led_test_managed_components_espressif__led_strip_api_led_strip_set_pixel, scripts_led_test_managed_components_espressif__led_strip_api_led_strip_set_pixel_hsv, scripts_led_test_managed_components_espressif__led_strip_api_led_strip_set_pixel_rgbw, scripts_led_test_managed_components_espressif__led_strip_api_led_strip_refresh, scripts_led_test_managed_components_espressif__led_strip_api_led_strip_clear [EXTRACTED 1.00]
- **Dynamic pattern contract** — led_driver_docs_pattern_contract_class_shape, led_driver_docs_pattern_contract_run_generator_rules, led_driver_docs_pattern_contract_drawing_brightness, led_driver_docs_pattern_contract_step_semantics, led_driver_docs_pattern_contract_error_handling [EXTRACTED 1.00]
- **Pi Animation Engine Output Pipeline** — docs_specification_pixel_generator, docs_specification_output_drivers, docs_specification_output_record, docs_specification_zone_playback, docs_specification_sequencer [EXTRACTED 1.00]
- **Beat-Driven Scene Activation** — docs_specification_beat_detection_device, docs_specification_bpm_sync, docs_specification_beat_counter_phases, docs_specification_scene_queue [INFERRED 0.85]
- **Fields defining an LED preset (name, pattern, colours, parameters)** — docs_images_help_preset_editor_preset_name_field, docs_images_help_preset_editor_pattern_selector, docs_images_help_preset_editor_palette_linked_colour, docs_images_help_preset_editor_preset_parameters [INFERRED 0.85]
- **Pattern settings composed and applied to devices** — docs_mockups_images_dashboard_pattern_selection, docs_mockups_images_dashboard_brightness_speed, docs_mockups_images_dashboard_colors, docs_mockups_images_dashboard_apply_settings [INFERRED 0.85]
- **Preset lifecycle actions (create, apply, sync)** — docs_mockups_images_presets_create_preset, docs_mockups_images_presets_apply_preset, docs_mockups_images_presets_sync_presets_to_all_devices [INFERRED 0.85]
- **ESP-NOW driver delivery layers** — docs_api_binary_envelope, docs_api_delivery_digest, docs_bench_test_reliable_link, docs_bench_test_beat_double_send [INFERRED 0.85]
- **v1 message handling on driver** — led_driver_docs_api_v1_message, led_driver_docs_patterns_process_data_flow, led_driver_docs_patterns_pattern_registry, led_driver_docs_patterns_preset_short_keys, led_driver_docs_api_select_message [INFERRED 0.85]
## Communities (214 total, 66 thin omitted)
### Community 0 - "IdfDevice"
Cohesion: 0.10
Nodes (7): _hex_rgb(), _idf_post(), _idf_show(), _preset_content(), run_idf(), IdfDevice, probe()
### Community 1 - "htmx Library"
Cohesion: 0.08
Nodes (101): a(), Ae(), an(), at(), B(), be(), bn(), bt() (+93 more)
### Community 3 - "Browser Tests & Mockup Images"
Cohesion: 0.06
Nodes (17): generate_image(), generate_with_html2image(), generate_with_playwright(), generate_with_selenium(), main(), browser(), _browser_sleep(), BrowserTest (+9 more)
### Community 4 - "Audio UI (JS)"
Cohesion: 0.11
Nodes (58): applyAudioStatus(), applyServerAudioUiFields(), audioRunPreferredDeviceId(), beatSyncButtonTitle(), bind(), clampLiveBpm(), clampSimulatedBpm(), clearBeatPhaseTimers() (+50 more)
### Community 5 - "cJSON"
Cohesion: 0.05
Nodes (90): add_item_to_array(), buffer_skip_whitespace(), case_insensitive_strcmp(), cast_away_const(), cJSON, cJSON_AddItemReferenceToArray(), cJSON_AddItemToObjectCS(), cJSON_AddRawToObject() (+82 more)
### Community 6 - "beat.c"
Cohesion: 0.07
Nodes (25): beat_reset(), beat_set_callback(), beat_start(), beat_tap(), beat_dsp_bpm(), dsp_event(), led_off_cb(), led_set() (+17 more)
### Community 7 - "led-tool Device CLI"
Cohesion: 0.06
Nodes (17): download_presets(), download_settings(), _get_ordered_actions(), main(), print_settings(), resolve_flash_binary(), upload_presets(), upload_settings() (+9 more)
### Community 8 - "ab"
Cohesion: 0.11
Nodes (86): chase_draw(), ease_t(), first_call(), fx_aurora(), fx_bar_graph(), fx_blink(), fx_blizzard(), fx_candle_glow() (+78 more)
### Community 9 - "Compiler"
Cohesion: 0.07
Nodes (5): Template, Loader, Loader, Compiler, Loader
### Community 10 - "Spec: Pi Animation Engine"
Cohesion: 0.07
Nodes (46): Pi Animation Engine (src/engine), docs/API.md, Beat Counter and Phases, Beat Detection Device, Binary Message Protocol, BPM Sync, Dashboard UI (dashboard.html), usqlite Database Schema (presets, profiles, scenes, scene_groups) (+38 more)
### Community 11 - "Asm"
Cohesion: 0.18
Nodes (11): Asm, buf, cnt, flags, last_us, lens, mac, mask (+3 more)
### Community 12 - "Presets UI (JS)"
Cohesion: 0.09
Nodes (42): arrayToGrid(), coerceManualBeatN(), coercePresetAuto(), coercePresetBackground(), coercePresetInt(), createPresetButton(), deviceNamesForPresetOnCurrentZone(), editPresetFromTab() (+34 more)
### Community 13 - "Zones UI (JS)"
Cohesion: 0.10
Nodes (42): applyBrightnessSliders(), applyZoneContentKindEditModal(), clamp255(), computeZoneNamesTargets(), computeZonePresetUnionTargets(), computeZoneTargets(), createZone(), effectiveGroupIdsForZonePreset() (+34 more)
### Community 14 - "patterns.c"
Cohesion: 0.25
Nodes (18): add_name(), all_patterns(), base_name(), builtin(), create_driver_pattern(), exists(), file_names(), file_path() (+10 more)
### Community 15 - "new_id"
Cohesion: 0.08
Nodes (13): new_id(), test_preset_round_trip(), test_profile_round_trip(), test_sequence_round_trip(), test_play_needs_steps(), test_play_needs_zone(), test_scoped_to_profile(), test_clone() (+5 more)
### Community 16 - "Sequences UI (JS)"
Cohesion: 0.08
Nodes (55): addSeqTarget(), addSequenceToTab(), addTargetsPerDriver(), appendZoneSequenceTiles(), applySequenceEditorMode(), applySequenceKindUi(), applySequenceSwitchWaitFromServer(), buildLaneGroupIdsForEditor() (+47 more)
### Community 17 - "SerialTransport"
Cohesion: 0.13
Nodes (4): SerialIntercept, SerialTransport, TransportError, TransportExecError
### Community 18 - "main/main.c"
Cohesion: 0.06
Nodes (22): heap_caps_malloc(), cJSON_Hooks, cJSON_InitHooks(), be16(), be32(), ddp_set_enabled(), ddp_sync_task(), ddp_task() (+14 more)
### Community 19 - "led_strip Component Docs"
Cohesion: 0.10
Nodes (36): led_test ESP-IDF project, led_test main component (main.c), led_strip API Reference, led_model_t (WS2812/SK6812), led_pixel_format_t (GRB/GRBW), led_strip_clear(), led_strip_config_t, led_strip_del() (+28 more)
### Community 20 - "Art-Net Output"
Cohesion: 0.09
Nodes (10): ArtNet, as_channels(), build_artdmx(), _ip_bytes(), _pad(), port_lo(), ticks_diff(), ticks_ms() (+2 more)
### Community 21 - "freertos.c"
Cohesion: 0.05
Nodes (70): app_main(), ctl_open(), load_channel(), mic_start(), udp_open(), httpd_os_thread_create(), httpd_os_thread_delete(), httpd_os_thread_handle() (+62 more)
### Community 22 - "httpd_txrx.c"
Cohesion: 0.12
Nodes (32): httpd_err_code_t, httpd_err_handler_func_t, httpd_recv_opt_t, httpd_parse_req(), read_block(), httpd_default_recv(), httpd_default_send(), httpd_recv() (+24 more)
### Community 23 - "cJSON_IsString"
Cohesion: 0.10
Nodes (71): cJSON_GetArrayItem(), cJSON_GetArraySize(), cJSON_IsArray(), cJSON_IsString(), cJSON_PrintUnformatted(), apply_default(), apply_select(), apply_v1() (+63 more)
### Community 24 - "cJSON_Delete"
Cohesion: 0.15
Nodes (43): esp_err_to_name(), add_uri(), api_fn_t, api_http_entry(), api_req_t, api_route_t, app_js_get(), brightness_post() (+35 more)
### Community 26 - "ctrl_msg.cpp"
Cohesion: 0.17
Nodes (15): cstr(), ctrl_build_announce(), ctrl_handle(), ctrl_init(), expand_v1(), handle_env(), in_group(), KeyName (+7 more)
### Community 27 - "seqplay.c"
Cohesion: 0.10
Nodes (53): beat_get_info(), engine_zone_current(), add_id(), advance_time(), anchor_bar(), audio_drives(), beat_task(), bit() (+45 more)
### Community 28 - "Devices UI (JS)"
Cohesion: 0.10
Nodes (32): applyEspnowPingAggregateToDots(), applyEspnowPingToDeviceRows(), applyTcpSnapshot(), applyTransportVisibility(), collectDeviceEditPayload(), createDeviceFromModal(), createDeviceIdentifyButton(), DEVICE_DOT_CLASSES (+24 more)
### Community 29 - "binary_envelope.py"
Cohesion: 0.15
Nodes (18): brightness_0_255_from_wire(), brightness_wire_from_0_255(), _clamp_i16(), _colors_to_rgb_list(), _decode_default_blob(), _decode_preset_record(), _decode_presets_blob(), _decode_select_blob() (+10 more)
### Community 30 - "Colour Picker Mockups"
Cohesion: 0.11
Nodes (25): Chromium-style Color Picker Demo, ColorPickerChromium Component, updateColors() (Chromium demo), Custom Color Picker Demo, updateColors() (standard demo), Custom Colour Picker README, POST /api/colors (example), ColorPicker Component (+17 more)
### Community 32 - "httpd_sess.c"
Cohesion: 0.18
Nodes (22): httpd_session_enum_function, httpd_accept_conn(), httpd_process_ctrl_msg(), httpd_process_session(), httpd_server(), enum_function(), fd_is_valid(), httpd_is_sess_available() (+14 more)
### Community 33 - "httpd_parse.c"
Cohesion: 0.14
Nodes (26): httpd_config_t, cb_header_field(), cb_header_value(), cb_headers_complete(), cb_no_body(), cb_on_body(), cb_url(), httpd_cookie_key_value() (+18 more)
### Community 34 - "test_sequences.py"
Cohesion: 0.19
Nodes (19): clock(), make(), presets(), test_animation_over_sequence_keeps_time(), test_animation_plays_once_alone(), test_animation_step_fires_overlay(), test_beat_and_time_lanes_together(), test_chase_moves_and_bounces() (+11 more)
### Community 35 - "esp_http_server.h"
Cohesion: 0.07
Nodes (25): esp_http_server_event_data, http_method, httpd_close_func_t, httpd_method_t, httpd_open_func_t, httpd_resp_send_404(), httpd_resp_send_408(), httpd_resp_sendstr_chunk() (+17 more)
### Community 36 - "API Docs: Outputs & Audio"
Cohesion: 0.14
Nodes (23): Art-Net output (UDP 6454), Audio API /api/audio and /audio page routes, Profile/preset/sequence JSON bundles (import/export), Combined brightness (global x groups x device x zone), /db collection export and replace, Devices resource /devices, Driver group membership lists (group ids, z<zone id>), Device groups resource /groups (+15 more)
### Community 37 - "esp_timer_get_time"
Cohesion: 0.05
Nodes (52): esp_event_loop_create_default(), esp_rom_delay_us(), audio_api_resume_mic(), bench_on_echo(), bridge_active(), engine_init(), skip_unresponsive(), ap_event() (+44 more)
### Community 38 - "socket"
Cohesion: 0.20
Nodes (6): discover(), _expand(), _ip(), local_subnet(), ota_drivers(), parse_targets()
### Community 39 - "Beat Detection DSP (C)"
Cohesion: 0.27
Nodes (16): beat_feed(), analyse_beat(), bar_cue(), bar_decide(), beat_dsp_feed(), beat_dsp_init(), beat_dsp_tap(), best_phase() (+8 more)
### Community 40 - "cJSON_IsNumber"
Cohesion: 0.18
Nodes (25): cJSON_GetNumberValue(), cJSON_IsNumber(), num(), api_identify_group(), clamp255(), create_device(), device_driver_config(), device_status() (+17 more)
### Community 41 - "bridge_serial.c"
Cohesion: 0.18
Nodes (15): bridge_crc16_update(), bridge_decode_feed(), bridge_encode(), bridge_ports_json(), bridge_serial_has_mic(), bridge_serial_mic(), bridge_serial_ports_json(), bridge_serial_send() (+7 more)
### Community 42 - "run_all"
Cohesion: 0.13
Nodes (12): dim(), expected(), frame(), frame_sum(), mismatch_detail(), packet(), read_serial(), run_all() (+4 more)
### Community 43 - "outputs.c"
Cohesion: 0.41
Nodes (11): fail(), fill(), one_of(), put16(), resolve(), run_test(), send_artnet(), send_ddp() (+3 more)
### Community 44 - "httpd_req"
Cohesion: 0.20
Nodes (10): httpd_req, aux, content_len, free_ctx, handle, ignore_sess_ctx_changes, method, sess_ctx (+2 more)
### Community 45 - "http_parser.h"
Cohesion: 0.09
Nodes (20): http_cb, http_data_cb, http_errno, HTTP_ERRNO_MAP, http_method, http_parser_settings, on_body, on_chunk_complete (+12 more)
### Community 46 - "BridgeSim"
Cohesion: 0.06
Nodes (10): BridgeSim, api_seed_layout(), index(), driver_mac(), mac_str(), _read_json(), Strip, _hex() (+2 more)
### Community 47 - "USB Latency Tools"
Cohesion: 0.12
Nodes (13): discover(), local_subnet(), main(), analyze(), edges(), main(), pct(), read() (+5 more)
### Community 50 - "WS2812"
Cohesion: 0.09
Nodes (10): new_ws2812_encoder(), rmt_ws2812_encoder_t, WS2812, channel_, encoder_, num_leds_, order_, pixels_ (+2 more)
### Community 52 - "Transport"
Cohesion: 0.12
Nodes (3): _convert_filesystem_error(), stdout_write_bytes(), Transport
### Community 53 - "mpremote Transport"
Cohesion: 0.12
Nodes (20): Presets Mockup Page, addColorPicker() / initializeColorPickers(), ColorPicker component (color-picker.js / color-picker.css), Preset Delay (animation speed, 10-1000 ms), ESPNow preset distribution, filterPresets() / sortPresets() search, filter and sort, LED Patterns (on, off, blink, chase, circle, pulse, rainbow, transition), Pattern Parameters N1-N8 (+12 more)
### Community 54 - "httpd_main.c"
Cohesion: 0.08
Nodes (15): httpd_req, thread_data, handle, status, httpd_create(), httpd_delete(), httpd_get_client_list(), httpd_get_global_transport_ctx() (+7 more)
### Community 55 - "cJSON_CreateString"
Cohesion: 0.12
Nodes (58): list_pulse_sources(), cJSON_CreateString(), cJSON_Duplicate(), cJSON_GetObjectItem(), cJSON_IsObject(), cJSON_Parse(), cJSON_ParseWithLength(), cJSON_ParseWithOpts() (+50 more)
### Community 57 - "httpd_config"
Cohesion: 0.06
Nodes (30): httpd_config, backlog_conn, close_fn, core_id, ctrl_port, enable_so_linger, global_transport_ctx, global_transport_ctx_free_fn (+22 more)
### Community 59 - "mic_alsa.c"
Cohesion: 0.09
Nodes (20): capture_loop(), capture_thread(), list_alsa_devices(), mic_close(), mic_error(), mic_get_level(), mic_is_open(), mic_list_devices() (+12 more)
### Community 60 - "create_app"
Cohesion: 0.12
Nodes (6): create_app(), serial_ports(), ws_handler(), list_serial_ports(), main(), output_tick()
### Community 61 - "API Test Fixtures & Audio"
Cohesion: 0.17
Nodes (5): base_url(), c(), Client, profile(), restore_db()
### Community 63 - "Help: Zones & Palette"
Cohesion: 0.13
Nodes (18): Colour Palette (per profile), Zone default preset (default hint), DJ zone starter option, From Palette linked colours, LED driver JSON (presets, select, save, default, manifest), Patterns dialog, POST /presets/send, Preset editor (Try, Save, Send, Manual) (+10 more)
### Community 64 - "ddp_test.py"
Cohesion: 0.08
Nodes (23): hsv(), rig_mid(), rig_rows(), rig_xy(), soak_rig_bounce(), soak_rig_checker(), soak_rig_columns(), soak_rig_converge() (+15 more)
### Community 65 - "pytest"
Cohesion: 0.16
Nodes (3): test_events_stream(), need_sim(), rig()
### Community 66 - "http_parser.c"
Cohesion: 0.15
Nodes (10): parse_init(), http_message_needs_eof(), http_parse_host(), http_parse_host_char(), http_parser_execute(), http_parser_init(), http_parser_parse_url(), http_parser_settings_init() (+2 more)
### Community 67 - "sys"
Cohesion: 0.11
Nodes (5): mpremote_base(), main(), boot(), info(), upload()
### Community 68 - "sock_db"
Cohesion: 0.09
Nodes (33): httpd_free_ctx_fn_t, httpd_handle_t, httpd_pending_func_t, httpd_recv_func_t, httpd_send_func_t, sock_db, ctx, fd (+25 more)
### Community 70 - "Index Page Modals"
Cohesion: 0.11
Nodes (19): Audio Beat Detection modal, Header BPM / beat sync indicator, Colour Palette modal, Devices modal, Edit device modal, Edit Zone modal, Device groups modal, Header global brightness slider (+11 more)
### Community 71 - "string"
Cohesion: 0.08
Nodes (18): bridge_eth_ip(), on_eth_down(), on_got_ip(), build_info(), drop_unicast_peers(), ensure_peer(), handle_frame(), host_rx_task() (+10 more)
### Community 72 - "httpd_data"
Cohesion: 0.11
Nodes (17): esp_http_server_event_id_t, httpd_data, config, ctrl_fd, ctrl_sock_semaphore, err_handler_fns, hd_calls, hd_req (+9 more)
### Community 74 - "presets.cpp"
Cohesion: 0.19
Nodes (23): clear_all_presets(), build_defaults(), entry_key(), find(), load_entry(), load_legacy(), presets_add_defaults(), presets_apply_startup() (+15 more)
### Community 75 - "Bench test: S3 controller and one LED driver"
Cohesion: 0.23
Nodes (9): Bench endpoints /test/loss and /test/beats, 30 ms beat lead (CONFIG_BEAT_LEAD_MS), Bench test: S3 controller and one LED driver, ESP32-C3 vs S3 driver comparison, Logic analyzer latency (marker GPIO, tools/analyze_edges.py), Lossy-link test (simulated loss, retries, resync), Reliable link (rel: acked unicast, retransmits, ack timeouts), Bench troubleshooting (serial ports, channel mismatch, blank UI) (+1 more)
### Community 76 - "Controller Overview & OTA Docs"
Cohesion: 0.17
Nodes (16): led_controller ESP-IDF project, POST /patterns/upload (led-driver parity), Driver app update /drivers/ota (staged files, sha, commit/abort), Firmware OTA /ota (idle slot, rollback), Patterns resource /patterns, Driver app update over ESP-NOW test (tools/driver_ota.py), led-simulator, led-tool / led-cli serial device CLI (+8 more)
### Community 77 - "espnow_link.cpp"
Cohesion: 0.05
Nodes (29): esp_random(), beat_on_frame(), beat_period_ms(), asm_find(), asm_free(), Done, done_add(), done_has() (+21 more)
### Community 78 - "httpd_register_uri_handler"
Cohesion: 0.19
Nodes (16): httpd_uri_t, httpd_find_uri_handler(), httpd_register_uri_handler(), httpd_uri_match_simple(), audio_api_register(), audio_register(), start_webserver(), ota_register() (+8 more)
### Community 79 - "Audio Monitor Page"
Cohesion: 0.16
Nodes (16): /audio.wav live PCM stream, bar() bar-position renderer, /beats SSE event stream, draw() timeline canvas, Listen button (WAV stream playback via AudioContext), median(), Audio and beats page (/audio), stats() tap vs computer agreement (+8 more)
### Community 80 - "artnet_dmx.py"
Cohesion: 0.24
Nodes (9): parse(), _assert_eq(), main(), test_artnet_send_loopback(), test_build_artdmx(), test_fixture_patch(), test_pattern_blink_and_select(), test_pattern_upload() (+1 more)
### Community 82 - "events"
Cohesion: 0.09
Nodes (21): cached, exitCode, stdout, variable, CMAKE_C_FLAGS, CMAKE_C_FLAGS_DEBUG, CMAKE_CXX_FLAGS, CMAKE_CXX_FLAGS_DEBUG (+13 more)
### Community 83 - "httpd_resp_set_type"
Cohesion: 0.11
Nodes (29): esp_app_get_description(), esp_restart(), httpd_resp_sendstr(), httpd_req_recv(), httpd_resp_set_type(), fail(), ota_confirm_later(), ota_get_handler() (+21 more)
### Community 84 - "unique"
Cohesion: 0.08
Nodes (14): find_id_by_field(), missing(), unique(), test_scenes(), device(), group(), test_crud(), test_group_identify_needs_devices() (+6 more)
### Community 85 - "ESP-NOW Sender Bridge"
Cohesion: 0.20
Nodes (10): ap(), _broadcast_ws(), _espnow_receive_loop(), _init_espnow(), main(), _send_espnow(), _validate_envelope(), ws() (+2 more)
### Community 86 - "net.cpp"
Cohesion: 0.10
Nodes (30): apply_device_config(), ddp_start(), app_main(), ap_switch_later(), ap_timer_cb(), apply_ap(), apply_client_ip(), apply_sta_config() (+22 more)
### Community 89 - "api_call_t"
Cohesion: 0.33
Nodes (5): api_call_t, cap, done, msg, out
### Community 90 - "Sender"
Cohesion: 0.09
Nodes (10): get(), output_scale(), run_interactive(), handle(), show_menu(), run_soak(), sample(), send_sync() (+2 more)
### Community 92 - "http_parser"
Cohesion: 0.12
Nodes (18): continue_parsing(), parse_block(), http_parser, content_length, data, flags, header_state, http_errno (+10 more)
### Community 93 - "events"
Cohesion: 0.10
Nodes (24): cached, exitCode, stdout, variable, CMAKE_C_FLAGS, CMAKE_C_FLAGS_DEBUG, CMAKE_CXX_FLAGS, CMAKE_CXX_FLAGS_DEBUG (+16 more)
### Community 94 - "groups_route"
Cohesion: 0.29
Nodes (14): api_effective_brightness(), add_error(), api_driver_config(), api_mac(), brightness(), driver_config(), find(), groups_route() (+6 more)
### Community 95 - "Microdot Auth (dmx)"
Cohesion: 0.21
Nodes (6): wraps(), print_exception(), websocket_upgrade(), websocket_wrapper(), wrapper(), with_websocket()
### Community 96 - "cJSON_CreateObject"
Cohesion: 0.10
Nodes (65): add_item_to_object(), cJSON_AddArrayToObject(), cJSON_AddBoolToObject(), cJSON_AddFalseToObject(), cJSON_AddItemToArray(), cJSON_AddItemToObject(), cJSON_AddNullToObject(), cJSON_AddNumberToObject() (+57 more)
### Community 97 - "v1 driver messages (long/short keys)"
Cohesion: 0.25
Nodes (9): Controller WebSocket /ws (v1 presets/select), DMX Driver Art-Net and serial gateway, DMX fixture (output, start channel, role map; parcan/mover profiles), led-driver-style pattern engine (Preset object), Serial DMX512 output (250000 8N2), Binary envelope (main/envelope.c, test/binary_envelope.py), v1 driver messages (long/short keys), WebSocket /ws driver message relay (+1 more)
### Community 98 - "DMX Preset Model"
Cohesion: 0.13
Nodes (8): _expand(), _preset_from_map(), process_data(), _select_entries(), _targets_for_key(), play(), _parse_colour(), Preset
### Community 99 - "status_get"
Cohesion: 0.17
Nodes (8): bridge_eth_start(), esp_event_post(), esp_read_mac(), esp_http_server_dispatch_event(), net_ap_on(), patterns_count(), patterns_name(), status_get()
### Community 100 - "xSemaphoreGive"
Cohesion: 0.05
Nodes (73): ctl_task(), mic_task(), rx_task(), udp_send_up(), udp_task(), usb_send_frame(), httpd_os_thread_sleep(), vTaskDelay() (+65 more)
### Community 101 - "Groups UI (JS)"
Cohesion: 0.29
Nodes (9): fetchDevicesMapForGroups(), fetchGroupsMap(), identifyGroupById(), loadGroupsModal(), loadWifiFieldsFromGroup(), openEditGroupModal(), renderGroupDevicesEditor(), renderGroupsList() (+1 more)
### Community 102 - "httpd_req_aux"
Cohesion: 0.11
Nodes (18): httpd_req_aux, content_type, first_chunk_sent, max_req_hdr_len, max_uri_len, remaining_len, req_hdrs_count, resp_hdrs (+10 more)
### Community 103 - "Help: Mobile Menu Image"
Cohesion: 0.24
Nodes (10): Mobile Menu Help Illustration (narrow screen), Content Area (preset buttons), Menu Dropdown (Run mode, Profiles, Tabs, Presets, Help), Header Tab Buttons, Help, Menu Button (header dropdown trigger), Presets, Profiles (+2 more)
### Community 104 - "Pattern Selector Mockup Image"
Cohesion: 0.20
Nodes (11): Pattern Selector Mockup (Select LED Pattern), Apply Pattern / Cancel Actions, Blink Pattern, Chase Pattern, Circle Pattern, Off Pattern, On Pattern (solid color), Pattern Card Grid Layout (+3 more)
### Community 105 - "Driver Pattern Docs"
Cohesion: 0.24
Nodes (11): Message processing order (version, presets upsert, colour, selection), Auto vs manual (a) and manual chase flush, Built-in off / on patterns, Patterns and presets on the LED driver, MAX_PRESETS = 32, Pattern OTA via manifest / POST /patterns/upload, Pattern registry (Presets.reload_patterns), Preset short keys (p, c, d, b, a, bg, n1-n6) (+3 more)
### Community 106 - "USB ESP-NOW bridge"
Cohesion: 0.25
Nodes (7): Build and flash, Channel, Ethernet (W5500), Microphone (S3), Protocol, Running the controller against it, USB ESP-NOW bridge
### Community 107 - "main"
Cohesion: 0.18
Nodes (8): find_devices(), probe(), sweep(), load_rig(), local_prefix(), main(), neighbours(), set_fps()
### Community 108 - "bridge_sim.py"
Cohesion: 0.05
Nodes (26): lan_ip(), load_config(), main(), _merge(), sync_patterns(), normalise_layout(), _reversed_for_column(), side_name() (+18 more)
### Community 109 - "Driver Message API Docs"
Cohesion: 0.38
Nodes (10): Auto vs manual mode, Beat (re-select same preset restarts generator), Hex colour conversion and colour-order reordering, LED Driver API (message format), Pattern-specific parameters (rainbow, pulse, transition, chase, circle), Preset fields (pattern, colors, delay, brightness, auto, n1-n6), Select message (device -> [preset, step]), Step synchronization (+2 more)
### Community 111 - "led_strip Manifest"
Cohesion: 0.20
Nodes (9): dependencies, idf, description, repository, repository_info, commit_sha, path, url (+1 more)
### Community 112 - "led_strip_handle_t"
Cohesion: 0.33
Nodes (12): app_main(), app_main(), configure_led(), app_main(), configure_led(), led_strip_handle_t, led_strip_clear(), led_strip_del() (+4 more)
### Community 113 - "Outputs UI (JS)"
Cohesion: 0.33
Nodes (8): fetchOutputs(), loadOutputsModal(), openOutputEditor(), OUTPUT_PROTOCOL_LABELS, outputSummary(), renderOutputsList(), setOutputField(), syncOutputProtocolFields()
### Community 114 - "dependencies"
Cohesion: 0.50
Nodes (3): dependencies, espressif/w5500, version
### Community 115 - "Help PDF: Overview"
Cohesion: 0.25
Nodes (9): API.md, LED controller user guide, Main web UI (Raspberry Pi app), Pattern OTA install over HTTP (/patterns/ota, upload, driver, send), Pattern parameters n1-n8, README, Serial to ESP-NOW bridge transport, WebSocket /ws (+1 more)
### Community 116 - "Mockups Index Image"
Cohesion: 0.31
Nodes (9): LED Driver UI Mockups Index (screenshot), Dashboard Mockup, Device Groups, Device Management Mockup, LED Patterns (On, Off, Blink, Chase, Circle, Pulse, Rainbow, Transition), N1-N8 Pattern Parameters, Pattern Selector Mockup, Presets Mockup (+1 more)
### Community 118 - "Help: Header Toolbar Image"
Cohesion: 0.29
Nodes (8): Header Toolbar Help Image, Edit Mode Action Bar, Run/Edit Mode Toggle Button, Patterns Action, Presets Action, Profiles Action, Header Tab Buttons, Tabs Action
### Community 119 - "Help: Preset Editor Image"
Cohesion: 0.29
Nodes (5): Default Action, Preset Pattern Selector, Preset Editor Modal (help illustration), Preset Name Field, Brightness, Delay and n1-n8 Parameters (0-255)
### Community 120 - "Dashboard Mockup Image"
Cohesion: 0.32
Nodes (8): LED Driver Control Panel Dashboard Mockup, Apply Settings Action, Brightness & Speed Card (Brightness % and Delay ms sliders), Colors Card (color swatches palette, Add Color), Connected Devices Card (devices with group and online status), Device Groups, Pattern Selection Card (On, Off, Blink, Chase, Circle, Pulse, Rainbow, Transition), Save to Device Action
### Community 121 - "Device Management Mockup Image"
Cohesion: 0.32
Nodes (8): + Add Device Button, Connected Devices List, Device Group, Device & Group Management Screen (mockup), Device Row Actions (edit, settings, stop), Online/Offline Status Badge, Devices / Groups Tab Switcher, LED Device (MAC, group, pattern)
### Community 122 - "Presets Mockup Image"
Cohesion: 0.32
Nodes (8): Preset Management UI Mockup, Apply Preset Action, Create Preset Action, LED Pattern Types (Rainbow, Pulse, Chase, Circle, Blink, Transition), Preset Card (name, pattern badge, color swatches, delay, n1, apply/edit/delete), Preset Search/Filter/Sort Toolbar (pattern filter, sort by name, grid/list toggle), Preset Parameters (colors, delay ms, n1), Sync Presets to All Devices
### Community 123 - "Pattern Contract"
Cohesion: 0.29
Nodes (6): Pattern Contract, Drawing via driver.n and apply_brightness, Pattern error handling (Presets.tick catches), Presets._load_dynamic_patterns(), Shared driver.step semantics, Global vs per-preset brightness
### Community 124 - "esp_httpd_priv.h"
Cohesion: 0.21
Nodes (19): desktop_base64_encode(), desktop_sha1(), rol(), sha1_block(), httpd_ws_frame_t, httpd_send(), httpd_ws_check_req(), httpd_ws_get_frame_type() (+11 more)
### Community 125 - "led_strip_spi_dev.c"
Cohesion: 0.26
Nodes (8): heap_caps_calloc(), led_strip_new_spi_device(), __led_strip_spi_bit(), led_strip_spi_clear(), led_strip_spi_del(), led_strip_spi_refresh(), led_strip_spi_set_pixel(), led_strip_spi_set_pixel_rgbw()
### Community 126 - "sim_demo.py"
Cohesion: 0.26
Nodes (7): Api, main(), group(), preset(), sequence(), new_id(), rig_bars()
### Community 128 - "httpd_ctrl_data"
Cohesion: 0.22
Nodes (9): httpd_work_fn_t, httpd_ctrl_data, hc_msg, hc_work, hc_work_arg, httpd_ctrl_msg, HTTPD_CTRL_MAX, HTTPD_CTRL_SHUTDOWN (+1 more)
### Community 129 - "Colour Picker Demo Image"
Cohesion: 0.33
Nodes (6): Custom Color Picker Demo (screenshot), Hex and RGB input support, HSB (Hue, Saturation, Brightness) color model, Keyboard accessible, customizable styling, Multiple Color Pickers for LED Patterns, Single Color Picker
### Community 130 - "Settings Mockup Image"
Cohesion: 0.33
Nodes (7): Advanced Settings (Step Counter, Step Increment, Device ID, Debug Mode), Basic Settings (Device Name, LED Pin, Number of LEDs), Color Order Selector (RGB/RBG/GRB/GBR/BRG/BGR), Device Settings Page Mockup, Network Settings (Access Point Name, Password, Enable AP), Pattern Parameters N1-N6, Pattern Settings (Pattern, Brightness, Delay)
### Community 131 - "store_settings"
Cohesion: 0.18
Nodes (10): cJSON_IsFalse(), setting_int(), espnow_tx_set_mic_beats(), have_static_ips(), parse_static(), settings_str(), try_static_ips(), seqplay_init() (+2 more)
### Community 132 - "Response"
Cohesion: 0.09
Nodes (7): invoke_handler(), iscoroutine(), Response, aclose(), __anext__(), urldecode_bytes(), urldecode_str()
### Community 133 - "build_app"
Cohesion: 0.24
Nodes (4): build_app(), index(), static(), web()
### Community 137 - "time"
Cohesion: 0.07
Nodes (19): Blink, Pulse, call(), main(), switch(), wifi_state(), _default_image(), _info() (+11 more)
### Community 138 - "Help: Colour Palette Image"
Cohesion: 0.40
Nodes (6): Colour Palette modal mockup (help image), Add Swatch (+) Button, Colour Palette Modal, Palette Colour Swatches, Preset Editor 'From Palette', Profile (palette owner)
### Community 140 - "LED Driver README"
Cohesion: 0.47
Nodes (6): dev.py deploy/sync script, LED Driver README (MicroPython ESP32), Optional HTTP polling (http_poll.py), Wi-Fi TCP transport to Pi (port 8765), transport_type setting (wifi / espnow), UDP discovery (port 8766)
### Community 142 - "SPI Example Manifest"
Cohesion: 0.33
Nodes (5): dependencies, espressif/led_strip, idf, override_path, version
### Community 143 - "test_rig_sim.py"
Cohesion: 0.11
Nodes (27): rig_placements(), all_dark(), col_of(), frames(), led_x(), lit(), mac(), make_preset() (+19 more)
### Community 145 - "Help PDF: Modes"
Cohesion: 0.40
Nodes (4): Edit mode, Mobile layout Menu, Run mode, Zones modal
### Community 146 - "Help: Tab Preset Strip Image"
Cohesion: 0.60
Nodes (5): Help image: Main area brightness and preset tiles, Edit Mode: drag tiles to reorder, Global Brightness Slider, Preset Tile (gradient swatch, click to select on tab devices), Tab (e.g. lounge)
### Community 149 - "httpd_req_t"
Cohesion: 0.12
Nodes (65): cJSON_AddItemReferenceToObject(), cJSON_Delete(), cJSON_DeleteItemFromObject(), cJSON_IsNull(), httpd_req_t, httpd_resp_send_500(), api_body(), api_body_opt() (+57 more)
### Community 155 - "app.js"
Cohesion: 0.16
Nodes (35): addLog(), banner(), colourAt(), connectBridge(), deliver(), drawLabel(), drawPlaced(), drawStrip() (+27 more)
### Community 156 - "RMT Example Manifest"
Cohesion: 0.40
Nodes (4): dependencies, espressif/led_strip, override_path, version
### Community 157 - "Help Tab JS"
Cohesion: 0.25
Nodes (11): addStaticIpRow(), describeBridge(), loadBridgeSettings(), loadDeviceSettings(), loadNetworkStatus(), putBridges(), renderBridges(), setApToggle() (+3 more)
### Community 158 - "Settings Page Template"
Cohesion: 0.50
Nodes (4): Settings modal (device, network), loadEspnowChannel(), Device Settings page (ESP-NOW channel), wifi_channel setting (1-11)
### Community 159 - "led-driver/web/app.js"
Cohesion: 0.10
Nodes (49): api(), applyMode(), attachDrag(), closeEditor(), closeSock(), deviceChoices(), direct(), discoverDevices() (+41 more)
### Community 165 - "test_presets.py"
Cohesion: 0.13
Nodes (4): preset(), test_create_belongs_to_current_profile(), test_create_fills_defaults(), test_presets_scoped_to_profile()
### Community 166 - "mdns_host.c"
Cohesion: 0.25
Nodes (10): add_ptr(), build_query(), decode_name(), handle_rr(), mdns_dup(), mdns_query_ptr(), mdns_query_results_free(), parse_packet() (+2 more)
### Community 167 - "SerialDMX"
Cohesion: 0.24
Nodes (3): sleep_ms(), SerialDMX, sleep()
### Community 168 - "led_strip_rmt_dev_idf4.c"
Cohesion: 0.36
Nodes (5): led_strip_rmt_clear(), led_strip_rmt_del(), led_strip_rmt_refresh(), led_strip_rmt_set_pixel(), ws2812_rmt_adapter()
### Community 169 - "led_strip_rmt_encoder.c"
Cohesion: 0.22
Nodes (5): led_strip_encoder_config_t, rmt_del_led_strip_encoder(), rmt_encode_led_strip(), rmt_led_strip_encoder_reset(), rmt_new_led_strip_encoder()
### Community 170 - "dependencies"
Cohesion: 0.16
Nodes (13): dependencies, espressif/cjson, espressif/mdns, espressif/w5500, joltwallet/littlefs, version, rules, version (+5 more)
### Community 171 - "List Search (JS)"
Cohesion: 0.83
Nodes (3): applyListSearch(), initListSearch(), rowSearchText()
### Community 177 - "esp_glue.c"
Cohesion: 0.09
Nodes (19): esp_fill_random(), esp_get_free_heap_size(), esp_get_minimum_free_heap_size(), esp_log_level_set(), esp_log_timestamp(), esp_log_write(), init_level(), ws_client_send_text() (+11 more)
### Community 178 - "flags"
Cohesion: 0.22
Nodes (9): flags, F_CHUNKED, F_CONNECTION_CLOSE, F_CONNECTION_KEEP_ALIVE, F_CONNECTION_UPGRADE, F_CONTENTLENGTH, F_SKIPBODY, F_TRAILING (+1 more)
### Community 179 - "http_parser_url_fields"
Cohesion: 0.22
Nodes (9): http_parser_url_fields, UF_FRAGMENT, UF_HOST, UF_MAX, UF_PATH, UF_PORT, UF_QUERY, UF_SCHEMA (+1 more)
### Community 184 - "led_strip_types.h"
Cohesion: 0.29
Nodes (7): led_strip_rmt_config_t, led_model_t, led_pixel_format_t, led_strip_config_t, led_strip_t, led_strip_new_rmt_device(), led_strip_new_rmt_device()
### Community 197 - "led_strip_rmt_dev.c"
Cohesion: 0.57
Nodes (5): led_strip_rmt_clear(), led_strip_rmt_del(), led_strip_rmt_refresh(), led_strip_rmt_set_pixel(), led_strip_rmt_set_pixel_rgbw()
### Community 198 - "rmt_encode_ws2812"
Cohesion: 0.33
Nodes (3): rmt_del_ws2812_encoder(), rmt_encode_ws2812(), rmt_ws2812_encoder_reset()
### Community 199 - "led-controller on a desktop"
Cohesion: 0.33
Nodes (5): Build and run, How it is built, Install as a service (.deb), led-controller on a desktop, Limits
### Community 200 - "http_parser_url"
Cohesion: 0.50
Nodes (4): http_parser_url, field_data, field_set, port
### Community 201 - "_simlink_web.py"
Cohesion: 0.05
Nodes (13): ESPNow, NeoPixel, _check_flash(), on_feed(), push_pixels(), real_sleep(), recv(), recv_nowait() (+5 more)
### Community 203 - "relay_forward"
Cohesion: 0.11
Nodes (21): cJSON_free(), api_call_work(), envelope(), relay_client(), relay_do(), relay_forward(), relay_host_ok(), relay_path_ok() (+13 more)
### Community 204 - "_simlink_proc.py"
Cohesion: 0.16
Nodes (5): connect(), on_feed(), push_pixels(), _reader(), _send_pixels()
### Community 227 - "dependencies"
Cohesion: 0.33
Nodes (5): dependencies, espressif/cjson, espressif/mdns, version, version
## Knowledge Gaps
- **289 isolated node(s):** `next`, `prev`, `child`, `type`, `valuestring` (+284 more)
These have ≤1 connection - possible missing edges or undocumented components. (Counts symbols only; 1228 node(s) total have ≤1 connection when file, concept and rationale nodes are included.)
- **66 thin communities (<3 nodes) omitted from report** — run `graphify query` to explore isolated nodes.
## Suggested Questions
_Questions this graph is uniquely positioned to answer:_
- **Why does `led-controller ESP32-S3 firmware` connect `Controller Overview & OTA Docs` to `v1 driver messages (long/short keys)`, `API Docs: Outputs & Audio`, `led-controller on a desktop`, `USB ESP-NOW bridge`, `Bench test: S3 controller and one LED driver`?**
_High betweenness centrality (0.032) - this node is a cross-community bridge._
- **Are the 177 inferred relationships involving `cJSON_GetObjectItem()` (e.g. with `list_pulse_sources()` and `apply_default()`) actually correct?**
_`cJSON_GetObjectItem()` has 177 INFERRED edges - model-reasoned connections that need verification._
- **What connects `next`, `prev`, `child` to the rest of the system?**
_289 weakly-connected nodes found - possible documentation gaps or missing edges._
- **Should `IdfDevice` be split into smaller, more focused modules?**
_Cohesion score 0.10037878787878787 - nodes in this community are weakly interconnected._
- **Why does `DeviceConnection` connect `led-tool Device CLI` to `SerialTransport`?**
_High betweenness centrality (0.026) - this node is a cross-community bridge._
- **Are the 100 inferred relationships involving `cJSON_Delete()` (e.g. with `list_pulse_sources()` and `ctrl_handle()`) actually correct?**
_`cJSON_Delete()` has 100 INFERRED edges - model-reasoned connections that need verification._
- **Should `htmx Library` be split into smaller, more focused modules?**
_Cohesion score 0.07897684839432412 - nodes in this community are weakly interconnected._
+12
View File
@@ -0,0 +1,12 @@
{
"runs": [
{
"date": "2026-11-03T12:13:15.159050+00:00",
"input_tokens": 1267015,
"output_tokens": 0,
"files": 332
}
],
"total_input_tokens": 1267015,
"total_output_tokens": 0
}
+1
View File
@@ -0,0 +1 @@
{"directed":false,"multigraph":false,"graph":{"hyperedges":[{"id":"audio_page_endpoints","label":"Audio page live endpoints","nodes":["web_audio_status","web_audio_beats","web_audio_audio_wav","web_audio_time","web_audio_tap_ep"],"relation":"participate_in","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"web/audio.html"},{"id":"beat_latency_measurement","label":"Beat latency measurement methods","nodes":["docs_api_bench_endpoints","docs_bench_test_usb_latency","docs_bench_test_logic_analyzer","docs_bench_test_beat_lead"],"relation":"participate_in","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/BENCH_TEST.md"},{"id":"brightness_combination","label":"Combined brightness factors","nodes":["docs_api_combined_brightness","docs_api_settings","docs_api_groups","docs_api_devices","docs_api_zones"],"relation":"participate_in","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/API.md"},{"id":"color_picker_feature_set","label":"Color picker feature set","nodes":["docs_mockups_images_color_picker_demo_hsb_color_model","docs_mockups_images_color_picker_demo_hex_rgb_input","docs_mockups_images_color_picker_demo_keyboard_accessibility","docs_mockups_images_color_picker_demo_cross_platform_consistency"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/mockups/images/color-picker-demo.png"},{"id":"docs_help_edit_mode_management","label":"Edit-mode-only management features","nodes":["docs_help_edit_mode","docs_help_zones_modal","docs_help_send_presets","docs_help_patterns_dialog","docs_help_colour_palette","docs_help_presets_list"],"relation":"participate_in","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/help.pdf"},{"id":"docs_help_preset_editor_actions","label":"Preset editor actions (Try, Default, Save & Send, Remove from zone)","nodes":["docs_help_try_action","docs_help_default_preset","docs_help_save_and_send","docs_help_remove_from_zone"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/help.pdf"},{"id":"docs_images_help_mobile_menu_header_actions","label":"Header actions aggregated in mobile Menu","nodes":["docs_images_help_mobile_menu_run_mode","docs_images_help_mobile_menu_profiles","docs_images_help_mobile_menu_tabs","docs_images_help_mobile_menu_presets","docs_images_help_mobile_menu_help"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/images/help/mobile-menu.svg"},{"id":"docs_mockups_device_modal_flow","label":"Device/Group Modal Flow","nodes":["docs_mockups_device_management_showadddevicemodal","docs_mockups_device_management_showaddgroupmodal","docs_mockups_device_management_closemodal","docs_mockups_device_management_savedevice"],"relation":"participate_in","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/mockups/device-management.html"},{"id":"docs_mockups_images_index_ui_mockup_set","label":"LED Driver UI Mockup Set","nodes":["docs_mockups_images_index_dashboard_mockup","docs_mockups_images_index_pattern_selector_mockup","docs_mockups_images_index_device_management_mockup","docs_mockups_images_index_settings_mockup","docs_mockups_images_index_presets_mockup"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/mockups/images/index.png"},{"id":"docs_mockups_images_pattern_selector_led_patterns","label":"Selectable LED Patterns","nodes":["docs_mockups_images_pattern_selector_on","docs_mockups_images_pattern_selector_off","docs_mockups_images_pattern_selector_blink","docs_mockups_images_pattern_selector_chase","docs_mockups_images_pattern_selector_circle","docs_mockups_images_pattern_selector_pulse","docs_mockups_images_pattern_selector_rainbow","docs_mockups_images_pattern_selector_transition"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/mockups/images/pattern-selector.png"},{"id":"docs_mockups_preset_schema","label":"Preset/pattern configuration schema (pattern, colors, delay, step increment, N1-N8)","nodes":["docs_mockups_presets_led_patterns","docs_mockups_presets_delay","docs_mockups_presets_step_increment","docs_mockups_presets_n_parameters","docs_mockups_presets_step_offset"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/mockups/presets.html"},{"id":"docs_mockups_settings_sections","label":"Device settings sections","nodes":["docs_mockups_settings_basic_settings","docs_mockups_settings_pattern_settings","docs_mockups_settings_advanced_settings","docs_mockups_settings_network_settings"],"relation":"form","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"docs/mockups/settings.html"},{"id":"docs_mockups_ui_mockup_suite","label":"LED Driver UI Mockup Suite","nodes":["docs_mockups_index","docs_mockups_dashboard","docs_mockups_pattern_selector","docs_mockups_device_management","docs_mockups_readme_settings_mockup","docs_mockups_color_picker_readme_presets_mockup"],"relation":"foLine truncated
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,83 @@
{
"1": "htmx Library",
"3": "Browser Tests & Mockup Images",
"4": "Audio UI (JS)",
"7": "led-tool Device CLI",
"10": "Spec: Pi Animation Engine",
"12": "Presets UI (JS)",
"13": "Zones UI (JS)",
"16": "Sequences UI (JS)",
"19": "led_strip Component Docs",
"20": "Art-Net Output",
"28": "Devices UI (JS)",
"30": "Colour Picker Mockups",
"36": "API Docs: Outputs & Audio",
"39": "Beat Detection DSP (C)",
"47": "USB Latency Tools",
"48": "Colour Picker JS",
"49": "Chromium Colour Picker JS",
"51": "API Tests: Devices",
"53": "mpremote Transport",
"61": "API Test Fixtures & Audio",
"62": "Microdot Request (dmx)",
"63": "Help: Zones & Palette",
"70": "Index Page Modals",
"73": "Microdot WebSocket (dmx)",
"76": "Controller Overview & OTA Docs",
"79": "Audio Monitor Page",
"85": "ESP-NOW Sender Bridge",
"87": "Microdot Async IO (dmx)",
"88": "DMX Settings",
"91": "Microdot Routing (dmx)",
"95": "Microdot Auth (dmx)",
"98": "DMX Preset Model",
"101": "Groups UI (JS)",
"103": "Help: Mobile Menu Image",
"104": "Pattern Selector Mockup Image",
"105": "Driver Pattern Docs",
"109": "Driver Message API Docs",
"111": "led_strip Manifest",
"113": "Outputs UI (JS)",
"115": "Help PDF: Overview",
"116": "Mockups Index Image",
"118": "Help: Header Toolbar Image",
"119": "Help: Preset Editor Image",
"120": "Dashboard Mockup Image",
"121": "Device Management Mockup Image",
"122": "Presets Mockup Image",
"123": "Pattern Contract",
"127": "Numpad Shortcuts (JS)",
"129": "Colour Picker Demo Image",
"130": "Settings Mockup Image",
"134": "API Tests: Settings",
"138": "Help: Colour Palette Image",
"140": "LED Driver README",
"142": "SPI Example Manifest",
"145": "Help PDF: Modes",
"146": "Help: Tab Preset Strip Image",
"156": "RMT Example Manifest",
"157": "Help Tab JS",
"158": "Settings Page Template",
"171": "List Search (JS)",
"172": "DMX Solid Pattern",
"173": "led-test Manifest",
"174": "VPN Autoconnect Script",
"175": "Zone Devices Panel",
"176": "graphify Instructions",
"180": "Device Mockup Modals",
"181": "bulk.sh Script",
"182": "deploy.sh Script",
"183": "Driver install.sh",
"185": "led-tool install.sh",
"186": "Help PDF Build Script",
"187": "Web Build Script",
"188": "Patterns UI (JS)",
"189": "DMX Patterns Init",
"190": "Mockup Tab Switch",
"191": "Spec: Pattern Selector UI",
"192": "mpremote Package",
"193": "Bundle Import/Export (JS)",
"194": "Colour Palette (JS)",
"195": "Profiles UI (JS)",
"196": "Zone Palette (JS)"
}
+904
View File
@@ -0,0 +1,904 @@
# Graph Report - led-controller (2026-11-16)
## Corpus Check
- 382 files · ~673,458 words
- Verdict: corpus is large enough that graph structure adds value.
- Unclassified: 1317 file(s) not represented in the graph (top: .obj 884, .cmake 160, .a 104)
## Summary
- 4727 nodes · 13754 edges · 219 communities (154 shown, 65 thin omitted)
- Extraction: 75% EXTRACTED · 25% INFERRED · 0% AMBIGUOUS · INFERRED: 3504 edges (avg confidence: 0.85)
- Token cost: 0 input · 0 output
## Graph Freshness
- Built from commit: `698c1463`
- Run `git rev-parse HEAD` and compare to check if the graph is stale.
- Run `graphify update .` after code changes (no API cost).
## Community Hubs (Navigation)
- IdfDevice
- htmx Library
- machine.py
- Browser Tests & Mockup Images
- Audio UI (JS)
- cJSON
- create_app
- led-tool Device CLI
- ab
- Compiler
- Spec: Pi Animation Engine
- seq_timeline.js
- Presets UI (JS)
- Zones UI (JS)
- sim_rig.c
- new_id
- Sequences UI (JS)
- SerialTransport
- esp_err.h
- led_strip Component Docs
- Art-Net Output
- freertos.c
- LedSimulatorApp
- cJSON_IsString
- cJSON_Delete
- Microdot
- ctrl_msg.cpp
- seqplay.c
- Devices UI (JS)
- binary_envelope.py
- Colour Picker Mockups
- PyboardCommand
- cJSON_CreateObject
- httpd_parse.c
- test_sequences.py
- cJSON_Delete
- API Docs: Outputs & Audio
- http_parser
- socket
- Beat Detection DSP (C)
- xSemaphoreGive
- WS2812
- run_all
- usb_cfg.cpp
- httpd_handle_t
- http_parser.h
- http_parser.c
- USB Latency Tools
- Colour Picker JS
- Chromium Colour Picker JS
- exchange
- API Tests: Devices
- sys
- mpremote Transport
- httpd_sess.c
- test_outputs.py
- httpd_config
- gallery.js
- mic_alsa.c
- nvs_sim.cpp
- API Test Fixtures & Audio
- Microdot Request (dmx)
- Help: Zones & Palette
- ddp_test.py
- ESPNow
- httpd_handle_t
- BridgeSim
- httpd_uri.c
- led_strip_rmt_encoder.c
- Index Page Modals
- rel.c
- httpd_data
- Microdot WebSocket (dmx)
- presets.cpp
- Bench test: S3 controller and one LED driver
- Controller Overview & OTA Docs
- espnow_link.cpp
- sim_split.js
- Audio Monitor Page
- artnet_dmx.py
- OutputManager
- events
- web.c
- unique
- ESP-NOW Sender Bridge
- net.cpp
- Microdot Async IO (dmx)
- DMX Settings
- api_call_t
- Sender
- Microdot Routing (dmx)
- bridge_serial.c
- events
- Type
- Microdot Auth (dmx)
- esp_timer_create
- v1 driver messages (long/short keys)
- DMX Preset Model
- httpd_txrx.c
- test_routes.py
- Groups UI (JS)
- httpd_req_aux
- Help: Mobile Menu Image
- Pattern Selector Mockup Image
- Driver Pattern Docs
- USB ESP-NOW bridge
- main
- rig_seed.py
- Driver Message API Docs
- run_soak
- led_strip Manifest
- test_patterns.py
- Outputs UI (JS)
- dependencies
- Help PDF: Overview
- Mockups Index Image
- outputs.c
- Help: Header Toolbar Image
- Help: Preset Editor Image
- Dashboard Mockup Image
- Device Management Mockup Image
- Presets Mockup Image
- Pattern Contract
- esp_httpd_priv.h
- led_strip_spi_dev.c
- esp_http_server_dispatch_event
- Numpad Shortcuts (JS)
- httpd_ctrl_data
- Colour Picker Demo Image
- Settings Mockup Image
- flags
- microdot.py
- http_parser_url_fields
- PatternPlayer
- HttpDevice
- time
- Help: Colour Palette Image
- sim_demo.py
- LED Driver README
- DMX Driver Art-Net and serial gateway
- SPI Example Manifest
- test_rig_sim.py
- settings_editor.js
- Help PDF: Modes
- Help: Tab Preset Strip Image
- api_error
- vendor.sh
- app.js
- RMT Example Manifest
- Help Tab JS
- Settings Page Template
- led-driver/web/app.js
- test_presets.py
- mdns_host.c
- SerialDMX
- NeoPixel
- build_sim_web.sh
- dependencies
- List Search (JS)
- DMX Solid Pattern
- led-test Manifest
- VPN Autoconnect Script
- graphify Instructions
- espnow_tx.c
- mac_str
- load_config
- bulk.sh Script
- deploy.sh Script
- Driver install.sh
- beat.c
- led-tool install.sh
- Help PDF Build Script
- Web Build Script
- Spec: Pattern Selector UI
- cJSON_GetObjectItem
- Transport
- httpd_req
- HTTPException
- http_parser_type
- json
- desktop_main.c
- _simlink_proc.py
- esp_http_server.h
- relay_forward
- WLAN
- MultiDict
- build.sh
- dependencies
- examples/blink.py
- driver-worker.js
- layout.js
- README.md
## God Nodes (most connected - your core abstractions)
1. `cJSON` - 257 edges
2. `cJSON_GetObjectItem()` - 195 edges
3. `httpd_req_t` - 155 edges
4. `cJSON_Delete()` - 139 edges
5. `cJSON_CreateObject()` - 128 edges
6. `cJSON_IsString()` - 108 edges
7. `cJSON_AddStringToObject()` - 95 edges
8. `store_coll()` - 81 edges
9. `xSemaphoreTake()` - 68 edges
10. `xSemaphoreGive()` - 68 edges
## Surprising Connections (you probably didn't know these)
- `Channel` --references--> `bridge_serial_set_channel()` [INFERRED]
bridge/README.md → main/bridge_serial.c
- `Preset editor modal` --semantically_similar_to--> `Preset fields (pattern, colors, delay, brightness, auto, n1-n6)` [INFERRED] [semantically similar]
web/templates/index.html → led-driver/docs/API.md
- `status_payload()` --calls--> `mic_error()` [INFERRED]
main/audio_api.c → desktop/port/src/mic_alsa.c
- `audio_handler()` --calls--> `mic_is_open()` [INFERRED]
main/audio_api.c → desktop/port/src/mic_alsa.c
- `How it is built` --references--> `http_parser` [INFERRED]
desktop/README.md → desktop/third_party/http_parser/http_parser.h
## Import Cycles
- None detected.
## Hyperedges (group relationships)
- **Audio page live endpoints** — web_audio_status, web_audio_beats, web_audio_audio_wav, web_audio_time, web_audio_tap_ep [EXTRACTED 1.00]
- **Beat latency measurement methods** — docs_api_bench_endpoints, docs_bench_test_usb_latency, docs_bench_test_logic_analyzer, docs_bench_test_beat_lead [EXTRACTED 1.00]
- **Combined brightness factors** — docs_api_combined_brightness, docs_api_settings, docs_api_groups, docs_api_devices, docs_api_zones [EXTRACTED 1.00]
- **Color picker feature set** — docs_mockups_images_color_picker_demo_hsb_color_model, docs_mockups_images_color_picker_demo_hex_rgb_input, docs_mockups_images_color_picker_demo_keyboard_accessibility, docs_mockups_images_color_picker_demo_cross_platform_consistency [EXTRACTED 1.00]
- **Edit-mode-only management features** — docs_help_edit_mode, docs_help_zones_modal, docs_help_send_presets, docs_help_patterns_dialog, docs_help_colour_palette, docs_help_presets_list [EXTRACTED 1.00]
- **Preset editor actions (Try, Default, Save & Send, Remove from zone)** — docs_help_try_action, docs_help_default_preset, docs_help_save_and_send, docs_help_remove_from_zone [EXTRACTED 1.00]
- **Header actions aggregated in mobile Menu** — docs_images_help_mobile_menu_run_mode, docs_images_help_mobile_menu_profiles, docs_images_help_mobile_menu_tabs, docs_images_help_mobile_menu_presets, docs_images_help_mobile_menu_help [EXTRACTED 1.00]
- **Device/Group Modal Flow** — docs_mockups_device_management_showadddevicemodal, docs_mockups_device_management_showaddgroupmodal, docs_mockups_device_management_closemodal, docs_mockups_device_management_savedevice [EXTRACTED 1.00]
- **LED Driver UI Mockup Set** — docs_mockups_images_index_dashboard_mockup, docs_mockups_images_index_pattern_selector_mockup, docs_mockups_images_index_device_management_mockup, docs_mockups_images_index_settings_mockup, docs_mockups_images_index_presets_mockup [EXTRACTED 1.00]
- **Selectable LED Patterns** — docs_mockups_images_pattern_selector_on, docs_mockups_images_pattern_selector_off, docs_mockups_images_pattern_selector_blink, docs_mockups_images_pattern_selector_chase, docs_mockups_images_pattern_selector_circle, docs_mockups_images_pattern_selector_pulse, docs_mockups_images_pattern_selector_rainbow, docs_mockups_images_pattern_selector_transition [EXTRACTED 1.00]
- **Preset/pattern configuration schema (pattern, colors, delay, step increment, N1-N8)** — docs_mockups_presets_led_patterns, docs_mockups_presets_delay, docs_mockups_presets_step_increment, docs_mockups_presets_n_parameters, docs_mockups_presets_step_offset [EXTRACTED 1.00]
- **Device settings sections** — docs_mockups_settings_basic_settings, docs_mockups_settings_pattern_settings, docs_mockups_settings_advanced_settings, docs_mockups_settings_network_settings [EXTRACTED 1.00]
- **LED Driver UI Mockup Suite** — docs_mockups_index, docs_mockups_dashboard, docs_mockups_pattern_selector, docs_mockups_device_management, docs_mockups_readme_settings_mockup, docs_mockups_color_picker_readme_presets_mockup [EXTRACTED 1.00]
- **Pi-to-ESP32 Command Paths** — docs_specification_serial_espnow_bridge, docs_specification_wifi_driver_tcp, docs_specification_espnow, docs_specification_pi_controller [EXTRACTED 1.00]
- **led_strip backend choice (RMT vs SPI, DMA)** — scripts_led_test_managed_components_espressif__led_strip_readme_rmt_backend, scripts_led_test_managed_components_espressif__led_strip_readme_spi_backend, scripts_led_test_managed_components_espressif__led_strip_readme_dma_support, scripts_led_test_managed_components_espressif__led_strip_readme_backend_selection_flowchart [EXTRACTED 1.00]
- **led_strip pixel write and flush flow** — scripts_led_test_managed_components_espressif__led_strip_api_led_strip_set_pixel, scripts_led_test_managed_components_espressif__led_strip_api_led_strip_set_pixel_hsv, scripts_led_test_managed_components_espressif__led_strip_api_led_strip_set_pixel_rgbw, scripts_led_test_managed_components_espressif__led_strip_api_led_strip_refresh, scripts_led_test_managed_components_espressif__led_strip_api_led_strip_clear [EXTRACTED 1.00]
- **Dynamic pattern contract** — led_driver_docs_pattern_contract_class_shape, led_driver_docs_pattern_contract_run_generator_rules, led_driver_docs_pattern_contract_drawing_brightness, led_driver_docs_pattern_contract_step_semantics, led_driver_docs_pattern_contract_error_handling [EXTRACTED 1.00]
- **Pi Animation Engine Output Pipeline** — docs_specification_pixel_generator, docs_specification_output_drivers, docs_specification_output_record, docs_specification_zone_playback, docs_specification_sequencer [EXTRACTED 1.00]
- **Beat-Driven Scene Activation** — docs_specification_beat_detection_device, docs_specification_bpm_sync, docs_specification_beat_counter_phases, docs_specification_scene_queue [INFERRED 0.85]
- **Fields defining an LED preset (name, pattern, colours, parameters)** — docs_images_help_preset_editor_preset_name_field, docs_images_help_preset_editor_pattern_selector, docs_images_help_preset_editor_palette_linked_colour, docs_images_help_preset_editor_preset_parameters [INFERRED 0.85]
- **Pattern settings composed and applied to devices** — docs_mockups_images_dashboard_pattern_selection, docs_mockups_images_dashboard_brightness_speed, docs_mockups_images_dashboard_colors, docs_mockups_images_dashboard_apply_settings [INFERRED 0.85]
- **Preset lifecycle actions (create, apply, sync)** — docs_mockups_images_presets_create_preset, docs_mockups_images_presets_apply_preset, docs_mockups_images_presets_sync_presets_to_all_devices [INFERRED 0.85]
- **ESP-NOW driver delivery layers** — docs_api_binary_envelope, docs_api_delivery_digest, docs_bench_test_reliable_link, docs_bench_test_beat_double_send [INFERRED 0.85]
- **v1 message handling on driver** — led_driver_docs_api_v1_message, led_driver_docs_patterns_process_data_flow, led_driver_docs_patterns_pattern_registry, led_driver_docs_patterns_preset_short_keys, led_driver_docs_api_select_message [INFERRED 0.85]
## Communities (219 total, 65 thin omitted)
### Community 0 - "IdfDevice"
Cohesion: 0.09
Nodes (8): _hex_rgb(), _idf_post(), _idf_show(), _preset_content(), print_settings(), run_idf(), IdfDevice, probe()
### Community 1 - "htmx Library"
Cohesion: 0.08
Nodes (101): a(), Ae(), an(), at(), B(), be(), bn(), bt() (+93 more)
### Community 2 - "machine.py"
Cohesion: 0.10
Nodes (3): DMX, Pin, WDT
### Community 3 - "Browser Tests & Mockup Images"
Cohesion: 0.06
Nodes (17): generate_image(), generate_with_html2image(), generate_with_playwright(), generate_with_selenium(), main(), browser(), _browser_sleep(), BrowserTest (+9 more)
### Community 4 - "Audio UI (JS)"
Cohesion: 0.11
Nodes (58): applyAudioStatus(), applyServerAudioUiFields(), audioRunPreferredDeviceId(), beatSyncButtonTitle(), bind(), clampLiveBpm(), clampSimulatedBpm(), clearBeatPhaseTimers() (+50 more)
### Community 5 - "cJSON"
Cohesion: 0.07
Nodes (62): buffer_skip_whitespace(), case_insensitive_strcmp(), cast_away_const(), cJSON_AddItemReferenceToArray(), cJSON_AddItemToObjectCS(), cJSON_AddRawToObject(), cJSON_bool, cJSON_Compare() (+54 more)
### Community 6 - "create_app"
Cohesion: 0.12
Nodes (6): create_app(), serial_ports(), ws_handler(), list_serial_ports(), main(), output_tick()
### Community 7 - "led-tool Device CLI"
Cohesion: 0.07
Nodes (16): download_presets(), download_settings(), _get_ordered_actions(), main(), resolve_flash_binary(), upload_presets(), upload_settings(), copy_file() (+8 more)
### Community 8 - "ab"
Cohesion: 0.11
Nodes (86): chase_draw(), ease_t(), first_call(), fx_aurora(), fx_bar_graph(), fx_blink(), fx_blizzard(), fx_candle_glow() (+78 more)
### Community 9 - "Compiler"
Cohesion: 0.07
Nodes (5): Template, Loader, Loader, Compiler, Loader
### Community 10 - "Spec: Pi Animation Engine"
Cohesion: 0.07
Nodes (46): Pi Animation Engine (src/engine), docs/API.md, Beat Counter and Phases, Beat Detection Device, Binary Message Protocol, BPM Sync, Dashboard UI (dashboard.html), usqlite Database Schema (presets, profiles, scenes, scene_groups) (+38 more)
### Community 11 - "seq_timeline.js"
Cohesion: 0.11
Nodes (59): seqTl, seqTlOnOpen(), TL_COLORS, tlAddAt(), tlAddTrack(), tlBpm(), tlBtn(), tlBuildSnap() (+51 more)
### Community 12 - "Presets UI (JS)"
Cohesion: 0.09
Nodes (42): arrayToGrid(), coerceManualBeatN(), coercePresetAuto(), coercePresetBackground(), coercePresetInt(), createPresetButton(), deviceNamesForPresetOnCurrentZone(), editPresetFromTab() (+34 more)
### Community 13 - "Zones UI (JS)"
Cohesion: 0.10
Nodes (42): applyBrightnessSliders(), applyZoneContentKindEditModal(), clamp255(), computeZoneNamesTargets(), computeZonePresetUnionTargets(), computeZoneTargets(), createZone(), effectiveGroupIdsForZonePreset() (+34 more)
### Community 14 - "sim_rig.c"
Cohesion: 0.12
Nodes (45): list_pulse_sources(), cJSON_AddObjectToObject(), cJSON_Delete(), cJSON_Parse(), defaults(), api_sequence_defaults(), db_root(), load_file() (+37 more)
### Community 15 - "new_id"
Cohesion: 0.09
Nodes (11): new_id(), test_preset_round_trip(), test_profile_import_folds_animation_ids(), test_profile_round_trip(), test_sequence_round_trip(), test_clone(), test_clone_default_name(), test_delete_removes_from_profile() (+3 more)
### Community 16 - "Sequences UI (JS)"
Cohesion: 0.11
Nodes (33): addSeqTarget(), addSequenceToTab(), addTargetsPerDriver(), appendZoneSequenceTiles(), applySequenceSwitchWaitFromServer(), buildStepPlaySelect(), createSequenceTileRow(), deleteCurrentSequence() (+25 more)
### Community 17 - "SerialTransport"
Cohesion: 0.11
Nodes (4): SerialIntercept, SerialTransport, TransportError, TransportExecError
### Community 18 - "esp_err.h"
Cohesion: 0.04
Nodes (24): on_eth_down(), on_got_ip(), heap_caps_malloc(), esp_fill_random(), esp_get_free_heap_size(), esp_get_minimum_free_heap_size(), esp_log_level_set(), esp_log_set_vprintf() (+16 more)
### Community 19 - "led_strip Component Docs"
Cohesion: 0.10
Nodes (36): led_test ESP-IDF project, led_test main component (main.c), led_strip API Reference, led_model_t (WS2812/SK6812), led_pixel_format_t (GRB/GRBW), led_strip_clear(), led_strip_config_t, led_strip_del() (+28 more)
### Community 20 - "Art-Net Output"
Cohesion: 0.09
Nodes (10): ArtNet, as_channels(), build_artdmx(), _ip_bytes(), _pad(), port_lo(), ticks_diff(), ticks_ms() (+2 more)
### Community 21 - "freertos.c"
Cohesion: 0.06
Nodes (51): bridge_eth_start(), app_main(), ctl_open(), mic_start(), udp_open(), httpd_os_thread_create(), httpd_os_thread_handle(), make_deadline() (+43 more)
### Community 22 - "LedSimulatorApp"
Cohesion: 0.13
Nodes (4): lan_ip(), _hex(), LedSimulatorApp, main()
### Community 23 - "cJSON_IsString"
Cohesion: 0.07
Nodes (93): cJSON, child, cJSON_DeleteItemFromArray(), cJSON_DetachItemFromArray(), cJSON_GetArrayItem(), cJSON_GetArraySize(), cJSON_GetStringValue(), cJSON_InsertItemInArray() (+85 more)
### Community 24 - "cJSON_Delete"
Cohesion: 0.15
Nodes (44): net_ap_on(), net_sta_status(), patterns_get(), api_fn_t, api_http_entry(), api_req_t, api_route_t, app_js_get() (+36 more)
### Community 26 - "ctrl_msg.cpp"
Cohesion: 0.15
Nodes (23): apply_device_config(), apply_presets(), apply_v1(), cstr(), ctrl_handle(), decode_default(), decode_presets(), decode_select() (+15 more)
### Community 27 - "seqplay.c"
Cohesion: 0.12
Nodes (44): engine_zone_current(), add_id(), advance_time(), anchor_bar(), audio_drives(), bit(), chase_mask(), chase_move() (+36 more)
### Community 28 - "Devices UI (JS)"
Cohesion: 0.10
Nodes (32): applyEspnowPingAggregateToDots(), applyEspnowPingToDeviceRows(), applyTcpSnapshot(), applyTransportVisibility(), collectDeviceEditPayload(), createDeviceFromModal(), createDeviceIdentifyButton(), DEVICE_DOT_CLASSES (+24 more)
### Community 29 - "binary_envelope.py"
Cohesion: 0.15
Nodes (18): brightness_0_255_from_wire(), brightness_wire_from_0_255(), _clamp_i16(), _colors_to_rgb_list(), _decode_default_blob(), _decode_preset_record(), _decode_presets_blob(), _decode_select_blob() (+10 more)
### Community 30 - "Colour Picker Mockups"
Cohesion: 0.11
Nodes (25): Chromium-style Color Picker Demo, ColorPickerChromium Component, updateColors() (Chromium demo), Custom Color Picker Demo, updateColors() (standard demo), Custom Colour Picker README, POST /api/colors (example), ColorPicker Component (+17 more)
### Community 32 - "cJSON_CreateObject"
Cohesion: 0.10
Nodes (68): add_item_to_array(), add_item_to_object(), cJSON_AddArrayToObject(), cJSON_AddBoolToObject(), cJSON_AddFalseToObject(), cJSON_AddItemToArray(), cJSON_AddItemToObject(), cJSON_AddNullToObject() (+60 more)
### Community 33 - "httpd_parse.c"
Cohesion: 0.16
Nodes (25): cb_header_field(), cb_header_value(), cb_headers_complete(), cb_no_body(), cb_on_body(), cb_url(), httpd_cookie_key_value(), httpd_get_raw_req_data() (+17 more)
### Community 34 - "test_sequences.py"
Cohesion: 0.17
Nodes (24): clock(), make(), presets(), test_beat_and_time_lanes_together(), test_chase_moves_and_bounces(), test_editing_stops_playback(), test_legacy_animation_kind_plays_once(), test_looping_sequence_as_clip_plays_once() (+16 more)
### Community 35 - "cJSON_Delete"
Cohesion: 0.12
Nodes (45): cJSON_GetObjectItem(), cJSON_IsNull(), cJSON_IsNumber(), cJSON_IsTrue(), setting_int(), have_static_ips(), parse_static(), settings_bool() (+37 more)
### Community 36 - "API Docs: Outputs & Audio"
Cohesion: 0.16
Nodes (21): Audio API /api/audio and /audio page routes, Profile/preset/sequence JSON bundles (import/export), Combined brightness (global x groups x device x zone), /db collection export and replace, Devices resource /devices, Driver group membership lists (group ids, z<zone id>), Device groups resource /groups, LED Controller HTTP/JSON API (+13 more)
### Community 37 - "http_parser"
Cohesion: 0.12
Nodes (21): continue_parsing(), parse_block(), http_message_needs_eof(), http_parser, content_length, data, http_parser_execute(), flags (+13 more)
### Community 38 - "socket"
Cohesion: 0.14
Nodes (9): discover(), local_subnet(), main(), discover(), _expand(), _ip(), local_subnet(), ota_drivers() (+1 more)
### Community 39 - "Beat Detection DSP (C)"
Cohesion: 0.27
Nodes (16): beat_feed(), analyse_beat(), bar_cue(), bar_decide(), beat_dsp_feed(), beat_dsp_init(), beat_dsp_tap(), best_phase() (+8 more)
### Community 40 - "xSemaphoreGive"
Cohesion: 0.04
Nodes (91): ctl_task(), log_hook(), mic_task(), on_sent(), rx_task(), udp_send_up(), udp_task(), usb_send_frame() (+83 more)
### Community 41 - "WS2812"
Cohesion: 0.06
Nodes (19): new_ws2812_encoder(), rmt_del_ws2812_encoder(), rmt_encode_ws2812(), rmt_ws2812_encoder_reset(), rmt_ws2812_encoder_t, WS2812, channel_, encoder_ (+11 more)
### Community 42 - "run_all"
Cohesion: 0.12
Nodes (13): dim(), expected(), frame(), frame_sum(), mismatch_detail(), packet(), read_serial(), run_all() (+5 more)
### Community 43 - "usb_cfg.cpp"
Cohesion: 0.07
Nodes (20): vTaskDelete(), be16(), be32(), ddp_set_enabled(), ddp_sync_task(), ddp_task(), patterns_count(), handle_line() (+12 more)
### Community 44 - "httpd_handle_t"
Cohesion: 0.12
Nodes (24): httpd_config_t, httpd_method_t, httpd_uri_t, httpd_create(), httpd_start(), httpd_find_uri_handler(), httpd_register_uri_handler(), httpd_unregister_uri() (+16 more)
### Community 45 - "http_parser.h"
Cohesion: 0.09
Nodes (20): http_cb, http_data_cb, http_errno, HTTP_ERRNO_MAP, http_method, http_parser_settings, on_body, on_chunk_complete (+12 more)
### Community 46 - "http_parser.c"
Cohesion: 0.15
Nodes (8): parse_init(), http_parse_host(), http_parse_host_char(), http_parser_init(), http_parser_parse_url(), http_parser_settings_init(), http_parser_url_init(), parse_url_char()
### Community 47 - "USB Latency Tools"
Cohesion: 0.17
Nodes (10): analyze(), edges(), main(), pct(), read(), fit_clock(), main(), pct() (+2 more)
### Community 50 - "exchange"
Cohesion: 0.13
Nodes (23): engine_zone_note(), beat_task(), on_beat(), seqplay_end_base_in(), seqplay_overlay_stop(), seqplay_stop(), seqplay_stop_if(), seqplay_switch_wait() (+15 more)
### Community 52 - "sys"
Cohesion: 0.08
Nodes (5): Build and run, mpremote_base(), main(), info(), upload()
### Community 53 - "mpremote Transport"
Cohesion: 0.12
Nodes (20): Presets Mockup Page, addColorPicker() / initializeColorPickers(), ColorPicker component (color-picker.js / color-picker.css), Preset Delay (animation speed, 10-1000 ms), ESPNow preset distribution, filterPresets() / sortPresets() search, filter and sort, LED Patterns (on, off, blink, chase, circle, pulse, rainbow, transition), Pattern Parameters N1-N8 (+12 more)
### Community 54 - "httpd_sess.c"
Cohesion: 0.16
Nodes (24): httpd_os_thread_delete(), httpd_accept_conn(), httpd_process_session(), httpd_server(), httpd_thread(), enum_function(), fd_is_valid(), httpd_is_sess_available() (+16 more)
### Community 57 - "httpd_config"
Cohesion: 0.06
Nodes (30): httpd_config, backlog_conn, close_fn, core_id, ctrl_port, enable_so_linger, global_transport_ctx, global_transport_ctx_free_fn (+22 more)
### Community 58 - "gallery.js"
Cohesion: 0.26
Nodes (15): apply(), banner(), bgField(), buildCard(), checkField(), colourList(), draw(), hex() (+7 more)
### Community 59 - "mic_alsa.c"
Cohesion: 0.09
Nodes (21): capture_loop(), capture_thread(), list_alsa_devices(), mic_close(), mic_error(), mic_get_level(), mic_is_open(), mic_list_devices() (+13 more)
### Community 60 - "nvs_sim.cpp"
Cohesion: 0.15
Nodes (31): drop_unicast_peers(), load_channel(), set_channel(), ctrl_init(), save_groups(), get_str(), settings_load_hw(), settings_save_hw() (+23 more)
### Community 61 - "API Test Fixtures & Audio"
Cohesion: 0.13
Nodes (6): base_url(), c(), Client, profile(), restore_db(), missing()
### Community 62 - "Microdot Request (dmx)"
Cohesion: 0.15
Nodes (4): Request, G, urldecode_bytes(), urldecode_str()
### Community 63 - "Help: Zones & Palette"
Cohesion: 0.13
Nodes (18): Colour Palette (per profile), Zone default preset (default hint), DJ zone starter option, From Palette linked colours, LED driver JSON (presets, select, save, default, manifest), Patterns dialog, POST /presets/send, Preset editor (Try, Save, Send, Manual) (+10 more)
### Community 64 - "ddp_test.py"
Cohesion: 0.08
Nodes (23): hsv(), rig_mid(), rig_rows(), rig_xy(), soak_rig_bounce(), soak_rig_checker(), soak_rig_columns(), soak_rig_converge() (+15 more)
### Community 66 - "httpd_handle_t"
Cohesion: 0.09
Nodes (33): httpd_free_ctx_fn_t, httpd_handle_t, httpd_pending_func_t, httpd_recv_func_t, httpd_send_func_t, sock_db, ctx, fd (+25 more)
### Community 67 - "BridgeSim"
Cohesion: 0.13
Nodes (4): BridgeSim, driver_mac(), main(), Strip
### Community 68 - "httpd_uri.c"
Cohesion: 0.11
Nodes (9): httpd_req, httpd_session_enum_function, thread_data, handle, status, httpd_get_client_list(), httpd_get_global_transport_ctx(), httpd_get_global_user_ctx() (+1 more)
### Community 69 - "led_strip_rmt_encoder.c"
Cohesion: 0.25
Nodes (5): led_strip_encoder_config_t, rmt_del_led_strip_encoder(), rmt_encode_led_strip(), rmt_led_strip_encoder_reset(), rmt_new_led_strip_encoder()
### Community 70 - "Index Page Modals"
Cohesion: 0.11
Nodes (19): Audio Beat Detection modal, Header BPM / beat sync indicator, Colour Palette modal, Devices modal, Edit device modal, Edit Zone modal, Device groups modal, Header global brightness slider (+11 more)
### Community 71 - "rel.c"
Cohesion: 0.06
Nodes (31): beat_get_info(), bench_on_echo(), bridge_list(), espnow_tx_ap_clients(), espnow_tx_send(), espnow_tx_stats(), reset_reason(), status_get_handler() (+23 more)
### Community 72 - "httpd_data"
Cohesion: 0.11
Nodes (18): esp_http_server_event_id_t, httpd_err_handler_func_t, httpd_data, config, ctrl_fd, ctrl_sock_semaphore, err_handler_fns, hd_calls (+10 more)
### Community 74 - "presets.cpp"
Cohesion: 0.18
Nodes (24): clear_all_presets(), entry_key(), find(), load_entry(), load_legacy(), presets_add_defaults(), presets_apply_startup(), presets_at() (+16 more)
### Community 75 - "Bench test: S3 controller and one LED driver"
Cohesion: 0.23
Nodes (9): Bench endpoints /test/loss and /test/beats, 30 ms beat lead (CONFIG_BEAT_LEAD_MS), Bench test: S3 controller and one LED driver, ESP32-C3 vs S3 driver comparison, Logic analyzer latency (marker GPIO, tools/analyze_edges.py), Lossy-link test (simulated loss, retries, resync), Reliable link (rel: acked unicast, retransmits, ack timeouts), Bench troubleshooting (serial ports, channel mismatch, blank UI) (+1 more)
### Community 76 - "Controller Overview & OTA Docs"
Cohesion: 0.20
Nodes (11): led_controller ESP-IDF project, Driver app update /drivers/ota (staged files, sha, commit/abort), Firmware OTA /ota (idle slot, rollback), Driver app update over ESP-NOW test (tools/driver_ota.py), led-tool / led-cli serial device CLI, led-cli --ota controller update over Ethernet, driver settings.json (mpremote download/merge/upload), main ESP-IDF component (firmware sources) (+3 more)
### Community 77 - "espnow_link.cpp"
Cohesion: 0.06
Nodes (44): on_recv(), beat_on_frame(), Asm, buf, cnt, asm_find(), flags, asm_free() (+36 more)
### Community 78 - "sim_split.js"
Cohesion: 0.32
Nodes (18): addMenuEntries(), applyWidth(), attachSwipe(), build(), clampWidth(), close(), init(), isOpen() (+10 more)
### Community 79 - "Audio Monitor Page"
Cohesion: 0.16
Nodes (16): /audio.wav live PCM stream, bar() bar-position renderer, /beats SSE event stream, draw() timeline canvas, Listen button (WAV stream playback via AudioContext), median(), Audio and beats page (/audio), stats() tap vs computer agreement (+8 more)
### Community 80 - "artnet_dmx.py"
Cohesion: 0.26
Nodes (9): parse(), _assert_eq(), main(), test_artnet_send_loopback(), test_build_artdmx(), test_fixture_patch(), test_pattern_blink_and_select(), test_pattern_upload() (+1 more)
### Community 82 - "events"
Cohesion: 0.09
Nodes (21): cached, exitCode, stdout, variable, CMAKE_C_FLAGS, CMAKE_C_FLAGS_DEBUG, CMAKE_CXX_FLAGS, CMAKE_CXX_FLAGS_DEBUG (+13 more)
### Community 83 - "web.c"
Cohesion: 0.33
Nodes (11): audio_page_handler(), etag(), favicon_handler(), find_file(), index_handler(), mime_for(), send_gz(), static_handler() (+3 more)
### Community 84 - "unique"
Cohesion: 0.08
Nodes (16): find_id_by_field(), unique(), test_scenes(), device(), group(), test_crud(), test_group_identify_needs_devices(), test_profile_scoped_group() (+8 more)
### Community 85 - "ESP-NOW Sender Bridge"
Cohesion: 0.20
Nodes (10): ap(), _broadcast_ws(), _espnow_receive_loop(), _init_espnow(), main(), _send_espnow(), _validate_envelope(), ws() (+2 more)
### Community 86 - "net.cpp"
Cohesion: 0.12
Nodes (23): ctrl_build_announce(), names_me(), own_mac_hex(), ddp_start(), app_main(), ap_switch_later(), ap_timer_cb(), apply_ap() (+15 more)
### Community 89 - "api_call_t"
Cohesion: 0.33
Nodes (5): api_call_t, cap, done, msg, out
### Community 90 - "Sender"
Cohesion: 0.14
Nodes (4): run_interactive(), handle(), show_menu(), Sender
### Community 92 - "bridge_serial.c"
Cohesion: 0.13
Nodes (21): bridge_eth_ip(), build_info(), handle_frame(), host_rx_task(), put_u32(), send_info(), bridge_crc16_update(), bridge_decode_feed() (+13 more)
### Community 93 - "events"
Cohesion: 0.10
Nodes (24): cached, exitCode, stdout, variable, CMAKE_C_FLAGS, CMAKE_C_FLAGS_DEBUG, CMAKE_CXX_FLAGS, CMAKE_CXX_FLAGS_DEBUG (+16 more)
### Community 94 - "Type"
Cohesion: 0.18
Nodes (11): Type, T_BLOB, T_I32, T_I64, T_STR, T_U32, T_U8, Value (+3 more)
### Community 95 - "Microdot Auth (dmx)"
Cohesion: 0.19
Nodes (6): wraps(), print_exception(), websocket_upgrade(), websocket_wrapper(), wrapper(), with_websocket()
### Community 96 - "esp_timer_create"
Cohesion: 0.36
Nodes (7): ota_confirm_later(), ota_confirm_later(), arm(), esp_timer_create(), esp_timer_is_active(), esp_timer_start_once(), esp_timer_start_periodic()
### Community 97 - "v1 driver messages (long/short keys)"
Cohesion: 0.40
Nodes (5): Controller WebSocket /ws (v1 presets/select), Binary envelope (main/envelope.c, test/binary_envelope.py), v1 driver messages (long/short keys), WebSocket /ws driver message relay, espnow-sender Microdot WebSocket receiver
### Community 98 - "DMX Preset Model"
Cohesion: 0.13
Nodes (8): _expand(), _preset_from_map(), process_data(), _select_entries(), _targets_for_key(), play(), _parse_colour(), Preset
### Community 99 - "httpd_txrx.c"
Cohesion: 0.12
Nodes (37): esp_app_get_description(), httpd_err_code_t, httpd_resp_sendstr(), httpd_default_recv(), httpd_default_send(), httpd_recv(), httpd_register_err_handler(), httpd_req_async_handler_begin() (+29 more)
### Community 101 - "Groups UI (JS)"
Cohesion: 0.29
Nodes (9): fetchDevicesMapForGroups(), fetchGroupsMap(), identifyGroupById(), loadGroupsModal(), loadWifiFieldsFromGroup(), openEditGroupModal(), renderGroupDevicesEditor(), renderGroupsList() (+1 more)
### Community 102 - "httpd_req_aux"
Cohesion: 0.11
Nodes (18): httpd_req_aux, content_type, first_chunk_sent, max_req_hdr_len, max_uri_len, remaining_len, req_hdrs_count, resp_hdrs (+10 more)
### Community 103 - "Help: Mobile Menu Image"
Cohesion: 0.24
Nodes (10): Mobile Menu Help Illustration (narrow screen), Content Area (preset buttons), Menu Dropdown (Run mode, Profiles, Tabs, Presets, Help), Header Tab Buttons, Help, Menu Button (header dropdown trigger), Presets, Profiles (+2 more)
### Community 104 - "Pattern Selector Mockup Image"
Cohesion: 0.20
Nodes (11): Pattern Selector Mockup (Select LED Pattern), Apply Pattern / Cancel Actions, Blink Pattern, Chase Pattern, Circle Pattern, Off Pattern, On Pattern (solid color), Pattern Card Grid Layout (+3 more)
### Community 105 - "Driver Pattern Docs"
Cohesion: 0.24
Nodes (11): Message processing order (version, presets upsert, colour, selection), Auto vs manual (a) and manual chase flush, Built-in off / on patterns, Patterns and presets on the LED driver, MAX_PRESETS = 32, Pattern OTA via manifest / POST /patterns/upload, Pattern registry (Presets.reload_patterns), Preset short keys (p, c, d, b, a, bg, n1-n6) (+3 more)
### Community 106 - "USB ESP-NOW bridge"
Cohesion: 0.13
Nodes (13): Build and flash, Channel, Ethernet (W5500), Microphone (S3), Protocol, Running the controller against it, USB ESP-NOW bridge, How it is built (+5 more)
### Community 107 - "main"
Cohesion: 0.18
Nodes (8): find_devices(), probe(), sweep(), load_rig(), local_prefix(), main(), neighbours(), set_fps()
### Community 108 - "rig_seed.py"
Cohesion: 0.13
Nodes (13): sync_patterns(), normalise_layout(), _reversed_for_column(), rig_placements(), side_name(), strip_count(), strip_places(), StripPlace (+5 more)
### Community 109 - "Driver Message API Docs"
Cohesion: 0.38
Nodes (10): Auto vs manual mode, Beat (re-select same preset restarts generator), Hex colour conversion and colour-order reordering, LED Driver API (message format), Pattern-specific parameters (rainbow, pulse, transition, chase, circle), Preset fields (pattern, colors, delay, brightness, auto, n1-n6), Select message (device -> [preset, step]), Step synchronization (+2 more)
### Community 110 - "run_soak"
Cohesion: 0.18
Nodes (6): get(), Missing, output_scale(), run_soak(), sample(), soft_get()
### Community 111 - "led_strip Manifest"
Cohesion: 0.20
Nodes (9): dependencies, idf, description, repository, repository_info, commit_sha, path, url (+1 more)
### Community 113 - "Outputs UI (JS)"
Cohesion: 0.33
Nodes (8): fetchOutputs(), loadOutputsModal(), openOutputEditor(), OUTPUT_PROTOCOL_LABELS, outputSummary(), renderOutputsList(), setOutputField(), syncOutputProtocolFields()
### Community 114 - "dependencies"
Cohesion: 0.50
Nodes (3): dependencies, espressif/w5500, version
### Community 115 - "Help PDF: Overview"
Cohesion: 0.25
Nodes (9): API.md, LED controller user guide, Main web UI (Raspberry Pi app), Pattern OTA install over HTTP (/patterns/ota, upload, driver, send), Pattern parameters n1-n8, README, Serial to ESP-NOW bridge transport, WebSocket /ws (+1 more)
### Community 116 - "Mockups Index Image"
Cohesion: 0.31
Nodes (9): LED Driver UI Mockups Index (screenshot), Dashboard Mockup, Device Groups, Device Management Mockup, LED Patterns (On, Off, Blink, Chase, Circle, Pulse, Rainbow, Transition), N1-N8 Pattern Parameters, Pattern Selector Mockup, Presets Mockup (+1 more)
### Community 117 - "outputs.c"
Cohesion: 0.32
Nodes (11): fail(), fill(), one_of(), put16(), resolve(), run_test(), send_artnet(), send_ddp() (+3 more)
### Community 118 - "Help: Header Toolbar Image"
Cohesion: 0.29
Nodes (8): Header Toolbar Help Image, Edit Mode Action Bar, Run/Edit Mode Toggle Button, Patterns Action, Presets Action, Profiles Action, Header Tab Buttons, Tabs Action
### Community 119 - "Help: Preset Editor Image"
Cohesion: 0.29
Nodes (5): Default Action, Preset Pattern Selector, Preset Editor Modal (help illustration), Preset Name Field, Brightness, Delay and n1-n8 Parameters (0-255)
### Community 120 - "Dashboard Mockup Image"
Cohesion: 0.32
Nodes (8): LED Driver Control Panel Dashboard Mockup, Apply Settings Action, Brightness & Speed Card (Brightness % and Delay ms sliders), Colors Card (color swatches palette, Add Color), Connected Devices Card (devices with group and online status), Device Groups, Pattern Selection Card (On, Off, Blink, Chase, Circle, Pulse, Rainbow, Transition), Save to Device Action
### Community 121 - "Device Management Mockup Image"
Cohesion: 0.32
Nodes (8): + Add Device Button, Connected Devices List, Device Group, Device & Group Management Screen (mockup), Device Row Actions (edit, settings, stop), Online/Offline Status Badge, Devices / Groups Tab Switcher, LED Device (MAC, group, pattern)
### Community 122 - "Presets Mockup Image"
Cohesion: 0.32
Nodes (8): Preset Management UI Mockup, Apply Preset Action, Create Preset Action, LED Pattern Types (Rainbow, Pulse, Chase, Circle, Blink, Transition), Preset Card (name, pattern badge, color swatches, delay, n1, apply/edit/delete), Preset Search/Filter/Sort Toolbar (pattern filter, sort by name, grid/list toggle), Preset Parameters (colors, delay ms, n1), Sync Presets to All Devices
### Community 123 - "Pattern Contract"
Cohesion: 0.29
Nodes (6): Pattern Contract, Drawing via driver.n and apply_brightness, Pattern error handling (Presets.tick catches), Presets._load_dynamic_patterns(), Shared driver.step semantics, Global vs per-preset brightness
### Community 124 - "esp_httpd_priv.h"
Cohesion: 0.18
Nodes (20): desktop_base64_encode(), desktop_sha1(), rol(), sha1_block(), httpd_ws_frame_t, httpd_recv_opt_t, httpd_recv_pending(), httpd_recv_with_opt() (+12 more)
### Community 125 - "led_strip_spi_dev.c"
Cohesion: 0.06
Nodes (38): heap_caps_calloc(), app_main(), app_main(), configure_led(), app_main(), configure_led(), led_strip_rmt_config_t, led_strip_spi_config_t (+30 more)
### Community 126 - "esp_http_server_dispatch_event"
Cohesion: 0.33
Nodes (4): esp_err_to_name(), esp_event_post(), esp_read_mac(), esp_http_server_dispatch_event()
### Community 128 - "httpd_ctrl_data"
Cohesion: 0.22
Nodes (9): httpd_work_fn_t, httpd_ctrl_data, hc_msg, hc_work, hc_work_arg, httpd_ctrl_msg, HTTPD_CTRL_MAX, HTTPD_CTRL_SHUTDOWN (+1 more)
### Community 129 - "Colour Picker Demo Image"
Cohesion: 0.33
Nodes (6): Custom Color Picker Demo (screenshot), Hex and RGB input support, HSB (Hue, Saturation, Brightness) color model, Keyboard accessible, customizable styling, Multiple Color Pickers for LED Patterns, Single Color Picker
### Community 130 - "Settings Mockup Image"
Cohesion: 0.33
Nodes (7): Advanced Settings (Step Counter, Step Increment, Device ID, Debug Mode), Basic Settings (Device Name, LED Pin, Number of LEDs), Color Order Selector (RGB/RBG/GRB/GBR/BRG/BGR), Device Settings Page Mockup, Network Settings (Access Point Name, Password, Enable AP), Pattern Parameters N1-N6, Pattern Settings (Pattern, Brightness, Delay)
### Community 131 - "flags"
Cohesion: 0.22
Nodes (9): flags, F_CHUNKED, F_CONNECTION_CLOSE, F_CONNECTION_KEEP_ALIVE, F_CONNECTION_UPGRADE, F_CONTENTLENGTH, F_SKIPBODY, F_TRAILING (+1 more)
### Community 132 - "microdot.py"
Cohesion: 0.10
Nodes (5): invoke_handler(), iscoroutine(), Response, aclose(), __anext__()
### Community 133 - "http_parser_url_fields"
Cohesion: 0.22
Nodes (9): http_parser_url_fields, UF_FRAGMENT, UF_HOST, UF_MAX, UF_PATH, UF_PORT, UF_QUERY, UF_SCHEMA (+1 more)
### Community 137 - "time"
Cohesion: 0.15
Nodes (9): Blink, Pulse, sleep(), sleep_ms(), sleep_us(), ticks_diff(), ticks_ms(), ticks_us() (+1 more)
### Community 138 - "Help: Colour Palette Image"
Cohesion: 0.40
Nodes (6): Colour Palette modal mockup (help image), Add Swatch (+) Button, Colour Palette Modal, Palette Colour Swatches, Preset Editor 'From Palette', Profile (palette owner)
### Community 139 - "sim_demo.py"
Cohesion: 0.26
Nodes (7): Api, main(), group(), preset(), sequence(), new_id(), rig_bars()
### Community 140 - "LED Driver README"
Cohesion: 0.47
Nodes (6): dev.py deploy/sync script, LED Driver README (MicroPython ESP32), Optional HTTP polling (http_poll.py), Wi-Fi TCP transport to Pi (port 8765), transport_type setting (wifi / espnow), UDP discovery (port 8766)
### Community 141 - "DMX Driver Art-Net and serial gateway"
Cohesion: 0.28
Nodes (9): Art-Net output (UDP 6454), DMX Driver Art-Net and serial gateway, DMX fixture (output, start channel, role map; parcan/mover profiles), led-driver-style pattern engine (Preset object), POST /patterns/upload (led-driver parity), Serial DMX512 output (250000 8N2), Outputs (DDP, Art-Net, sACN, DMX serial pixel fixtures), Patterns resource /patterns (+1 more)
### Community 142 - "SPI Example Manifest"
Cohesion: 0.33
Nodes (5): dependencies, espressif/led_strip, idf, override_path, version
### Community 143 - "test_rig_sim.py"
Cohesion: 0.10
Nodes (28): all_dark(), col_of(), frames(), led_x(), lit(), mac(), make_preset(), need_sim() (+20 more)
### Community 145 - "Help PDF: Modes"
Cohesion: 0.40
Nodes (4): Edit mode, Mobile layout Menu, Run mode, Zones modal
### Community 146 - "Help: Tab Preset Strip Image"
Cohesion: 0.60
Nodes (5): Help image: Main area brightness and preset tiles, Edit Mode: drag tiles to reorder, Global Brightness Slider, Preset Tile (gradient swatch, click to select on tab devices), Tab (e.g. lounge)
### Community 149 - "api_error"
Cohesion: 0.10
Nodes (58): httpd_req_t, httpd_resp_send_500(), api_body(), api_body_opt(), api_current_profile(), api_error(), api_json(), api_merge() (+50 more)
### Community 155 - "app.js"
Cohesion: 0.11
Nodes (56): addBridge(), addFixture(), addLog(), api(), applyConfig(), banner(), changed(), colourAt() (+48 more)
### Community 156 - "RMT Example Manifest"
Cohesion: 0.40
Nodes (4): dependencies, espressif/led_strip, override_path, version
### Community 157 - "Help Tab JS"
Cohesion: 0.25
Nodes (11): addStaticIpRow(), describeBridge(), loadBridgeSettings(), loadDeviceSettings(), loadNetworkStatus(), putBridges(), renderBridges(), setApToggle() (+3 more)
### Community 158 - "Settings Page Template"
Cohesion: 0.50
Nodes (4): Settings modal (device, network), loadEspnowChannel(), Device Settings page (ESP-NOW channel), wifi_channel setting (1-11)
### Community 159 - "led-driver/web/app.js"
Cohesion: 0.10
Nodes (49): api(), applyMode(), attachDrag(), closeEditor(), closeSock(), deviceChoices(), direct(), discoverDevices() (+41 more)
### Community 165 - "test_presets.py"
Cohesion: 0.13
Nodes (4): preset(), test_create_belongs_to_current_profile(), test_create_fills_defaults(), test_presets_scoped_to_profile()
### Community 166 - "mdns_host.c"
Cohesion: 0.15
Nodes (9): add_ptr(), build_query(), decode_name(), handle_rr(), mdns_dup(), mdns_query_ptr(), mdns_query_results_free(), parse_packet() (+1 more)
### Community 167 - "SerialDMX"
Cohesion: 0.24
Nodes (3): sleep_ms(), SerialDMX, sleep()
### Community 170 - "dependencies"
Cohesion: 0.16
Nodes (13): dependencies, espressif/cjson, espressif/mdns, espressif/w5500, joltwallet/littlefs, version, rules, version (+5 more)
### Community 171 - "List Search (JS)"
Cohesion: 0.83
Nodes (3): applyListSearch(), initListSearch(), rowSearchText()
### Community 177 - "espnow_tx.c"
Cohesion: 0.05
Nodes (48): ensure_peer(), tx_task(), esp_event_loop_create_default(), cJSON_Hooks, cJSON_InitHooks(), espnow_link_start(), bench_running(), bench_stop() (+40 more)
### Community 178 - "mac_str"
Cohesion: 0.25
Nodes (3): api_seed_layout(), index(), mac_str()
### Community 179 - "load_config"
Cohesion: 0.33
Nodes (3): load_config(), _merge(), _read_json()
### Community 184 - "beat.c"
Cohesion: 0.07
Nodes (31): vQueueDelete(), httpd_req_async_handler_complete(), httpd_req_to_sockfd(), events_task(), send_all(), audio_stream_task(), beats_get_handler(), beats_stream_task() (+23 more)
### Community 197 - "cJSON_GetObjectItem"
Cohesion: 0.10
Nodes (76): cJSON_AddItemReferenceToObject(), cJSON_CreateBool(), cJSON_CreateString(), cJSON_DeleteItemFromObject(), cJSON_Duplicate(), cJSON_IsObject(), cJSON_ReplaceItemInObject(), api_add() (+68 more)
### Community 198 - "Transport"
Cohesion: 0.23
Nodes (3): _convert_filesystem_error(), stdout_write_bytes(), Transport
### Community 199 - "httpd_req"
Cohesion: 0.20
Nodes (10): httpd_req, aux, content_len, free_ctx, handle, ignore_sess_ctx_changes, method, sess_ctx (+2 more)
### Community 201 - "http_parser_type"
Cohesion: 0.50
Nodes (4): http_parser_type, HTTP_BOTH, HTTP_REQUEST, HTTP_RESPONSE
### Community 202 - "json"
Cohesion: 0.09
Nodes (11): call(), main(), switch(), wifi_state(), _default_image(), _info(), ota_update(), _default_image() (+3 more)
### Community 203 - "desktop_main.c"
Cohesion: 0.60
Nodes (3): main(), set_from_env(), usage()
### Community 204 - "_simlink_proc.py"
Cohesion: 0.16
Nodes (5): connect(), on_feed(), push_pixels(), _reader(), _send_pixels()
### Community 205 - "esp_http_server.h"
Cohesion: 0.08
Nodes (22): esp_http_server_event_data, http_method, httpd_close_func_t, httpd_open_func_t, httpd_resp_send_404(), httpd_resp_send_408(), httpd_resp_sendstr_chunk(), httpd_uri (+14 more)
### Community 207 - "relay_forward"
Cohesion: 0.11
Nodes (20): cJSON_free(), api_call_work(), envelope(), relay_client(), relay_do(), relay_forward(), relay_host_ok(), relay_path_ok() (+12 more)
### Community 227 - "dependencies"
Cohesion: 0.33
Nodes (5): dependencies, espressif/cjson, espressif/mdns, version, version
### Community 235 - "driver-worker.js"
Cohesion: 0.53
Nodes (4): boot(), exit(), log(), startPixels()
### Community 236 - "layout.js"
Cohesion: 0.43
Nodes (3): fixtureEnd(), fixtureLeds(), roomStrips()
## Knowledge Gaps
- **297 isolated node(s):** `next`, `prev`, `child`, `type`, `valuestring` (+292 more)
These have ≤1 connection - possible missing edges or undocumented components. (Counts symbols only; 1235 node(s) total have ≤1 connection when file, concept and rationale nodes are included.)
- **65 thin communities (<3 nodes) omitted from report** — run `graphify query` to explore isolated nodes.
## Suggested Questions
_Questions this graph is uniquely positioned to answer:_
- **Why does `string` connect `esp_err.h` to `cJSON`, `sim_rig.c`, `freertos.c`, `api_error`, `cJSON_IsString`, `seqplay.c`, `cJSON_CreateObject`, `httpd_parse.c`, `cJSON_Delete`, `mdns_host.c`, `Beat Detection DSP (C)`, `xSemaphoreGive`, `http_parser.c`, `espnow_tx.c`, `mic_alsa.c`, `nvs_sim.cpp`, `httpd_uri.c`, `cJSON_GetObjectItem`, `rel.c`, `desktop_main.c`, `esp_http_server.h`, `web.c`, `bridge_serial.c`, `Type`, `outputs.c`, `esp_httpd_priv.h`, `led_strip_spi_dev.c`?**
_High betweenness centrality (0.061) - this node is a cross-community bridge._
- **Are the 190 inferred relationships involving `cJSON_GetObjectItem()` (e.g. with `list_pulse_sources()` and `apply_default()`) actually correct?**
_`cJSON_GetObjectItem()` has 190 INFERRED edges - model-reasoned connections that need verification._
- **What connects `next`, `prev`, `child` to the rest of the system?**
_297 weakly-connected nodes found - possible documentation gaps or missing edges._
- **Should `IdfDevice` be split into smaller, more focused modules?**
_Cohesion score 0.09411764705882353 - nodes in this community are weakly interconnected._
- **Why does `PyboardCommand` connect `PyboardCommand` to `SerialTransport`?**
_High betweenness centrality (0.027) - this node is a cross-community bridge._
- **Are the 114 inferred relationships involving `cJSON_Delete()` (e.g. with `list_pulse_sources()` and `ctrl_handle()`) actually correct?**
_`cJSON_Delete()` has 114 INFERRED edges - model-reasoned connections that need verification._
- **Should `htmx Library` be split into smaller, more focused modules?**
_Cohesion score 0.07897684839432412 - nodes in this community are weakly interconnected._
Loaded 100 of 506 files, more files were not shown because too many files have changed in this diff. Show more