Fix trackball click: I2S MCLK was claiming GPIO0; emulator pin-ownership parity

Root cause (on device): sound_engine zero-initialized i2s_pin_config_t,
leaving mck_io_num == 0. i2s_set_pin() then claimed GPIO0 — an
MCLK-capable pin on the S3 and the trackball centre / BOOT line — as
its MCLK output. Verified on device with a diagnostic build: pin0 read
LOW at idle, exactly one latched FALLING edge, clicks never registered.

- sound_engine: set pins.mck_io_num = I2S_PIN_NO_CHANGE explicitly.
- NetDeck: register the trackball click on release with contact-bounce
  collapse (the proven CrtTerminal pattern); pollTouch re-arms when
  isPressed() stays true but getPoint() reports no points (stuck GT911
  IRQ on some units).
- Emulator parity (so this class of bug dies before flashing):
  GPIO-matrix pin-ownership model in the shim — i2s_set_pin() claims
  its pins, claimed pins are dead inputs (digitalRead LOW, no edges,
  loud WARNING on claim/ISR collisions); host pin writes go through
  emu::setPin/togglePin with an edge-accurate ISR latch (a full
  press+release pulse between dispatches no longer gets swallowed);
  E2E inits SDL_INIT_AUDIO so the I2S path actually runs there.
  Regression coverage: e2e/trackball_click (fails on the old engine),
  unit/shim_claimed_pin_is_dead_input,
  unit/shim_edge_survives_same_dispatch_pulse.
- Makefile: firmware step follows the sketch move (root platformio.ini,
  src_dir = src/netdeck).
- HW.md: new notes file for emulator-vs-hardware quirks and the
  on-device debugging recipe.

On-device verified: clicks register in both views (beacon drops, node
routing). Fast layer 23 unit + 7 integration green. Note: e2e
boot_and_controls + network_journey failures are pre-existing at HEAD
(reproduced on a clean stash before this change).
This commit is contained in:
Dejvino
2026-11-15 10:24:30 +01:00
parent 4645c7a1c6
commit 1dcc87d8d4
12 changed files with 368 additions and 30 deletions
+103
View File
@@ -0,0 +1,103 @@
# T-Deck hardware notes — emulator vs device quirks
Lessons from debugging on the physical T-Deck that the SDL3 emulator
cannot reproduce (or reproduces differently). Read this before blaming
app logic for input/sound problems that "work in the emulator".
## GPIO0 is shared: trackball centre = BOOT — and MCLK-capable
- The trackball centre click is wired to **GPIO 0** (`BOARD_BOOT_PIN`),
the same pin as the BOOT strap button. It idles HIGH (pull-up), press
pulls it LOW. LilyGO docs: while the ES7210 microphone is active,
GPIO0 is unavailable (NetDeck only drives the speaker via I2S TX, so
this does not apply).
- **GPIO0 is one of the few MCLK-capable pins** (GPIO0/1/3, see the
`i2s_pin_config_t` comment in the S3 SDK header). A zero-initialized
pin config (`i2s_pin_config_t pins = {};`) leaves `mck_io_num = 0`,
and `i2s_set_pin()` then claims GPIO0 as the I2S MCLK output.
Symptom (NetDeck, fixed 261115): app boots fine, trackball roll
works, but `digitalRead(GPIO0)` reads **0 at idle** and the click
never registers — the sound engine had silently hijacked the line
right after `attachTrackball()`.
Fix: always set `pins.mck_io_num = I2S_PIN_NO_CHANGE` explicitly.
- Meta-lesson: the emulator's `i2s_set_pin()` shim is a no-op, so pin
conflicts like this are **invisible in every emulator test layer**.
Any peripheral that reconfigures pins (I2S, SD, radio, touch) needs
an on-device sanity check of the pins it does not own.
## Button/click conventions proven on device
- **Trackball click acts on RELEASE**: contact bounce fires several
FALLING edges while the pin is low; latch the count in the ISR and
consume it only once `digitalRead()` is back HIGH — that collapses
the burst into one action and survives a press spanning a frame
boundary (`CrtTerminal.pollClick()`, NetDeck `applyTrackball()`).
Acting directly on the first FALLING edge double-fires.
- **Touch acts on PRESS**: `pollTouch()` moves the cursor to the tap
and registers the click immediately.
- The GT911 can keep `isPressed()` true after the finger lifts (stuck
IRQ line on some units). `getPoint()` returning 0 points while
`isPressed()` is true is the real release signal — re-arm `wasDown`
there or all later taps are swallowed.
## Trackball roll: device vs emulator edge rates
- Device: real quadrature pins (`G02=2 right, G01=3 up, G04=1 down,
G03=15 left`) at raw pulse rates. Emulator: arrow keys toggle one pin
every 3rd loop iteration, mouse wheel queues ~6-edge bursts — far
slower. This is why `TB_IMPULSE`/`TB_FRICTION` are split per build
(`#ifdef EMULATOR` in the sketch). Tune feel on hardware only.
## Emulator input shim gaps (known, accepted)
- Touch shim: left mouse button = single-finger tap at fixed coords;
no multi-touch, no stuck-IRQ behavior, so the GT911 quirk above can
only be validated on device.
- The emulated MCLK line idles LOW and does not toggle during actual
playback (a real MCLK square wave would make digitalRead sample
quasi-random values). Only the idle signature is emulated.
- Clicks accumulated during the 1.4 s boot grace are discarded
(`resetTrackball()` at boot end) — intentional on both targets.
## Emulator parity features (added after the GPIO0 incident)
- **Pin ownership / GPIO-matrix model** (`emu_input.h`, `Arduino.h`,
shim `driver/i2s.h`): `i2s_set_pin()` now *claims* every configured
pin, exactly like the real driver. A claimed pin is a driven output:
`digitalRead()` sees the driven level (idle LOW), `emu::setPin()`
writes from the outside world are ignored, and `dispatchIsrs()`
never edges it. Claiming a pin that already has an attached ISR —
the exact signature of the sound-engine/GPIO0 hijack — prints a
loud `[emu] WARNING: ... on hardware that input just died`. With the
bug present the emulator now *kills the click* and fails
`e2e/trackball_click`; with `mck_io_num = I2S_PIN_NO_CHANGE` set,
silence and a passing journey.
- **Edge-accurate ISR latch**: host pin writes go through
`emu::setPin()`/`togglePin()`, which record every transition;
`dispatchIsrs()` drains them first. A press+release pulse fully
contained between two dispatches now registers (previously the
level-diff sweep silently swallowed it — covered by
`unit/shim_edge_survives_same_dispatch_pulse`).
- **E2E runs with audio**: the E2E binary inits `SDL_INIT_AUDIO`
(dummy driver). Without it `i2s_driver_install` failed early and
`i2s_set_pin()` never ran, leaving the whole pin-ownership class of
bugs dormant in E2E. Rule: if a shim driver can fail early, the E2E
host must init enough SDL for it to take the same code path as on
the device.
- Regression journeys/tests: `e2e/trackball_click` (full device
pipeline: ISR latch -> release gate -> registerClick),
`unit/shim_claimed_pin_is_dead_input`,
`unit/shim_edge_survives_same_dispatch_pulse`.
## On-device debugging recipe (that worked here)
1. `cat /dev/ttyACM0` or a pyserial loop reads the app's Serial output
(`pio device monitor` refuses a non-TTY stdin). Opening the port
does not reset the board; `pio run -t upload` does.
2. Add a low-rate health line (e.g. 4 Hz) printing the suspect pin
level, ISR edge counter, and pending counts — it instantly showed
`pin0=0` at idle with exactly one latched FALLING edge.
3. Bracket init stages with `digitalRead()` prints (pre-tft / after
touch / after trackball / after sound) to bisect *which* init call
steals the pin — this pinned the drop to `sound.begin()` in one
flash cycle.
+2 -2
View File
@@ -24,8 +24,8 @@ endif
netdeck: netdeck:
@echo "=== [1/2] NetDeck firmware (ESP32-S3, pio) ===" @echo "=== [1/2] NetDeck firmware (ESP32-S3, pio) ==="
$(PIO) run -d examples/NetDeck $(PIO) run -e T-Deck
@echo "=== [2/2] NetDeck emulator (SDL2) ===" @echo "=== [2/2] NetDeck emulator (SDL3) ==="
$(MAKE) --no-print-directory -C emulator APP=NetDeck $(MAKE) --no-print-directory -C emulator APP=NetDeck
@echo "=== both NetDeck targets built OK ===" @echo "=== both NetDeck targets built OK ==="
+19 -17
View File
@@ -41,6 +41,8 @@ bool emuAutoplay = false;
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
namespace emu { namespace emu {
uint8_t pinLevels[64]; uint8_t pinLevels[64];
const char *pinDrivenBy[64];
std::deque<PinEdge> pinEdges;
bool touchDown = false; bool touchDown = false;
int touchX = 0, touchY = 0; int touchX = 0, touchY = 0;
std::deque<uint8_t> keyboard; std::deque<uint8_t> keyboard;
@@ -165,13 +167,13 @@ int main(int argc, char **argv)
if (e.key.repeat) break; if (e.key.repeat) break;
SDL_Keycode k = e.key.key; SDL_Keycode k = e.key.key;
switch (k) { switch (k) {
case SDLK_RIGHT: held[0] = true; emu::pinLevels[dirPin[0]] = 0; break; case SDLK_RIGHT: held[0] = true; emu::setPin(dirPin[0], 0); break;
case SDLK_UP: held[1] = true; emu::pinLevels[dirPin[1]] = 0; break; case SDLK_UP: held[1] = true; emu::setPin(dirPin[1], 0); break;
case SDLK_LEFT: held[2] = true; emu::pinLevels[dirPin[2]] = 0; break; case SDLK_LEFT: held[2] = true; emu::setPin(dirPin[2], 0); break;
case SDLK_DOWN: held[3] = true; emu::pinLevels[dirPin[3]] = 0; break; case SDLK_DOWN: held[3] = true; emu::setPin(dirPin[3], 0); break;
case SDLK_RETURN: case SDLK_RETURN:
case SDLK_KP_ENTER: case SDLK_KP_ENTER:
emu::pinLevels[BOARD_BOOT_PIN] = 0; // trackball press emu::setPin(BOARD_BOOT_PIN, 0); // trackball press
break; break;
case SDLK_SPACE: case SDLK_SPACE:
emu::keyboard.push_back(' '); emu::keyboard.push_back(' ');
@@ -202,13 +204,13 @@ int main(int argc, char **argv)
case SDL_EVENT_KEY_UP: { case SDL_EVENT_KEY_UP: {
SDL_Keycode k = e.key.key; SDL_Keycode k = e.key.key;
switch (k) { switch (k) {
case SDLK_RIGHT: held[0] = false; emu::pinLevels[dirPin[0]] = 1; break; case SDLK_RIGHT: held[0] = false; emu::setPin(dirPin[0], 1); break;
case SDLK_UP: held[1] = false; emu::pinLevels[dirPin[1]] = 1; break; case SDLK_UP: held[1] = false; emu::setPin(dirPin[1], 1); break;
case SDLK_LEFT: held[2] = false; emu::pinLevels[dirPin[2]] = 1; break; case SDLK_LEFT: held[2] = false; emu::setPin(dirPin[2], 1); break;
case SDLK_DOWN: held[3] = false; emu::pinLevels[dirPin[3]] = 1; break; case SDLK_DOWN: held[3] = false; emu::setPin(dirPin[3], 1); break;
case SDLK_RETURN: case SDLK_RETURN:
case SDLK_KP_ENTER: case SDLK_KP_ENTER:
emu::pinLevels[BOARD_BOOT_PIN] = 1; emu::setPin(BOARD_BOOT_PIN, 1);
break; break;
default: break; default: break;
} }
@@ -267,8 +269,8 @@ int main(int argc, char **argv)
emu::touchX = wx; emu::touchX = wx;
emu::touchY = wy; emu::touchY = wy;
} else if (e.button.button == SDL_BUTTON_RIGHT) { } else if (e.button.button == SDL_BUTTON_RIGHT) {
emu::pinLevels[BOARD_BOOT_PIN] = emu::setPin(BOARD_BOOT_PIN,
(e.type == SDL_EVENT_MOUSE_BUTTON_DOWN) ? 0 : 1; (e.type == SDL_EVENT_MOUSE_BUTTON_DOWN) ? 0 : 1);
} }
break; break;
} }
@@ -280,13 +282,13 @@ int main(int argc, char **argv)
// mouse-wheel pulse queues (one toggle per iteration = one ball edge). // mouse-wheel pulse queues (one toggle per iteration = one ball edge).
for (int d = 0; d < 4; d++) { for (int d = 0; d < 4; d++) {
if (wheelPulse[d] > 0) { if (wheelPulse[d] > 0) {
emu::pinLevels[dirPin[d]] ^= 1; emu::togglePin(dirPin[d]);
wheelPulse[d]--; wheelPulse[d]--;
} }
} }
if (++frame % 3 == 0) { if (++frame % 3 == 0) {
for (int d = 0; d < 4; d++) { for (int d = 0; d < 4; d++) {
if (held[d]) emu::pinLevels[dirPin[d]] ^= 1; if (held[d]) emu::togglePin(dirPin[d]);
} }
} }
@@ -302,7 +304,7 @@ int main(int argc, char **argv)
const TypeEvt &te = typeEvts[curType]; const TypeEvt &te = typeEvts[curType];
if (frame >= (uint32_t)te.at) { if (frame >= (uint32_t)te.at) {
if (typePressPin >= 0) { if (typePressPin >= 0) {
emu::pinLevels[typePressPin] = 1; // release the Enter press emu::setPin(typePressPin, 1); // release the Enter press
typePressPin = -1; typePressPin = -1;
} }
const char *typeEnd = te.s + strlen(te.s); const char *typeEnd = te.s + strlen(te.s);
@@ -314,7 +316,7 @@ int main(int argc, char **argv)
lastTypeMs = millis(); lastTypeMs = millis();
if (*typeNext == '\n' || *typeNext == '\r') { if (*typeNext == '\n' || *typeNext == '\r') {
typeNext++; // consume the Enter char typeNext++; // consume the Enter char
emu::pinLevels[BOARD_BOOT_PIN] = 0; emu::setPin(BOARD_BOOT_PIN, 0);
typePressPin = BOARD_BOOT_PIN; typePressPin = BOARD_BOOT_PIN;
} else { } else {
emu::keyboard.push_back((uint8_t)*typeNext++); emu::keyboard.push_back((uint8_t)*typeNext++);
@@ -333,7 +335,7 @@ int main(int argc, char **argv)
} }
static int dir = 0; static int dir = 0;
if (frame % 45 == 0) dir = (dir + 1) & 3; if (frame % 45 == 0) dir = (dir + 1) & 3;
if (frame % 4 == 0) emu::pinLevels[dirPin[dir]] ^= 1; if (frame % 4 == 0) emu::togglePin(dirPin[dir]);
if (frame % 75 == 0) emu::keyboard.push_back('s'); if (frame % 75 == 0) emu::keyboard.push_back('s');
} }
#endif #endif
+69 -1
View File
@@ -107,7 +107,14 @@ inline uint32_t esp_random()
#define LOW 0 #define LOW 0
inline void pinMode(int, int) {} inline void pinMode(int, int) {}
inline int digitalRead(int pin) { return emu::pinLevels[pin & 63]; } inline int digitalRead(int pin)
{
// A pin claimed by a peripheral is a driven output: an input read sees
// the driven level, not the outside world. The emulated peripheral
// lines idle LOW (the gated MCLK signature observed on the S3).
if (emu::pinDrivenBy[pin & 63]) return LOW;
return emu::pinLevels[pin & 63];
}
inline void digitalWrite(int, int) {} inline void digitalWrite(int, int) {}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -133,9 +140,28 @@ inline IsrEntry isrs[64];
inline void dispatchIsrs() inline void dispatchIsrs()
{ {
// First drain the edges recorded by setPin()/togglePin() since the last
// dispatch — this catches full press+release pulses that would be
// invisible to a level-diff sweep.
while (!emu::pinEdges.empty()) {
emu::PinEdge ev = emu::pinEdges.front();
emu::pinEdges.pop_front();
IsrEntry &e = isrs[ev.pin];
e.last = ev.to;
if (!e.fn) continue;
bool edge =
(e.mode == FALLING && ev.to == LOW) ||
(e.mode == RISING && ev.to == HIGH) ||
(e.mode == CHANGE);
if (edge) e.fn();
}
// Safety net: level-diff sweep for pins changed without setPin()
// (bulk init, harness resets). Claimed pins are skipped: the peripheral
// owns the line and the outside world cannot edge it.
for (int p = 0; p < 64; p++) { for (int p = 0; p < 64; p++) {
IsrEntry &e = isrs[p]; IsrEntry &e = isrs[p];
if (!e.fn) continue; if (!e.fn) continue;
if (pinDrivenBy[p]) { e.last = pinLevels[p]; continue; }
int cur = pinLevels[p]; int cur = pinLevels[p];
bool edge = bool edge =
(e.mode == FALLING && e.last == HIGH && cur == LOW) || (e.mode == FALLING && e.last == HIGH && cur == LOW) ||
@@ -150,6 +176,12 @@ inline void dispatchIsrs()
inline void attachInterrupt(int pin, isr_handler_t fn, int mode) inline void attachInterrupt(int pin, isr_handler_t fn, int mode)
{ {
emu::IsrEntry &e = emu::isrs[pin & 63]; emu::IsrEntry &e = emu::isrs[pin & 63];
if (emu::pinDrivenBy[pin & 63]) {
std::fprintf(stderr,
"[emu] WARNING: ISR attached to GPIO %d but the pin is "
"already claimed by %s — on hardware this input is dead\n",
pin & 63, emu::pinDrivenBy[pin & 63]);
}
e.fn = fn; e.fn = fn;
e.mode = mode; e.mode = mode;
e.last = emu::pinLevels[pin & 63]; // no phantom edge at attach time e.last = emu::pinLevels[pin & 63]; // no phantom edge at attach time
@@ -160,6 +192,42 @@ inline void detachInterrupt(int pin)
emu::isrs[pin & 63].fn = nullptr; emu::isrs[pin & 63].fn = nullptr;
} }
// Record that a peripheral driver took the pin over (GPIO-matrix parity).
// Claims warn loudly when they collide with an attached ISR — the exact
// signature of the sound-engine/GPIO0 trackball-click hijack — and put the
// line in its driven idle state (LOW).
namespace emu {
inline void claimPin(int pin, const char *owner)
{
pin &= 63;
if (pinDrivenBy[pin] && pinDrivenBy[pin] != owner) {
std::fprintf(stderr,
"[emu] WARNING: %s claims GPIO %d already claimed by %s\n",
owner, pin, pinDrivenBy[pin]);
}
pinDrivenBy[pin] = owner;
if (isrs[pin].fn) {
std::fprintf(stderr,
"[emu] WARNING: %s claims GPIO %d which has an attached "
"ISR — on hardware that input just died (note: GPIO0/1/3 "
"are MCLK-capable, so a zero-initialized i2s_pin_config_t "
"silently claims GPIO0)\n",
owner, pin);
}
pinLevels[pin] = 0;
isrs[pin].last = 0;
}
// Peripheral released the pin: back to a free pulled-up input.
inline void releasePin(int pin)
{
pin &= 63;
pinDrivenBy[pin] = nullptr;
pinLevels[pin] = 1;
isrs[pin].last = 1;
}
} // namespace emu
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// FreeRTOS-ish primitives (queues + detached threads) // FreeRTOS-ish primitives (queues + detached threads)
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
+18 -1
View File
@@ -6,6 +6,7 @@
#include <cstdint> #include <cstdint>
#include <cstddef> #include <cstddef>
#include <SDL3/SDL.h> #include <SDL3/SDL.h>
#include "../Arduino.h" // emu::claimPin — GPIO-matrix pin-ownership model
#define ESP_OK 0 #define ESP_OK 0
#define ESP_FAIL -1 #define ESP_FAIL -1
@@ -33,6 +34,8 @@ struct i2s_config_t {
}; };
struct i2s_pin_config_t { struct i2s_pin_config_t {
int mck_io_num; // mirrors the S3 header: GPIO0 is MCLK-capable, so a
// zero-initialized config silently claims GPIO0
int bck_io_num; int bck_io_num;
int ws_io_num; int ws_io_num;
int data_out_num; int data_out_num;
@@ -66,7 +69,21 @@ inline int i2s_driver_install(i2s_port_t, const i2s_config_t *cfg, int, void *)
return ESP_OK; return ESP_OK;
} }
inline int i2s_set_pin(i2s_port_t, const i2s_pin_config_t *) { return ESP_OK; } inline int i2s_set_pin(i2s_port_t, const i2s_pin_config_t *pins)
{
// GPIO-matrix parity: the real driver routes every configured pin to the
// I2S peripheral and OWNS it from then on — inputs/ISRs on the same GPIO
// die. In particular a zero-initialized i2s_pin_config_t carries
// mck_io_num == 0, and GPIO0 is MCLK-capable on the ESP32-S3 — which is
// exactly how the NetDeck sound engine used to kill the trackball click
// line (HW.md). emu::claimPin() makes that visible here.
if (pins->mck_io_num != I2S_PIN_NO_CHANGE) emu::claimPin(pins->mck_io_num, "i2s MCLK");
if (pins->bck_io_num != I2S_PIN_NO_CHANGE) emu::claimPin(pins->bck_io_num, "i2s BCK");
if (pins->ws_io_num != I2S_PIN_NO_CHANGE) emu::claimPin(pins->ws_io_num, "i2s WS");
if (pins->data_out_num != I2S_PIN_NO_CHANGE) emu::claimPin(pins->data_out_num, "i2s DOUT");
if (pins->data_in_num != I2S_PIN_NO_CHANGE) emu::claimPin(pins->data_in_num, "i2s DIN");
return ESP_OK;
}
inline int i2s_write(i2s_port_t, const void *src, size_t size, size_t *written, unsigned) inline int i2s_write(i2s_port_t, const void *src, size_t size, size_t *written, unsigned)
{ {
+35
View File
@@ -12,6 +12,41 @@ namespace emu {
// keyboard/mouse events in main.cpp. // keyboard/mouse events in main.cpp.
extern uint8_t pinLevels[64]; extern uint8_t pinLevels[64];
// Pin ownership (GPIO-matrix parity): on real hardware a peripheral driver
// (i2s_set_pin, SD, radio, ...) claims its pins and drives them — an input
// on the same GPIO then sees the driven level and its ISR never fires from
// the outside world. The shim records who owns what, so app bugs like
// "the sound engine claims GPIO0 (an MCLK-capable pin) and kills the
// trackball click" reproduce HERE instead of only on the device.
// nullptr = free input pin; otherwise the owner tag (for diagnostics).
extern const char *pinDrivenBy[64];
// Edge events recorded by setPin()/togglePin() and drained by
// dispatchIsrs(). This makes the emulated ISRs level-change-quantized
// like the hardware latch: a press+release fully contained between two
// dispatches still yields its edge (the old level-diff sweep silently
// swallowed such pulses).
struct PinEdge { int pin, from, to; };
extern std::deque<PinEdge> pinEdges;
// Write a pin the way the SDL host input would (external world side).
// Writes to a pin claimed by a peripheral are ignored — on hardware the
// GPIO matrix owns that line and the outside world can't move it.
inline void setPin(int pin, int level)
{
pin &= 63;
if (pinDrivenBy[pin]) return;
int from = pinLevels[pin];
if (from == level) return;
pinLevels[pin] = (uint8_t)level;
pinEdges.push_back({pin, from, level});
}
inline void togglePin(int pin)
{
pin &= 63;
setPin(pin, pinLevels[pin] ? 0 : 1);
}
// GT911 touch emulation (left mouse button on the canvas) // GT911 touch emulation (left mouse button on the canvas)
extern bool touchDown; extern bool touchDown;
extern int touchX; extern int touchX;
+38 -4
View File
@@ -29,6 +29,7 @@ struct Evt {
int x, y; // tap coords int x, y; // tap coords
bool fired = false; bool fired = false;
int holdIters = 0; int holdIters = 0;
bool pin = false; // trackball centre press (GPIO0 pulse) instead
}; };
static std::vector<Evt> g_evts; static std::vector<Evt> g_evts;
@@ -36,13 +37,23 @@ static unsigned long g_iters = 0;
static void schedule(double at, char key) { g_evts.push_back({at, key, 0, 0}); } static void schedule(double at, char key) { g_evts.push_back({at, key, 0, 0}); }
static void scheduleTap(double at, int x, int y) { g_evts.push_back({at, 0, x, y}); } static void scheduleTap(double at, int x, int y) { g_evts.push_back({at, 0, x, y}); }
static void schedulePin(double at)
{
Evt e;
e.at = at;
e.pin = true;
g_evts.push_back(e);
}
static void pumpEvents(double el) static void pumpEvents(double el)
{ {
for (auto &e : g_evts) { for (auto &e : g_evts) {
if (!e.fired && el >= e.at) { if (!e.fired && el >= e.at) {
e.fired = true; e.fired = true;
if (e.key) { if (e.pin) {
emu::setPin(BOARD_BOOT_PIN, LOW); // trackball centre press
e.holdIters = 2; // released 2 iterations later
} else if (e.key) {
test::typeKey(e.key); test::typeKey(e.key);
} else { } else {
emu::touchDown = true; emu::touchDown = true;
@@ -51,7 +62,8 @@ static void pumpEvents(double el)
e.holdIters = 60; // ~80 ms press, like main.cpp e.holdIters = 60; // ~80 ms press, like main.cpp
} }
} else if (e.fired && e.holdIters > 0 && --e.holdIters == 0) { } else if (e.fired && e.holdIters > 0 && --e.holdIters == 0) {
emu::touchDown = false; // release -> pollTouch edge if (e.pin) emu::setPin(BOARD_BOOT_PIN, HIGH); // click release
else emu::touchDown = false; // release -> pollTouch edge
} }
} }
} }
@@ -158,11 +170,33 @@ TEST(e2e/corridor_assault)
EXPECT(garrisonHit || test::serialHas("[combat]")); EXPECT(garrisonHit || test::serialHas("[combat]"));
} }
// The trackball centre click must act exactly like a screen tap. This drives
// the FULL device pipeline (attachTrackball ISR -> tbClicks latch ->
// applyTrackball release gate -> registerClick) — and it doubles as the
// regression for the I2S sound engine silently claiming GPIO0 as its MCLK
// output (a zero-initialized i2s_pin_config_t), which killed the click line
// on hardware while every emulator build looked fine. With the pin-ownership
// model in the shim, the claimed GPIO0 is a dead input here too, so this
// journey fails until the sketch stops claiming the pin.
TEST(e2e/trackball_click)
{
reboot();
EXPECT(pumpUntil(8.0, bootDone));
test::serialClear();
schedulePin(1.0); // trackball centre click
EXPECT(pumpFor(3.0));
EXPECT(test::serialHas("[click]")); // registered (beacon or blocked)
}
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
// headless: no window needed — rendering goes into the shim framebuffer // headless: no window needed — rendering goes into the shim framebuffer.
// AUDIO matters for parity too: without it the sketch's i2s_driver_install
// fails early and i2s_set_pin() never runs, so the shim's pin-ownership
// model (and any bug it exists to catch) would stay dormant in E2E.
::setenv("SDL_VIDEODRIVER", "dummy", 1); ::setenv("SDL_VIDEODRIVER", "dummy", 1);
if (!SDL_Init(SDL_INIT_VIDEO)) { ::setenv("SDL_AUDIODRIVER", "dummy", 1);
if (!SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO)) {
std::printf("SDL_Init failed: %s\n", SDL_GetError()); std::printf("SDL_Init failed: %s\n", SDL_GetError());
return 2; return 2;
} }
+2
View File
@@ -14,6 +14,8 @@
namespace emu { namespace emu {
uint8_t pinLevels[64]; uint8_t pinLevels[64];
const char *pinDrivenBy[64];
std::deque<PinEdge> pinEdges;
bool touchDown = false; bool touchDown = false;
int touchX = 0, touchY = 0; int touchX = 0, touchY = 0;
std::deque<uint8_t> keyboard; std::deque<uint8_t> keyboard;
+41
View File
@@ -347,3 +347,44 @@ TEST(unit/fog_sight_covers_marine_fire_range)
units[3].tx = 12; units[3].ty = 12; // droid at the edge tile units[3].tx = 12; units[3].ty = 12; // droid at the edge tile
EXPECT_EQ(acquireTarget(0), 3); // marine locks it in the light EXPECT_EQ(acquireTarget(0), 3); // marine locks it in the light
} }
// --- emulator shim: GPIO-matrix pin ownership ------------------------------
// Parity tests for the pin model that reproduces hardware-only bugs here:
// a peripheral driver (i2s_set_pin, ...) claims a pin and drives it, so an
// input/ISR on the same GPIO stops seeing the outside world. Regression for
// the sound engine silently claiming GPIO0 (MCLK-capable!) and killing the
// trackball click line on the device while every emulator build looked fine.
TEST(unit/shim_claimed_pin_is_dead_input)
{
test::resetInput();
emu::releasePin(BOARD_BOOT_PIN);
EXPECT_EQ(digitalRead(BOARD_BOOT_PIN), HIGH); // free pulled-up input
emu::claimPin(BOARD_BOOT_PIN, "test MCLK");
EXPECT(digitalRead(BOARD_BOOT_PIN) == LOW); // driven line, idles low
emu::setPin(BOARD_BOOT_PIN, HIGH); // the outside world...
EXPECT(digitalRead(BOARD_BOOT_PIN) == LOW); // ...cannot move it
emu::releasePin(BOARD_BOOT_PIN); // peripheral released
EXPECT_EQ(digitalRead(BOARD_BOOT_PIN), HIGH); // input again
}
TEST(unit/shim_edge_survives_same_dispatch_pulse)
{
// A press+release fully contained between two dispatchIsrs() calls used
// to be invisible to the level-diff sweep (the click was swallowed).
test::resetInput();
emu::releasePin(BOARD_BOOT_PIN);
detachInterrupt(BOARD_BOOT_PIN);
static int fires;
fires = 0;
attachInterrupt(BOARD_BOOT_PIN, [] { fires++; }, FALLING);
emu::setPin(BOARD_BOOT_PIN, LOW);
emu::setPin(BOARD_BOOT_PIN, HIGH); // pulse within one batch
emu::dispatchIsrs();
EXPECT_EQ(fires, 1); // the edge must survive
detachInterrupt(BOARD_BOOT_PIN);
emu::releasePin(BOARD_BOOT_PIN);
}
+22 -5
View File
@@ -1154,10 +1154,22 @@ static void pollKeyboard()
static void pollTouch() static void pollTouch()
{ {
if (!touchAvail) return; if (!touchAvail) return;
// Only act on a NEW press (wasDown guards held touches). If the GT911
// keeps isPressed() true after the finger lifted (stuck IRQ observed on
// some units), getPoint() reporting zero points is the real release
// signal — re-arm so the next physical tap still registers.
static bool wasDown = false; static bool wasDown = false;
bool down = touch.isPressed(); bool down = touch.isPressed();
if (!down) { wasDown = false; return; } if (!down) { wasDown = false; return; }
if (wasDown) return; // only act on new taps if (wasDown) {
// After a press, attempt to detect release by reading the point.
// If getPoint() reports no active point, the IRQ may have been stuck;
// reset wasDown so the next physical tap can be registered.
int16_t x[1], y[1];
int gp = touch.getPoint(x, y, 1);
if (gp <= 0) { wasDown = false; }
return;
}
int16_t x[1], y[1]; int16_t x[1], y[1];
int gp = touch.getPoint(x, y, 1); int gp = touch.getPoint(x, y, 1);
if (gp > 0) { if (gp > 0) {
@@ -1174,10 +1186,8 @@ static void pollTouch()
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
static void applyTrackball() static void applyTrackball()
{ {
uint32_t e[4], clicks; uint32_t e[4];
for (int i = 0; i < 4; i++) { e[i] = tbEdges[i]; tbEdges[i] = 0; } for (int i = 0; i < 4; i++) { e[i] = tbEdges[i]; tbEdges[i] = 0; }
clicks = tbClicks;
tbClicks = 0;
tbVelX += ((int32_t)e[0] - (int32_t)e[2]) * TB_IMPULSE; tbVelX += ((int32_t)e[0] - (int32_t)e[2]) * TB_IMPULSE;
tbVelY += ((int32_t)e[3] - (int32_t)e[1]) * TB_IMPULSE; tbVelY += ((int32_t)e[3] - (int32_t)e[1]) * TB_IMPULSE;
@@ -1200,7 +1210,14 @@ static void applyTrackball()
clampCursor(); clampCursor();
} }
if (clicks) registerClick(); // Click acts on RELEASE (like CrtTerminal): contact bounce fires several
// FALLING edges while the pin is low, so consuming only once the pin is
// back HIGH collapses the burst into one registered click — and a click
// still counts if the frame boundary lands mid-press.
if (tbClicks && digitalRead(BOARD_BOOT_PIN) == HIGH) {
tbClicks = 0;
registerClick();
}
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
+14
View File
@@ -188,3 +188,17 @@ E2E freeze-tint pixel assertions were stale since the diagonal-stripe
rework (pre-existing failures at HEAD under SDL2 too) — updated to the rework (pre-existing failures at HEAD under SDL2 too) — updated to the
committed pattern, sampled away from the freeze text. Full suite green: committed pattern, sampled away from the freeze text. Full suite green:
14 unit + 7 integration + 3 E2E journeys, 0 failures. 14 unit + 7 integration + 3 E2E journeys, 0 failures.
### Hardware fix: trackball click dead on device (fixed this commit)
The sound engine zero-initialized `i2s_pin_config_t`, leaving
`mck_io_num == 0`; `i2s_set_pin()` then claimed **GPIO0** — an
MCLK-capable pin on the S3 and the trackball centre / BOOT line — as
its MCLK output, so clicks never registered on hardware (verified with
an on-device diagnostic build: `pin0=0` at idle, one latched FALLING
edge). Fix: `pins.mck_io_num = I2S_PIN_NO_CHANGE` in
`sound_engine.cpp`; the click now also registers on release with
contact-bounce collapse (the proven `CrtTerminal` pattern). The
emulator gained a GPIO-matrix pin-ownership model + edge-accurate ISR
latch so this class of bug reproduces there (`e2e/trackball_click`
fails on the old code, passes on the fix) — see [HW.md](HW.md).
+5
View File
@@ -39,6 +39,11 @@ bool SoundEngine::begin()
pins.ws_io_num = BOARD_I2S_WS; pins.ws_io_num = BOARD_I2S_WS;
pins.data_out_num = BOARD_I2S_DOUT; pins.data_out_num = BOARD_I2S_DOUT;
pins.data_in_num = I2S_PIN_NO_CHANGE; pins.data_in_num = I2S_PIN_NO_CHANGE;
// MCLK must be explicitly disabled: `= {}` zero-initializes mck_io_num
// to 0, and i2s_set_pin() then claims GPIO0 as the MCLK output (GPIO0 is
// one of the few MCLK-capable pins) — GPIO0 is the trackball centre /
// BOOT line, so the click would go dead.
pins.mck_io_num = I2S_PIN_NO_CHANGE;
i2s_set_pin(SND_I2S_PORT, &pins); i2s_set_pin(SND_I2S_PORT, &pins);
q_ = xQueueCreate(12, sizeof(SndEvent)); q_ = xQueueCreate(12, sizeof(SndEvent));