Skip to content

Latest commit

 

History

History
593 lines (522 loc) · 52.4 KB

API.md

File metadata and controls

593 lines (522 loc) · 52.4 KB

Dune Weaver / FluidNC sand-table API

The controller (MKS-DLC32 / ESP32, FluidNC sandtable build) is a headless controller: it exposes this WiFi API and holds no rich UI. Clients (the native app, scripts) drive it over stateless HTTP. This document is the stable contract — treat command names and the $Sand/Status schema as the interface.

Source of truth: FluidNC/src/SandApi.cpp, SandStatus.cpp, Playlist.cpp, FileCommands.cpp, Leds.cpp, Kinematics/ThetaRho.cpp, WebUI/WebServer.cpp, WebUI/Mdns.cpp.

Transports

Transport Port Use Execution context
HTTP /sand_* routes HTTP (default 80) Primary — status/listing reads + the motion actions action routes only signal the main loop ✅
HTTP /command 80 Fire-and-forget cmds + $/ reads runs inline in the polling_loop task ⚠️
HTTP file routes 80 Upload, fetch .thr/files —
USB serial — Recovery console (never password-gated) main loop

HTTP is the only network transport: the build has no WebSocket server, no telnet (port 23) and no ArduinoOTA/espota (port 3232). Firmware updates go through POST /updatefw.

⚠️ Start blocking motion through the dedicated routes, not /command. Commands sent over /command?plain= execute synchronously inside Web_Server::poll() (the polling_loop task); a blocking motion command there ($H, a jog) fights the main loop's segment prep (this caused the homing-crawl bug). The /sand_home, /sand_goto, /sand_stop, /sand_feed routes only signal the main loop and are safe. Job starts ($Sand/Run, $SD/Run, $Playlist/Run) are fire-and-forget and fine over /command.

Discovery (mDNS)

Advertised when connected in STA mode (WebUI/Mdns.cpp):

  • Service: _http._tcp.local on the HTTP port; hostname <host>.local.
  • TXT records identify a sand table:
    • model=dune-weaver
    • api=sandtable/1
    • mac=<aa:bb:cc:dd:ee:ff> — lowercase STA MAC, the table's stable hardware identity (same value as /sand_status mac)

Discovery can pause, so never make it the only way a client finds a table. The responder answers at most ~10 queries/sec (an ESP-IDF limit, see CLAUDE.md), and above that its unbounded response backlog would eat the heap and panic the board, so the firmware drops the responder when free heap falls under 24 KB and brings it back once the heap recovers (60 s later, doubling per repeat up to 30 min). While it is down <host>.local does not resolve and the table does not appear in a service browse — but every HTTP route keeps working normally by IP. Clients should cache the last known IP (keyed on the TXT mac) and fall back to it rather than treating a failed mDNS lookup as "table offline". A client that browses aggressively can cause this: keep discovery to occasional browses, not a tight poll.

App flow: browse _http._tcp, keep services whose TXT has model=dune-weaver, key saved tables by the mac TXT value (dedupes a discovered table against one saved by IP; survives DHCP changes and hostname edits). Manual-IP entry is the fallback — read mac from /sand_status there.

Commands

Commands can be sent on any transport, but command output routing differs (verified live against the board, 2026-06):

  • HTTP GET/POST /command?plain=<urlencoded cmd> runs the command (the action always takes effect), as do the commandText= and cmd= arg forms — all three are synchronous and equivalent. (Before v0.1.18 only plain= and [ESPxxx] ran; the other forms were routed to the disabled WebSocket, so they answered 500 "WebSocket dead" and never executed the command.) Its text response is racy except for $/ settings reads — plain $ / [ESP…] output is emitted asynchronously and may not reach the request. So use /command for fire-and-forget actions ($SD/Run=, $THR/Feed=, $LED/*, $Playlist/*, settings writes) and confirm via a status poll; for reads, use the dedicated /sand_* JSON routes below. This fork ships HTTP/BlockDuringMotion defaulted OFF, so /command and /sd/... file serving work while a pattern is playing (the block-during-motion gate is a CNC-safety default that doesn't apply to a slow sand table); the /sand_* routes bypass the gate regardless.

→ App rule of thumb (multi-client): read via the /sand_* JSON routes (status / patterns / playlists / settings), act via /command + the /sand_* action routes, fetch files via /sd/.... All of that is stateless and multi-client — any number of app instances at once, including during playback.

Coordination note: the table is one machine and commands are last-writer-wins (a second $SD/Run preempts the first — they are not queued). Multi-user works mechanically; any "who's driving" UX is the app's job. Scale assumption is household (a handful of pollers), not crowds — the ESP32 serves HTTP serially and has a small socket pool.

Polling cadence is the client's biggest lever on board load. Every /sand_status poll is a full TCP connection (the server sends Connection: close, so keep-alive is a no-op) — the per-poll cost is fixed, only the rate is yours to control. Poll at the base rate normally, and back off hard when the board signals heap pressure (heap_largest below ~20k, or a 503 busy: low memory) — that's the regime that actually strains the single-client server. Also back off a table that's unreachable, and stop polling when backgrounded / mid-upload. See POLLING.md for the full rule and per-client checklist.

Status & listing — multi-client HTTP routes (JSON body, work during motion)

Endpoint Returns
GET /sand_status status object (schema below)
GET /sand_patterns JSON array of pattern paths (.thr, and plain G-code .gcode/.gc/.nc). If /patterns/index.json (a prebuilt manifest) exists, it is served verbatim — a fast single-file read of the full recursive catalog (paths relative to /patterns, e.g. custom_patterns/x.thr; run via $Sand/Run=/patterns/<path>). Generate it on the host and upload to the card whenever patterns change (see COMMANDS.md); since v0.2.3 an uploaded pattern adds itself to it (see Upload). Without a manifest it falls back to a non-recursive top-level listing (subfolders omitted — enumerating the ~1000-file nested library on the slow SD froze the single-threaded server). Chunked/streamed. Conditional GET: when a manifest is present the response carries an ETag (a content hash) and Cache-Control: no-cache; send it back as If-None-Match: <etag> and an unchanged catalog answers 304 Not Modified with no body instead of re-streaming the whole manifest. Clients that re-read the catalog on every launch/table-switch should cache the ETag and revalidate — the repeated full downloads, colliding with an app's launch connection burst, are what pushed the heap-tight board into low-memory shedding. The ETag changes whenever the manifest is re-uploaded; the live-listing fallback has no ETag (always 200). Ranged GET: when the manifest is served the response carries Accept-Ranges: bytes and honors a single Range: header (a-b, a-, -n) with 206 + Content-Range, so a client can pull a large catalog in bounded windows instead of one multi-second transfer that leaves the single-threaded server deaf while pollers stack behind it (the live-listing fallback is not seekable — no Range). Load-shedding: a revalidation (a conditional GET carrying If-None-Match) is exempt from the low-heap 503 guard so the library stays usable on a stressed board; a cold full GET is sheddable (503 busy: low memory) — retry with backoff or ranged pulls.
GET /sand_playlists JSON array of .txt files in the top level of /playlists (non-recursive)
GET /sand_settings JSON object of app settings (speed, homing mode, LED, playlist, quiet hours), values as strings. Also "LED/Palettes": read-only palette count (not a setting); absent on firmware before WLED's palettes
GET /sand_time wall clock {epoch, synced, local, tz}. ?epoch=<unix> sets the clock (app auto-sync / AP mode); ?tz=<POSIX> sets + persists the timezone. Safe mid-run: the zone applies immediately and the (idle-gated) NVS write is deferred to the return to idle. Also surfaced in /sand_status under time
GET /sand_bootlog plain-text boot log (the $SS startup log). Stored in RTC RAM: after a panic reset it still holds the previous boot's log (first line says so), making it the on-device crash breadcrumb. Cleared by a power cycle
GET /sand_log plain-text rolling session log — the last ~8 KB of runtime log lines, each prefixed with [+<uptime seconds>], then @<unix epoch> once the clock is set (NTP or /sand_time?epoch=), e.g. [+123] @1764430200 [MSG:INFO: …]. The epoch comes second so clients that parse [+N] keep working; lines logged before the clock is set have no @ field. Streamed straight from the ring, so lines logged while it is being sent are left for the next read. This is where playlist end reasons ("playlist: … canceled by alarm"), SD errors, and alarms land on a headless table. The ring is kept in no-init RAM, so a warm reset (panic, watchdog, brownout, $Bye, OTA) keeps the previous session's lines, and they come back in the normal response: above a === reboot (<reason>), previous session above === line, each prefixed prev (prev [+123] …). The prefix keeps clients that merge by [+uptime] correct without changes: they don't parse those lines as uptimes, so reboot detection and timestamps behave as on older firmware (the app files them untimed after its restart marker; the Pi host skips them). A power cycle clears the ring; /crash-N.log survives it. After a crash reset (last_reset panic/int_wdt/task_wdt/wdt/brownout) the boot also saves the pre-reboot lines to littlefs as GET /crash-0.log (first line: reset reason + firmware), shifting older ones to /crash-1.log and /crash-2.log; these survive power cycles. A crash loop saves only its first three boots (a streak ends after 10 healthy minutes), so the first, most telling log stays as crash-2.log. 404 = no crash saved. Delete with /files?action=delete&filename=crash-0.log&path=/. $Log/SD=ON (default OFF; writable while paused) also appends the log to the SD card as /sd/logs/dw.log: only while the table is Idle with no job, at most once a minute, rotating at 256 KB to dw.1.log. Lines logged while a job runs reach the card at the next idle; if a long job logged more than the 8 KB ring holds, the file shows === log gap ... === there. It keeps a table's history across power cycles; the cost is that a power cut during an append can damage the card's FAT, hence off by default. Listed in /sand_settings as Log/SD
GET /sand_coredump (Through v0.2.9 this always answered present:false: an upstream stub no-op'd the dump. Real since v0.2.10.) JSON crash report from the coredump flash partition, written on any panic including a task-WDT hang (the firmware panics deliberately after ~120 s of a wedged core task, so hangs self-reboot and self-document). {present, task, pc, backtrace:[…], bt_corrupted, elf_sha256} — decode with xtensa-esp32-elf-addr2line -pfiaC -e firmware.elf <addrs> against the matching build. ?erase=1 clears it. Persists across reboots until erased/overwritten

These are read-only, fast, and skip the block-during-motion gate, so clients keep reading while a pattern runs. The $Sand/Status / $Sand/Patterns / $Sand/Playlists commands return the same data, but their text output over /command is racy, so use the routes. Pattern/playlist contents are fetched as files: GET /sd/patterns/<name>.thr, GET /sd/playlists/<name>.txt.

Playback (asynchronous — poll $Sand/Status for progress)

Command Action
$SD/Run=/patterns/<file>.thr run a pattern (.thr translated on the fly by ThetaRho kinematics). Cartesian (CoreXY) tables run plain G-code patterns (.gcode/.gc/.nc, no translation) through the same commands and playlists; .thr plays only on ThetaRho
$Sand/Run=/patterns/<file>.thr [clear=<mode>] run a pattern, optionally preceded by a clear ("pre-execution"). clear=none|adaptive|in|out|sideway|random (default none); adaptive picks in/out from the pattern's first rho (never sideway). Clear moves honor $Playlist/ClearSpeed (0 = same as $THR/Feed) and the $Playlist/ClearIn|ClearOut file overrides. Sequenced by the firmware (clear→pattern, then stop); aborts any running job first. Requires a playlist: config section (the clear files live there). Filenames may contain spaces; clear= must be the last token (everything before it is the path).
$SD/Show=/patterns/<file>.thr dump file contents (preview; requires Idle/Alarm)
$Playlist/Run=<name> run playlist /playlists/<name>.txt. Unplayable entries are skipped, not fatal: a pattern that fails to start (missing/renamed file, SD read hiccup) or an unreadable playlist slot is logged (playlist: skipping …) and the run advances immediately (no between-pattern pause). A clear that fails to start skips the whole item — the run advances to the next item (its own clear→pattern) rather than drawing the pattern on an un-cleared table (clear did not start, skipping item …). 5 consecutive failures (no pattern started in between, clear-failures included) means the SD itself is broken → run cancels (too many unplayable patterns in a row). A single $Sand/Run still fails loudly (canceled: file did not start)
$Playlist/Stop stop after the current pattern
$Playlist/Skip skip the current item and jump straight to the next one — no between-patterns pause. Skipping while the main pattern draws advances to the next item; skipping while the clear draws skips the whole item too (not just the clear), so the current item's pattern is not drawn. Skipping during the between-patterns pause ends the pause immediately
$Playlist/List text listing + active playlist index/total/name
$Sand/Goto theta=<rad> rho=<0..1> / GET /sand_goto?theta=&rho= jog to an absolute θ (radians) and/or ρ (0..1); either or both axes (omitted axis stays put). For manual positioning between patterns — requires Idle (rejects with IdleError/HTTP 409 if a pattern is running or unhomed). ρ clamped to 0..1; uses the current feed; runs as a G1 move (through ThetaRho kinematics) in the main loop — stop with /sand_stop. Cartesian (CoreXY) tables use x=<mm>/y=<mm> instead — clamped to the machine travel, fixed 1000 mm/min reposition feed. The forms are not mixable, and the wrong form for the active kinematics answers HTTP 400 (command: InvalidStatement) with a hint naming the right one
$Sand/Home / GET /sand_home home honoring $Sand/HomingMode; runs in the main loop (safe over HTTP). sensor = limit-switch $H; crash = drive ρ (Y) blindly into the center stop then zero θ/ρ. On a cartesian (CoreXY) table this is always a plain $H — crash mode and $Sand/ThetaOffset are polar concepts and are ignored there
$Sand/HomingMode=sensor|crash persisted homing mode (NVS; default sensor). Honored by /sand_home, $Sand/Home, and the boot startup line (set startup_line0: $Sand/Home). Also returned by GET /sand_settings
$Sand/ThetaOffset=<deg> theta zero offset in degrees (UI "Sensor Offset"; NVS; -360..360; default 0). At home time (both modes) pattern θ=0 is placed this many degrees from the home reference (limit switch in sensor mode, crash position in crash mode). Idle-gated; takes effect on the next home. Honored on boot only via startup_line0: $Sand/Home. Returned by GET /sand_settings
$H force a sensor home (sets θ=0, normalizes). Over the network use /sand_home: $H via /command blocks the web task
! / ~ realtime feed-hold (pause) / cycle-start (resume)
0x18 (Ctrl-X) realtime soft reset (loses position)

Speed

Command Notes
/sand_feed?mm=<0..100000> ThetaRho only (a cartesian table's G-code patterns carry their own F words — 400, use pct=). Set base feed rate (motor mm/min) live; works mid-pattern. Idle → persists to $THR/Feed; running → in-memory override that persists across the whole playlist/run (no longer reset per pattern), then flushed to $THR/Feed on the return to idle so a speed set mid-pattern sticks as the new default — immediately on natural completion, and after a stop once motion drains to idle; a pause keeps it in memory (flash is blocked mid-Hold) and it persists at the next idle
$THR/Feed=<mm_per_min> same base rate, NVS-persisted; idle-gated; applied on the next .thr move
/sand_feed?pct=<10..200> scale the base rate by an absolute override percentage; works mid-pattern
/sand_feed?d=up|down|reset HTTP one-shot coarse feed-override ±10% / reset to 100%

Effective speed = base feed (feed) × feed_override/100; both are in /sand_status.

LEDs (NVS-persisted; only present if leds: is configured)

$LED/Effect=<name> · $LED/Palette=<name> · $LED/Color=RRGGBB · $LED/Color2=RRGGBB · $LED/Brightness=0..255 · $LED/Speed=1..255 · $LED/Intensity=0..255 · $LED/Count=1..400 (strip length; default = config.yaml num_leds, applies on the next frame; idle/paused like the other $LED/*; not a live /sand_led key) · $LED/Order=GRB|RGB|…|GRBW|… (wire color order, any of the 30 permutations of RGB / RGBW; default = config.yaml color_order; applies on the next frame, reallocating for 3 <-> 4 bytes/pixel; idle/paused; not a live key; listed in /sand_settings) · $LED/RunEffect=none|<name> · $LED/IdleEffect=none|<name> · $LED/Speed and $LED/Intensity mirror WLED's two effect sliders per effect — an effect uses intensity exactly when WLED shows that slider, with WLED's meaning (gap size, # of balls, spark rate, …); a few effects also take WLED's speed meaning (fire = cooling, dissolve = repeat speed, lightning = gap between strikes) and fireworks ignores speed. Default intensity 128 · per-effect table in COMMANDS.md · $LED/White=none|brighter|accurate|max (RGBW strips — a 4-letter $LED/Order / color_order such as GRBW — only: how each pixel's W byte is derived from its RGB, WLED's auto-white modes; default accurate. No effect on 3-byte strips; /sand_status led.rgbw says which you have.) $LED/Direction=cw|ccw · $LED/Align=0..359 · $LED/BallSize=1..200 (the ball effect: ring winding vs theta, angular offset, glow size in LEDs). More ball settings: $LED/Color=blob colour · $LED/BallBright=0..255=blob brightness · $LED/Color2=solid background colour · $LED/BallBg=<effect>=background sub-effect (static=solid Color2, off=black, or any effect name like rainbow/fire/plasma rendered behind the blob) · $LED/BallBgBright=0..255=background brightness · $LED/Speed=tracking smoothness (low=smoother/laggier, high=snappier). Motion is sub-pixel/anti-aliased; master $LED/Brightness still scales the whole strip. Effect names: off static rainbow breathe colorloop theater scan running sine gradient sinelon twinkle sparkle fire candle meteor bouncing wipe dualscan juggle multicomet glitter dissolve ripple drip lightning fireworks plasma heartbeat strobe police chase railway pacifica aurora pride colorwaves bpm ball + 114 WLED effects (blink ... polar_lights; full list in COMMANDS.md) on firmware reporting "LED/Palettes". Effect, hook, ball-background and palette settings are stored by name (NVS keys LED/Effect2, LED/RunEffect2, LED/IdleEffect2, LED/BallBg2, LED/Palette2), moved once at boot from the old int8 keys Palette names: default (alias rainbow) + 67 — the original ocean lava forest party cloud heat sunset, then WLED's set; full list in COMMANDS.md. default keeps each effect's own colors (WLED's "Default"); any other palette recolors every effect except static pride police ball, replacing Color on the color effects. Firmware before WLED's palettes has only the first eight (id 0 named rainbow) and applies them to the auto-hue effects only. Live LED keys (/sand_led?… or $Sand/Led=): effect palette color color2 brightness speed intensity direction align size bg fgbright bgbright (bg=ball background sub-effect, fgbright=blob brightness, bgbright=background brightness)

The $LED/* settings are idle-gated, and since v0.1.18-rc3 also accepted while the table is PAUSED (Hold) — see "Settings and the machine state" below. For live control during a pattern use:

Command Notes
/sand_led?effect=&palette=&color=&color2=&brightness=&speed=&intensity= HTTP; any subset of keys; applies in-memory live, persisted to NVS on return to idle
$Sand/Led=<key>=<val> [<key>=<val> ...] command form, not idle-gated; same behavior
/sand_status led reflects the live value during a run.

$LED/RunEffect / $LED/IdleEffect yield to an explicit effect change. Setting the effect ($Sand/Led=effect=…, /sand_led?effect=… or $LED/Effect=…) suppresses the hook for the current machine state until the table next starts or stops moving — otherwise $LED/IdleEffect=off makes every "turn the LEDs on" a silent no-op at an idle table (the setting is written and the hook keeps the strip dark). Clearing a hook (=none) takes effect immediately. led.active in /sand_status always names the effect actually being rendered, and led.override names what is holding it apart from led.effect, so a client never has to infer it.

Playlist / quiet-hours settings (NVS)

$Playlist/Mode=single|loop · $Playlist/Shuffle=ON|OFF · $Playlist/PauseTime=<sec> · $Playlist/PauseFromStart=ON|OFF · $Playlist/ClearPattern=none|adaptive|in|out|sideway|random (adaptive chooses in/out only, never sideway) · $Playlist/ClearIn=<sd path> · $Playlist/ClearOut=<sd path> (clear-from-in/-out pattern files; empty = the playlist: config default) · $Playlist/ClearSpeed=<mm/min> (feed for clear moves; 0 = use $THR/Feed) · $Playlist/AutoHome=<n> · $Playlist/Autostart=<name> · $Sands/Enabled=ON|OFF · $Sands/Slots=HH:MM-HH:MM@days,... $Sands/LedOff=ON|OFF (turn LEDs off during quiet hours; works headless/idle) · $Sands/FinishPattern=ON|OFF (ON=pause between patterns/finish current [default]; OFF=feed-hold mid-pattern and resume when the window ends). Quiet hours need a set clock (time:/NTP).

$Playlist/Autostart=<name> auto-runs playlist /playlists/<name>.txt on every boot, once the table is Idle and has homed successfully (auto-play never starts from an unknown position; if no boot home arrives within ~5 s it requests one itself, honoring $Sand/HomingMode). Empty (default) disables it. The boot run uses its own parameters (independent of the manual-run $Playlist/* settings) so auto-play can behave differently: $Playlist/AutostartMode=single|loop · $Playlist/AutostartShuffle=ON|OFF · $Playlist/AutostartPause=<sec> · $Playlist/AutostartPauseFromStart=ON|OFF · $Playlist/AutostartClear=none|adaptive|in|out|sideway|random (defaults: loop, OFF, 0, OFF, none).

Clock (needed by quiet hours)

Configure NTP + timezone in config.yaml (time: section: ntp, server, tz). Runtime/over-HTTP: $Time/Show (current local time + sync state) · $Time/Set=<unix epoch> (set the clock manually) · $Time/Zone=<POSIX> (override + persist the tz, empty = use config). Prefer the JSON GET /sand_time for apps (read + ?epoch= / ?tz= to sync).

Optional DS3231 RTC (time: rtc_i2c: <bus> plus an i2c<bus>: section): the clock is restored from the chip at boot when nothing else has set it, and every clock set (NTP, $Time/Set, /sand_time?epoch=) is written back to it. The chip holds UTC. A set oscillator-stopped flag (new/dead battery) makes the firmware ignore the chip's time until the clock is set. $Time/RTC prints the chip's UTC time and flag state (no value; output goes to the command's channel, like $Time/Show). Appears in no JSON: time.synced simply reads true after a restore.

Command Notes
$RI=<ms> set this channel's auto-report interval (min 50 ms). Streams standard <state|MPos:…|…> frames
? one-shot status report

MPos:x,y,z is motor-space; the app can convert X/Y → θ/ρ, or just poll $Sand/Status (already converted) at 1–2 Hz for the sand-specific JSON.

WiFi onboarding / setup portal

Two ways to run the table, both driven by the same two NVS settings ($WiFi/Mode + $Sta/SSID):

  • Home-WiFi mode ($WiFi/Mode=STA>AP, the default): the table joins the LAN; the app finds it via mDNS. If the join fails (wrong password, 2.4 GHz SSID missing, moved house) or no SSID is set, the board falls back to its own AP (fallback AP) and serves a captive setup portal: joining the DuneWeaver-<MAC4> hotspot (password 12345678) pops the phone's captive sheet with a chooser — connect to home WiFi (scan, pick, password) or switch to standalone. A failed join's reason (wrong password / network not found / timeout) is shown on the portal. With an SSID saved, this boot-time hotspot keeps probing for the home network every 5 minutes (see below), so a table powered up before its router joins on its own once the network appears.
  • Standalone mode ($WiFi/Mode=AP): the AP is deliberate — the phone joins the hotspot and the app drives the same HTTP API at 192.168.0.1. In this mode the OS connectivity probes (/generate_204, /hotspot-detect.html, /ncsi.txt, /connecttest.txt) are answered with the "internet OK" responses each OS expects, so phones stay on the hotspot without captive nagging. (Android caveat: some builds still prefer cellular for a no-internet AP — the app should bind its socket to the WiFi network when in hotspot mode.) Switching standalone→home-WiFi: open http://192.168.0.1/wifi or use the routes below from the app.

Dropped home-WiFi links recover on their own. If the AP goes away (a router reboot, a rolling AP restart), the table retries the join itself rather than sitting dark until a power cycle — the ESP32 WiFi stack refuses to auto-retry some disconnect reasons, notably the one many APs send as they shut down. Retries start ~20 s after the drop and repeat every 30 s (slowing to 2 min after five tries), but only at a moment that cannot disturb motion: the machine at Idle (or Alarm — e.g. a failed boot home), or the instant a pattern or clear finishes, so a continuously looping playlist still gets recovery windows. A table is therefore reachable again within a minute of the AP returning if it is idle, or by the end of the current pattern if it is drawing. Serial log lines: WiFi Disconnected, reason <n> (<name>), WiFi down <n>s; reconnect attempt <n>, WiFi reconnected after <n>s, IP <addr>.

If the network stays gone, the setup hotspot comes up on its own. After the home network has been unreachable for $WiFi/ApFallbackMin minutes (default 10, 0 disables) — checked at the same safe moments, so never mid-pattern — the table raises the same DuneWeaver-<MAC4> AP and captive setup portal it uses at boot, at 192.168.0.1, without rebooting. This is the "moved house / renamed the network / changed the password" case: the owner joins the hotspot and re-points the table from the portal.

The station is not abandoned while the hotspot is up. It is parked (so the shared radio can hold the AP's channel) and wakes for a bounded probe of the home network every 5 minutes; if the router simply came back, the table rejoins the LAN on its own and the hotspot disappears again with no user action. Log lines: setup hotspot DuneWeaver-<MAC4> raised at 192.168.0.1 (home network probed every 5 min), probing home network (attempt <n>) while the hotspot stays up, and Setup hotspot lowered; back to station only.

The same hotspot-plus-probes is what a table gets at boot when its saved network is not found (first probe ~30 s after the hotspot rises). Choosing standalone from the hotspot stops the probing.

Only $WiFi/Mode=STA>AP (the default) raises the hotspot; a table deliberately set to STA stays a station. While the hotspot is up, GET /wifi_status reports mode:"fallback" and fail explains why: the boot join's failure reason, or how long the home network has been unreachable.

Portal routes (registered in every mode, so the app can also reconfigure a table over the LAN):

Endpoint Returns / action
GET / or GET /wifi the setup portal page (self-contained HTML; root serves it in every mode — the plain-text API map is at GET /help)
GET /wifi_status {mode:"sta"|"fallback"|"standalone", sta_ssid, ap_ssid, fail} — fail is this boot's STA join failure reason ("" if none)
GET /wifi_scan {status:"scanning"} while the async scan runs (poll ~1.5 s), then {status:"ok", aps:[{ssid, rssi, secure}]} — deduped per SSID, strongest signal kept, hidden SSIDs omitted. ?rescan=1 forces a fresh scan
POST /wifi_save form fields ssid (1–32 chars) + password (8–64 chars; open networks unsupported — Sta/MinSecurity defaults to WPA2). Persists credentials, forces $WiFi/Mode=STA>AP, replies {status:"ok",reboot:1}, then reboots (~0.5 s later). Success = table appears on the LAN; failure = fallback AP returns with fail set. Not Idle → 503 {status:"busy"}, and if a pattern/playlist is running this call stops it (homing is never interrupted); retry every ~2 s until ok
POST /wifi_standalone persists $WiFi/Mode=AP. From the AP: applies live (no reboot, phone stays joined), replies {reboot:0}. From STA: replies {reboot:1} and reboots into the hotspot. Busy handling as /wifi_save — from the AP no reboot follows, so a playlist it stopped stays stopped

Serial onboarding (used by the USB installer; ASCII SSIDs only over serial): [ESP410] (scan → {"AP_LIST":[{SSID,SIGNAL,IS_PROTECTED},…]}) · $Sta/SSID= · $Sta/Password= · $WiFi/Mode=STA>AP · $Bye (reboot). Non-ASCII SSIDs only work over the HTTP/WS path, not serial.

$Sand/Status JSON schema

Single-line JSON (SandStatus.cpp:encode). Float precision: θ/ρ 4 dp, x/y 3 dp, feed 0 dp, progress 3 dp.

{
  "state": "Idle|Run|Hold|Alarm|Home|Jog|...",
  "kinematics": "ThetaRho",   // coordinate model: "ThetaRho" (theta/rho below) or
                              //   "CoreXY"/"Cartesian" — then the two position fields are
                              //   "x" and "y" in machine mm instead of theta/rho, and
                              //   "feed" is 0 (each G-code pattern carries its own F words;
                              //   speed control is feed_override)
  "theta": 1.2340,            // radians, accumulates turns
  "rho": 0.5000,              // 0.0 center .. 1.0 perimeter
  "feed": 100,                // $THR/Feed programmed rate, motor mm/min
  "feed_override": 110,       // live override % (set via /sand_feed); effective = feed * pct/100
  "running": true,            // an SD job is active
  "file": "/sd/patterns/star.thr",
  "progress": 0.425,          // 0..1 fraction of executed motion, or -1 if unknown
  "elapsed": 312,             // seconds since the current pattern started drawing, or -1 if nothing running.
  //  Pair with progress for a client-side ETA:  remaining_s = elapsed * (1 - progress) / progress;
  //  finish = <client's own now> + remaining_s. Monotonic clock (immune to the device's tz/RTC), so
  //  DON'T treat it as a wall-clock timestamp. It STANDS STILL through a mid-pattern hold (quiet
  //  hours, /sand_pause) since v0.2.9; before that it kept counting, which inflated the ETA after
  //  a resume. Progress stands still too, so gate the ETA on state == "Run" and on
  //  progress above a small floor (~0.03) — below that the divide blows the estimate up. A fresh
  //  count starts on every pattern (and excludes any pre-execution clear, which is timed separately).
  "playlist": { "active": true, "index": 2, "total": 10, "name": "evening",
                "next": "/patterns/owl.thr", "last": "/patterns/star.thr",
                "clearing": false, "quiet": false, "pause_remaining": -1, "pause_total": -1 },
  //  next = what the table will draw next, resolved from the firmware's internal
  //  (possibly shuffled) order. ALWAYS use this for an "up next" display — deriving
  //  it from the playlist file's line order is wrong whenever shuffle is on.
  //  Phase-dependent: while a pre-execution clear is drawing (clearing=true), next
  //  is THIS item's own pattern — the one the clear is preparing for (so "up next"
  //  during a clear shows the pattern about to appear, not the following item).
  //  Once the main pattern is drawing, next is the genuine following item.
  //  "" = unknown: last pattern of a loop pass (the next pass reshuffles when it
  //  starts) — show nothing or "reshuffling".
  //  last = the most recently COMPLETED pattern of this run = what is currently
  //  drawn on the table. During the between-patterns pause it names the pattern
  //  that just finished, so render its preview as "on the table now". "" until
  //  the first pattern of the run completes. (A skipped/aborted pattern never
  //  finished drawing, so it does not become last.)
  //  clearing=true means a pre-execution clear is running before the chosen
  //  pattern; progress then tracks the CLEAR file's own 0..1 progress (file is the
  //  clear pattern). Render it as a separate "Clearing…" bar that resets when the
  //  real pattern starts, rather than the chosen pattern's progress.
  //  pause_remaining = seconds left in the between-patterns pause ($Playlist/PauseTime),
  //  counting down live; pause_total = that pause's full length in seconds; both -1
  //  when not pausing. Progress bar fill = (pause_total - pause_remaining) / pause_total.
  "led": { "effect": "rainbow", "active": "rainbow", "brightness": 40, "rgbw": false },  // omitted if no leds: config
  //  effect = the chosen effect ($LED/Effect, or a live mid-run override).
  //  active = what the strip is ACTUALLY showing (since v0.1.19; fall back to effect).
  //  These differ while something overrides the choice, and then an "override" member
  //  names it: "idle"/"run" = the $LED/IdleEffect / $LED/RunEffect state hook,
  //  "quiet" = Still Sands holding the strip off. Absent when nothing overrides.
  //  Show `active` to the user: reading only `effect` reports LEDs "on · rainbow" at a
  //  table whose $LED/IdleEffect=off is keeping it dark.
  //  rgbw = true when the strip is 4 bytes/pixel (color_order has a W); only then does
  //  $LED/White do anything, so hide the white-mode control otherwise.
  "sd_ok": true,              // boot-time SD readability probe; omitted if no SD configured.
  //  false = card didn't mount or root unreadable at boot (unseated/corrupt) -> surface
  //  a "check SD card" banner. Re-tested only on reboot.
  "last_reset": "power_on",   // why the board last rebooted: power_on|software|panic|
  //  int_wdt|task_wdt|wdt|brownout|external|deepsleep|sdio|unknown. panic/wdt/brownout
  //  mean a crash; pair with /sand_bootlog (panic preserves the previous boot's log).
  "uptime": 86400,            // seconds since boot; a drop between polls = silent reboot
  "heap": 145000,             // free heap bytes now
  "heap_min": 98000,          // lowest free heap since boot (low-water mark)
  "heap_largest": 60000,      // largest allocatable block; heap flat + this decaying
  //  = fragmentation trending toward an OOM panic — alert well before it hits ~2 KB
  "fw": "v0.1.2 (main-8035bb6e)",  // firmware version — compare against the app's
  //  latest release to offer an update; re-read after POST /updatefw to verify
  "mcu": "esp32",              // build target: "esp32" | "esp32s3". OTA clients MUST
  //  flash the matching MCU-prefixed release image (esp32-firmware.bin /
  //  esp32s3-firmware.bin) — a wrong image uploads fully and is only rejected by the
  //  chip-ID check at the very end (the 0xE9 magic byte is identical on both).
  //  Absent on firmware that predates the field: treat as "esp32" (every table in
  //  the field before the S3 board is one).
  "mac": "a0:b1:c2:d3:e4:f5",  // lowercase STA MAC — the table's STABLE IDENTITY.
  //  Key saved tables by this (not IP, not hostname): it dedupes a table added
  //  by IP against the same one found via mDNS (whose TXT carries the same
  //  value), and survives DHCP changes and hostname edits.
  "hostname": "DWMP",          // network hostname — $Hostname if the user has renamed
  //  the table, else config.yaml `hostname:` (its factory name). A human-readable
  //  default name for a table added by bare IP. Rename with `$Hostname=<name>`;
  //  this field and <name>.local follow immediately, no reboot needed.
  "time": { "epoch": 1718971402, "synced": true, "local": "2026-06-21 14:03:22", "tz": "ICT-7" }
  //  synced=false means the clock isn't set (no NTP yet / no $Time/Set) -> quiet
  //  hours won't fire; the app can push time via GET /sand_time?epoch=<unix>.
}

Files

Storage layout (SD card)

  • /patterns/*.thr — patterns. Line format: <theta_rad> <rho_0..1>; # comments; blanks ignored. Cartesian (CoreXY) tables use plain G-code patterns instead (.gcode/.gc/.nc, host-generated).
  • /playlists/*.txt — one SD-relative pattern path per line; # comments. Max 64 KB / 1024 items.
  • /clear_from_in.thr, /clear_from_out.thr, /clear_sideway.thr — clear templates (a cartesian table points the playlist: clear paths at G-code wipe files; adaptive can't read a first-ρ from G-code, so it falls back to a random in/out pick).

Fetch a file (for in-app preview)

GET /sd/patterns/<file>.thr (and any /sd/... path) — served by the catch-all file handler. The app fetches the .thr and renders the polar preview locally (no server-side thumbnails).

Ranged GETs are supported (single bytes= ranges: a-b, a-, -n): responses carry Accept-Ranges: bytes; a valid Range: header gets 206 + Content-Range, a range past EOF gets 416. Multi-range or malformed headers fall back to the whole file (200). Clients pulling multi-MB files (preview-bundle shards) should fetch in ranged chunks of ≤256 KB: the server is single-threaded, so one monolithic 5 MB response leaves every other client (status polls, stop buttons) unserved for the whole transfer, and their queued connections each pin ~2 KB of heap. A transfer may also be cut short mid-body if free heap drops below ~12 KB (detect via the byte count / shard hash and retry with backoff).

Load shedding (low heap)

Three floors. The warn line is on total free heap; the two shedding floors are gauged on the largest allocatable BLOCK (heap_largest), not total free — a fragmented heap can sit at 11–14 KB free while the largest block collapses to ~5 KB, which is what actually fails an allocation or an SD remount:

  • < 15 KB free — [MSG:WARN: Low memory: dipped to N bytes (largest M), now F free/L largest, http busy <uri> for Tms, pend=P] in /sand_log. N/M are this dip's trough and the largest block at that trough; F/L are the heap at the instant the line was printed, so a wide gap between the pairs means the board has already recovered. The http … tail names what the web server was serving — the usual culprit behind a crater is a connection pileup while one long request monopolizes the single-threaded server. The warning re-arms once free heap climbs back over 30 KB, so a table that craters repeatedly logs every crater. (Before v0.1.19 the line was Low memory: N bytes, largest M, … where N was the boot-lifetime minimum and M was sampled live at print time — two different instants, which produced impossible readings like 2452 bytes, largest 65524, and only the single deepest dip of the whole boot was ever reported.)
  • largest block < 12 KB — non-exempt routes get 503 busy: low memory before the handler runs; /sand_status, stop/pause/resume, and a /sand_patterns revalidation (conditional GET with If-None-Match) still work.
  • largest block < 8 KB — new connections are RST-closed at accept, before the request is read (no route is exempt — parsing itself costs heap the board no longer has). Back off and retry. The same happens for 2 s after any failed allocation (the board's emergency window, see $Net/Filter below), even if the heap has already bounced back.
  • free heap < 14 KB — responses slow down instead of failing: each write waits (up to 200 ms, 1 s per request) for queued TX buffers to drain, and a /sand_patterns stream waits up to 1 s in total before it gives up below 12 KB. Expect a slower response, not an error.

Upload

POST /upload (SD) multipart: the multipart filename carries the full destination path (filename=/patterns/x.thr; a path arg is ignored — a bare filename lands at /); field <filename>S = size in bytes, field <filename> = file bytes (both named with that full path). Returns JSON {status, files:[{name,size,…}], path, total, used, occupation}; send ?dontlist=yes to leave the files listing out (an SD directory walk nobody needs after an upload; the app always does). Pre-checks free space. Missing parent folders are created automatically (a card prepared on a computer often lacks /playlists / /patterns). (Serial alternative: $Xmodem/Receive=<path> / $Xmodem/Send=<path>.) The size check compares <filename>S with the bytes that reached the file (every write and the close succeeded), not a stat of the file afterwards. An SD upload that doesn't complete (cut off, wrong size, failed close) is deleted, not left truncated under its real name (since v0.2.3). A complete upload of a pattern (.thr, .gcode/.gc/.nc) under /patterns (not previews/) is appended to /patterns/index.json in place when the card has one and it doesn't list the file yet (since v0.2.3), so a client no longer has to rewrite the manifest after an upload (one that does finds the entry there and has nothing to do); deletes still need the client's update. Parts may come in any order and a request may carry many files, minutes of them (since v0.2.3: the app sends a whole background sync as one request); a request takes at most 32 non-file fields, so a big batch leaves the optional <filename>S size fields out (each is held for the whole request). Timing on a DW Gold (8 MHz SD bus, a big /patterns, 2026-11-15): a small pattern ~0.55 s (it was ~1.5 s: the per-upload directory lookups and SD remounts); a NEW file 1–3 s, more the more files in its folder share its first 6 characters (FAT short-name generation scans the directory several times); 1 MB ~7.5–8 s (was ~9 s; ~130 KB/s, the TCP window and the Wi-Fi, not the SD, are the limit). A file part's data may pause up to 30 s; longer, and the upload is dropped (upload cancelled); the next upload then works (before 2026-11-15 it failed once with 500 upload cancelled). Refused while the table runs (since v0.2.8): a multipart POST /upload or /files while a job is active or the machine is in Cycle/Hold/Homing/Jog (the same rule as /updatefw) answers 409 busy: the table is running without reading the body. The body is read inside the task that feeds the running pattern its next line, so on v0.2.7 and older an upload mid-pattern stopped the ball until the transfer ended, and the table answered nothing meanwhile (the app read it as offline). Because the body stays unread, the board's close is a TCP reset: a client still sending may see that reset instead of the 409. Upload at Idle (or Alarm); stop or finish the pattern first.

File ops (GET /upload?path=<dir>&action=delete|deletedir|createdir|rename&filename=<name>[&newname=])

Same JSON shape as upload. An action= request carries no files listing unless it also passes list=yes (since v0.2.1; before that every action re-listed path in one in-RAM string, which on a full /patterns folder was a bad_alloc panic + Test-Drive boot — send dontlist=yes to pre-v0.2.1 firmware). Any listing (GET /upload?path=<dir> with no action, or list=yes) stops at 100 entries and then carries "truncated":"true"; it is a maintenance view, not the catalog — use /sand_patterns for that. If building even the capped listing fails for memory, the response is a 500 cannot list <dir>: … with the action's own outcome still in status.

File-op errors (upload, delete, createdir, rename, list)

Success is HTTP 200 with status text. Any failure is a real HTTP error plus an error member: {"status":"Upload failed", "error":{"code":"2","message":"<detail>"}} (the file-ops encoder emits numbers as JSON strings — same as occupation).

  • 503 — filesystem inaccessible (SD unmounted/dead); body status is No SD card
  • 507 — not enough space
  • 401 — authentication (when auth is enabled)
  • 500 — everything else (create/write/rename/delete failed, size mismatch, …)

error.code: 1 auth, 2 file-creation/fs-inaccessible, 3 write, 4 upload/size-mismatch, 5 space, 6 cancelled, 7 close, 8 generic file op. error.message carries the actionable detail (e.g. cannot create /patterns/sub/x.thr (missing directory, bad name, or filesystem full)). Uploads create missing intermediate directories themselves; on older firmware fopen won't, so clients targeting them should createdir first when uploading into a new subfolder (createdir on an existing dir answers 500 — treat as success).

Low-memory load shedding (any route)

When the largest free block drops below ~12 KB, EVERY route except /sand_status, /sand_stop, /sand_pause, and /sand_resume answers 503 plain-text busy: low memory instead of running its handler (a stalled handler used to wedge the whole single-threaded server). Clients should back off and retry in a few seconds; the status poll keeps working so the app can tell the table is still alive.

Network protection (v0.2.10)

The station's RX path runs through the firmware's own hook (WiFi STA only; the setup hotspot is untouched):

  • $Net/Filter=ON|OFF (NVS, default ON) rate-limits traffic that measurably costs heap: ICMP echo 10/s, new TCP connections to :80/:23 30/s, UDP other than DHCP/DNS/NTP/mDNS 50/s, IPv4 fragments 20/s (bursts allowed). When free heap is under 12 KB, or for 2 s after any allocation failed, only frames that help the heap recover are admitted: ARP, segments of established TCP connections, and DHCP/DNS/NTP replies.
  • $Net/FilterStats prints passed/dropped per class, emergency_dropped, rx_frames and alloc_failures.
  • A liveness watchdog always runs, filter on or off. If no frame arrives for 60 s while the station reports connected, it ARPs the gateway. After a further 10 s of silence it reconnects, and if the link is still dead 60 s after that it restarts (never during homing). It logs WiFi: no frames for N s while connected; reconnecting and WiFi: link still dead after a reconnect; restarting.

Crash recovery. One panic no longer drops the table into Default (Test Drive): the board reboots into its real config (log: Restarted after a panic; loading the configuration, /sand_status last_reset:"panic"). Only a second panic in a row, with no healthy 10 minutes between them, falls back to Test Drive, which keeps crash-loop protection.

Firmware update (OTA)

POST /updatefw multipart: field <name>S = size in bytes, field <name> = the app image, which must match this board's MCU — flash the release asset the status/probe mcu field names (esp32-firmware.bin / esp32s3-firmware.bin; the unprefixed firmware.bin release alias is the ESP32 image). A wrong-MCU image uploads fully and only fails at the final chip-ID check ("failed", old firmware keeps running) — the 0xE9 magic byte is identical on both chips, so nothing catches it earlier. The image is written to the inactive OTA slot. GET /updatefw (no file) probes availability first.

Response {"status", "code", "fw", "mcu"} (mcu absent on firmware predating it — treat as "esp32"):

  • "ok" (HTTP 200) — flashed; the board reboots ~1 s after responding. Poll /sand_status until uptime resets, then verify fw shows the new version (~10–30 s WiFi rejoin).
  • "ready" / "busy" (200 / 409) — probe result. Updates are rejected while motion or a job is running so an app-triggered auto-update can never kill a pattern mid-run; retry when idle. Updates DO work in Alarm/ConfigAlarm — a wedged board must stay updatable.
  • "failed" (HTTP 500) — upload rejected or image invalid; code is the raw UploadStatus enum (0 none, 1 failed, 2 cancelled, 3 successful, 4 ongoing).

App auto-update flow: read fw from /sand_status → compare to latest release → GET /updatefw until "ready" → POST the image → poll /sand_status for the new fw. Note the response contract above applies from this firmware onward; a board still on an older build replies with the legacy {"status":"<code>"} body.

Security / constraints

API password ($Sand/Password)

Off by default (empty value = everything open, the historical behavior). Setting a password locks the network control surfaces; reads stay open so status pollers need no credentials.

  • Set / change / clear: $Sand/Password=<pw> (1–32 chars) over /command or serial; $Sand/Password= clears. Accepted at idle or while paused (see "Settings and the machine state"). Once set, changing it requires the key (it rides /command). USB serial is never gated — a lost password is read or cleared over USB.
  • Sending the key: ?key=<pw> query arg or X-Sand-Key: <pw> header on the request. Wrong/missing key → 401 {"status":"password required (send ?key= or X-Sand-Key)"}.
  • Locked routes (when a password is set): /command, /command_silent, all action routes (/sand_home|stop|pause|resume|goto|feed|led), the /feedhold_reload//cyclestart_reload//restart_reload trio, file ops + uploads (/files, /upload), firmware update (/updatefw), /sand_time with epoch/tz args, /sand_coredump?erase=1, and /wifi_save//wifi_standalone in STA/standalone modes (the fallback provisioning AP is exempt so the captive portal keeps working).
  • Open routes: /, /help, /sand_status, /sand_patterns, /sand_playlists, /sand_settings (never includes the password), /sand_bootlog, /sand_log, /sand_coredump (read), /sand_time (read), /wifi_status, /wifi_scan, and plain file downloads (e.g. GET /config.yaml).
  • No other network control surface. The build has no telnet (port 23; the $Telnet/* settings are gone) and no ArduinoOTA/espota (port 3232), so the HTTP lock covers the whole LAN side. Firmware updates use /updatefw (locked).

Scope: this is a LAN convenience lock (plain HTTP, no TLS — the key is visible to anyone sniffing the LAN). It keeps guests and stray scripts from driving the table; it is not a defense against a hostile network.

Settings and the machine state

NVS-backed $Key=value writes are state-gated: FluidNC refuses them outside Idle/Alarm with Error: Command requires idle state (IdleError), because a flash write under a running job can disturb it and a machine-config change would corrupt the rest of the run.

Since v0.1.18-rc3 the sand-table policy settings are additionally accepted while the table is paused (Hold) — a feed hold is a job standing still, so nothing is stepping and nothing is streaming off the SD card. That is what lets a client offer "pause to change settings" instead of demanding a stop:

  • accepted while paused: $Playlist/* (including the Autostart* overrides), $Sands/*, $LED/*, $Hostname, $Sand/Password, $Log/SD, $Sand/HomingMode, $Sand/ThetaOffset (the last two are consulted at HOME time, and resuming a paused job never re-homes, so they cannot disturb the job in flight).
  • still Idle/Alarm only: everything else — machine configuration, $THR/Feed, WiFi credentials (/wifi_save reboots the table, which a paused job would not survive), and $Sand/Goto jogs (SandApi::goTo requires Idle), which is what the orientation-alignment flow uses.

Unrelated to this, SD file operations and OTA (/updatefw) treat Hold as busy: the paused job still holds its file open, and a flash+reboot ends it.

Other constraints

  • No CORS headers in the sandtable build. Native apps are unaffected by CORS; a browser/Electron app on another origin would need CORS added to WebServer.cpp.