diff --git a/.github/ci/build-esp3d.sh b/.github/ci/build-esp3d.sh index fe56f409..854632c0 100644 --- a/.github/ci/build-esp3d.sh +++ b/.github/ci/build-esp3d.sh @@ -39,6 +39,8 @@ else platformio run -e esp32dev platformio run -e esp32-s2 platformio run -e esp32-s3 + platformio run -e wemos_s2_mini + platformio run -e esp32_s3_touch_lcd147 platformio run -e esp32-c3 platformio run -e esp8266dev fi diff --git a/.gitignore b/.gitignore index 07e8293d..cb7b690e 100644 --- a/.gitignore +++ b/.gitignore @@ -10,4 +10,6 @@ embedded/node_modules .vscode/launch.json .vscode/arduino.json esp3d/myconfig.h -__pycache__ \ No newline at end of file +__pycache__ +to_do/ +discussions-consensus/ diff --git a/docs/Commands.md b/docs/Commands.md index 3276b699..5e696896 100644 --- a/docs/Commands.md +++ b/docs/Commands.md @@ -244,11 +244,12 @@ label can be: light/framesize/quality/contrast/brightness/saturation/gainceiling output is JSON or plain text according parameter `[ESP450]json= ` -* Get authentication level - `[ESP500] json=` +* Get authentication level / login for stream clients (telnet, WebSocket data, Bluetooth, USB CDC, serial bridge) + `[ESP500] json= pwd=` + `[ESP500]LOGOUT json=` -* Get/Set session timeout - `[ESP510] json= pwd=` +* Get/Set session timeout (web interface / stream clients) + `[ESP510]HTTP= STREAM= json= pwd=` * Change admin password `[ESP550] json= pwd=` @@ -308,6 +309,9 @@ label can be: light/framesize/quality/contrast/brightness/saturation/gainceiling * Get / Set Serial Baud Rate `[ESP901] json= pwd=` +* Get / Set USB host (OTG) Baud Rate + `[ESP902] json= pwd=` + * Get state / Set Enable / Disable buzzer `[ESP910] json= pwd=` @@ -321,5 +325,8 @@ label can be: light/framesize/quality/contrast/brightness/saturation/gainceiling * Get state / Set Enable / Disable / Close native USB CDC client `[ESP935] json= pwd=` +* Get / Set printer output: serial (UART) or USB host (OTG) + `[ESP950] json= pwd=` + * Set quiet boot if strapping pin is High `[ESP999]QUIETBOOT pwd=` diff --git a/docs/Module-client.md b/docs/Module-client.md index 9226f4f5..51bbf4dc 100644 --- a/docs/Module-client.md +++ b/docs/Module-client.md @@ -54,4 +54,36 @@ USB Serial is a full duplex client, it is optional output client for ESP32 S2/S3 The Library has 2 intialization functions: `usb_serial_init()` and `usb_serial_create_task()` which handle usb events. if no need to handle usb events just call `usb_serial_init()` and do not call `usb_serial_create_task()`. Additionaly USB Serial client has a dedicated task that check if there is any supported USB Serial device connected, it try all drivers one by one until it find one that match the supported ones. -If device is found it willhook a usb event function and a onreceive function to handle data. \ No newline at end of file +If device is found it willhook a usb event function and a onreceive function to handle data. + +## USB CDC (native USB device) + +USB CDC is a full duplex user client (like telnet or websocket), it is not an output client: the printer/cnc stays on the serial port (UART0) or on USB host ([ESP950]). +It is for boards without USB-UART chip, where the ESP32 USB connector is the native USB (ESP32 S2/S3/C3/C6), the PC connects to ESP3D through this port. + +It needs `USB_CDC_CLIENT_FEATURE` and `ARDUINO_USB_CDC_ON_BOOT=1`, and is not compatible with `USB_SERIAL_FEATURE` (same USB controller). +With `ARDUINO_USB_CDC_ON_BOOT=1`, `Serial` is the native USB and UART0 is `Serial0`, ESP3D uses `Serial0` for the printer. +Available environments in platformio.ini: `wemos_s2_mini` (TinyUSB, `ARDUINO_USB_MODE=0`) and `esp32_s3_touch_lcd147` (USB-Serial-JTAG, `ARDUINO_USB_MODE=1`). + +### PC -> ESP3D + +The handle function polls the port, fills the buffer until `\n` is found, buffer is full or no data comes for 1.5 s, then the message is dispatched to the output client (or processed if it is an ESP3D command). Realtime commands are sent immediately. +Authentication works like serial client: `pwd=` with `ESP_SECURE_SERIAL`, and authentication is reset when the PC disconnects. + +### ESP3D -> PC + +Data are sent using `availableForWrite()` with a short timeout, if no PC reads the port the data are dropped instead of blocking ESP3D. +Printer/cnc responses are sent to the PC only when the port is opened by the PC. + +### Settings, commands and log + +* `[ESP935]` enable / disable (at next boot) / stop the client, `service/usb_cdc` setting in [ESP400], `USB_CDC_active` in esp3dcnf.ini +* `LOG_OUTPUT_USB_CDC` sends the log to the same port, a warning is displayed at build time if the client is also enabled because log and responses are mixed +* `LOG_USB_CDC_WAIT_MS` wait up to x ms at boot for the PC to open the port, to get the first log lines + +## Authentication of user clients + +With `AUTHENTICATION_FEATURE`, the user clients (telnet, websocket data, bluetooth, USB CDC, serial bridge) start as `guest` at each connection. A guest client can only send ESP3D commands: G-code, free text and realtime commands are refused with an error, and the printer/cnc output is not sent to it, until it authenticates with `pwd=` on an ESP3D command (`[ESP500] pwd=` is the recommended one). +USB CDC and serial bridge are locked only if the serial security setting (`ESP_SECURE_SERIAL`) is enabled. The serial / USB host link to the printer/cnc is not concerned. +Only one client of each type is connected at a time, a second one is refused. +See [authentication](authentication.md) for details. diff --git a/docs/authentication.md b/docs/authentication.md index 7bb69def..05282fa1 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -33,13 +33,42 @@ The web interface allows also inline authentication. This means that you can pas http://user:password@ ``` -On the web interface an authenticated session will stay open until the browser is closed. So if you close the browser and reopen it, you will be asked for authentication again. This session can also have a timeout. The default timeout is 3 minutes of inactivity. This timeout can be changed in the ESP3D configuration web interface or using `[ESP510]` command. +On the web interface an authenticated session will stay open until the browser is closed. So if you close the browser and reopen it, you will be asked for authentication again. This session can also have a timeout. The default timeout is 3 minutes of inactivity. This timeout can be changed in the ESP3D configuration web interface or using `[ESP510]HTTP=` command. ## ESPXXX Command When user authentication is enabled, the ESPXXX commands will ask for a password. If the authentication is successful, the command will be executed. If the authentication fails, the command will be rejected. The session for ESPXXX commands is a sticky session. This means that once authenticated, the session will stay authenticated until the ESP3D is restarted or session is closed (e.g: Telnet / WebSocket). + +On stream clients (see below), `pwd=` on any ESPXXX command authenticates the client. The recommended command is `[ESP500] pwd=`, because it answers the resulting level. A wrong password returns an error and the client keeps its current level. `[ESP500]LOGOUT` sets the client back to `guest`. + +## Stream clients: Telnet, WebSocket data, Bluetooth, USB CDC, serial bridge + +When authentication is enabled, a stream client is `guest` after connection. A guest can only send ESPXXX commands, to authenticate: + +``` +[ESP500] pwd= +``` + +The answer is the resulting level (`user` or `admin`). Until the client is authenticated: +- G-code, free text and realtime commands (`?`, `!`, `~`, 0x18…) are refused with `error: authentication required, use [ESP500] pwd=` +- file transfers on WebSocket data are refused (status `L`, see [WebSocket protocol](websockets_protocol.md)) +- the machine output (printer / CNC responses) is not sent to the client + +Rules: +- The authentication only applies to the client that sent the password, and lasts until it disconnects, logs out with `[ESP500]LOGOUT`, or its session expires. +- Session timeout: after `stream session timeout` minutes without anything received from the client, it is back to `guest` and receives `session expired`. 0 (default) means no timeout. Set it with `[ESP510]STREAM=` or `[ESP401]`; it is separate from the web interface timeout, because a client that only listens (e.g. a pendant showing the machine state) sends nothing. +- A wrong password returns `Wrong password`, the client keeps its current level. +- A new connection always starts as `guest`. +- Only one client at a time per type: a second Telnet or WebSocket data client is refused with `error: another client is already connected`, the first one is not affected. Dead connections are closed after a short delay (WebSocket ping / TCP keepalive). +- Serial bridge and USB CDC are local links: they are locked only if the serial security setting is enabled (`[ESP400]` `security/serial`, `ESP_SECURE_SERIAL`), like the serial port. +- The serial / USB host link to the printer or CNC is not concerned: its data are the machine responses. + +## WebUI terminal WebSocket + +When authentication is enabled, the WebUI terminal WebSocket (`/ws`) only accepts a connection that carries a valid WebUI session cookie (`ESPSESSIONID`). A connection without valid session is refused and does not disconnect the current WebUI. When the session ends, the terminal WebSocket is closed too: immediately on logout, and at the next data received from the WebUI (e.g. `PING`) on session expiry. The WebUI session and the stream client authentication are independent: one never authenticates the other. + # Limitations The current authentication miss a lot of features, like: @@ -57,7 +86,9 @@ Because ESPXXX commands only rely on password, do not use same password for user The password are never been displayed in clear text, but they are stored in the ESP3D configuration in clear text. So if you want to change the password, you must use the WebInterface or ESPXXX commands. In web interface the passwords are replaced by `*******` so any modification must be complete not partial. -All passwords and sensitive informations are sent using plain text. So if you want to use ESP3D in a public network or outside of your local network (which is not recommended), you must use a VPN. +All passwords and sensitive informations are sent using plain text, on HTTP and on all stream clients (Telnet, WebSocket, Bluetooth, USB CDC, serial bridge). So if you want to use ESP3D in a public network or outside of your local network (which is not recommended), you must use a VPN. + +Stream clients have no session timeout by default: once authenticated, a client stays authenticated until it disconnects or logs out. A serial bridge has no connection, so it stays authenticated until `[ESP500]LOGOUT` or restart, unless a stream session timeout is set. # Scope @@ -66,9 +97,11 @@ Here the scope of right for each authentication level: |-|:-------------------:|:--------:|:------:|:-------:| | Web Interface | No | No | Yes | Yes | | Telnet | No | No | Yes | Yes | -| WebSocket | No | No | Yes | Yes | +| WebSocket (terminal `/ws` and data `/wsdata`) | No | No | Yes | Yes | | WebDav | No | No | Yes | Yes | | Bluetooth | No | No | Yes | Yes | +| USB CDC (if serial security enabled) | No | No | Yes | Yes | +| Serial bridge (if serial security enabled) | No | No | Yes | Yes | | Upload | No | No | Yes | Yes | | Update | No | No | No | Yes | | ESP0 | Yes | Yes | Yes | Yes | @@ -138,23 +171,26 @@ Here the scope of right for each authentication level: | ESP800 | No | No | Get/Set | Get/Set | | ESP900 | No | No | Get/Set | Get/Set | | ESP901 | No | No | Get | Get/Set | +| ESP902 | No | No | Get | Get/Set | | ESP910 | No | No | Get/Set | Get/Set | | ESP930 | No | No | Get | Get/Set | | ESP931 | No | No | Get | Get/Set | | ESP935 | No | No | Get | Get/Set | +| ESP950 | No | No | Get | Get/Set | | ESP999 | No | No | No | Set | # API Description ## Global -Each authenticated session have unique session id, that will be stored on ESP3D with additionnal informations: -- session id (25 characters) +Each authenticated HTTP session has a unique session id, that is stored on ESP3D with additional information: +- session id - session level (Guest / Admin / User) -- client_id (serial / http / telnet / WebSocket) +- client type - session last activity (timestamp) -- client IP (http) -- Client socket ID (telnet / WebSocket) +- client IP + +Stream clients (Telnet, WebSocket data, Bluetooth, USB CDC, serial bridge) have no session id: the authentication level is kept by the client service, and reset to `guest` when the client disconnects. ## Http When authentication is enabled, the http server will check if the session is authenticated. If not, it will ask for authentication. If the session is authenticated, it will check if the session is still valid. If not, it will ask for authentication again. If the session is still valid, it will process the request. -the Session ID is stored in the cookie `ESP3D_SESSIONID`. +the Session ID is stored in the cookie `ESPSESSIONID`. diff --git a/docs/esp3dcnf.ini b/docs/esp3dcnf.ini index e740193c..ebc35a3f 100644 --- a/docs/esp3dcnf.ini +++ b/docs/esp3dcnf.ini @@ -69,6 +69,9 @@ Serial_Bridge_active = Yes # Serial Bridge baudrate Serial_Bridge_Baud = 115200 +#Active or not native USB CDC client Yes / No (USB_CDC_CLIENT_FEATURE only) +USB_CDC_active = Yes + #Active or not HTTP Yes / No HTTP_active = Yes @@ -146,7 +149,9 @@ Time_DST = No ADMIN_PASSWORD = xxxxxxx USER_PASSWORD = xxxxxxx #session time out in min -Sesion_timeout = 3 +Session_timeout = 3 +#stream clients (telnet, websocket, bluetooth, usb cdc, serial bridge) session time out in min, 0 = no time out +Stream_session_timeout = 0 #Sensor type if enabled None / DHT11 / DHT22 / ANALOG / BMP280 / BME280 SENSOR_TYPE = NONE diff --git a/docs/espXXX.md b/docs/espXXX.md index 1ead362f..cf13fdca 100644 --- a/docs/espXXX.md +++ b/docs/espXXX.md @@ -2134,17 +2134,23 @@ archetype = "section" title = "[ESP500]" weight = 800 +++ -Get authentication status +Get authentication status / authenticate a stream client (Telnet, WebSocket data, Bluetooth, USB CDC, serial bridge) / logout ## Input -`[ESP500] json= pwd=` +`[ESP500] json= pwd=` +`[ESP500]LOGOUT json=` + +* LOGOUT +the client is back to `guest`, the answer is the new level (`guest`). For a web request, the web session is closed too. * json=no the output format can be in JSON or plain text -* pwd= -the admin password if authentication is enabled +* pwd= +the user or admin password if authentication is enabled. +On a stream client, the resulting level stays attached to the client until it disconnects, logs out or its session expires (see `[ESP510]`). With a wrong password, the command returns an error and the client keeps its current level. +Any ESPXXX command with `pwd=` authenticates the client the same way, `[ESP500]` is the recommended one because it answers the resulting level. ## Output @@ -2169,23 +2175,42 @@ the admin password if authentication is enabled admin ``` +- Wrong password, in json format + +```json +{ + "cmd":"500", + "status":"error", + "data":"Wrong password" +} +``` + + - plain text format + +```Text +Wrong password +``` + +++ archetype = "section" title = "[ESP510]" weight = 800 +++ -Set/display session time out +Set/display session time out, for web interface (HTTP) and for stream clients (Telnet, WebSocket data, Bluetooth, USB CDC, serial bridge) ## Input -`[ESP510] json= pwd=` +`[ESP510]HTTP= STREAM= json= pwd=` +`[ESP510] json= pwd=` (HTTP timeout, for compatibility) * json=no the output format can be in JSON or plain text -* timeout - * if timeout is empty, it will display current timeout (0~255 minutes), 0 means disable timeout - * if timeout is not empty, it will set the timeout +* timeout (0 means disable timeout): HTTP 0~255 minutes, STREAM 0~254 minutes + * if no parameter, it will display both timeouts + * `HTTP=` web interface session timeout, default 3 minutes + * `STREAM=` stream client session timeout, default 0: after this delay without anything received from the client, it is back to `guest` + * `HTTP=` and `STREAM=` can be set together or alone * pwd= the admin password if authentication is enabled @@ -2199,18 +2224,18 @@ the admin password if authentication is enabled { "cmd":"510", "status":"ok", - "data":"10" + "data":{"HTTP":"3","STREAM":"0"} } ``` * `cmd` Id of requested command, should be `510` * `status` status of command, should be `ok` -* `data` content of response, here the current timeout +* `data` content of response, here the current timeouts - plain text format ```Text -10 +HTTP=3 STREAM=0 ``` +++ @@ -3173,6 +3198,64 @@ the admin password if authentication is enabled 115200 ``` ++++ +archetype = "section" +title = "[ESP902]" +weight = 800 ++++ +Set USB host (OTG) baudrate, used when printer is connected to ESP USB port +Only available on ESP32 S2/S3 built with `USB_SERIAL_FEATURE`, applied at next boot + +## Input +`[ESP902] json= pwd=` + +* json=no +the output format + +* baudrate + * if baudrate is empty, it will display current baudrate + * if baudrate is not empty, it will set the baudrate + currently only these baudrates are supported: + - 9600 + - 19200 + - 38400 + - 57600 + - 74880 + - 115200 + - 230400 + - 250000 + - 500000 + - 921600 + - 1000000 + - 1958400 + - 2000000 + +* pwd= +the admin password if authentication is enabled + + +## Output + +- In json format + +```json +{ + "cmd":"902", + "status":"ok", + "data":"115200" +} +``` + +* `cmd` Id of requested command, should be `902` +* `status` status of command, should be `ok` +* `data` content of response, here the current baudrate + + - plain text format + +```Text +115200 +``` + +++ archetype = "section" title = "[ESP910]" @@ -3370,6 +3453,54 @@ the admin password if authentication is enabled ENABLED - Connected ``` ++++ +archetype = "section" +title = "[ESP950]" +weight = 800 ++++ +Set printer output: serial (UART) or USB host (OTG, printer connected to ESP USB port) +Only available on ESP32 S2/S3 built with `USB_SERIAL_FEATURE`, applied at next boot +Not related to native USB CDC client ([ESP935]) + +## Input +`[ESP950] json= pwd=` + +* json=no +the output format + +* output + * if output is empty, it will display current output + * if output is not empty, it will set the output + currently only these outputs are supported: + - SERIAL + - USB-OTG (`USB` is still accepted as alias) + +* pwd= +the admin password if authentication is enabled + + +## Output + +- In json format + +```json +{ + "cmd":"950", + "status":"ok", + "data":"SERIAL" +} +``` + +* `cmd` Id of requested command, should be `950` +* `status` status of command, should be `ok` +* `data` content of response, here the current output + + - plain text format + +```Text +SERIAL +``` + +++ archetype = "section" title = "[ESP999]" diff --git "a/docs/ongoing_reflection/ESP3D API Key Authentication \342\200\224 Design Spec.md" "b/docs/ongoing_reflection/ESP3D API Key Authentication \342\200\224 Design Spec.md" new file mode 100644 index 00000000..87495959 --- /dev/null +++ "b/docs/ongoing_reflection/ESP3D API Key Authentication \342\200\224 Design Spec.md" @@ -0,0 +1,221 @@ +# ESP3D API Key Authentication — Design Spec + +Oct 27, 2026 · @Luc LEBOSSE + +**Target release:** ESP3D-X `2.0.0a15` (see [release_plan.md](../roadmap/release_plan.md)). Not started: a14 is frozen to tests and bug fixes. + +## Overview + +ESP3D will accept an API key as an alternative to the user/password pair, at the same two levels (admin, user). The key is derived from the level's password and a random per-device secret, so nothing new is stored except that secret, and the key reveals neither the password nor the secret. Over the network, the key is accepted only on HTTPS. + +Scope: ESP32-family targets only. + +- **ESP3D-X** (ESP-IDF) implements it first: it is today the only firmware with an HTTPS server, which comes with its Brotli implementation. +- **ESP3D** and **ESP3DLib** on ESP32 follow once they have HTTPS (and Brotli), either through Espressif's `esp_https_server` or by reusing the ESP3D-X code. +- **ESP8266 is out of scope**: not enough RAM for a TLS server, and ESP3D has no HTTPS server there. + +Algorithm, formats and command behaviour must be identical on all targets, so a client works unchanged with any of them. + +Why add it: + +- Tools such as slicers, Home Assistant and scripts send one header per request, with no login flow or session cookie. +- A leaked key does not expose the password, and can be revoked without changing it. +- Slicers already speak this pattern: PrusaSlicer and OrcaSlicer send `X-Api-Key` to OctoPrint-type hosts. + +Out of scope: ESP8266, per-client keys, scoped permissions finer than admin/user, and OctoPrint API emulation (a possible follow-up). + +## Background + +An API key is a long secret the client sends with every request. There is no login step and no session: the server checks the key on each request and grants the level bound to it. + +| Transport | Example | Status | +| --- | --- | --- | +| Standard header | `Authorization: Bearer ` | Preferred, defined by RFC 6750 | +| Custom header | `X-Api-Key: ` | De facto standard (OctoPrint, Moonraker, slicers) | +| Query parameter | `/command?apikey=` | Discouraged: leaks into logs, history and Referer | + +No RFC defines "API key" as such. The rules that apply: + +- **RFC 6750** defines the `Bearer` scheme of the `Authorization` header. +- **RFC 6648** deprecates `X-` header prefixes; `X-Api-Key` is still kept for compatibility. +- **OWASP** (REST Security Cheat Sheet, API Security Top 10): at least 128 bits of entropy from a cryptographic RNG, keys never in URLs, constant-time comparison, keys revocable, transport over HTTPS only. + +On plain HTTP the key would travel in clear to anyone on the LAN. ESP3D therefore applies the OWASP rule strictly: over the network, the key is accepted only on a TLS connection. HTTPS gives confidentiality; the key gives separation from the password and revocability. + +## Design choice + +The key is an HMAC-SHA256 of the level's password, keyed with a random secret that never leaves the device. This was chosen over three alternatives: + +| Option | Formula | Verdict | Reason | +| --- | --- | --- | --- | +| Naive hash | `SHA256(user:password)` | Rejected | Not reversible, but brute-forceable offline: a GPU tests billions of guesses per second, and typical device passwords fall in seconds. The same key appears on every device with the same password. | +| MAC address as salt | `HMAC(MAC, user:password)` | Rejected | The MAC is public: sent in clear in every Wi-Fi frame, visible via ARP, printed on labels, shown by ESP3D. Only 24 bits after the Espressif OUI. It adds uniqueness, not secrecy. | +| Random stored key | `key = random(32)` | Not chosen | Strongest per-key revocation, but adds a stored value per level, and a password change does not invalidate it. | +| **Derived key (chosen)** | `HMAC(device_secret, level:password)` | **Chosen** | Cannot be brute-forced without the secret. Unique per device. Revoked by a password change or a secret regeneration. Only one value to store. | + +Accepted trade-off: keys cannot be revoked one by one (for example "the slicer's" without "Home Assistant's"). With one key per level, that is acceptable for ESP3D. + +## Device secret lifecycle + +The device secret is 32 random bytes, generated once on the device and stored in settings. It is never returned by any command, API or WebUI page. + +**Generation.** At authentication service start, if the stored secret is empty, generate it and store it before computing any key. This happens on every boot path, whatever the network state (Wi-Fi, Ethernet, Bluetooth only, or no network at all), so commands over serial can use a key on a device that never had Wi-Fi. + +**Entropy.** The hardware RNG only gives true randomness when an entropy source is running. The generator must ensure one is: + +| Platform | RNG call | Radio running | Radio not running | +| --- | --- | --- | --- | +| ESP3D / ESP3DLib, ESP32 (Arduino core) | `esp_random()` / `esp_fill_random()` | Use directly | Wrap in `bootloader_random_enable()` / `bootloader_random_disable()` (ADC noise source) | +| ESP3D-X, ESP32 family (ESP-IDF) | `esp_fill_random()` | Use directly | Same wrapper, from `bootloader_random.h` | + +The `bootloader_random_enable()` wrapper must not run while Wi-Fi, Bluetooth or the SAR ADC are in use: call it before they start, or skip it when the radio is already up. + +**Storage.** One setting holding the 32 bytes (raw, or 64 hex characters if the settings layer only stores strings). Default value: empty. + +**Factory reset.** Resets the setting to empty, so all previous keys are invalid. The next service start generates a fresh secret. No special code is needed in the reset path. + +**Regeneration.** An admin-only command overwrites the secret with a new random value and recomputes the keys. All existing keys become invalid; passwords are unchanged. + +[embedded content: device secret and key lifecycle\] + +Only the secret touches flash. A password change recomputes one key; REGENERATE or a factory reset replaces the secret and invalidates both keys. + +## Key derivation and verification + +Each level has exactly one key, computed in RAM from the secret and that level's password: + +```latex +\text{key}_{level} = \text{hex}\big(\text{HMAC-SHA256}(\text{device\_secret},\ \texttt{"esp3d-apikey-v1:"} \,\|\, level \,\|\, \texttt{":"} \,\|\, password_{level})\big) +``` + +- `level` is the literal string `admin` or `user`. +- The `esp3d-apikey-v1:` prefix separates this use of the secret from any future one and allows a new version without ambiguity. +- Output: 64 lowercase hex characters (256 bits). Clients send it exactly as displayed. +- If a level's password is empty, that level has no key: it cannot be derived or used. + +**RAM cache.** The service holds `adminKey` and `userKey` in RAM. They are recomputed on: + +1. Service start, after the secret is loaded or generated. +2. A change of the admin or user password. +3. Secret regeneration. +4. Factory reset (via the next service start). + +One HMAC-SHA256 takes about a millisecond or less on ESP32, so recomputation cost does not matter. + +**Verification.** For each request or command carrying a key: + +1. Reject if the length is not 64. +2. Compare against `adminKey`, then `userKey`, each with a constant-time comparison over the full 64 bytes (no early exit). +3. On a match, grant that level. On no match, the result is `guest`, exactly like a wrong password today; the caller returns its usual 401 or error. + +If a request carries several credentials (key, Basic auth, session cookie), the highest level obtained wins, consistent with the current behaviour. + +## Transport + +The key is accepted wherever a password is accepted today, plus two HTTP headers. + +| Channel | How the key is sent | Notes | +| --- | --- | --- | +| HTTPS | `Authorization: Bearer ` | RFC 6750 form. Coexists with Basic/Digest on the same header: dispatch on the scheme word. | +| HTTPS | `X-Api-Key: ` | For slicers and tools that expect the OctoPrint convention. | +| ESP commands over HTTPS `/command` or secure WebSocket (`wss`) | `[ESPxxx] ... pwd=` | Same TLS connection. | +| ESP commands over serial or Bluetooth | `[ESPxxx] ... pwd=` | Local link, no network exposure. Works even if the device never had Wi-Fi. | +| Plain HTTP, `ws`, Telnet, FTP | Refused | A key received there is ignored (result: guest, so the usual 401 or error). The password keeps working as today. | +| Query string `?apikey=` | Not supported | See open questions (snapshot embeds). | + +Rules: + +- The TLS check is made on the connection that reached the device, never on a header such as `X-Forwarded-Proto`. +- Key-authenticated HTTP requests are stateless: no session is created and no `ESPSESSIONID` cookie is set. +- The header names are matched case-insensitively; the `Bearer` scheme word too (RFC 7235). +- The key is never echoed in a response, a log line or an error message. Debug logs may print only that a key was present, the channel, and the resulting level. + +## Management command and settings + +One new command, proposed as **`[ESP560]`**: it sits next to the authentication commands (`ESP500` status, `ESP510` session timeout, `ESP550` admin password, `ESP555` user password) and is free in ESP3D 3.1. + +| Syntax | Required level | Effect | +| --- | --- | --- | +| `[ESP560] pwd=` | user or admin | Returns the key of the caller's level. A user never sees the admin key. | +| `[ESP560]REGENERATE pwd=` | admin | Generates a new device secret, recomputes both keys, returns the new key of the caller's level. All previous keys become invalid. | + +- `json=yes` returns the usual envelope: `{"cmd":"560","status":"ok","data":""}`. +- If the caller's level has no key (empty password), the command returns an error, not an empty key. +- If authentication is not compiled in, the command returns an error: there is nothing to protect. + +**Setting.** One new setting, for example `ESP_API_SECRET`: + +- 32 bytes, default empty, hidden: not listed by `[ESP400]`, not readable or writable through `[ESP401]`. +- Excluded from settings export and import. Restoring it on another device would clone its keys. +- Changing `ESP550` or `ESP555` must trigger the key recompute. + +**WebUI.** In the security pane: + +- show the current user's key with a copy button; +- for admin, a Regenerate button with a confirmation that all integrations using a key will stop working; +- a note that changing a password also changes that level's key. + +## Platform implementation notes + +The algorithm, key format and command behaviour are shared; only these building blocks differ. + +| Building block | ESP3D / ESP3DLib, ESP32 (Arduino) | ESP3D-X (ESP-IDF) | +| --- | --- | --- | +| HTTPS server | Not yet: will come with Brotli, via `esp_https_server` or the ESP3D-X code | `esp_https_server`, implemented together with Brotli | +| Is this request on TLS? | Requests served by the HTTPS instance of the chosen server | Requests served by the HTTPS `httpd` instance, separate from any plain one | +| Random bytes | `esp_fill_random()` + `bootloader_random_*` wrapper | `esp_fill_random()` + `bootloader_random_*` wrapper | +| HMAC-SHA256 | mbedTLS: `mbedtls_md_hmac()` with `MBEDTLS_MD_SHA256` | mbedTLS: `mbedtls_md_hmac()` | +| Secret storage | NVS via the settings layer | NVS blob (`nvs_set_blob`) | +| Read headers | Depends on the chosen server | `httpd_req_get_hdr_value_str()` | +| Constant-time compare | Own helper (XOR accumulate over all bytes) | Same, or `mbedtls_ct_memcmp()` | + +**ESP3D / ESP3DLib entry points, once HTTPS exists.** Current code locations, to be adapted to the HTTPS server chosen: + +- authentication\_service.cpp:52 `getAuthenticatedLevel()`: add the key check on the `pwd` path (commands) and on the HTTP path next to the existing `Authorization` handling (lines 72-81), dispatching on `Bearer` before calling `_webserver->authenticate()`. +- http\_server.cpp:244: add `X-Api-Key` to the collected header list. +- `AuthenticationService::begin()`: load or generate the secret, then compute both keys. +- The `ESP550` and `ESP555` handlers: call the recompute after a successful password change. +- Keep `isadmin()` / `isuser()` password-only. They are also used by FTP and `/login` (FtpServer.cpp:356, handle-login.cpp:62); add a separate key check so accepting a key there is an explicit decision. + +**ESP3D-X (ESP-IDF), reference implementation.** Same structure in its authentication component. Check the key only on requests served by the HTTPS server instance. Call `bootloader_random_enable()` only when Wi-Fi and Bluetooth are not started, which is the case early in boot. Declare the `bootloader_support` and `mbedtls` components in `PRIV_REQUIRES`. + +**Shared test vectors.** Both firmwares must produce these keys. Secret = the 32 bytes `0x00, 0x01, …, 0x1f`; computed with Python `hmac` + `hashlib.sha256`. + +| Level | Password | HMAC message | Expected key | +| --- | --- | --- | --- | +| admin | `admin` | `esp3d-apikey-v1:admin:admin` | `6e69111772d35dcec2a2e87905ccee28705e807434d338e3116c05e949ca353e` | +| user | `user` | `esp3d-apikey-v1:user:user` | `3a378df2c0a7f8a198f62727302ec8d1518405ac1b2d2b2c1b9fa1d956fe2d06` | + +## Security, tests and open questions + +**Limitations accepted.** + +- HTTPS required: no key over the network until a target has an HTTPS server (ESP3D / ESP3DLib today), and never on ESP8266. +- Self-signed certificate: unless clients trust or pin the device certificate, TLS stops passive sniffing but not an active man-in-the-middle. +- A key is a bearer credential: whoever holds it has its level until the password changes or the secret is regenerated. +- No per-client revocation and no finer scopes than admin/user. +- An attacker who reads the flash gets the secret and the passwords anyway; this design does not protect against physical access. + +**Test plan.** + +- [ ] Test vectors above match on ESP3D-X and, later, on ESP3D / ESP3DLib (ESP32). +- [ ] Fresh flash, no network configured: secret is generated at first boot and `[ESP560]` over serial returns a key. +- [ ] Admin key over HTTPS `Authorization: Bearer` and over `X-Api-Key` gives admin; user key gives user; wrong or truncated key gives guest (401). +- [ ] A valid key over plain HTTP, `ws`, Telnet or FTP gives guest; the same key over HTTPS gives its level. +- [ ] Key in `pwd=` works on serial, Bluetooth, `wss` and HTTPS `/command`. +- [ ] Changing `ESP550` invalidates the old admin key only; changing `ESP555` invalidates the old user key only. +- [ ] `[ESP560]REGENERATE` invalidates both keys; it is refused at user level. +- [ ] Factory reset invalidates both keys and a new secret appears at next boot. +- [ ] Secret never appears in `[ESP400]`, settings export, logs or any response. +- [ ] Two devices with identical passwords produce different keys. +- [ ] Key requests create no session cookie. + +**Open questions.** + +- [ ] ESP3D / ESP3DLib: `esp_https_server` directly, or reuse of the ESP3D-X HTTPS + Brotli code? +- [ ] Certificate: self-signed and generated on the device, or uploaded by the user? How do slicers handle a self-signed certificate? +- [ ] When both HTTP and HTTPS run, should `[ESP560]` itself be refused over plain HTTP, so the key is never displayed in clear? +- [ ] Is `ESP560` free in ESP3D-X as well? +- [ ] Snapshot embeds (`/snap` in an ``) cannot send headers: allow `?apikey=` over HTTPS behind a build option, or not at all? +- [ ] Key prefix (for example `e3d_`) so secret scanners can detect leaked keys? +- [ ] Follow-up: OctoPrint-compatible upload endpoint (`/api/files/local`) for direct upload from slicers. diff --git a/docs/ongoing_reflection/arduino_to_idf_porting_analysis.md b/docs/ongoing_reflection/arduino_to_idf_porting_analysis.md new file mode 100644 index 00000000..b0730429 --- /dev/null +++ b/docs/ongoing_reflection/arduino_to_idf_porting_analysis.md @@ -0,0 +1,353 @@ +# ESP3D Arduino → ESP3D-X IDF: porting analysis + +> Generated: 2026-05-29 +> Source: ESP3D Arduino (`ESP3D/esp3d/`) vs ESP3D-X IDF (`Luc-ESP3D-X/`) +> Out of scope: ESP8266 / ESP8285 (separate architecture, not targeted) + +--- + +## 1. Chip coverage + +| SoC | Arduino ESP3D | IDF ESP3D-X | Notes | +|-----|:---:|:---:|---| +| ESP32 (classic) | ✅ | ✅ | PiBot V1 (`pibot_pendant_v1_0` board) | +| ESP32-S2 | ✅ | ❌ | Native USB CDC; missing from IDF | +| ESP32-S3 | ✅ | ✅ | `ESP32_S3_WROOM_CAM`, `FYSETC_WIFI_PRO` boards | +| ESP32-C3 | ✅ | ✅ | `ESP32_C3_BARE` board | +| ESP32-C6 | ❓ partial | ❌ | Depends on Arduino version used | +| ESP32-H2 | ❌ | ❌ | BLE 5 only, no WiFi | + +**Priority missing chip: ESP32-S2** — the only SoC with native USB CDC absent from IDF. + +--- + +## 2. Features — porting status + +### 2.1 Ported features ✅ + +| Arduino feature | IDF CMake | Notes | +|---|---|---| +| `WIFI_FEATURE` | `WIFI_SERVICE` | | +| `BLUETOOTH_FEATURE` (SPP) | `BT_SERVICE` (SPP + **BLE GATT**) | Extended: BLE absent in Arduino | +| `HTTP_FEATURE` | `WEB_SERVICES` / `WEBUI_SERVER` | | +| `WS_DATA_FEATURE` | `WS_SERVER_SERVICE` | opt, default OFF on PiBot | +| `MDNS_FEATURE` | `MDNS_SERVICE` | Enhanced: `_device-info` TXT records | +| `SSDP_FEATURE` | `SSDP_SERVICE` | | +| `NOTIFICATION_FEATURE` | `NOTIFICATIONS_SERVICE` | Email, Pushover, IFTTT, Telegram, HA, WhatsApp | +| `FILESYSTEM_FEATURE` | LittleFS + `USE_FAT_INSTEAD_OF_LITTLEFS` | | +| `SD_DEVICE_CONNECTION` | `SD_CARD_SERVICE` + `SD_SHARED_SERVICE` | | +| `GLOBAL_FILESYSTEM_FEATURE` | GlobalFS (WebDAV union) | | +| `WEBDAV_FEATURE` | `WEBDAV_SERVICES` | | +| `WEB_UPDATE_FEATURE` + `OTA_FEATURE` + `SD_UPDATE_FEATURE` | `UPDATE_SERVICE` (unified) | | +| `AUTHENTICATION_FEATURE` | `ESP3D_AUTHENTICATION` | HTTP session management | +| `GCODE_HOST_FEATURE` | `gcode_host/` | ✅ In progress — ACK/resend state machine | +| `ESP_LUA_INTERPRETER_FEATURE` | `LUA_INTERPRETER_SERVICE` | Native Lua 5.4 (Arduino used Lua 5.3) | +| `SENSOR_DEVICE` | `SENSOR_SERVICE` (DHT/BMP280/Analog) | | +| `BUZZER_DEVICE` | `BUZZER_SERVICE` | | +| `CAMERA_DEVICE` | `CAMERA_SERVICE` | opt, requires S3+PSRAM | +| `USB_SERIAL_FEATURE` | `USB_SERIAL_SERVICE` | opt, native USB MCU (S3/S2) | +| `DISPLAY_DEVICE` (OLED) | Full TFT/LVGL multi-resolution | Far beyond original: LVGL, multi-SKU | +| `TELNET_FEATURE` | `SOCKET_SERVER_SERVICE` | ⚠️ Renamed — raw TCP socket = functional telnet | +| `PIN_RESET_FEATURE` | *(recovery — to implement)* | See §4.5 | +| `TIME_SERVICE` / NTP | `TIME_SERVICE` | Partial: timezone edge cases, HW RTC missing | + +### 2.2 Missing features ❌ + +| Arduino feature | IDF status | Related commands | +|---|---|---| +| `ETH_FEATURE` | ❌ Not targeted on V1 hardware | ESP116, ESP117, ESP118 | +| `CAPTIVE_PORTAL_FEATURE` | ❌ Not ported | *(no dedicated command)* | +| `FILESYSTEM_TIMESTAMP_FEATURE` | ❌ Not ported | — | +| `SD_TIMESTAMP_FEATURE` | ❌ Not ported | — | +| `DIRECT_PIN_FEATURE` | ❌ Not ported | ESP201 | +| `ESP_ACCESS_CONTROL_ALLOW_ORIGIN` (CORS) | ❌ Not ported | *(HTTP config)* | +| `ESP_GOT_IP_HOOK` | ❌ No explicit hook | ESP212 (printer side) | +| `ESP_GOT_DATE_TIME_HOOK` | ❌ No explicit hook | — | +| `ESP_AUTOSTART_SCRIPT` | 📋 Planned (backlog §9) | `ESP3D_LUA_AUTOSTART_SCRIPT` | +| `PRINTER_HAS_DISPLAY` | 🚫 N/A for pendant — **required for full Arduino port** | ESP212 | +| `OLED` (`DISPLAY_DEVICE OLED_*`) | ❌ Not ported (matrix `—`) | — | +| `PIN_RESET_FEATURE` *(recovery)* | ❌ Not ported (matrix `—`) | — | + +### 2.3 Intentionally not ported 🚫 + +| Arduino feature | IDF decision | Reason | +|---|---|---| +| `FTP_FEATURE` | Not planned | Superseded by WebDAV + WS data channel | +| `COMMUNICATION_PROTOCOL MKS_SERIAL` | Not targeted | MakerBase protocol, out of pendant scope | +| `ESP_SERIAL_BRIDGE_OUTPUT` — **Serial bridge** | Not targeted | Bridges two physical UARTs (main ↔ secondary); pendant does not expose a secondary UART for bridging (ESP930, ESP931) | +| `serial2socket` module | ⏳ Undetermined — see §2.5 | Used by **ESP3DLib** (ESP3D embedded inside another firmware e.g. Marlin); not a standalone feature | + +### 2.4 New features in IDF (absent from Arduino) + +| IDF feature | Description | +|---|---| +| `BT_SERVICE` BLE GATT | Bluetooth Low Energy in addition to classic SPP | +| `WS_CLIENT_SERVICE` | Outgoing WebSocket **client** toward FluidNC/grblHAL | +| Hardware inputs (encoder, buttons, switch, pot) | Full physical input system | +| `TFT_BRIGHTNESS_CONTROL` | PWM backlight control | +| `UART_EXT_SERVICE` | Second external UART | +| Multiple CNC targets | FluidNC (default), grblHAL, GRBL, Marlin, Repetier, Smoothieware | +| LVGL multi-resolution | 320×240, 480×272, 480×320, 800×480 | +| `HTTPS_SERVICE` | TLS over HTTP (requires PSRAM) | +| `SENSOR_ANALOG` | Analog sensor (absent from Arduino sensor module) | + +### 2.5 ESP3DLib — undetermined use case + +**ESP3DLib** is an Arduino library variant of ESP3D designed to be **embedded inside another firmware** (e.g. Marlin, Repetier) rather than running as a standalone application. In this mode, the host firmware retains control of the main loop and serial port; ESP3D runs as a subsystem alongside it. The `serial2socket` module exists specifically to bridge the host firmware's serial stream to the TCP layer in this embedded context. + +The IDF equivalent would be **"ESP3D-X as an IDF component"** — embedding the ESP3D-X subsystem into a larger IDF project (e.g. a CNC controller firmware that also hosts a WiFi/WebUI stack). This is technically possible with ESP-IDF's component model (`idf_component.yml`), but the approach has **not yet been evaluated** for ESP3D-X. + +**Open questions:** +- Is there a concrete need for an IDF component variant (which host firmware would consume it)? +- Would the IDF component expose the same `serial2socket`-style bridge, or a different API? +- Memory budget: embedding ESP3D-X alongside a full CNC firmware on an ESP32 without PSRAM is likely infeasible; S3+PSRAM is probably the minimum viable target. + +**Status: ⏳ Not yet decided** — track this separately once a target host firmware is identified. + +--- + +## 3. ESP commands — comparison + +### 3.1 Present in Arduino, missing in IDF + +| Command | Function | Feature | IDF status | +|---|---|---|---| +| `ESP116` | ETH STA IP config (DHCP/STATIC) | `ETH_FEATURE` | 🚫 Not targeted | +| `ESP117` | ETH STA IP/Mask/GW | `ETH_FEATURE` | 🚫 Not targeted | +| `ESP118` | ETH fallback mode (BT/WIFI-SETUP/OFF) | `ETH_FEATURE` | 🚫 Not targeted | +| `ESP150` | Boot delay + verbose boot | none | ❌ To implement | +| `ESP161` | WebSocket `/wsdata` port | `WS_DATA_FEATURE` | ❓ Is port configurable? | +| `ESP180` | FTP state (ON/OFF/CLOSE) | `FTP_FEATURE` | 🚫 Intentional decision | +| `ESP181` | FTP ports | `FTP_FEATURE` | 🚫 Intentional decision | +| `ESP191` | WebDAV port | `WEBDAV_FEATURE` | ❓ Is port configurable? | +| `ESP201` | Get/Set GPIO pin value | `DIRECT_PIN_FEATURE` | ❌ To implement | +| `ESP212` | Output to printer screen | `PRINTER_HAS_DISPLAY` | 🚫 N/A pendant / required for full port | +| `ESP215` | Touch calibration | `DISPLAY_DEVICE` + touch | ❓ Different approach in LVGL? | +| `ESP220` | Display pin definitions | none | ❌ To implement | +| `ESP620` | Notification via encoded URL | `NOTIFICATION_FEATURE` | ❓ Covered by ESP610? | +| `ESP715` | Format SD card | `SD_DEVICE` | ❌ To implement | +| `ESP930` | Serial bridge state (ON/OFF/CLOSE) | `ESP_SERIAL_BRIDGE_OUTPUT` | 🚫 Not targeted | +| `ESP931` | Serial bridge baudrate | `ESP_SERIAL_BRIDGE_OUTPUT` | 🚫 Not targeted | +| `ESP999` | Quiet boot (strapping pin) | ESP32-S2/S3/C3 | ❓ Relevant for S3/C3 builds | + +### 3.2 Present in IDF, absent from Arduino (new commands) + +| IDF command | Likely description | +|---|---| +| `ESP132` | IDF-specific setting | +| `ESP133` | IDF-specific setting | +| `ESP134` | IDF-specific setting | +| `ESP135` | IDF-specific setting | +| `ESP216` | IDF-specific network service | +| `ESP270` | CNC/pendant specific | +| `ESP280` | CNC/pendant specific | +| `ESP281` | CNC/pendant specific | +| `ESP300` | Lua: execute script | +| `ESP301` | Lua: interpreter state | +| `ESP455` | UI/TFT specific | +| `ESP460` | UI/TFT specific | +| `ESP702` | Filesystem specific | + +--- + +## 4. Work items by missing feature + +Each section lists: CMake option, ESP commands, NVS settings, and integration points. + +--- + +### 4.1 `DIRECT_PIN_FEATURE` — Direct GPIO control + +**Use case:** direct read/write of a GPIO pin via command. Required for Lua macros and GPIO automation. + +**To do:** +- [ ] CMake: add `DIRECT_PIN_FEATURE` option in `CMakeLists.txt` and `cmake/features.cmake` +- [ ] Command: implement `main/core/commands/esp201.cpp` + - `[ESP201]` → GET: return state of all defined pins + - `[ESP201] P= V=<0|1>` → SET: force pin value + - `[ESP201] P= PULLUP=<0|1> MODE=` → pin configuration +- [ ] Safety: define allowed pin list in BSP (`board_config.cmake`) to avoid conflicts with LVGL/SPI/I2C +- [ ] Sanity check: exclude reserved pins (SD, TFT SPI, encoder, etc.) + +--- + +### 4.2 `CAPTIVE_PORTAL_FEATURE` — Captive portal in AP mode + +**Use case:** automatic redirect to WebUI when a device connects to the ESP3D-X access point. +**Active only in WiFi AP mode** — must not start in STA mode or when WiFi is off. + +**To do:** +- [ ] CMake: add `CAPTIVE_PORTAL_SERVICE` option (depends on `WIFI_SERVICE` + `WEB_SERVICES`; runtime guard: AP mode only) + - Without `WEB_SERVICES` the DNS redirect reaches the AP IP but the HTTP connection is refused — the OS cannot detect the portal and the user gets an error +- [ ] Create `main/modules/captive_portal/esp3d_captive_portal.cpp/.h` + - Minimal UDP DNS server on port 53: respond to all queries with the AP IP (A record, TTL 0) + - Static 256 B buffer — no dynamic allocation + - Dedicated FreeRTOS task (~2 KB stack) +- [ ] Start/stop tied strictly to AP mode events in `main/modules/wifi/esp3d_wifi_ap.cpp`: + - `WIFI_EVENT_AP_START` → `esp3dCaptivePortal.start(ap_ip)` + - `WIFI_EVENT_AP_STOP` → `esp3dCaptivePortal.stop()` + - **Never start in STA mode** +- [ ] HTTP catch-all handler in `main/modules/http/`: return `302 → http:///` for any unknown URI +- [ ] No dedicated ESP command — activated automatically when AP mode starts +- [ ] Sanity check: requires `WIFI_SERVICE=ON` + `WEB_SERVICES=ON` + WiFi configured in AP or STA+AP mode at runtime — must not compile if either `WIFI_SERVICE` or `WEB_SERVICES` is OFF; must not start outside AP mode; disable if `SOCKET_CLIENT_SERVICE=ON` (memory pressure, and `WEB_SERVICES` is already forbidden with it) +- [ ] Reference: `$IDF_PATH/examples/protocols/http_server/captive_portal/` as implementation base + +--- + +### 4.3 File timestamps — `FILESYSTEM_TIMESTAMP_FEATURE` / `SD_TIMESTAMP_FEATURE` + +**Use case:** timestamp files created/modified on flash and SD card using NTP time. + +**To do:** +- [ ] CMake: add `FILESYSTEM_TIMESTAMP_FEATURE` and `SD_TIMESTAMP_FEATURE` (depend on `TIME_SERVICE`) +- [ ] Integration in `main/modules/filesystem/`: LittleFS timestamp callback or VFS hook +- [ ] Integration in `main/modules/filesystem/` SD: `ff_diskio_t` timestamp callback +- [ ] Implicit dependency: enable `TIMESTAMP_FEATURE` if either is ON (mirrors Arduino `sanity.h` logic) +- [ ] No dedicated ESP commands needed (transparent to the user) + +--- + +### 4.4 Event hooks — `ESP_GOT_IP_HOOK` / `ESP_GOT_DATE_TIME_HOOK` + +**Use case:** automatically execute a G-code or ESP command when the IP is obtained or NTP time is synchronized. + +**To do:** +- [ ] NVS settings: add `ESP_GOT_IP_HOOK` and `ESP_GOT_DATE_TIME_HOOK` as configurable string settings in `esp3d_settings.h` +- [ ] IP hook: call the command dispatcher from `esp3d_wifi_sta.cpp` on `IP_EVENT_STA_GOT_IP` +- [ ] DateTime hook: call the dispatcher from `main/modules/time/` once NTP is synchronized +- [ ] Settings: add corresponding NVS IDs in `esp3d_settings.h` +- [ ] Configuration interface: settings screen or dedicated ESP commands + +--- + +### 4.5 `PIN_RESET_FEATURE` — Settings reset via physical pin (recovery) + +**Use case:** holding a pin LOW for more than 1 s at boot clears all NVS settings (factory reset). + +**To do:** +- [ ] CMake: add `PIN_RESET_FEATURE` option in `CMakeLists.txt` +- [ ] BSP: add `ESP3D_RESET_PIN` in `board_config.cmake` (`-1` = disabled) +- [ ] Implement in `main/core/esp3d_x.cpp` or `main/main.cpp`: read pin at boot before NVS init +- [ ] Logic: if pin is LOW for > 1 s → erase NVS → reboot +- [ ] Optional: buzzer feedback + log output + +--- + +### 4.6 `ESP150` — Boot delay + verbose boot + +**Use case:** configurable startup delay (give the printer time to boot), verbose console mode. + +**To do:** +- [ ] NVS setting: `BOOT_DELAY_MS` (0 = disabled) +- [ ] Command: implement `main/core/commands/esp150.cpp` + - `[ESP150]` → GET: display current delay + - `[ESP150] T=` → SET: configure delay + - `[ESP150] V=<0|1>` → SET: enable/disable verbose boot +- [ ] Integration: add pause in `ESP3DX::begin()` if setting > 0 + +--- + +### 4.7 `ESP715` — Format SD card + +**Use case:** format the SD card as FAT32 from an ESP command. + +**To do:** +- [ ] Command: implement `main/core/commands/esp715.cpp` + - `[ESP715]` → format SD partition as FAT32 + - Protection: SD must be mounted; require `FORMAT=YES` confirmation +- [ ] Integration with `SD_CARD_SERVICE`: unmount, format, remount +- [ ] Response: progress feedback / confirmation + +--- + +### 4.8 `ESP220` — Display pin definitions + +**Use case:** return the list of pins configured for the current board (debug, documentation). + +**To do:** +- [ ] Command: implement `main/core/commands/esp220.cpp` + - `[ESP220]` → list all pins defined in the active BSP +- [ ] Read `#define` values from `board_config.cmake` → generated in `esp3d_board_config.h` + +--- + +### 4.9 `PRINTER_HAS_DISPLAY` + `ESP212` — Full Arduino port (non-pendant use case) + +> This feature is **not applicable** for the PiBot pendant, but **required** if ESP3D-X IDF is meant to cover the classic Arduino use case (ESP3D as serial bridge for printers with their own display). + +**To do (full Arduino port):** +- [ ] CMake: add `PRINTER_HAS_DISPLAY` option +- [ ] Command: implement `main/core/commands/esp212.cpp` + - `[ESP212] ` → send message to the printer screen via UART +- [ ] Integration: dispatch to the active transport client (serial / BT / socket) +- [ ] Hook: `ESP_GOT_IP_HOOK` typically points to `[ESP212]IP:%ESP_IP%` + +--- + +### 4.10 ESP32-S2 board support + +**Use case:** native USB CDC on S2 without an external UART chip; boards: ESP32-S2-Saola, etc. + +**To do:** +- [ ] Create `boards/esp32_s2_bare/` with `board_config.cmake` (USB D+/D- pins) +- [ ] Enable `USB_SERIAL_SERVICE` on S2 (already conditional in code) +- [ ] Verify S2 memory constraints (320 KB DRAM, no PSRAM on low-end boards) +- [ ] Build script `boards/esp32_s2_bare/build_scripts/variants.py` +- [ ] Sanity check: no Bluetooth on S2 (no BT controller) + +--- + +### 4.11 `ESP999` — Quiet boot (strapping pin) + +**Use case:** suppress bootloader log output when the strapping pin is HIGH at boot (S2/S3/C3). + +**To do:** +- [ ] Command: implement `main/core/commands/esp999.cpp` + - `[ESP999]` → GET: current quiet boot state + - `[ESP999] V=<0|1>` → SET: enable/disable +- [ ] Conditional: `#if defined(CONFIG_IDF_TARGET_ESP32S3) || defined(CONFIG_IDF_TARGET_ESP32C3)` +- [ ] Mechanism: write via `esp_efuse_set_rom_log_scheme()` or equivalent + +--- + +### 4.12 Items requiring verification (❓ commands) + +These need a code check in IDF before deciding whether they are missing or already covered: + +| Item | Question | Files to check | +|---|---|---| +| `ESP161` WS port | Is the `/wsdata` port configurable in IDF? | `esp3d_settings.h`, `esp161.cpp` absent → create? | +| `ESP191` WebDAV port | Is the WebDAV port hardcoded or in NVS? | `esp3d_settings.h`, WebDAV handler | +| `ESP620` notification URL | Does `ESP610` cover encoded-URL notification? | `esp610.cpp` vs Arduino `ESP620.cpp` | +| `ESP215` touch calib | Is LVGL touch calibration already in IDF? | `display/`, touch driver, settings | +| CORS HTTP | Is CORS handled in the HTTP handler? | `main/modules/http/` | + +--- + +## 5. Priority summary + +### High priority (missing functionality with significant impact) +1. ~~**`GCODE_HOST_FEATURE`**~~ — ✅ In progress +2. **`CAPTIVE_PORTAL_FEATURE`** — AP mode UX severely degraded without it +3. **`PIN_RESET_FEATURE`** (recovery) — field safety and maintenance +4. **`DIRECT_PIN_FEATURE`** / `ESP201` — required for Lua GPIO macros +5. **File timestamps** — expected by users migrating from Arduino + +### Medium priority (improvement or comfort) +6. **Event hooks** (`ESP_GOT_IP_HOOK`, `ESP_GOT_DATE_TIME_HOOK`) — expected Arduino behavior +7. **`ESP150`** — boot delay, useful for compatibility with slow-starting printers +8. **`ESP715`** — SD format, common maintenance operation +9. **`ESP220`** — pin display, helps debugging +10. **Verify `ESP161`, `ESP191`, `ESP620`, `ESP215`** — resolve the ❓ items + +### Low priority (not targeted or non-blocking) +11. **ESP32-S2 board** — only if an S2 board is targeted +12. **`PRINTER_HAS_DISPLAY` / `ESP212`** — only if a full Arduino port is planned +13. **`ESP999`** — quiet boot, comfort for S3/C3 builds +14. **CORS (`ESP_ACCESS_CONTROL_ALLOW_ORIGIN`)** — cross-origin camera use case + +### Definitive decisions (do not implement) +- **FTP** → WebDAV + WebSocket data channel +- **MKS Serial** → not targeted for pendant +- **Serial bridge** → not targeted for pendant +- **Ethernet** → not targeted on V1 hardware (revisit if an Ethernet board is added) diff --git a/docs/ongoing_reflection/esp3d_serial_mux_framing_draft.md b/docs/ongoing_reflection/esp3d_serial_mux_framing_draft.md new file mode 100644 index 00000000..e8bb1d72 --- /dev/null +++ b/docs/ongoing_reflection/esp3d_serial_mux_framing_draft.md @@ -0,0 +1,213 @@ +# ESP3D serial multiplex framing — working draft + +**Status:** working draft — **not** implemented in firmware unless explicitly referenced from code. +**Purpose:** define a **single byte-stream** protocol (UART, Bluetooth SPP, BLE UART bridge, etc.) that can **interleave** interactive **commands** and **file-transfer** messages without an exclusive “file mode” vs “command mode”, while staying safe for **embedded RAM** and **binary-safe** parsing. + +**Related specs:** WebSocket data channel framing and V1 file semantics are defined in [`websockets_protocol_V1_0.md`](../architecture/websockets_protocol_V1_0.md) and [`esp3d_websocket_protocol_v1.md`](esp3d_websocket_protocol_v1.md). This draft **reuses the same file opcodes and payloads** inside a **wrapper** so **both ends** can share one state machine where practical. + +### Symmetric peers (serial has no host / client) + +On UART, Bluetooth SPP, or similar, the link is **fully bidirectional**: there is **no** framing-level **host vs client**, **master vs slave**, or **initiator-only** role. **Either peer** may emit **CMD**, **RSP**, or **FILE** frames at any time (subject to product policy and V1 sequencing). The **same** parse-and-dispatch rules apply **in both directions**. + +*Note:* WebSocket documentation often uses “client” and “server” for the HTTP upgrade; that is **transport history**, not a requirement for serial. On serial, map “who sends **SU** / **SD**” to **your product’s** file-engine rules, not to a wire role. + +### Pure API (receiver interprets) + +The protocol is **pure API at the framing layer**: each frame **delivers** a **CLASS** and **PAYLOAD** to **whoever receives it**. **Meaning, success vs failure, side effects, and replies** are entirely **defined and handled by the consumer** (command interpreter, V1 file engine, UI bridge, etc.). There is **no** mandatory envelope-level **RPC**, **status code**, or **request–response pairing** beyond what **your** handlers and **V1** already define. The sender **does not** rely on the wire for “business outcome”; the receiver **acts on** what it parsed. + +--- + +## 1. Design goals + +| Goal | Rule | +|------|------| +| **One parser** | Every message is a **single outer frame**: fixed header + length + payload. **Text and binary** use the **same** envelope. | +| **Explicit routing** | A **message class** field tells the receiver whether to forward the payload to the **command pipeline** or the **file-transfer (V1) pipeline**. | +| **Pure API** | Framing **only** delivers bytes to the right handler; **interpretation** is **receiver-side** (see above). | +| **Bounded size** | **Maximum outer payload** (application data after the header) is **1536 bytes (1.5 KiB)**. Implementations **must** reject larger lengths. | +| **Multiplexing** | **Command** frames may appear **between** **file** frames on the same link; receivers handle them **frame by frame** (no reliance on “only files until done”). | +| **Resync (serial)** | A **start-of-frame** pattern (**SOF**, §2) reduces ambiguity after noise or partial reads on raw serial. | +| **Lightweight integrity** | **No** per-frame checksum or CRC in the **default** profile (§2.1); optional **8-bit checksum** or **CRC** only if peers agree and the link justifies the cost. | + +--- + +## 2. Outer frame format (normative for this draft) + +All multi-byte integers are **little-endian** unless stated otherwise. + +| Offset | Size | Field | Description | +|--------|------|--------|-------------| +| 0 | 2 | **SOF** | **Start of frame:** `0xE5 0x3D`. If a transport is already message-delimited **and** lossless, implementations **may** omit SOF only if both peers agree; default for **UART / SPP** is **SOF required**. | +| 2 | 1 | **VER** | Protocol version. **1** for this draft. | +| 3 | 1 | **CLASS** | Message class — routes the payload (§3). | +| 4 | 1 | **FLAGS** | Bit flags (§4). **0** if unused. | +| 5 | 2 | **LEN** | Payload length **N**, **0 ≤ N ≤ 1536**. | +| 7 | N | **PAYLOAD** | Opaque to the framing layer; interpretation depends on **CLASS**. | + +- **Total wire size:** `7 + N` bytes (with SOF). + +### 2.1 Integrity — baseline without checksum or CRC (recommended for embedded) + +**Default:** the outer frame has **no** checksum and **no** CRC — aligned with **WebSocket V1**, which already documents **no** frame checksum (`../architecture/websockets_protocol_V1_0.md`). + +**Why skip per-frame integrity on constrained MCUs:** any scheme that covers the **whole** payload still needs at least **one linear pass** over up to **1536 bytes** per frame (plus tiny fixed cost). That is usually **smaller** for a simple **checksum** than for **CRC16/CRC32** (no lookup table, a few bytes of code), but it is **not free**, and it is **weaker** than a CRC: e.g. an **8-bit additive** (sum of bytes mod 256, or XOR of all bytes) misses many error patterns (reordered bytes, certain multi-bit flips) that **CRC** would catch far more often. **CRC** adds **more** **CPU** per byte (unless hardware-assisted) and **more** **flash** (bitwise CRC or table-driven implementation). On a **clean UART / SPP** link at modest baud rates, **SOF + fixed header + LEN bounds + V1 sequencing** already turn a lot of corruption into **parse errors**, **illegal opcodes**, or **file-engine rejects**. If end-to-end file integrity matters, **application-level** checks (e.g. hash after complete write, or size/id checks already in V1) often **target the risk** without taxing **every** small **CMD** frame. + +**Checksum vs CRC (if you add something later):** + +| Approach | Typical cost | Detection strength | +|----------|----------------|-------------------| +| **None** (default) | Lowest | Rely on framing + V1 + app checks | +| **8-bit checksum** (e.g. sum mod 256, or XOR fold over header + payload — exact formula TBD in a profile doc) | Low code, one pass | Modest; good for accidental single-byte glitches, not a substitute for cryptographic or file hashes | +| **CRC16 / CRC32** | Higher code and/or table; one pass | Much stronger for random bit errors | + +**Pragmatic lightweight combo — frame size + checksum:** this format **already** includes **LEN** (payload byte count). That is **not** perfect protection by itself, but it **defines how many bytes** belong to the current frame (with **SOF** / **VER** / **CLASS** / **FLAGS** before it), rejects **illegal** lengths, and helps recover from **desync** (wrong length → abandon frame, resync on **SOF**). Pairing **LEN** with an optional **checksum** over the **bytes that LEN covers** (typically **header fields + PAYLOAD**, or **PAYLOAD** only — exact coverage TBD per profile) is still **not** a substitute for a **strong file hash** after a complete transfer, but it is a **reasonable, cheap** middle ground: **size** catches many **boundary** and **truncation** errors; **checksum** catches **some** bit/byte corruption **inside** that region. Neither is airtight alone; **together** they are **“good enough”** for many workshop links without paying **CRC32**-level cost. + +**Optional profile (future):** two peers **may** agree on a **FLAGS** bit or higher **VER** meaning “**trailer after PAYLOAD**”: e.g. **1 byte** checksum, **2 bytes** CRC16, or **4 bytes** CRC32, with the **exact polynomial and coverage** (header only vs header+payload) defined in that profile. That remains **negotiated**, not a **global requirement**, so **low-resource** builds can stay **checksum-free** and still interoperate where the link is trusted. + +**Note:** a **checksum over the header only** (e.g. **CLASS** + **FLAGS** + **LEN**) is **cheap** (fixed ~4 bytes) but does **not** protect **PAYLOAD**; **LEN** already constrains payload size, so a **payload-inclusive** checksum (or full header+payload) is what complements **LEN** for content integrity. + +--- + +## 3. CLASS values (routing) + +| Value | Name | Payload semantics | +|-------|------|-------------------| +| `0x01` | **CMD** | **Command / interactive line.** Typically UTF-8 text (ESP commands, G-code). **Line discipline** is **application-defined**: recommended practice is one logical line per frame, terminated with `\n` or `\r` inside **PAYLOAD**, matching [`websockets_protocol_V1_0.md`](../architecture/websockets_protocol_V1_0.md) text handling where possible. Binary **CMD** payloads are allowed if both peers define them; the framing layer does not interpret them. | +| `0x02` | **RSP** | **Textual (or opaque) replies** from **either peer** — same rules as **CMD** for line termination. **Optional:** implementations **may** use only **CMD** in both directions and ignore **RSP**; the distinction is for application tagging, not for “who is allowed to send”. | +| `0x10` | **FILE** | **File-transfer (V1-compatible) block.** **PAYLOAD** is a **complete V1 binary message** as in [`websockets_protocol_V1_0.md`](../architecture/websockets_protocol_V1_0.md): **2-byte ASCII opcode** + **2-byte inner length** + **inner payload**, with **inner total size ≤ 1536** so it fits in one outer frame. The **inner** `SR`, `SU`, `UP`, `EU`, `SD`, `DP`, … formats are **unchanged** from the WebSocket spec. | + +**Routing rule:** after parsing **LEN** and copying **PAYLOAD**, the receiver **dispatches** by **CLASS** only: + +- **CMD** / **RSP** → command or response handler (same code path as today’s line-oriented input, modulo buffering policy). +- **FILE** → existing V1 parser / state machine (status, upload, download). + +Unknown **CLASS** values: implementations **should** discard the frame and **may** emit an application-level error; they **must not** mis-route as **CMD** or **FILE**. + +--- + +## 4. FLAGS (draft bits) + +| Bit | Meaning (if set) | +|-----|------------------| +| 0 | **REQ_ACK** — sender asks for an application-level acknowledgement (optional; not defined in this draft). | +| 1–7 | Reserved — **must be 0** in version **1** unless a later doc defines them. | + +--- + +## 5. Size budget (1.5 KiB) + +- **Outer** **PAYLOAD** max = **1536** bytes. +- For **CLASS = FILE**, the **entire** V1 message (opcode + inner length + inner body) **must** fit in those **1536** bytes. +- Today’s documented default **UP** data chunk is **1024** bytes plus **4**-byte packet id plus **4**-byte header → **1032** bytes inner → **fits** with margin. +- If a future change increases chunk size, it **must** stay ≤ **1536** inner **or** introduce **fragmentation** at the V1 layer (out of scope for this draft). + +--- + +## 6. Ordering and concurrency (product policy) + +This draft **only** specifies **framing and routing**. Policy is recommended as follows (aligns with V1 “one transfer per connection” spirit): + +- **At most one active V1 transfer** per logical session unless a later revision defines transfer IDs. +- While a transfer is active, **CMD** frames **may** still be processed; **each peer** **should** define which commands are safe (e.g. status vs motion). +- **FILE** frames that violate V1 sequencing (e.g. **UP** without **SU**) **should** be rejected with the same error behaviour as on WebSocket. + +### 6.1 Sequenced payload — no silent progress past a failed unit + +**Scope:** this applies to **application / V1** semantics for **ordered** data (e.g. **UP** packets identified by a **packet id** in the inner V1 payload). **How** to retry (count, backoff) stays **applicative**; the **framing** layer does not define **NAK** here. + +**Rule:** once a unit **N** is in an **error** state (checksum fail, parse reject, storage **I/O** error, or explicit **V1** **error** response), the receiver **must not** treat the stream as **healthy** for **subsequent** units **as if N had succeeded**. + +If unit **N+1** arrives while **N** is still **failed**: + +| Allowed strategy | Requirement | +|------------------|-------------| +| **Reject / stall** | Treat **N+1** as **invalid** for commit (same **error** or **busy** until **N** is **repaired** or the **transfer** is **aborted**). **Do not** append **N+1** to the file **while N is missing or bad**. | +| **Cache** | **Buffer** **N+1** (and optionally further units) **until** **N** is **successfully** received or **retransmitted**; only then **commit in order**. **RAM** bounds for the cache are **product-defined**; if the cache **overflows**, the **transfer** **should** **abort** rather than **drop** **N** and accept **N+1**. | + +**Forbidden:** accepting and **committing** **N+1** **while ignoring** that **N** is still **erroneous** (logical **hole** or **reordering** without recovery). Peers that need **simple** behaviour may **abort the whole transfer** on **first** **FILE** **error** instead of caching. + +--- + +## 7. Lower layers (BLE, external modules) + +- This spec is the **L2 application framing** on top of a **reliable ordered byte stream**. +- **UART**, **SPI**, **USB-CDC**, and similar can carry the **same** frame bytes: for **SPI**, only **who clocks**, **CS**, and how octets are **chunked** into transactions are **link-specific**; the **parser** does not change. +- If the physical transport has a smaller MTU (e.g. BLE GATT), a **sub-framing** or **link-layer segmentation** **below** this spec **must** reassemble to deliver **complete outer frames** to the parser. +- **1.5 KiB** is the **logical** maximum per **outer** message; it does **not** imply that one radio PDU carries one message. + +--- + +## 8. Cross-platform portability (e.g. STM32 ↔ ESP32) + +Yes — the on-wire format is **vendor-neutral**: **plain bytes**, **little-endian** **LEN**, bounded payload, **no** dependency on ESP-IDF, HAL brand, or a specific RTOS. Any MCU with **UART** (or USB-CDC exposing a byte stream) can implement the **same** parser and emitter in **C** or **Rust**. + +**Typical alignment between STM32 and ESP32:** + +- Both are **little-endian** for `uint16_t` / `uint32_t` in common toolchains; **LEN** matches native layout without swaps. +- **RAM:** each side needs either a **ring buffer** plus a **reassembly** state machine, or a buffer of up to **7 + 1536** bytes for a whole frame — the **numbers** are identical on both platforms; only **available heap/stack** differs by project. +- **Concurrency:** parsing can run in **ISR + queue**, **DMA idle callback**, or a **task** — outside the scope of this doc; the **byte sequence** is what must match. + +**Interop rule:** if a future peer uses **big-endian** **LEN** (unusual on these MCUs), it **must** document byte order; default for this draft remains **LE** everywhere. + +--- + +## 9. Example (hex, conceptual) + +Outer: **CMD** with payload `PING:0\n` (7 bytes): + +`E5 3D 01 01 00 07 00 50 49 4E 47 3A 30 0A` + +Outer: **FILE** wrapping a minimal V1 **SR** (opcode `SR`, inner length 0): + +`E5 3D 01 10 00 04 00 53 52 00 00` + +(The other peer may answer with **CLASS FILE** and inner **RS**, etc. — **same** frame format in either direction.) + +--- + +## 10. Open points (for a future revision) + +- **Optional negotiated** trailer: **8-bit checksum** or **CRC16/CRC32** (see §2.1) — **profile**, not mandatory interop. +- Explicit **transfer handle** in **FLAGS** or a header extension for **multiple concurrent** sessions. +- **Discovery** byte (capability advertisement) on connect, analogous to WS welcome + **SR**/**RS**. +- Formal mapping to **BT BLE** GATT service UUIDs / characteristics (if not a transparent UART). + +--- + +## 11. Informative — lessons from comparable ESP ↔ MCU links + +This section is **not normative**. It records **design takeaways** from studying **other** on-wire protocols between an **ESP** (or similar) and a **host MCU** (e.g. **WiFi bridge modules** for 3D printers). Those protocols are **not interchangeable** with this draft; the point is **what to learn** and **what gaps to watch**. + +### Ideas worth considering (optional product choices) + +| Idea | Why it matters | How it could map here | +|------|----------------|------------------------| +| **End delimiter** after payload (some use a fixed **tail** byte) | **SOF + LEN** already defines length; a **tail** can help detect **corrupted LEN** or **lost sync** (wrong length still “closes” visually only if tail matches — weak alone, stronger **with** checksum). | Future **profile**: optional **EOT** byte after **PAYLOAD** (cost: +1 byte/frame). | +| **Predictable file chunk size** (fixed payload + padding) | Receiver **RAM** and **flash write** timing are easier to budget. | V1 already uses bounded **UP** chunks; document **preferred** inner sizes as **implementation guidance**. | +| **Different UART speeds** for bulk vs interactive traffic | High baud for **file** throughput, lower for **robust** command/debug. | **Out of scope** for framing; **recommended** in integration guides (both peers renegotiate rate the same way). | +| **Periodic status** on the link | Liveness and **UI** state without polling commands. | Could be **CMD**/**RSP** lines or a small **future CLASS**; not required in v1 draft. | +| **Explicit “receiver ready”** (some use a **GPIO**) | Avoids overrunning a slow MCU. | **Product wiring**; or **in-band** **windowing** / “go” **CMD** if no extra pin. | + +### Gaps often seen elsewhere that this draft already mitigates + +| Topic | Typical pain elsewhere | This draft | +|-------|------------------------|------------| +| **Command vs file on one wire** | Separate **type** namespaces **per direction** → easy to confuse. | **CLASS** (**CMD** / **FILE**) is **explicit** and **symmetric** (§3, §8). | +| **File semantics** | Custom opcodes per vendor. | **FILE** wraps **documented V1** (`../architecture/websockets_protocol_V1_0.md`) for reuse with existing tooling/logic. | +| **Binary safety** | Ad-hoc parsing. | **Fixed header + LEN cap + SOF** (§2). | +| **Integrity (optional)** | Often **none** on the wire. | **Optional** checksum/CRC **profiles** (§2.1). | + +### Gaps you may still want to close (future work) + +| Gap | Note | +|-----|------| +| **Retry / NAK** | **Retransmit policy** is **applicative**. **Sequencing integrity** when a unit **fails** is **not** optional: see **§6.1** (reject later units, **cache** until gap closed, or **abort** — **never** commit **ahead** while **ignoring** a bad **N**). A **profile** may add explicit **NAK** + **retry** for **FILE** without blocking **CMD** traffic. | +| **Timeouts** | **Half-open** transfer if a peer disappears — define **idle timeout** and **abort** at **V1** or **session** layer. | +| **Link bring-up** | **Baud**, optional **EOT**, optional **checksum**: **capability** or **version** exchange on **first** frames (related to **discovery** in §10). | +| **Flow control without GPIO** | **Credit** (N frames OK to send) or **small** **RSP** **ACK** **CMD** profile for slow receivers. | + +--- + +## 12. Summary + +Use one **binary envelope** for everything: **SOF + version + CLASS + FLAGS + LEN + PAYLOAD**, with **LEN ≤ 1536**. **CMD**/**RSP** carry interactive text (or agreed binary); **FILE** carries a **full V1 message** identical to the WebSocket binary format. **Both peers** use the **same** rules to parse and emit frames; **file chunks and commands can be interleaved** in **either** direction on the same serial-style link, with **no** framing-level host/client and **no** shared exclusive “mode” at the envelope layer. Semantics are **receiver-driven** (**pure API**); **default** framing has **no** checksum or CRC for **lightweight** implementations, with **optional** **checksum** or **CRC** profiles reserved for difficult links. The byte layout is **cross-platform** (e.g. **STM32** ↔ **ESP32**); see §8. Informative **lessons** from other ESP ↔ MCU protocols: §11. **Sequenced** **FILE** payloads **must not** be **committed** **ahead** of a **failed** unit **without** **reject**, **ordered cache**, or **transfer abort**: §6.1. diff --git a/docs/ongoing_reflection/gcode_host_streaming_implementation.md b/docs/ongoing_reflection/gcode_host_streaming_implementation.md new file mode 100644 index 00000000..23854ed7 --- /dev/null +++ b/docs/ongoing_reflection/gcode_host_streaming_implementation.md @@ -0,0 +1,247 @@ +# GCode Host Streaming Implementation Notes + +This document is meant for implementation discussion and design review. It describes how the current firmware streams G-code/macros (at the host level), what depends on the selected CNC/3D target, and what needs to change to achieve higher sustained throughput without generating motion “blobs” or timeouts. + +## Why this matters + +The current `ESP3DGCodeHostService` scheduler is correct for functional sequencing (ordering, pause/resume/abort, timeouts), but its throughput is limited by: + +- host task tick cadence (it can progress only one scheduler step per `handle()` call) +- heavy per-line work on the `fs_stream` / `sd_stream` path (string/precision formatting and status/progress updates) +- optional per-line `ok` waiting when `hasAck()` applies (today only `$J` on FluidNC/grblHAL) + +When targeting a CNC laser (high feed + low tolerance to idle gaps), a “ping-pong” host loop can become too slow. Similarly, for 3D printing, insufficient sustained throughput or late ACK handling can translate into underfed planner buffers and visible artifacts. + +## Current system dependency contract (target-driven) + +`gcode_host` delegates response classification and ACK policy to `esp3d_gcode_handler_service` (the selected target implementation). + +### Methods used by `gcode_host` today + +- `bool hasAck(command)`: + - host decides whether to enter `wait_for_ack` after sending a line. + +- `ESP3DDataType getType(data)`: + - host classifies incoming lines as `ack`, `status`, `error`, `comment`, `gcode`, `esp_command`, etc. + - the `ack` branch unblocks the stream state machine. + +- `const char* getLastError()`: + - used when `getType()` classifies an incoming line as `error` (status bar display). + +### Removed from the current model + +Line-numbered / checksummed G-code (`N cmd*cksum`), `_CheckSumCommand`, resend recovery, and `getLineResend()` are **not** in the current host path. Commands are sent as plain `cmd\n`. See `docs/architecture/gcode_host_streaming_flow.md` (ACK and Timeout). + +### FluidNC / grblHAL observations (current code) + +- `hasAck()` returns true for **all non-realtime lines** on both targets (realtime bytes like `?`, `!`, `~`, overrides never consume ok credit — FluidNC can stack `ok` while in hold). +- The host no longer uses a lone `_awaitingAck` boolean: `pending_ok` credit in `gcodeHostFlow*` allows up to `getStreamMaxInFlight()` (4) lines in flight; `wait_for_ack` is entered only at the cap or for `single_command`. + +Implication: when host streaming is used, the dominant bottleneck is usually **not** strict ACK ping-pong, but host tick cadence (10 ms) and per-line CPU overhead in `read_cursor`. + +## Current host streaming architecture (host-side scheduler) + +At a high level, `ESP3DGCodeHostService` runs a single scheduler loop driven by FreeRTOS task ticks: + +- `handle()`: + - `_handle_notifications()` + - `_handle_stream_selection()` + - `_handle_stream_states()` (state-machine step) + - `_handle_msgs()` (consume RX) + - `esp3dGcodeHandler.handle()` (target periodic processing) + +The state machine for file streaming (`fs_stream` / `sd_stream`) advances roughly like: + +- `start` +- `ready_to_read_cursor` +- `read_cursor` -> `send_gcode_command` (prepare + send one line) +- optionally `wait_for_ack` +- back to `read_cursor` for the next line + +### Throughput limiting behavior + +Because the task loop calls `handle()` at a fixed cadence and the scheduler performs one step per `handle()` call, the maximum send rate is bounded by “one scheduler step per tick”. + +Additionally, the `read_cursor` path: + +- updates progress/duration strings (with `std::to_string` and precision formatting) +- may update TFT values depending on intervals +- manipulates stream cursor state and performs command normalization + +## Product model — when host streaming matters + +### Unified command routing (invariant) + +All CNC commands go through `gcodeHostService.process()`. The **only** bypass of stream / ACK management is **`ESP3DMessagePriority::high`** (`_forwardUrgent`) — emergency and urgent realtime (`!`, `~`, `0x18`, `0x85`, …). This separation must remain when unified `ok` + buffer flow control is added. + +Normal-priority traffic — including `$SD/Run`, `$F=`, `$J=`, `G-code`, and polling `?` — is queued and sequenced by the host (`single_command` or file stream). + +### Default: firmware SD execution (FluidNC / grblHAL) + +Job and macro launch uses **one normal-priority command through `gcode_host`**; the target firmware then reads the file from **its** SD: + +- FluidNC: `$SD/Run=` +- grblHAL: `$F=` + +The pendant does not stream the file content. Benefits: no UART throughput ceiling for long jobs, lower CPU/RAM, CNC handles pause/feed during SD execution. + +### Future: host streaming use cases (next SKU priority) + +**Next product:** TFT + **pure GRBL without SD** — see [`grbl_no_sd_preparation.md`](../roadmap/grbl_no_sd_preparation.md). + +Host streaming (`fs_stream` / `sd_stream`, `[ESP700]`, `multiple_commands`) is planned for: + +- **pure grbl** (no firmware-side SD run command) — **primary next step** +- **grblHAL without SD** +- **local macros** or **multiline command batches** generated or stored on the pendant + +**Transport:** serial, USB serial, or Bluetooth only — not WiFi on the default pendant SKU. WiFi serves monitoring/control (HTTP / WebUI). Socket-client CNC over WiFi is a separate configuration; host file streaming optimization does not target that path today (policy may change). + +**3D printers** (Marlin-style planner feeding, checksummed lines): out of scope for now. + +### Implication for optimization priority + +- **Low urgency** for FluidNC/grblHAL SD jobs — already on Strategy B (firmware SD run). +- **Medium urgency** for scripts, single commands, and future grbl-without-SD targets. +- Host scheduler work (tick cadence, in-flight window, hot-path CPU) should be driven by **measured** needs on serial/USB/BT transports, not by the current PiBot UI job path. + +## What “efficient streaming” should mean + +An implementation should achieve three properties: + +1. Sustained throughput: + - the host must keep the target’s planner/input fed without long gaps + - gaps should be bounded by a small fraction of the CNC/3D planner refill time + +2. Correctness: + - ordering must hold + - pause/resume/abort must be deterministic + - error handling must not cascade into infinite retries + +3. Bounded memory: + - no unbounded buffering + - prefer fixed-size buffers and predictable allocations + +## Proposed target-aware streaming strategies + +### Strategy A: Unified flow control (`ok` + planner buffer) — implemented + +**This is the model for all platforms when host streaming is active.** Implemented in `target/cnc/modules/gcode_host/esp3d_gcode_host_flow.cpp`, wired in the core host: + +1. **`pending_ok` credit** — lines sent minus `ok`/`error:` received (`getStreamMaxInFlight()` caps the window at 4). +2. **Planner gate** — `buffer_blocks` from latest `|Bf:|` (cached as integers in the handler); no send when free blocks ≤ 5 (same threshold as jog). +3. **RX window (character counting)** — local ring of in-flight wire lengths; no send when `inflight_bytes + line_len + 1 > getStreamRxBufferSize()` (grblHAL 1024, FluidNC 256, pure GRBL will be 128). Hard cap, independent of `|Bf:|` freshness. +4. **RX snapshot gate** — `line_len + 1` must also fit in the last reported `|Bf:` bytes value (inactive until first report). + +Send while all gates allow (`gcodeHostFlowCanSendLine`); enter `wait_for_ack` only when `pending_ok` reaches the cap (or for `single_command`). `error:` is handled as the negative ack of one line and stops the current + main stream (`command_rejected`), recovery is user-driven. + +This gives coherent throughput on GRBL (ok-heavy), FluidNC, and grblHAL without per-platform state machines in the UI. + +### Strategy B: Delegate SD execution to firmware (current PiBot default) + +FluidNC (`$SD/Run=`) and grblHAL (`$F=`) execute jobs from the **target SD**. This is the **preferred** path whenever the CNC has its own card — not a fallback. + +Host-side file streaming is unnecessary for those workloads and should not drive optimization priority today. + +### Strategy C: Hybrid: host reads file, firmware executes buffered chunks + +If firmware supports a “batch” mechanism (for example a chunk endpoint, or a “queue” command), the host can: + +- read from pendant SD at high speed +- send chunks in bigger atomic groups +- keep per-line scheduling logic minimal + +This requires target-specific extension of `esp3d_gcode_handler_service` (new commands / parsing rules). + +## Bottlenecks to measure (before code changes) + +To avoid refactoring in the dark, measure these metrics: + +- Host send cadence: + - time delta between consecutive UART/TCP writes from `gcode_host` + - effective lines/second sent during a steady job +- RX processing latency: + - time between receiving a firmware “ok” and updating host state +- In-flight pressure: + - queue depth growth in `esp3dCommands` / TX path (if measurable) +- CPU hot path time: + - time spent inside `read_cursor` and progress formatting + +## Task priorities and scheduling (board-specific reality) + +On PiBot v1.0, `ESP3DGCodeHostService` runs as a pinned FreeRTOS task on core 1 with a high priority: + +- `ESP3D_GCODE_HOST_TASK_PRIORITY` = 14 +- `ESP3D_GCODE_HOST_TASK_CORE` = 1 + +This is defined in `boards/pibot_pendant_v1_0/components/bsp/tasks_def.h`. + +Scheduling implication: + +- The gcode host task should not be starved by LVGL (core 1) only, but it can still lose CPU time due to long critical sections inside the host hot path (string formatting, progress updates, per-line normalization). +- If we implement an in-flight window, we must ensure the new “send loop” remains time-bounded (send multiple commands per tick, but for a short duration) so we do not starve RX parsing or pause/abort handling. + +Instrumentation should log with timestamps but must be gated (debug-only) to avoid worsening performance. + +## Feasibility discussion: can we stream fast enough for CNC laser and 3D at speed? + +### CNC laser + +- A streaming pipeline that keeps “in-flight” commands above the CNC planner’s minimum refill threshold is the typical approach. +- If the firmware supports internal queuing, host in-flight windowing is usually sufficient. +- If firmware forces strict per-line acknowledgement, then performance depends on: + - ACK latency + - whether `ok` is emitted per planner consumption vs per line receipt + - ability to pipeline multiple lines safely + +Given the current scheduler “one step per handle tick”, a single immediate improvement is likely to be raising the scheduler’s ability to send more than one line per iteration or reducing the tick delay budget. + +### 3D printing at high speed (“blobs”) + +“Blobs” typically mean the motion planner is not continuously fed (or the command stream gets “lumpy” due to retransmits / stalls / late flow control). + +Host ping-pong behavior (or progress/UI overhead that steals CPU time) can create those stalls even if ACK semantics are mostly correct. + +The implementation must ensure: + +- sustained send throughput +- predictable handling of `ok` timing +- resend/error recovery that does not introduce long idle periods + +For targets where line numbering + checksum is required, the “in-flight window” must preserve the ability to map acknowledgements back to the correct line sequence. + +## Execution plan (what to implement next, in order) + +1. **Strategy B** remains default for FluidNC/grblHAL **SD jobs** (`$SD/Run` / `$F=`). + +2. **Host scheduler prep** (done): RX before states, multi-step per tick, progress off hot path. + +2b. **Core + flow split** (done): `main/modules/gcode_host/` + `target/cnc/modules/gcode_host/` — see [`gcode_host_architecture.md`](../architecture/gcode_host_architecture.md). CNC tested on final layout; 3D adds its flow file only. + +3. **Unified flow control** in handler cache + `gcodeHostFlow*` (CNC done): + - `canAcceptStreamLine(size_t line_len)` — combines `pending_ok`, `buffer_blocks`, `buffer_bytes` + - `onStreamLineSent()` / `onStreamAck()` — maintain credit (or host-owned with handler thresholds) + - `hasAck()` → true for all non-realtime lines on GRBL; FluidNC/grblHAL align when host streaming enabled + - Reuse planner threshold from jog (`ESP3D_PLANNER_BUFFER_SIZE_THRESHOLD` or per-target NVS) + +4. **Host `gcode_host` integration**: + - Replace `_awaitingAck` with `pending_ok` + call `canAcceptStreamLine()` in `read_cursor` / `send_gcode_command` + - Keep `wait_for_ack` when at in-flight cap, not only on boolean ack flag + +5. **GRBL target handler** (next SKU) — see [`grbl_no_sd_preparation.md`](../roadmap/grbl_no_sd_preparation.md). + +6. **Back-port unified model to FluidNC / grblHAL** host streams (`[ESP700]`, local macros) so one code path serves all targets. + +7. **Instrumentation** (debug-only) — lines/s, pending_ok, buffer_blocks at send time. + +8. **3D / Marlin** — deferred. + +## Open questions (must be answered with data) + +Answer on **grbl or grblHAL-no-SD over serial/USB/BT**, not on FluidNC SD jobs (those bypass the host). + +1. Does the target accept multiple G-code lines without waiting for per-line `ok`? What is the safe in-flight count before UART/parser overflow? +2. How much CPU time is spent in `read_cursor` progress formatting per line during a steady stream? +3. For local macros / `multiple_commands`, is current ~33 lines/s (3 state steps × 10 ms tick) sufficient, or is batching required? +4. Should `[ESP700]` / WebUI file streaming remain supported on WiFi for remote maintenance, or be restricted to wired transports only? + diff --git a/docs/ongoing_reflection/input_overflow_postmortem.md b/docs/ongoing_reflection/input_overflow_postmortem.md new file mode 100644 index 00000000..2298c7f8 --- /dev/null +++ b/docs/ongoing_reflection/input_overflow_postmortem.md @@ -0,0 +1,519 @@ +# Input overflow (memory saturation): post-mortem, mitigation and audit + +Status: **draft for review**, written 2026-10-20, updated 2026-10-21. §2-§7 +describe the first mitigation as audited. The audit recommendations approved +on 2026-10-21 are implemented (see §9). Everything builds (8mb_wifi_fluidnc +dev, 8mb_serial_fluidnc, 4mb_bt_serial_fluidnc, 4mb_bt_ble_fluidnc) but is +**not yet hardware-tested**. + +Related: [esp32_memory_constraints.md](../guides/esp32_memory_constraints.md) +§3 (as-built description of the guard), [gcode_host_streaming_flow.md](../architecture/gcode_host_streaming_flow.md) +(host state machine and flow control). + +--- + +## 1. Summary + +Pasting a large text into the serial console (a stress test simulating an +external device flooding the pendant) **rebooted the pendant**. Successive +fixes removed the crash, but then left the pendant **alive and unusable**: +no command reached the CNC any more, and the Restart button did not recover +it. + +The root cause is structural: every queue on the input path is bounded on its +own, in **payload bytes only**, but nothing bounds their **sum, overhead +included**, against the heap actually free (~17-20 KB with WiFi, ~10 KB +with Bluetooth). A flood fills all queues at once and exhausts the heap. +With no C++ exception emergency pool, the first failed `std::string` / `new` +ends in `std::terminate`, even inside a `try/catch`. + +The mitigation now in place has four parts: + +1. **Admission at the transport entry**, before any allocation. +2. **Full purge** of the gcode host when an overflow is detected. +3. **Visible error state** (local message + ERROR icon), latched. +4. **Manual recovery** through the Restart button, which resynchronizes the + host and the controller. + +The audit (§6) finds the approach sound as a **last-resort safety net**, but +identifies false positives with heavy consequences (job purged), silent loss +paths that are not detected, and one machine-safety decision left open. + +--- + +## 2. Timeline (2026-10-20) + +| # | Observation | Diagnosis | Change | +|---|-------------|-----------|--------| +| 1 | Paste in the serial terminal → reboot, `Reset reason: PANIC` | Decoded backtrace: uncaught `std::bad_alloc` from `std::string cmd = str_trim(command)` in `ESP3DGCodeHostService::addStream()` (host task) → `abort()` | `try/catch` around the copy; the command is dropped and logged | +| 2 | Still reboots | The `catch` logs with `esp3d_log_e` → the error log hook pushes into the system message history (allocation) → `__cxa_allocate_exception` fails → `std::terminate`. `CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE=0`: under **total** exhaustion `try/catch` cannot work | Low-memory admission guard in `ESP3DClient::addRxData()`: refuse a new message below 6144 B free / 2048 B largest block | +| 3 | Still reboots; log shows `free=65 KB largest=63 KB` while every allocation fails | `MALLOC_CAP_INTERNAL` alone also counts 32-bit-only IRAM, which `malloc` cannot use: the guard never triggered | Measure with `MALLOC_CAP_INTERNAL \| MALLOC_CAP_8BIT` | +| 4 | No crash; task watchdog backtrace (IDLE core 0 starved 5 s), non-fatal | 2 `esp3d_log_e` per dropped line (~7 ms of UART each + hook allocation) | Serial client drop reports rate-limited (1 log/s with count) | +| 5 | No crash, but afterwards even `$H` does nothing | The guard also refused **CNC responses** (`pushMsgToRxQueue failed for: `) → an `ok` was lost → the host waited forever (status reports keep resetting its timeout since the S1 fix) → its queue never drained → heap stayed below the reserve → every new command refused | Guard exempts `origin == output client`; host drop log rate-limited | +| 6 | No crash; still no recovery, even after Restart in the firmware status screen | Restart only sent `0x18`. The controller discards its buffer on reset, so the line in flight is never acknowledged, and the host kept all its queues and kept waiting | Current mitigation (§4) | + +Facts vs inferences: steps 1-5 are backed by decoded backtraces or log lines. +Step 6 is the user's report plus code reading (no log yet); the explanation is +strong but **not observed** in a log. + +--- + +## 3. Root cause analysis + +### 3.1 Where the memory goes during a flood + +```mermaid +flowchart LR + UART["UART driver ring
1024 B static
(allocated at install)"] --> SRX + SRX["Serial client RX queue
≤ 4096 B payload
(2048 if not output)"] --> HRX + HRX["Gcode host RX queue
≤ 1024 B payload"] --> SCR + SCR["Host scripts list
≤ 50 entries
1 stream per line"] --> CNC["CNC link
(flow-controlled)"] + LOG["Error log hook
system message history
(allocates per esp3d_log_e)"] + SRX -. drop logs .-> LOG + SCR -. "Script list is full" .-> LOG +``` + +Each line costs **two heap allocations per stage** (struct + data copy), plus +container nodes and allocator headers. **None of that overhead is counted** by +the queue limits, which count payload bytes only. + +Order-of-magnitude estimate (to be measured, §7 H1). The estimate uses 50-100 +byte pasted lines and ~8-16 B of allocator header per block: + +| Stage | Bound | Estimated heap at saturation | +|-------|-------|------------------------------| +| Serial client RX | 4096 B payload ≈ 80 short lines × (24 B `ESP3DMessage` + 2 headers + deque slot + data) | ≈ 8-9 KB | +| Host RX | 1024 B payload | ≈ 2 KB | +| Host scripts | 50 × (`ESP3DGcodeStream` ~64 B + list node + 2 headers + line copy) | ≈ 8-9 KB | +| **Total** | | **≈ 18-20 KB**, i.e. the **whole** free heap in WiFi mode, twice the free heap in BT mode | + +The flood does not need to be large. A few KB of short lines are enough, +because the per-line overhead dominates. + +### 3.2 Why it crashed instead of degrading + +- **No exception emergency pool** (`EMG_POOL_SIZE=0`). `bad_alloc` itself + needs a heap allocation, so under total exhaustion any throwing allocation + is fatal, whatever the `try/catch`. +- **Logging allocates.** `esp3d_log_e` feeds the system message history + (`std::deque` + `std::string`). Reporting an allocation failure triggers + another one. +- **Misleading measurement.** `MALLOC_CAP_INTERNAL` reports IRAM that + `malloc` cannot use. About 100 diagnostic logs still print this value + (over-estimated). `files_screen` (3 targets × 2 sites) uses it for a + protective decision (`MIN_FREE_HEAP_BYTES`): same bug, not fixed yet. + +### 3.3 Why it stayed dead after the crash was fixed + +- **Ack wait without an upper bound.** Since the S1 fix, status reports + `<…>` reset the host timeout, so that `$H` does not time out. Side effect: + a lost `ok` is now waited for **forever**. +- **Soft reset does not resynchronize the host.** The controller drops its + RX buffer and planner on `0x18`, but the host kept its queues, its current + stream and its flow-control credits. + +--- + +## 4. Mitigation in place (as built) + +### 4.1 Components + +| Part | Where | What | +|------|-------|------| +| Entry admission | `ESP3DClient::rxAdmit()` (`main/core/esp3d_client.cpp`), called first in the `pushMsgToRxQueue()` of the 8 transports (serial, USB serial, socket client, websocket client, BT serial, BT BLE, telnet server, websocket server) | Decides on the raw line, **before any allocation**. A refused line returns `true` (dropped on purpose, no error log) | +| CNC link policy | same | Always read (connection kept). Below the reserve, only **vital lines** are processed: `ok`, `error…`, `ALARM:`, `Grbl…` banner. Other lines are skipped | +| Other inputs policy | same | Refused below the reserve; the first refusal **closes the input** (`esp3d_rx_input_closed()`) | +| Safety net | `ESP3DClient::addRxData()` guard | Same reserve for messages created outside the transports (pendant UI, HTTP, Lua); CNC responses exempt | +| Overflow event | `esp3d_rx_overflow_take()` | Lock-free flag raised by every refusal, consumed by the host task | +| Full purge | `ESP3DGCodeHostService::_dropAll()` in `handle()` | Host RX queue, scripts, streams (job included), open file closed, flow state reset | +| Notification | same | Once per episode: local system message *"Input overflow: commands lost, all queues purged. Press Restart."* + `firmware_status` re-published | +| Error display | `FirmwareStatusComponent`, `firmware_status_screen` | ERROR icon / status forced while the input is closed | +| Late lines | `ESP3DGCodeHostService::process()` | While closed, lines already queued by a transport are dropped (except CNC responses and `system` origin) | +| Recovery | Restart (default action) of the firmware status screen | `gcodeHostService.resetAll()` (full purge, input reopened), then `0x18` + `?`. **Manual only** (user decision) | +| Thresholds | `ESP3D_RX_MIN_FREE_HEAP` 6144, `ESP3D_RX_MIN_LARGEST_BLOCK` 2048 | Measured with `MALLOC_CAP_INTERNAL \| MALLOC_CAP_8BIT` | + +### 4.2 Admission decision + +```mermaid +flowchart TD + A[Raw line received by a transport] --> B{origin == output client?
CNC link} + B -- yes --> C{Heap below reserve?} + C -- no --> OK[Admit: allocate + queue] + C -- yes --> D{Vital line?
ok / error / ALARM: / Grbl} + D -- yes --> OK + D -- no --> SKIP[Skip silently
rate-limited warning] + B -- no --> E{Input closed?} + E -- yes --> DROP[Drop
rate-limited warning] + E -- no --> F{Heap below reserve?} + F -- no --> OK + F -- yes --> G[Drop + raise overflow flag
+ close input] +``` + +### 4.3 Episode lifecycle + +```mermaid +stateDiagram-v2 + [*] --> Normal + Normal --> Saturated: refusal below reserve
(overflow flag + input closed) + Saturated --> Purged: host task consumes flag
_dropAll() + message + ERROR + Purged --> Purged: further refusals
(purge again, no new message) + Purged --> Normal: user presses Restart
resetAll() + 0x18 + ? + note right of Purged + CNC link alive (acks/alarms always processed) + Console / telnet / WebUI input refused + Pendant UI (system origin) still accepted + end note +``` + +### 4.4 Restart sequence + +```mermaid +sequenceDiagram + participant U as User + participant FS as Firmware status screen (LVGL) + participant H as Gcode host + participant C as CNC + U->>FS: Restart + FS->>H: resetAll() + Note over H: _emergency_stopping, wait tick (≤ 50 ms)
_dropAll(), reopen input, clear latch + FS->>C: 0x18 (high priority, bypasses host queues) + C-->>C: discard RX buffer + planner + FS->>C: ? + C-->>FS: → real status replaces ERROR +``` + +--- + +## 5. Situations catalog + +Coverage: ✅ covered · ⚠️ partially covered · ❌ not covered · ❓ to verify. + +| # | Situation | Current behavior | Coverage | +|---|-----------|------------------|----------| +| S1 | Paste flood on the serial console (WiFi CNC) | Entry refusal → purge → ERROR → Restart | ✅ (not hardware-tested yet) | +| S2 | Flood from telnet / WebSocket / WebUI terminal | Same path through `rxAdmit()` | ✅ (not tested) | +| S3 | Flood on the console while the CNC link is BT serial / BLE | Same path; BT heap baseline much lower (see S10) | ⚠️ | +| S4 | CNC sends many lines under low memory (`$$` dump, verbose `[MSG:]`) | Non-vital lines skipped: incomplete `$$` list, lost `[PRB:]` (probe screen waits), lost `[GC:]` | ⚠️ | +| S5 | Flood **during a running SD job** | Job purged, `job_status` idle, but the controller still executes its buffered moves (RX buffer + planner), **spindle/coolant stay on** afterwards | ❌ machine-side action undecided | +| S6 | Moderate flood that never reaches the heap reserve but fills a queue: host RX (1024 B, `Cannot add msg to client queue`) or scripts (50, `Script list is full`) | Lines **silently lost**, following lines still forwarded to the CNC. No purge, no notification. `Script list is full` also logs `esp3d_log_e` per line (allocates) | ❌ | +| S7 | UART driver ring (1024 B) overflows if the serial task stalls (~90 ms at 115200 baud) | Bytes lost **inside** lines: truncated or merged lines can be forwarded to the CNC as valid G-code. UART overflow events are not checked | ❌ ❓ | +| S8 | Transient heap dip caused by another subsystem (HTTP page load, TLS, WiFi scan) when a single remote line arrives | Treated as an overflow: **full purge, job included**, input closed until Restart | ❌ false positive | +| S9 | Pendant UI command (`system` origin, e.g. handwheel `$J`, `$H`) refused by the `addRxData()` guard | `rxHeapReserveReached()` raises the overflow flag and **closes the input** for any non-output origin → full purge + ERROR, triggered by the pendant itself | ❌ probably unintended | +| S10 | BT mode baseline: ~10 KB free; largest block may be < 2 KB under normal fragmentation | If the baseline is already below 2048 B largest, the guard trips on the **first** console or UI command → permanent overflow loop | ❓ **blocker, measure on BT hardware** | +| S11 | Slow leak (not a flood) reaching the reserve | Reported as "Input overflow", misleading diagnosis; free/largest not shown in the message | ⚠️ | +| S12 | Overflow while the CNC is disconnected | `handle()` returns early (`canSendData()` false): purge and message are deferred until connection; input already closed; icon not updated until a status update | ⚠️ minor | +| S13 | **Stray acks after the purge.** The controller still holds lines of the purged stream; their `ok` / `error:` arrive after the flow reset | They release credits of **new** commands (pendant UI before Restart): in-flight bytes under-counted → possible controller RX overrun; an `error:` attributed to the wrong command | ⚠️ fixed only once Restart is pressed | +| S14 | Restart pressed while the machine is actually moving (status forced to ERROR) | `0x18` during motion → controller alarm, position lost (re-homing needed) | ⚠️ acceptable: explicit user action, but the UI hides the real state | +| S15 | Remote operator (WebUI / telnet) after an overflow | Cannot recover remotely: input closed until someone presses Restart on the pendant | ⚠️ by design, to confirm | +| S16 | Remote **realtime safety bytes** (`!` feed hold, `0x18`, `0x85`) while the input is closed | Dropped like any other line | ⚠️ to decide | +| S17 | Notification allocation (`std::string` + deque) right after the purge | Purge frees memory first, so normally fine. If the memory is held elsewhere (not by the input pipeline), allocation can still fail → terminate | ⚠️ low probability | +| S18 | `resetAll()` from LVGL while a host tick lasts > 50 ms | Purges anyway (pre-existing pattern of all purge functions) | ⚠️ low probability | +| S19 | Boot-time reboots reported earlier (2-3, no trace) | Possibly the same exhaustion (boot traffic) | ❓ `Reset reason` now logged | +| S20 | Handwheel jog in progress at overflow | Queued `$J` purged; the controller finishes buffered jog lines | ✅ acceptable | + +--- + +## 6. Review of the approach + +### 6.1 Pros + +- **No crash path left on the input side**: the refusal path allocates + nothing (flag + rate-limited warning). +- **Decision at the earliest point**: one function, 8 call sites, applied on + the raw line before `newMsg()`. +- **CNC link never cut**: acks and alarms always processed, so the host can + stay in sync and safety messages are not lost. +- **Clear, visible recovery**: error message, ERROR icon, one button. The + same action (Restart) also resynchronizes host and controller after any + soft reset, which fixes the general "lost `ok` after reset" problem (§3.3). +- **Conservative by construction**: once commands are lost, nothing + incomplete is forwarded until a human acknowledges. + +### 6.2 Cons + +- **The trigger is "heap below reserve", not "input lost".** Any heap dip + causes a full purge, whatever its cause (S8, S9, S10, S11), with a heavy + consequence (running job purged). Conversely, real losses that happen + above the reserve are not detected at all (S6, S7). +- **The job purge is not paired with a machine-side action** (S5): the + pendant forgets the job while the machine keeps running briefly, with + spindle on. +- **Empirical thresholds.** 6144 / 2048 B were chosen from WiFi + measurements. They are not derived from a budget and not validated for BT. +- **Heuristic whitelist** of vital CNC lines (prefix match, target-agnostic): + correct for grbl / grblHAL / FluidNC acks and alarms, but it loses + response data that some screens wait for (S4). +- **Stray acks** between the purge and Restart (S13). +- **Recovery is local only** (S15) and remote realtime commands are ignored + while closed (S16). + +### 6.3 Is it the right approach? + +As a **last-resort safety net**, yes. "Never crash, drop, tell the user, +recover explicitly" is the correct behavior once memory is truly exhausted, +and the entry-point placement is the right one. + +As the **primary** protection, no. It reacts to a symptom (low heap) instead +of the cause (unbounded total input pipeline), which explains both the false +positives and the undetected losses. The alternatives below address the +cause. + +### 6.4 Other approaches + +| Id | Approach | Pros | Cons | +|----|----------|------|------| +| A | **Global input budget.** Account bytes **and** per-message overhead across all input queues (one counter, incremented at admission, decremented at free); admit while under budget | Deterministic, independent of other subsystems' transient heap use (removes S8); a full budget is an exact "loss" signal (catches S6) | Touches every free path of queued messages; the budget must be sized per configuration (BT) | +| B | **Backpressure instead of drop** for TCP inputs (telnet, WS): stop reading the socket when the pipeline is full | No loss for remote clients; TCP throttles the sender | lwIP keeps unread data (bounded by the TCP window, still heap); not possible on UART without RTS/CTS | +| C | **Static pools** for input messages and host scripts (e.g. 32 × 128 B) | No heap use at all on the input path: fragmentation-proof, no exhaustion possible | Permanent static DRAM cost (~4-8 KB) on a board where DRAM is the scarcest resource | +| D | **Two-level reaction**: a single refusal = drop that line + warning; an overflow = N refusals within T ms, or any refusal while a multi-line input is in progress → purge + latch | Removes most false positives (S8, S9) with little code | Needs tuning; a single lost line in a G-code sequence is still a lost line (so it must at least be notified) | +| E | **Enable the C++ exception emergency pool** (`EMG_POOL_SIZE` ≈ 1-2 KB) | `try/catch` works again under total exhaustion: defense in depth for every `std::string` site | Permanent DRAM cost; does not prevent exhaustion, only makes it survivable where caught | +| F | **Unify loss detection.** Raise the same overflow event on host RX full, scripts full, UART overflow events (`UART_FIFO_OVF` / `UART_BUFFER_FULL`) | Covers S6 and S7 with the existing purge/notify/Restart flow | Must make sure each site is allocation-free | +| G | **Machine-side action on overflow during a job**: send feed hold `!` automatically (position kept), or soft reset `0x18` (stops spindle, position lost) | Closes the S5 safety gap | Behavior choice belongs to the user; hold keeps the spindle running on grbl unless parking is configured | +| H | **Per-transport line-rate limiter** (token bucket, e.g. console ≤ N lines/s) | Cheap, prevents a flood from ever reaching memory pressure | Arbitrary rate; a legitimate fast sender (G-code streamed over telnet) would be throttled | +| I | **Do not forward console input to the CNC while a job runs** | Removes the job-purge risk from the most common flood source | Policy change; user stated that console forwarding is allowed by design | + +### 6.5 Recommendation (no code change yet) + +By priority. Each item needs a user decision before coding: + +1. **Measure S10 on BT hardware** (blocker): log free / largest + (`MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT`) at idle, during a job, and + during handwheel jog. If largest < 2048 B at baseline, the thresholds + must change before the mitigation can ship in BT variants. +2. **Do not latch on `system`-origin refusals** (S9). Drop the command and + warn; only transport refusals start an overflow episode. +3. **Two-level reaction (D)** to stop transient dips (S8) from purging a + running job. +4. **Unify loss detection (F)**: queue-full sites and UART overflow events + raise the same event (S6, S7). Replace the per-line `esp3d_log_e` of + `Script list is full` with a rate-limited warning. +5. **Decide the machine-side action (G)** on an overflow during a job (S5), + and whether the purge should also block pendant normal-priority sends + until Restart (S13). +6. **Decide on S16**: admit single-byte realtime safety commands even while + the input is closed (they cost one tiny message). +7. **Long term**: global budget (A) or static pools (C); optionally the + emergency pool (E) as defense in depth. + +--- + +## 7. Hypotheses to consolidate + +| Id | Hypothesis | Status | How to confirm | +|----|------------|--------|----------------| +| H1 | Exhaustion comes from the **sum** of bounded input queues, overhead included (§3.1 estimate ≈ 18-20 KB) | Inferred (consistent with the free heap and the logs) | During a paste test, log once per second: free / largest (8BIT), serial RX bytes + count, host RX bytes + count, scripts count. Expected: scripts reaches 50 and serial RX nears 4096 when free reaches ~6 KB | +| H2 | `bad_alloc` → `std::terminate` because `EMG_POOL_SIZE=0` | **Confirmed** (decoded backtrace, crash #2) | — | +| H3 | `MALLOC_CAP_INTERNAL` over-estimates usable heap | **Confirmed** (65 KB reported while allocations failed) | — | +| H4 | The dead state after the flood = lost `ok` + unbounded wait | **Confirmed** for step 5 (log `pushMsgToRxQueue failed for: `) | — | +| H5 | Restart did not recover because the host was never reset | Strong inference (user report + code) | Hardware test of the current build: after Restart, `$H` must work | +| H6 | 6144 / 2048 thresholds are adequate | WiFi: plausible; BT: **unknown** | S10 measurement | +| H7 | Earlier unexplained boot reboots share the same cause | Unverified | Read `Reset reason` (boot log / `[ESP420]` dev section) at the next occurrence | +| H8 | No periodic normal-priority polling exists that could trigger S9 on its own | FluidNC: `$G` / `$report_inches` are one-shot at startup; status uses auto-report or realtime `?` (high priority, bypasses the guard). grbl / grblHAL: same pattern seen, not exhaustively checked | Grep each target's `handle()` for periodic `ESP3DCommandType::normal` sends | + +--- + +## 8. Test plan for the current build + +1. **S1 paste test, WiFi FluidNC.** Expected: no reboot; one *Input + overflow* message; ERROR icon; console input ignored; Restart → status + back to Idle; `$H` works. +2. **Same test during a short SD job.** Observe what the machine does after + the purge (S5 input for decision G). +3. **Same test from telnet** (S2). +4. **BT variant:** baseline heap measurement (S10) **before** any flood test. +5. **Idle soak (30 min)** with WebUI page reloads while sending occasional + console commands: no spurious overflow expected (S8). + +--- + +## 9. Follow-up implemented (2026-10-21) + +User decisions: feed hold on an overflow during a job; pendant normal +commands blocked until Restart; realtime safety commands admitted while the +input is closed; reset of the saturated state manual only (Restart). + +| Audit item | Change | Situations | +|------------|--------|------------| +| 2 | `addRxData()` guard only drops (no flag, no input closure) | S9 ✅ | +| 3 | Two-level reaction in `rxAdmit()`: isolated refusal = drop; refusal within 500 ms of another admitted input line, or 3 refusals in 1 s = overflow | S8 ✅ (to validate with the soak test) | +| 4 | `esp3d_rx_overflow_raise()` on host RX queue full and scripts list full; `esp3d_rx_line_lost(origin)` at the 27 loss points of the 8 transports (queue full, oldest message evicted, allocation failure). `Script list is full` is now a rate-limited warning | S6 ✅ | +| 5 (G) | Feed hold `!` sent after the purge when a job was running (not paused) | S5 ✅ | +| 5 (S13) | While the input is closed, the host drops every non-realtime command that is not a CNC response, pendant commands included | S13 ✅ | +| 6 | `esp3d_rx_is_safety_realtime()`: `!` `~` `?` `0x18` `0x85` alone on a line pass `rxAdmit()` and the host while closed (heap permitting) | S16 ✅ | +| S11 | Notification carries free / largest heap after the purge | S11 ✅ | +| 1 | `[ESP420]` dev line `dbg:heap_8bit free/largest/min` for the BT baseline measurement | S10 ❓ measurement pending | + +Still open: + +- **S7** (UART driver ring overflow): not addressed. Detecting it needs the + UART event queue (`UART_FIFO_OVF` / `UART_BUFFER_FULL`), which the serial + client does not install today. +- **New finding, CNC responses evicted in BT mode.** BT serial / BT BLE (and + USB serial when it is the CNC link) evict the **oldest** RX message when + their queue is full. When that transport is the CNC link, an evicted `ok` + leaves the host waiting forever, the same dead state as timeline step 5. + `esp3d_rx_line_lost()` deliberately ignores the CNC link, so this is not + covered. +- **S4, S12, S14, S15, S17, S18**: unchanged (accepted or low probability). +- **Item 7** (global budget / static pools / emergency pool): long term. + +--- + +## 10. Code review after resync (2026-10-24) + +All mitigation hooks are still in place after the 2026-10-22/23 updates +(rxAdmit in the 8 transports, 27 loss points, host purge / feed hold / +notification / latch, Restart `resetAll()`). Two of those updates help the +recovery flow: + +- an unexpected `ok` no longer ends a single command that was not sent yet + (`_parseResponse()`, fixed 2026-10-23): stray acks after a purge are now + harmless; +- the welcome banner replays the startup sequence + (`resetStartupCommandsSent()`), so a Restart restores `$Report/Interval` + and the homing queries. + +Findings, most severe first: + +| # | Severity | Finding | Proposal | +|---|----------|---------|----------| +| R1 | High | **Only the Restart button resynchronizes the host after a soft reset.** The status screen STOP (`abort()` + `0x18`), the ALARM secondary reset, the change-tool reset, a `0x18` from a remote client (admitted while the input is closed) and a controller reboot all leave the host state as is. A single command in `wait_for_ack` (e.g. `$H`) then waits forever: status reports keep its timeout alive. Worse, after a controller reboot during a job the host keeps streaming the job into a reset controller; with homing disabled the job resumes from the middle of the file at a wrong position | Cause-based resync: when the welcome banner arrives (new controller session, whatever triggered it), the host drops its in-flight state (flow reset, current command, job aborted with an error). The Restart `resetAll()` stays for the overflow latch | +| R2 | Medium | Under the reserve, CNC status reports `<…>` are skipped. The `wait_for_ack` keepalive `?` and the flow-gate ping are answered by a status report, so if the heap stays low (leak, BT baseline) for 10 s the host declares a false link loss (`time_out`, `communication_lost`) | Add `<` to the vital CNC lines: status reports are the link liveness signal; each one is freed right after parsing | +| R3 | Medium | An isolated refused input line (two-level rule) is dropped with a warning log only: a console command typed during a low-memory period vanishes with no feedback on the pendant | Rate-limited local system message (at most 1 per 10 s): "Low memory: command dropped" | +| R4 | Low | A controller banner received while the input is closed replays the startup commands, which the host drops (S13 rule) | Accepted: Restart sends `0x18`, the banner comes back and the replay then succeeds | +| R5 | Low | The overflow notification is English-only (other pendant messages are translated fr/es/it) | Translation label (next free ID) + .lng packs | +| R6 | Low | `window_start_ms` / `window_refusals` in `rxAdmit()` are plain statics written by several transport tasks | Benign race (a count can be off by one); accepted | + +Still open from §9: S7 (UART driver ring overflow), CNC response eviction +when a BT / USB transport is the CNC link, S10 measurement. + +### Test status + +Nothing of §9 has been tested on hardware yet. Order: + +1. BT variant built with `--dev`: `[ESP420]` `dbg:heap_8bit` at idle, during + a job, during handwheel jog (S10, decides the thresholds for BT). +2. WiFi FluidNC paste test: one notification, ERROR icon, console ignored, + `!` still accepted from the console, Restart → Idle, `$H` works. +3. Paste test during a short SD job: machine goes to Hold (feed hold), then + Restart. +4. Single console command during a heap dip (WebUI page reloads): dropped + without purge (S8). +5. R1 reproduction (after its fix): `$H` then STOP on the status screen; and + controller reset button during a job. + +--- + +## 11. Follow-up implemented (2026-10-24) + +| Item | Change | +|------|--------| +| Critical alert screen (user design) | `ui_manager.registerScreen(type, screen, destructor)` stores each screen's `prepareForDestruction` (30 screens; `update_screen` has none and is never interrupted). Global transition signal `beginScreenTransition()` / `isScreenTransitionPending()` (set in `ESP3D_TRANSITION_START`, the 3 Pattern 3 `create()`, the firmware status component; cleared by `registerScreen()`; stale after 2 s). New value `critical_alert` (`"overflow:free=… largest=…"`). `criticalAlert` module (CNC display) opens a message box Error on top of the active screen, button = Recover (`resetAll()` + `0x18` + `?`), back to main. Waits while a transition is pending, during an update, or while a message box is open. The ERROR icon and the firmware status Restart remain as fallback | +| R1 | Welcome banner (fluidnc, grbl, grblHAL) → `requestControllerSessionReset()`; the host task applies it at the top of `handle()` and at the start of `sendStartupCommands()` (purge always before the startup replay): drops all host state, *Controller restarted: job aborted* if a job was running. Transport link (re)openings do not trigger it | +| R2 | Status reports `<…>` added to the vital CNC lines | +| R3 | Isolated drop → `esp3d_rx_isolated_drop_take()` → host posts *Low memory: command dropped* (warning, at most every 10 s) | +| R5 | Labels 116-119 (overflow title / message, command dropped, controller restarted) in fr / es / it / template; host notices use them (English fallback without display) | + +Not tested on hardware. Test additions to §10: + +- overflow while on the jog screen, a settings list, the keyboard, and with a + message box open (alert must wait for it): the alert opens, Recover + returns to main, `$H` works; +- R1: `$H` then STOP on the status screen (host must not stay blocked); + controller reset button during a job (job aborted message, no further + lines sent); +- R2: hold the heap below the reserve > 10 s (no false link loss). + +### Serial variant paste test (CNC on UART0) + +On the PiBot the serial variant has no console: UART0 **is** the CNC link +(`serial`, or `uart_ext` on the same UART, `UART_EXT_SAME_AS_SERIAL`), and +WiFi is off. Pasting into a PC terminal on UART0 therefore means **the PC +plays the controller**: the flood arrives from the output client, the case +the mitigation deliberately treats differently (the CNC link is never closed). + +Expected behavior: + +- no crash, no reboot, no task watchdog; +- **no** overflow alert and no input closure (by design); +- under the reserve, `Low memory: CNC lines skipped (acks kept)` warnings: + pasted lines are refused before allocation, except vital ones; +- pasted lines that look vital are processed as controller output: + `ok` / `error:` (flow credits, an `error:` can stop a stream), `<…>` + (status, positions), `ALARM:` (alarm state), and a `Grbl … [FluidNC` line + triggers a controller session reset (R1: host purge, startup replay); +- after the paste, reconnecting the real controller works without reboot. + +Build: production (or `ESP3D_LOG_BACKEND_DEV 1`, SD card), never the serial +log backend - dev logs would be written on the CNC link. + +--- + +## 12. Three distinct situations (2026-10-24) + +User rule: memory saturation, local buffer overflow and link loss are three +different problems. They may share mechanisms, but they are classified and +notified separately, every one with a notice. + +| Case | What | Reaction | Notice | +|------|------|----------|--------| +| A | General heap below the reserve: stability of the whole system at risk | Overflow episode (§4, §11): full purge, input closed, feed hold, critical alert, Recover | Critical alert + error message with heap figures | +| B | One queue full while the heap is fine: only that source's data | Localized purge of that origin's queued commands (`_purgeOrigin()`: RX/TX messages + scripts, now tagged with their origin); CNC link: flow reset + streams stopped (`ack_number`) | Non-blocking warning: *``: buffer full, lines lost (N)* / *CNC responses lost: stream stopped* | +| C | Link loss / corruption (cable, network, noise) | Existing connection management | Existing connection notices | + +Code changes: + +- `esp3d_rx_line_lost(origin)` classifies by the heap (A below the reserve, + else B) and applies to **every** client, the CNC link included: this + closes the open item "CNC responses evicted in BT mode" (now B on the CNC + link: the host can no longer wait forever for a lost `ok`). +- Host RX queue full and scripts list full use the same classification + (pendant commands during a heap dip: dropped only, S9). +- CNC link hard floor (3072 / 1024 B, to confirm with the S10 measurement): + below it even vital lines are refused and raise A. +- `ESP3DGcodeStream::origin` (propagated from the message by + `addStream(..., origin)`, default `no_client`), `purgeByOrigin()` now also + purges queued scripts of that origin. +- Labels 120 / 121. Translated labels carry no format specifier: the format + is fixed in the code, so a language pack can never alter it. + +Tests to add: a fast telnet / WebSocket sender while the heap is fine (B: +notice, only that source purged, SD job continues); a BT CNC flooding +responses (B on the CNC link: stream stopped, notice, no freeze). + +## 13. S7 implemented (2026-10-31) + +`ESP3DSerialClient` (serial and uart_ext) installs the UART driver with an +event queue (20 events) and `checkUartOverflow()` drains it at the top of +every `readSerial()`. Overflow = an `UART_FIFO_OVF` / `UART_BUFFER_FULL` +event, or, when the event queue was saturated (the driver then drops the +overflow events too), an RX ring found full. Reaction: `uart_flush_input()`, +current line dropped, bytes dropped up to the next end char (the broken +line), `esp3d_rx_buffer_lost(origin)` (case B: on the CNC link, flow reset +and streams stopped). `reconnect()` resets the event queue: overflows during +a manual pause concern purged data. Same reaction on the USB CDC device +client (driver RX overrun, partial write on the CNC link). Built, not +hardware-tested (release_plan.md a14 test list). + +## 14. S21: lines for the controller lost on the TX side (2026-10-31) + +Found by the 2026-10-31 audit "are overflows handled on every client?". The +RX side was covered on every transport (admission + `esp3d_rx_line_lost()`; +USB-OTG, BT SPP, TCP and the BLE link layer are lossless below the client; +serial and USB CDC driver overruns handled since S7). The **TX side on the +CNC link was not**: a write error or a full TX queue dropped the line with a +log only, on BT serial (any error but `ESP_FAIL`), BLE (chunk write error), +socket client (`sendToSocket()` failure, e.g. EAGAIN timeout while the +connection survives), WebSocket client, USB-OTG (`tx_blocking()` failure) and +serial (TX stalled 500 ms). The controller never answers a line it did not +receive: the host could wait forever or miscount its credits. + +Fix: `esp3d_tx_line_lost(client)` (allocation-free, any task) called at every +such point; it only acts when that client is the CNC output client +(monitoring copies keep their own drop policy). The host task consumes it +(`esp3d_cnc_tx_lost_take()`) with the same reaction as lost CNC responses +(`_cncResponsesLost()`: flow reset, streams stopped with an error) and its own +notice, label 122 *Lines to CNC not sent: stream stopped*. A real +disconnection stays connection management (case C); "not connected, +discarding" paths are not reported. Built, not hardware-tested; the +WebSocket client is not compiled by any variant (not build-checked). diff --git a/docs/ongoing_reflection/screenshot_automation.md b/docs/ongoing_reflection/screenshot_automation.md new file mode 100644 index 00000000..fd4e62b2 --- /dev/null +++ b/docs/ongoing_reflection/screenshot_automation.md @@ -0,0 +1,81 @@ +# Documentation screenshots — capture workflow + +> Status: **implemented, not tested on hardware** (2026-11-11). +> Scope: **dev builds only** — `[ESP216]` exists only with +> `ESP3D_SNAPSHOT_FEATURE`, which `cmake/dev_tools.cmake` forces to 0 in +> `PROD_BUILD`. + +## 1. Goal + +The number of screens × views × button levels × firmwares × resolutions makes +the screenshots of the user documentation hard to keep up to date. The goal is +a repeatable session that produces every file with its **final name**, so that +the documentation does not change. + +## 2. Chosen design: user-driven, script-guided + +The firmware does not navigate by itself: **the user sets the pendant in each +state**, the PC script only names and triggers the captures. + +1. `tools/user-docs/snapshot_capture.py` prints the next entry of + `tools/user-docs/screenshots.json` (file name + description). +2. The user puts the pendant on that screen / view / button level and presses + Enter. +3. The script sends `[ESP216]SNAP name= json=yes`, waits for the answer, + then shows the next entry (`s` skip, `r` retake previous, `q` quit, + `--start ` to resume). + +Firmware impact: one optional parameter on `[ESP216]` (§3). No change to the +screens, the screen manager or the gcode host. + +Usage: [tools.md — `tools/user-docs/`](../guides/tools.md#toolsuser-docs). + +## 3. `[ESP216]` `name=` parameter + +``` +[ESP216]SNAP [name=] json= pwd= +``` + +- `name=` present → `/screenshots/.raw` on the SD card (folder created + when missing, existing file overwritten so a capture can be retaken). +- `name=` value: letters, digits, `_`, `-`, 1–64 characters (no path, no + extension) — anything else is rejected with an error, so the file always + lands in `/screenshots/`. +- `name=` absent → unchanged behavior, `/snapshot.raw`. +- The capture is synchronous: the answer is sent once the file is written, + which is what the script waits for. + +## 4. Transport + +Use the link that is **not** the CNC link: + +- CNC on serial (default SKU: serial CNC + WiFi remote) → telnet. +- CNC on WiFi → the serial port (UART0 is free), or USB-CDC on S2/S3. + +Screens that only exist with one transport (WiFi scan, server scan, BT scan, +output selector variants) are captured in a second session on the other +variant; skip them with `s` in the first one. + +## 5. `screenshots.json` + +Initial content generated from the images referenced by +`docs/user documentation/user_doc/user_documentation.md` (order of the +document, description = section heading + alt text), plus the new captures +listed in [a14_user_doc_screenshots.md](a14_user_doc_screenshots.md). The +descriptions are meant to be edited by hand (what to show, which view, which +button level, lock state…). + +Not in the list: `status_screen_workspace` (obsolete) and the files of +`images/screens/` that the document does not reference. + +## 6. Rejected alternative (kept for reference) + +A fully automatic run (`[ESP216]` with `screen=` / `view=` / `buttons=` / +`wait=`, scenario file streamed by `[ESP700]`) was studied: it needs an +asynchronous capture on the LVGL task, a new wait state in the gcode host (the +host task also processes CNC RX and polling, so `[ESP216]` must not block it), +and a preset function per multi-state screen (like +`statusScreen::setInitialState()`). Rejected for now: large firmware impact, +and flow-driven screens (probe, change tool) or popups could not be reached +anyway. The user-driven workflow covers every screen with a one-parameter +change. diff --git a/docs/ongoing_reflection/small_display_dashboard_and_ui_tiers_study.md b/docs/ongoing_reflection/small_display_dashboard_and_ui_tiers_study.md new file mode 100644 index 00000000..d43a8743 --- /dev/null +++ b/docs/ongoing_reflection/small_display_dashboard_and_ui_tiers_study.md @@ -0,0 +1,261 @@ +# Small display dashboard (172x320) and UI tiers study + +**Date:** 2026-10-30 +**Status:** study agreed with the user; no implementation yet +**Related:** `usb_device_cdc_client_study.md` (same first test board), `docs/architecture/screens_architecture.md`, `docs/architecture/display_drivers.md`, `docs/ui_resources/development.md` + +## 1. Goal + +Support 1.47" 172x320 displays as an **informative dashboard**, not as an interactive pendant. + +Target product: a **WiFi bridge** to the CNC controller. Remote control and SD file streaming +go through the WebUI; the display shows what is happening. Touch is a **bonus**: the dashboard +must be 100% usable without it. + +## 2. Boards + +Two separate board directories are required: different display controllers and different pinouts. + +| Board | Display | Touch | Board directory | +|---|---|---|---| +| Waveshare ESP32-S3-Touch-LCD-1.47 | JD9853, SPI (CLK 38, DIN 39, CS 21, DC 45, RST 40, BL 46) | AXS5106L, I2C (SDA 42, SCL 41, RST 47, INT 48) | `boards/ESP32_S3_TOUCH_LCD_1_47` (exists, headless today) | +| Waveshare ESP32-S3-LCD-1.47B | ST7789 (not named on the schematic, to confirm), SPI | none | `boards/ESP32_S3_LCD_1_47B` (created 2026-10-31, headless + `16mb_wifi_fluidnc_display_test`, driver `hardware/common/drivers/disp_st7789` = SPI wrapper around ESP-IDF `esp_lcd_new_panel_st7789`). Confirmed on hardware 2026-11-04 with the replacement unit: display test (colors, inversion ON, 34 px offset, vertical alignment, backlight 48; row 0 = side opposite the USB-C), small UI tier dashboard (same LVGL wiring as the Touch board, no touch, BOOT = page button), USB CDC device, WiFi AP, SD 4-bit at 20 MHz. The first unit was probably not dead: after an esptool flash over native USB the chip can stay in download mode until RESET is pressed. The `_display_test` variants of both 1.47 boards were removed after validation; the `BOARD_DISPLAY_TEST` code stays in `board_init.c` (build with `-D BOARD_DISPLAY_TEST=ON` to run it again) | + +Touch-LCD-1.47 pins come from the existing `board_config.h` header comment (ESP3D 3.x platformio +env `waveshare_s3_touch_lcd147`, tested on hardware). No JD9853 or AXS5106L driver exists in the +repository: both are new. + +### 2.1 ESP32-S3-LCD-1.47B pinout (from `to_port/1.47inch_Touch_LCD_Demo_ESP32/ESP32-S3-LCD-1.47B_schematic_diagram.pdf`) + +| Function | GPIO | +|---|---| +| LCD RST / CLK / DC / CS / DIN | 39 / 40 / 41 / 42 / 45 | +| LCD backlight (MOSFET, PWM capable) | 46 on the schematic, **48 on the user's board** (board pinmap, 2026-10-31: 46 does not light it; the schematic may be another revision). 48 matches the Waveshare ESP32-S3-LCD-1.47 wiki and is confirmed on hardware (2026-11-04) | +| SD 4-bit SDIO: CLK / CMD / D0 / D1 / D2 / D3 | 14 / 15 / 16 / 18 / 17 / 21 | +| UART TX / RX | 43 / 44 | +| WS2812B RGB LED | 38 | +| QMI8658 IMU SDA / SCL / INT1 / INT2 | 48 / 47 / 13 / 12 | +| Battery ADC (ETA6098 charger on board) | 1 | +| BOOT key | 0 | +| Native USB D- / D+ | 19 / 20 | + +USB-C VBUS feeds the board through diode D1 (MBR230) to VSYS. The board most likely **cannot output +5 V on VBUS** for a USB host role (to confirm, see §3). + +### 2.2 Reference driver code (`to_port/1.47inch_Touch_LCD_Demo_ESP32/`) + +The demo targets the **bare "1.47inch Touch LCD" module** wired to a generic ESP32-S3 (demo pins: +LCD SCLK 1, MOSI 2, CS 39, DC 41, RST 40, BL 6; touch SDA 15, SCL 7, RST 16, INT 17; 2 MB flash). +Its pins are NOT the integrated board pins; only the driver logic is reused. + +- **JD9853** (`esp_lcd_jd9853`): standard `esp_lcd` panel driver (Espressif template) with a + vendor init sequence. Settings used by the demo in portrait: `set_gap(34, 0)`, color inversion ON, + RGB element order, 16 bpp, LVGL byte swap, SPI 80 MHz. Implemented as + `hardware/common/drivers/disp_jd9853` with the `disp_st7796` layout (panel file + SPI wrapper + + config header). The vendor init sequence and the orientation table (mirror bits, RAM offset + moving to Y when X/Y are swapped) are kept from the Waveshare reference; the offset is a config + field (`display.col_offset`, 34 for 172x320). Only RGB565 is supported (the vendor sequence forces + COLMOD 0x05). +- **AXS5106L** (`esp_lcd_touch_axs5106`), I2C address 0x63, no init and no firmware upload, only a + reset pulse on RST. Read 14 bytes from register 0x01: `points = data[1] & 0x0F`, + `x = (data[2] & 0x0F) << 8 | data[3]`, `y = (data[4] & 0x0F) << 8 | data[5]`. Portrait needs + `mirror_x`. + Implemented as `hardware/common/drivers/touch_axs5106` (same public API shape as + `touch_ft6336u`) on the **new** I2C master API, without the `esp_lcd_touch` component: the board + creates the bus and passes the handle in the config. The rest of the repository still uses the + legacy API and both cannot be linked in one firmware, see + `docs/roadmap/i2c_new_api_migration.md`. Demo defects not copied: the write function returns + nothing, I2C errors are ignored, the device handle is a global. + The register write and the data read must be two transactions (STOP in between, as in the + demo): with `i2c_master_transmit_receive` (repeated start) the touch did not work. + +**Hardware bring-up (2026-10-31, 1.47 touch board, `BOARD_DISPLAY_TEST` variant):** confirmed +LCD pins (CLK 38, DIN 39, CS 21, DC 45, RST 40, BL 46), colors and inversion, 34 px column offset, +vertical alignment, touch wiring SDA 42 / SCL 41 / RST 47 (INT 48 not used, polling). The glass +corners are rounded: corner pixels are not visible. Touch-to-display mapping in portrait confirmed +(`invert_x` only, as in the demo). + +Known trap for 172-pixel-wide panels: a column offset (typically 34 px on ST7789 172x320) must be +applied in the driver, otherwise the image is shifted or shows garbage. + +The BOOT button (GPIO0) is usable as an input once the board has booted: it gives a minimal +interaction (page change) on both boards, including the one without touch. + +## 3. Open hardware point: USB role + +The ESP32-S3 has a single USB OTG controller, so the native USB-C port has **one role per build +variant**: + +- **USB host** to the CNC controller (WiFi bridge use case, `USB_SERIAL_SERVICE`), or +- **USB device** to a PC (`USB_CDC_DEVICE_SERVICE`, see the USB CDC study). + +The current `board_config.cmake` forces `USB_SERIAL_SERVICE OFF` (device role only). The host +variant must be added as an alternative, not mixed with the device role. + +To verify on the Waveshare schematic: many CNC boards power their USB-UART bridge (CH340, CP2102) +from the cable VBUS. The ESP32 board must then **output 5 V on VBUS**, or a powered OTG adapter is +needed. + +## 4. UI tiers architecture + +### 4.1 Principle + +The **UI tier** (layout philosophy) is separated from the **resolution** (pixel assets and +positions). Three mutually exclusive tiers: + +| Flag | Directory | Target | +|---|---|---| +| `ESP3D_UI_SMALL` | `small_ui/` | 1.47" dashboard (172x320), informative | +| `ESP3D_UI_MEDIUM` | `medium_ui/` | current pendant UI (320x240 to 800x480) | +| `ESP3D_UI_BIG` | `big_ui/` | future UI adapted to 7" displays | + +### 4.2 The tier is chosen by the board, not derived from the resolution + +Four boards share `res_800_480`: esp32s3_8048s043c (4.3"), esp32s3_8048s050c (5"), +esp32s3_8048s070c and esp32s3_8048_touch_lcd_7 (7"). Only the 7" ones are meant to get the big UI. +Therefore: + +- each `board_config.cmake` sets the tier, as it sets `RESOLUTION_SCREEN` today; +- resolution directories live **under each tier** (a big 800x480 layout differs from a medium one); +- `cmake/sanity_check.cmake` enforces exactly one tier with `check_single_selection` (same pattern + as `FIRMWARES_LIST`), and checks that the tier + resolution combination exists. + +### 4.3 The tier applies at every display level + +`main/CMakeLists.txt` assembles the UI on three levels, each with `components/`, `screens/` and +`res_XXX/`: common (`display/`), family (`display/cnc/`) and firmware (`display/cnc/fluidnc/`). +The pendant screens (status, jog, probe, ...) live in the family and firmware levels, so the tier +split must exist at every level: + +``` +display/medium_ui/{components,screens} +display/cnc/medium_ui/{components,screens,res_320_240,...} +display/cnc/fluidnc/medium_ui/{components,screens,res_...} +display/small_ui/{components,screens} +display/cnc/small_ui/{screens,res_172_320} (likely one CNC screen, no per-firmware code) +``` + +Tier-independent code stays at the root of `display/`: `esp3d_ui.cpp`, styles, translations, +`ui_resources` access, `critical_alert`, and the screen transition engine. + +### 4.4 Couplings to cut + +Code outside the screens includes screen headers directly: + +- `main/display/esp3d_x_ui.cpp:41` includes `screens/update_screen.h`; +- `main/core/esp3d_x.cpp:49` includes `screens/update_screen.h`. + +Each tier must provide the same entry points (splash, update screen, switch to main screen). + +### 4.5 Impact on ui_resources tooling (deferred to the big UI) + +The kit, UI Studio and `generate_resources.py` are keyed by resolution today. With +`big_ui/res_800_480` next to `medium_ui/res_800_480`, the key becomes tier + resolution. This is the +widest impact; it is done when the big UI starts, not before. + +## 5. Small UI dashboard content + +### 5.1 Base features (no touch) + +| Area | Content | +|---|---| +| Network | STA/AP mode, SSID, RSSI bars, **IP in large font**, hostname / mDNS name | +| CNC link | Connection status (U/T/C/?/A), transport (USB / serial), detected firmware (FluidNC / grblHAL) | +| Machine state | Idle/Run/Hold/Alarm/Door/Home with color coding, alarm code | +| Activity | Streamed file name, progress %, elapsed / remaining time; or "WebUI client connected" | +| Last message | Last error / alarm as a temporary banner | +| QR code | WebUI URL; in AP mode, **WiFi join QR code** (needs `LV_USE_QRCODE 1` in the board `lv_conf.h`) | +| Pages | Status / Positions (WPos XYZ, feed, spindle) / Network; BOOT button cycles pages, optional auto-rotation | + +Backlight timeout reuses `activity_monitoring`. + +### 5.2 Bonus features (touch boards only) + +- Swipe between pages, tap to show the QR code, brightness setting. +- Job control: Pause / Resume (`!` / `~`); **Stop only with hold-to-confirm** (accidental touches + are frequent on a 1.47" screen). +- `$X` unlock and soft reset with the same hold-to-confirm. +- Possibly "restart last file". A full SD file list stays in the WebUI (too narrow at 172 px). +- **No jog**, on purpose: too small, safety risk, no handwheel. + +### 5.3 Rules + +- All data comes from `ESP3DValues` observers (change-only notifications), with throttled updates. +- The small UI reuses theme tokens, fonts and icons from the `ui_resources` partition. +- Both boards have 8 MB PSRAM, but any shared code added must stay valid for the worst memory + configuration (see `CLAUDE.md`, memory constraints). + +## 6. Implementation plan + +1. **Display driver bring-up** (JD9853) and LVGL showing a label. + Check: correct rendering on hardware, no color drift, no offset. +2. **Tier flags + small UI only**: new `small_ui/` directories; the medium tier keeps its current + paths (no file moved). + Check: all existing boards build unchanged; ESP32_S3_TOUCH_LCD_1_47 builds with the dashboard. +3. **Read-only status screen** wired on `ESP3DValues`, throttled. + Check: network, CNC link and machine state displayed correctly on hardware. +4. **Pages, BOOT button, QR codes.** +5. **Touch driver** (AXS5106L) and touch actions with hold-to-confirm. +6. **Second board** ESP32-S3-LCD-1.47B (ST7789, no touch). +7. **Move the medium UI into `medium_ui/`**, pure move with no code change. + Check: every board rebuilds identically. (Use `git mv` on the user side to keep history.) +8. **Big UI** later, together with the ui_resources tooling change (§4.5). + +### 6.1 Small tier wiring as implemented (2026-10-31, steps 1-2, label screen confirmed on hardware) + +Decision: the small tier uses **built-in LVGL fonts (Montserrat) and LVGL symbols only**, no +`ui_resources` partition (a boot splash is the only foreseeable image). Consequences: + +- The board selects the tier in `board_config.cmake` with `set(UI_TIER "SMALL")` (plus + `TFT_UI_SERVICE ON`). Unset = current pendant UI, unchanged. `cmake/sanity_check.cmake` rejects any + other value and SMALL without `TFT_UI_SERVICE`. +- `cmake/features.cmake` defines `ESP3D_UI_SMALL` (and `ESP3D_TOUCH_FEATURE` if touch) but **not** + `ESP3D_DISPLAY_FEATURE`: in core code that macro means "pendant UI" (translations, update screen, + screen commands, ~40 files), so a small-tier board is headless for the core (log-only update + callback). No medium flag exists yet; it comes with step 7. +- `main/CMakeLists.txt` compiles only `display/small_ui` for the small tier (no translations, no + rendering client, no pendant screens). +- `main/core/esp3d_x.cpp` starts `esp3dSmallUi.begin()` where the pendant UI starts `esp3dXui`. +- `display/small_ui/esp3d_small_ui.cpp`: one LVGL task (core 1) that also runs + `esp3dXValues.handle()`, so value callbacks run in the LVGL context, as in the pendant UI. +- The BSP initializes the panel, touch and LVGL (`board_init()`), and exposes `get_lvgl_display()` + and `get_lvgl_lock()`. Board files: `lv_conf.h` (Montserrat 14 default + 28, `LV_MEM_SIZE` 32 KB), + `CONFIG_LV_CONF_SKIP=n` in the board sdkconfig (LVGL 9.6 ignores `lv_conf.h` otherwise). +- `BOARD_DISPLAY_TEST` turns the UI off (it drives the LCD itself). + +### 6.2 Dashboard content as decided with the user (2026-10-31, steps 3-4) + +Replaces the §5.1 wish list for the 1.47 boards: + +- Fonts: Montserrat 20 minimum (14 is barely readable on the 1.47" glass), 28 for large values. +- **Page 1**: top-left icon = remote access available to reach the board (`LV_SYMBOL_WIFI` = STA + connected, text "AP" = own access point, `BLUETOOTH`; radio access has priority since the board + can be reached that way), `LV_SYMBOL_USB` = USB CDC client connected, shown only without radio + access, `LV_SYMBOL_WARNING` if none; top-right = network state: STA → `LV_SYMBOL_OK` / `LV_SYMBOL_CLOSE`, + AP → number of connected stations (`esp_wifi_ap_get_sta_list`, orange if 0 = setup state, not an + error, green otherwise); + IP below (shown as soon as the AP runs, even without station). + Activity: job (`job_status`/`job_progress`/`job_filename`) or update (`update_progress`/ + `update_status`, has priority) as title + arc with the % in the center; idle shows name + version. +- **No machine / firmware state** (no interaction possible) and no CNC link indicator: the core + connection tracking stays display-only (`ESP3D_DISPLAY_FEATURE`), no core change. +- **Page 2**: SD card accessible and network name (SSID from `esp_wifi_get_config`). SD state from + `sd.getState()`, which is not a passive read (it remounts the card unless busy): queried only on + page entry, outside the LVGL lock. `busy` is shown as accessible (mounted, in use by another task, + e.g. the SD log backend of dev builds writes every 200 ms). +- **Page 3**: TBD, optional; the page button cycles back to page 1 meanwhile. +- Page button: BOOT key (`UI_PAGE_BUTTON_PIN` in the board `board_config.h`, GPIO0), polled and + debounced in the UI task. +- Findings: `current_ip` is declared but never set (IP read from `esp3dNetwork`); link / network + state has no value notification (polled every 1 s with change detection); the headless update + callback in `esp3d_x.cpp` also sets `update_progress` / `update_status` for the small tier. + +Documentation is updated at each step: `screens_architecture.md`, `display_drivers.md`, +`ui_resources/development.md`, `CLAUDE.md` documentation index. + +## 7. Open questions + +- USB role of the bridge variant (host to CNC) and VBUS 5 V output (§3). +- ~~ST7789 1.47B pinout to be confirmed from the Waveshare documentation.~~ Done 2026-11-04: the + Waveshare ESP32-S3-LCD-1.47 wiki gives the LCD and SD pins of §2.1 (BL 48), all confirmed on + hardware. diff --git a/docs/ongoing_reflection/sound_customization_design.md b/docs/ongoing_reflection/sound_customization_design.md new file mode 100644 index 00000000..34d41d17 --- /dev/null +++ b/docs/ongoing_reflection/sound_customization_design.md @@ -0,0 +1,304 @@ +# Sound customization — design draft + +Status: **phases 1 and 2 implemented** (2b: SD kit, manifest rebuild, user docs) (engine, API, tone backend, +`sounds` blob, `/esp3dsound.ini` SD update, board overlay) — the as-built +reference is `docs/architecture/sound_system.md`, which supersedes §5–§7 +below where they differ (as built: `notes = off` mutes since the ini parser +drops empty values, several `notes =` lines per event, 1640-byte partition +slot for 24 events). Remaining: phase 3 (audio backend). + +## 1. Goals and constraints + +- Every UI sound becomes user-customizable (notes, durations), stored in the + `ui_resources` partition next to the theme palettes, updatable from SD + (`/esp3dsound.ini`) like `/esp3dtheme.ini`. +- Each sound can be individually muted (0 notes). The global on/off setting + (`esp3d_buzzer_on`) is kept. +- Hard per-sound limits (note count, total duration) are enforced **by the + firmware**, not by the data: a bad ini or blob can never freeze the UI. +- **No sound may block the LVGL task.** Today `buzzer_bip()` calls + `vTaskDelay(duration)` inside UI callbacks (ERROR/LOCK freeze the UI 200 ms). +- **No heap at play time.** Today `buzzer_play()` mallocs a tone copy and + creates a 2 KB-stack task per melody, and refuses to play while another + melody runs. +- **All sound code isolated in `main/modules/buzzer/`** behind a semantic API: + callers say *what happened* (`error`, `back`, …), never *how it sounds* + (frequency, duration, file). This is what makes a future MP3 backend + transparent to the rest of the firmware. + +## 2. Current inventory (to be preserved as defaults) + +Defined as macros in `main/display/esp3d_ui.h`. + +| Event | Current sound | Call sites | Usage | +|---|---|---|---| +| `selection` | 523 Hz / 50 ms | 101 | button press / validation | +| `forward` | 500 Hz / 20 ms | 18 | encoder step forward | +| `backward` | 600 Hz / 20 ms | 17 | encoder step backward | +| `active_item` | 600 Hz / 100 ms | 23 | value chosen in a list | +| `back` | 300 Hz / 50 ms | 31 | leave screen | +| `response_no` | 262 Hz / 100 ms | 8 | "No" / cancel in dialogs | +| `error` | 100 Hz / 200 ms | 44 | error (command refused, alarm, failure) | +| `lock` | 100 Hz / 200 ms | 11 | action blocked (lock, machine busy) | +| `wakeup` | C5 50, E5 50, G5 80 | 1 | screen wake-up | +| `success` | C5 100, E5 100, G5 200 | 1 | update finished | +| `startup` | 8 notes, ~1.3 s | 1 | splash screen | + +`ESP3D_TICK_BEEP` (440 Hz / 15 ms) was originally the encoder click; it has +been superseded by `forward` / `backward` (one pitch per direction) and has no +call site left. It is **removed** in phase 1 (no event). + +New default for `lock` (distinct from `error`): two short low notes, +`150:80, 0:40, 150:80` (200 ms total, same length as today). + +New event `unlock` (user lock released; previously `response_no` or +`selection` depending on the screen): rising variant of `lock`, +`150:80, 0:40, 300:80`. + +## 3. Architecture + +``` + UI screens / components / commands + │ ESP3D_*_BEEP / ESP3D_*_SOUND macros (unchanged names) + ▼ + ┌────────────── main/modules/buzzer/ ─────────────────┐ + │ esp3d_sound.h public API (events, enable, mute)│ + │ esp3d_sound.cpp engine: priority, preemption, │ + │ sequencing, limits, definitions │ + │ backend interface ─┬─ tone backend (LEDC buzzer) │ + │ └─ mp3 backend (future) │ + └─────────────────────────────────────────────────────┘ + │ + hardware/common/drivers/buzzer (LEDC, unchanged API) +``` + +### 3.1 Public API (`esp3d_sound.h`) + +```cpp +enum class ESP3DSoundEvent : uint8_t { + selection, forward, backward, active_item, back, response_no, + error, lock, wakeup, success, startup, unlock, + count +}; + +class ESP3DSound final { + public: + bool begin(); // load definitions, init backend + void end(); + bool enabled(bool fromSettings = false); + void enable(bool enable = true, bool toSettings = false); + void play(ESP3DSoundEvent event); // non-blocking, any task, never fails loudly + esp_err_t playTone(uint16_t freq_hz, uint16_t duration_ms); // [ESP250] raw tone + void stop(); + uint32_t muteAndSave(); // replaces saveSoundStateAndDisable() + uint32_t restoreMute(); // replaces restoreSoundState() +}; +extern ESP3DSound esp3d_sound; +``` + +- `play()` returns `void`: a sound is best-effort feedback, no caller should + branch on it. +- The macros in `esp3d_ui.h` keep their names (280 call sites untouched) and + become **single statements**: `#define ESP3D_ERROR_BEEP esp3d_sound.play(ESP3DSoundEvent::error);` + (today they expand to two statements — unsafe in a braceless `if`). +- `saveSoundStateAndDisable()` / `restoreSoundState()` (currently in + `esp3d_ui.cpp`) move into the module; `ESP3D_SAVE_SOUND_STATE_AND_DISABLE` + / `ESP3D_RESTORE_SOUND_STATE` keep their names. +- `Buzzer` / `esp3d_buzzer` are renamed or wrapped; external users today: + `esp3d_x.cpp` (begin), `esp401.cpp` / `esp910.cpp` (begin), `esp250.cpp` + (bip), `settings_screen.cpp` (enable toggle), `esp3d_ui.cpp` (mute stack). + +### 3.2 Engine — no task, no queue, no heap (recommended) + +Instead of a persistent task + queue, the engine is driven by **one static +one-shot `esp_timer`**: + +1. `play(event)` takes a short mutex, applies the priority rule (§3.3), sets + `current = &definitions[event]`, `index = 0`, starts note 0 via the backend + (LEDC freq + duty, non-blocking), arms the timer for its duration. +2. Timer callback (runs in the existing `esp_timer` task): stops the note, + advances `index`, starts the next note or ends the sequence. A 10 ms gap + between notes is kept (same as today's play task). + +Why rather than a dedicated task + queue (option validated earlier, same +intent): + +- zero extra stack (a task costs ≥ 1.5–2 KB of static DRAM forever; this + matters in BT mode); +- preemption is trivial (overwrite `current`), no queue draining; +- definitions are read in place (const, from the mmapped partition or the + compiled defaults) — no copy. + +The LEDC calls (`ledc_set_freq`, `ledc_set_duty`, `ledc_update_duty`) are +task-context safe; `esp_timer` callbacks run in task context +(`ESP_TIMER_TASK` dispatch), never in ISR. + +If a future backend needs its own task (I2S MP3 decoding), that task belongs +to the backend, not to the engine. + +Rules for the timer callback (it shares the `esp_timer` task — Core 0, +`CONFIG_ESP_TIMER_TASK_STACK_SIZE=2048` — with the LVGL tick timer of +`board_init.c`, so a slow callback delays `lv_tick` and every other timer): + +- **no LVGL call**, ever (LVGL is not thread-safe and lives on Core 1); +- **no blocking**: no mutex wait, no `vTaskDelay`, no flash/SD access, no + backend call that can block — engine state is protected by a `portMUX` + spinlock held only around the few state fields, LEDC calls are made + outside it; +- **no `esp3d_log`** in the hot path (formatting eats the 2 KB stack); + logs only on error; +- callback cost: a few µs (two LEDC register updates + re-arm). + +### 3.3 Priority and preemption + +Each event has a fixed priority class (compiled, not user-editable): + +| Class | Events | Priority | +|---|---|---| +| Encoder | forward, backward | 0 | +| Interaction | selection, back, active_item, response_no | 1 | +| Alert | error, lock, unlock | 2 | +| Event | wakeup, success, startup | 2 | + +Rule: a new sound **preempts** the current one if its priority is ≥ the +current one; otherwise it is dropped. So an error is never cut by an encoder +tick, and fast encoder turns restart the click instead of piling up. + +### 3.4 Backend interface + +```cpp +struct ESP3DSoundBackend { + bool (*begin)(); + void (*end)(); + // Start one step of an event's definition; returns its duration in ms + // (0 = backend handles timing itself, e.g. an mp3 track). + uint32_t (*start)(ESP3DSoundEvent event, const ESP3DSoundNote *note); + void (*stop)(); +}; +``` + +- **Tone backend** (now): `start()` = LEDC freq + 50 % duty, returns + `note->duration_ms`; `stop()` = duty 0. Uses + `hardware/common/drivers/buzzer` (its blocking `buzzer_bip()` and + malloc-based `buzzer_play()` are removed from that driver; the Factory + apps have their own `buzzer.c` copies and are unaffected). +- **Audio backend** (future, first candidate: `esp32s3_hmi43v3`; no driver + yet, file format and storage location **not decided**). Only the generic + entry points are fixed now: + - the engine passes the **event ID** to every backend; how an event is + resolved to audio (file path, track number, format MP3/WAV/…) is the + backend's private business and is not part of the engine, the API or the + `sounds` blob; + - `start()` returning 0 means "the backend times itself"; it then reports + the end of playback through `esp3d_sound_backend_done()` so the priority + rule keeps working; + - an event the backend cannot play (missing file, …) falls back to its tone + definition when the board also has a buzzer, otherwise stays silent; + - the stable, user-visible key for an event is its **name** + (`selection`, `error`, …) — the same names as the ini sections, so a + future file-based backend can reuse them (e.g. `/.`) + without new conventions. +- Backend selection: compile-time per board (`board_config.cmake`), e.g. + `ESP3D_SOUND_BACKEND tone|mp3`. No runtime switching. + +## 4. Limits (enforced at load, firmware-side) + +| Class | Events | Max notes | Max total duration | +|---|---|---|---| +| Encoder | forward, backward | 1 | 40 ms | +| Interaction | selection, back, active_item, response_no | 2 | 150 ms | +| Alert | error, lock, unlock | 5 | 800 ms | +| Event | wakeup, success | 5 | 1000 ms | +| Startup | startup | 16 | 3000 ms | + +- Frequency: 100–5000 Hz, or `0` = rest (silence). +- 0 notes = event muted. +- Out-of-limit definition: truncated to the limit (extra notes dropped, last + note shortened) and a warning logged. Never rejected wholesale. + +## 5. Storage — `sounds` blob in `ui_resources` + +One fixed-size blob, ID `djb2("sounds")`, riding in the font directory like +the 4 theme palettes (same `FontDirEntry`, read via +`esp3d_resources_get_blob()`, written via `esp3d_resources_write_blob()`). + +``` +offset size field +0 4 magic "SND1" +4 1 version (1) +5 1 event count (12) +6 2 reserved +8 12 × 68 B event slots, in ESP3DSoundEvent order: + u8 note_count + u8 reserved[3] + 16 × { u16 freq_hz, u16 duration_ms } (LE) +``` + +Total 824 bytes. Fixed 16-note slots for every event keep the layout trivial +and the blob size constant (SD updates never relocate it); the per-class +limits of §4 apply on top. + +Fallback: compiled-in defaults (current sounds, §2) when the blob is absent, +has a bad magic/version, or a different event count. + +Single source of defaults: `resources/sounds/sounds_default.ini`, generating +both the blob and the fallback header (same pattern as +`themes_default.ini` → palettes + `esp3d_theme_palettes.h`). + +## 6. ini format + +```ini +# notes = comma-separated freq:duration_ms +# freq = Hz or note name (C4..B7), 0 = rest; empty = muted +[selection] +notes = C5:50 + +[error] +notes = 100:200 + +[startup] +notes = E5:150, E5:150, 0:75, E5:150, 0:75, C5:150, E5:300, G5:300 + +[forward] +notes = +``` + +Partial files are allowed (section by section), same overlay semantics as +`esp3dtheme.ini`. + +## 7. Update paths + +- **SD**: `/esp3dsound.ini` → new `ESP3DUpdateType::sounds = 7`. Parsed via + `ESP3DConfigFile`, merged on the current blob, written with + `esp3d_resources_write_blob()`, renamed `.ok`/`.bad`, reboot. Priority + order: after `language_packs`, before `resource_patches`. +- **Board overlay**: `boards//resources/sounds/esp3dsound.ini` + (partial, like `themes/esp3dtheme.ini`). +- **Rebuild / kit**: `generate_resources.py`, the JSON manifest and + `ui_resources_kit` get a sounds entry, mirroring the theme palettes. + +## 8. Implementation phases + +1. **Engine + API** (no visible change except that sounds no longer block): + `esp3d_sound` module, esp_timer engine, tone backend, compiled defaults, + macros rewired, mute stack moved into the module, `[ESP250]` on + `playTone()` (and fix its inverted result check: `!esp3d_buzzer.bip()` + tests an `esp_err_t`, so it reports an error on success), `TICK_BEEP` + removed, new `lock` default. + Verify: build all SKUs; on hardware, UI stays responsive during + error/lock, the startup melody plays, the encoder clicks still play during + fast turns. +2. **Customization**: blob + ini + generator + SD update + kit + docs. + Verify: custom `/esp3dsound.ini` applied, out-of-limit values truncated, + muted event silent, missing blob falls back to defaults. +3. **MP3 backend** (future, board-dependent). + +## 9. Decisions and open questions + +Decided (2026-10-07): +- `TICK_BEEP` removed (superseded by `forward` / `backward`). +- `lock` gets a distinct default (§2). +- Audio backend: only the generic entry points are fixed now (§3.4); driver, + format and file location to be designed with the `esp32s3_hmi43v3` port. +- UI Studio sound editor: later, out of scope of phases 1–2. +- Engine (§3.2): `esp_timer`, with the callback rules listed there. diff --git a/docs/ongoing_reflection/tool_change_webui_pendant_consensus.md b/docs/ongoing_reflection/tool_change_webui_pendant_consensus.md new file mode 100644 index 00000000..d87b7b17 --- /dev/null +++ b/docs/ongoing_reflection/tool_change_webui_pendant_consensus.md @@ -0,0 +1,108 @@ +# Tool change — WebUI / pendant consensus + +> **Status:** consensus being finalized (2026-11-14). Nothing below is validated on a real machine, on either side. The bench test list (§6) is the source of truth for the unknowns; the WebUI grblHAL mock is aligned on its results. +> **Scope:** grblHAL tool change (`T M6`, `$341` modes, `$TPW`) and SET mode (`M61Q`), shared by the WebUI and the pendant. FluidNC: see §5. +> **Release:** pendant side is an a14 fix (wrong flow, not a new feature) — `docs/roadmap/release_plan.md`. +> **Pendant references:** `docs/ux_flows/grblhal/change_tool_screen.md`, `main/display/cnc/grblhal/screens/change_tool_screen.cpp`, `docs/ux_flows/README.md` (common flow rules), `docs/ux_flows/grblhal/grblHAL_pendant_connection_flow.md` (MPG token). +> **Tests:** `tests/grblhal_test_plan.md` §4. + +Goal: one single flow on both sides. The WebUI behaves as a pendant; the two implementations must not diverge. + +--- + +## 1. Common flow (grblHAL) + +``` +IDLE → MOVING_TO_CHANGE → (auto-ack) → WAITING_USER → (PROBING) → COMPLETING → SUCCESS / FAILED +``` + +- Common state names in both codes. WAITING_ACK remains a transient state name only (the ack is automatic, §3). +- **`$341` read before Start** (may also be read at panel open for display, but the value used is the one read at Start): + - mode 4 (M6 ignored) → Start disabled with an explicit message; + - modes 0 and 3 → `$TPW` button hidden; + - modes 1 and 2 → `$TPW` shown, with a mode-specific guidance text: + - mode 1 (probes at the current position): "Jog above the tool setter, then Probe"; + - mode 2 (probes @ G59.3, the firmware moves there itself): "Install the tool, then Probe". +- **Timeouts:** 60 s on MOVING_TO_CHANGE, PROBING and COMPLETING; none on WAITING_USER (human action). The COMPLETING timeout covers the automatic touch-off of mode 3. Timeout → FAILED → recovery rule (§2). +- **End of `$TPW`:** messages first (`[PRB:]` / `ALARM`, exact messages per bench test 2), state heuristic (leave Tool, then return to Tool) as fallback. +- Explicit terminal states SUCCESS / FAILED with a message. +- **Finish** button sending `~`; the status-bar cycle start stays usable in parallel. +- **Probing rule:** G38 only with the machine Idle (never during Tool); `$TPW` only during Tool, after the ack. The classic Probe panel is locked during the Tool state on both sides. +- **SET mode** (`M61Q`) + optional G38 touch-off is kept: it is a work zero, not a TLO; it complements `$TPW`, it does not replace it. `G43.1` is not an alternative (it assumes a known length). + +## 2. Cancel / recovery (common rule) + +1. Send `0x18` (soft reset). +2. Wait for a stable state. +3. If ALARM: show it ("Unlock required, `$X`"); do **not** send `M61Q` blindly (G-code locked → error 9). +4. Once Idle: re-read `$G`; send `M61Q` **only if** the tool number actually changed. + +The previous tool is read **at Start** (`$G` parser state), not at panel open: a job or the other UI may have changed it in between. + +## 3. Ack and control — no ownership + +- **No ownership.** Both UIs follow the firmware state, which is the single source of truth; either UI may act (`$TPW`, Finish). It does not matter who sent the M6 (panel, console, macro, job): opening the panel while the machine is in Tool resumes the flow, the same way on both sides. Reasons: FluidNC has no ownership either, and either UI may be closed in the meantime. A user acting on both UIs at the same time is not protected against. +- **Ack = infrastructure, not ownership.** Each UI auto-acks (`0xA3`, as ioSender) as soon as it sees the Tool state, whether or not its change tool panel is open, and re-acks after a reconnection if Tool is seen again. The only limit is the right to send: + - grblHAL with the pendant in MPG mode: the WebUI has priority. While the pendant is PASSIVE (no MPG token) it sends nothing, the ack included, and its change tool screen is not reachable (commands disabled). When the pendant holds the token (ACTIVE), it acks. + - Pendant as sole sender (standard mode, UART primary): the pendant acks. + - A duplicate `0xA3` (both UIs acking) is expected to be harmless (bench test 5); if it is not, only the UI that has control acks. +- If bench test 1 shows that the ack starts a motion in `$341=3`, auto-ack becomes conditional on the mode, on both sides. +- **M6 from a streamed job:** acked automatically like any other M6, even with no change tool panel open. The pendant notifies the user (message / sound); the WebUI relies on its global ack + state-driven panel + status-bar cycle start (no automatic navigation, not the WebUI model). The job is never blocked as long as a UI with control is connected. CNC powered off or link lost: the job stays in Tool until a UI reconnects and acks — same on both sides. + +## 4. Consensus (summary) + +1. Flow: IDLE → MOVING_TO_CHANGE → (auto-ack) → WAITING_USER → (PROBING) → COMPLETING → SUCCESS / FAILED. +2. `$341` read before Start: 4 blocks CHANGE; 0 and 3 hide `$TPW`; 1 and 2 show `$TPW` with their guidance text. +3. Timeouts: 60 s on MOVING_TO_CHANGE, PROBING, COMPLETING; none on WAITING_USER. +4. Cancel: `0x18` → stable state → ALARM reported → `M61Q` only after re-reading `$G`, and only if needed. +5. Previous tool read at Start. +6. G38 only with the machine Idle; `$TPW` only in Tool after the ack. +7. No ownership: the firmware state drives both UIs. The ack is infrastructure: every UI allowed to send acks on seeing Tool. +8. M6 from a job: same flow, auto-acked. + +## 5. FluidNC — compatibility (pendant only) + +**This section concerns the pendant only.** FluidNC ships its own, different WebUI: the WebUI side of this consensus does not apply to FluidNC and cannot be used as a reference there. The pendant FluidNC flow only has to stay consistent with the pendant grblHAL flow (same skeleton, same rules where the firmware allows it). + +The FluidNC flow keeps its own firmware steps but fits the same skeleton: + +| Common rule | grblHAL | FluidNC | +|---|---|---| +| Start | `T M6` | `M6T` | +| "Is a tool change possible?" check before Start | `$341` (4 → blocked) | `$CD` (no `atc:` / `m6_macro:` → blocked, already done) | +| Ack | `0xA3`, automatic | none (no Tool state; `atc_manual` holds → `Hold`) | +| Tool length probe | `$TPW` (modes 1/2) or firmware (mode 3) | firmware (`atc_manual`), after `~` | +| Finish | `~` | `~` | +| States | MOVING_TO_CHANGE → WAITING_USER → (PROBING) → COMPLETING | MOVING_TO_CHANGE → WAITING_USER → PROBING (= COMPLETING: firmware probe after `~`) | +| Timeouts | 60 s MOVING / PROBING / COMPLETING, none WAITING_USER | same (already) | +| Previous tool read at Start | yes | yes (to check in code) | +| Ownership | none | none (already) | +| Cancel | `0x18` → stable state → `$G` → conditional `M61Q` | `!` + reset-before-resume, then `M61Q` immediately — **to check on the bench** whether the `M61Q` is accepted and whether the number had changed; align on the common rule if not | + +Conclusion: compatible. The only FluidNC point to verify is the cancel/revert (FluidNC bench test F1, §6, pendant only). + +## 6. Bench tests (one bench, results shared with both teams) + +| # | Test | Decides | +|---|---|---| +| 1 | `$341=3`: does the ack alone trigger a motion, or only `~`? | §3 auto-ack | +| 2 | `$TPW` in modes 1 and 2: state sequence (Tool → Run → Tool?) and end messages (`[PRB:]`? `[TLO:]`?) | End-of-probe detection | +| 3 | `$TPW` in mode 0: reply | Hiding rule | +| 4 | `0x18` during MOVING_TO_CHANGE and during PROBING: resulting state, tool number in `$G` — and **when** the number changes (at `T`, at M6, at the ack, at cycle start) | §2 cancel + conditional `M61Q` | +| 5 | Duplicate `0xA3`; ack from the pendant while PASSIVE (MPG) | §3 ack | +| 6 | Reference tool: how it is established (`$TLR`?), does it survive a reset | §1 guidance | +| 7 | `T M6` in a streamed job: behaviour with no ack | §3 job | +| F1 | FluidNC (pendant only): cancel during MOVING and during PROBING: state, `M61Q` accepted?, tool number after recovery | §5 cancel | + +The grblHAL behaviours stated here (probe on `~` in mode 3, ALARM after reset in motion, `$TLR`) are code readings, **not verified** — this is why they are in the test list. + +## 7. Implementation status + +**WebUI** (pending validation, not committed): full state machine with the three timeouts; cancel/recovery per §2; previous tool read at Start; `$341` read at panel open (to also re-read at Start, §1); Finish (`~`); SUCCESS / FAILED toasts; classic Probe panel locked during Tool; single ack via the global handler (BackgroundContainer). grblHAL mock: `$341` stored and reflected in `$$`; `$TPW` simulated Tool → Run (~2 s) → Tool then `[PRB:]`/`ok` or `ALARM:5`; reset in motion → ALARM; reset at rest → clears the alarm; `$X` unlocks. To realign on the bench results. + +**Pendant** (a14 fix, coded 2026-11-14, built, not hardware-tested — `docs/ux_flows/grblhal/change_tool_screen.md`): +1. Auto-ack in the grblHAL handler on every entry into the Tool state, only when the pendant is allowed to send (MPG ACTIVE / sole sender); the user sees `Tool` in the status bar on every screen; manual Ack button removed. +2. `$341` read at each Start (single-setting query, 3 s): mode 4 blocks CHANGE, modes 0/3 hide `$TPW`, guidance for modes 1/2; unknown → `$TPW` offered. +3. Cancel/recovery per §2 (soft reset on Stop / timeout, Alarm reported, `$G` re-read, conditional `M61Q`). A change resumed from the Tool state (not started on the pendant) has no known previous tool: no revert. +4. Already compliant before: three timeouts, previous tool read at Start, Probe screen refused in Tool. +5. FluidNC: no change, unless bench test F1 shows the cancel/revert is wrong. diff --git a/docs/ongoing_reflection/usb_device_cdc_client_study.md b/docs/ongoing_reflection/usb_device_cdc_client_study.md new file mode 100644 index 00000000..7e4a4b98 --- /dev/null +++ b/docs/ongoing_reflection/usb_device_cdc_client_study.md @@ -0,0 +1,537 @@ +# Native USB CDC device client and log backend study + +**Date:** 2026-10-29 +**Status:** Phases 1–4 and 6 coded (Phases 2+3 confirmed on hardware 2026-10-30, Phases 4 and 6 not yet), `[ESP935]` added 2026-10-30; Phases 5 and 7 open (see §11) +**Software baseline:** ESP-IDF 5.4.3 and the current ESP3D clients +**Canonical document:** this file supersedes the earlier French and English drafts + +## 1. Executive decision + +The recommended solution is a **native TinyUSB dual CDC-ACM device** with two equally important application features: + +| USB interface | Purpose | Importance in the MVP | +|---|---|---| +| CDC #0 | ESP3D commands, G-code input, command responses and CNC monitoring | **Core feature** | +| CDC #1 | Application diagnostics through a new `esp3d_log` backend | **Core feature** | + +The two streams must never be mixed. In particular, no debug line may be emitted on CDC #0, even when no command session is active. + +For the MVP, CDC #0 is a **PC command and monitoring channel**, modeled on `socket_server`, not merely a debug accessory and not a new CNC output client. The existing CNC link remains Serial, UART extension, WiFi, BLE, USB host, or another already supported output. + +The **CNC output-client role** (USB CDC selectable as the CNC link) was confirmed as equally important by the user on 2026-10-29. It is a **planned phase right after the MVP** (§6.5, Phase 6), built on the same driver and client, not an optional idea. + +The first test board is the available **Waveshare ESP32-S3-Touch-LCD-1.47**, initially running headless. Small ESP32-S3 and ESP32-S2 boards without a USB-UART bridge remain important product targets after the software prototype. + +**Recommendation: conditional go**, provided that the peer is a USB host, the board USB connector reaches the native USB controller, BOOT/RESET recovery works, and the dual CDC transport passes the command, logging, hot-plug and non-regression tests in this study. + +## 2. Functional scope and USB roles + +### 2.1 The peer must be a USB host + +The ESP32 becomes a USB device. The peer can be a PC, Raspberry Pi, or a CNC controller with a real USB host port. + +Two USB devices cannot communicate directly. If a FluidNC, grblHAL, or other controller exposes only a USB device interface, this new client is not the right link; the existing USB host path must be used or extended instead (§2.4). + +### 2.2 Possible use cases + +| Case | Purpose | Decision | +|---|---|---| +| A | USB CDC is the CNC output link to a USB host acting as the machine side (PC software acting as controller, grbl / grblHAL simulator, Raspberry Pi bridge) | **Planned phase after the MVP** (§6.5) | +| B | A PC sends ESP3D commands/G-code and receives responses/monitoring | **MVP, core feature** | +| C | Both A and B | Result of the output phase: command channel unchanged when USB is not the selected output | +| Debug | Application logs on a second USB CDC port | **MVP, core feature** | + +Case B is not a reduced diagnostic mode. It must provide the same command-path care as the other ESP3D input clients: authentication, bounded queues, response routing, monitoring, and immediate handling of safety real-time commands. + +### 2.3 Do not confuse the existing USB paths + +| Path | ESP32 role | Current or proposed use | +|---|---|---| +| Existing `USB_SERIAL_SERVICE` | USB OTG host | Opens CH34x, CP210x, FTDI, PL2303, CH9102, STM32 VCP and similar devices | +| New `USB_CDC_DEVICE_SERVICE` | USB OTG device | Exposes command/monitoring and log ports to a USB host | +| USB Serial/JTAG | Fixed-function device | Console/JTAG on supported SoCs; optional separate backend, not the dual CDC MVP | + +The existing host client uses `usb/cdc_acm_host.h`, `usb/vcp.hpp`, `VCP::open()`, `line_coding_set()` and `tx_blocking()`. Its driver selects `USB_OTG_MODE_HOST`. The new device client must therefore have an explicit name and must not reuse the `usb_serial` identity or its settings. + +### 2.4 ESP32 pendant ↔ screenless controller (host path, separate work item) + +A screenless CNC / 3D controller (FluidNC, grblHAL, Marlin — confirmed targets, user 2026-10-29) is always a USB **device**, through a bridge chip or its native USB. In that topology the pendant must be the **host**, i.e. the **existing** `usb_serial` client, not the new device client. + +Gap found in the existing host client: it opens devices with `esp_usb::VCP::open()`, which only matches the registered drivers (`hardware/drivers_usb_otg/usb_serial/usb_serial.cpp`: FT23x, CP210x, CH34x, PL2303, CH9102, STM32 VCP). A controller exposing a **generic CDC-ACM** interface is very likely not opened today. + +| Controller hardware | USB on the controller side | Host client today | +|---|---|---| +| ESP32 classic (FluidNC, grblHAL, Marlin e.g. MKS TinyBee) | CH340 / CP2102 bridge | supported | +| ESP32-S3 / S2 native USB (FluidNC 4.x on S3, grblHAL) | generic CDC-ACM, VID `303a` | gap | +| STM32 native USB (grblHAL, Marlin) | ST VCP `0483:xxxx` | supported if the PID is in `vcp_stm32.hpp` | +| RP2040, Teensy 4.x, LPC176x (grblHAL, Marlin SKR 1.x) | generic CDC-ACM, vendor VIDs | gap | + +Exact VID/PIDs to confirm on real boards. Proposed fix (small, in the host client, independent of this study's MVP): fall back to a generic `cdc_acm_host_open()` (any VID/PID) when no VCP driver matches, to verify against the `usb_host_vcp` version in use. In host mode the pendant must also **supply 5 V on VBUS** to the controller's USB side (board-level check). + +## 3. Supported chips and board policy + +### 3.1 Chip support + +| SoC | Native programmable USB OTG | TinyUSB CDC-ACM | Decision | +|---|---:|---:|---| +| ESP32-S3 | Yes, one controller | Yes | **Prototype and first product target** | +| ESP32-S2 | Yes, one controller | Yes | Second product target; single-core port required | +| ESP32-P4 | Yes, two controllers | Yes | Future extension with a real BSP | +| ESP32 classic | No | No | Excluded | +| ESP32-C3 | No | No for this client | Optional future USB Serial/JTAG design only | +| ESP32-C6 | No | No for this client | Optional future USB Serial/JTAG design only | +| ESP32-H2 | No | No for this client | Optional future USB Serial/JTAG design only | + +ESP-IDF 5.4.3 documents TinyUSB CDC-ACM on S2, S3 and P4, and native USB on GPIO19/GPIO20 for S2/S3. [Espressif — ESP32-S3 USB Device Stack](https://docs.espressif.com/projects/esp-idf/en/v5.4.3/esp32s3/api-reference/peripherals/usb_device.html "citation"), [Espressif — ESP32-S2 USB Device Stack](https://docs.espressif.com/projects/esp-idf/en/v5.4.3/esp32s2/api-reference/peripherals/usb_device.html "citation"), [Espressif — ESP32-P4 USB Device Stack](https://docs.espressif.com/projects/esp-idf/en/v5.4.3/esp32p4/api-reference/peripherals/usb_device.html "citation") + +USB Serial/JTAG on S3, C3, C6 and H2 does not replace the programmable OTG controller needed by this dual CDC design. A later single-port USJ command client would need a separate log-mixing policy and is outside this MVP. [Espressif — USB Serial/JTAG Controller](https://docs.espressif.com/projects/esp-idf/en/v5.4.3/esp32s3/api-guides/usb-serial-jtag-console.html "citation") + +### 3.2 Board opt-in is mandatory + +SoC support is not sufficient. A board is eligible only when: + +- its USB connector is wired to native USB GPIO19/GPIO20 on S2/S3; +- those pins are not used by the display, touch controller, or another peripheral; +- VBUS and self-powered behavior are understood; +- the BSP explicitly enables the service; +- enumeration and ROM recovery have been tested on that board. + +| Board | Assessment | Planned use | +|---|---|---| +| Waveshare `ESP32-S3-Touch-LCD-1.47` | Available; native USB-C, BOOT/RESET, SD; headless BSP created (Phase 1) | **First headless prototype** | +| Mini ESP32-S3 without USB-UART bridge | Exact model still to identify | First small/headless product validation | +| Mini ESP32-S2 without USB-UART bridge | Exact model and memory still to identify | Second target, with single-core adaptations | +| `ESP32_S3_WROOM_CAM` | Existing USB host integration | Secondary development vehicle with host mode disabled | +| `esp32s3_8048_touch_lcd_7` | GPIO19/20 free in the current BSP | Candidate only after schematic and connector checks | +| `esp32s3_hmi43v3`, `esp32s3_zx3d50ce02s_usrc_4832`, `esp32s3_bzm_tft35_gt911` | GPIO19/20 free in current BSP data | Candidates only after schematic checks | +| `esp32s3_4827s043c`, `esp32s3_8048s043c`, `esp32s3_8048s050c`, `esp32s3_8048s070c` | Touch/I2C uses GPIO19/GPIO20 | Excluded without hardware changes | + +## 4. First prototype: Waveshare ESP32-S3-Touch-LCD-1.47 + +### 4.1 Verified board data + +- ESP32-S3R8 dual-core module, 16 MB flash and 8 MB octal PSRAM (GPIO35-37). +- USB-C for power, USB communication and firmware download, on native USB GPIO19 (`USB_N`) / GPIO20 (`USB_P`). +- JD9853 SPI LCD, 172 × 320: CLK GPIO38, DIN GPIO39, CS GPIO21, DC GPIO45, RST GPIO40 and backlight GPIO46. +- AXS5106L capacitive touch on I2C: SDA GPIO42, SCL GPIO41, RST GPIO47, INT GPIO48. +- TF card in four-bit SDMMC mode: CMD GPIO15, CLK GPIO16, D0 GPIO17, D1 GPIO18, D2 GPIO13 and D3 GPIO14. +- Header: TXD GPIO43 / RXD GPIO44 (UART0), GPIO1-11, GPIO41/42 (I2C), VBUS, VBAT, 3V3, GND. + +Source: Waveshare product pin definition (`to_port/pinout.png`, `to_port/lcd-specs.png`) and the ESP3D 3.x PlatformIO environment `waveshare_s3_touch_lcd147`, already tested on hardware (it also uses `USB_CDC_CLIENT_FEATURE`). **Not** the `ESP32-S3-LCD-1.47B` (ST7789, no touch): its wiki and schematic describe a different pinout and must not be used for this board. + +GPIO19/GPIO20 do not conflict with the LCD, touch or SD pins. The stock firmware enumeration should still be recorded before replacing it; any observed VID/PID is test evidence, not a value to copy into the new product descriptors. + +### 4.2 Headless BSP decision + +Create a provisional BSP named `ESP32_S3_TOUCH_LCD_1_47` with: + +- `TFT_UI_SERVICE=OFF`; +- `TFT_TOUCH_SERVICE=OFF`; +- a suitable 16 MB partition table; +- SD support enabled only after its BSP integration is validated; +- WiFi/WebUI available for baseline and command-path tests; +- native USB device support opt-in. + +The headless model can follow the existing `fysetc_wifi_pro` approach. The 172 × 320 UI port is a separate project and must not delay or obscure USB validation. + +The SD card can provide a fallback diagnostic path after validation. Because this board can run from a battery, self-powered USB behavior and VBUS monitoring must be checked before battery-powered hot-plug tests. + +## 5. TinyUSB dual CDC architecture + +### 5.1 Naming and identity + +Proposed identifiers: + +- CMake option: `USB_CDC_DEVICE_SERVICE`, default `OFF`; +- compile macro: `ESP3D_USB_CDC_DEVICE_FEATURE`; +- low-level driver: `hardware/drivers_usb_device/usb_cdc_device/`; +- command client: `main/modules/usb_cdc_device/`; +- class: `ESP3DUsbCdcDeviceClient`; +- instance: `usbCdcDeviceClient`; +- client type: `ESP3DClientType::usb_cdc_device = 18`; +- log backend: `ESP3D_LOG_BACKEND_USB_CDC = 5`. + +The value `18` is appended after `uart_ext = 16` and `lua_script = 17`. Existing client values must not change. Although this type identifies the command origin, it is **not** added to `esp3d_output_client` in the MVP. + +### 5.2 TinyUSB dependency and dual descriptors + +`dependencies.lock` currently selects ESP-IDF 5.4.3 and does not yet include `espressif/esp_tinyusb`. The new driver must declare a compatible dependency and freeze the resolved version. The official IDF 5.4.3 example uses `espressif/esp_tinyusb: "^1"` and `idf: "^5.0"`. [Espressif — CDC example manifest](https://raw.githubusercontent.com/espressif/esp-idf/v5.4.3/examples/peripherals/usb/device/tusb_serial_device/main/idf_component.yml "citation") + +The dual CDC configuration must exist from the first USB skeleton, with `CONFIG_TINYUSB_CDC_COUNT=2`, rather than adding the second interface after the command protocol is complete. The official example supports more than one CDC interface. [Espressif — TinyUSB serial device example](https://raw.githubusercontent.com/espressif/esp-idf/v5.4.3/examples/peripherals/usb/device/tusb_serial_device/main/tusb_serial_device_main.c "citation") + +Relevant APIs include: + +- `tinyusb_driver_install()`; +- `tusb_cdc_acm_init()`; +- `tinyusb_cdcacm_read()`; +- `tinyusb_cdcacm_write_queue()`; +- `tinyusb_cdcacm_write_flush()`; +- RX, DTR/RTS and line-coding callbacks. + +The BSP must provide explicit descriptor and device configuration: VID/PID policy, product strings, power mode, VBUS monitor where applicable, buffer sizes and task parameters. VID/PID values must not be copied arbitrarily from another product. + +### 5.3 Three ownership layers + +1. **USB device driver** — sole owner of TinyUSB, descriptors, VBUS configuration, CDC interfaces, callbacks and low-level RX/TX primitives. +2. **Command client** — owns CDC #0 message queues, command/G-code parsing, authentication context, response routing and monitoring backpressure. +3. **Log backend** — owns only the CDC #1 log buffer and writer; it does not install TinyUSB or manipulate callbacks directly. + +TinyUSB has a **global service lifecycle**. It starts when the command client or USB log backend requires it and is not uninstalled when the active CNC output changes. A full driver stop requires coordinated shutdown of both users. + +### 5.4 Host/device exclusion and target guards + +On S2 and S3, the same OTG controller cannot run the existing host client and the new device client simultaneously. CMake must reject: + +```text +USB_SERIAL_SERVICE=ON +USB_CDC_DEVICE_SERVICE=ON +``` + +The configuration must also: + +- reject targets other than `esp32s2` and `esp32s3` (no P4 BSP exists; extend the guard only when one is added); +- retain a C++ guard based on `SOC_USB_OTG_SUPPORTED`; +- require an explicit board BSP; +- reject log backend 5 when `USB_CDC_DEVICE_SERVICE=OFF`. + +## 6. CDC #0: command and monitoring client + +### 6.1 MVP behavior + +The command client follows the `socket_server` model: + +- the PC can send ESP3D commands and G-code; +- incoming messages use `ESP3DClientType::usb_cdc_device` as their origin and target the normal command/G-code stream; +- direct command responses return to that origin; +- relevant `all_clients` broadcasts are copied to the USB client while its port is open; +- messages whose origin is the USB client are not echoed back to it by the broadcast path; +- the existing authentication and admission rules are reused; +- monitoring backpressure is bounded and must never block CNC processing. + +The current `socket_server` broadcast branch in `esp3d_commands.cpp` provides the reference pattern, including its `isConnected()` guard and origin exclusion. + +### 6.2 Deliberately excluded from the MVP + +Because CDC #0 is not the CNC output client, the MVP does not add: + +- an output-selector entry; +- an `esp3d_output_client` setting or `[ESP950]` token; +- CNC `sendInitCommand()` or welcome sequencing; +- CNC ping/inactivity handling; +- CNC connection-status characters; +- a physical baudrate setting or `[ESP902]` behavior. + +DTR indicates a USB terminal session, not a CNC connection. The case A/C implementation (§6.5) must design the output-client behavior separately rather than accidentally inheriting it from the command channel. + +### 6.3 RX path + +The TinyUSB callback must only: + +1. read a bounded number of bytes with `tinyusb_cdcacm_read()`; +2. copy them into a static bounded ring buffer or queue; +3. notify the owning task; +4. count overruns without allocation or heavy logging. + +Parsing and message allocation happen in application context. The client must reuse `ESP3DClient::rxAdmit()`, `esp3d_rx_line_lost()` and the existing authentication/session model. + +The parser must handle fragmented lines, multiple lines per USB packet, incomplete-line flush and overlong lines. Safety real-time bytes such as `?`, `!`, `~`, Ctrl-X and jog cancel must be extracted immediately and must not wait for a newline. + +### 6.4 TX path and connection state + +The TX path must: + +- split data into bounded chunks; +- use `tinyusb_cdcacm_write_queue()` and bounded `tinyusb_cdcacm_write_flush()` calls; +- serialize producers where necessary; +- stop or drop according to a documented policy when DTR is inactive or the host stops reading; +- invalidate the session on close, detach, suspend, or error; +- never allow monitoring traffic to grow memory without limit or stall CNC work. + +The initial policy is to accept command traffic only when CDC #0 is configured and DTR is active. This must be tested with every supported terminal because host terminal behavior varies. + +Driver installation, VBUS presence, enumeration, DTR and an active application protocol are separate states and must not be conflated. + +### 6.4.1 `[ESP935]` client control (ported from ESP3D 3.x, 2026-10-30) + +`[ESP935] json= pwd=`, same syntax and answers as ESP3D 3.x `[ESP935]`: + +| Parameter | Effect | +|---|---| +| none | `ENABLED` / `DISABLED` (setting) + ` - Connected` / ` - Not connected` (terminal session, §6.4); guest rejected, user and admin can read | +| `ENABLE` | Writes `esp3d_usb_cdc_on = 1` and starts the client if it is stopped (admin) | +| `DISABLE` | Writes `esp3d_usb_cdc_on = 0`; applied at next boot, or use `CLOSE` (admin) | +| `CLOSE` | Stops the client until next boot or `ENABLE` (admin); the answer is sent first, so a terminal on CDC #0 itself gets it (`end()` supports the call from its own task) | + +Setting `esp3d_usb_cdc_on` (NVS `usb_cdc_on`, INI `services/USB_CDC_active`, default ON; `[ESP400]` `service/usb_cdc` "enable"). At boot (`esp3d_x.cpp`) the client starts only when it is ON; when it is OFF the TinyUSB driver is still installed (`usb_cdc_device_init()`), because the CDC #1 log backend never installs it (§7) and the board would not enumerate otherwise. + +`[ESP420]` reports `usb_cdc`: `ON (connected)`, `ON (not connected)` or `OFF`. mDNS `_device-info._tcp` carries `usb-cdc=enabled` (`docs/features/mdns.md`). + +### 6.5 CNC output-client role (planned phase after the MVP) + +When the user selects USB CDC as the CNC output, CDC #0 becomes the CNC link with the same contract as `serial` / `uart_ext` / `usb_serial`: output-selector entry, `esp3d_output_client` value, `[ESP950]USB-CDC` token (the USB host client is `USB-OTG` since 2026-10-30), init / welcome / startup commands, 10 s ping and 30 s inactivity timeout, connection-status characters, stream `begin/handle/end`, `ok`-paced streaming. When USB is not the selected output, the §6.1 command-channel behavior is unchanged. + +Only useful when the machine side is a **USB host** (§2.2 case A); for a pendant facing a screenless controller, see §2.4. + +Files concerned by this phase: `main/modules/gcode_host/esp3d_x_stream.cpp`, the three `main/target/cnc/*/esp3d_gcode_handler_service.cpp` (and the 3D-printer targets if needed), `esp400.cpp` (output list built from the compiled services, NVS values kept), `esp950.cpp`, `esp3d_settings_defs.inc` (allowed output values), output-selector, connection-status, information and settings screens, `esp3d_update_service.cpp`. `[ESP902]` / baud settings stay host-client only (§8.3). + +## 7. CDC #1: application log backend + +### 7.1 Backend selection + +Add `ESP3D_LOG_BACKEND_USB_CDC = 5` without changing existing backend values 0–4. It is selected with `ESP3D_LOG_BACKEND_DEV 5` or `-DESP3D_LOG_BACKEND=5` and depends on `USB_CDC_DEVICE_SERVICE=ON`. + +Proposed implementation file: + +```text +main/modules/log/usb_cdc/esp3d_log_usb_cdc_backend.cpp +``` + +### 7.2 Non-blocking contract + +The backend is an observer and must never stall CNC work: + +- `init()` creates a bounded static ring buffer immediately, before TinyUSB installation; +- `write()` copies a line and returns without waiting for VBUS, enumeration, DTR, or flush; +- an independent writer drains CDC #1 in small bounded chunks; +- CDC #0 and CDC #1 maintain independent DTR/session states; +- a reentrancy guard prevents USB writer errors from recursively logging into the same backend; +- a full buffer, closed port, or stopped reader causes the backend to drop its own lines and count the losses; +- after saturation, a bounded message reports dropped lines without recursively calling `esp3d_log`; +- pre-open boot logs survive only within the buffer limit, with an explicit overwrite/drop policy; +- closing the log port or changing the CNC output does not uninstall TinyUSB or reboot the device. + +The log backend must work while Serial, WiFi, BLE, or another client provides the CNC link. + +### 7.3 Boot, ROM and panic limits + +This backend covers application logs emitted after `esp3d_log` initialization. It does **not** guarantee ROM/bootloader output or the final messages from a panic/reset. + +ROM and early USB behavior must be checked on the generated configuration and real board. No irreversible eFuse change is proposed. Core dump, validated SD logging, or an optional external UART adapter remains necessary for those diagnostics. + +## 8. Console, flashing and line coding + +### 8.1 Console configuration + +The USB device build must explicitly choose its console configuration rather than relying on short board defaults: + +- set `CONFIG_ESP_CONSOLE_SECONDARY_NONE=y` after verifying the generated `sdkconfig`; +- keep the primary console on UART or none, according to the BSP; +- disable incompatible `CONFIG_ESP_CONSOLE_USB_CDC` use; +- do not call `esp_tusb_init_console()`; +- never redirect `stdout`/`stderr` into CDC #0. + +The generated `sdkconfig` is authoritative. Why the secondary-console setting matters: all board sdkconfig files are short defaults files, so on S3 the IDF default `CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG=y` applies. This **cannot** inject log text into CDC #0: before TinyUSB starts, USJ output goes to a **different** USB function (the "USB JTAG/serial debug unit" COM port, which disappears at re-enumeration); after TinyUSB switches the PHY to OTG, USJ output no longer reaches the cable. The setting is still required to avoid a useless console path, possible write timeouts on a disconnected USJ, and confusion about where early logs go. `boards/ESP32_S3_WROOM_CAM/save/sdkconfig` shows the secondary console enabled. [Espressif — USB OTG Console](https://docs.espressif.com/projects/esp-idf/en/v5.4.3/esp32s3/api-guides/usb-otg-console.html "citation") + +### 8.2 Flashing and recovery + +Do not assume that esptool auto-reset still works after TinyUSB replaces the stock USB function. Mandatory recovery for the prototype is native USB ROM download using BOOT/RESET. + +A later ESP command or documented reset-to-download mechanism may restore flashing convenience, but it is not an MVP dependency. The exact recovery procedure must be tested before and after TinyUSB integration. + +### 8.3 No physical baudrate + +The host-provided CDC line coding is session information; it does not configure a physical UART between the ESP32 and PC. It may be recorded for diagnostics, but the command client exposes no baudrate selector and does not reuse the USB host client's `[ESP902]` setting. + +## 9. Power and hot-plug behavior + +A battery-powered pendant is a self-powered USB device. It must monitor VBUS and configure `self_powered` / `vbus_monitor_io` correctly. VBUS must not be applied directly to a GPIO without suitable hardware. [Espressif — USB Device Stack, Self-Powered Device](https://docs.espressif.com/projects/esp-idf/en/v5.4.3/esp32s3/api-reference/peripherals/usb_device.html "citation") + +For the Waveshare prototype: + +1. begin with USB-powered tests; +2. review the schematic for usable VBUS detection; +3. validate detach/suspend behavior on USB power; +4. test battery-powered hot-plug only after the self-powered configuration is understood. + +If the hardware cannot provide suitable detection, the limitation must be documented rather than claiming USB compliance by default. + +## 10. Implementation map + +### 10.1 New files + +| File | Responsibility | +|---|---| +| `hardware/drivers_usb_device/usb_cdc_device/idf_component.yml` | TinyUSB dependency | +| `hardware/drivers_usb_device/usb_cdc_device/usb_cdc_device.h` | Low-level device API | +| `hardware/drivers_usb_device/usb_cdc_device/usb_cdc_device.cpp` | Descriptors, callbacks, dual CDC RX/TX and state | +| `main/modules/usb_cdc_device/esp3d_usb_cdc_device_client.h` | Command client declaration | +| `main/modules/usb_cdc_device/esp3d_usb_cdc_device_client.cpp` | Parsing, authentication, queues, response routing and monitoring | +| `main/modules/log/usb_cdc/esp3d_log_usb_cdc_backend.cpp` | Backend 5, bounded buffer and CDC #1 writer | +| `boards/ESP32_S3_TOUCH_LCD_1_47/` | Headless Waveshare BSP, partitions and USB configuration | + +### 10.2 Build, core and routing changes + +- `CMakeLists.txt`: add `USB_CDC_DEVICE_SERVICE`; +- `main/CMakeLists.txt`: conditionally add the command client and USB log backend; +- `cmake/features.cmake`: feature macro and configuration summary; +- `cmake/dev_tools.cmake`: backend 5 and the 0–5 documentation range; +- `cmake/sanity_check.cmake`: target, BSP, host/device and log dependency checks; +- `components/esp3d_log/esp3d_log.h`: backend constant 5; +- `components/esp3d_log/CMakeLists.txt`: accept backend 5 while retaining `-u esp3d_log_get_backend`; +- `main/core/includes/esp3d_client_types.h`: append type 18; +- `main/core/esp3d_client.cpp`: client name and related dispatch support; +- `main/core/esp3d_commands.cpp/.h`: direct dispatch and `all_clients` monitoring branch with connection and origin guards; +- `main/core/esp3d_x.cpp`: initialize log buffering, global USB service and command client in a coordinated order; +- board `board_config.cmake`, BSP headers and `sdkconfig` defaults; +- `dependencies.lock`: generated by the dependency tool, never hand-edited; +- `docs/guides/esp3d_log_guide.md`, `connection_management.md`, `features.md` and `feature_resource_matrix.md`: document the new command and log paths. + +Output-selector, CNC ping/init, `[ESP950]` and CNC connection-status files are not part of the MVP implementation map; they belong to the output-client phase (§6.5). `[ESP902]` is never touched. + +## 11. Delivery phases + +### Phase 0 — lock the use case and hardware baseline + +- Confirm a PC/USB host as the peer and command/monitoring as a core requirement. +- Record stock Waveshare USB enumeration. +- Validate BOOT/RESET ROM recovery before replacing the firmware. +- Review VBUS and battery behavior. +- Define supported-terminal DTR expectations. + +### Phase 1 — headless Waveshare BSP + +- Create `ESP32_S3_TOUCH_LCD_1_47`, 16 MB partitions and headless feature settings. +- Validate feature-OFF build, WiFi/WebUI and SD independently. +- Inspect the generated console configuration. +- Repeat native USB flashing and ROM recovery. + +Status (2026-10-30): BSP created in `boards/ESP32_S3_TOUCH_LCD_1_47/` (root option `ESP32_S3_TOUCH_LCD_1_47`, variant `16mb_wifi_fluidnc`: UART0 CNC + WiFi/WebUI + SD 4-bit SDMMC, no USB host, no HTTPS). Build OK, not yet tested on hardware. Generated console: primary UART0, secondary USB-Serial-JTAG (kept on purpose until Phase 2, see the board sdkconfig comment). + +### Phase 2 — global TinyUSB dual CDC skeleton + +- Install the global driver with two CDC interfaces from the start. +- Implement descriptors, bounded RX/TX primitives, DTR, detach and re-enumeration. +- Verify two stable ports on Windows and Linux before adding application protocols. + +### Phase 3 — full CDC #0 command and monitoring client + +- Add type 18, parsing, authentication and normal command dispatch. +- Validate ESP3D commands, G-code, direct responses and `all_clients` monitoring. +- Validate real-time bytes, backpressure and operation with Serial and WiFi CNC links. +- Add no CNC output-selector behavior. + +Status Phases 2+3 (2026-10-30, done together on user request): coded and built (`16mb_wifi_fluidnc` now has `USB_CDC_DEVICE_SERVICE=ON`), **not yet tested on hardware**. As built: + +- Driver `hardware/drivers_usb_device/usb_cdc_device/` (`espressif/esp_tinyusb` ^1, resolved 1.7.6): Kconfig default descriptors (Espressif VID, TinyUSB PID scheme, strings "ESP3D" / "ESP3D-X"), bus powered (no VBUS monitoring), TinyUSB task on core 0. RX: callback copies CDC #0 bytes into a static 1 KB stream buffer (overruns counted), CDC #1 input drained and dropped. TX: `write_queue` + non-blocking flush, bounded by a caller timeout. Connected = `tud_ready() && tud_cdc_n_connected()` (enumerated, not suspended, DTR). +- Board opt-in: `BOARD_USB_CDC_DEVICE_SUPPORTED` in `board_config.cmake`, which also adds the driver directory and appends `sdkconfig.usb_cdc_device` (console secondary NONE, `CONFIG_TINYUSB_CDC_COUNT=2`). `sanity_check.cmake` enforces S2/S3 target, board opt-in and host/device exclusion. +- Client `main/modules/usb_cdc_device/` (type 18, name "USB CDC"): socket_server model — own task (`ESP3D_USB_CDC_DEVICE_TASK_*` in the board `tasks_def.h`), line assembly in a static buffer, 1.5 s partial-line flush, safety realtime byte (`esp3d_rx_is_safety_realtime()`) sent at once **only at the start of a line** (inside a line it stays data: passwords / ESP commands may contain `!` or `?`), welcome message on DTR up, session reset (half line, TX queue, authentication) on DTR down / unplug / suspend. Authentication: same rule as Serial (`DISABLE_SERIAL_AUTHENTICATION` → admin), otherwise the first line of each session must carry `pwd=`. Monitoring copy of `all_clients` messages with origin exclusion (`esp3d_commands.cpp`); TX drop on overflow with a rate-limited warning (observer policy). +- Started in `ESP3DX::begin()` after the G-code stream; a failure does not fail the boot. + +### Phase 4 — full CDC #1 log backend + +- Add backend 5, boot buffer, independent writer, loss counters and reentrancy guard. +- Verify that no log reaches CDC #0. +- Validate closed-port, stopped-reader, saturation and hot-plug behavior. + +Status Phase 4 (2026-10-30): coded and built with `-DESP3D_LOG_BACKEND=5` (dev), backend symbols verified in the ELF, **not yet tested on hardware**. As built (`main/modules/log/usb_cdc/`, documented in `docs/guides/esp3d_log_guide.md` §4): SD-backend design — static 4 KB stream buffer (whole line or dropped + counted), static writer task (core 0, idle+1) draining to CDC #1 only while DTR is set, session marker on each open, drop count written directly. Boot lines kept up to the buffer size. No reentrancy guard needed: neither `write()` nor the USB write path logs. Never installs TinyUSB (`sanity_check.cmake` requires `USB_CDC_DEVICE_SERVICE`). CDC #0 never receives logs (separate port, the command client does not mirror `esp3d_log`). + +### Phase 5 — hardening + +- Measure memory, stacks and real-time latency under command, monitoring and log load. + +### Phase 6 — CNC output-client role (§6.5) + +- Add the output selection, init / ping / status cycle and stream integration. +- Validate with a grbl / grblHAL simulator on the PC acting as the machine; check that the command channel is unchanged when USB is not the selected output. + +Status Phase 6 (2026-10-31): coded and built, **not yet tested on hardware**; user documentation deferred (a15). As built: `[ESP950]USB-CDC` and INI `system/output = USB-CDC` select `usb_cdc_device` as the output client; the stream starts the client whatever `[ESP935]` says. In that role the CDC #0 client (`esp3d_usb_cdc_device_client.cpp`) follows the usb_serial contract: DTR up = transport `"C"` + init command, DTR down = `"?"`, data re-arms the init, 10 s ping / 30 s inactivity (display builds only, as serial / usb_serial), no authentication, no realtime extraction, no welcome, RX target `all_clients`, TX never dropped by the observer policy, partial write or full TX queue = lines to CNC not sent (S21, post-mortem §14); no monitoring copy to it (`esp3d_commands.cpp`). grblHAL treats it like serial (no welcome on port open). The machine-side host must assert DTR. Not done: TFT output selector entry (no display board with USB CDC yet), `[ESP400]` output list (USB-OTG builds only). + +### Phase 7 — extension + +- Validate the mini S3 product board. +- Port to the mini S2: single core (`SOC_CPU_CORES_NUM = 1`), so every task pinned to core 1 (`LVGL_TASK_CORE`, `ESP3D_*_TASK_CORE`, `TASKCORE` in the `esp3d_task_create_pinned()` callers, defined in each BSP `tasks_def.h`) must map to core 0 or be unpinned; no Bluetooth; no `board_config.cmake` selects `esp32s2` today, so this is a board port, not just enabling the client. +- Consider the 172 × 320 UI or a separate USJ design only after the dual CDC MVP is stable. + +### Separate item — generic CDC-ACM in the USB host client (§2.4) + +Independent of these phases; prioritized separately. + +## 12. Validation plan + +### 12.1 Build and non-regression matrix + +| Variant | Expected result | +|---|---| +| Waveshare headless, USB service OFF | 16 MB baseline build; SD and WebUI work; no LCD initialization | +| S3, device ON + host OFF | TinyUSB dual CDC build and link succeed | +| S3, host ON + device OFF | Existing host behavior remains unchanged | +| S3, host ON + device ON | Explicit CMake failure | +| S3, log backend 5 + USB service OFF | Explicit dependency failure | +| S3, log backends 0, 1, 2, 3 and 4 | Existing builds and behavior remain unchanged | +| ESP32/C3/C6/H2, TinyUSB device ON | Explicit CMake failure | +| S3, Serial/WiFi CNC + USB command client | CNC output remains independent; USB commands and monitoring work | +| S2, device ON + backend 5 | No incompatible pin or core-1 assignment | + +Use a fresh configuration/build after changing the client enum or log backend to detect stale objects and cached configuration. + +### 12.2 USB system tests + +- Record the stock Waveshare enumeration, then demonstrate two BOOT/RESET recovery cycles before TinyUSB integration. +- Windows: two identifiable COM ports, open/close/reopen and re-enumeration. +- Linux: two identifiable `/dev/ttyACM*` ports, permissions, open/close and unplug. +- Independent DTR behavior: opening CDC #1 does not activate CDC #0; closing CDC #0 does not stop logs. +- Hot-plug during idle, RX, TX, command bursts, monitoring and log bursts without crashes or stale callbacks. +- USB-powered tests first; battery tests only after VBUS validation. + +### 12.3 Command-path tests + +- ESP3D command request/response returns to the USB origin and is not duplicated back by `all_clients`. +- G-code input follows the normal command stream with authentication preserved. +- Monitoring is received while the CNC uses Serial, then WiFi; closing the USB port never changes the CNC output. +- Fragmented input one byte at a time and multiple lines in one packet. +- Exact buffer-length and overlong lines. +- `?`, hold/resume, Ctrl-X and jog cancel interleaved with traffic without waiting for `\n`. +- Direct responses, broadcasts and high-frequency monitoring do not create unbounded queues or block CNC processing. +- No init, ping, output-selector or baudrate behavior appears in the MVP. + +### 12.4 Log-path tests + +- No application log, boot message handled by the backend, or USB error message appears on CDC #0. +- Opening CDC #1 after boot returns only lines retained by the bounded buffer, then live logs. +- Closing the log port, stopping reads and saturating the buffer never block the CNC. +- Dropped lines are counted and reported without recursion. +- Logs continue while another client provides the CNC link and while that output changes. +- ROM/bootloader/panic limitations are confirmed and the SD/core-dump fallback is tested where available. + +### 12.5 Resource and exit criteria + +Measure internal heap, largest free block, PSRAM and stack high-water marks before/after repeated hot-plug and load tests. Measure real-time command latency during UI/WebUI/WiFi activity plus monitoring and log saturation. + +The MVP exits prototype status only when: + +1. the USB host role and board wiring are confirmed; +2. both CDC ports enumerate and reopen reliably on Windows and Linux; +3. command, response, monitoring and real-time tests pass; +4. log saturation and hot-plug never block the CNC or mix streams; +5. ROM recovery is documented and repeatedly successful; +6. memory/stack measurements show no leak or unbounded blocking; +7. host, Serial/WiFi CNC, log backends 0–4 and feature-OFF builds remain functional. + +## 13. Main risks and mitigations + +| Risk | Severity | Mitigation | +|---|---|---| +| Two USB devices connected face to face | Blocking | Confirm a real USB host before product use | +| Connector not wired to native USB or GPIO19/20 conflict | Blocking per board | BSP opt-in, schematic review and enumeration test | +| Command channel accidentally implemented as CNC output | High functional | Follow `socket_server`; exclude output-selector and CNC ping/init from MVP | +| Logs mixed into CDC #0 | Blocking functional | Two interfaces, backend restricted to CDC #1 and explicit stream-separation tests | +| Monitoring or log backpressure stalls CNC | High | Bounded queues, DTR/session checks, drop policies and latency tests | +| Secondary console injects USJ output into commands | High | Explicit `CONFIG_ESP_CONSOLE_SECONDARY_NONE=y` and generated-`sdkconfig` inspection | +| ROM/bootloader/panic messages unavailable on CDC #1 | High for diagnostics | Document limits; retain core dump, SD or optional external UART | +| Flashing convenience lost after TinyUSB starts | High for development | Mandatory BOOT/RESET recovery tests; optional reset-to-download later | +| Battery-powered hot-plug without validated VBUS detection | High | USB-powered prototype first, then self-powered review and tests | +| Reentrant USB log failures | High | Reentrancy guard and counter-based reporting | +| Heavy work in USB callbacks | High | Static rings and application-context parsing | +| Extra TinyUSB RAM/flash cost | Medium/high | Measure under WiFi/WebUI and command/log load | +| S2 single-core regressions | Medium | S2-specific task mapping and latency tests | +| Confusion with existing USB host settings | Medium | Explicit `USB_CDC_DEVICE` naming and no physical baudrate setting | + +## 14. Final recommendation + +Proceed with the Waveshare headless prototype using **one global TinyUSB driver and two CDC interfaces from the first implementation step**. + +CDC #0 must be implemented as a complete, authenticated **PC command and monitoring client**, modeled on `socket_server`. CDC #1 must be implemented as a complete non-blocking **application log backend**. Neither feature is an afterthought, and neither may compromise CNC real-time behavior. + +The MVP does not make USB the CNC output; that role is the planned phase right after it (§6.5, Phase 6). The next hardware milestones are a precisely identified mini S3 product board and then a mini S2 with its single-core port. Generic CDC-ACM support in the existing USB host client (§2.4) is a separate item for pendants facing screenless controllers. + +**Study limits:** no firmware code has been changed, no build has been run and no hardware test has yet been performed. VBUS behavior, terminal DTR behavior, ROM recovery and actual resource costs remain to be validated on the prototype. diff --git a/docs/websockets_protocol.md b/docs/websockets_protocol.md deleted file mode 100644 index f177b4c1..00000000 --- a/docs/websockets_protocol.md +++ /dev/null @@ -1,320 +0,0 @@ - # WebSocket Protocol - -There are **two separate WebSocket endpoints** on the same HTTP port. They use **different URI paths and subprotocols**; a client **must** use the correct pair. Negotiating the wrong subprotocol or path means the connection is handled by the **wrong** service — file transfer will **not** work. - -| Endpoint | Typical URI | Subprotocol (`Sec-WebSocket-Protocol`) | Role | -|----------|-------------|----------------------------------------|------| -| **Terminal / WebUI** | **`/ws`** | **`webui-v3`** | **BINARY** = raw machine/serial bytes (no V1 header). **TEXT** = `PING`, `NOTIFICATION:`, `currentID:`, etc. | -| **Data (external tools)** | **`/wsdata`** | **`esp3d-v1`** | ESP commands + G-code in **TEXT**; **BINARY** = V1 status and file upload/download (`SR`, `SU`, …). | - -**Common mistake:** sending V1 binary opcodes on `/ws`. The server treats binary as stream data, not file-transfer frames — **transfers are impossible on that socket by design**. - -## Subprotocols vs capabilities - -Both endpoints use the same WebSocket transport (HTTP upgrade, TEXT and BINARY frames). What changes is which service handles the connection — fixed by URI path and negotiated subprotocol — and therefore what each frame type means. - -| Subprotocol (with path) | TEXT frames | BINARY frames | File transfer (V1) | -|-------------------------|-------------|---------------|--------------------| -| **`webui-v3`** on **`/ws`** | WebUI protocol (`PING`, `NOTIFICATION:`, …), G-code / commands | Machine / serial stream (raw bytes, no V1 header) | **No** — do not send `SR`/`SU`/… here | -| **`esp3d-v1`** on **`/wsdata`** | ESP commands (e.g. `[ESP720]`), G-code relay | V1 — status (`SR`/`RS`) and upload/download framing | **Yes** | - -## Implementation differences: ESP-IDF vs Arduino - -Depending on the underlying HTTP server framework, the deployment of these two endpoints differs: - -- **ESP-IDF (`httpd_ws`)**: Both `/ws` and `/wsdata` operate on the **same HTTP port** (port 80). The server routes connections to the correct handler strictly based on the requested URI path. -- **Arduino (`WebSocketsServer`)**: The server cannot natively multiplex WebSockets on the main HTTP port 80. Instead, ESP3D creates **two separate TCP listeners on different ports**. Typically, the Terminal WebSocket uses `HTTP_PORT + 1` (e.g., 81), and the Data WebSocket uses the port configured in settings (`ESP_WEBSOCKET_PORT`, typically 82). The URI path (`/ws` vs `/wsdata`) is ignored; the client must connect to the correct **port** directly. - ---- - -## 1. Terminal WebSocket — `/ws`, subprotocol `webui-v3` - -### Text mode - -Reserved messages between WebUI and ESP. Format: `