Author SHA1 Message Date
jimmyandCursor cb9758b97b fix(api): align zone content kind validation with model
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-08 10:33:42 +12:00
jimmyandCursor aab62efd4f feat(ui): refresh layout, help assets, and panel styling
Update the main template and client scripts for the revised navigation
and zone/device panels, and add bundled help SVG assets under static.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-08 10:33:41 +12:00
jimmyandCursor 2382ef16a1 refactor(api): migrate server to fastapi and uvicorn
Replace the Microdot-only entrypoint with a CombinedASGI app that
handles FastAPI routes (audio API, websocket, dev live-reload) while
delegating the rest to Microdot. Suppress noisy /__dev/ access logs
during live-reload polling.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-08 10:33:38 +12:00
jimmyandCursor cfdd6de291 docs(espnow): update docs and tests for p2p merge
Align API, architecture, and help with devices envelope transport,
bridge wifi/serial settings, and MAC-keyed device registry. Fix
endpoint tests for envelope identify payloads; remove obsolete p2p.py.
Bump led-tool for --serial-usb bridge provisioning.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-06 21:10:06 +12:00
jimmyandCursor d682753e42 chore(submodules): bump led-driver
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-29 16:01:01 +12:00
jimmyandCursor 53976cdd70 chore(scripts): add mpremote ESP-NOW ch5 send helpers
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-29 16:01:01 +12:00
jimmyandCursor 94635a8cc7 chore(db): add devices to test group
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-29 16:01:01 +12:00
jimmyandCursor de0547615c feat(ui): add device from devices modal
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-29 16:00:59 +12:00
jimmyandCursor 78dc8ffc77 feat(bridge): add wifi/serial bridge runtime and UI
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-28 00:38:21 +12:00
jimmyandCursor 2cf019079e chore(submodules): bump led-driver and led-tool
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 22:03:24 +12:00
jimmyandCursor b87382d2be feat(espnow): broadcast delivery with group-filtered routing
Send presets and select on broadcast with groups; unicast only for
per-device settings. V1 select as [preset_id, step?]. Sequence steps
use beat counts; manual presets get select each beat, auto only on
step change. Bridge downlink router, Pi envelope delivery, and tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-24 01:44:28 +12:00
jimmyandCursor 1a69fabd98 fix(espnow): bridge async rx, uplink framing, driver RX handling
Bridge uses async for on AIOESPNow, pack_ws_uplink to Pi, AP channel
from settings. Driver applies binary wire and JSON commands on receive.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 22:45:13 +12:00
jimmyandCursor 4fc3f46866 feat(espnow): Pi bridge client, binary wire, and espnow-sender firmware
Replace serial/Wi-Fi driver transport paths with WebSocket bridge client,
binary espnow_wire delivery, device announce registry, and restructured
espnow-sender (AP + broadcast passthrough). Includes docs and tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 22:44:44 +12:00
jimmyandCursor f4ef85c182 chore(db): add test group and enable auto on chase/pulse
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 11:07:37 +12:00
jimmyandCursor f02eaa6bad chore(submodules): bump led-tool for Web Serial fixes
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-19 00:23:21 +12:00
jimmyandCursor 7015032f5c test: cover zone content kind lock and sequence groups
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-19 00:23:21 +12:00
jimmyandCursor d7a3fa96c5 feat(db): add Winter profile with 2x3 grid sequences
Winter profile, scoped groups, presets, and five multi-lane sequences;
include setup script for regeneration.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-19 00:23:21 +12:00
jimmyandCursor 7a7bedc07c fix(sequences): target only checked lane groups
Use zone group checkboxes in the editor; empty lane groups no longer
fall back to the whole zone. Remove cross-lane device splitting.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-19 00:23:21 +12:00
jimmyandCursor baec87068a feat(ui): lock zone type and start audio from BPM
Zone preset vs sequence is fixed at create; edit shows read-only type.
Header BPM button starts beat detection when the detector is stopped.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-19 00:23:15 +12:00
jimmyandCursor b140aedf00 chore(submodules): bump led-tool for settings editor
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-18 14:54:24 +12:00
jimmyandCursor 15f8c8a039 fix(wifi): limit outbound driver WS to hello-triggered attempts
Remove periodic UDP hello loop; dial each driver at most
wifi_driver_initial_connect_attempts times per discovery hello.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-18 14:54:22 +12:00
jimmyandCursor 70641c63af feat(led-tool): embed settings editor in main UI
Serve led-tool static editor at /led-tool/editor, filter host serial
ports, and load the modal via iframe instead of the legacy form.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-18 14:54:18 +12:00
jimmyandCursor ef15c54593 chore(submodules): bump led-driver and led-tool for file_hashes deploy
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-17 19:14:54 +12:00
jimmyandCursor 301e1c64bf test: cover audio, sequences, pattern direction, and settings
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-17 18:32:12 +12:00
jimmyandCursor c286e504eb feat(ui): numpad, audio readout, and sequence beat controls
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-17 18:32:12 +12:00
jimmyandCursor 964cfc6d91 feat(audio-sequences): beat phase sync and aligned playback
Add bar-phase tracking, audio reset/anchor APIs, BPM holdover, beat-phase
sequence switching, sync-phase endpoint, and sample sequence data.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-17 18:32:10 +12:00
jimmyandCursor 7ecb5c3b3e chore(submodules): bump led-driver for pattern reverse
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-17 18:32:07 +12:00
jimmyandCursor 879db2a7df chore(submodules): bump led-driver and led-tool
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-16 21:14:57 +12:00
jimmyandCursor 96d1e1b5fd feat(ui): pattern modes, bundles, and zone content kind
Add profile/preset/sequence JSON import and export; map preset mode to
wire n6 with a mode dropdown for multi-mode patterns; zone edit shows
presets or sequences only with content_kind on save; update catalogue
and tests for merged pattern names.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-16 21:12:42 +12:00
jimmyandCursor 6286297646 feat(patterns): register northern wave, candle glow, starfall, ice sparkle
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-16 15:11:33 +12:00
jimmyandCursor ca3fef3f8a feat(patterns): winter icicles blizzard rime in controller catalogue
Register pattern metadata and test presets for new led-driver effects; bump led-driver submodule.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-16 15:10:02 +12:00
jimmyandCursor 6c9e06f33b feat(zones): profile-scoped groups, zone modes, sequence brightness
- Optional profile_id on groups; UI and API for shared vs profile-only groups\n- Zone content_kind (presets vs sequences); edit modal shows matching sections; devices via groups only\n- Server sequence playback folds zone brightness into preset wire b (per MAC where needed)\n- Related preset/sequence/audio/beat-route and client updates

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-13 01:58:00 +12:00
jimmyandCursor c1c3e5d71b feat(ui): edit tab zones, audio readout, live reload
- Zones/presets/sequence strip and Pipfile dev command fix
- Optional live reload and beat test audio asset + generator

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-13 00:44:20 +12:00
jimmyandCursor c64dd736f2 feat(api): parallel group sends and batch identify
- asyncio.gather for group brightness and driver-config Wi-Fi pushes
- Batch identify envelope for group members

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-13 00:44:13 +12:00
jimmyandCursor cad0aa7e59 feat(sequences): multi-lane playback and per-lane manual beats
- Add sequence_playback with beat and time advance, zone targeting fixes
- Per-lane manual beat routing in beat_driver_route (parallel lanes)
- Sequence API, editor JS, fix sequence model filename, tests

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-13 00:44:08 +12:00
jimmyandCursor 0ae39ab94b chore(release): beta-1.03
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-10 16:55:07 +12:00
jimmyandCursor 822d9d8e01 feat(audio): move beat routing server-side and extend presets
Route beat-triggered manual selects from the controller server, add preset background and beat-counter UI support, and bump led-driver to include the matching pattern/runtime fixes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-09 20:08:05 +12:00
jimmyandCursor 1db905eaae feat(patterns): add supports_manual metadata in db/pattern.json
Allow staging db/pattern.json by replacing blanket db/ ignore with a whitelist for tracked db files.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-09 17:06:56 +12:00
jimmyandCursor 3d6ef5c7b4 chore(git): stop tracking runtime db state files
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-06 20:35:50 +12:00
jimmyandCursor 78a4ce009c feat(ui): refresh preset data flow and bump driver pointer
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-06 20:28:56 +12:00
jimmyandCursor 7ccab6fbc4 feat(zones): persist per-zone brightness and update submodules
Store zone brightness in model/data flow, apply it in the zones UI, and record updated led-driver, led-simulator, and led-tool submodule pointers.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-04 22:49:06 +12:00
1081 changed files with 33774 additions and 45055 deletions

No files matched your search

-3
View File
@@ -1,3 +0,0 @@
# graphify
- **graphify** (`.claude/skills/graphify/SKILL.md`) - any input to knowledge graph. Trigger: `/graphify`
When the user types `/graphify`, use the installed graphify skill or instructions before doing anything else.
@@ -1 +0,0 @@
0.9.101
-797
View File
@@ -1,797 +0,0 @@
---
name: graphify
description: "Use for any question about a codebase, its architecture, file relationships, or project content — especially when graphify-out/ exists, where the question should be treated as a graphify query first. Turns any input (code, docs, papers, images, videos) into a persistent knowledge graph with god nodes, community detection, and query/path/explain tools."
---
# /graphify
Turn any folder of files into a navigable knowledge graph with community detection, an honest audit trail, and three outputs: interactive HTML, GraphRAG-ready JSON, and a plain-language GRAPH_REPORT.md.
## Usage
```
/graphify # full pipeline on current directory (HTML viz; add --obsidian for a vault)
/graphify <path> # full pipeline on specific path
/graphify https://github.com/<owner>/<repo> # clone repo then run full pipeline on it
/graphify https://github.com/<owner>/<repo> --branch <branch> # clone a specific branch
/graphify <url1> <url2> ... # clone multiple repos, build each, merge into one cross-repo graph
/graphify <path> --mode deep # thorough extraction, richer INFERRED edges
/graphify <path> --update # incremental - re-extract only new/changed files
/graphify <path> --directed # build directed graph (preserves edge direction: source→target)
/graphify <path> --whisper-model medium # use a larger Whisper model for better transcription accuracy
/graphify <path> --cluster-only # rerun clustering on existing graph
/graphify <path> --no-viz # skip visualization, just report + JSON
/graphify <path> --html # (HTML is generated by default - this flag is a no-op)
/graphify <path> --svg # also export graph.svg (embeds in Notion, GitHub)
/graphify <path> --graphml # export graph.graphml (Gephi, yEd)
/graphify <path> --neo4j # generate graphify-out/cypher.txt for Neo4j
/graphify <path> --neo4j-push bolt://localhost:7687 # push directly to Neo4j
/graphify <path> --falkordb # generate graphify-out/cypher.txt for FalkorDB
/graphify <path> --falkordb-push falkordb://localhost:6379 # push directly to FalkorDB
/graphify <path> --mcp # start MCP stdio server for agent access
/graphify <path> --watch # watch folder, auto-rebuild on code changes (no LLM needed)
/graphify <path> --wiki # build agent-crawlable wiki (index.md + one article per community)
/graphify <path> --obsidian --obsidian-dir ~/vaults/my-project # write vault to custom path (e.g. existing vault)
/graphify add <url> # fetch URL, save to ./raw, update graph
/graphify add <url> --author "Name" # tag who wrote it
/graphify add <url> --contributor "Name" # tag who added it to the corpus
/graphify query "<question>" # BFS traversal - broad context
/graphify query "<question>" --dfs # DFS - trace a specific path
/graphify query "<question>" --budget 1500 # cap answer at N tokens
/graphify path "AuthModule" "Database" # shortest path between two concepts
/graphify explain "SwinTransformer" # plain-language explanation of a node
```
## What graphify is for
Drop any folder of code, docs, papers, images, or video into graphify and get a queryable knowledge graph. Persistent across sessions, honest audit trail (EXTRACTED/INFERRED/AMBIGUOUS), community detection surfaces cross-document connections you wouldn't think to ask about.
**When a graph is worth building:** this applies when you are choosing a tool yourself; if the user invoked `/graphify`, follow that request as asked. AST extraction of code is fast and free, but semantic extraction of docs, papers and images runs the model over every file, which can cost minutes and tens of thousands of tokens.
If a graph already exists, query it. With no graph, one targeted lookup ("where is X defined", "what calls Y" in an ordinary-sized codebase) is faster and free with a plain text search such as `grep` and `Read`: search directly instead of running the steps below, and mention that a graph can be built if the user wants one. Build one when you expect many questions against this corpus, the corpus is large or unfamiliar, the question needs links text search cannot see (doc to code, across documents), or it is structural (communities, bridges, import cycles).
## What You Must Do When Invoked
If the user invoked `/graphify --help` or `/graphify -h` (with no other arguments), print the contents of the `## Usage` section above verbatim and stop. Do not run any commands, do not detect files, do not default the path to `.`. Just print the Usage block and return.
**Fast path — existing graph:** Before doing anything else, check whether `graphify-out/graph.json` exists. The expected location is `graphify-out/graph.json` relative to the **current working directory** (i.e. the project root where you are running commands). If it exists AND the user's request is a natural-language question about the codebase (e.g. "How does X work?", "What calls Y?", "Trace the data flow through Z") and NOT an explicit rebuild command (`--update`, `--cluster-only`, or a bare path/URL that implies fresh extraction): **skip Steps 1–5 entirely and jump straight to `## For /graphify query`.** Run `graphify query "<question>"` immediately. Do not run detect. Do not check corpus size. Do not ask the user to narrow. The graph is already built — use it.
If no path was given, use `.` (current directory). Do not ask the user for a path.
If the path argument starts with `https://github.com/` or `http://github.com/`, treat it as a GitHub URL - run Step 0 before anything else, then continue with the resolved local path.
Follow these steps in order unless the fast path above applies.
### Step 0 - GitHub repos and multi-path merge (only if a URL or several paths)
Only when the path is one or more `https://github.com/...` URLs, or several local subfolders to merge. See `references/github-and-merge.md` for the clone, cross-repo merge, and monorepo flow, then continue with the resolved local path. A plain local path skips this step.
### Step 1 - Ensure graphify is installed
```bash
# Detect the correct Python interpreter (handles uv tool, pipx, venv, system installs)
PYTHON=""
GRAPHIFY_BIN=$(which graphify 2>/dev/null)
# 1. uv tool installs — most reliable on modern Mac/Linux
if [ -z "$PYTHON" ] && command -v uv >/dev/null 2>&1; then
_UV_PY=$(uv tool run --from graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
fi
# 2. Read shebang from graphify binary (pipx and direct pip installs)
if [ -z "$PYTHON" ] && [ -n "$GRAPHIFY_BIN" ]; then
_SHEBANG=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
case "$_SHEBANG" in
*[!a-zA-Z0-9/_.@-]*) ;;
*) "$_SHEBANG" -c "import graphify" 2>/dev/null && PYTHON="$_SHEBANG" ;;
esac
fi
# 3. Fall back to python3
if [ -z "$PYTHON" ]; then PYTHON="python3"; fi
if ! "$PYTHON" -c "import graphify" 2>/dev/null; then
if command -v uv >/dev/null 2>&1; then
uv tool install --upgrade graphifyy -q 2>&1 | tail -3
_UV_PY=$(uv tool run --from graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
else
"$PYTHON" -m pip install graphifyy -q 2>/dev/null \
|| "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3
fi
fi
# Write interpreter path for all subsequent steps (persists across invocations)
mkdir -p graphify-out
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
# Save scan root so `graphify update` (no args) knows where to look next time.
# The scan path is passed through a quoted heredoc, never substituted into the
# command line itself: a bare `cd <path>` (or an unquoted heredoc, which
# still expands $()/backticks in its body) would let a malicious path execute
# as shell code the moment this line runs.
"$PYTHON" -c "import os, sys; out_path = os.path.abspath('graphify-out/.graphify_root'); os.chdir(sys.stdin.readline().rstrip('\n')); open(out_path, 'w', encoding='utf-8').write(os.getcwd())" <<'GRAPHIFY_ROOT_EOF'
INPUT_PATH
GRAPHIFY_ROOT_EOF
```
If the import succeeds, print nothing and move straight to Step 2.
**In every subsequent bash block, replace `python3` with `$(cat graphify-out/.graphify_python)` to use the correct interpreter.**
### Step 2 - Detect files
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.detect import detect
from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
# Write the sidecar from Python, not a shell redirect, so the same block renders
# on PowerShell hosts without console-encoding drift (#2528).
Path('graphify-out/.graphify_detect.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
print(f'Detected {result[\"total_files\"]} files')
"
```
Replace INPUT_PATH with the actual path the user provided. Do NOT cat or print the JSON - read it silently and present a clean summary instead:
```
Corpus: X files · ~Y words
code: N files (.py .ts .go ...)
docs: N files (.md .txt ...)
papers: N files (.pdf ...)
images: N files
video: N files (.mp4 .mp3 ...)
```
Omit any category with 0 files from the summary.
Then act on it:
- If `total_files` is 0: stop with "No supported files found in [path]."
- If `skipped_sensitive` is non-empty: report the count and list the skipped file names, so a wrongly-flagged source or doc is visible and can be renamed or moved (#2106).
- If `total_words` > 2,000,000 OR `total_files` > 500: show the warning. Then compute the top 5 first-level subdirectories by file count:
- Read `scan_root` from the detect JSON (always an absolute path to the resolved INPUT_PATH).
- Concatenate all file lists across all types (`code`, `document`, `paper`, `image`, `video`).
- Filter out any path that starts with `scan_root + "/graphify-out/"` to exclude converted sidecars.
- For each file, strip the `scan_root` prefix and take the first path component. Files directly in `scan_root` with no subdirectory count as `(root)`.
- If all files are in `(root)` with no subdirectories, do not ask to narrow — no subfolders exist. Instead suggest `--no-cluster` to skip the expensive clustering step and proceed.
- Otherwise rank by count, show the top 5 with file counts, then ask which subfolder to run on. Wait for the user's answer before proceeding.
- Otherwise: proceed directly to Step 2.5 if video files were detected, or Step 3 if not.
### Step 2.5 - Video and audio (only if video files detected)
Skip this step entirely if `detect` returned zero `video` files. When the corpus has video or audio, see `references/transcribe.md` to transcribe them to text first, then treat the transcripts as doc files in Step 3.
### Step 3 - Extract entities and relationships
**Before starting:** note whether `--mode deep` was given. You must pass `DEEP_MODE=true` to every subagent in Step B2 if it was. Track this from the original invocation - do not lose it.
This step has two parts: **structural extraction** (deterministic, free) and **semantic extraction** (LLM, costs tokens).
> **graphify needs no API key. Never ask the user for one, and never block on one.** Code is extracted structurally (AST) with no LLM and no key at all — a code-only corpus (the common `/graphify .` on a repo) skips semantic extraction entirely, so it needs nothing here: go straight to Part A and skip Part B. Semantic extraction (only for docs, papers, and images) uses Gemini **only if** `GEMINI_API_KEY`/`GOOGLE_API_KEY` is already set; otherwise the host agent itself is the LLM. graphify does **not** read `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or any other provider key. If you catch yourself about to prompt for, wait on, or stop because of a missing API key, that is a misread of this skill — proceed without one.
**Before semantic extraction:** check whether `GEMINI_API_KEY` or `GOOGLE_API_KEY` is set. If neither is set, print this one-liner to the user:
> Tip: set `GEMINI_API_KEY` or `GOOGLE_API_KEY` to use Gemini for semantic extraction (`pip install 'graphifyy[gemini]'`).
Print it once, then continue — do not wait for the user to supply a key. If `GEMINI_API_KEY` or `GOOGLE_API_KEY` IS set, use `graphify.llm.extract_corpus_parallel(files, backend="gemini")` for semantic extraction instead of dispatching subagents. The default Gemini model is `gemini-3-flash-preview`; set `GRAPHIFY_GEMINI_MODEL` or pass `--model` in headless CLI flows to override it.
> **No other API keys are read.** When `GEMINI_API_KEY`/`GOOGLE_API_KEY` are unset, semantic extraction falls to the host agent itself — the running session is the LLM. On a host that dispatches subagents (e.g. Claude Code), dispatch them as written in Part B. On a host that runs the CLI directly in a terminal and cannot dispatch subagents, do not stall: a code-only corpus has no semantic work, so write the empty semantic file (Part B "Fast path") and continue to Part C; for a corpus with docs/papers/images, either set a Gemini key or extract those inline yourself, but in no case prompt for `ANTHROPIC_API_KEY` — that prompt is a misread of this skill.
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs/papers.
#### Part A - Structural extraction for code files
For any code files detected, run AST extraction in parallel with Part B subagents:
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.extract import collect_files, extract
from pathlib import Path
import json
code_files = []
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
for f in detect.get('files', {}).get('code', []):
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
if code_files:
# root= anchors node ids and source_file on the scan root; cache_root only says
# where graphify-out/cache lives. Pass both: without root= the anchor falls back
# to cache_root, so pointing the cache elsewhere would rename every node (#3727).
result = extract(code_files, cache_root=Path('INPUT_PATH'), root=Path('INPUT_PATH'))
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
else:
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding=\"utf-8\")
print('No code files - skipping AST extraction')
"
```
#### Part B - Semantic extraction (parallel subagents)
**Fast path:** If detection found zero docs, papers, and images (code-only corpus), skip Part B entirely and go straight to Part C. AST handles code - there is nothing for semantic subagents to do. **First write an empty semantic file** so Part C's merge has its input (it reads `.graphify_semantic.json` unconditionally; without this a code-only run hits `FileNotFoundError`):
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
"
```
**MANDATORY: You MUST use the Agent tool here. Reading files yourself one-by-one is forbidden - it is 5-10x slower. If you do not use the Agent tool you are doing this wrong.**
Before dispatching subagents, print a timing estimate:
- Load `total_words` and file counts from `graphify-out/.graphify_detect.json`
- Estimate agents needed: `ceil(uncached_non_code_files / 22)` (chunk size is 20-25 files, capped at ~6000 total lines)
- Estimate time: ~45s per agent batch (they run in parallel, so total ≈ 45s × ceil(agents/parallel_limit))
- Print: "Semantic extraction: ~N files → X agents, estimated ~Ys"
**Step B0 - Check extraction cache first**
Before dispatching any subagents, check which files already have cached extraction results:
SPEC_PATH below is the **absolute** path of the `references/extraction-spec.md` that ships beside this SKILL.md — the same file Step B2 loads and hands to every subagent. It is the extraction prompt, so cache entries are attributed to it: when a graphify upgrade changes the prompt, entries produced by the old one are re-extracted instead of replayed, and unchanged prompts keep their entries (#1939). Substitute the real path in both Step B0 and Step B3 — pass the same one to each, and do not drop the argument.
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.cache import check_semantic_cache
from pathlib import Path
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
# Only content files go to semantic extraction. Code is already covered structurally
# by the AST pass (Part A); flattening every category here makes subagents re-read
# every source file (#1392). Video is transcribed to a document in Step 2.5 first.
all_files = [f for cat in ('document', 'paper', 'image') for f in detect['files'].get(cat, [])]
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files, root='INPUT_PATH', prompt_file='SPEC_PATH')
# Always (re)write the cache file: write hits, else DELETE any leftover from a prior
# run so Part C never merges a stale .graphify_cached.json (#1392).
if cached_nodes or cached_edges or cached_hyperedges:
Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}, ensure_ascii=False), encoding=\"utf-8\")
else:
Path('graphify-out/.graphify_cached.json').unlink(missing_ok=True)
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached), encoding=\"utf-8\")
# Nothing has been dispatched yet, so any chunk file on disk is a leftover from an
# interrupted run, and Step B3 merges every .graphify_chunk_*.json it finds.
for stale in Path('graphify-out').glob('.graphify_chunk_*.json'):
stale.unlink()
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
"
```
Only dispatch subagents for files listed in `graphify-out/.graphify_uncached.txt`. If all files are cached, skip Steps B1 and B2 but still run Step B3's commands: its merge is the only Part B step that writes `graphify-out/.graphify_semantic.json`, and Part C reads that file unconditionally. Do not write an empty `.graphify_semantic.json` instead, because that drops every cached node.
**Step B1 - Split into chunks**
Load files from `graphify-out/.graphify_uncached.txt`. Split into chunks bounded by BOTH limits: at most 20-25 files AND at most ~6000 total lines per chunk. A text file longer than 2000 lines gets a chunk to itself - that is past the Read tool's single-call cap, so sharing a chunk with other files guarantees it is only partly read. Each image gets its own chunk (vision needs separate context). When splitting, group files from the same directory together so related artifacts land in the same chunk and cross-file relationships are more likely to be extracted.
Both bounds matter. The line bound is not only about the 2000-line Read cap: a subagent holding 25 files splits its attention across all of them and skims the dense ones, and a 590-line plan can come back with zero nodes that way. Bounding content as well as file count is what keeps a chunk's coverage honest (#2225).
**Step B2 - Dispatch ALL subagents in a single message**
Call the Agent tool multiple times IN THE SAME RESPONSE - one call per chunk. This is the only way they run in parallel. If you make one Agent call, wait, then make another, you are doing it sequentially and defeating the purpose.
**IMPORTANT - subagent type:** Always use `subagent_type="general-purpose"`. Do NOT use `Explore` - it is read-only and cannot write chunk files to disk, which silently drops extraction results. General-purpose has Write and Bash access which the subagent needs.
Concrete example for 3 chunks:
```
[Agent tool call 1: files 1-15, subagent_type="general-purpose"]
[Agent tool call 2: files 16-30, subagent_type="general-purpose"]
[Agent tool call 3: files 31-45, subagent_type="general-purpose"]
```
All three in one message. Not three separate messages.
Each subagent receives this exact prompt (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
CHUNK_PATH must be an **absolute** path — derive it before dispatching:
```bash
PROJECT_ROOT=$(pwd) # cwd — where Part C globs graphify-out/ (NOT .graphify_root/scan dir, #1392)
# Then for chunk N: CHUNK_PATH="${PROJECT_ROOT}/graphify-out/.graphify_chunk_0N.json"
```
Subagent prompt template:
See `references/extraction-spec.md` for the exact subagent prompt (JSON schema, node-ID rules, confidence rubric, frontmatter, hyperedge, and vision rules). Load it only here, only when at least one chunk holds a doc, paper, or image; a pure-code corpus has skipped Part B and never reads it. Pass each subagent that prompt verbatim with FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH substituted, and have it write the result to CHUNK_PATH.
**Step B3 - Collect, cache, and merge**
Wait for all subagents. For each result:
- Check that `graphify-out/.graphify_chunk_NN.json` exists on disk — this is the success signal
- If the file exists and contains valid JSON with `nodes` and `edges`, include it and save to cache
- If the file is missing, the subagent was likely dispatched as read-only (Explore type) — print a warning: "chunk N missing from disk — subagent may have been read-only. Re-run with general-purpose agent." Do not silently skip.
- If a subagent failed or returned invalid JSON, print a warning and skip that chunk - do not abort
If more than half the chunks failed or are missing, stop and tell the user to re-run and ensure `subagent_type="general-purpose"` is used.
**Step B3.5 - Verify each reported file was actually read to its end**
A subagent that only read the first Read call's worth of a long file still writes a well-formed chunk, so "chunk file exists and parses" is not evidence of coverage. Compare each file's self-reported `coverage` against its real length:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
covered = {}
for c in sorted(glob.glob('graphify-out/.graphify_chunk_*.json')):
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
for src, n in (d.get('coverage') or {}).items():
covered[src] = max(covered.get(src, 0), int(n))
partial = []
for src, n in sorted(covered.items()):
p = Path(src)
if not p.is_absolute():
p = Path('INPUT_PATH') / src
if not p.is_file():
continue
total = sum(1 for _ in p.open(encoding='utf-8', errors='replace'))
if total and n < total:
partial.append((src, n, total))
Path('graphify-out/.graphify_partial.txt').write_text('\n'.join(s for s, _, _ in partial), encoding=\"utf-8\")
if partial:
print(f'WARNING: {len(partial)} file(s) were only partly read. They are cached as partial and retried on the next --update:')
for src, n, total in partial:
print(f' {src}: read {n} of {total} lines')
else:
print('Coverage OK - every file a subagent reported was read to its last line')
"
```
Tell the user which files came up short and what was lost (the line counts are printed above). The nodes already extracted for those files are kept - they are still true - but the file is cached as partial and left unstamped in the manifest below, so the next `--update` re-dispatches it and replace-on-re-extract swaps the partial node set for a complete one. This is the same mechanism the library path uses for a truncated LLM response (#933, #1950), so both paths now recover instead of silently keeping a half-read file forever. A file a subagent did not report at all is not counted as partial - there is nothing to compare against - which is why the prompt rule in `references/extraction-spec.md` asks for the count in the first place.
Merge all chunk files into `.graphify_semantic_new.json`. **After each Agent call completes, read the real token counts from the Agent tool result's `usage` field and write them back into the chunk JSON before merging** — the chunk JSON itself always has placeholder zeros. Then run:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, glob
from pathlib import Path
chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
all_nodes, all_edges, all_hyperedges = [], [], []
total_in, total_out = 0, 0
for c in chunks:
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
all_nodes += d.get('nodes', [])
all_edges += d.get('edges', [])
all_hyperedges += d.get('hyperedges', [])
total_in += d.get('input_tokens', 0)
total_out += d.get('output_tokens', 0)
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
'input_tokens': total_in, 'output_tokens': total_out,
}, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
"
```
Save new results to cache. Pass the same SPEC_PATH as Step B0 — it stamps each entry with the prompt that produced it, and a write under a different prompt than the read lands where the next run won't look (#1939):
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.cache import save_semantic_cache
from pathlib import Path
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
uncached = [line for line in Path('graphify-out/.graphify_uncached.txt').read_text(encoding=\"utf-8\").splitlines() if line]
# A partly-read file is cached with partial: True, which load_cached treats as a MISS,
# so the next --update re-dispatches it instead of serving a truncated extraction forever
# (#2225). Same contract the library path uses for a truncated LLM response (#933/#1950).
partial = [line for line in Path('graphify-out/.graphify_partial.txt').read_text(encoding=\"utf-8\").splitlines() if line] if Path('graphify-out/.graphify_partial.txt').exists() else []
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []), root='INPUT_PATH', allowed_source_files=uncached, prompt_file='SPEC_PATH', partial_source_files=partial)
note = f' ({len(partial)} left partial for retry)' if partial else ''
print(f'Cached {saved} files' + note)
"
```
Merge cached + new results into `graphify-out/.graphify_semantic.json`:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
all_nodes = cached['nodes'] + new.get('nodes', [])
all_edges = cached['edges'] + new.get('edges', [])
all_hyperedges = cached.get('hyperedges', []) + new.get('hyperedges', [])
seen = set()
deduped = []
for n in all_nodes:
if n['id'] not in seen:
seen.add(n['id'])
deduped.append(n)
merged = {
'nodes': deduped,
'edges': all_edges,
'hyperedges': all_hyperedges,
'input_tokens': new.get('input_tokens', 0),
'output_tokens': new.get('output_tokens', 0),
}
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached[\"nodes\"])} from cache, {len(new.get(\"nodes\",[]))} new)')
"
```
Clean up temp files: `rm -f graphify-out/.graphify_cached.json graphify-out/.graphify_uncached.txt graphify-out/.graphify_semantic_new.json`
#### Part C - Merge AST + semantic into final extraction
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from pathlib import Path
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text(encoding=\"utf-8\"))
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text(encoding=\"utf-8\"))
# Stamp tier provenance on the semantic side. build._is_ast_tier reads
# _origin when present and otherwise guesses from the SHAPE of
# source_location ('L<line>' means AST). A subagent that writes 'L12' for a
# doc section therefore made that node read as AST, and the next
# graphify update deleted it along with the re-extracted code file it
# seemed to belong to (#2843). extract() stamps its own items 'ast'; the
# semantic side must say so explicitly.
for n in sem['nodes']:
n.setdefault('_origin', 'semantic')
for e in sem['edges']:
e.setdefault('_origin', 'semantic')
# Merge: AST nodes first, semantic nodes deduplicated by id
seen = {n['id'] for n in ast['nodes']}
merged_nodes = list(ast['nodes'])
for n in sem['nodes']:
if n['id'] not in seen:
merged_nodes.append(n)
seen.add(n['id'])
merged_edges = ast['edges'] + sem['edges']
merged_hyperedges = sem.get('hyperedges', [])
merged = {
'nodes': merged_nodes,
'edges': merged_edges,
'hyperedges': merged_hyperedges,
'input_tokens': sem.get('input_tokens', 0),
'output_tokens': sem.get('output_tokens', 0),
}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding=\"utf-8\")
total = len(merged_nodes)
edges = len(merged_edges)
print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)')
"
```
### Step 4 - Build graph, cluster, analyze, generate outputs
**Before starting:** the code blocks below pass `directed=IS_DIRECTED` to `build_from_json()`. Replace `IS_DIRECTED` with `True` if `--directed` was given (builds a `DiGraph` preserving edge direction source→target), otherwise `False` (the default undirected `Graph`). Substitute it the same way you substitute `INPUT_PATH` — do not leave the literal `IS_DIRECTED` in the code.
```bash
mkdir -p graphify-out
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import cluster, score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from graphify.export import to_json
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
# root= mirrors the --update runbook (#1361): relativize source_file to the same
# base so the full build and incremental --update never drift apart on re-extract.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
# Guard BEFORE any write: an empty extraction must not clobber a good graph.json /
# GRAPH_REPORT.md / analysis sidecar. Check immediately after build (#1392).
if G.number_of_nodes() == 0:
print('ERROR: Graph is empty - extraction produced no nodes.')
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
raise SystemExit(1)
communities = cluster(G)
cohesion = score_all(G, communities)
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
gods = god_nodes(G)
surprises = surprising_connections(G, communities)
labels = {cid: 'Community ' + str(cid) for cid in communities}
# Placeholder questions - regenerated with real labels in Step 5
questions = suggest_questions(G, communities, labels)
# Export FIRST and honor the #479 shrink-guard: to_json returns False (writing
# nothing) when the new graph is smaller than the existing graph.json. Only write
# GRAPH_REPORT.md + the analysis sidecar when the graph was actually written, so
# they never describe a graph that graph.json doesn't contain (#1392).
wrote = to_json(G, communities, 'graphify-out/graph.json')
if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
raise SystemExit(1)
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
analysis = {
'communities': {str(k): v for k, v in communities.items()},
'cohesion': {str(k): v for k, v in cohesion.items()},
'gods': gods,
'surprises': surprises,
'questions': questions,
}
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'Graph: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges, {len(communities)} communities')
"
```
If this step prints `ERROR: Graph is empty`, stop and tell the user what happened - do not proceed to labeling or visualization.
Replace INPUT_PATH with the actual path.
### Step 4.5 - Graph health check (read-only integrity gate)
A non-destructive diagnostic on the extraction, before labeling. It surfaces edge collapse, dangling/missing endpoints, and self-loops — the silent-corruption modes of incremental updates and AST/LLM id mismatches. Read-only; never aborts.
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
from graphify.diagnostics import diagnose_extraction, format_diagnostic_report
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
summary = diagnose_extraction(extraction, directed=IS_DIRECTED, root='INPUT_PATH')
print(format_diagnostic_report(summary))
flags = [f'{summary[k]} {label}' for k, label in (
('dangling_endpoint_edges', 'dangling-endpoint edges'),
('missing_endpoint_edges', 'missing-endpoint edges'),
('self_loop_edges', 'self-loop edges'),
('directed_same_endpoint_collapsed_edges', 'collapsed (directed) edges'),
('undirected_same_endpoint_collapsed_edges', 'collapsed (undirected) edges'),
) if summary.get(k, 0)]
print('GRAPH HEALTH WARNING: ' + '; '.join(flags) + ' - graph may be incomplete/corrupt.' if flags else 'Graph health: OK (no dangling/missing/collapsed edges).')
"
```
Substitute `IS_DIRECTED` and `INPUT_PATH` as in Step 4. If a `GRAPH HEALTH WARNING` prints, surface it in the final summary (do not abort — the graph is still usable, but the integrity issue must be visible, per the Honesty Rules).
### Step 5 - Label communities
Read `graphify-out/.graphify_analysis.json`. For each community key, look at its node labels and write a 2-5 word plain-language name (e.g. "Attention Mechanism", "Training Pipeline", "Data Loading").
Then regenerate the report and save the labels for the visualizer:
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.build import build_from_json
from graphify.cluster import score_all
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
from graphify.report import generate
from graphify.export import to_json
from pathlib import Path
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
# root= as in Step 4 / the --update runbook (#1361) — same base for node-key parity.
G = build_from_json(extraction, root='INPUT_PATH', directed=IS_DIRECTED)
communities = {int(k): v for k, v in analysis['communities'].items()}
cohesion = {int(k): v for k, v in analysis['cohesion'].items()}
tokens = {'input': extraction.get('input_tokens', 0), 'output': extraction.get('output_tokens', 0)}
# LABELS - replace these with the names you chose above
labels = LABELS_DICT
# Regenerate questions with real community labels (labels affect question phrasing)
questions = suggest_questions(G, communities, labels)
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
# Re-export so graph.json nodes carry the curated community_name (#2490).
# Same extraction as Step 4, so the #479 shrink-guard passes on node count;
# if it still refuses, surface the guard message - do not force past it.
wrote = to_json(G, communities, 'graphify-out/graph.json', community_labels=labels)
if not wrote:
print('ERROR: refused to shrink graphify-out/graph.json (existing graph has more nodes; #479).')
print('If this shrink is intentional (you deleted files), re-run a full build with --force.')
print('Report updated with community labels')
"
```
Replace `LABELS_DICT` with the actual dict you constructed (e.g. `{0: "Attention Mechanism", 1: "Training Pipeline"}`).
Replace INPUT_PATH with the actual path.
### Step 6 - Generate Obsidian vault (opt-in) + HTML
**Generate HTML always** (unless `--no-viz`). **Obsidian vault only if `--obsidian` was explicitly given** — skip it otherwise, it generates one file per node.
If `--obsidian` was given:
- If `--obsidian-dir <path>` was also given, pass it via `--dir`. Otherwise defaults to `graphify-out/obsidian`.
```bash
graphify export obsidian
# or with custom dir: graphify export obsidian --dir ~/vaults/my-project
```
Generate the HTML graph (always, unless `--no-viz`):
```bash
graphify export html # auto-aggregates to community view if graph > 5000 nodes
# or: graphify export html --no-viz
```
### Steps 6b-8 - Wiki, Neo4j, FalkorDB, SVG, GraphML, MCP, benchmark (only on their flags)
These run only when their flag is present (`--wiki`, `--neo4j`/`--neo4j-push`, `--falkordb`/`--falkordb-push`, `--svg`, `--graphml`, `--mcp`) or, for the token-reduction benchmark, when `total_words` exceeds 5,000. A default run with no export flags skips all of them. See `references/exports.md` for each one. Run any `--wiki` export before Step 9 cleanup so `.graphify_labels.json` is still available.
---
### Step 9 - Save manifest, update cost tracker, clean up, and report
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
from datetime import datetime, timezone
from graphify.detect import save_manifest
# Save manifest for --update
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
# root= relativizes the manifest keys to the scan root (same base as the build),
# so the on-disk manifest is portable across clones/machines and a later --update
# matches cached files instead of missing every one (#1417).
#
# Only stamp semantic files (docs/papers/images) that ACTUALLY produced output:
# a detected file whose chunk failed or was omitted must stay unstamped so the
# next --update re-queues it, otherwise it is marked done and its content is lost
# forever (#2015). This mirrors the library extract path exactly
# (cli._stamped_manifest_files + clear_semantic + scan_corpus); do not stamp the
# raw corpus. Code files are always stamped (AST is deterministic); only semantic
# types are gated on output.
from graphify.cli import _stamped_manifest_files
_corpus = detect.get('all_files') or detect['files']
# A file a subagent only partly read DID produce output, so the stamp filter alone would
# keep it - but its node set covers just the head of the file, and stamping it means
# detect_incremental reads it as done and never re-queues it, leaving the truncated graph
# live forever. Name those files so they stay unstamped and are retried next run (#2225).
_pf = Path('graphify-out/.graphify_partial.txt')
_partial = {l.strip() for l in _pf.read_text(encoding=\"utf-8\").splitlines() if l.strip()} if _pf.exists() else set()
_manifest_files = _stamped_manifest_files(_corpus, extract, Path('INPUT_PATH'), partial_source_files=_partial)
# Files dispatched this run (the changed subset) but NOT stamped above still carry
# a stale semantic_hash from a prior run; clear it so detect_incremental re-queues
# them instead of reading them as unchanged (#1948).
_sem_types = ('document', 'paper', 'image')
_dispatched = {f for t, fl in detect['files'].items() if t in _sem_types for f in fl}
_stamped = {f for fl in _manifest_files.values() for f in fl}
_cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus (not the stamp-filtered subset) so in-root
# files newly excluded since last run are dropped rather than masquerading as
# deletions; untouched files' prior rows are still preserved (#1908).
_scan = {f for fl in _corpus.values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
# Update cumulative cost tracker
input_tok = extract.get('input_tokens', 0)
output_tok = extract.get('output_tokens', 0)
cost_path = Path('graphify-out/cost.json')
if cost_path.exists():
cost = json.loads(cost_path.read_text(encoding=\"utf-8\"))
else:
cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
cost['runs'].append({
'date': datetime.now(timezone.utc).isoformat(),
'input_tokens': input_tok,
'output_tokens': output_tok,
'files': detect.get('total_files', 0),
})
cost['total_input_tokens'] += input_tok
cost['total_output_tokens'] += output_tok
cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"utf-8\")
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
"
rm -f graphify-out/.graphify_detect.json graphify-out/.graphify_extract.json graphify-out/.graphify_ast.json graphify-out/.graphify_semantic.json graphify-out/.graphify_analysis.json graphify-out/.graphify_partial.txt
find graphify-out -maxdepth 1 -name '.graphify_chunk_*.json' -delete 2>/dev/null
rm -f graphify-out/.needs_update 2>/dev/null || true
```
Replace INPUT_PATH with the actual path (same value used in Steps 4-5) so the manifest is relativized to the scan root.
Tell the user (omit the obsidian line unless --obsidian was given):
```
Graph complete. Outputs in PATH_TO_DIR/graphify-out/
graph.html - interactive graph, open in browser
GRAPH_REPORT.md - audit report
graph.json - raw graph data
obsidian/ - Obsidian vault (only if --obsidian was given)
```
If graphify saved you time, consider supporting it: https://github.com/sponsors/safishamsi
Replace PATH_TO_DIR with the actual absolute path of the directory that was processed.
If PATH_TO_DIR is inside a git repository, add one line to the report: `graphify-out/` was written into the working tree, so unless the repository already ignores it, it will show in `git status`; the user can add `graphify-out/` to `.gitignore`, or commit only the outputs their team should share (see https://docs.graphify.com/guides/team-workflows).
Then paste these sections from GRAPH_REPORT.md directly into the chat:
- God Nodes
- Surprising Connections
- Suggested Questions
Do NOT paste the full report - just those three sections. Keep it concise.
Then immediately offer to explore. Pick the single most interesting suggested question from the report - the one that crosses the most community boundaries or has the most surprising bridge node - and ask:
> "The most interesting question this graph can answer: **[question]**. Want me to trace it?"
If the user says yes, run `/graphify query "[question]"` on the graph and walk them through the answer using the graph structure - which nodes connect, which community boundaries get crossed, what the path reveals. Keep going as long as they want to explore. Each answer should end with a natural follow-up ("this connects to X - want to go deeper?") so the session feels like navigation, not a one-shot report.
The graph is the map. Your job after the pipeline is to be the guide.
---
## Interpreter guard for subcommands
Before running any subcommand below (`--update`, `--cluster-only`, `query`, `path`, `explain`, `add`), check that `.graphify_python` exists. If it's missing (e.g. user deleted `graphify-out/`), re-resolve the interpreter first:
```bash
if [ ! -f graphify-out/.graphify_python ]; then
GRAPHIFY_BIN=$(which graphify 2>/dev/null)
if [ -n "$GRAPHIFY_BIN" ]; then
PYTHON=$(head -1 "$GRAPHIFY_BIN" | tr -d '#!')
case "$PYTHON" in *[!a-zA-Z0-9/_.@-]*) PYTHON="python3" ;; esac
else
PYTHON="python3"
fi
mkdir -p graphify-out
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
fi
```
## For --update and --cluster-only
Both are non-default subcommands. `--update` re-extracts only new or changed files; `--cluster-only` reruns clustering on the existing graph. See `references/update.md` for both flows.
---
## For /graphify query
When `graphify-out/graph.json` already exists and the user asks a question about the corpus, answer from the graph rather than rebuilding it:
```bash
graphify query "<question>"
```
Before traversal, expand the question against the graph's own vocabulary so a wording mismatch does not collapse the answer to noise. If the `graphify query` CLI is unavailable, fall back to an inline NetworkX traversal of `graphify-out/graph.json`. Answer using only what the graph output contains, and quote `source_location` when citing a specific fact. For that vocab-expansion step, the BFS/DFS traversal modes, the `--budget` cap, the NetworkX fallback, `save-result` feedback, and the `/graphify path` and `/graphify explain` flows, see `references/query.md`.
---
## For /graphify add and --watch
Neither is part of the default build. When the user runs `/graphify add <url>` to fetch a URL into the corpus, or passes `--watch` to auto-rebuild on file changes, see `references/add-watch.md`.
---
## For the commit hook and native CLAUDE.md integration
When the user asks to install the post-commit auto-rebuild hook or wire graphify into a project's CLAUDE.md, see `references/hooks.md`.
---
## Honesty Rules
- Never invent an edge. If unsure, use AMBIGUOUS.
- Never skip the corpus check warning.
- Always show token cost in the report.
- Never hide cohesion scores behind symbols - show the raw number.
- Never run HTML viz on a graph with more than 5,000 nodes without warning the user.
@@ -1,56 +0,0 @@
# graphify reference: add a URL and watch a folder
Load this when the user ran `/graphify add <url>` or passed `--watch`. Neither is part of the default build.
## For /graphify add
Fetch a URL and add it to the corpus, then update the graph.
```bash
$(cat graphify-out/.graphify_python) -c "
import sys
from graphify.ingest import ingest
from pathlib import Path
try:
out = ingest('URL', Path('./raw'), author='AUTHOR', contributor='CONTRIBUTOR')
print(f'Saved to {out}')
except ValueError as e:
print(f'error: {e}', file=sys.stderr)
sys.exit(1)
except RuntimeError as e:
print(f'error: {e}', file=sys.stderr)
sys.exit(1)
"
```
Replace `URL` with the actual URL, `AUTHOR` with the user's name if provided, `CONTRIBUTOR` likewise. If the command exits with an error, tell the user what went wrong - do not silently continue. After a successful save, automatically run the `--update` pipeline on `./raw` to merge the new file into the existing graph.
Supported URL types (auto-detected):
- YouTube / any video URL → audio downloaded via yt-dlp, transcribed to `.txt` on next run (requires `pip install 'graphifyy[video]'`)
- Twitter/X → fetched via oEmbed, saved as `.md` with tweet text and author
- arXiv → abstract + metadata saved as `.md`
- PDF → downloaded as `.pdf`
- Images (.png/.jpg/.webp) → downloaded, Claude vision extracts on next run
- Any webpage → converted to markdown via html2text
---
## For --watch
Start a background watcher that monitors a folder and auto-updates the graph when files change.
```bash
$(cat graphify-out/.graphify_python) -m graphify.watch "$(cat graphify-out/.graphify_root)" --debounce 3
```
This watches the same folder graphify extracted, read from the trusted `graphify-out/.graphify_root` that Step 1 resolved - there is no path to substitute, so a scan root containing shell metacharacters can never be re-interpreted here. Behavior depends on what changed:
- **Code files only (.py, .ts, .go, etc.):** re-runs AST extraction + rebuild + cluster immediately, no LLM needed. `graph.json` and `GRAPH_REPORT.md` are updated automatically.
- **Docs, papers, or images:** writes a `graphify-out/needs_update` flag and prints a notification to run `/graphify --update` (LLM semantic re-extraction required).
Debounce (default 3s): waits until file activity stops before triggering, so a wave of parallel agent writes doesn't trigger a rebuild per file.
Press Ctrl+C to stop.
For agentic workflows: run `--watch` in a background terminal. Code changes from agent waves are picked up automatically between waves. If agents are also writing docs or notes, you'll need a manual `/graphify --update` after those waves.
@@ -1,91 +0,0 @@
# graphify reference: extra exports and benchmark
Load this when the user passed one of the export flags (`--wiki`, `--neo4j`, `--neo4j-push`, `--falkordb`, `--falkordb-push`, `--svg`, `--graphml`, `--mcp`), or when the corpus is large enough for the token-reduction benchmark. Each step runs only for its own flag.
### Step 6b - Wiki (only if --wiki flag)
**Only run this step if `--wiki` was explicitly given in the original command.**
Run this before Step 9 (cleanup) so `.graphify_labels.json` is still available.
```bash
graphify export wiki
```
### Step 7 - Neo4j export (only if --neo4j or --neo4j-push flag)
**If `--neo4j`** - generate a Cypher file for manual import:
```bash
graphify export neo4j
```
**If `--neo4j-push`** - push directly to Neo4j using the destination URI supplied with the original `/graphify` command. Only push when this flag was explicitly given.
Pass the exact URI from the original `/graphify` command as one argument. When constructing a shell command, quote the URI for the shell that will execute the command (use `shlex.quote` for POSIX shells), or use a structured argument interface. Keep the URI as data; never interpolate it unquoted or evaluate it as shell code. Never replace a supplied URI with localhost. If the user explicitly requested a push but supplied no URI, use the documented local default. Do not print the URI or credentials in status output or generated artifacts.
```bash
graphify export neo4j --push 'bolt://remote-host:7687' --user neo4j
```
Default URI is `bolt://localhost:7687`, default user is `neo4j`. Prefer the `NEO4J_PASSWORD` environment variable so the password is kept off argv; ask for credentials only when needed. Uses MERGE - safe to re-run without creating duplicates.
### Step 7a - FalkorDB export (only if --falkordb or --falkordb-push flag)
**If `--falkordb`** - generate a Cypher file. The statements are OpenCypher, but FalkorDB's `GRAPH.QUERY` runs one statement at a time (no bulk script import like Neo4j's `cypher-shell`), so prefer `--falkordb-push` to load a graph. Use this only when you want the portable `cypher.txt` artifact:
```bash
graphify export falkordb
```
**If `--falkordb-push`** - push directly to FalkorDB using the destination URI supplied with the original `/graphify` command. Only push when this flag was explicitly given.
Pass the exact URI from the original `/graphify` command as one argument. When constructing a shell command, quote the URI for the shell that will execute the command (use `shlex.quote` for POSIX shells), or use a structured argument interface. Keep the URI as data; never interpolate it unquoted or evaluate it as shell code. Never replace a supplied URI with localhost. If the user explicitly requested a push but supplied no URI, use the documented local default. Do not print the URI or credentials in status output or generated artifacts. Credentials are optional; ask only if the instance requires authentication, and use `FALKORDB_PASSWORD` for a password rather than printing it.
```bash
graphify export falkordb --push 'falkordb://remote-host:6379'
```
Default URI is `falkordb://localhost:6379` (the scheme is informational - `redis://` or a bare `host:port` work too), auth is optional, and the target graph defaults to `graphify`. Uses MERGE - safe to re-run without creating duplicates.
### Step 7b - SVG export (only if --svg flag)
```bash
graphify export svg
```
### Step 7c - GraphML export (only if --graphml flag)
```bash
graphify export graphml
```
### Step 7d - MCP server (only if --mcp flag)
```bash
$(cat graphify-out/.graphify_python) -m graphify.serve graphify-out/graph.json
```
This starts a stdio MCP server that exposes tools: `query_graph`, `get_node`, `get_neighbors`, `get_community`, `god_nodes`, `graph_stats`, `shortest_path`. Add to Claude Desktop or any MCP-compatible agent orchestrator so other agents can query the graph live.
To configure in Claude Desktop, add to `claude_desktop_config.json`. Claude Desktop can't run `$(...)`, and under `uv tool install` the system `python3` can't import graphify — so set `command` to the **absolute interpreter path** printed by `cat graphify-out/.graphify_python`:
```json
{
"mcpServers": {
"graphify": {
"command": "<absolute path from: cat graphify-out/.graphify_python>",
"args": ["-m", "graphify.serve", "/absolute/path/to/graphify-out/graph.json"]
}
}
}
```
### Step 8 - Token reduction benchmark (only if total_words > 5000)
If `total_words` from `graphify-out/.graphify_detect.json` is greater than 5,000, run:
```bash
graphify benchmark
```
Print the output directly in chat. If `total_words <= 5000`, skip silently - the graph value is structural clarity, not token compression, for small corpora.
@@ -1,86 +0,0 @@
# graphify reference: extraction subagent prompt
Load this in Step 3 Part B when the corpus has at least one doc, paper, or image chunk. A pure-code corpus skips Part B and never reads this file. Each semantic subagent receives the prompt below verbatim (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
```
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
Output ONLY valid JSON matching the schema below - no explanation, no markdown fences, no preamble.
Files (chunk CHUNK_NUM of TOTAL_CHUNKS):
FILE_LIST
Read every file in this list COMPLETELY before extracting anything from it. The Read tool
returns at most 2000 lines per call and reports NO error and NO warning when it truncates, so a
long file silently yields a partial extraction. When a file is longer than one call, keep paging
with offset/limit until you have actually seen its last line - never assume the first call
returned the whole file. Never emit nodes for a file you have only partly read. A partial
extraction is worse than none: replace-on-re-extract first DROPS that file's existing nodes and
then re-adds only what you saw, so the unread tail disappears from the graph, and the file is then
recorded as successfully extracted and never retried (#2225).
Report the coverage you actually achieved, so a short read is caught instead of guessed at: add a
top-level "coverage" object mapping each FILE_LIST path you extracted to the number of lines you
read, e.g. {"coverage": {"docs/plan.md": 452}}. If you could not reach a file's last line, still
report the count you did read. A short count is recoverable - Step B3 warns, the entry is cached
as partial, and the next --update retries the file - whereas a missing entry is indistinguishable
from a complete read.
Rules:
- EXTRACTED: relationship explicit in source (import, call, citation, "see §3.2")
- INFERRED: reasonable inference (shared data structure, implied dependency)
- AMBIGUOUS: uncertain - flag for review, do not omit
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
Do not re-extract imports - AST already has those.
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). `file_type` MUST be one of exactly these six values: `code`, `document`, `paper`, `image`, `rationale`, `concept`. Any other value is invalid and will be rejected.
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction. `calls` edges MUST stay within one language: a Python function cannot `calls` a JS/TS/Go/Rust/Java symbol and vice versa — cross-language call edges are phantom artifacts, never emit them.
Image files: use vision to understand what the image IS - do not just OCR.
UI screenshot: layout patterns, design decisions, key elements, purpose.
Chart: metric, trend/insight, data source.
Tweet/post: claim as node, author, concepts mentioned.
Diagram: components and connections.
Research figure: what it demonstrates, method, result.
Handwritten/whiteboard: ideas and arrows, mark uncertain readings AMBIGUOUS.
DEEP_MODE (if --mode deep was given): be aggressive with INFERRED edges - indirect deps,
shared assumptions, latent couplings. Mark uncertain ones AMBIGUOUS instead of omitting.
Semantic similarity: if two concepts in this chunk solve the same problem or represent the same idea without any structural link (no import, no call, no citation), add a `semantically_similar_to` edge marked INFERRED with a confidence_score reflecting how similar they are (0.6-0.95). Examples:
- Two functions that both validate user input but never call each other
- A class in code and a concept in a paper that describe the same algorithm
- Two error types that handle the same failure mode differently
Only add these when the similarity is genuinely non-obvious and cross-cutting. Do not add them for trivially similar things.
Hyperedges: if 3 or more nodes clearly participate together in a shared concept, flow, or pattern that is not captured by pairwise edges alone, add a hyperedge to a top-level `hyperedges` array. Examples:
- All classes that implement a common protocol or interface
- All functions in an authentication flow (even if they don't all call each other)
- All concepts from a paper section that form one coherent idea
Use sparingly — only when the group relationship adds information beyond the pairwise edges. Maximum 3 hyperedges per chunk.
If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, author,
contributor onto every node from that file.
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
- EXTRACTED edges: confidence_score = 1.0 always
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
0.95 direct structural evidence (shared data structure, named cross-file reference).
0.85 strong inference (clear functional alignment, no direct symbol link).
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
0.65 weak inference (thematically related, no shape evidence).
0.55 speculative but plausible (surface-level co-occurrence only).
Models follow discrete rubrics better than continuous ranges; the bimodal
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
range guidance is being collapsed to a binary. If no value above fits, mark
the edge AMBIGUOUS rather than picking 0.4 or below.
- AMBIGUOUS edges: 0.1-0.3
Node ID format: lowercase, word characters only (`[^\W]` after casefolding — `[a-z0-9_]` for ASCII input, but non-ASCII letters and digits are kept as-is), no dots or slashes. Format: `{stem}_{entity}` where stem is the **full repo-relative path with the extension dropped**, every path segment kept and joined with `_` (each segment lowercased with non-alphanumeric chars replaced by `_`), and entity is the symbol name similarly normalized. Use every directory level, not just the immediate parent — this keeps same-named files in different directories distinct. Examples: `src/auth/session.py` + `ValidateToken` → `src_auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `lib_utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`; `docs/v1/api/README.md` + `getUser` → `docs_v1_api_readme_getuser`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or only the immediate parent (e.g., `auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project built under the old immediate-parent format, the user should run `graphify extract --force` to rebuild cleanly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
Generate the extraction JSON matching this schema exactly:
{"nodes":[{"id":"auth_session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"<FILE_LIST path verbatim>","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"<FILE_LIST path verbatim>","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"<FILE_LIST path verbatim>"}],"input_tokens":0,"output_tokens":0,"coverage":{"<FILE_LIST path verbatim>":0}}
source_file RULE (every node, edge, and hyperedge): set source_file to the path of the originating file EXACTLY as it appears in FILE_LIST — verbatim and absolute. Do NOT shorten to a basename, do NOT re-relativize, do NOT strip any directory prefix, and do NOT change separators (the engine canonicalizes separators and relativizes against the build root downstream). Copy the FILE_LIST entry character-for-character. This keeps the full build and incremental --update on the same base, so build_merge's replace-on-re-extract matches the existing node instead of accumulating a duplicate.
Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):
CHUNK_PATH
```
@@ -1,46 +0,0 @@
# graphify reference: GitHub clone and cross-repo merge
Load this when the user passed one or more `https://github.com/...` URLs, or named several local subfolders to merge into one graph.
### Step 0 - Clone GitHub repo(s) (only if a GitHub URL was given)
**Single repo:**
```bash
LOCAL_PATH=$(graphify clone <github-url> [--branch <branch>])
# Use LOCAL_PATH as the target for all subsequent steps
```
**Multiple repos (cross-repo graph):**
```bash
# Clone each repo, run the full pipeline on each, then merge
graphify clone <url1> # → ~/.graphify/repos/<owner1>/<repo1>
graphify clone <url2> # → ~/.graphify/repos/<owner2>/<repo2>
# Run /graphify on each local path to produce their graph.json files
# Then merge:
graphify merge-graphs \
~/.graphify/repos/<owner1>/<repo1>/graphify-out/graph.json \
~/.graphify/repos/<owner2>/<repo2>/graphify-out/graph.json \
--out graphify-out/cross-repo-graph.json
```
Graphify clones into `~/.graphify/repos/<owner>/<repo>` and reuses existing clones on repeat runs. Each node in the merged graph carries a `repo` attribute so you can filter by origin.
**Multiple local subfolders (monorepo or multi-service layout):**
The skill pipeline writes all intermediate and final outputs to `graphify-out/` in the current working directory. Running the skill on each subfolder separately will clobber the same output dir. Instead, use the CLI directly for each subfolder — it places `graphify-out/` *inside* the scanned path:
```bash
graphify extract ./core/ # → ./core/graphify-out/graph.json
graphify extract ./service/ # → ./service/graphify-out/graph.json
graphify extract ./platform/ # → ./platform/graphify-out/graph.json
# Add --backend gemini|kimi|openai|deepseek|claude-cli depending on which API key you have set
# Then merge at the project root:
graphify merge-graphs \
./core/graphify-out/graph.json \
./service/graphify-out/graph.json \
./platform/graphify-out/graph.json \
--out graphify-out/graph.json
```
Once `graphify-out/graph.json` exists, the fast path above takes over: any codebase question runs `graphify query` directly on the merged graph — no re-extraction, no size gate.
@@ -1,33 +0,0 @@
# graphify reference: commit hook and native CLAUDE.md integration
Load this when the user asked to install the post-commit hook or wire graphify into a project's CLAUDE.md.
## For git commit hook
Install a post-commit hook that auto-rebuilds the graph after every commit. No background process needed - triggers once per commit, works with any editor.
```bash
graphify hook install # install
graphify hook uninstall # remove
graphify hook status # check
```
After every `git commit`, the hook detects which code files changed (via `git diff HEAD~1`), re-runs AST extraction on those files, and rebuilds `graph.json` and `GRAPH_REPORT.md`. Doc/image changes are ignored by the hook - run `/graphify --update` manually for those.
If a post-commit hook already exists, graphify appends to it rather than replacing it.
---
## For native CLAUDE.md integration
Run once per project to make graphify always-on in Claude Code sessions:
```bash
graphify claude install
```
This writes a `## graphify` section to the local `CLAUDE.md` that instructs Claude to check the graph before answering codebase questions and rebuild it after code changes. No manual `/graphify` needed in future sessions.
```bash
graphify claude uninstall # remove the section
```
-317
View File
@@ -1,317 +0,0 @@
# graphify reference: query, path, explain
Load this when the user asks a question against an existing graph, or runs `/graphify path` or `/graphify explain`. The core's query stub points here for the full traversal flow. These flows use the `graphify query` CLI when it is available and fall back to an inline NetworkX traversal otherwise.
Two traversal modes - choose based on the question:
| Mode | Flag | Best for |
|------|------|----------|
| BFS (default) | _(none)_ | "What is X connected to?" - broad context, nearest neighbors first |
| DFS | `--dfs` | "How does X reach Y?" - trace a specific chain or dependency path |
First check the graph exists:
```bash
$(cat graphify-out/.graphify_python) -c "
from pathlib import Path
if not Path('graphify-out/graph.json').exists():
print('ERROR: No graph found. Run /graphify <path> first to build the graph.')
raise SystemExit(1)
"
```
If it fails, stop and tell the user to run `/graphify <path>` first.
### Step 0 — Constrained query expansion (REQUIRED before traversal)
graphify's `query` CLI matches nodes via case-folded substring + IDF — there is **no stemming, no synonyms, no cross-language match** inside the binary, and the inline fallback below matches the same way. If the user's question uses different language or different domain vocabulary than the graph's labels (user says "обработчик" / graph says "handler"; user says "authentication" / graph says "Guardian"), the literal matcher returns 0 hits and the answer collapses to noise.
Fix this **without inventing tokens** by expanding the query against the actual graph vocabulary first:
1. Extract the token vocabulary from node labels:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, re
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
vocab = set()
for n in data['nodes']:
for c in re.findall(r'[^\W\d_]+', n.get('label','') or '', re.UNICODE):
parts = re.findall(r'[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+', c) or [c]
for p in parts:
t = p.lower()
if 3 <= len(t) <= 30:
vocab.add(t)
Path('graphify-out/.vocab.txt').write_text('\n'.join(sorted(vocab)), encoding='utf-8')
print(f'vocab: {len(vocab)} tokens')
"
```
2. Read `graphify-out/.vocab.txt`. Then for the user's question, select **up to 12 tokens from this exact list** that semantically match the query intent. Hard constraints:
- You MUST pick only tokens present in the vocabulary file. Do NOT invent tokens.
- If a query concept has no plausible token in the vocab, skip it — do not substitute a near-synonym from training memory.
- If **no** vocab tokens match the query at all, output an empty list and tell the user the corpus has no relevant vocabulary for this question. Do not fabricate a search.
- Translate cross-language: Russian "аутентификация" → look for `auth`, `credential`, `token`, `security` IFF present in vocab.
- Morphology: "handlers" maps to `handler` IFF present; "todos" maps to `todo` IFF present.
3. Print the selection explicitly to the user before running the query, so the expansion is auditable:
```
Query expanded to (from graph vocab, N tokens): [token1, token2, ...]
```
If the list is empty, say so plainly and stop — do not proceed to traversal.
### Step 1 — Traversal
Build the **expanded query string** by joining the selected tokens with spaces. Use this string as `QUESTION` below — NOT the original user question. (The original question is preserved only for `save-result` at the end.)
Prefer the CLI when it is installed:
```bash
graphify query "QUESTION"
# or: graphify query "QUESTION" --dfs --budget 3000
```
If the CLI is unavailable, load `graphify-out/graph.json` and run the traversal inline:
1. Find the 1-3 nodes whose label best matches the expanded tokens.
2. Run the appropriate traversal from each starting node.
3. Read the subgraph - node labels, edge relations, confidence tags, source locations.
4. Answer using **only** what the graph contains. Quote `source_location` when citing a specific fact.
5. If the graph lacks enough information, say so - do not hallucinate edges.
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from networkx.readwrite import json_graph
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
G = json_graph.node_link_graph(data, edges='links')
question = 'QUESTION'
mode = 'MODE' # 'bfs' or 'dfs'
terms = [t.lower() for t in question.split() if len(t) >= 3] # match the vocab threshold; keeps api/jwt/ios (#1392)
# Find best-matching start nodes
scored = []
for nid, ndata in G.nodes(data=True):
label = ndata.get('label', '').lower()
score = sum(1 for t in terms if t in label)
if score > 0:
scored.append((score, nid))
scored.sort(reverse=True)
start_nodes = [nid for _, nid in scored[:3]]
if not start_nodes:
print('No matching nodes found for query terms:', terms)
sys.exit(0)
subgraph_nodes = set()
if mode == 'dfs':
# DFS: follow one path as deep as possible before backtracking.
# Depth-limited to 6 to avoid traversing the whole graph.
visited = set()
stack = [(n, 0) for n in reversed(start_nodes)]
while stack:
node, depth = stack.pop()
if node in visited or depth > 6:
continue
visited.add(node)
subgraph_nodes.add(node)
for neighbor in G.neighbors(node):
if neighbor not in visited:
stack.append((neighbor, depth + 1))
else:
# BFS: explore all neighbors layer by layer up to depth 3.
frontier = set(start_nodes)
subgraph_nodes = set(start_nodes)
for _ in range(3):
next_frontier = set()
for n in frontier:
for neighbor in G.neighbors(n):
if neighbor not in subgraph_nodes:
next_frontier.add(neighbor)
subgraph_nodes.update(next_frontier)
frontier = next_frontier
# Traversal chooses the nodes; collect relationships separately so seed edges,
# cycles, and cross-links are not lost just because both endpoints were visited.
# Taking the induced subgraph also keeps edges to nodes beyond the depth limit
# out of the result. data=True retains each edge's own attributes, including
# distinct parallel relationships in a MultiGraph.
subgraph_edges = [
(u, v, edge_data)
for u, v, edge_data in G.subgraph(subgraph_nodes).edges(data=True)
if u != v
]
# Token-budget aware output: rank by relevance, cut at budget (~4 chars/token)
token_budget = BUDGET # default 2000
char_budget = token_budget * 4
# Score each node by term overlap for ranked output
def relevance(nid):
label = G.nodes[nid].get('label', '').lower()
return sum(1 for t in terms if t in label)
ranked_nodes = sorted(subgraph_nodes, key=relevance, reverse=True)
lines = [f'Traversal: {mode.upper()} | Start: {[G.nodes[n].get(\"label\",n) for n in start_nodes]} | {len(subgraph_nodes)} nodes']
for nid in ranked_nodes:
d = G.nodes[nid]
lines.append(f' NODE {d.get(\"label\", nid)} [src={d.get(\"source_file\",\"\")} loc={d.get(\"source_location\",\"\")}]')
for u, v, edge_data in subgraph_edges:
if u in subgraph_nodes and v in subgraph_nodes:
lines.append(f' EDGE {G.nodes[u].get(\"label\",u)} --{edge_data.get(\"relation\",\"\")} [{edge_data.get(\"confidence\",\"\")}]--> {G.nodes[v].get(\"label\",v)}')
output = '\n'.join(lines)
if len(output) > char_budget:
output = output[:char_budget] + f'\n... (truncated at ~{token_budget} token budget - use --budget N for more)'
print(output)
"
```
Replace `QUESTION` with the **expanded** query string, `MODE` with `bfs` or `dfs`, and `BUDGET` with the token budget (default `2000`, or whatever `--budget N` specifies). Then answer based on the subgraph output above, using only what the graph contains.
After writing the answer, save it back into the graph so it improves future queries. Include the expanded tokens inside the `--answer` text (e.g. `"Expanded from original query via vocab: [tokens]. Then traversed..."`) so the next `--update` extracts the expansion history as a graph node:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "ORIGINAL_QUESTION" --answer "ANSWER" --type query --nodes NODE1 NODE2
```
Replace `ORIGINAL_QUESTION` with the user's verbatim question, `ANSWER` with your full answer text (containing the expanded-token trace), `NODE1 NODE2` with the list of node labels you cited. This closes the feedback loop: the next `--update` will extract this Q&A as a node in the graph.
**Work memory (self-improving loop).** Add an `--outcome` so future sessions learn from this one — append `--outcome useful|dead_end|corrected` to the `save-result` command (and `--correction "the right answer"` when correcting):
- `useful` — the cited nodes answered the question well (they become *preferred sources*).
- `dead_end` — the question/path led nowhere; don't re-derive it next time.
- `corrected` — the saved answer was wrong; `--correction` records what was right.
At the **start** of graph work, refresh and read the lessons: run `graphify reflect --if-stale` (cheap, deterministic, no LLM; `--if-stale` makes it a no-op when `LESSONS.md` is already newer than every input, e.g. when the git hook just refreshed it), then read `graphify-out/reflections/LESSONS.md`. It lists **preferred sources** (start there), **known dead ends** (skip them), and prior **corrections**. Running `reflect` yourself keeps the lessons current even without the git hook installed; if the post-commit hook *is* installed, `--if-stale` means your session-start run costs almost nothing.
---
## For /graphify path
Find the shortest path between two named concepts in the graph. Prefer the CLI when installed:
```bash
graphify path "NODE_A" "NODE_B"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
G = json_graph.node_link_graph(data, edges='links')
a_term = 'NODE_A'
b_term = 'NODE_B'
def find_node(term):
term = term.lower()
scored = sorted(
[(sum(1 for w in term.split() if w in G.nodes[n].get('label','').lower()), n)
for n in G.nodes()],
reverse=True
)
return scored[0][1] if scored and scored[0][0] > 0 else None
src = find_node(a_term)
tgt = find_node(b_term)
if not src or not tgt:
print(f'Could not find nodes matching: {a_term!r} or {b_term!r}')
sys.exit(0)
try:
path = nx.shortest_path(G, src, tgt)
print(f'Shortest path ({len(path)-1} hops):')
for i, nid in enumerate(path):
label = G.nodes[nid].get('label', nid)
if i < len(path) - 1:
_raw = G[nid][path[i+1]]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
print(f' {label} --{rel}--> [{conf}]')
else:
print(f' {label}')
except nx.NetworkXNoPath:
print(f'No path found between {a_term!r} and {b_term!r}')
except nx.NodeNotFound as e:
print(f'Node not found: {e}')
"
```
Replace `NODE_A` and `NODE_B` with the actual concept names from the user. Then explain the path in plain language - what each hop means, why it's significant.
After writing the explanation, save it back:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Path from NODE_A to NODE_B" --answer "ANSWER" --type path_query --nodes NODE_A NODE_B
```
---
## For /graphify explain
Give a plain-language explanation of a single node - everything connected to it. Prefer the CLI when installed:
```bash
graphify explain "NODE_NAME"
```
If the CLI is unavailable, run it inline:
```bash
$(cat graphify-out/.graphify_python) -c "
import json, sys
import networkx as nx
from networkx.readwrite import json_graph
from pathlib import Path
data = json.loads(Path('graphify-out/graph.json').read_text(encoding='utf-8'))
G = json_graph.node_link_graph(data, edges='links')
term = 'NODE_NAME'
term_lower = term.lower()
# Find best matching node
scored = sorted(
[(sum(1 for w in term_lower.split() if w in G.nodes[n].get('label','').lower()), n)
for n in G.nodes()],
reverse=True
)
if not scored or scored[0][0] == 0:
print(f'No node matching {term!r}')
sys.exit(0)
nid = scored[0][1]
data_n = G.nodes[nid]
print(f'NODE: {data_n.get(\"label\", nid)}')
print(f' source: {data_n.get(\"source_file\",\"unknown\")}')
print(f' type: {data_n.get(\"file_type\",\"unknown\")}')
print(f' degree: {G.degree(nid)}')
print()
print('CONNECTIONS:')
for neighbor in G.neighbors(nid):
_raw = G[nid][neighbor]; edge = next(iter(_raw.values()), {}) if isinstance(G, nx.MultiGraph) else _raw
nlabel = G.nodes[neighbor].get('label', neighbor)
rel = edge.get('relation', '')
conf = edge.get('confidence', '')
src_file = G.nodes[neighbor].get('source_file', '')
print(f' --{rel}--> {nlabel} [{conf}] ({src_file})')
"
```
Replace `NODE_NAME` with the concept the user asked about. Then write a 3-5 sentence explanation of what this node is, what it connects to, and why those connections are significant. Use the source locations as citations.
After writing the explanation, save it back:
```bash
$(cat graphify-out/.graphify_python) -m graphify save-result --question "Explain NODE_NAME" --answer "ANSWER" --type explain --nodes NODE_NAME
```
@@ -1,52 +0,0 @@
# graphify reference: transcribe video and audio
Load this only when `detect` reported one or more `video` files. A corpus with no video never reads this.
### Step 2.5 - Transcribe video / audio files (only if video files detected)
Skip this step entirely if `detect` returned zero `video` files.
Video and audio files cannot be read directly. Transcribe them to text first, then treat the transcripts as doc files in Step 3.
**Strategy:** Read the god nodes from `graphify-out/.graphify_detect.json` (or the analysis file if it exists from a previous run). You are already a language model — write a one-sentence domain hint yourself from those labels. Then pass it to Whisper as the initial prompt. No separate API call needed.
**However**, if the corpus has *only* video files and no other docs/code, use the generic fallback prompt: `"Use proper punctuation and paragraph breaks."`
**Step 1 - Write the Whisper prompt yourself.**
Read the top god node labels from detect output or analysis, then compose a short domain hint sentence, for example:
- Labels: `transformer, attention, encoder, decoder` → `"Machine learning research on transformer architectures and attention mechanisms. Use proper punctuation and paragraph breaks."`
- Labels: `kubernetes, deployment, pod, helm` → `"DevOps discussion about Kubernetes deployments and Helm charts. Use proper punctuation and paragraph breaks."`
**Export** it as `GRAPHIFY_WHISPER_PROMPT` (the exact name the transcriber reads — and it must be `export`ed so the child Python process sees it) for the next command.
**Step 2 - Transcribe:**
```bash
export GRAPHIFY_WHISPER_MODEL=base # or whatever --whisper-model the user passed (must be exported)
export GRAPHIFY_WHISPER_PROMPT="<the one-sentence domain hint you composed in Step 1>"
$(cat graphify-out/.graphify_python) -c "
import json, os, sys
from pathlib import Path
from graphify.transcribe import transcribe_all
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
video_files = detect.get('files', {}).get('video', [])
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
# Write the JSON from Python (NOT a shell '>' redirect): transcribe_all/Whisper
# print progress to stdout, which would otherwise corrupt the JSON file (#1392).
Path('graphify-out/.graphify_transcripts.json').write_text(json.dumps(transcript_paths, ensure_ascii=False), encoding=\"utf-8\")
print(f'Transcribed {len(transcript_paths)} file(s)', file=sys.stderr)
"
```
After transcription:
- Read the transcript paths from `graphify-out/.graphify_transcripts.json`
- Add them to the docs list before dispatching semantic subagents in Step 3B
- Print how many transcripts were created: `Transcribed N video file(s) -> treating as docs`
- If transcription fails for a file, print a warning and continue with the rest
**Whisper model:** Default is `base`. If the user passed `--whisper-model <name>`, `export GRAPHIFY_WHISPER_MODEL=<name>` (it must be exported, not just assigned) before running the command above.
@@ -1,221 +0,0 @@
# graphify reference: incremental update and cluster-only
Load this only when the user passed `--update` or `--cluster-only`. A first-time full build never reads this file.
## For --update (incremental re-extraction)
Use when you've added or modified files since the last run. Only re-extracts changed files - saves tokens and time.
```bash
$(cat graphify-out/.graphify_python) -c "
import sys, json
from graphify.detect import detect_incremental, save_manifest
from pathlib import Path
from graphify.paths import out_path
from graphify.watch import _read_build_excludes, _read_build_gitignore
result = detect_incremental(Path('INPUT_PATH'), extra_excludes=_read_build_excludes(out_path()), gitignore=_read_build_gitignore(out_path()))
new_total = result.get('new_total', 0)
nf = result.get('new_files', {})
print(json.dumps({
'new_total': new_total,
'deleted': len(result.get('deleted_files', [])),
'new_by_type': {t: len(v) for t, v in nf.items()},
'total_files': result.get('total_files'),
'total_words': result.get('total_words'),
'skipped_sensitive': result.get('skipped_sensitive', []),
}, indent=2, ensure_ascii=False))
print('Full result: graphify-out/.graphify_incremental.json')
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
deleted = list(result.get('deleted_files', []))
if new_total == 0 and not deleted:
print('No files changed since last run. Nothing to update.')
raise SystemExit(0)
if deleted:
print(f'{len(deleted)} deleted file(s) to prune.')
if new_total > 0:
print(f'{new_total} new/changed file(s) to re-extract.')
"
```
Then populate `.graphify_detect.json` so Steps 3A–6 (which read it unconditionally) see the right state for an incremental run. `files` carries the changed subset (drives Step 3A AST + Step 3B0 cache check on only what changed); `all_files` carries the full corpus for any step that needs corpus-wide context:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
r = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
Path('graphify-out/.graphify_detect.json').write_text(json.dumps({
'files': r.get('new_files', {}),
'all_files': r.get('files', {}),
'total_files': r.get('new_total', 0),
'total_words': r.get('total_words', 0),
'skipped_sensitive': r.get('skipped_sensitive', []),
'needs_graph': True,
}, ensure_ascii=False), encoding=\"utf-8\")
"
```
If new files exist, first check whether all changed files are code files:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
result = json.loads(open('graphify-out/.graphify_incremental.json', encoding='utf-8').read()) if Path('graphify-out/.graphify_incremental.json').exists() else {}
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc','.f','.F','.f90','.F90','.f95','.F95','.f03','.F03','.f08','.F08'}
new_files = result.get('new_files', {})
all_changed = [f for files in new_files.values() for f in files]
code_only = all(Path(f).suffix.lower() in code_exts for f in all_changed)
print('code_only:', code_only)
"
```
If `code_only` is True: print `[graphify update] Code-only changes detected - skipping semantic extraction (no LLM needed)`, run Step 3A (AST) on the changed files, then follow only Part B's **Fast path** to overwrite `.graphify_semantic.json` with an empty result and run Part C to create `.graphify_extract.json` from the fresh AST result. Skip semantic cache checks/writes and subagents (Steps B0–B3); do not reuse semantic sidecars from a prior run. Continue to the incremental merge and Steps 4–8 only after Part C has completed.
If `code_only` is False (any changed file is a doc/paper/image/video): **first, if any changed file is in `new_files['video']`, run `references/transcribe.md` (Step 2.5) on those files, then rewrite `.graphify_detect.json` to move the resulting transcript paths into `files['document']` and drop `files['video']`** — otherwise raw `.mp4/.mp3` paths are fed to semantic subagents as unreadable media (#1392). Then run the full Steps 3A–3C pipeline as normal.
If no new files exist (only deletions), create an empty extraction so the merge step can prune:
```bash
if [ ! -f graphify-out/.graphify_extract.json ]; then
echo '[graphify update] Only deletions -- creating empty extraction for merge.'
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
Path('graphify-out/.graphify_extract.json').write_text(json.dumps({'nodes':[],'edges':[],'hyperedges':[],'input_tokens':0,'output_tokens':0}), encoding='utf-8')
"
fi
```
Then:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from pathlib import Path
from graphify.build import build_merge
from graphify.detect import save_manifest
# Load new extraction and incremental state
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
deleted = list(incremental.get('deleted_files', []))
# prune_sources is ONLY for genuinely DELETED files. Changed/re-extracted files are
# handled by build_merge's replace-on-re-extract (#1344): every source_file in
# new_chunks is dropped from the base before merge, so old/stale nodes don't survive.
# Do NOT add changed here: with root= passed, prune_set relativizes to the same base
# as the freshly merged nodes and would DELETE the re-extracted content (#1178 is moot
# now that replace — not the dedup pass — reconciles changed files).
prune = list(deleted) or None
# Use build_merge() — reads graph.json directly without NetworkX round-trip
# so edge direction (calls, implements, imports) is always preserved (#801).
# Pass root= so prune_sources (absolute paths from detect_incremental) are
# relativized to match the graph's relative source_file values; without it
# nothing is pruned and stale nodes accumulate on every update (#1361).
# directed=IS_DIRECTED: replace IS_DIRECTED with True if --directed was given, else
# False. Without it a --directed --update silently rebuilds undirected and collapses
# reciprocal A<->B edges (#1392).
G = build_merge(
[new_extraction],
graph_path='graphify-out/graph.json',
prune_sources=prune,
root='INPUT_PATH',
directed=IS_DIRECTED,
)
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
# Write merged result back to .graphify_extract.json so Step 4 sees the full graph
merged_out = {
'nodes': [{'id': n, **d} for n, d in G.nodes(data=True)],
'edges': [
# Explicit source/target last so they win over any stale attrs in d.
{**{k: val for k, val in d.items() if k not in ('_src', '_tgt', 'source', 'target')},
'source': d.get('_src', u), 'target': d.get('_tgt', v)}
for u, v, d in G.edges(data=True)
],
# G.graph["hyperedges"] holds hyperedges from both existing graph.json
# and new_extraction (build_merge combines them). Falling back to
# new_extraction only would silently drop prior-run hyperedges (#801).
'hyperedges': list(G.graph.get('hyperedges', [])),
'input_tokens': new_extraction.get('input_tokens', 0),
'output_tokens': new_extraction.get('output_tokens', 0),
}
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged_out, ensure_ascii=False), encoding=\"utf-8\")
print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])} nodes, {len(merged_out[\"edges\"])} edges)')
# Save manifest so next --update diffs against today's state, not the
# prior run's baseline (prevents ghost-node reports on subsequent updates).
# root= matches the build_merge call above so the manifest keys stay relative to
# the scan root — portable across clones/machines, so --update keeps matching
# cached files instead of missing every one after a move (#1417).
#
# Only stamp semantic files (docs/papers/images) that ACTUALLY produced output
# THIS run (new_extraction is this run's fresh extraction, read above before the
# merge overwrote the file): a changed doc whose chunk failed must stay unstamped
# so the next --update re-queues it, otherwise it is marked done and its content
# is lost forever (#2015). Mirrors the library extract path
# (cli._stamped_manifest_files + clear_semantic + scan_corpus).
from graphify.cli import _stamped_manifest_files
_manifest_files = _stamped_manifest_files(incremental['files'], new_extraction, Path('INPUT_PATH'))
# Changed semantic files dispatched this run but NOT stamped had their chunk fail
# or be omitted; clear any stale semantic_hash so they are re-queued (#1948).
_sem_types = ('document', 'paper', 'image')
_dispatched = {f for t, fl in incremental.get('new_files', {}).items() if t in _sem_types for f in fl}
_stamped = {f for fl in _manifest_files.values() for f in fl}
_cleared = _dispatched - _stamped
# scan_corpus = the RAW full corpus so in-root files newly excluded since last run
# are dropped rather than masquerading as deletions; untouched rows preserved (#1908).
_scan = {f for fl in incremental['files'].values() for f in fl}
save_manifest(_manifest_files, root='INPUT_PATH', scan_corpus=_scan, clear_semantic=_cleared or None)
print('[graphify update] Manifest saved.')
"
```
Then run Steps 4–8 on the merged graph as normal.
After Step 4, show the graph diff:
```bash
$(cat graphify-out/.graphify_python) -c "
import json
from graphify.analyze import graph_diff
from graphify.build import build_from_json
from graphify.paths import load_node_link_graph
import networkx as nx
from pathlib import Path
# Load old graph (before update) from backup written before merge
old_data = json.loads(Path('graphify-out/.graphify_old.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_old.json').exists() else None
new_extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
G_new = build_from_json(new_extract, directed=IS_DIRECTED)
if old_data:
G_old = load_node_link_graph(old_data)
diff = graph_diff(G_old, G_new)
print(diff['summary'])
if diff['new_nodes']:
print('New nodes:', ', '.join(n['label'] for n in diff['new_nodes'][:5]))
if diff['new_edges']:
print('New edges:', len(diff['new_edges']))
"
```
Before the merge step, save the old graph: `cp graphify-out/graph.json graphify-out/.graphify_old.json`
Clean up after: `rm -f graphify-out/.graphify_old.json`
---
## For --cluster-only
Skip Steps 1–3. Re-run clustering on the existing graph:
```bash
graphify cluster-only .
```
`graphify cluster-only .` is **self-contained**: it re-clusters, names communities, and regenerates `GRAPH_REPORT.md`, `graph.json`, and `graph.html` from the existing graph. **Do not re-run Steps 5–9** — they read intermediate files (`.graphify_extract.json`, `.graphify_detect.json`, `.graphify_analysis.json`) that a prior build's cleanup (Step 9) already deleted, so they raise `FileNotFoundError` (#1392). When it finishes, present the refreshed `GRAPH_REPORT.md` summary as usual.
+3 -1
View File
@@ -7,6 +7,8 @@ alwaysApply: true
1. When creating a new pattern under `led-driver/src/patterns/`, also add/update a corresponding test file in `led-driver/tests/patterns/`.
2. When adding a new pattern, ensure led-controller has `db/pattern.json`; if it does not exist, create it. Add the new pattern metadata and parameter mappings there.
2. When adding a new pattern, ensure led-controller has `db/pattern.json`; if it does not exist, create it. Add the new pattern metadata and parameter mappings there. Optionally set **`supports_manual`** to `false` when the pattern is a poor fit for manual mode or audio beat triggers (smooth/blended animations); omit or `true` otherwise.
3. When adding a new pattern, add at least one test preset entry in `db/preset.json` in led-controller that uses the new pattern.
4. For any pattern that supports both auto and manual modes, keep behaviour parity unless explicitly requested otherwise: background colour handling, colour-cycling order, and parameter timing semantics (e.g. `n2`/`n3` meaning) must match between auto and manual paths.
@@ -0,0 +1,18 @@
---
description: Keep led-driver and led-tool git submodules in sync when updating led-controller
alwaysApply: true
---
# Submodule pointers (`led-driver`, `led-tool`)
This repo tracks **`led-driver`** and **`led-tool`** as git submodules (see `.gitmodules`).
When you **update led-controller** work that should ship with matching firmware or CLI behaviour—or when you finish changes **inside** those submodule directories—**record the new submodule commits in the parent repo**:
1. In each submodule, commit and push on its remote if there are local commits (or ensure the checkout is the intended revision).
2. From the **led-controller** root: `git add led-driver led-tool` after their HEADs point at the right commits.
3. Include the parent-repo commit that bumps the gitlinks (so CI and clones get consistent trees).
**Do not** leave submodule directories dirty or forgotten while presenting the parent repo as “done”: either commit the submodule pointer update in led-controller, or leave an explicit note if the user must push submodule remotes first.
If the user only asked for a submodule bump with no code edits, a single `chore(submodules): bump led-driver and led-tool` style commit is appropriate (see commit rule).
+11 -5
View File
@@ -28,13 +28,19 @@ Thumbs.db
scripts/.led-controller-venv
docs/.help-print.html
settings.json
# Track shared JSON + preset binaries; ignore other db/*.json (e.g. device, zone) locally
db/*
!db/group.json
!db/palette.json
!db/pattern.json
!db/preset.json
!db/profile.json
!db/scene.json
!db/sequence.json
!db/presets/
!db/presets/*.bin
*.log
*.db
*.sqlite
.pytest_cache/
.ropeproject/
build/
sdkconfig
sdkconfig.old
managed_components/
www_dist/
-10
View File
@@ -1,10 +0,0 @@
## graphify
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
Rules:
- When graphify-out/graph.json exists, run `graphify query "<question>"` before your first grep, search or source-file read for a codebase question, and put this rule in every subagent prompt that explores code. Read raw files only for lines the graph or an earlier read already located. Use `graphify path "<A>" "<B>"` for relationships and `graphify explain "<concept>"` for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output.
- If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
- 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.
-3
View File
@@ -1,3 +0,0 @@
cmake_minimum_required(VERSION 3.16)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(led_controller)
-142
View File
@@ -1,142 +0,0 @@
# Build, flash and monitor the ESP32-S3 controller (ESP-IDF in Docker).
#
# make build, flash, then monitor (same as: make all)
# make help list the targets
# make build minify the web UI, then build the firmware
# make flash flash the last build to the S3 (does not build)
# make monitor serial console (Ctrl-] to quit)
# make flash-monitor
#
# Override on the command line, e.g. make flash PORT=/dev/ttyACM1
PORT ?= /dev/ttyACM0
IDF_IMAGE ?= espressif/idf:v6.1
SECS ?= 10
DOCKER_RUN = docker run --rm -v "$(CURDIR)":/project -w /project
DEVICE = --device=$(PORT)
# Interactive terminal only when there is one (monitor needs it, CI does not have it)
TTY := $(shell [ -t 0 ] && echo -it)
# Rootless Docker maps container root to you, so files must end up owned by uid 0 inside; with a
# normal daemon they must be owned by you.
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
# Default target: build, flash, then open the console (run in order, so not with make -j)
all: build flash monitor
help:
@echo "LED controller (ESP32-S3):"
@echo " make [all] build, flash, then open the console"
@echo " make build minify + gzip the web UI, then build the firmware"
@echo " make flash flash the last build (firmware and web UI) to PORT ($(PORT)); does not build"
@echo " make ota [HOST=ip] build, then upload the firmware (web UI included) over Ethernet (no USB);"
@echo " HOST defaults to led-controller.local"
@echo " make monitor serial console on PORT (Ctrl-] to quit)"
@echo " make flash-monitor flash the last build, then open the console"
@echo " make log [SECS=10] print the console for SECS seconds and exit (no terminal needed)"
@echo " make web only rebuild the web UI (needs node/npx)"
@echo " make size memory use of the last build"
@echo " make menuconfig change the ESP-NOW channel, marker pin, W5500 pins, ..."
@echo " make erase erase the whole flash (loses the stored data)"
@echo " make clean remove the build directory (keeps sdkconfig)"
@echo " make fullclean also remove sdkconfig and the web UI output"
@echo " make test driver unit tests + C/Python envelope cross-check"
@echo " make test-api HOST=ip HTTP API tests against a running controller (data restored afterwards)"
@echo " make test-browser HOST=ip Selenium UI tests against a running controller (needs selenium + chromedriver)"
@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 test-sim rig tests (groups, field patterns, sequences) + the API tests against make sim"
@echo "variables: PORT=$(PORT) IDF_IMAGE=$(IDF_IMAGE)"
# --- web UI ---------------------------------------------------------------
web:
tools/build_web.sh
# --- firmware -------------------------------------------------------------
# The build time in the image comes from esp_app_desc.c, which nothing else recompiles (a web-only
# change just relinks), so drop its object and every build gets the current time.
APP_DESC_OBJ = build/esp-idf/esp_app_format/CMakeFiles/__idf_esp_app_format.dir/esp_app_desc.c.obj
build: web
$(DOCKER_RUN) $(IDF_IMAGE) bash -c 'rm -f $(APP_DESC_OBJ); idf.py build; rc=$$?; $(FIX_OWNER); exit $$rc'
flash:
$(DOCKER_RUN) $(DEVICE) $(IDF_IMAGE) bash -c 'idf.py -p $(PORT) flash; rc=$$?; $(FIX_OWNER); exit $$rc'
ota: HOST ?= led-controller.local
ota: build
python3 tools/ota.py $(HOST)
monitor:
$(DOCKER_RUN) $(TTY) $(DEVICE) $(IDF_IMAGE) idf.py -p $(PORT) monitor
flash-monitor: flash monitor
# Non-interactive: reset the board and print what it says for SECS seconds
log:
python3 tools/serial_log.py $(PORT) $(SECS)
size:
$(DOCKER_RUN) $(IDF_IMAGE) bash -c 'idf.py size; rc=$$?; $(FIX_OWNER); exit $$rc'
menuconfig:
$(DOCKER_RUN) -it $(IDF_IMAGE) bash -c 'idf.py menuconfig; rc=$$?; $(FIX_OWNER); exit $$rc'
erase:
$(DOCKER_RUN) $(DEVICE) $(IDF_IMAGE) idf.py -p $(PORT) erase-flash
clean:
rm -rf build
fullclean: clean
rm -rf sdkconfig sdkconfig.old www_dist
# --- tests ----------------------------------------------------------------
test: test-driver test-envelope
# Host-side unit tests for the driver's link layer and beat sync (pure Python)
test-driver:
python3 tools/run_driver_tests.py
# HTTP API tests (ported from v1) against a running controller; v1 features v2 lacks are xfail
test-api:
@test -n "$(HOST)" || { echo "usage: make test-api HOST=<controller ip>"; exit 1; }
python3 -m pytest test/api -q --host $(HOST)
# Selenium UI tests (ported from v1); they change the controller's data and do not restore it
test-browser:
@test -n "$(HOST)" || { echo "usage: make test-browser HOST=<controller ip>"; exit 1; }
LED_CONTROLLER_RUN_BROWSER_TESTS=1 LED_HOST=$(HOST) python3 -m pytest test/browser -q
# The C envelope packer must produce the same bytes as test/binary_envelope.py
test-envelope:
@tmp=$$(mktemp -d); \
(cd test && python3 env_check.py) > $$tmp/py.txt; \
docker run --rm -v "$(CURDIR)":/project -w /project/test $(IDF_IMAGE) bash -c \
'gcc -Wall -I/opt/esp/idf/components/json/cJSON env_host.c ../main/envelope.c /opt/esp/idf/components/json/cJSON/cJSON.c -o /tmp/t -lm && /tmp/t' 2>&1 | tail -4 | head -3 > $$tmp/c.txt; \
if diff -q $$tmp/py.txt $$tmp/c.txt >/dev/null; then echo "envelope: C and Python agree"; rm -rf $$tmp; \
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.
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
$(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)
test-sim:
python3 -m pytest test/api -q --host localhost:8080
+37
View File
@@ -0,0 +1,37 @@
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"
[packages]
mpremote = "*"
pyserial = "*"
pyserial-asyncio = "*"
esptool = "*"
pyjwt = "*"
watchfiles = "*"
requests = "*"
selenium = "*"
adafruit-ampy = "*"
microdot = "*"
fastapi = "*"
websockets = "*"
httpx = "*"
numpy = "*"
sounddevice = "*"
uvicorn = {extras = ["standard"], version = "*"}
[dev-packages]
pytest = "*"
[requires]
python_version = "3.11"
[scripts]
web = "python tests/web.py"
watch = "python -m watchfiles \"python tests/web.py\" src tests"
run = "sh -c 'cd src && uvicorn fastapi_app:app --host 0.0.0.0 --port \"${PORT:-80}\"'"
dev = "sh -c 'cd src && LED_CONTROLLER_LIVE_RELOAD=1 uvicorn fastapi_app:app --host 0.0.0.0 --port \"${PORT:-80}\" --reload --reload-dir . --reload-include \"**/*.html\" --reload-include \"**/*.css\" --reload-include \"**/*.js\" --reload-exclude \"**/db/**\" --reload-exclude \"**/settings.json\" --reload-exclude \"**/settings.json.*\"'"
test = "python -m pytest"
test-browser = "sh -c 'python tests/web.py > /tmp/led-controller-web.log 2>&1 & pid=$!; trap \"kill $pid\" EXIT; sleep 2; LED_CONTROLLER_RUN_BROWSER_TESTS=1 LED_CONTROLLER_DEVICE_IP=http://127.0.0.1:5000 python -m pytest tests/test_browser.py'"
test-browser-device = "sh -c 'LED_CONTROLLER_RUN_BROWSER_TESTS=1 python -m pytest tests/test_browser.py'"
Generated
+1447
View File
File diff suppressed because it is too large. Load diff
+31 -35
View File
@@ -1,50 +1,46 @@
# led-controller
ESP32-S3 controller for LED drivers: W5500 Ethernet, web UI, I2S microphone beat detection and an ESP-NOW link to the drivers. The firmware is C (ESP-IDF) at the repository root; see [`docs/BENCH_TEST.md`](docs/BENCH_TEST.md) for the bench tests.
LED controller web app for managing profiles, **zones**, presets, and colour palettes, and sending commands to LED devices over **ESP-NOW** (peer-to-peer on 2.4 GHz Wi‑Fi radio).
It keeps profiles, zones, presets, device groups, sequences, palettes, patterns and outputs in its flash, and serves the web UI and JSON API ([`docs/API.md`](docs/API.md)). Zones play to device groups. Sequences advance on the beats the microphone detects, or on a BPM clock while audio is stopped. Profiles, presets and sequences import and export as JSON bundles.
- **Bridge ESP32**: routes Pi traffic to drivers. The Pi connects over **WebSocket** (`bridge_transport`: `wifi`, `bridge_ws_url` e.g. `ws://192.168.4.1/ws`) or **USB serial** (`bridge_transport`: `serial`, `bridge_serial_port`).
- **LED drivers**: announce on boot via ESP-NOW broadcast; the controller registers them (MAC-keyed) and pushes group membership.
- Optional **Wi-Fi drivers** on the LAN still work over UDP discovery + outbound WebSocket.
- Architecture (diagrams): [docs/espnow-architecture.md](docs/espnow-architecture.md)
- Wire format (byte layouts): [docs/espnow-binary-protocol.md](docs/espnow-binary-protocol.md) (≤250 bytes per ESP-NOW frame; Pi ↔ bridge uses JSON devices envelope)
## Build and flash
## Run
```bash
make build # minify the web UI from web/, then build the firmware (ESP-IDF in Docker)
make flash # flash over USB
make ota [HOST=<ip>] # update firmware (web UI included) over Ethernet, no USB (POST /ota); HOST defaults to led-controller.local
make monitor # serial console
make test # driver unit tests and the C/Python envelope cross-check
make test-api HOST=<ip> # HTTP API tests against a running controller (its data is restored afterwards)
make test-browser HOST=<ip> # Selenium UI tests (needs selenium and chromedriver)
```
- One-time setup for port 80 without root: `sudo scripts/setup-port80.sh`
- Start app: `pipenv run run` (FastAPI + uvicorn; override listen port with **`PORT`**)
- Dev mode (uvicorn **`--reload`** on `src/` + browser refresh via `dev-live-reload.js`): `pipenv run dev`
- Regenerate **`docs/help.pdf`** from **`docs/help.md`**: `pipenv run help-pdf` (requires **pandoc** and **chromium** on the host)
`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.
## UI modes
## Other directories
- **Run mode**: focused control view. Select zones/presets and apply profiles. Editing actions are hidden.
- **Edit mode**: management view. Shows **Zones**, Presets, Patterns, Colour Palette, and Send Presets controls, plus per-tile preset edit/remove and drag-reorder.
- `led-driver/` (submodule): MicroPython firmware for the ESP32 LED drivers.
- `led-tool/` (submodule): `led-cli`, configures drivers over serial and updates the controller over Ethernet (`led-cli --ota HOST`).
- `led-simulator/` (submodule), `espnow-sender/`: test helpers.
- `db/`: the records a controller starts with (the `default` profile and group the firmware seeds at first boot, plus pattern metadata), importable with `PUT /db/<name>`.
- `test/api/`: the API tests (`test/api/README.md`); `test/browser/`: the UI tests.
## Profiles
## Docs
- Applying a profile updates session scope and refreshes the active zone content.
- In **Run mode**, Profiles supports apply-only behaviour (no create/clone/delete).
- In **Edit mode**, Profiles supports create/clone/delete.
- Creating a profile always creates a populated `default` zone (starter presets).
- Optional **DJ zone** seeding creates:
- `dj` zone bound to device name `dj`
- starter DJ presets (rainbow, single colour, transition)
- API reference: `docs/API.md`
- User guide: `docs/help.md` (`scripts/build_help_pdf.sh` regenerates `docs/help.pdf`)
- Specification: `docs/SPECIFICATION.md`
## Preset colours and palette linking
## Network
- In preset editor, selecting a colour picker value auto-adds it when the picker closes.
- Use **From Palette** to add a palette-linked preset colour.
- Linked colours are stored as palette references and shown with a `P` badge.
- When profile palette colours change, linked preset colours update across that profile.
The controller advertises `<hostname>.local` over mDNS (default `led-controller`, plus an `_http._tcp` service). Both settings below come from `/settings` and apply on reboot.
## API docs
`static_ips` is a list of networks to try, in order, each time the Ethernet link comes up. The first entry whose gateway answers ARP is used; if none does (or the list is empty) the controller uses DHCP. `netmask` defaults to `255.255.255.0`, `dns` to the gateway.
- Main API reference: `docs/API.md`
If DHCP gets no answer within 15 seconds, the controller takes `192.168.4.1/24`. For a cable straight from a PC, give the PC a static IP on that subnet, such as `192.168.4.2/24`, and open `http://192.168.4.1/`. The controller tries DHCP again only when the link next comes up.
## Driver pattern modules
```bash
curl -X PUT http://led-controller.local/settings/settings -H 'Content-Type: application/json' -d '{
"hostname": "stage",
"static_ips": [
{"ip": "192.168.1.50", "netmask": "255.255.255.0", "gw": "192.168.1.1"},
{"ip": "10.0.0.50", "netmask": "255.255.255.0", "gw": "10.0.0.1"}
]}'
```
Pattern **`.py`** sources live under **`led-driver/src/patterns`**. The Pi app resolves that path via `util.driver_patterns.driver_patterns_dir()`. If you deploy without that tree next to the app, set **`LED_CONTROLLER_PATTERNS_DIR`** to the directory that contains those files.
+19
View File
@@ -0,0 +1,19 @@
# bridge-serial
ESP32 ESP-NOW bridge with **USB/serial** uplink to the Pi (GPIO UART). Sync loop only — no asyncio, no Microdot.
```
bridge-serial/
src/
main.py # entry
settings.py # /settings.json on device
```
Deploy:
```bash
cd bridge-serial
python ../led-tool/cli.py -p /dev/ttyUSB0 --src -r -f
```
No `--lib` required. Match `serial_baudrate` on the ESP and Pi (e.g. `921600`).
+166
View File
@@ -0,0 +1,166 @@
"""ESP-NOW bridge: Pi USB-serial downlink, ESP-NOW to drivers (sync loop)."""
import gc, json, struct, time
import espnow, machine, network
from machine import Pin, UART
from settings import Settings
BROADCAST = b"\xff\xff\xff\xff\xff\xff"
WIRE = 0x4C
MAX_SERIAL = 4096
MAX_ESPNOW = 250
ESPNOW_EXIST = -12395
ESPNOW_FULL = -12392
def add_peer_if_needed(esp, dest, ch):
try:
esp.add_peer(dest, channel=ch)
except TypeError:
try:
esp.add_peer(dest)
except OSError as e:
if e.args[0] != ESPNOW_EXIST:
raise
except OSError as e:
if e.args[0] != ESPNOW_EXIST:
raise
def del_peer_if_present(esp, dest):
try:
esp.del_peer(dest)
except Exception:
pass
def send_unicast_temp_peer(esp, dest, ch, pkt):
try:
add_peer_if_needed(esp, dest, ch)
except OSError as e:
if e.args and e.args[0] == ESPNOW_FULL:
del_peer_if_present(esp, dest)
add_peer_if_needed(esp, dest, ch)
else:
raise
try:
esp.send(dest, pkt, True)
finally:
del_peer_if_present(esp, dest)
def init_radio(ch, name, password):
network.WLAN(network.STA_IF).active(False)
network.WLAN(network.AP_IF).active(False)
time.sleep_ms(100)
ap = network.WLAN(network.AP_IF)
ap.active(True)
time.sleep_ms(50)
if password:
try:
ap.config(essid=name or "bridge", password=password, channel=ch, hidden=True)
except TypeError:
ap.config(essid=name or "bridge", channel=ch)
else:
try:
ap.config(essid=name or "bridge", channel=ch, hidden=True)
except TypeError:
ap.config(essid=name or "bridge", channel=ch)
sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.config(pm=network.WLAN.PM_NONE)
try:
sta.config(channel=ch)
except Exception:
pass
def mac_bytes(addr):
h = str(addr).replace(":", "").replace("-", "").strip().lower()
return bytes.fromhex(h)
def read_serial(uart, buf):
if uart.any():
buf.extend(uart.read(min(uart.any(), 256)))
out = []
while len(buf) >= 2:
n = (buf[0] << 8) | buf[1]
if n > MAX_SERIAL:
buf[:] = buf[1:]
continue
need = 2 + n
if len(buf) < need:
break
out.append(bytes(buf[2:need]))
buf[:] = buf[need:]
return out
def downlink(esp, ch, raw):
if not raw:
return
if raw[0] == WIRE:
if len(raw) < 2:
return
esp.send(BROADCAST, raw, True)
return
if len(raw) < 8 or raw[0] != ord("{"):
return
try:
data = json.loads(raw)
except ValueError:
return
devs = data.get("dv") or data.get("devices")
if data.get("v") != "1" or not isinstance(devs, dict):
return
for mac_s, body in devs.items():
if not isinstance(body, dict):
continue
try:
msg = {"v": "1"}
msg.update(body)
pkt = json.dumps(msg, separators=(",", ":")).encode()
if len(pkt) > MAX_ESPNOW:
continue
dest = mac_bytes(mac_s)
except (ValueError, TypeError):
continue
if dest == BROADCAST:
esp.send(BROADCAST, pkt, True)
else:
send_unicast_temp_peer(esp, dest, ch, pkt)
time.sleep_ms(5)
gc.collect()
s = Settings()
ch = max(1, min(11, int(s.get("wifi_channel", 5))))
init_radio(ch, s.get("name"), s.get("ap_password") or "")
baud = int(s.get("serial_baudrate", 921600))
uart = UART(
int(s.get("serial_uart_id", 1)),
baud,
tx=Pin(int(s.get("serial_tx_pin", 2))),
rx=Pin(int(s.get("serial_rx_pin", 3))),
)
esp = espnow.ESPNow()
esp.active(True)
add_peer_if_needed(esp, BROADCAST, ch)
print("bridge ch", ch, "baud", baud, "heap", gc.mem_free())
wdt = machine.WDT(timeout=10000)
rx_buf = bytearray()
while True:
wdt.feed()
for frame in read_serial(uart, rx_buf):
try:
downlink(esp, ch, frame)
except OSError as e:
print("dl", e)
host, msg = esp.recv(0)
if host:
up = bytes([0]) + host + msg
uart.write(struct.pack(">H", len(up)) + up)
else:
time.sleep_ms(1)
+62
View File
@@ -0,0 +1,62 @@
import json
import time
import ubinascii
import network
WIFI_CHANNEL_DEFAULT = 5
def _sta_mac_hex():
sta = network.WLAN(network.STA_IF)
was_on = sta.active()
if not was_on:
sta.active(True)
time.sleep_ms(50)
try:
mac = ubinascii.hexlify(sta.config("mac")).decode().lower()
except Exception:
mac = "000000000000"
if not was_on:
sta.active(False)
return mac
class Settings(dict):
SETTINGS_FILE = "/settings.json"
def __init__(self):
super().__init__()
self.load()
def set_defaults(self):
self["name"] = "bridge-" + _sta_mac_hex()
self["wifi_channel"] = WIFI_CHANNEL_DEFAULT
self["ap_password"] = ""
self["serial_baudrate"] = 921600
self["serial_uart_id"] = 1
self["serial_tx_pin"] = 2
self["serial_rx_pin"] = 3
self["serial_usb"] = False
def save(self):
try:
with open(self.SETTINGS_FILE, "w") as f:
f.write(json.dumps(self))
except Exception as e:
print("save settings:", e)
def load(self):
try:
with open(self.SETTINGS_FILE, "r") as f:
loaded = json.load(f)
if not isinstance(loaded, dict):
raise ValueError("not object")
except Exception:
self.clear()
self.set_defaults()
self.save()
return
self.clear()
self.set_defaults()
for k, v in loaded.items():
self[k] = v
+22
View File
@@ -0,0 +1,22 @@
# bridge-wifi
ESP32 ESP-NOW bridge with **Wi‑Fi AP + WebSocket** (`/ws`). Same ESP-NOW downlink as bridge-serial.
```
bridge-wifi/
src/
main.py
settings.py
wifi_ap.py
espnow_wire.py # uplink frame helper only
lib/microdot/ # WebSocket server
```
Deploy:
```bash
cd bridge-wifi
python ../led-tool/cli.py -p /dev/ttyUSB0 --src --lib -r -f
```
Pi: join bridge AP, `bridge_ws_url` → `ws://192.168.4.1/ws`.
+2
View File
@@ -0,0 +1,2 @@
from microdot.microdot import Microdot, Request, Response, abort, redirect, \
send_file # noqa: F401
+8
View File
@@ -0,0 +1,8 @@
try:
from functools import wraps
except ImportError: # pragma: no cover
# MicroPython does not currently implement functools.wraps
def wraps(wrapped):
def _(wrapper):
return wrapper
return _
File diff suppressed because it is too large. Load diff
+225
View File
@@ -0,0 +1,225 @@
try:
import jwt
HAS_JWT = True
except ImportError:
HAS_JWT = False
try:
import ubinascii
except ImportError:
import binascii as ubinascii
try:
import uhashlib as hashlib
except ImportError:
import hashlib
try:
import uhmac as hmac
except ImportError:
try:
import hmac
except ImportError:
hmac = None
import json
from microdot.microdot import invoke_handler
from microdot.helpers import wraps
class SessionDict(dict):
"""A session dictionary.
The session dictionary is a standard Python dictionary that has been
extended with convenience ``save()`` and ``delete()`` methods.
"""
def __init__(self, request, session_dict):
super().__init__(session_dict)
self.request = request
def save(self):
"""Update the session cookie."""
self.request.app._session.update(self.request, self)
def delete(self):
"""Delete the session cookie."""
self.request.app._session.delete(self.request)
class Session:
"""Session handling
:param app: The application instance.
:param secret_key: The secret key, as a string or bytes object.
:param cookie_options: A dictionary with cookie options to pass as
arguments to :meth:`Response.set_cookie()
<microdot.Response.set_cookie>`.
"""
secret_key = None
def __init__(self, app=None, secret_key=None, cookie_options=None):
self.secret_key = secret_key
self.cookie_options = cookie_options or {}
if app is not None:
self.initialize(app)
def initialize(self, app, secret_key=None, cookie_options=None):
if secret_key is not None:
self.secret_key = secret_key
if cookie_options is not None:
self.cookie_options = cookie_options
if 'path' not in self.cookie_options:
self.cookie_options['path'] = '/'
if 'http_only' not in self.cookie_options:
self.cookie_options['http_only'] = True
app._session = self
def get(self, request):
"""Retrieve the user session.
:param request: The client request.
The return value is a session dictionary with the data stored in the
user's session, or ``{}`` if the session data is not available or
invalid.
"""
if not self.secret_key:
raise ValueError('The session secret key is not configured')
if hasattr(request.g, '_session'):
return request.g._session
session = request.cookies.get('session')
if session is None:
request.g._session = SessionDict(request, {})
return request.g._session
request.g._session = SessionDict(request, self.decode(session))
return request.g._session
def update(self, request, session):
"""Update the user session.
:param request: The client request.
:param session: A dictionary with the update session data for the user.
Applications would normally not call this method directly, instead they
would use the :meth:`SessionDict.save` method on the session
dictionary, which calls this method. For example::
@app.route('/')
@with_session
def index(request, session):
session['foo'] = 'bar'
session.save()
return 'Hello, World!'
Calling this method adds a cookie with the updated session to the
request currently being processed.
"""
if not self.secret_key:
raise ValueError('The session secret key is not configured')
encoded_session = self.encode(session)
@request.after_request
def _update_session(request, response):
response.set_cookie('session', encoded_session,
**self.cookie_options)
return response
def delete(self, request):
"""Remove the user session.
:param request: The client request.
Applications would normally not call this method directly, instead they
would use the :meth:`SessionDict.delete` method on the session
dictionary, which calls this method. For example::
@app.route('/')
@with_session
def index(request, session):
session.delete()
return 'Hello, World!'
Calling this method adds a cookie removal header to the request
currently being processed.
"""
@request.after_request
def _delete_session(request, response):
response.delete_cookie('session', **self.cookie_options)
return response
def encode(self, payload, secret_key=None):
"""Encode session data using JWT if available, otherwise use simple HMAC."""
if HAS_JWT:
return jwt.encode(payload, secret_key or self.secret_key,
algorithm='HS256')
else:
# Simple encoding for MicroPython: base64(json) + HMAC signature
key = (secret_key or self.secret_key).encode() if isinstance(secret_key or self.secret_key, str) else (secret_key or self.secret_key)
payload_json = json.dumps(payload)
payload_b64 = ubinascii.b2a_base64(payload_json.encode()).decode().strip()
# Create HMAC signature
if hmac:
# Use hmac module if available
h = hmac.new(key, payload_json.encode(), hashlib.sha256)
else:
# Fallback: simple SHA256(key + message)
h = hashlib.sha256(key + payload_json.encode())
signature = ubinascii.b2a_base64(h.digest()).decode().strip()
return f"{payload_b64}.{signature}"
def decode(self, session, secret_key=None):
"""Decode session data using JWT if available, otherwise use simple HMAC."""
if HAS_JWT:
try:
payload = jwt.decode(session, secret_key or self.secret_key,
algorithms=['HS256'])
except jwt.exceptions.PyJWTError: # pragma: no cover
return {}
return payload
else:
try:
# Simple decoding for MicroPython
if '.' not in session:
return {}
payload_b64, signature = session.rsplit('.', 1)
payload_json = ubinascii.a2b_base64(payload_b64).decode()
# Verify HMAC signature
key = (secret_key or self.secret_key).encode() if isinstance(secret_key or self.secret_key, str) else (secret_key or self.secret_key)
if hmac:
# Use hmac module if available
h = hmac.new(key, payload_json.encode(), hashlib.sha256)
else:
# Fallback: simple SHA256(key + message)
h = hashlib.sha256(key + payload_json.encode())
expected_signature = ubinascii.b2a_base64(h.digest()).decode().strip()
if signature != expected_signature:
return {}
return json.loads(payload_json)
except Exception:
return {}
def with_session(f):
"""Decorator that passes the user session to the route handler.
The session dictionary is passed to the decorated function as an argument
after the request object. Example::
@app.route('/')
@with_session
def index(request, session):
return 'Hello, World!'
Note that the decorator does not save the session. To update the session,
call the :func:`session.save() <microdot.session.SessionDict.save>` method.
"""
@wraps(f)
async def wrapper(request, *args, **kwargs):
return await invoke_handler(
f, request, request.app._session.get(request), *args, **kwargs)
return wrapper
+70
View File
@@ -0,0 +1,70 @@
from utemplate import recompile
_loader = None
class Template:
"""A template object.
:param template: The filename of the template to render, relative to the
configured template directory.
"""
@classmethod
def initialize(cls, template_dir='templates',
loader_class=recompile.Loader):
"""Initialize the templating subsystem.
:param template_dir: the directory where templates are stored. This
argument is optional. The default is to load
templates from a *templates* subdirectory.
:param loader_class: the ``utemplate.Loader`` class to use when loading
templates. This argument is optional. The default
is the ``recompile.Loader`` class, which
automatically recompiles templates when they
change.
"""
global _loader
_loader = loader_class(None, template_dir)
def __init__(self, template):
if _loader is None: # pragma: no cover
self.initialize()
#: The name of the template
self.name = template
self.template = _loader.load(template)
def generate(self, *args, **kwargs):
"""Return a generator that renders the template in chunks, with the
given arguments."""
return self.template(*args, **kwargs)
def render(self, *args, **kwargs):
"""Render the template with the given arguments and return it as a
string."""
return ''.join(self.generate(*args, **kwargs))
def generate_async(self, *args, **kwargs):
"""Return an asynchronous generator that renders the template in
chunks, using the given arguments."""
class sync_to_async_iter():
def __init__(self, iter):
self.iter = iter
def __aiter__(self):
return self
async def __anext__(self):
try:
return next(self.iter)
except StopIteration:
raise StopAsyncIteration
return sync_to_async_iter(self.generate(*args, **kwargs))
async def render_async(self, *args, **kwargs):
"""Render the template with the given arguments asynchronously and
return it as a string."""
response = ''
async for chunk in self.generate_async(*args, **kwargs):
response += chunk
return response
+231
View File
@@ -0,0 +1,231 @@
import binascii
import hashlib
from microdot import Request, Response
from microdot.microdot import MUTED_SOCKET_ERRORS, print_exception
from microdot.helpers import wraps
class WebSocketError(Exception):
"""Exception raised when an error occurs in a WebSocket connection."""
pass
class WebSocket:
"""A WebSocket connection object.
An instance of this class is sent to handler functions to manage the
WebSocket connection.
"""
CONT = 0
TEXT = 1
BINARY = 2
CLOSE = 8
PING = 9
PONG = 10
#: Specify the maximum message size that can be received when calling the
#: ``receive()`` method. Messages with payloads that are larger than this
#: size will be rejected and the connection closed. Set to 0 to disable
#: the size check (be aware of potential security issues if you do this),
#: or to -1 to use the value set in
#: ``Request.max_body_length``. The default is -1.
#:
#: Example::
#:
#: WebSocket.max_message_length = 4 * 1024 # up to 4KB messages
max_message_length = -1
def __init__(self, request):
self.request = request
self.closed = False
async def handshake(self):
response = self._handshake_response()
await self.request.sock[1].awrite(
b'HTTP/1.1 101 Switching Protocols\r\n')
await self.request.sock[1].awrite(b'Upgrade: websocket\r\n')
await self.request.sock[1].awrite(b'Connection: Upgrade\r\n')
await self.request.sock[1].awrite(
b'Sec-WebSocket-Accept: ' + response + b'\r\n\r\n')
async def receive(self):
"""Receive a message from the client."""
while True:
opcode, payload = await self._read_frame()
send_opcode, data = self._process_websocket_frame(opcode, payload)
if send_opcode: # pragma: no cover
await self.send(data, send_opcode)
elif data: # pragma: no branch
return data
async def send(self, data, opcode=None):
"""Send a message to the client.
:param data: the data to send, given as a string or bytes.
:param opcode: a custom frame opcode to use. If not given, the opcode
is ``TEXT`` or ``BINARY`` depending on the type of the
data.
"""
frame = self._encode_websocket_frame(
opcode or (self.TEXT if isinstance(data, str) else self.BINARY),
data)
await self.request.sock[1].awrite(frame)
async def close(self):
"""Close the websocket connection."""
if not self.closed: # pragma: no cover
self.closed = True
await self.send(b'', self.CLOSE)
def _handshake_response(self):
connection = False
upgrade = False
websocket_key = None
for header, value in self.request.headers.items():
h = header.lower()
if h == 'connection':
connection = True
if 'upgrade' not in value.lower():
return self.request.app.abort(400)
elif h == 'upgrade':
upgrade = True
if not value.lower() == 'websocket':
return self.request.app.abort(400)
elif h == 'sec-websocket-key':
websocket_key = value
if not connection or not upgrade or not websocket_key:
return self.request.app.abort(400)
d = hashlib.sha1(websocket_key.encode())
d.update(b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
return binascii.b2a_base64(d.digest())[:-1]
@classmethod
def _parse_frame_header(cls, header):
fin = header[0] & 0x80
opcode = header[0] & 0x0f
if fin == 0 or opcode == cls.CONT: # pragma: no cover
raise WebSocketError('Continuation frames not supported')
has_mask = header[1] & 0x80
length = header[1] & 0x7f
if length == 126:
length = -2
elif length == 127:
length = -8
return fin, opcode, has_mask, length
def _process_websocket_frame(self, opcode, payload):
if opcode == self.TEXT:
payload = payload.decode()
elif opcode == self.BINARY:
pass
elif opcode == self.CLOSE:
raise WebSocketError('Websocket connection closed')
elif opcode == self.PING:
return self.PONG, payload
elif opcode == self.PONG: # pragma: no branch
return None, None
return None, payload
@classmethod
def _encode_websocket_frame(cls, opcode, payload):
frame = bytearray()
frame.append(0x80 | opcode)
if opcode == cls.TEXT:
payload = payload.encode()
if len(payload) < 126:
frame.append(len(payload))
elif len(payload) < (1 << 16):
frame.append(126)
frame.extend(len(payload).to_bytes(2, 'big'))
else:
frame.append(127)
frame.extend(len(payload).to_bytes(8, 'big'))
frame.extend(payload)
return frame
async def _read_frame(self):
header = await self.request.sock[0].read(2)
if len(header) != 2: # pragma: no cover
raise WebSocketError('Websocket connection closed')
fin, opcode, has_mask, length = self._parse_frame_header(header)
if length == -2:
length = await self.request.sock[0].read(2)
length = int.from_bytes(length, 'big')
elif length == -8:
length = await self.request.sock[0].read(8)
length = int.from_bytes(length, 'big')
max_allowed_length = Request.max_body_length \
if self.max_message_length == -1 else self.max_message_length
if length > max_allowed_length:
raise WebSocketError('Message too large')
if has_mask: # pragma: no cover
mask = await self.request.sock[0].read(4)
payload = await self.request.sock[0].read(length)
if has_mask: # pragma: no cover
payload = bytes(x ^ mask[i % 4] for i, x in enumerate(payload))
return opcode, payload
async def websocket_upgrade(request):
"""Upgrade a request handler to a websocket connection.
This function can be called directly inside a route function to process a
WebSocket upgrade handshake, for example after the user's credentials are
verified. The function returns the websocket object::
@app.route('/echo')
async def echo(request):
if not authenticate_user(request):
abort(401)
ws = await websocket_upgrade(request)
while True:
message = await ws.receive()
await ws.send(message)
"""
ws = WebSocket(request)
await ws.handshake()
@request.after_request
async def after_request(request, response):
return Response.already_handled
return ws
def websocket_wrapper(f, upgrade_function):
@wraps(f)
async def wrapper(request, *args, **kwargs):
ws = await upgrade_function(request)
try:
await f(request, ws, *args, **kwargs)
except OSError as exc:
if exc.errno not in MUTED_SOCKET_ERRORS: # pragma: no cover
raise
except WebSocketError:
pass
except Exception as exc:
print_exception(exc)
finally: # pragma: no cover
try:
await ws.close()
except Exception:
pass
return Response.already_handled
return wrapper
def with_websocket(f):
"""Decorator to make a route a WebSocket endpoint.
This decorator is used to define a route that accepts websocket
connections. The route then receives a websocket object as a second
argument that it can use to send and receive messages::
@app.route('/echo')
@with_websocket
async def echo(request, ws):
while True:
message = await ws.receive()
await ws.send(message)
"""
return websocket_wrapper(f, websocket_upgrade)
+7
View File
@@ -0,0 +1,7 @@
"""WebSocket uplink framing (Pi ↔ bridge)."""
BROADCAST_MAC = b"\xff\xff\xff\xff\xff\xff"
def pack_ws_uplink(peer, espnow_packet):
return bytes([0]) + peer + espnow_packet
+218
View File
@@ -0,0 +1,218 @@
"""ESP-NOW bridge: Pi WebSocket downlink, ESP-NOW to drivers."""
import asyncio
import gc
import json
import time
import espnow
import machine
from espnow_wire import BROADCAST_MAC, pack_ws_uplink
from microdot import Microdot
from microdot.websocket import WebSocketError, with_websocket
from settings import Settings
from wifi_ap import init_bridge_network
BROADCAST = BROADCAST_MAC
WIRE = 0x4C
MAX_ESPNOW = 250
ESPNOW_EXIST = -12395
ESPNOW_FULL = -12392
def mac_str(mac):
return ":".join("%02x" % b for b in mac)
def dbg(msg):
if DEBUG:
print(msg)
def add_peer_if_needed(esp, dest, ch):
try:
esp.add_peer(dest, channel=ch)
dbg("peer add " + mac_str(dest))
except TypeError:
try:
esp.add_peer(dest)
dbg("peer add " + mac_str(dest))
except OSError as e:
if e.args[0] != ESPNOW_EXIST:
raise
dbg("peer exists " + mac_str(dest))
except OSError as e:
if e.args[0] != ESPNOW_EXIST:
raise
dbg("peer exists " + mac_str(dest))
def del_peer_if_present(esp, dest):
try:
esp.del_peer(dest)
dbg("peer del " + mac_str(dest))
except Exception as e:
dbg("peer del skip " + mac_str(dest) + " " + repr(e))
def send_espnow(esp, dest, pkt):
try:
esp.send(dest, pkt, True)
return True
except OSError as e:
label = "bcast" if dest == BROADCAST else mac_str(dest)
print("send err", label, len(pkt), e)
return False
def send_unicast_temp_peer(esp, dest, ch, pkt):
try:
add_peer_if_needed(esp, dest, ch)
except OSError as e:
# If peer table is full but this peer already exists, delete+retry once.
if e.args and e.args[0] == ESPNOW_FULL:
dbg("peer full " + mac_str(dest) + " retry")
del_peer_if_present(esp, dest)
add_peer_if_needed(esp, dest, ch)
else:
raise
ok = send_espnow(esp, dest, pkt)
del_peer_if_present(esp, dest)
return ok
def downlink(esp, ch, raw):
n = len(raw)
if not raw:
return
if raw[0] == WIRE:
if n < 2:
dbg("dl skip wire short " + str(n))
return
dbg("dl wire bcast " + str(n))
send_espnow(esp, BROADCAST, raw)
return
if n < 8 or raw[0] != ord("{"):
dbg("dl skip json " + str(n))
return
try:
data = json.loads(raw)
except ValueError:
dbg("dl skip json")
return
devs = data.get("dv") or data.get("devices")
if data.get("v") != "1" or not isinstance(devs, dict):
dbg("dl skip envelope")
return
dbg("dl env " + str(len(devs)) + " dev")
for mac_s, body in devs.items():
if not isinstance(body, dict):
dbg("dl skip body " + str(mac_s))
continue
try:
h = str(mac_s).replace(":", "").replace("-", "").strip().lower()
dest = BROADCAST if h == "ffffffffffff" else bytes.fromhex(h)
msg = {"v": "1"}
msg.update(body)
pkt = json.dumps(msg, separators=(",", ":")).encode()
if len(pkt) > MAX_ESPNOW:
dbg("dl skip big " + str(len(pkt)))
continue
except (ValueError, TypeError):
dbg("dl skip mac " + str(mac_s))
continue
if dest == BROADCAST:
dbg("dl bcast " + str(len(pkt)))
send_espnow(esp, BROADCAST, pkt)
else:
dbg("dl uni " + mac_str(dest) + " " + str(len(pkt)))
send_unicast_temp_peer(esp, dest, ch, pkt)
time.sleep_ms(5)
gc.collect()
settings = Settings()
DEBUG = bool(settings.get("debug", True))
ch = max(1, min(11, int(settings.get("wifi_channel", 5))))
init_bridge_network(settings)
esp = espnow.ESPNow()
esp.active(True)
add_peer_if_needed(esp, BROADCAST, ch)
print(
"bridge-wifi ch",
ch,
"debug",
DEBUG,
"heap",
gc.mem_free(),
"ws",
int(settings.get("ws_port", 80)),
)
app = Microdot()
clients = set()
wdt = machine.WDT(timeout=10000)
@app.route("/ws")
@with_websocket
async def ws_handler(request, ws):
clients.add(ws)
print("ws client +", len(clients))
try:
while True:
try:
raw = await ws.receive()
except WebSocketError:
dbg("ws closed")
break
if not raw:
dbg("ws empty")
break
if isinstance(raw, str):
raw = raw.encode("utf-8")
dbg("ws rx " + str(len(raw)))
try:
downlink(esp, ch, raw)
except OSError as e:
print("dl err", e)
finally:
clients.discard(ws)
print("ws client -", len(clients))
async def espnow_rx_loop():
while True:
host, msg = esp.recv(0)
if host:
dbg("up " + mac_str(host) + " " + str(len(msg)))
frame = pack_ws_uplink(host, msg)
dead = []
sent = 0
for ws in list(clients):
try:
await ws.send(frame)
sent += 1
except Exception as e:
dbg("ws up err " + repr(e))
dead.append(ws)
for ws in dead:
clients.discard(ws)
if not clients:
dbg("up no ws clients")
else:
dbg("up ws " + str(sent) + "/" + str(len(clients)))
else:
await asyncio.sleep_ms(1)
wdt.feed()
async def main():
asyncio.create_task(espnow_rx_loop())
port = int(settings.get("ws_port", 80))
print("ws listen", port)
await app.start_server(host="0.0.0.0", port=port)
asyncio.run(main())
+60
View File
@@ -0,0 +1,60 @@
import json
import time
import ubinascii
import network
WIFI_CHANNEL_DEFAULT = 5
def _sta_mac_hex():
sta = network.WLAN(network.STA_IF)
was_on = sta.active()
if not was_on:
sta.active(True)
time.sleep_ms(50)
try:
mac = ubinascii.hexlify(sta.config("mac")).decode().lower()
except Exception:
mac = "000000000000"
if not was_on:
sta.active(False)
return mac
class Settings(dict):
SETTINGS_FILE = "/settings.json"
def __init__(self):
super().__init__()
self.load()
def set_defaults(self):
self["name"] = "bridge-" + _sta_mac_hex()
self["wifi_channel"] = WIFI_CHANNEL_DEFAULT
self["ap_password"] = ""
self["ap_ip"] = "192.168.4.1"
self["ws_port"] = 80
self["debug"] = True
def save(self):
try:
with open(self.SETTINGS_FILE, "w") as f:
f.write(json.dumps(self))
except Exception as e:
print("save settings:", e)
def load(self):
try:
with open(self.SETTINGS_FILE, "r") as f:
loaded = json.load(f)
if not isinstance(loaded, dict):
raise ValueError("not object")
except Exception:
self.clear()
self.set_defaults()
self.save()
return
self.clear()
self.set_defaults()
for k, v in loaded.items():
self[k] = v
+52
View File
@@ -0,0 +1,52 @@
"""AP + STA for ESP-NOW; Pi joins the AP for WebSocket."""
import time
import network
from settings import WIFI_CHANNEL_DEFAULT
def _channel(settings):
try:
return max(1, min(11, int(settings.get("wifi_channel", WIFI_CHANNEL_DEFAULT))))
except (TypeError, ValueError):
return WIFI_CHANNEL_DEFAULT
def init_bridge_network(settings):
ch = _channel(settings)
essid = settings.get("name") or "bridge"
password = settings.get("ap_password") or ""
ap_ip = settings.get("ap_ip") or "192.168.4.1"
sta = network.WLAN(network.STA_IF)
ap = network.WLAN(network.AP_IF)
sta.active(False)
ap.active(False)
time.sleep_ms(100)
ap.active(True)
time.sleep_ms(50)
if password:
try:
ap.config(essid=essid, password=password, channel=ch)
except TypeError:
ap.config(essid=essid, channel=ch)
else:
ap.config(essid=essid, channel=ch)
try:
ap.ifconfig((ap_ip, "255.255.255.0", ap_ip, "8.8.8.8"))
except Exception:
pass
sta.active(True)
sta.config(pm=network.WLAN.PM_NONE)
try:
sta.config(channel=ch)
except Exception:
pass
port = int(settings.get("ws_port", 80))
print("bridge AP", essid, "ch", ch, "ip", ap.ifconfig()[0])
print("bridge_ws_url: ws://%s:%s/ws" % (ap_ip, port))
-6
View File
@@ -1,6 +0,0 @@
{
"enabled": true,
"device": "simulated",
"device_override": "",
"device_select": "simulated"
}
-16
View File
@@ -1,16 +0,0 @@
[
{
"id": "c9ab898d-740",
"label": "bridge1",
"transport": "ip",
"ip": "192.168.4.1",
"ws_port": 80
},
{
"id": "18d85e86-17b",
"label": "bridge2",
"transport": "serial",
"serial_port": "/dev/ttyUSB0",
"serial_baudrate": 115200
}
]
-1
View File
@@ -1 +0,0 @@
{}
+1 -1
View File
@@ -1 +1 @@
{"1": {"name": "default", "devices": [], "wifi_driver_display_name": null, "wifi_driver_num_leds": null, "wifi_color_order": null, "wifi_startup_mode": null, "output_brightness": 255, "bridge_id": null, "pattern": "on", "colors": ["000000", "FF0000"], "brightness": 100, "delay": 100, "step_offset": 0, "step_increment": 1, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "id": "1"}}
{"6": {"name": "winter top-left", "devices": ["a0b100000001"], "profile_id": "3", "wifi_color_order": "rgb", "wifi_startup_mode": "default", "output_brightness": 255, "pattern": "on", "colors": ["000000", "E8F4FF"], "brightness": 100, "delay": 100, "step_offset": 0, "step_increment": 1, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "wifi_driver_display_name": null, "wifi_driver_num_leds": null, "bridge_id": null}, "7": {"name": "winter top-centre", "devices": ["a0b100000002"], "profile_id": "3", "wifi_color_order": "rgb", "wifi_startup_mode": "default", "output_brightness": 255, "pattern": "on", "colors": ["000000", "E8F4FF"], "brightness": 100, "delay": 100, "step_offset": 0, "step_increment": 1, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "wifi_driver_display_name": null, "wifi_driver_num_leds": null, "bridge_id": null}, "8": {"name": "winter top-right", "devices": ["a0b100000003"], "profile_id": "3", "wifi_color_order": "rgb", "wifi_startup_mode": "default", "output_brightness": 255, "pattern": "on", "colors": ["000000", "E8F4FF"], "brightness": 100, "delay": 100, "step_offset": 0, "step_increment": 1, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "wifi_driver_display_name": null, "wifi_driver_num_leds": null, "bridge_id": null}, "9": {"name": "winter bottom-left", "devices": ["a0b100000004"], "profile_id": "3", "wifi_color_order": "rgb", "wifi_startup_mode": "default", "output_brightness": 255, "pattern": "on", "colors": ["000000", "E8F4FF"], "brightness": 100, "delay": 100, "step_offset": 0, "step_increment": 1, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "wifi_driver_display_name": null, "wifi_driver_num_leds": null, "bridge_id": null}, "10": {"name": "winter bottom-centre", "devices": ["a0b100000005"], "profile_id": "3", "wifi_color_order": "rgb", "wifi_startup_mode": "default", "output_brightness": 255, "pattern": "on", "colors": ["000000", "E8F4FF"], "brightness": 100, "delay": 100, "step_offset": 0, "step_increment": 1, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "wifi_driver_display_name": null, "wifi_driver_num_leds": null, "bridge_id": null}, "11": {"name": "winter bottom-right", "devices": ["a0b100000006"], "profile_id": "3", "wifi_color_order": "rgb", "wifi_startup_mode": "default", "output_brightness": 255, "pattern": "on", "colors": ["000000", "E8F4FF"], "brightness": 100, "delay": 100, "step_offset": 0, "step_increment": 1, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "wifi_driver_display_name": null, "wifi_driver_num_leds": null, "bridge_id": null}, "12": {"name": "winter top row", "devices": ["a0b100000001", "a0b100000002", "a0b100000003"], "profile_id": "3", "wifi_color_order": "rgb", "wifi_startup_mode": "default", "output_brightness": 255, "pattern": "on", "colors": ["000000", "E8F4FF"], "brightness": 100, "delay": 100, "step_offset": 0, "step_increment": 1, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "wifi_driver_display_name": null, "wifi_driver_num_leds": null, "bridge_id": null}, "13": {"name": "winter bottom row", "devices": ["a0b100000004", "a0b100000005", "a0b100000006"], "profile_id": "3", "wifi_color_order": "rgb", "wifi_startup_mode": "default", "output_brightness": 255, "pattern": "on", "colors": ["000000", "E8F4FF"], "brightness": 100, "delay": 100, "step_offset": 0, "step_increment": 1, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "wifi_driver_display_name": null, "wifi_driver_num_leds": null, "bridge_id": null}, "14": {"name": "winter left column", "devices": ["a0b100000001", "a0b100000004"], "profile_id": "3", "wifi_color_order": "rgb", "wifi_startup_mode": "default", "output_brightness": 255, "pattern": "on", "colors": ["000000", "E8F4FF"], "brightness": 100, "delay": 100, "step_offset": 0, "step_increment": 1, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "wifi_driver_display_name": null, "wifi_driver_num_leds": null, "bridge_id": null}, "15": {"name": "winter centre column", "devices": ["a0b100000002", "a0b100000005"], "profile_id": "3", "wifi_color_order": "rgb", "wifi_startup_mode": "default", "output_brightness": 255, "pattern": "on", "colors": ["000000", "E8F4FF"], "brightness": 100, "delay": 100, "step_offset": 0, "step_increment": 1, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "wifi_driver_display_name": null, "wifi_driver_num_leds": null, "bridge_id": null}, "16": {"name": "winter right column", "devices": ["a0b100000003", "a0b100000006"], "profile_id": "3", "wifi_color_order": "rgb", "wifi_startup_mode": "default", "output_brightness": 255, "pattern": "on", "colors": ["000000", "E8F4FF"], "brightness": 100, "delay": 100, "step_offset": 0, "step_increment": 1, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "wifi_driver_display_name": null, "wifi_driver_num_leds": nullLine truncated
-1
View File
@@ -1 +0,0 @@
{}
+1 -1
View File
@@ -1 +1 @@
{"1": ["#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#FF00FF", "#00FFFF", "#FFFFFF", "#000000"]}
{"1":["#FF0000","#00FF00","#0000FF","#FFFF00","#FF00FF","#00FFFF","#FFFFFF","#000000","#050500"],"2":[],"3":[],"4":[],"5":[],"6":[],"7":["#FF0000","#00FF00","#0000FF","#FFFF00","#FF00FF","#00FFFF","#FFFFFF","#000000"],"8":[],"9":[],"10":[],"11":[],"12":["#890b0b","#0b8935"],"13":[],"14":["#E8F4FF","#9ECFFF","#5080C8","#FFFFFF","#B0DCFF","#0A1520","#FF8020","#071018"]}
+280 -1
View File
@@ -1 +1,280 @@
{"on": {"min_delay": 10, "max_delay": 10000, "max_colors": 1}, "off": {"min_delay": 10, "max_delay": 10000, "max_colors": 0}, "rainbow": {"n1": "Step Rate", "min_delay": 10, "max_delay": 10000, "max_colors": 0}, "colour_cycle": {"n1": "Step Rate", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "transition": {"min_delay": 10, "max_delay": 10000, "max_colors": 10}, "chase": {"n1": "Colour 1 Length", "n2": "Colour 2 Length", "n3": "Step 1", "n4": "Step 2", "min_delay": 10, "max_delay": 10000, "max_colors": 2}, "pulse": {"n1": "Attack", "n2": "Hold", "n3": "Decay", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "circle": {"n1": "Head Rate", "n2": "Max Length", "n3": "Tail Rate", "n4": "Min Length", "min_delay": 10, "max_delay": 10000, "max_colors": 2}, "blink": {"min_delay": 10, "max_delay": 10000, "max_colors": 10}, "flicker": {"n1": "Min brightness", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "flame": {"n1": "Min brightness", "n2": "Breath period (ms)", "n3": "Spark gap min (ms, 0=default 10\u201330 s, -1=off)", "n4": "Spark gap max (ms)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "twinkle": {"n1": "Twinkle activity (1\u2013255, higher = more changes)", "n2": "Density (0\u2013255, higher = more of the strip lit)", "n3": "Min adjacent LEDs per twinkle (same as max for fixed length)", "n4": "Max adjacent LEDs per twinkle (same as min for fixed length)", "min_delay": 84, "max_delay": 10000, "max_colors": 10}, "radiate": {"n1": "Node spacing (LEDs)", "n2": "Out time (ms)", "n3": "In time (ms)", "min_delay": 10, "max_delay": 10000, "max_colors": 2}, "meteor_rain": {"n1": "Tail length", "n2": "Speed (LEDs per frame)", "n3": "Fade amount (1-255)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "scanner": {"n1": "Eye width", "n2": "End pause (frames)", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "gradient_scroll": {"n1": "Scroll step rate", "min_delay": 10, "max_delay": 10000, "max_colors": 10}, "comet_dual": {"n1": "Tail length", "n2": "Speed", "n3": "Gap", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "sparkle_trail": {"n1": "Spark density", "n2": "Decay", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "wave": {"n1": "Wavelength", "n2": "Amplitude", "n3": "Drift speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "plasma": {"n1": "Scale", "n2": "Speed", "n3": "Contrast", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "segment_chase": {"n1": "Segment size", "n2": "Phase step", "n3": "Segment phase offset", "n4": "Gap per segment", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "bar_graph": {"n1": "Level percent", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "breathing_dual": {"n1": "Phase offset", "n2": "Ease", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "strobe_burst": {"n1": "Burst count", "n2": "Burst gap", "n3": "Cooldown", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "rain_drops": {"n1": "Drop rate", "n2": "Ripple width", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "fireflies": {"n1": "Count", "n2": "Twinkle speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "clock_sweep": {"n1": "Hand width", "n2": "Marker interval", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "marquee": {"n1": "On length", "n2": "Off length", "n3": "Step", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "aurora": {"n1": "Band count", "n2": "Shimmer", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "snowfall": {"n1": "Flake density", "n2": "Fall speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "heartbeat": {"n1": "Pulse 1 ms", "n2": "Pulse 2 ms", "n3": "Pause ms", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "orbit": {"n1": "Orbit count", "n2": "Base speed", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "palette_morph": {"n1": "Morph ms", "n2": "Warp rate", "n3": "Turbulence", "max_colors": 10, "min_delay": 10, "max_delay": 10000}, "gradient_wipe": {"n1": "Start LED", "n2": "End LED", "min_delay": 10, "max_delay": 10000, "max_colors": 2}}
{
"on": {
"min_delay": 10,
"max_delay": 10000,
"max_colors": 1,
"supports_manual": true
},
"off": {
"min_delay": 10,
"max_delay": 10000,
"max_colors": 0,
"supports_manual": true
},
"colour_cycle": {
"supports_reverse": true,
"n1": "Step rate",
"mode": {
"0": "Scroll palette gradient",
"1": "Rainbow wheel (preset colours ignored)"
},
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"supports_manual": true
},
"transition": {
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"supports_manual": false
},
"chase": {
"supports_reverse": true,
"n1": "Colour 1 Length",
"n2": "Colour 2 Length",
"n3": "Step 1",
"n4": "Step 2",
"min_delay": 10,
"max_delay": 10000,
"max_colors": 2,
"has_background": true,
"supports_manual": true,
"mode": {
"0": "Two-colour chase",
"1": "Marquee dashes (n1 on length, n2 off, n3 step)"
}
},
"pulse": {
"n1": "Attack",
"n2": "Hold",
"n3": "Decay",
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"has_background": true,
"supports_manual": true
},
"circle": {
"n1": "Head Rate",
"n2": "Max Length",
"n3": "Tail Rate",
"n4": "Min Length",
"min_delay": 10,
"max_delay": 10000,
"max_colors": 2,
"has_background": true,
"supports_manual": false
},
"blink": {
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"has_background": true,
"supports_manual": false
},
"flicker": {
"n1": "Min brightness",
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"supports_manual": true
},
"flame": {
"n1": "Min brightness",
"n2": "Breath period (ms)",
"n3": "Spark gap min (ms, 0=default 10\u201330 s, -1=off)",
"n4": "Spark gap max (ms)",
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"supports_manual": false
},
"twinkle": {
"n1": "Twinkle activity (1\u2013255, higher = more changes)",
"n2": "Density (0\u2013255, higher = more of the strip lit)",
"n3": "Min adjacent LEDs per twinkle (same as max for fixed length)",
"n4": "Max adjacent LEDs per twinkle (same as min for fixed length)",
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"has_background": true,
"supports_manual": true
},
"radiate": {
"n1": "Node spacing (LEDs)",
"n2": "Out time (ms)",
"n3": "In time (ms)",
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"has_background": true,
"supports_manual": true
},
"plasma": {
"n1": "Scale",
"n2": "Speed",
"n3": "Contrast",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"supports_manual": false
},
"bar_graph": {
"n1": "Level percent",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"has_background": true,
"supports_manual": false
},
"strobe_burst": {
"n1": "Burst count",
"n2": "Burst gap",
"n3": "Cooldown",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"has_background": true,
"supports_manual": true
},
"rain_drops": {
"n1": "Drop rate",
"n2": "Ripple width",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"has_background": true,
"supports_manual": true
},
"clock_sweep": {
"n1": "Hand width",
"n2": "Marker interval",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"has_background": true,
"supports_manual": true
},
"aurora": {
"supports_reverse": true,
"n1": "Band count (0) or spatial period LEDs (1)",
"n2": "Shimmer (0) or blend strength (1)",
"n3": "Unused (0) or drift speed (1)",
"mode": {
"0": "Colour bands + shimmer",
"1": "Sine northern wave"
},
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"has_background": true,
"supports_manual": true
},
"icicles": {
"supports_reverse": true,
"n1": "Anchor spacing (LEDs)",
"n2": "Max icicle length (LEDs)",
"n3": "Phase step per refresh",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"has_background": true,
"supports_manual": true
},
"blizzard": {
"supports_reverse": true,
"n1": "Flake density",
"n2": "Fall speed",
"n3": "Wind (128 = centred; lower/raise for drift bias)",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"has_background": true,
"supports_manual": true
},
"rime": {
"n1": "Crystallisation rate",
"n2": "Melt (decay) per refresh",
"n3": "Spark cap (LEDs refreshed per cycle)",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"has_background": true,
"supports_manual": true
},
"candle_glow": {
"n1": "Candle count",
"n2": "Glow width (LEDs)",
"n3": "Flicker strength",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"has_background": true,
"supports_manual": true
},
"orbit": {
"n1": "Orbit count",
"n2": "Base speed",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"has_background": true,
"supports_manual": true
},
"palette_morph": {
"n1": "Morph ms",
"n2": "Warp rate",
"n3": "Turbulence",
"max_colors": 10,
"min_delay": 10,
"max_delay": 10000,
"supports_manual": false
},
"meteor": {
"supports_reverse": true,
"n1": "Tail length (0–1) or eye width (2)",
"n2": "Speed (LEDs per frame)",
"n3": "Fade amount (0), comet gap (1), or end pause frames (2)",
"mode": {
"0": "Fading meteor",
"1": "Dual comets",
"2": "Bouncing scanner"
},
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"has_background": true,
"supports_manual": true
},
"particles": {
"supports_reverse": true,
"n1": "Flake density (0) or spawn rate (1)",
"n2": "Fall speed (LEDs per frame)",
"n3": "Unused (0) or streak length (1)",
"mode": {
"0": "Snowfall flakes",
"1": "Starfall streaks"
},
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"has_background": true,
"supports_manual": true
},
"sparkle": {
"n1": "Spark density (0–1) or firefly count (2)",
"n2": "Trail decay (0) or twinkle speed (2)",
"n3": "Ice halo width LEDs (1); unused in 0 and 2",
"mode": {
"0": "Sparkle trail",
"1": "Ice burst + halo",
"2": "Fireflies"
},
"min_delay": 10,
"max_delay": 10000,
"max_colors": 10,
"has_background": true,
"supports_manual": true
}
}
+1 -1
View File
@@ -1 +1 @@
{"1":{"name":"on","pattern":"on","colors":["#FFFFFF"],"brightness":255,"delay":100,"n1":0,"n2":0,"n3":0,"n4":0,"n5":0,"n6":0,"n7":0,"n8":0,"profile_id":"1","auto":true,"id":"1"},"2":{"name":"off","pattern":"off","colors":[],"brightness":0,"delay":100,"n1":0,"n2":0,"n3":0,"n4":0,"n5":0,"n6":0,"n7":0,"n8":0,"profile_id":"1","auto":true,"id":"2"},"3":{"name":"rainbow","pattern":"rainbow","colors":[],"brightness":255,"delay":100,"n1":2,"n2":0,"n3":0,"n4":0,"n5":0,"n6":0,"n7":0,"n8":0,"profile_id":"1","auto":true,"id":"3"},"4":{"name":"Colour Cycle","pattern":"colour_cycle","colors":["#FF0000","#00FF00","#0000FF"],"brightness":255,"delay":100,"n1":1,"n2":0,"n3":0,"n4":0,"n5":0,"n6":0,"n7":0,"n8":0,"profile_id":"1","auto":true,"id":"4"},"5":{"name":"transition","pattern":"transition","colors":["#FF0000","#00FF00","#0000FF"],"brightness":255,"delay":500,"n1":0,"n2":0,"n3":0,"n4":0,"n5":0,"n6":0,"n7":0,"n8":0,"profile_id":"1","auto":true,"id":"5"},"6":{"name":"flicker","pattern":"flicker","colors":["#FFB84D"],"brightness":255,"delay":80,"n1":30,"n2":0,"n3":0,"n4":0,"n5":0,"n6":0,"n7":0,"n8":0,"profile_id":"1","auto":true,"id":"6"},"7":{"name":"flame","pattern":"flame","colors":[],"brightness":255,"delay":50,"n1":35,"n2":2600,"n3":0,"n4":0,"n5":0,"n6":0,"n7":0,"n8":0,"profile_id":"1","auto":true,"id":"7"},"8":{"name":"twinkle","pattern":"twinkle","colors":["#78C8FF","#508CFF","#B478FF","#64DCE8","#A0C8FF"],"brightness":255,"delay":55,"n1":72,"n2":140,"n3":2,"n4":6,"n5":0,"n6":0,"n7":0,"n8":0,"profile_id":"1","auto":true,"id":"8"}}
{"1": {"name": "on", "pattern": "on", "colors": ["#FFFFFF"], "brightness": 255, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "2": {"name": "off", "pattern": "off", "colors": [], "brightness": 0, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "3": {"name": "rainbow", "pattern": "colour_cycle", "colors": [], "brightness": 255, "delay": 100, "auto": true, "n1": 2, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 1, "n7": 0, "n8": 0, "profile_id": "1"}, "4": {"name": "transition", "pattern": "transition", "colors": ["#FF0000", "#00FF00", "#0000FF"], "brightness": 255, "delay": 300, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null, null], "background": "#000000", "manual_beat_n": 1}, "5": {"name": "chase", "pattern": "chase", "colors": ["#FFFF00", "#FF00FF"], "brightness": 128, "delay": 200, "auto": false, "n1": 30, "n2": 30, "n3": 30, "n4": 30, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [3, 4], "manual_beat_n": 1, "background": "#000000", "background_palette_ref": null, "mode": 0}, "6": {"name": "pulse", "pattern": "pulse", "colors": ["#FF00FF"], "brightness": 255, "delay": 1000, "auto": false, "n1": 100, "n2": 0, "n3": 100, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [4], "background_color": "#ec0909", "background_palette_ref": 8, "manual_beat_n": 1, "background": "#050500"}, "7": {"name": "circle", "pattern": "circle", "colors": ["#FFA500", "#800080"], "brightness": 255, "delay": 200, "auto": true, "n1": 2, "n2": 10, "n3": 2, "n4": 5, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "8": {"name": "blink", "pattern": "blink", "colors": ["#FF0000", "#00FF00", "#0000FF", "#FFFF00"], "brightness": 255, "delay": 1000, "auto": false, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1", "palette_refs": [null, null, null, null]}, "9": {"name": "warm white", "pattern": "on", "colors": ["#FFF5E6"], "brightness": 200, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "10": {"name": "cool white", "pattern": "on", "colors": ["#E6F2FF"], "brightness": 200, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "11": {"name": "red", "pattern": "on", "colors": ["#FF0000"], "brightness": 255, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "12": {"name": "blue", "pattern": "on", "colors": ["#0000FF"], "brightness": 255, "delay": 100, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "13": {"name": "rainbow slow", "pattern": "colour_cycle", "colors": [], "brightness": 255, "delay": 150, "auto": true, "n1": 1, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 1, "n7": 0, "n8": 0, "profile_id": "1"}, "14": {"name": "pulse slow", "pattern": "pulse", "colors": ["#FF6600"], "brightness": 255, "delay": 800, "auto": true, "n1": 2000, "n2": 1000, "n3": 2000, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "15": {"name": "blink red green", "pattern": "blink", "colors": ["#FF0000", "#00FF00"], "brightness": 255, "delay": 500, "auto": true, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "1"}, "30": {"name": "rainbow slow", "pattern": "colour_cycle", "colors": [], "brightness": 255, "delay": 150, "auto": true, "n1": 1, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 1, "n7": 0, "n8": 0, "profile_id": "2"}, "31": {"name": "DJ Rainbow", "pattern": "colour_cycle", "colors": [], "brightness": 220, "delay": 60, "n1": 12, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 1, "n7": 0, "n8": 0, "profile_id": "2"}, "32": {"name": "DJ Single Color", "pattern": "on", "colors": ["#ff00ff"], "brightness": 220, "delay": 100, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "33": {"name": "DJ Transition", "pattern": "transition", "colors": ["#ff0000", "#00ff00", "#0000ff"], "brightness": 220, "delay": 250, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "34": {"name": "DJ Rainbow", "pattern": "colour_cycle", "colors": [], "brightness": 220, "delay": 60, "n1": 12, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 1, "n7": 0, "n8": 0, "profile_id": "2"}, "35": {"name": "DJ Single Color", "pattern": "on", "colors": ["#ff00ff"], "brightness": 220, "delay": 100, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profile_id": "2"}, "36": {"name": "DJ Transition", "pattern": "transition", "colors": ["#ff0000", "#00ff00", "#0000ff"], "brightness": 220, "delay": 250, "n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0, "n7": 0, "n8": 0, "profiLine truncated
BIN
View File
Binary file not shown.
+3
View File
@@ -0,0 +1,3 @@
PRST1xœ%ÎÁ
Â0Ð_‘ñšCSµJîæ'D$¶«␍ÄÝ’¦ˆˆÿntOovæ²opxz‘´zޱ ¦P
e®µp={I’g¸ÖÇηÞãlpÍñ>¦¹mÓ ” ÎþrXŠÀ•¼�[¸Zq«l”­²S:e¯þLYn1Ñ%õ‹Ï ¥/ï
+2
View File
@@ -0,0 +1,2 @@
PRST1xњ%ОAВ …б»<·,J5\Е4␍К $84SX4Ж»‹eхеНlюШЅ B
‹+…„ЫОЬж#§,+м␍‡@ЖЏIб.сщ*Lk{ЊЖ(xJnѓХГ аjЙ°E*)°†m';ЗО©c:зОҐsЭY$‡�hЋѕuиЅ*Qлљ…В?†kJУчП=5Я
+1
View File
@@ -0,0 +1 @@
PRST1xœ%ÎA л|·, ŠÐK˜ÆP;* ␍……1Þ݉3›—ÿÿf>àø"̹ ÖØU–¢°Ä[É¥nì¬Ü8b2˜kz<Ó&Ãà½ÁB9¾œµ±·‚Ðj'vRñ ì•ƒâ•£rRÎÖZî)Ó5-ò‡Ã÷yÒ-€
+2
View File
@@ -0,0 +1,2 @@
PRST1xœEÎÁ
Â0Ð_‘9ç`«Qɯˆ”Ô®ˆ»e“RDüwsðô˜™Ë¼ÁñIИx”uS²¬p˜c­¤ü¬»J-ç‹Ã¨éþ¨LÅrï½ÃD9¾:¿uˆK„ª 9pg¥Ñ#ØÂ»Æ¾á‡Æ±qú1«ÜR¦!Mö¡Ãç ��1
+2
View File
@@ -0,0 +1,2 @@
PRST1xœ=ÎÝ
!†á[‰¯StK[¼€½‰ˆ°v*ÁTü!"º÷Ü¤Žžá�9˜¼¹4bu™VÙ…¢)…’ÿåVÎÁ…”¡÷XO“RœãÀpJöz+žr[ R2ÌäÌzäœÁÔ KªÄàE;àKõ´èÓæß¶Ð ²£:»Îø%¦p±ŽŽvn? ¼?�¨2ú
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
PRST1xœUÎÁ
Â0ЙsM5Uò+"²µ«â¦lSDÄwiNž³3‡ý@èɈPJ2–fª•Uþn×’‹.ˆ§³Ã¨éþ¨Â‹å>‡‰3½}×9ÐZ bÕ•ÄÛÀè­‘]cß�¡qh7f-·”ù’&ûÁãûF9/.
+2
View File
@@ -0,0 +1,2 @@
PRST1xœEÎÁ
Â0Ð_‘9ç`«Qɯˆ”Ô®ˆ»e“RDüwsðô˜™Ë¼ÁñIИx”uS²¬p˜c­¤ü¬»J-ç‹Ã¨éþ¨LÅrï½ÃD9¾:¿uˆK„ª 9pg¥Ñ#ØÂ»Æ¾á‡Æ±qú1«ÜR¦!Mö¡Çç �“1
BIN
View File
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
PRST1xœ%ͽÂ0 àW©Ž5C~•&VÆ
¡@�)uª4K…xwR<}ç»Á° —ks <DjÎ)¦ …É•B™ë–¸ž¯µža;l¼×Ú{Üž9 ïÂ4×Á­ÐSt l«kævÅ[a'ì…ƒpN¦œ|ˆô}ýmðý‡-‰
+1
View File
@@ -0,0 +1 @@
PRST1xœMÎ1! †á¿b¾[=5ÌNÎnÆô@I°\€Åÿ»Å.²<oÚ¼Aîéa±?,ŽÅQ�-f‚ÂìZó…xÓþÇ·œr©°' !h~<´î-Õg…k‰÷G#_ùØ­0ùä^Ü#7-a;FX ka6ÂVØý˜K1ùKœø_Ÿ/ÐM4y
BIN
View File
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
PRST1xœ%ͽÂ0 àW©Ž5C~•&VÆ
¡@�)uª4K…xwR<}ç»Á° —ks <DjÎ)¦ …É•B™ë–¸ž¯µža;l¼×Ú{Üž9 ïÂ4×Á­ÐSt l«kævÅ[a'ì…ƒpN¦œ|ˆô}ýmðý‡-‰
+1
View File
@@ -0,0 +1 @@
PRST1xœMÎ1! †á¿b¾[=5ÌNÎnÆô@I°\€Åÿ»Å.²<oÚ¼Aîéa±?,ŽÅQ�-f‚ÂìZó…xÓþÇ·œr©°' !h~<´î-Õg…k‰÷G#_ùØ­0ùä^Ü#7-a;FX ka6ÂVØý˜K1ùKœø_Ÿ/ÐM4y
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+3
View File
@@ -0,0 +1,3 @@
PRST1xœUÎÁ‚0„áw¯=¤jú*†�
[m\[²”ƒ1¾»…ž<}ÉÌåÿ ºÁÂsŸ$P˜]Î$ño'Y`¯88ÒÚ{ô
7 ÷GŽ´”£5Fa"voX£Üšl–•bÛè2ÆvãXé*¦rªœ+—�Y’LC˜JM³·1•ºAÈo5qeî¿?ªð9±
BIN
View File
Binary file not shown.
+4
View File
@@ -0,0 +1,4 @@
PRST1xśMÎÁ‚0„áwŻ=$ű*†�
[%Y[RÚ1ľ»…^<}ÉĚĺ˙Ŕ™7�`ĺPa51rpËäŇ␍tÇĹÚ©×�Â#,ĎWtĽĺŁŞ{…™Ĺě V+�=(†Ä
®5m¶՝ίk@×B[č
·B˛oáq™sMu¶ çş1°=z\ľ?µ¦8>
+2
View File
@@ -0,0 +1,2 @@
PRST1xśmŹÁ‚0 †ßĄ\wČ`ŮMQ^Â2ĄčâÜČ1ĆřînĚ‹‰—~í—?Mű#ďüC™›F 0IďŃ™w¶ÚşÄ˛š7Ľm�ËĺMęveýuUąo<v[şć:'§.Wop
Ć ¨ĺDN)ąx » �<H¤)B2r"˘Śá@–Ć*ˇNŕ+&gGĄ±WC8<_ßĐéŽńpłhMţ”îýŹ!I°
+2
View File
@@ -0,0 +1,2 @@
PRST1xњUЋ;В0птТєp>°WAQґђ5X2Nд8BЬ;©hv¤·SМЃ_BдЙq(,њ’Др·Эg?ЗtEЕЅЦЦж­ТZіf
·иПdНJcЊВ$ћЯ “ЮТ Jq…PѓЪј…t)ПР‚є] ЁАињњw,q¶ОЛи¦\Wп­^rнЕ–є°yЇКѕ?Эh>Ў
BIN
View File
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
PRST1xœEÎM
Â0à«Ès›Eÿ¢’ôE$¶£â¤$Ó…ˆww0 góÁ{o1o°„ŠìÊì™)Ã`õ"”Y‹6§˜r�›°ÇFgƒk÷‡0-:k␍Šþ×7~“'y#ná¥Ó™ÒÃ逇Э*ÇÊéÇšÓ-Dº„Eiñù¹L2‡
+3
View File
@@ -0,0 +1,3 @@
PRST1xœ=ŽA‚0E¯B>Û.
*š€KC*ŒØ¤¶¤Æxw�Í{™7‹y!ØÁ€)s5';9
\å1Eï¡°XfJA~mø·1ú˜2ÌußkÙÕZo^ls\®ÉÍw”å¸mµÂDÞ>a:Q»r„á´’Bh¤ Z)aW°/8tÇ‚ÓKŠ7çip“üÙàý)<¡
+3
View File
@@ -0,0 +1,3 @@
PRST1xś-ÎÁ‚0Đ_!õ‡Šdo˝ô'Ś!Ş’”–”ĺ`Ś˙î<˝ÍĚö�čfű•‹!Íž‹qs
‹cö9J·Çý?RHy]QZkŚÖ’•Zc-n
÷<=_ý*“Zk…Ń÷µrşŤ�óćbę„T ␍¨N ŮĹóA{p9čv–śSđý4Ęcľ?6Đ
+2
View File
@@ -0,0 +1,2 @@
PRST1x�5־A‚0…ב«�ַ¶ @Dׂ- —0ֶT©�X[2ֶxwG׳ש&‎»˜‚yXh°M\₪�׀��‚ֹ8…�0[
’ור/חט#%ט=ֺ¾†q”·r\…¹כ�ƒMע¥©*…ֹzף„מd5 Gh¦ֵ*„Zz+6b-1l ¿´™m¦ֻל2‎ֺLסגה"7ֹy5�־ד:G
+2
View File
@@ -0,0 +1,2 @@
PRST1xœ-ÎÁ Ð_1ã•ÔZŽúÆ´«’ 4°Õã¿»Š§7;sÙ¢»,˜
/îNP˜3å(í¿8¥�r�Ýa©õ¶ìŽÙ_®©ÈÐh­0RpOØN¢›9ÁržI!XÓˆ�ØËW„ö{­+]eSéL9�} ƒåƒ÷ªù0¿
+2
View File
@@ -0,0 +1,2 @@
PRST1x�=ЮA
Т0аЋШw�EZ5JаK�б�ZH��L"онС�Ћ7ќџѓFЄ�с!\e�е�`�I�KдќнRHЅТ�и�ЕЮсlp-ѓу)�ЋНЕzС;=i�/ee�иiІє:Sv�=МютЁсЧЦщG.щ>ОЬ�Овсѓ,�1И
BIN
View File
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
PRST1xœ5ÎA‚0Ы�϶‹‚ˆ¦è%Œ!F �–´ÃÂïîhu6o2ÿ/æ ïV‚Sâ"Ѹ’碟\"(lŽ™¢—ø—tÿ¤Kˆ æ‚ÒZ-#·ò£µ¸*Üâ<Nì)I¥ÖZa Å=`ZYÝΆãN
¾‚i„¦0RðMæ˜i3§ÌùËÃ}^¨›ù­Âë␍Çü8÷
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
PRST1xœ5Î=Â0 †á«Tk†þQ�À%*T%Ô@¥’TŽ; ÄÝIáå±ôzðÞ¾å¨ET Ž ·JT,V•ŧšÃð·0‰ ‡Ë>¸8™OõS¨ËÒ`äÙ¾A]Zíª¤²²�¯@M¢ÎÉ7 v;÷-hã˜é2§Ìyg‘pŸf¦1ýTáû^
7˜
+3
View File
@@ -0,0 +1,3 @@
PRST1x�5ΞΝ
Β0ΰW)γ5‡ώh­Ήϊ"%ΪU5)›νAΔww5xϊ–™9μ Α=BI
v>Η%Α`q"ΔA»o<ώγK�#'Ψ#6‡²ο†'ƒ3ϋΫ]%-κ²4�hvOΨVO·J„^Ι T°M­Φ��ΐκ"l3»L›ΩgΊ Η«�iτ“ώSαύ��5%
+4
View File
@@ -0,0 +1,4 @@
PRST1xœMαÂ0 Ð_A×5CZ ´™Q~!¨ ‘BR%î€ÿŽE¦gÝÝà7¢{ ˜
ofŸiž
ÇL9JõŸÞRH¹ÀœÐX{Ô½–¬µµ£ÆYášýýÁ‘ŠL:­&
îÓËéVN0œWRˆ­dB3[Ä]e_é+‡ÊðcÉiö�.~’¿Z|¾¡ 61
+1
View File
@@ -0,0 +1 @@
PRST1xœ5ŽAƒ E¯b¾[¨U+WiŒ¡2¶¦ `š¦éÝ ’nxÌ›Y¼Œ|ùPÌÚÎ�¿ˆ60l2r&.?ýýlµuâ‚Rõ|àCt%Wuß5®n½Ýƒ!OjÎiùN¹ ÜN ¦‚¨¢35DÑ@¤é”Ñft}ÆùÀæì²jšVÓª#TSL�-)ËìZ³ôŒßQ•AÓ
+1
View File
@@ -0,0 +1 @@
PRST1xњEО1В0 Р« ПљЎiЎ ЂK „5)MЪФвоXНЂ—gщяБD72В‹lF—зВ ѓЙ‰pЋьoчR^@glOлаbpЛющ’И‹mУ ЬФлкЉ$ђдВС‚:ҐХљТЃ¬Іi/о+}еP9®L9=|а«ф‹пжg2д
+2
View File
@@ -0,0 +1,2 @@
PRST1xœ=ÎÍ
Â0àW‘é5‡ô?ìM"} ‰vÕBMJ’D|wSž¾afû†5O!rˆ;³zç␍#{›úuu³ótDQi­”N]ÑÊ^␍Öö²•�“ÀÅO÷G´Òq%¥Àȳy�ºÍ(ú•l ª¨I“­AM¦Ít™>£~,Þݦ™ÏÓ˜þ+ñùÚ¦5ó
+3
View File
@@ -0,0 +1,3 @@
PRST1x°Mна
б0 ЮW▒вз╘SzTЯ%D╓╨L╣m├┬ЬНfКе\╬ДOЫ ╦'а┌)С"┤ЬЙ°ВP3╔ ⌡©П}LЖ└Й8≈dуNЖр²╝╘©?8P√⌠Zk┘√╪{ц6р╨▒#,╖▒┌≥Жb␍k└%Л4╜
КBSь╤3C┼]ОИр╥Р≈аВ┘┘6
+2
View File
@@ -0,0 +1,2 @@
PRST1xœMÎK
Â0…á½§ÜT£’tR$Ú«âMÉc âÞm�ˆ£þ39Oˆ»3,¦2Car¥p’¿rŽ!¦ {ÀЍï‰0(œ’¿ÞŠpž‡Î…‘ƒ{À"WK„-©²‚hXMK•î;Ëú—6° ¦±mìûSŠøèÇù’Æë␍»0Ø
+4
View File
@@ -0,0 +1,4 @@
PRST1xœMÎA‚0Ы˜ï¶‹RÉ€KcŠŒBR[Ò c¼»­l\½Éÿùɼáí“ANr˜ÙFÙ
V+ÂÑçê?½b␍8ö½éj�‹Â—Ç,žS.ŒÖ
;ûµù´›�Ä�|ªL½uŨ)_ƒ
ÍN»sÞé~¬1ÜÇ×eÊ/Uø|Æœ5
BIN
View File
Binary file not shown.
+3
View File
@@ -0,0 +1,3 @@
PRST1xœ5ŽA‚0E¯B>Û.
*š€KCªŒBRÚ¦ c¼»ÅÙ¼7óÿb>ðv"0Í\D눙Š)¤8@!ZÙ’—xOºò.¤抲mµŒÜJ­W϶:n
÷4¾ö4K¹ÖZ¡'gß0�¨]8ÀpZHÁW0ÕVðõÞô˜ÇŒSF“qθlˆ)<GGÝØË«¾?ð¹<
+3
View File
@@ -0,0 +1,3 @@
PRST1xœMŽ1Â0 Eïò»fp
�(K/�
­�H!©Òt@ˆ»cÈÂô¾Ÿ¿%¿�üƒá0†2F†Âìkå’þÕ˜c. ÜÝ0 ‘¸Î‘%œ.%Üî5ñ"•Þ…‰£J&RðkÍpµ¬¬�´HA§e•6mÜÂÉQ2p_¹kØ7Øæ’¯!ò9Lò–Æû¼Ã1ó
BIN
View File
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
PRST1xœ%ÎK
Ã0 Ы”éÖ‹$ýâ«”ÜFn Ž›PJï^ÇÖæI£Í|Áf&hlFæÃ6¹HPXLŒ$œãÀù|d…~àhË WxŠ{O‘iÍ�®iFòæÝî»I1@GI¤À-tޏ«œ*çÊ¥r­Ü*÷Â"Á:Oƒs�¶´ò”{␍Bv/ÃÉûþ÷½8ù
+1 -1
View File
@@ -1 +1 @@
{"1": {"name": "default", "type": "zones", "zones": ["1"], "scenes": [], "palette_id": "1", "id": "1"}}
{"1":{"name":"default","type":"zones","zones":["1","9","8","10"],"scenes":[],"palette_id":"1"},"2":{"name":"test","type":"zones","zones":["6","7"],"scenes":[],"palette_id":"12"},"3":{"name":"Winter","type":"zones","zones":["11","12"],"scenes":[],"palette_id":"14"}}
+22 -1
View File
@@ -1 +1,22 @@
{}
{
"1": {
"name": "Default Scene",
"sequences": [
"1"
],
"groups": [
"1"
]
},
"2": {
"name": "Party Mode",
"sequences": [
"1",
"2"
],
"groups": [
"1",
"2"
]
}
}
+1 -1
View File
@@ -1 +1 @@
{}
{"1": {"name": "Pulse (manual)", "profile_id": "1", "group_ids": ["18"], "lanes": [[{"preset_id": "6", "beats": 1}]], "lanes_group_ids": [["18"]], "advance_mode": "beats", "steps": [{"preset_id": "6", "beats": 1}], "step_duration_ms": 3000, "simulated_bpm": 120, "sequence_transition": 500, "loop": true}, "2": {"name": "Off (1 beat)", "profile_id": "1", "group_ids": ["5"], "lanes": [[{"preset_id": "2", "beats": 1}]], "lanes_group_ids": [["5"]], "advance_mode": "beats", "steps": [{"preset_id": "2", "beats": 1}], "step_duration_ms": 3000, "simulated_bpm": 120, "sequence_transition": 500, "loop": false}, "3": {"name": "On (1 beat)", "profile_id": "1", "group_ids": ["5"], "lanes": [[{"preset_id": "1", "beats": 1}]], "lanes_group_ids": [["5"]], "advance_mode": "beats", "steps": [{"preset_id": "1", "beats": 1}], "step_duration_ms": 3000, "simulated_bpm": 120, "sequence_transition": 500, "loop": false}, "4": {"name": "Rainbow \u2192 transition \u2192 off", "profile_id": "1", "group_ids": ["18"], "lanes": [[{"preset_id": "3", "beats": 4}, {"preset_id": "4", "beats": 4}, {"preset_id": "2", "beats": 2}]], "lanes_group_ids": [["18"]], "advance_mode": "beats", "steps": [{"preset_id": "3", "beats": 4}, {"preset_id": "4", "beats": 4}, {"preset_id": "2", "beats": 2}], "step_duration_ms": 3000, "simulated_bpm": 100, "sequence_transition": 500, "loop": true}, "5": {"name": "Manual pulse + chase", "profile_id": "1", "group_ids": ["18"], "lanes": [[{"preset_id": "6", "beats": 2}, {"preset_id": "5", "beats": 2}]], "lanes_group_ids": [["18"]], "advance_mode": "beats", "steps": [{"preset_id": "6", "beats": 2}, {"preset_id": "5", "beats": 2}], "step_duration_ms": 3000, "simulated_bpm": 120, "sequence_transition": 500, "loop": true}, "6": {"name": "RGB solid cycle", "profile_id": "1", "group_ids": ["5"], "lanes": [[{"preset_id": "11", "beats": 2}, {"preset_id": "12", "beats": 2}, {"preset_id": "9", "beats": 2}, {"preset_id": "10", "beats": 2}]], "lanes_group_ids": [["5"]], "advance_mode": "beats", "steps": [{"preset_id": "11", "beats": 2}, {"preset_id": "12", "beats": 2}, {"preset_id": "9", "beats": 2}, {"preset_id": "10", "beats": 2}], "step_duration_ms": 3000, "simulated_bpm": 90, "sequence_transition": 500, "loop": true}, "7": {"name": "Winter trio", "profile_id": "1", "group_ids": ["18"], "lanes": [[{"preset_id": "64", "beats": 8}, {"preset_id": "65", "beats": 8}, {"preset_id": "66", "beats": 8}]], "lanes_group_ids": [["18"]], "advance_mode": "beats", "steps": [{"preset_id": "64", "beats": 8}, {"preset_id": "65", "beats": 8}, {"preset_id": "66", "beats": 8}], "step_duration_ms": 3000, "simulated_bpm": 80, "sequence_transition": 500, "loop": true}, "8": {"name": "Fast rainbow", "profile_id": "1", "group_ids": ["18"], "lanes": [[{"preset_id": "3", "beats": 4}]], "lanes_group_ids": [["18"]], "advance_mode": "beats", "steps": [{"preset_id": "3", "beats": 4}], "step_duration_ms": 3000, "simulated_bpm": 180, "sequence_transition": 500, "loop": true}, "9": {"name": "Off then on", "profile_id": "1", "group_ids": ["18"], "lanes": [[{"preset_id": "2", "beats": 2}, {"preset_id": "1", "beats": 4}]], "lanes_group_ids": [["18"]], "advance_mode": "beats", "steps": [{"preset_id": "2", "beats": 2}, {"preset_id": "1", "beats": 4}], "step_duration_ms": 3000, "simulated_bpm": 120, "sequence_transition": 500, "loop": true}, "10": {"name": "Twinkle + flame", "profile_id": "1", "group_ids": ["18"], "lanes": [[{"preset_id": "41", "beats": 6}]], "lanes_group_ids": [["18"]], "advance_mode": "beats", "steps": [{"preset_id": "41", "beats": 6}], "step_duration_ms": 3000, "simulated_bpm": 110, "sequence_transition": 500, "loop": true}, "11": {"name": "radiate chase", "profile_id": "1", "group_ids": ["18"], "lanes": [[{"preset_id": "42", "beats": 12}, {"preset_id": "5", "beats": 4}]], "lanes_group_ids": [["18"]], "advance_mode": "beats", "steps": [{"preset_id": "42", "beats": 12}, {"preset_id": "5", "beats": 4}], "step_duration_ms": 3000, "simulated_bpm": 120, "sequence_transition": 500, "loop": true}, "12": {"name": "Winter cell cascade", "profile_id": "3", "group_ids": ["17"], "lanes": [[{"preset_id": "80", "beats": 6}], [{"preset_id": "85", "beats": 6}], [{"preset_id": "81", "beats": 6}], [{"preset_id": "82", "beats": 6}], [{"preset_id": "83", "beats": 6}], [{"preset_id": "84", "beats": 6}]], "lanes_group_ids": [["6"], ["7"], ["8"], ["9"], ["10"], ["11"]], "advance_mode": "beats", "steps": [{"preset_id": "80", "beats": 6}, {"preset_id": "85", "beats": 6}, {"preset_id": "81", "beats": 6}, {"preset_id": "82", "beats": 6}, {"preset_id": "83", "beats": 6}, {"preset_id": "84", "beats": 6}], "step_duration_ms": 3000, "simulated_bpm": 85, "sequence_transition": 500, "loop": true}, "13": {"name": "Winter row waves", "profile_id": "3", "group_ids": ["17"], "lanes": [[{"preset_id": "81", "beats": 8}, {"preset_id": "80", "beats": 8}], [{"preset_id": "83", "beats": 8}, {"preset_id": "82", "beats": 8}]], "lanes_group_ids": [["12"], ["13"]], "advance_mode": "beats", "Line truncated
-1
View File
@@ -1 +0,0 @@
{"1": {"name": "default", "names": ["1"], "presets": [["1", "2", "3", "4", "5", "6", "7", "8"]], "presets_flat": ["1", "2", "3", "4", "5", "6", "7", "8"], "default_preset": "1", "id": "1", "group_ids": ["1"], "preset_group_ids": {}, "sequence_ids": [], "content_kind": "presets"}}
-31
View File
@@ -1,31 +0,0 @@
dependencies:
espressif/mdns:
component_hash: ef0766474b37459f6ad22461e453a8713e780e831a7c993b16919d817988dff6
dependencies:
- name: idf
require: private
version: '>=5.0'
source:
registry_url: https://components.espressif.com/
type: service
version: 1.14.1
idf:
source:
type: idf
version: 5.5.5
joltwallet/littlefs:
component_hash: e1a0f4a6adf821759cb34703a91107bbdce5d7ff6f4728f40ab012bb87842974
dependencies:
- name: idf
require: private
version: '>=5.0'
source:
registry_url: https://components.espressif.com/
type: service
version: 1.23.1
direct_dependencies:
- espressif/mdns
- joltwallet/littlefs
manifest_hash: a5329d49f0154685d9701ccb399916a87107b77ddfe802c911aa2bb41ed5bab0
target: esp32s3
version: 2.0.0
Submodule dmx-driver deleted from d2ffcb1969.
+344 -294
View File
@@ -1,358 +1,408 @@
# LED Controller API
The controller is an ESP32-S3 on Ethernet (W5500). It serves the web UI and a JSON API on port 80, detects beats from its I2S microphone and talks to the LED drivers over ESP-NOW. This document covers:
This document covers:
1. The HTTP and WebSocket API, by resource.
2. How the controller turns API calls into driver messages, and the message format.
1. **HTTP and WebSocket** exposed by the Raspberry Pi app (`src/main.py`) — profiles, zones, presets, transport send, pattern OTA helpers, and related resources.
2. **LED driver JSON** — the compact **v1** message format. ESP-NOW traffic is wrapped in a **devices envelope** (`dv` map keyed by MAC) on the Pi ↔ bridge link (WebSocket or USB serial); drivers receive compact per-device bodies (≤250 bytes). **Wi-Fi** drivers still accept **single JSON text messages** over an outbound WebSocket (same logical fields).
Request and response bodies are JSON (`Content-Type: application/json`) unless noted. Errors come back as `{"error": "..."}` with a 4xx or 5xx status.
Default HTTP listen address: `0.0.0.0`. Port defaults to **80**; override with the **`PORT`** environment variable (see `pipenv run run`).
## Data and scoping
**ESP-NOW bridge:** Set **`bridge_transport`** to **`wifi`** (default) or **`serial`**. Wi‑Fi mode uses **`bridge_ws_url`** (e.g. `ws://192.168.4.1/ws`) after joining the bridge AP; serial mode uses **`bridge_serial_port`** and **`bridge_serial_baudrate`** (default **921600**). Saved bridge profiles and connect helpers live under **`/settings/wifi/*`** (see below). Architecture: [espnow-architecture.md](espnow-architecture.md).
- **Storage.** Each resource is a collection (`device`, `zone`, `preset`, `profile`, `palette`, `pattern`, `sequence`, `scene`, `group`, `output`, `settings`), stored as one JSON object of id → record on the flash filesystem. New records get the next numeric id (highest + 1), as a string. Devices are keyed by MAC (12 lowercase hex digits, no colons) and patterns by name.
- **Current profile.** `settings.current_profile_id`, set by `POST /profiles/<id>/apply`. When it is unset or names a missing profile, the first profile is current. It is global (the same for every browser).
- **Profile scoping.** Presets and sequences belong to a profile (`profile_id`). The list routes return only the current profile's records, and the single-record routes answer 404 for another profile's. Groups with a `profile_id` are visible only while that profile is current; groups without one are shared.
- **Current zone.** A `current_zone` cookie, set by `POST /zones/<id>/set-current`. Without it, the current profile's first zone.
- **Migration.** At boot, groups, zones and sequences written by older versions get the fields described below.
**Wi-Fi drivers (optional):** **UDP** on port **8766** is the **discovery** channel: each driver’s JSON hello (**`device_name`**, **MAC**, optional **`type`**) **creates or updates** that device in **`db/device.json`** (keyed by MAC); the Pi echoes the datagram. After a valid hello with **`v`:** **`"1"`**, the Pi also opens an **outbound WebSocket** to that IP (**`wifi_driver_ws_port`**, default **80**; **`wifi_driver_ws_path`**, default **`/ws`**) for v1 commands; presets are not pushed automatically on connect (use **Send Presets** / profile apply). The Pi may send periodic UDP **hello** nudges to known Wi‑Fi device IPs when the WebSocket is down (**`wifi_driver_hello_interval_s`** in settings).
All JSON APIs use `Content-Type: application/json` for bodies and responses unless noted.
---
## Pages and static files
## UI behavior notes
The main UI has two modes controlled by the mode toggle:
- **Run mode**: optimized for operation (zone/preset selection and profile apply).
- **Edit mode**: shows editing/management controls (zones, presets, patterns, colour palette, send presets, profile management actions, **Devices** registry for LED driver names/MACs, and related tools).
Profiles are available in both modes, but behavior differs:
- **Run mode**: profile **apply** only.
- **Edit mode**: profile **create/clone/delete/apply**.
`POST /presets/send` is wired to the **Send Presets** UI action, which is exposed in Edit mode.
---
## Session and scoping
Several routes use **`@with_session`**: the server stores a **current profile** in the session (cookie). Endpoints that scope data to “the current profile” (notably **`/presets`**) only return or mutate presets whose `profile_id` matches that session value.
Profiles are selected with **`POST /profiles/<id>/apply`**, which sets `current_profile` in the session.
---
## Static pages and assets
| Method | Path | Description |
|--------|------|-------------|
| GET | `/` | Main UI |
| GET | `/settings/page` | Standalone settings page |
| GET | `/audio` | Live audio and beat page (level, tempo, bar position, tap) |
| GET | `/settings/editor` | Driver settings editor: sends a driver settings (`PUT /devices/<id>`) |
| GET | `/static/<path>` | UI scripts and styles |
| GET | `/favicon.ico` | 204 |
| GET | `/` | Main UI (`templates/index.html`) |
| GET | `/settings/page` | Standalone settings page (`templates/settings.html`) |
| GET | `/favicon.ico` | Empty response (204) |
| GET | `/static/<path>` | Static files under `src/static/` |
Pages and static files are built into the firmware (gzipped, sent with `Content-Encoding: gzip`). They carry `Cache-Control: no-cache` and an `ETag` of the firmware build, so a browser revalidates each load (304 until the next update).
---
## Controller
## WebSocket: `/ws`
Connect to **`ws://<host>:<port>/ws`**.
- Send **JSON**: the object is forwarded through the **ESP-NOW bridge** as a **devices envelope** (or legacy MAC-prefixed / binary payload). Optional key **`to`**: 12-character hex MAC address; if present it is removed from the object and the payload is sent to that peer; otherwise the default destination from settings is used. Example envelope: [msg.json](msg.json).
- Send **non-JSON text**: forwarded as raw bytes with the default address.
- On send failure, the server may reply with `{"error": "Send failed"}`.
Wi-Fi devices are not targeted by `/ws` directly; use **`POST /presets/send`**, device routes, or **`POST /patterns/<name>/send`** as appropriate.
---
## HTTP API by resource
Below, `<id>` values are string identifiers used by the JSON stores. **Device** ids are **12-character lowercase hex MACs** (no colons); other resources typically use numeric string ids.
### Settings — `/settings`
| Method | Path | Description |
|--------|------|-------------|
| GET | `/status` | IP, `eth` (ip, mask, gw, up), `ap_ip`, `ap_clients` (`[{mac, ip}]` on the Wi-Fi access point), MAC, uptime, `free_heap`, `free_internal` (internal RAM), mic level, tempo and beat counts, ESP-NOW and link statistics |
| POST | `/reboot` | Replies `{"message":"rebooting"}`, then restarts after 0.5 s |
| GET | `/ota` | Running image: partition, version, build time, IDF version, sha |
| POST | `/ota` | Body: the raw firmware `.bin` (web UI included). Written to the idle slot, made the boot image, then the board reboots. A new image confirms itself after staying up a few seconds; one that crashes on start rolls back. `make ota HOST=<ip>` |
| GET | `/db/<collection>` | Export a whole collection |
| PUT | `/db/<collection>` | Replace a whole collection. Body: the object of id → record. Reply: `{"records": n}` |
| GET | `/settings` | Full settings object (from `settings.json` / `Settings` model). |
| PUT | `/settings/settings` | Merge keys into settings and save. Returns `{"message": "Settings updated successfully"}`. |
| GET | `/settings/wifi/ap` | Saved Wi‑Fi AP fields: `saved_ssid`, `saved_password`, `saved_channel`, `active` (Pi: `active` is always false). |
| POST | `/settings/wifi/ap` | Body: `ssid` (required), `password`, `channel` (1–11). Persists AP-related settings. |
| GET | `/settings/page` | Serves `templates/settings.html`. |
**Bench tests** (see `docs/BENCH_TEST.md`):
### Bridge — `/settings/wifi`
Pi-side bridge configuration (ESP-NOW path to drivers). Mounted from `controllers/wifi_bridge.py`.
| Method | Path | Description |
|--------|------|-------------|
| GET, POST | `/test/loss` | Simulated ESP-NOW loss. Body `{"percent": 0–100, "beats": bool}` (whether beat frames are dropped too). Reply: the current setting |
| POST | `/test/beats` | Body `{"bpm": 30–300, "count": n}` (0 = until stopped): synthetic beats to the drivers, with delivery and latency measured from their echoes. The mic's beats are muted meanwhile |
| GET | `/test/beats` | Results so far |
| POST | `/test/beats/stop` | Stop the generator |
| GET | `/settings/wifi/interfaces` | List Wi‑Fi interfaces via NetworkManager (`nmcli`). |
| GET | `/settings/wifi/scan?device=<ifname>` | Scan SSIDs on the given interface. |
| GET | `/settings/wifi/bridges` | Bridge state: `bridge_transport`, `bridge_ws_url`, `bridge_connected`, `wifi_interface`, saved **`bridges`** profiles, serial port/baud. |
| PUT | `/settings/wifi/bridges` | Merge bridge settings and/or replace the **`bridges`** profile list. |
| DELETE | `/settings/wifi/bridges/<id>` | Remove a saved bridge profile. |
| POST | `/settings/wifi/bridges/<id>/connect` | Connect using a saved profile (`transport`: `wifi` or `serial`). |
| POST | `/settings/wifi/connect` | Join a bridge AP and open its WebSocket. Body: `device`, `ssid`, optional `password`, `ap_ip` (default `192.168.4.1`), `ws_port`, `label`, `save_profile`. |
| POST | `/settings/wifi/serial/connect` | Open the bridge over USB serial. Body: `port`, optional `baudrate`, `label`, `save_profile`. |
## Settings — `/settings`
### Devices — `/devices`
Registry in `db/device.json`: storage key **`<id>`** is the device **MAC** (12 lowercase hex characters, no colons). Each record includes:
| Field | Description |
|-------|-------------|
| **`id`** | Same as the storage key (12-char hex MAC). |
| **`name`** | Shown in the UI; matched when building zone **`select`** lists. |
| **`type`** | `led` (only value today; extensible). |
| **`transport`** | `espnow` (default) or `wifi`. |
| **`address`** | For **`espnow`**: same as **`id`** (MAC). For **`wifi`**: IP or hostname used for outbound WebSocket / OTA. |
| **`connected`** | Response-only on GET list/detail: always **`null`** today (ESP-NOW has no live session flag on the Pi). |
| **`default_pattern`**, **`zones`** | Optional. Legacy **`tabs`** may still appear in old files and is migrated away on load. |
Drivers also **self-register** on ESP-NOW **ANNOUNCE** (bridge uplink) or Wi‑Fi UDP hello; manual **`POST /devices`** is optional.
| Method | Path | Description |
|--------|------|-------------|
| GET | `/settings` | The settings object |
| PUT | `/settings` or `/settings/settings` | Merge keys into the settings. Reply: `{"message": "Settings updated successfully"}` |
| GET | `/devices` | Map of device id → device object (includes **`connected`**). |
| GET | `/devices/<id>` | One device, 404 if missing. |
| POST | `/devices` | Create. Body: **`name`** (required), **`type`** (default `led`), **`transport`** (default `espnow`), optional **`address`**, **`mac`** (required for Wi‑Fi when address is set), **`default_pattern`**, **`zones`**. Returns `{ "<id>": { ... } }`, 201. |
| PUT | `/devices/<id>` | Partial update. **`name`** cannot be cleared. **`id`** in the body is ignored. **`type`** / **`transport`** validated; **`address`** normalised for the resulting transport. |
| DELETE | `/devices/<id>` | Remove device. |
| POST | `/devices/<id>/identify` | ESP-NOW: sends a short red **blink** preset (`__identify`, 10 Hz) via the bridge, then **`off`** after ~2 s. Not persisted on the Pi. |
| POST | `/groups/<id>/identify` | Same identify blink for every device in the group (broadcast envelope; drivers filter by group membership). |
Keys with meaning on the controller (others are stored as they are):
| Key | Checked | Meaning |
|-----|---------|---------|
| `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`) |
| `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 |
| `wifi_channel` | integer 1–11 | Stored for reference. The controller's ESP-NOW channel is set at build time (`make menuconfig`) |
| `audio_simulated_bpm` | clamped to 60–200 | Tempo of the beat clock (default 120) |
| `sequence_switch_wait` | `beat` or `downbeat` | When a newly started sequence takes over from the playing one |
| `audio_beat_phase_ms` | integer 0–500 | Stored for the UI |
| `audio_input_volume` | integer 0–200 | Stored for the UI |
| `current_profile_id` | | Set by profile apply and import |
| `audio_timing` | | Set by `/api/audio/start` and `/stop` |
Defaults filled at boot: `wifi_channel` (the build's ESP-NOW channel) and `global_brightness` (255).
## Profiles — `/profiles`
A profile is `{name, type: "zones", zones: [zone ids], scenes, palette_id}`.
### Profiles — `/profiles`
| Method | Path | Description |
|--------|------|-------------|
| GET | `/profiles` | `{"profiles": {...}, "current_profile_id": "<id>"}` |
| GET | `/profiles/current` | `{"id": "<id>", "profile": {...}}`; 404 when there are no profiles |
| GET | `/profiles/<id>` | One profile (`current` works as an id) |
| POST | `/profiles` | Create. Body: `name` and any other fields; optional `seed_dj_zone`. Reply `{"<id>": profile}`, 201. See below |
| PUT | `/profiles/<id>`, `/profiles/current` | Merge fields |
| POST | `/profiles/<id>/apply` | Make it current. Reply `{"message": "Profile applied", "id": "<id>"}` |
| POST | `/profiles/<id>/clone` | Copy with its own palette, zones and presets (preset references in the zones point at the copies). Body: optional `name`. 201 |
| DELETE | `/profiles/<id>` | Delete it with its presets and sequences, and its zones and palette unless another profile lists them |
| GET | `/profiles/<id>/export` | Profile bundle (see Import and export) |
| POST | `/profiles/import` | Body: `{"bundle": {...}, "name"?, "apply"? (default true)}` or the bundle itself. Reply `{"<id>": profile, "id": "<id>"}`, 201 |
| GET | `/profiles` | `{"profiles": {...}, "current_profile_id": "<id>"}`. Ensures a default current profile when possible. |
| GET | `/profiles/current` | `{"id": "...", "profile": {...}}` |
| GET | `/profiles/<id>` | Single profile. If `<id>` is `current`, same as `/profiles/current`. |
| POST | `/profiles` | Create profile. Body may include `name` and other fields. Optional `seed_dj_zone` (request-only) seeds a DJ zone + presets. New profiles always get a populated `default` zone. Returns `{ "<id>": { ... } }` with status 201. |
| POST | `/profiles/<id>/apply` | Sets session current profile to `<id>`. |
| POST | `/profiles/<id>/clone` | Clone profile (zones, palettes, presets). Body may include `name`. |
| PUT | `/profiles/current` | Update the current profile (from session). |
| PUT | `/profiles/<id>` | Update profile by id. |
| DELETE | `/profiles/<id>` | Delete profile. |
A store with no profile gets one at boot, `default`, with the same seed, a starter palette and an empty `default` group that its zone plays to. A new profile gets an empty palette, eight presets (`on`, `off`, `rainbow`, `Colour Cycle`, `transition`, `flicker`, `flame`, `twinkle`) and a zone `default` that lists them and names driver `1`. With `seed_dj_zone` it also gets three `DJ …` presets in a zone `dj` naming driver `dj`.
### Presets — `/presets`
## Presets — `/presets`
A preset has `name`, `pattern`, `colors` (`#RRGGBB`), `brightness`, `delay`, `n1`–`n8`, `profile_id`, and optionally `auto`, `palette_refs` (palette index per colour slot), `background` / `background_palette_ref`, `mode` (sent as `n6`), `manual_beat_n`, `fade` (0–10000 ms: crossfade from what the strip showed when the preset is selected) and `beat_time` (`true`: the delay and timing parameters of patterns that support it count quarter beats, so the preset follows the tempo). New presets start with every field set and belong to the current profile.
**Animation patterns** (driver patterns, labels in `/patterns`). Each plays once with `auto: false` and holds its end state; with `auto: true` it repeats.
- One-shots: `hit` (flash with attack, hold and decay), `keyframes` (ramp through the colours with easing).
- Field patterns, which span the whole rig using each driver's place from `/devices/layout`: `sweep`, `ripple`, `spin`, `grow`, `field_wave`.
Scoped to **current profile** in session (see above).
| Method | Path | Description |
|--------|------|-------------|
| GET | `/presets` | The current profile's presets |
| GET | `/presets/<id>` | One preset (404 for another profile's) |
| POST | `/presets` | Create in the current profile. Reply `{"<id>": preset}`, 201 |
| PUT | `/presets/<id>` | Merge fields |
| DELETE | `/presets/<id>` | Delete |
| POST | `/presets/push` | Send driver messages. Body: `{"sequence": [message, ...]}` or `{"payload": message}`, optional `targets` (MACs: acked unicast to each). Without targets, broadcast. Reply `{"message": "Delivered"}`. See Driver messages |
| POST | `/presets/send` | Send stored presets. Body: `preset_ids` (or `ids`), `save` (default true), `default` (startup preset id), `targets` or `destination_mac`. Reply `{"message": "Presets sent", "presets_sent": n}` |
| GET | `/presets/<id>/export` | Preset bundle |
| POST | `/presets/import` | Body: a preset bundle (or `{"bundle": ...}`). New id in the current profile, 201 |
| GET | `/presets` | Map of preset id → preset object for the current profile only. |
| GET | `/presets/<id>` | One preset, 404 if missing or wrong profile. |
| POST | `/presets` | Create preset; server assigns id and sets `profile_id`. Body fields stored on the preset. Returns `{ "<id>": { ... } }`, 201. |
| PUT | `/presets/<id>` | Update preset (must belong to current profile). |
| DELETE | `/presets/<id>` | Delete preset. |
| POST | `/presets/send` | Push presets to the LED driver over the configured transport (see below). |
## Zones — `/zones`
**`POST /presets/send` body:**
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).
```json
{
"preset_ids": ["1", "2"],
"save": true,
"default": "1",
"destination_mac": "aabbccddeeff"
}
```
- **`preset_ids`** (or **`ids`**): non-empty list of preset ids to include.
- **`save`**: if true, the outgoing message includes `"save": true` so the driver may persist presets (default true).
- **`default`**: optional preset id string; forwarded as top-level `"default"` in the driver message (startup selection on device).
- **`destination_mac`** (or **`to`**): optional 12-character hex MAC for unicast; omitted uses the transport default (e.g. broadcast).
Response on success includes `presets_sent`, `messages_sent` (chunking splits payloads so each JSON string stays ≤ 240 bytes).
Stored preset records can include:
- `colors`: resolved hex colours for editor/display.
- `palette_refs`: optional array of palette indexes parallel to `colors`. If a slot contains an integer index, the colour is linked to the current profile palette at that index.
### Zones — `/zones`
| Method | Path | Description |
|--------|------|-------------|
| GET | `/zones` | `{"zones": {...all zones}, "zone_order": [current profile's zone ids], "current_zone_id", "profile_id"}` |
| GET | `/zones/current` | `{"zone": {...}, "zone_id": "<id>"}`, or 404 `{"error", "zone": null, "zone_id": null}` |
| GET | `/zones/<id>` | One zone |
| POST | `/zones` | Create (body: `name` required, `names` or `ids`, `group_ids`, `presets`, `content_kind`, ...). Added to the current profile's zone list. 201 |
| PUT | `/zones/<id>` | Merge fields |
| DELETE | `/zones/<id>` | Delete (`current` works as an id) and remove it from every profile. Clears the cookie if it was current |
| 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>/stop` | Select `off` on the zone's groups. `{"stopped": bool}` |
| GET | `/zones/engine/status` | Sequence playback status (as `/sequences/status`) |
| GET | `/zones` | `zones` (map of zone id → zone object), `zone_order`, `current_zone_id`, `profile_id` for the session-backed profile. |
| GET | `/zones/current` | Current zone from cookie/session. |
| POST | `/zones` | Create zone; optional JSON `name`, `names`, `presets`; can append to current profile’s zone list. |
| GET | `/zones/<id>` | Zone JSON. |
| PUT | `/zones/<id>` | Update zone. |
| DELETE | `/zones/<id>` | Delete zone; can delete `current` to remove the active zone; updates profile zone list. |
| POST | `/zones/<id>/set-current` | Sets `current_zone` cookie. |
| POST | `/zones/<id>/clone` | Clone zone into current profile. |
## Groups — `/groups`
A group lists drivers by MAC (`devices`) and carries `output_brightness` (0–255), driver defaults (`wifi_driver_display_name`, `wifi_driver_num_leds`, `wifi_color_order`, `wifi_startup_mode`) and pattern fields. MACs are normalised to 12 lowercase hex digits. A driver's group membership is every group listing its MAC (see Driver groups), sent to it whenever groups, zones or devices change.
### Palettes — `/palettes`
| Method | Path | Description |
|--------|------|-------------|
| GET | `/groups` | Groups visible in the current profile |
| GET | `/groups/<id>` | One group (404 when scoped to another profile) |
| POST | `/groups` | Create with defaults; `profile_scoped: true` ties it to the current profile, `profile_id` may only name the current profile or be null. Reply: the group, 201 |
| PUT | `/groups/<id>` | Merge fields |
| DELETE | `/groups/<id>` | Delete |
| POST | `/groups/<id>/brightness` | Each member gets its combined brightness, saved on the driver. `{"message", "sent", "errors": [{mac, error}]}` |
| POST | `/groups/<id>/driver-config` | Each member gets `device_config` from the group's driver defaults (body fields override for this send). 400 when none is set |
| POST | `/groups/<id>/identify` | All members blink red together for 2 s, then go off. 400 when the group has no devices |
**Combined brightness** for a driver: `round(255 × global/255 × g₁/255 × … × device/255 [× zone/255])`, with one factor per group listing it (`output_brightness`), the device's `output_brightness` and, when given, the zone slider.
## Devices — `/devices`
A device is `{id: MAC, name, type: "led", transport: "espnow" | "wifi", address, default_pattern, zones, output_brightness?}`. ESP-NOW drivers register themselves when they boot (announce) and when they answer a ping. For ESP-NOW devices `address` is the MAC. The controller has no Wi-Fi driver transport: Wi-Fi records are kept, but nothing is sent to them.
| Method | Path | Description |
|--------|------|-------------|
| GET | `/devices` | All devices, each with `connected` (`null` for ESP-NOW, `false` for Wi-Fi) |
| GET | `/devices/<id>` | One device (the id may be written with colons) |
| POST | `/devices` | Create. `name` required; `mac` (or, for ESP-NOW, a MAC in `address`); `transport` `espnow` (default) or `wifi`. Reply `{"<mac>": device}`, 201; 409 for a MAC already registered |
| PUT | `/devices/<id>` | Merge fields. `name` cannot be blank, the MAC cannot change, `output_brightness` 0–255. Changing `name`, `max_brightness`, `num_leds`, `color_order`, `startup_mode` or `reversed` also sends them to the driver as `device_config` |
| DELETE | `/devices/<id>` | Delete |
| GET | `/devices/status` | Per driver: `{"last_ack_ms_ago": ms or -1, "failed_messages": n}` from the acked link |
| POST | `/devices/ping` | Body `{"timeout_s": 0.5–30, "broadcast": bool}` (timeout default 3). Sends the ping as an acked unicast to each known device and collects replies; `"broadcast": true`, or no known devices, broadcasts it instead so new drivers are found: `{"ok", "ping_id", "timeout_s", "responses": {mac: {mac, name, rtt_ms}}, "registered": n}`. Drivers that answer are added or renamed |
| POST | `/devices/layout` | Body `{"placements": {mac: {x0, y0, x1, y1} \| null}, "center"?: {x, y}}`: where each bar sits, in any units with y up, and the rig's centre (kept in `settings.rig_center`; without one, the layout's bounding-box centre). `x0,y0` is LED 1, the data-in end; `null` removes a bar. Saved as the device's `placement`. Then every placed ESP-NOW driver gets `device_config.place`: its ends relative to the centre, scaled so the furthest end is 1 from it. Reply `{"updated", "sent", "failed"}`; 400 without `placements` |
| POST | `/devices/groups` | Send every ESP-NOW driver its groups and wait for the acks: `{"ok", "total", "sent", "failed"}` (503 when any failed, 400 with no ESP-NOW devices) |
| POST | `/devices/resolve-brightness` | Body `{"macs": [...], "zone_brightness"?}` → `{"values": {mac: brightness}}` |
| POST | `/devices/<id>/brightness` | Body `{"zone_brightness"?}`: send the combined brightness, saved on the driver. `{"message", "brightness"}` |
| POST | `/devices/<id>/driver-config` | Body: any of `name`, `num_leds` (1–2048), `color_order`, `startup_mode` (`default`, `last`, `off`) |
| POST | `/devices/<id>/identify` | Red 10 Hz blink for 2 s, then off |
## 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.
- `kind`: `"sequence"` (default) or `"animation"`: a clip that is fired once over whatever runs (see Animations). Both are stored here.
- `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.
- `offset`: beats (or seconds, time lanes) before the lane starts, on the first pass only. With a copy of a lane this gives a canon or ripple.
- `rate`: 0.25–4, speed multiplier. A 1-beat step at rate 2 lasts half a beat.
- `targets`: indexes into `targets` the lane plays to. Without them the lane's groups come from the older fields: `lanes_group_ids[lane]`, else `group_ids`, else (single lane) the step's `group_ids`, else the zone's groups.
- `chase`: `{order: "forward" | "reverse" | "bounce" | "random", width (default 1), others: "off" (default) | "hold"}`. Each step moves the lit position along the lane's targets (in the order listed in the lane's `targets`). The step's preset goes to `width` targets from there, and the rest go off or keep what they show.
- A step is `{preset_id, beats (default 1, from 0.25), seconds (default 3, 0.1–3600), targets?, others?, rest?, animation_id?, length?, group_ids?}`:
- `beats` / `seconds`: how long it lasts, by its lane's mode.
- `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).
| Method | Path | Description |
|--------|------|-------------|
| GET | `/sequences` | The current profile's sequences |
| GET | `/sequences/<id>` | One sequence |
| 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/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) |
| POST | `/sequences/import` | Body: a sequence bundle. The presets are copied into the current profile and the steps point at the copies. 201 |
**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`.
- **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.
- 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.
- **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.
## Audio — `/api/audio`
| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/audio/status` | `{"status": {...}}`, see below |
| GET | `/api/audio/events` | Server-sent events, `data: {"type": "status" | "beat", "status": {...}}`: a status event first, one on every detected beat, and a status heartbeat every 0.5 s |
| POST | `/api/audio/start` | Mic beats time sequences and go to the drivers. Saved. `{"ok": true, "status"}` |
| POST | `/api/audio/stop` | The beat clock times sequences instead; the mic's beats stop going to the drivers. Saved |
| POST | `/api/audio/reset` | Forget the tempo and bar position and track again (409 while stopped) |
| POST | `/api/audio/anchor-bar` | Make the last beat bar beat 1 (409 while stopped) |
| GET | `/api/audio/devices` | The single input: `{"devices": [{"id": "i2s", "name", "display_name", "is_default": true}], "diagnostics": {}}` |
| PUT | `/api/audio/device` | Body `{"device_select"}`: stored only (there is one microphone) |
Status fields: `running` (audio timing on), `bpm` (locked tempo, `null` without a lock, the clock's tempo while stopped), `bpm_simulated`, `beat_seq`, `bar_beat`, `beats_per_bar`, `is_downbeat`, `bar_phase_readout`, `phase_confidence`, `input_level`, `last_beat_ts`, `sequence` (playback status), `sequence_pending`, `beat_readout`, `sequence_switch_wait` (in effect) and `sequence_switch_wait_saved`, `audio_simulated_bpm`, `simulated_beat_tick`, `audio_run`, `beat_phase_ms`, `input_volume`.
The `/audio` page uses its own routes:
| Method | Path | Description |
|--------|------|-------------|
| GET | `/audio.wav` | Live microphone audio (16 kHz mono WAV stream; one listener at a time) |
| GET | `/beats` | Server-sent events: `beat` (`bpm`, `n`, `bar`, `meter`, `sure`, `us`), `onset`, and `tempo` every second |
| POST | `/tap` | The user tapped bar beat 1 now |
| GET | `/time` | Board clock (`{"us": ...}`) for the page to line its clock up with |
## Patterns — `/patterns`
Pattern metadata is the `pattern` collection, keyed by name. Pattern sources are the led-driver `src/patterns/*.py` files built into the firmware, plus uploads (stored on the controller, and they take precedence). `on` and `off` are built into the driver and have no file.
| Method | Path | Description |
|--------|------|-------------|
| GET | `/patterns`, `/patterns/definitions` | Metadata, plus `{}` for every pattern file without metadata |
| GET | `/patterns/<name>` | Metadata record |
| POST | `/patterns` | Body `{name, data: {...}, ...}`: `data` and the other keys become the record under `name`. Reply: the record, 201 |
| PUT, DELETE | `/patterns/<name>` | Merge, delete (the file stays) |
| GET | `/patterns/ota/manifest` | `{"files": [{"name": "x.py", "url": "http://<Host>/patterns/ota/file/x.py"}]}` |
| GET | `/patterns/ota/file/<name>.py` | The source (`text/plain`); 400 for `on`/`off`, 404 when missing |
| POST | `/patterns/upload` | Body `{name, code, overwrite?}`: store a source. 409 when it exists and `overwrite` is false. 201 |
| POST | `/patterns/driver` | Body `{name, code, overwrite?, min_delay?, max_delay?, max_colors?, n1?..n8?}`: store the source and its metadata (`n1`–`n8` are parameter labels). The name must be an identifier. 201 |
| POST | `/devices/<id>/patterns/push` | 400: not supported for ESP-NOW devices |
## Palettes — `/palettes`
A palette is a list of colours.
| Method | Path | Description |
|--------|------|-------------|
| GET | `/palettes` | `{id: [colours]}` |
| GET | `/palettes` | Map of id → colour list. |
| GET | `/palettes/<id>` | `{"colors": [...], "id": "<id>"}` |
| POST | `/palettes` | Body `{"colors"}`. Reply `{"id", "colors"}`, 201 |
| PUT | `/palettes/<id>` | Body `{"colors"}`: replaces the list |
| DELETE | `/palettes/<id>` | Delete |
| POST | `/palettes` | Body may include `colors`. Returns palette object with `id`, 201. |
| PUT | `/palettes/<id>` | Update colours (`name` ignored). |
| DELETE | `/palettes/<id>` | Delete palette. |
## Scenes — `/scenes`
Plain records: GET (list, one), POST (201), PUT (merge), DELETE. Scenes do not play.
## Outputs — `/outputs`
Network pixel fixtures. An output is `{id, name, protocol: "ddp" | "artnet" | "sacn" | "dmx_serial", host, port, universe, channel, serial_port, dmx_mode, pixel_count, pixel_offset, color_order, reverse, brightness, fps, enabled}` with defaults filled in. The checks:
- `ddp` needs a `host`. `dmx_serial` needs a `serial_port`, and its pixels must fit one DMX universe.
- Number ranges: `port` 1–65535, `universe` 0–32767 (sACN 1–63999), `channel` 1–512, `brightness` 0–255, `fps` 1–120.
- `color_order` is one of `rgb rbg grb gbr brg bgr`.
### Groups — `/groups`
| Method | Path | Description |
|--------|------|-------------|
| GET | `/outputs`, `/outputs/<id>` | List, one |
| POST | `/outputs` | Create (400 with the failed check). Reply: the output, 201 |
| PUT | `/outputs/<id>` | Merge and check again |
| DELETE | `/outputs/<id>` | Delete |
| POST | `/outputs/<id>/test` | Body `{"step_s": 0.1–5}` (default 1): solid red, green, blue and white for `step_s` each at `fps`, then black. `{"message", "status": {name, protocol, kind, pixel_count, frames, packets, bytes, errors, last_error}}`. 503 for `dmx_serial` (no USB-DMX adapter on this board) |
| GET | `/groups` | All groups. |
| GET | `/groups/<id>` | One group. |
| POST | `/groups` | Create; optional `name` and fields. |
| PUT | `/groups/<id>` | Update. |
| DELETE | `/groups/<id>` | Delete. |
Zones do not render to outputs: only the test pattern is sent.
### Scenes — `/scenes`
## WebSocket — `/ws`
| Method | Path | Description |
|--------|------|-------------|
| GET | `/scenes` | All scenes. |
| GET | `/scenes/<id>` | One scene. |
| POST | `/scenes` | Create (body JSON stored on scene). |
| PUT | `/scenes/<id>` | Update. |
| DELETE | `/scenes/<id>` | Delete. |
On connect the controller sends `{"type": "device_tcp_snapshot", "connected_ips": []}` (there are no Wi-Fi driver sessions). Each text frame is a driver message (JSON object), sent as `/presets/push` would send it: an optional `to` (MAC) addresses one driver, otherwise it is broadcast. A frame that is not a JSON object, or a failed send, gets `{"error": ...}` back. A plain GET gets 426.
### Sequences — `/sequences`
| Method | Path | Description |
|--------|------|-------------|
| GET | `/sequences` | All sequences. |
| GET | `/sequences/<id>` | One sequence. |
| POST | `/sequences` | Create; may use `group_name`, `presets` in body. |
| PUT | `/sequences/<id>` | Update. |
| DELETE | `/sequences/<id>` | Delete. |
### Patterns — `/patterns`
Pattern metadata lives in **`db/pattern.json`**; driver source files live under **`led-driver/src/patterns/`**. Several routes expose a **runtime map** (metadata merged with on-disk `.py` names so new files appear in menus).
| Method | Path | Description |
|--------|------|-------------|
| GET | `/patterns` | Runtime pattern map (object keyed by pattern id). |
| GET | `/patterns/definitions` | Same runtime map (intended for UI “definitions” clients). |
| GET | `/patterns/ota/manifest` | JSON `{"files":[{"name":"blink.py","url":"http://<Host>/patterns/ota/file/blink.py"},...]}` for OTA pulls. Requires **`Host`** header. |
| GET | `/patterns/ota/file/<name>` | Raw **`.py`** source for one driver pattern (`name` must be a safe filename, e.g. `rainbow.py`). |
| POST | `/patterns/<name>/send` | Push a **manifest** JSON line to **Wi-Fi** devices so they pull one pattern file over HTTP. Body may include **`device_id`** to target one device; otherwise all Wi-Fi devices with an **`address`** are tried. **`<name>`** may be with or without `.py`. |
| POST | `/patterns/upload` | Body JSON: **`name`**, **`code`**, optional **`overwrite`** (default true). Writes **`led-driver/src/patterns/<name>.py`**. |
| POST | `/patterns/driver` | Body JSON: **`name`** (identifier), **`code`**, optional metadata (`min_delay`, `max_delay`, `max_colors`, `n1`…`n8`, **`overwrite`**). Creates/updates both the **`.py`** file and **`db/pattern.json`** via the Pattern model. |
| GET | `/patterns/<id>` | One pattern record from the Pattern model (metadata only). |
| POST | `/patterns` | Create (`name`, optional `data`). |
| PUT | `/patterns/<id>` | Update. |
| DELETE | `/patterns/<id>` | Delete. |
**Devices — pattern OTA push**
| Method | Path | Description |
|--------|------|-------------|
| POST | `/devices/<id>/patterns/push` | Wi-Fi only. Asks the driver at **`address`** to pull pattern files from this server. Optional body **`manifest`**: either a **URL string** pointing at a manifest JSON document, or a **manifest object** (same shape as in driver messages). If omitted, a default manifest is built from the request **`Host`** header. |
---
## Driver messages
## LED driver message format (transport / ESP-NOW / Wi-Fi)
The UI, `/presets/push`, `/ws` and the controller itself send drivers **v1 messages**: JSON objects with `"v": "1"`. The controller does not send them as they are:
- **Binary envelope.** A message that only carries presets, a select, brightness, `save` and `groups` goes out as a compact binary envelope (`main/envelope.c`, mirrored by `test/binary_envelope.py`).
- Version 2 is the usual frame.
- A frame whose presets use `fade` or `beat_time` is version 3: each preset record is followed by `[ext_len][key, len, value]…`, with key 1 the fade ms (u16) and key 2 the beat timing (u8).
- Drivers skip keys they don't know. Drivers without v3 support ignore v3 frames, so they miss only presets that use the new fields.
- **JSON.** Any other message goes as JSON with short keys, split across several messages when it does not fit one ESP-NOW frame. A preset with a background colour (`bg`) is one of these: the envelope has no field for it.
- **Delivery.** Broadcasts are never acked (envelopes go out twice, JSON once); drivers that miss a state change notice from the state digest and ask to be brought up to date. Messages with `targets` are unicast to each MAC, acked and retried.
Messages are JSON objects. The Pi **`build_message()`** helper (`src/util/espnow_message.py`) produces per-device bodies; **`build_devices_envelope()`** (`src/util/bridge_envelope.py`) wraps them for the bridge WebSocket or USB serial link. Wi-Fi drivers accept the same logical body as a **single JSON text message** over the outbound WebSocket.
### Fields
### Devices envelope (Pi → bridge)
| Long key | Short | Meaning |
|----------|-------|---------|
| `presets` | `p` | Map of preset id → preset |
| `select` | `s` | `["preset_id"]` or `["preset_id", step]` for every driver addressed; or a map of driver name → that list |
| `groups` | `g` | Only drivers in one of these groups apply the message |
| `set_groups` | `sg` | With `groups`: replace the driver's group list |
| `save` | `sv` | Persist presets, brightness or config on the driver |
| `default` | `df` | Startup preset id |
| `device_config` | `dc` | `name`, `num_leds`, `color_order`, `startup_mode`, `max_brightness`, `reversed`, `place` ([x0, y0, x1, y1] in rig coordinates, see `/devices/layout`; `null` clears it), `usb_log` (per-beat USB log; on reboot). Drivers print nothing over USB unless their `debug` or `usb_log` setting is on: on the ESP32-C3, unread USB output blocks the driver |
| `clear_presets` | `cp` | Drop stored presets |
| `manifest` | `mf` | Pattern files to fetch (Wi-Fi drivers) |
| `b` | | Driver brightness 0–255 |
Preset fields: `p`/`pattern`, `c`/`colors` (`#RRGGBB`), `d`/`delay` (ms, default 100), `b`/`brightness` (0–255), `a`/`auto` (`true` runs freely, `false` steps once per beat), `bg`/`background`, `n1`–`n6` (pattern parameters; `n5` is reverse, `n6` the style mode), `f`/`fade`, `tb`/`beat_time`. Other fields (`name`, `manual_beat_n`, …) are dropped on the way out.
Sending `select` again with the same preset is a beat for that preset. Selecting `off` resets the step, so the next select starts every driver at step 0 unless a step is given.
### Driver groups
A driver keeps a list of group ids and applies a group command (or a message with `groups`) only when it holds one of them. The controller sends each ESP-NOW driver its list whenever groups, zones or devices change, when the driver boots, and when it asks to be brought up to date. A driver that has failed three messages in a row gets these updates at most every 30 s until it answers again. The list holds:
- every group (`group` collection) whose `devices` lists the driver's MAC, by group id;
- `z<zone id>` for every zone whose `names` lists the driver's name (zones from before groups);
- its own group `d<mac>` (12 lowercase hex digits), always first, so a sequence target can name a single driver. It doesn't change any other membership.
A zone plays to its `group_ids` and, when it names drivers, to `z<zone id>`. A message with `groups` that fits the envelope goes out as one group command per group.
### Example
On the bridge link, traffic uses a top-level **`dv`** map (long name **`devices`** still accepted on receive):
```json
{
"v": "1",
"presets": {
"12": {"pattern": "chase", "colors": ["#ff0000", "#0000ff"], "delay": 80, "brightness": 255, "auto": true, "n1": 4, "n2": 4}
},
"select": ["12"],
"groups": ["3"],
"save": true
"dv": {
"e8:f6:0a:16:ea:10": {
"p": { "2": { "p": "on", "c": ["#FFFFFF"], "a": true } },
"s": ["2", 0],
"g": ["5"],
"sg": false,
"sv": true
}
}
}
```
Pattern parameters are documented in the led-driver repository.
See [espnow-architecture.md](espnow-architecture.md) for routing (`sg`, broadcast MAC `ff:ff:ff:ff:ff:ff`, and group filtering).
### Per-device body fields (inside `dv` or Wi-Fi WebSocket)
Short wire keys are used on the bridge and over ESP-NOW (long names still accepted on receive):
```json
{
"v": "1",
"p": { },
"s": ["preset_id", 0],
"sv": true,
"df": "preset_id",
"b": 255,
"g": ["5"],
"sg": false
}
```
| Short | Long | Meaning |
|-------|------|---------|
| `p` | `presets` | Map of preset id → preset object (see below). |
| `s` | `select` | **`["preset_id"]`** or **`["preset_id", step]`** — routing is by MAC envelope / group membership, not by device name. |
| `sv` | `save` | If true, driver may persist presets to flash. |
| `df` | `default` | Startup default preset id. |
| `g` | `groups` | Group ids for membership updates or broadcast filtering. |
| `sg` | `set_groups` | If true, replace stored group list before applying the body. |
- **`v`** (required): Must be `"1"` or the driver ignores the message.
- **`b`**: Optional **global** brightness 0–255 (driver applies this in addition to per-preset brightness).
### Preset object (wire / driver keys)
On the wire, presets use **short keys** (saves space in the ≤240-byte chunks):
| Key | Meaning | Notes |
|-----|---------|--------|
| `p` | Pattern id | `off`, `on`, `blink`, `rainbow`, `pulse`, `transition`, `chase`, `circle` |
| `c` | Colours | Array of `"#RRGGBB"` hex strings; converted to RGB on device |
| `d` | Delay ms | Default 100 |
| `b` | Preset brightness | 0–255; combined with global `b` on the device |
| `a` | Auto | `true`: run continuously; `false`: one step/cycle per “beat” |
| `n1`–`n6` | Pattern parameters | See below |
The HTTP app’s **`POST /presets/send`** path builds this from stored presets via **`build_preset_dict()`** (long names like `pattern` / `colors` in the DB are translated to `p` / `c` / …).
### Pattern-specific parameters (`n1`–`n6`)
#### Rainbow
- **`n1`**: Step increment on the colour wheel per update (default 1).
#### Pulse
- **`n1`**: Attack (fade in) ms
- **`n2`**: Hold ms
- **`n3`**: Decay (fade out) ms
- **`d`**: Off time between pulses ms
#### Transition
- **`d`**: Transition duration ms
#### Chase
- **`n1`**: LEDs with first colour
- **`n2`**: LEDs with second colour
- **`n3`**: Movement on even steps (may be negative)
- **`n4`**: Movement on odd steps (may be negative)
#### Circle
- **`n1`**: Head speed (LEDs/s)
- **`n2`**: Max length
- **`n3`**: Tail speed (LEDs/s)
- **`n4`**: Min length
### Select messages
```json
{
"select": {
"device_name": ["preset_id"],
"other_device": ["preset_id", 10]
}
}
```
- One element: select preset; step behavior follows driver rules (reset on `off`, etc.).
- Two elements: explicit **step** for sync.
### Beat and sync behavior
- Sending **`select`** again with the **same** preset name acts as a **beat** (advances manual patterns / restarts generators per driver logic).
- Choosing **`off`** resets step as a sync point; then selecting a pattern aligns step 0 across devices unless a step is passed explicitly.
### Example (compact preset map)
```json
{
"v": "1",
"save": true,
"presets": {
"1": {
"name": "Red blink",
"p": "blink",
"c": ["#FF0000"],
"d": 200,
"b": 255,
"a": true,
"n1": 0, "n2": 0, "n3": 0, "n4": 0, "n5": 0, "n6": 0
}
},
"select": {
"living-room": ["1"]
}
}
```
---
## Processing summary (driver)
1. Reject if `v != "1"`.
2. Apply optional top-level **`b`** (global brightness).
3. For each entry in **`presets`**, normalize colours and upsert preset by id.
4. If this device’s **`name`** appears in **`select`**, run selection (optional step).
5. If **`default`** is set, store startup preset id.
6. If **`save`** is set, persist presets.
---
## Error handling (HTTP)
Controllers typically return JSON with an **`error`** string and 4xx/5xx status codes. Invalid JSON bodies often yield `{"error": "Invalid JSON"}`.
---
## Notes
- **Human-readable preset fields** (`pattern`, `colors`, `delay`, …) are fine in the **web app / database**; the **send path** converts them to **`p` / `c` / `d`** for the driver.
- For a copy of the older long-key reference, see **`led-driver/docs/API.md`** in this repo (conceptually the same behavior; wire format prefers short keys).
-295
View File
@@ -1,295 +0,0 @@
# Bench test: one S3 controller and one LED driver
This walks one ESP32-S3 controller (W5500 Ethernet, INMP441 mic) and one `led-driver` unit through flashing, a smoke test, a lossy-link test and a beat latency measurement. Nothing here has been run on hardware yet, so treat the expected numbers as targets to check, not results.
## 0. What you need
- Controller: XIAO ESP32-S3 with a W5500 module wired as in `main/Kconfig.projbuild` (SCLK 7, MISO 8, MOSI 9, CS 2, INT 3, RST 1), Ethernet cable to a DHCP network. The mic is optional for this test; the bench generator makes its own beats.
- Driver: one `led-driver` unit (MicroPython, the `p2p` ESP-NOW branch) with a few LEDs. It needs no Wi-Fi network.
- A PC on the same network. Docker with `espressif/idf:v6.1` for building.
- For the true latency measurement: a logic analyzer or scope with two channels and a common ground. Optional: the software echo numbers need nothing extra.
**Channel rule.** ESP-NOW only works when both radios use the same channel. The p2p driver uses its `wifi_channel` setting (default 5); the controller's default is now 5 as well (`CONFIG_ESPNOW_CHANNEL` in `sdkconfig.defaults`). If your driver uses another channel, change the controller before building:
```bash
docker run --rm -v "$PWD":/project -w /project espressif/idf:v6.1 idf.py menuconfig
```
then *ESP-NOW config → Wi-Fi channel*. Alternatively set `CONFIG_ESPNOW_CHANNEL=<n>` in `sdkconfig.defaults` (delete `sdkconfig` after, so it is regenerated). To use the beat marker pin, also set `CONFIG_BEAT_TEST_GPIO` (for example 44) in the same menu.
## 1. Build and flash the controller
The repository root has a Makefile that wraps all of this: `make build`, `make flash`, `make monitor` (Ctrl-] to quit), `make log` (console for 10 s, no terminal needed), `make test`, and `make help` for the rest; `PORT=/dev/ttyACM1` selects another port. The manual commands below do the same thing.
```bash
tools/build_web.sh
docker run --rm -v "$PWD":/project -w /project espressif/idf:v6.1 idf.py build
```
Expect `Project build complete`, the app well under its 2 MB slot, with the web UI embedded (`www_dist/www.pack`). Fix ownership if Docker left it root-owned: `docker run --rm -v "$PWD":/project espressif/idf:v6.1 chown -R 0:0 /project`.
Flash with the S3 on USB (check which port it is; `ls /dev/ttyACM*`):
```bash
docker run --rm --device=/dev/ttyACM0 -v "$PWD":/project -w /project espressif/idf:v6.1 idf.py -p /dev/ttyACM0 flash
```
This writes the bootloader, partition table and app (the web UI is part of the app). Watch the log:
```bash
docker run --rm -it --device=/dev/ttyACM0 -v "$PWD":/project -w /project espressif/idf:v6.1 idf.py -p /dev/ttyACM0 monitor
```
Look for, in order: `store: ... records` lines, `espnow_tx: ESP-NOW up on channel N`, `rel: reliable link up`, `Ethernet Link Up`, `Got IP: x.x.x.x`, `HTTP server started`.
## 2. First checks (replace `$S3` with the IP)
```bash
export S3=192.168.1.50
curl -s http://$S3/status
```
Expect JSON with `uptime_s`, `reset_reason` (why the board last restarted, such as `panic`, `task_watchdog` or `brownout`; opening the USB serial port resets the board and replaces it with `usb`, so read it first), `bpm`, an `espnow` block and a `link` block (`ver` nonzero, `digests` increasing by one about every 1.5 s). If the mic hears music, `bpm` and `beats_sent` move too, which means beats are already being broadcast. Open `http://$S3/` in a browser: the UI should load, and the dev tools network tab should show `Content-Encoding: gzip` on `/static/*.js`.
```bash
curl -s -D - -o /dev/null -H 'Accept-Encoding: gzip' http://$S3/static/presets.js | grep -i -E 'content-encoding|content-type'
```
**Audio and beats.** `http://$S3/audio` is the mic page: live levels, tempo and bar position, a tap button to correct beat 1, and a Listen button for the 16 kHz mono stream. The underlying endpoints are `/audio.wav` (one listener at a time), `/beats` (server-sent events: `beat`, `onset`, `tempo`), `POST /tap` and `/time`. `/status` carries the mic levels (`mic_rms_dbfs`, `mic_spl_db`) and the beat state (`bpm`, `beat_locked`, `meter`, `bar_beat`, `bar_sure`).
## 3. Load data and add a test zone
Import the Pi database (the files hold your real zones and presets, so use a copy if you want a smaller test):
```bash
for n in device zone preset profile palette pattern sequence scene; do
curl -s -X PUT --data-binary @../db/$n.json http://$S3/db/$n; echo " $n"
done
```
The driver registers itself: it broadcasts a hello at boot, the controller adds it to the device list under its MAC and sends it its group list. Check with `curl -s http://$S3/devices/<mac>` once the driver is running (step 4). Zones are the drivers' groups: a zone's `names` must contain the driver's **name** exactly (`led-<mac>` by default, see its `settings.json`).
```bash
curl -s -X POST -d '{"name":"bench","names":["led-aabbccddeeff"]}' http://$S3/zones
curl -s -X POST -d '{"name":"bench red","pattern":"on","colors":["#ff0000"],"delay":100,"brightness":255,"auto":true}' http://$S3/presets
```
Note the returned ids (`<zone>` and `<preset>` below). Creating or changing a zone re-sends group lists to every registered ESP-NOW driver.
## 4. Prepare the driver
The driver runs the `p2p` branch of `led-driver` plus these files from this work: `src/beat_sync.py`, `src/espnow_rx.py`, and changed `src/main.py` and `src/presets.py`. Back up the device's own copies first (`mpremote fs cp :main.py ./main.py.bak`), then copy the new ones (`mpremote fs cp src/main.py :main.py` and so on) and reset.
Optional keys in the driver's `settings.json` for the later tests:
| key | value | meaning |
|---|---|---|
| `bench` | `true` | echo every fired beat to the controller and print stats every 50 beats |
| `beat_pin` | e.g. `5` | GPIO toggled on every fired beat, for the logic analyzer |
| `espnow_loss` | `0` | percent of received frames the driver discards (set later) |
After boot, the controller's `/devices` list should contain the driver's MAC and `/status` should show `link.acked` rising (the group list was acknowledged). `mpremote` interrupts the running program, so reset the driver after using it.
## 5. Smoke test
```bash
curl -s -X POST -d '{"preset_id":"<preset>"}' http://$S3/zones/<zone>/play
```
The driver's console should log the preset and select it received (once each, although the controller sends every state frame twice), and the LEDs should go red within a fraction of a second. Then:
```bash
curl -s -X POST http://$S3/zones/<zone>/stop # LEDs off
curl -s http://$S3/devices/status # last_ack_ms_ago / failed_messages per registered driver
```
Zone play is a group broadcast, so `devices/status` only changes for acked (unicast) traffic. Trigger one with a targeted push:
```bash
curl -s -X POST -d '{"sequence":[{"v":"1","select":{"led-aabbccddeeff":["<preset>"]}}],"targets":["aabbccddeeff"]}' http://$S3/presets/push
curl -s http://$S3/devices/status
```
Expected: `last_ack_ms_ago` is small (tens of ms) and `failed_messages` is 0. `/status` shows `link.acked` increased.
## 6. Lossy-link test
The loss mode discards a percentage of frames before the radio on the controller (all outgoing frames, and incoming acks and echoes). The driver can discard received frames too. This makes the retry, fragment and resync layers do real work without moving antennas.
```bash
# controller: 40% loss, beats included
curl -s -X POST -d '{"percent":40,"beats":true}' http://$S3/test/loss
curl -s http://$S3/status # sim_dropped counts dropped frames
```
Run these and compare with the table:
| test | how | expected |
|---|---|---|
| Acked unicast under loss | repeat the targeted push from step 5 twenty times at 40% (give each a different select step so you can tell them apart on the driver console) | all reach the driver; `link.retransmits` rises. A message needs its data and its ack to both survive, and there are 5 sends in total, so about 1 in 10 is reported as timed out even though the driver usually has it |
| Give up and report | set `percent` to 100, push once, wait 2 s | `link.ack_timeouts` +1 and `devices/status` shows `failed_messages: 1` |
| Lost broadcast, digest recovery | `percent` 100, play a different preset on the zone, then set `percent` 0 | the LEDs do not change at first, then within about 1.5 to 5 s the driver sends a resync and shows the new preset; `link.resyncs` +1 |
| Driver-side loss | set `"espnow_loss": 40` in the driver's `settings.json` (restore it afterwards), controller loss 0, push twenty times | every push is processed once on the driver (retransmissions are de-duplicated); `link.retransmits` rises. Lost acks are covered by the controller-side loss rows above, because that setting also drops incoming acks |
| Multi-message send | `POST /presets/send` with 10+ preset ids, `save: false` and `targets` | the controller packs the presets into a few binary messages (14 presets took 2); all arrive under loss, with retransmits. `save: true` makes the driver write its `presets.json`, so restore that file afterwards. Frame-level fragmentation exists in the link but nothing in the current API produces a message over one frame, so it is only covered by the driver's unit tests |
Set loss back to 0 when done: `curl -s -X POST -d '{"percent":0}' http://$S3/test/loss`.
Reading the numbers: the controller drops a reply with the same probability as a request, so under loss an unicast message needs both the data and the ack to survive. Resync requests are also subject to loss and to the driver's 3 s minimum gap, so recovery may take a few digests.
### Results of the first run (S3 to one p2p driver, channel 5)
| test | result |
|---|---|
| 20 acked pushes, controller loss 40% | 20 of 20 reached the driver; 19 acked, 1 reported timed out (its ack was lost); 19 retransmits; 34 frames dropped by the test mode |
| 1 push, loss 100% | gave up after 2.0 s with 4 retransmits; `failed_messages` 1; driver heard nothing |
| zone play during a 100% outage, then loss back to 0 | driver was untouched during the outage; 1.5 s after the link returned it received its groups, the preset and the select, one resync, and the new state |
| 20 acked pushes, driver-side loss 40% | 20 of 20 processed exactly once; 14 retransmits; 0 timeouts |
| `/presets/send` of 14 presets at driver loss 40% | 2 messages (209 and 217 bytes), both acked, 1 retransmit |
## 7. Beat latency and delivery
### Software numbers (no equipment)
Start synthetic beats with the driver in `bench` mode:
```bash
curl -s -X POST -d '{"bpm":120,"count":200}' http://$S3/test/beats
sleep 105
curl -s http://$S3/test/beats
```
Results include:
- `beats_sent`, `echoes` and `hit_pct_total`: the share of beats each driver fired on and reported. With no loss expect 100%.
- `rtt_minus_lead_min/avg/max_us`: time from the first beat copy going out to the driver's echo coming back, minus the 30 ms the driver deliberately waits (`CONFIG_BEAT_LEAD_MS`). This is out-airtime plus the driver's MicroPython work plus return airtime, so it overstates one-way delay. Expect roughly 2 to 15 ms; the maximum shows the worst case you will see on the LEDs.
- `spread_avg_us` and `spread_max_us`: only meaningful with two or more drivers; shows how far apart they fire for the same beat.
On the driver's serial console every 50 beats you get the true driver-side counts, for example `beat {'fires': 100, 'dups': 100, 'late': 0, 'freerun': 0}`:
- `fires`: beats it acted on.
- `dups`: second copies dropped (with the double send this should be close to `fires`).
- `freerun`: beats it generated itself because both copies were missed. Zero without loss.
- `late`: frames rejected as too soon or old.
### Delivery under loss
Repeat the run with loss on:
```bash
curl -s -X POST -d '{"percent":30,"beats":true}' http://$S3/test/loss
curl -s -X POST -d '{"bpm":120,"count":200}' http://$S3/test/beats
```
Judge delivery from the driver's own `fires` and `freerun` counts: with two copies the chance of missing both is about 9% at 30% loss, and the free-run covers those, so `fires` should stay near `beats_sent` with `freerun` around 9% of it. The controller's `hit_pct_total` is lower because echoes are dropped by the same loss setting; it is a lower bound, roughly `(1 - loss) × delivery`.
### Latency over USB (no extra equipment)
Both boards are on USB, so the PC can timestamp one event line from each and compare them. Settings already applied for this: the driver has `"usb_log": true` in `settings.json`. The controller prints `BT <beat> <microseconds>` for every synthetic beat; the driver prints `FIRE <beat> <ticks_us>` when it fires.
```bash
python3 tools/usb_latency.py --ctrl-port /dev/ttyACM0 --drv-port /dev/ttyACM1 --url http://$S3 --beats 200
```
The script starts the generator, reads both ports, and maps each board's clock onto the PC's by using the fastest USB deliveries per 5 s window (this also removes crystal drift). USB serial delivers in bursts, so single lines arrive up to about 50 ms late; the fastest ones are close to on time, which is what the mapping relies on. The remaining error is the difference between the two ports' fastest delivery, roughly 1 ms, so read results to about a millisecond. The script prints the delivery jitter so you can see how noisy the ports were. The driver's `FIRE` time is when the beat triggers the pattern step; the LED data follows within the same loop pass, and a 119-LED strip takes about 3.6 ms to clock out.
Close any serial monitor first (only one program can hold a port). Do not run long `mpremote exec` commands on the driver during the capture (see Troubleshooting).
### True latency with a logic analyzer
For a measurement that does not depend on USB. Marker pins are set up already: the controller toggles **GPIO44 (D7)** when the first copy of each beat goes out (`CONFIG_BEAT_TEST_GPIO=44`, in `sdkconfig.defaults`) and the driver toggles **GPIO44 (D7)** when it fires (`"beat_pin": 44` in its `settings.json`). Both are XIAO ESP32S3 boards, where D7 is free.
Wiring (3.3 V logic, any 2 or 3 channel analyzer):
| analyzer | connect to |
|---|---|
| GND | GND on the controller **and** GND on the driver (one common ground) |
| channel 0 | controller **D7** |
| channel 1 | driver **D7** |
| channel 2 (optional) | driver **D10** (GPIO9, the LED data line) to see when the LEDs really update |
Steps:
1. Make sure the driver runs a preset that changes on every beat if you use channel 2, for example a `chase` preset with `auto` off, selected on the zone. With the plain `on` preset the LED data line stays quiet.
2. Start a capture: sample rate at least 1 MS/s, length at least 60 s (edges only; it stays small), trigger on any edge of channel 0.
3. Start the beats: `curl -s -X POST -d '{"bpm":120,"count":100}' http://$S3/test/beats`. Both markers toggle on every beat, so you will see edges 500 ms apart.
4. Stop the capture when the generator finishes (about 52 s) and export the digital data as CSV (time in seconds, one column per channel).
5. Analyze: `python3 tools/analyze_edges.py capture.csv --ctrl 0 --drv 1 --time-unit s`. Use `--lead-ms` if you changed `CONFIG_BEAT_LEAD_MS`. It pairs each controller edge with the next driver edge and prints the delay beyond the 30 ms lead, with min, mean, median, p95, max and jitter, plus the count of unmatched beats. On the scope, channel 2 shows the true light delay: the first data burst after the driver edge.
Targets from the plan: under about 10 ms from the controller edge to the driver edge (after subtracting the lead).
Return to normal use by deleting `beat_pin` and `usb_log` from the driver's `settings.json` and setting `CONFIG_BEAT_TEST_GPIO=-1` (the marker pin otherwise toggles on every beat, including live mic beats).
### Results of the first run (software numbers, one driver, channel 5)
Synthetic beats at 120 BPM, 160 beats per run, mic beats muted while the generator runs, driver in `bench` mode.
| | no loss | 30% loss (beats included) |
|---|---|---|
| beats the driver acted on, per beat sent | 1.00 | 1.00 |
| beats the driver invented itself (free-run) | 0% | 11% (theory for two independent copies: 9%) |
| second copies dropped as duplicates | 100% | 47% (theory: 49%) |
| echoes the controller received | 162 of 162 | 96 of 161 (echoes are lost at 30% too, and invented beats do not echo) |
| round trip minus the 30 ms lead, min / avg / max | 9.8 / 15.0 / 25.7 ms | 3.4 / 16.2 / 26.0 ms |
Reading it: the double send plus free-run gave the driver a beat every time, even with 30% of frames lost. The round-trip figure includes the driver's loop and the echo's trip back, so it is an upper bound on the delay the LEDs see; it is not the controller-to-LED latency. The USB and logic analyzer measurements below give the real figure.
Latency over USB (200 beats at 120 BPM, one driver, 119 LEDs): delay beyond the 30 ms lead min 0.49, mean 2.07, median 1.77, p95 4.41, max 7.95 ms (std 1.3 ms; accuracy about 1 ms). 197 of 200 beats matched. Both clocks drifted by 60 to 80 ppm against the PC, and individual USB lines arrived up to 54 ms late, which is why the script uses the fastest deliveries. This is the time from the controller sending a beat to the driver firing, beyond the built-in lead. The logic analyzer run has not been done.
### ESP32-C3 driver compared with the S3 driver
Driver: XIAO ESP32-C3 (MAC 58:8c:81:a3:74:58), MicroPython v1.22.1 stock (no ws2812-dma patch), 160 MHz, about 128 KB free heap, 119 LEDs on pin 10. Same tests as above, same controller.
| | S3 driver, no loss | C3 driver, no loss |
|---|---|---|
| echoes the controller received | 162 of 162 | 160 of 160 |
| round trip minus the 30 ms lead, min / avg / max | 9.8 / 15.0 / 25.7 ms | 2.6 / 4.5 / 17.8 ms |
C3 with 30% loss (160 beats): every beat produced exactly one pattern step, 15 of the 160 (9%, theory 9%) came from free-run, and 68 second copies were dropped as duplicates; the controller got 99 of 160 echoes. That matches the S3 result in the table above.
Reading the free-run counter: after the generator stops, the driver keeps stepping for up to 4 more beats on its last period. A stats window that runs past the end of the test therefore shows 4 extra "free-run" fires even with no loss. They are not missed beats. (My first read of the C3's no-loss run said otherwise; that was wrong.)
Latency over USB, same settings on both boards (`usb_log` only), 200 beats at 120 BPM, delay beyond the 30 ms lead, accuracy about 1 ms:
| | matched | min | mean | median | p95 | max | std |
|---|---|---|---|---|---|---|---|
| S3 driver (240 MHz) | 200 / 200 | -2.4 | 2.15 | 2.03 | 6.03 | 12.3 | 2.5 ms |
| C3 driver (160 MHz) | 200 / 200 | 0.2 | 3.36 | 3.06 | 7.47 | 19.7 | 2.3 ms |
The C3 is about 1.2 ms slower on average and has a longer tail (maximum 19.7 ms against 12.3 ms). With the method's 1 ms accuracy, the mean difference is small and the tail difference is the more telling one. Both are well inside a 120 BPM beat. The echo round trip disagrees with this (S3 15 ms mean, C3 4.5 ms). The S3 echo runs had `usb_log` and a marker pin switched on and the C3 runs did not, and I did not rerun the S3 echo test with identical settings, so treat the echo figures as unexplained and prefer the USB ones.
Pattern frame rate (strip writes per second, 119 LEDs, delay 1 ms, 2 s each; only patterns that wrote anything are shown):
| pattern | C3 (160 MHz, 115 KB free) | S3 (240 MHz, 8 MB free) |
|---|---|---|
| flame | 22 | 33 |
| palette_morph | 21 | 32 |
| circle | 150 | 170 |
The CPU-heavy patterns run about 1.5 times faster on the S3, which is the clock ratio; a light pattern is limited by the strip write and differs by about 13%. `aurora` and `chase` wrote nothing with the parameters I used, so they are not measured.
Groups: the controller sends a driver its group list when the driver announces itself, but now only if the driver is in at least one zone. A driver in no zone keeps the groups it already has (an empty list from the controller used to wipe them). An explicit zone or device edit still re-sends every list, including empty ones.
**Wi-Fi start-up order on the C3.** With the extra link code loaded before Wi-Fi start-up, the C3 failed with `Wifi Unknown Error 0x0101` on about every other cold boot (2 of 4). Starting ESP-NOW before the pattern library and the LED driver claim memory fixed it (6 of 6 boots). `led-driver/src/main.py` now does this.
## 8. Troubleshooting
- **A board on a USB-serial/JTAG port (C3, and the S3 controller) resets whenever a program opens its port,** and a C3 can land in ROM download mode (`wait usb download`). The old apt `mpremote` 0.4.0 hangs on this. Use the newer one in `~/projects/micropython/micropython/tools/mpremote/mpremote.py`, or `led-tool`, and note that `fs cp -r` fails on drivers that print timestamps (copy named files instead).
- **Only one program can use a board's serial port at a time.** A serial logger left running while `led-cli` uploads corrupts the transfer silently: `led-cli` reports the files uploaded, but the old ones stay on the driver.
- **Running a long `mpremote exec` on the driver resets it:** the driver's watchdog (10 s) keeps running after `mpremote` interrupts `main.py`, so keep REPL experiments under about 8 s and reset the driver afterwards.
- **Driver never reacts, no acks:** channel mismatch. Check `CONFIG_ESPNOW_CHANNEL` against the driver's `wifi_channel`. Neighbouring channels can still work at bench range, so a working link does not prove they match.
- **Zone play logs nothing on the driver:** the driver is not in the zone's group (silent). Check the zone's `names` against the driver's `name`.
- **Devices show `last_ack_ms_ago: -1`:** the device record has no usable 12-character MAC in `address` or as its key.
- **`beats_sent` rises but `echoes` stays 0:** the driver is not in `bench` mode, or it has not yet heard a controller frame (it learns the controller's MAC from the first data or digest frame; wait a few seconds).
- **Resync never triggers:** the driver ignores a digest equal to its own version; confirm with `/status` that `link.ver` changed after the missed play.
- **Web UI is blank:** the web UI was not packed before the build; run `tools/build_web.sh` and build again (`make build` does this).
## 9. Cleanup
```bash
curl -s -X POST -d '{"percent":0}' http://$S3/test/loss
curl -s -X POST http://$S3/test/beats/stop
```
Set the driver's `bench` and `espnow_loss` back to off for normal use.
+9 -44
View File
@@ -1,14 +1,13 @@
# LED Driver System - Specification Document
**Version:** 1.1
**Date:** October 2026
**Version:** 1.0
**Date:** December 2025
**Status:** Draft
## Table of Contents
1. [Overview](#overview)
2. [System Architecture](#system-architecture)
- [Raspberry Pi Controller and Animation Engine](#raspberry-pi-controller-and-animation-engine)
3. [User Interface Specifications](#user-interface-specifications)
4. [Feature Specifications](#feature-specifications)
5. [Preset System](#preset-system)
@@ -29,7 +28,7 @@
The LED Driver system is a MicroPython-based application for controlling LED strips via ESP32-C3 microcontrollers. The system uses a custom firmware image with usqlite and microdot built-in as frozen modules. The system provides:
- Real-time LED pattern control
- Multi-device management via peer-to-peer communication (ESPNow)
- Multi-device management via ESP-NOW (peer-to-peer on 2.4 GHz; Pi reaches drivers through a bridge ESP32)
- Group-based device control
- Web-based configuration interface
- Binary message protocol for efficient communication
@@ -50,16 +49,11 @@ The LED Driver system is a MicroPython-based application for controlling LED str
- Preset system for saving and loading pattern configurations
- Profile and Scene system for complex lighting setups
- Preset sequencing within groups for time-based transitions
- Peer-to-peer communication via ESPNow
- ESP-NOW peer-to-peer between bridge and led-driver devices; Pi ↔ bridge over WebSocket or USB serial
- Binary message protocol for bandwidth efficiency
- Persistent settings storage (usqlite database)
- Web-based configuration interface (Microdot web server)
- SQLite database for presets and event logging
- **Raspberry Pi controller** (`src/`): Microdot web app with JSON-file storage (`db/*.json`) managing profiles, zones, presets, palettes, scenes, sequences and outputs
- **Pi-side animation engine** (`src/engine/`): renders the unchanged driver patterns on the Pi and streams pixels over DDP, Art-Net, sACN (E1.31) or USB-DMX
- **Preset sequencer**: timed preset chains per zone, resumed after restart
- Server-wide global brightness (0-255) pushed to drivers, including on Wi-Fi reconnect
- Search filter in the Devices, Zones and Presets lists
---
@@ -231,29 +225,6 @@ The LED Driver system uses a master/slave architecture where one device acts as
---
## Raspberry Pi Controller and Animation Engine
The current deployment adds a Raspberry Pi running the web app (`src/main.py`, Microdot on CPython). It is the authoritative store and UI host; ESP32 firmware is unchanged. Full route detail is in `docs/API.md`.
**Outbound paths**
- Serial → ESP-NOW bridge (JSON lines over UART).
- Wi-Fi drivers: TCP JSON lines (port 8765 on the Pi; drivers discover the Pi via UDP 8766 broadcast).
- Pixel outputs rendered by the Pi engine (below).
**Data model (`db/*.json`):** profile, zone, preset, palette, pattern, device, scene, sequence, output. A zone's `names` list holds ESP32 device names and/or output names.
### Animation Engine (`src/engine/`)
- **Pixel generator:** loads `led-driver/src/patterns/*.py` unmodified under CPython (`utime` shim plus a NeoPixel-like buffer) and runs one render thread per zone from the same preset JSON the drivers receive. Static frames are re-sent as keepalive.
- **Output drivers:** DDP (UDP 4048), Art-Net (ArtDMX/ArtSync, UDP 6454), sACN/E1.31 (UDP 5568, multicast or unicast), USB-DMX (Enttec DMX USB Pro or Open DMX). 170 RGB pixels per universe, consecutive universes for longer strips. A preset output for our ESP32 drivers (`outputs/driver.py`) reuses the existing preset + `select` path.
- **Output record** (`db/output.json`): `name`, `protocol`, `host`, `port`, `universe`, `serial_port`, `dmx_mode`, `channel`, `pixel_count`, `pixel_offset`, `color_order`, `reverse`, `brightness` (0-255, multiplied by global brightness), `fps` (default 40), `enabled`. CRUD and a test pattern (R, G, B, W, off) at `/outputs`.
- **Zone playback:** `POST /zones/<id>/play` renders a preset on every target and sends `select` to ESP32 drivers; `POST /zones/<id>/stop` blanks pixel outputs. `GET /zones/engine/status` reports per-zone and per-output counters.
- **Sequencer:** a sequence is `{name, zone_id, loop, repeat_count, steps: [{preset_id, duration_s}], active}`. `duration_s` is clamped to 0.5-600 s (default 5); steps are hard cuts; `repeat_count` of 0 loops forever. Deadline-based scheduling, `active` sequences resume after restart, manual preset selection on a zone stops its sequence. Legacy records (`group_name`, `presets`, `sequence_duration` ms) are migrated on load. Scenes start/stop the sequences they list (`/scenes/<id>/play`, `/stop`).
- **CLI:** `python -m engine.cli --output "ddp://host?pixels=300" --test | --preset N | --pattern NAME` (terminal preview when no output is given).
- **UI:** Outputs and Sequences modals (edit mode), preset tiles drive pixel outputs, header brightness slider, list search filters.
---
## User Interface Specifications
### 1. Dashboard (Main Control Panel)
@@ -1604,13 +1575,11 @@ peak_mem = usqlite.mem_peak()
### Flow 8: Sequence Between Presets
*(Implemented by the Pi-side sequencer; see Animation Engine.)*
1. User plays a sequence (or a scene that lists it) on a zone
2. Pi applies the first step: renders it to the zone's pixel outputs and sends the preset + `select` to its ESP32 drivers
3. After `duration_s` expires, the sequencer hard-cuts to the next step
4. Process repeats for all steps; loops forever or for `repeat_count` passes
5. Continues until stopped, the zone is played manually, or the app restarts (active sequences then resume)
1. Scene activated with group having multiple presets
2. Master applies first preset to itself (if in group), sends to slaves
3. After duration expires, master transitions to next preset with fade effect
4. Process repeats for all presets, loops if enabled
5. Continues until scene changes or manual stop
---
@@ -1680,10 +1649,6 @@ peak_mem = usqlite.mem_peak()
- Any length (1-1000 LEDs supported)
- 5V power supply (external)
**Raspberry Pi (controller):**
- Python 3.x, runs the web app and animation engine
- Optional: Wi-Fi/Ethernet to DDP, Art-Net or sACN fixtures; USB-DMX adapter (Enttec DMX USB Pro / Open DMX)
**Host Computer:**
- Python 3.x
- pipenv for dependency management
+198
View File
@@ -0,0 +1,198 @@
# ESP-NOW transport architecture
This document describes how **led-controller**, the **bridge ESP32**, and **led-driver** devices work together. Wire-level byte layouts are in [espnow-binary-protocol.md](espnow-binary-protocol.md).
**Pi ↔ bridge:** v1 **devices envelope** (JSON) over **WebSocket** (`bridge_transport`: `wifi`) or **USB serial** (`bridge_transport`: `serial`) — example: [msg.json](msg.json). **ESP-NOW over the air:** JSON driver payloads (≤250 bytes) or legacy binary (`0x4C` wire). The Pi web UI and `db/*.json` use JSON internally.
## System overview
![Three-node ESP-NOW architecture](images/espnow/system-overview.svg)
| Component | Firmware / path | Role |
|-----------|-----------------|------|
| **led-controller** | Raspberry Pi, `src/` | Web app; WebSocket **client** to bridge (auto-reconnect); device registry; builds devices envelope |
| **Bridge** | [`espnow-sender/`](../espnow-sender/) (or [`bridge-serial/`](../bridge-serial/) for UART-only) | WebSocket **server** `/ws` and/or USB serial; routes envelope per MAC; max **20** ESP-NOW peers (LRU) |
| **led-driver** | [`led-driver/`](../led-driver/) submodule | Boot **ANNOUNCE** broadcast; applies **GROUPS**, **CMD**, **GROUP_CMD** |
Configure the Pi in `settings.json`:
```json
{
"bridge_transport": "wifi",
"bridge_ws_url": "ws://192.168.4.1/ws",
"wifi_channel": 5
}
```
For **USB serial** to the bridge ESP32 instead of Wi‑Fi:
```json
{
"bridge_transport": "serial",
"bridge_serial_port": "/dev/ttyACM0",
"bridge_serial_baudrate": 921600,
"wifi_channel": 5
}
```
**Wi‑Fi mode:** connect the Pi to the **bridge access point** (SSID = bridge `name` in `/settings.json`, default IP **192.168.4.1**). Use **Help → Bridge** or **`POST /settings/wifi/connect`** to join and set `bridge_ws_url`. **Serial mode:** plug in the bridge and set `bridge_serial_port` (or use **`POST /settings/wifi/serial/connect`**).
All nodes must use the same 2.4 GHz **channel**: set `wifi_channel` in the bridge and each led-driver `/settings.json` (applied at boot on those devices). The Pi stores `wifi_channel` in its own `settings.json` for alignment (restart led-controller after changing).
---
## Boot and registration
![Boot and registration sequence](images/espnow/boot-sequence.svg)
1. Driver powers on and sends **ANNOUNCE** to broadcast MAC `ff:ff:ff:ff:ff:ff`.
2. Bridge receives it and forwards a **WebSocket uplink** frame to the Pi (peer MAC + packet).
3. Pi **upserts** the device in `db/device.json` (key = 12-char hex MAC).
4. Pi scans `db/group.json` and sends a **groups** envelope (`set_groups: true`) unicast to that MAC.
5. Driver stores group ids in RAM (`device_groups`) for filtering.
6. Pi bridge client **reconnects** automatically if the WebSocket drops (2 s backoff).
If the Pi or bridge is not up yet, the driver re-sends **ANNOUNCE** periodically until **GROUPS** arrives.
---
## Devices envelope (Pi → bridge)
```json
{
"v": "1",
"dv": {
"ff:ff:ff:ff:ff:ff": {
"p": { "2": { "p": "on", "c": ["#FFFFFF"], "a": true } },
"s": ["2", 0],
"g": ["5", "18"],
"sg": false,
"sv": true
}
}
}
```
Short wire names (long names still accepted on receive): `dv`=devices, `p`=presets, `s`=select (`["preset_id", step?]` — no device name), `g`=groups, `sg`=set_groups, `sv`=save, `df`=default; preset fields `p/c/d/b/a/bg/n1…`.
| `set_groups` | Destination | Bridge | Driver |
|--------------|-------------|--------|--------|
| `true` | any | Unicast only (expand `ff:ff:…` to all known peers) | `groups_replace`, then apply body |
| `false` | `ff:ff:ff:ff:ff:ff` | ESP-NOW air broadcast | Apply only if device is in `groups` |
| `false` | specific MAC | Unicast | Same group filter |
Legacy raw payloads (binary wire or plain v1 JSON without `devices`) are still **broadcast** by the bridge.
## Sending presets and commands
1. UI or API triggers a send (e.g. `POST /presets/push`).
2. Pi builds a **devices envelope** (or legacy binary) and sends it on the bridge WebSocket.
3. Bridge routes each MAC entry to unicast or ESP-NOW broadcast per `set_groups`.
4. Driver `process_data` applies presets, select (`[preset_id, step?]`; legacy name map still accepted), brightness, etc.
---
## Packet layers
![Packet layer stack](images/espnow/packet-layers.svg)
### Layer A — WebSocket frame (Pi ↔ bridge)
| Offset | Size | Field |
|--------|------|--------|
| 0 | 1 | `flags` — bit0 = broadcast (`ff:ff:…`); peer ignored if set |
| 1 | 6 | `peer` — destination MAC (raw bytes) |
| 7 | … | Full ESP-NOW packet (layer B) |
**Uplink** (bridge → Pi): same layout; `flags = 0`, `peer` = sender.
**Ack** (bridge → Pi after downlink): 1 byte — `0x01` ok, `0x00` error.
### Layer B — ESP-NOW packet (on air)
| Offset | Size | Field |
|--------|------|--------|
| 0 | 1 | Magic `0x4C` (`'L'`) |
| 1 | 1 | Message type |
| 2 | … | Body (≤248 bytes so total ≤250) |
![Message types](images/espnow/message-types.svg)
| Type | Value | Direction | Purpose |
|------|-------|-------------|---------|
| ANNOUNCE | `0x01` | Driver → broadcast | Boot settings |
| GROUPS | `0x02` | Pi → driver | Group membership |
| CMD | `0x03` | Pi → driver | Command (v2 envelope) |
| GROUP_CMD | `0x04` | Pi → broadcast | Command scoped to one group |
| BRIDGE_CH | `0x10` | Pi → bridge | Set STA channel 1–11 |
### Layer C — v2 command envelope (inside CMD / GROUP_CMD)
Used for presets, select, default, brightness. **No JSON.**
| Byte | Field |
|------|--------|
| 0 | Version `2` |
| 1 | Brightness wire 0–127 (→ 0–255); `128–255` = unchanged |
| 2 | `lp` — presets section length |
| 3 | `ls` — select section length |
| 4 | `ld` — default section length |
| 5… | Presets blob (`lp` bytes) |
| … | Select blob (`ls` bytes) |
| … | Default blob (`ld` bytes) |
Optional trailing `0x01` after the envelope in **CMD** means `save` (persist to flash).
Implementation: [`src/util/binary_envelope.py`](../src/util/binary_envelope.py), [`src/util/espnow_wire.py`](../src/util/espnow_wire.py).
---
## Message body reference
### ANNOUNCE (`0x01`)
Sender MAC comes from ESP-NOW headers, not the body.
```
name_len (u8) | name (utf-8) | num_leds (u16 LE) | color_order (u8) | startup_mode (u8) | brightness (u8) | device_type (u8)
```
| `color_order` | `startup_mode` |
|---------------|----------------|
| 0=rgb, 1=rbg, 2=grb, 3=gbr, 4=brg, 5=bgr | 0=default, 1=last, 2=off |
### GROUPS (`0x02`)
```
count (u8) | repeat: id_len (u8) | group_id (utf-8)
```
Group ids match keys in `db/group.json` (e.g. `"5"`, `"18"`).
### GROUP_CMD (`0x04`)
```
group_id_len (u8) | group_id (utf-8) | v2 envelope | [optional 0x01 save]
```
Driver applies only if `group_id` is in its stored list.
---
## Size limits and chunking
- **250 bytes** max per ESP-NOW datagram.
- Large preset libraries → multiple **CMD** packets from the Pi.
- Bridge stores at most **20** peer MACs; oldest peer evicted (LRU) when full.
---
## Related files
| Topic | Location |
|-------|----------|
| Byte-level spec | [espnow-binary-protocol.md](espnow-binary-protocol.md) |
| Pi wire codec | [`src/util/espnow_wire.py`](../src/util/espnow_wire.py) |
| Pi bridge client | [`src/models/bridge_ws_client.py`](../src/models/bridge_ws_client.py) |
| Bridge firmware | [`espnow-sender/src/main.py`](../espnow-sender/src/main.py) |
| Driver ESP-NOW | [`led-driver/src/espnow_transport.py`](../led-driver/src/espnow_transport.py) |
Loaded 100 of 1081 files, more files were not shown because too many files have changed in this diff. Show more