Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
# Firmware
ESP32-WROOM-32E firmware. Native ESP-IDF v5, with two Bluetooth host stacks: BTstack for the
Classic Switch Pro Controller emulation and Bluedroid for BLE (see
[Two Bluetooth host stacks](#two-bluetooth-host-stacks)). Built with PlatformIO or plain
`idf.py`. Source is in [`../firmware/`](../firmware/).
## Building from source
Requirements: Python 3 and [PlatformIO](https://platformio.org/) (CLI or the VSCode extension). Flash
and monitor through **[benchmux](https://github.com/cajunpanda/benchmux)** (see the next section);
these docs use it for every flash and serial example.
```bash
cd firmware
pio run -e wroom32 # build (plain ESP-IDF works too: idf.py set-target esp32 && idf.py build)
```
A build is the main static check; there is no unit-test suite. Treat warnings in `main/*.cpp` as
regressions. If the board already runs firmware, skip the cable and flash your build's
`firmware/.pio/build/wroom32/firmware.bin` over the air from the config page (drop it on the OTA
card; the stick verifies and reboots into it). See [`../web/README.md`](../web/README.md).
## Serial monitor and flashing (benchmux)
Only one process can own the serial port, which is awkward when a person and an automated tool both
want to watch it. **[benchmux](https://github.com/cajunpanda/benchmux)** (`serial_proxy.py`) owns the
port and tees everything to a shared logfile, and its `flash` command coordinates the port handoff so
the monitor never has to be stopped by hand. It is the recommended way to flash and monitor this
board. Run it by path or symlink it onto `PATH`:
```bash
serial_proxy.py monitor --port /dev/ttyUSB0 # own the port, tee to /tmp/serial_proxy.log
tail -f /tmp/serial_proxy.log # watch live, any number of readers
serial_proxy.py flash --flash-cmd 'pio run -e wroom32 -t upload' # build + upload without stopping the monitor
```
`pio device monitor` needs a real TTY; reading the proxy's logfile is the scriptable path. `ble_proxy.py`
does the same over BLE (console + OTA) with no cable. See [`../tools/README.md`](../tools/README.md).
## First flash (blank board)
A freshly fabbed board has no firmware, so the first flash goes over the Tag-Connect serial cable
(see [HARDWARE.md](HARDWARE.md)); after it, all updates are over the air. Install esptool
(`pip install esptool`), press the cable onto the J4 pads (it powers the board and auto-resets, no
buttons), then flash the merged image through benchmux:
```bash
serial_proxy.py monitor --port /dev/ttyUSB0
serial_proxy.py flash --flash-cmd 'esptool.py --chip esp32 --baud 460800 write_flash 0x0 bt-nes-advantage.bin'
```
The blue LED blinks on boot (pairing mode). To flash the separate images instead of the merged
`bt-nes-advantage.bin`, pass them to the same `write_flash`: `0x1000 bootloader.bin 0x8000
partitions.bin 0xf000 ota_data_initial.bin 0x20000 firmware.bin`.
### The merged image erases settings and pairings; the separate images do not
`nvs` lives at `0x9000..0xF000`, between the partition table and `otadata`, and holds bonds,
transport, button profile, directional mode, and the identity generation. A raw merged image is one
contiguous blob from `0x0`, so `write_flash 0x0 bt-nes-advantage.bin` pads that hole with `0xFF` and
takes NVS with it. The four separate images skip the hole and leave NVS intact, which is why the
benchmux flash command above uses them.
Both paths are supported and each has its own rule:
- **Updating an existing controller** is the common case, and it **must never erase NVS** unless the
release genuinely breaks the NVS schema. This is the OTA image (`firmware-vX.Y.Z.bin`) via the
config page, which only writes the inactive app slot. Over serial, use the four separate images.
On a real schema break, erasing is the point: do it deliberately and say so in the release notes.
- **Flashing a blank or bricked board** is the merged image (`bt-nes-advantage-vX.Y.Z.bin`) at `0x0`.
Erasing NVS here is correct and wanted: there is nothing to preserve, and it is the recovery path
for corrupt NVS. Label it as such in the release notes so nobody reaches for it to update.
If a merged image ever needs to preserve NVS, build it with `esptool.py merge_bin --format hex`:
Intel HEX keeps the gap instead of padding it.
## Module layout (`main/`)
| File | Role |
|---|---|
| `app_main.cpp` | Entry point and state machine: gestures, sleep, LEDs, player select |
| `nes_controller.{hpp,cpp}` | CD4021 read and player-select |
| `settings.{hpp,cpp}` | NVS settings: transport, profile, directional mode, identity generation |
| `bt_transport.{hpp,cpp}` | Transport-neutral `bt::` API, dispatch to the active transport |
| `bt_pro_btstack.cpp` | BT Classic Switch Pro transport (BTstack) and connection state machine |
| `bt_ble.cpp` | BLE HID transport, two HID services (P1/P2) for take-turns play |
| `bt_config.{hpp,cpp}` | BLE config/OTA boot mode: GATT settings service plus `esp_ota` update |
| `linklog.{hpp,cpp}` | Always-on black box for pairing/reconnect events (see [Link log](#link-log)) |
| `power.{hpp,cpp}` | ULP sleep polling, deep-sleep entry, post-wake RTC-GPIO release |
| `battery.{hpp,cpp}` | Battery monitor (ADC divider plus TP4056 status) |
| `board_config.h` | Pin map for the production board (matches [HARDWARE.md](HARDWARE.md)) |
| `board.{hpp,cpp}` | Board revision probe: resolves the CHG_STAT pin, which moved on PCB 2.1 |
`partitions.csv` defines two 1.75 MB OTA app slots plus `otadata`, so config mode can update
firmware over the air. `sdkconfig.defaults` holds the project Kconfig; key names can drift between
IDF versions, so reconcile with `menuconfig` if you change IDF.
## Two Bluetooth host stacks
One controller, two hosts, one of each per boot - selected by the transport setting:
- **Classic (Switch Pro)** runs on **BTstack**, vendored in `firmware/components/btstack`
(see its README for the pinned version, what is vendored, and the license). BTstack ships a real
HID *device* profile, so the Pro emulation is plain library calls; the same thing on Bluedroid
needed five build-time patches to its own source to bend the inbound HID path, Class-of-Device
handling, and Secure Connections support into shape. Moving to BTstack deleted all five and
dropped ~80 KB of flash.
- **BLE** (gameplay transport and the config/OTA boot mode) stays on **Bluedroid**.
Bluedroid's Classic half is therefore compiled out (`CONFIG_BT_CLASSIC_ENABLED=n`), which also
removes a `sdp_init` symbol clash with BTstack. Earlier builds carried five
`tools/patch_bluedroid_*.py` pre-build patches to bend Bluedroid's Classic HID into shape; they
are gone with it (recoverable from git history before the BTstack switch, if ever needed).
## Architecture
Gestures (hold-combos) are matched in `detect_gesture()` in `app_main.cpp`; the user-facing list is
in [MANUAL.md](MANUAL.md).
Chords (Select as a shift key) are resolved by `apply_chords()` in `app_main.cpp`, one layer below
the gestures and above the transports. It synthesises the four buttons the NES stick has no way to
send (Home, Capture, ZL, ZR) into `bt::NesInput` and clears the NES buttons it consumed, so a
transport maps them like any other input and needs no chord awareness. Three consequences worth
knowing before touching that code:
- **Minus cannot be sent on press.** HID has no undo: once `minus=1` is on the wire the host has
acted on it, and sending `minus=0` when the chord arrives doesn't un-open the menu it just opened.
So Minus is withheld until the outcome is known: a chord forms (Minus never sent), or the window
closes without one (Minus commits and follows the hold from there).
- **The window is a setting, not a constant.** `settings::chord_window_ms(transport)` is read once
at boot into `s_chord_window`. `kChordOff` disables the layer entirely and `apply_chords()` returns
immediately, so Select is an ordinary button; `kChordHold` never closes the window, which is the
2.2.x behaviour (chords at leisure, Select never holdable); anything else bounds it in ms. Classic
defaults to 200 ms. **BLE is hard off**, not merely defaulted off: the chord outputs would land on
buttons 5-8 that no profile reads, so `chord_window_ms()` returns `kChordOff` for BLE without
consulting NVS and `set_chord_window_ms()` drops the write. The config service and the web page
refuse to offer it there for the same reason, so no surface can promise what the device ignores.
- **The poll loop gates sends on the resolved snapshot, not `stateChanged()`.** The chord layer
breaks the 1:1 between raw and reported state in both directions: the Minus pulse ends on a timer
with no button moving, and a chord changes what a held button means without the raw state moving.
The commit that closes the window is gated on `s_chord_fired` alone, not on whether a member is
currently down. A chord formed *inside* the window keeps the shift for as long as it's held; a member
arriving *after* the deadline must not resurrect the chord, which is the whole point of bounding it.
This layer has host-side tests: `./tests/run.sh` compiles the chord section out of `app_main.cpp`
against a fake clock and runs the window modes and edge cases. Run it after touching `apply_chords()`;
the timing edges are hard to reproduce by hand on a console. The extraction keys on the section's
banner comments, so renaming them means updating `tests/run.sh` too.
### Sleep and wake
The NES buttons sit behind CD4021 shift registers, so wake-on-button cannot be a plain GPIO
interrupt; button state is only visible by clocking the register. In deep sleep the ULP coprocessor
pulses LATCH/CLK on RTC GPIOs, shifts in both players' 8 bits, compares against the stored state,
and wakes the main core only on a change. The CPU and radio are fully off between polls. Wake
latency is roughly 30 ms; standby draw is in the microamp range. The firmware wakes fully only if
Start is held; any other button change goes back to sleep.
Pin constraints that follow:
- LATCH/CLK/DATA must be RTC-capable GPIOs. LATCH/CLK use RTC output pins (25/26/27); DATA stays on
32/33, which have internal pulls (GPIO 34 to 39 are input-only without pulls).
- Battery sense must be ADC1 (GPIO 32 to 39); ADC2 is unusable while the radio is on.
- The DATA pull direction differs by phase (pull-down awake for the player-select sentinel, pull-up
asleep for standby current), so the pulls are the ESP32 internal ones and the external pull
footprints (R14/R15) stay unpopulated.
- GPIO12 (MTDI strap) must never be driven.
The pin map is in [`../firmware/main/board_config.h`](../firmware/main/board_config.h) and matches
[HARDWARE.md](HARDWARE.md).
### Transports
- **One radio per boot.** The active transport (Classic or BLE) is an NVS setting; only that
identity advertises. The Select+Start gesture toggles it and reboots. The two identities (Pro
Controller vs NES Advantage) are never live at once.
- **Forget rotates the identity.** The hold-Select gesture clears all bonds, XORs the base MAC with
a persisted generation counter, and reboots. The device returns with a fresh BT address, so a
forgotten host cannot half-reconnect against stale pairing state.
- **Reconnect vs fresh pair.** Classic stays passive and lets the host open the HID channels; it
does not device-initiate, even with a stored bond. BLE advertises for the host to connect.
### Link log
`linklog.cpp` records why a link did or did not come up. It records always rather than on a switch:
a failed reconnect happens at power-on, before anything could be armed, and the gesture that reads
it out reboots the device. Storage is chosen to survive that reboot.
- **RTC ring** (96 events, `RTC_NOINIT_ATTR`): the fine-grained trace. Survives `esp_restart` and
deep sleep, the two transitions that matter, but not a battery pull. Events span boots, so the
dump prints a `---- boot ----` separator where the timestamps restart.
- **NVS summary** (8 boots, namespace `linklog`): one 20-byte record per boot, for the power-off
case. Written at outcomes only: HID up, HID gone, pages exhausted, deep sleep, and immediately
before the reboot into config mode, which is the boot being asked about. Capped at 8 writes per
boot, because this partition also holds the BTstack link keys.
- **What it captures, reconnect side:** stored bonds at boot, each page attempt and its status,
ACL, authentication and encryption status, whether the host asked for our link key, whether it
stored a new one (it had forgotten the bond and re-paired), HID open and close, and the
disconnect reason.
- **What it captures, pairing side:** the host's page including its class of device, the role
change, its IO capability response with authentication requirements and OOB flag, numeric
confirmation, any passkey or OOB request, a legacy PIN request, and the simple-pairing status.
That is what identifies an unknown host and says which half of the handshake refused. This
device is NoInputNoOutput with no display and no spare keys, so a passkey or OOB request cannot
be answered at all; a host requiring MITM either degrades to Just Works or refuses, and only the
SSP status says which; a host requesting no bonding keeps no key, so every session starts by
pairing again.
- **What it captures on BLE:** stored bonds at boot, whether advertising actually started, the HID
connect, which keys the host distributed (a peer LTK is the bond, and without one the link is
encrypted for this session only), the authentication result with Bluedroid's failure reason, the
granted connection parameters, and the disconnect reason. The passkey, numeric-comparison and
OOB requests are recorded but not answered: this device sets `ESP_IO_CAP_NONE`, so a host asking
for any of them wants input that does not exist here, and the unanswered request is the finding.
Both transports share the bond count, disconnect reason and those input-request codes; the rest
differ, so the per-boot summary prints a `classic` or `ble` column set rather than one layout
that is half zeroes either way.
- **Readout:** the `dbg` console command, on the wire or over BLE. Over BLE the config loop paces
the dump a few lines per drain instead of printing it from the command dispatch, which runs on
the BT task and would overrun the 3 KB log ring. The config page's **save link log** button runs
`dbg`, captures the stream to its footer, and downloads it as a text file.
### Config / OTA mode
A+B+Select reboots into a dedicated BLE-only mode (`bt_config.cpp`) serving a small custom GATT
service, so a browser can change settings, test the controller live, and flash firmware over the
air. The web client is the single-file [`../web/index.html`](../web/index.html). The GATT contract
(service `5f1d0000-...`, seven characteristics: INFO/CMD/OTACTL/OTADATA plus INPUT/LOG/CONSOLE) is
documented at the top of `bt_config.cpp` and mirrored in `web/index.html`; change them together.
- Entry is a one-shot flag in `RTC_NOINIT_ATTR` memory, honored only when the reset reason is a
software reset. Any cold boot returns to gameplay. The `config` bench-console command arms the
same flag over serial, so config mode can be entered without the button gesture.
- Boot also enters config mode when no controller is detected. A disconnected NES Advantage reads as
all-buttons-held (both CD4021 data lines idle-high), which would oscillate player-select and trip
the Select+Start transport gesture into a reboot loop. `NESController::diagnose()` catches this at
boot; config mode reports it as `wiring` in the INFO JSON (none/p1/p2/both), blinks the red LED,
and answers the `diag` console command. The `diag` command works in gameplay too.
- Config mode brings up the battery monitor and streams a live INPUT frame (buttons, player-select,
turbo rate) plus the device log (LOG), and takes console commands (CONSOLE) whose output it
echoes back over LOG.
- Config mode advertises on a distinct BT address (factory MAC with one byte flipped). Hosts cache
GATT layouts per address; without this, a host that had bonded the gameplay HID would reuse the
stale handle map and fail to connect.
- The production board has no accessible reset button, so every exit is firmware driven: hold Start
3 s, a 5-minute idle timeout, and an OTA stall watchdog.
- OTA is the standard `esp_ota` dual-slot scheme. Images are SHA-256 verified before the boot
partition switches; a bad upload leaves the running slot untouched.
### Input latency
| Term | Approach |
|---|---|
| Sample | 1 kHz tick, 2 ms poll loop (~2.4 ms real period): about 1.2 ms average press-to-latch |
| Read | 4021 latch plus 8-bit shift-out: about 0.4 ms at the default 80 MHz |
| Hand-off | Reports ship on input change (task notify), not on a timer tick: tens of us |
| Air, BLE | Interval pinned at 7.5 ms (the BLE floor on this silicon): 3.75 ms average wait |
| Air, Classic | QoS requests t_poll about 10 ms to pin the link active; typical wait a few ms |
Board-side total, press to radio hand-off, is roughly 6 ms average on BLE and 4 ms on Classic — both
inside a single 16.7 ms frame, and small against the host stack and display downstream. Pinning the
BLE interval at 7.5 ms roughly halves worst-case report wait versus a host-chosen 15 ms. BLE's
retransmit granularity is a whole interval (+7.5 ms) where Classic retries a slot at a time
(+1.25 ms), so Classic has both the better average and the gentler jitter tail.
The Classic figure is the softer of the two: the QoS t_poll pin does not actually guarantee the link
stays out of sniff. A real Switch was observed holding the link in sniff steady state regardless (see
`../history/power-tuning/README.md`), which would put Classic latency under the negotiated sniff
interval rather than t_poll. That interval has not been measured.
### Player select and two-player
The BLE transport registers the same report map twice (two HID services with distinct report IDs),
so hosts enumerate two gamepads and the player-select slider routes the stick to P1's or P2's report
for take-turns play. Classic is one Pro Controller (one player); the slider only picks which. The
host-by-host behavior is in [MANUAL.md](MANUAL.md).
## Protocol reference
The byte-level Switch Pro Controller emulation contract (identity, input/output reports, handshake
order, sniff and connection-direction behavior) is in
[`switch_pro_protocol.md`](switch_pro_protocol.md).
5150f6db8This file is pinned to the selected release. Download the original to open it in your design tool.