haptics.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. #include "haptics.h"
  2. #include "bonds.h"
  3. #include "config.h"
  4. #include "rf_link.h"
  5. #include "usb_tx.h" // usbTxBoost/Unboost -- flood-rate CDC prints share the dcd DMA claim window
  6. #include "puck_hid.h" // puckLizardActive() -- gate the lizard-suppression keepalive
  7. #include "fault_diag.h" // faultDiagTrace() -- flight recorder
  8. // USBDevice.suspended() -> autonomous controller power-off on host sleep
  9. #include <Adafruit_TinyUSB.h>
  10. #include <Arduino.h>
  11. #include <string.h>
  12. uint8_t g_relayOp = 0xE3; // E3 poll
  13. // relay sub-TLV TYPE byte. Vestigial: rfConnFlushRelay derives the on-air type from the report id (0x05 for
  14. // actuators/haptics <0x87, 0x01 for config/settings/LED >=0x87). Still exposed over WebUSB diagnostics.
  15. uint8_t g_relaySub = 0x05;
  16. volatile uint8_t g_testHaptic = 0;
  17. volatile uint8_t g_hapticStop = 0;
  18. // Post-connect haptic block (see haptics.h): enabled + duration, both persisted and panel-adjustable.
  19. // Off by default -- opt in from the WebUSB panel if a controller's haptics come up degraded after connect.
  20. uint8_t g_hapticBlockOn = 0;
  21. uint16_t g_hapticBlockMs = HAPTIC_BLOCK_MS_DEFAULT;
  22. // id9 steering (see hapticTask): ON by default. Holds id9=0 while Steam is DRIVING (autonomous engine off,
  23. // Steam owns haptics, no reconnect buzz-latch) and lands id9=1 when lizard is PRESENTING (pure MODE_LIZARD
  24. // or Steam-closed fallback) so the autonomous pad layer -- the trackpad-tick source -- is on.
  25. // Persisted; console 'u' toggles for A/B.
  26. uint8_t g_lizKeep = 1;
  27. // EXPERIMENT (console "L87" toggles, persisted): land ALL relayed 0x87 SET_SETTINGS via type-01 framing so
  28. // Steam's haptic/amp/IMU config actually reaches the controller (verbatim relay = real-puck behavior),
  29. // instead of the whitelist discarding everything but LED(0x2D)/id9(0x09). Hypothesis: the buzz is the
  30. // controller's haptic engine left MISCONFIGURED because Steam's 0x87 config is discarded; landing it should
  31. // configure the engine correctly and stop the buzz. Default OFF (keeps the safe whitelist) because landing
  32. // reg 0x30 was once blamed for freezing the gyro and 0x34/0x35 for the buzz -- but those were OpenPuck's own
  33. // bad hapticReinit values, so Steam's real values may be fine. Flip it on hardware to test; flip back if the
  34. // gyro freezes.
  35. uint8_t g_landAll87 = 0;
  36. // Land Steam's amp/haptic-config 0x87 blocks (regs 0x18/0x2E/0x34/0x35, NOT gyro 0x30) so the controller's
  37. // amplifier is configured and haptics play as clean ticks instead of a default-amp buzz. On by default;
  38. // console "AMP" toggles for A/B. See the land01 whitelist in rfConnFlushRelay.
  39. uint8_t g_landAmp = 1;
  40. // Per-slot reconnect block. 0 = idle; non-zero = drop haptics aimed at this slot until millis() catches up.
  41. unsigned long g_hapticBlockUntil[NSLOT] = { 0 };
  42. // Controller power-off. CONFIRMED from a real Windows USB capture of the Valve puck: Steam's "turn off
  43. // controller" is the single feature-0x01 command 0x9F with payload ASCII "off!" (6F 66 66 21). The dongle
  44. // forwards host feature reports verbatim, so the controller acts on report 0x9F directly -- we relay it the
  45. // same way (E3 SET sub-TLV). The wire relay is NO-ACK, so send a small burst: a single lost frame must not
  46. // leave the controller on.
  47. void hapticSendShutdown(uint8_t slot)
  48. {
  49. static const uint8_t OFF[4] = { 0x6f, 0x66, 0x66, 0x21 }; // "off!"
  50. // slot-targeted: Steam's 0x9F arrives on ONE controller's interface and must power off only that
  51. // controller (broadcasting it killed every connected controller when the user turned off one). The
  52. // broadcast default (0xFF) remains for the triggers that logically mean "all off": host suspend and
  53. // the panel/test power-off button.
  54. faultDiagTrace(FR_OFF, slot);
  55. for (uint8_t i = 0; i < HAPTIC_SHUTDOWN_SHOTS; i++)
  56. relayEnqueue(0x9F, OFF, sizeof OFF, slot);
  57. }
  58. // millis of last 0x82 haptic OUTPUT relayed (Steam mode)
  59. static unsigned long g_haptic82Ms = 0;
  60. // a non-zero 0x82 haptic is currently active (awaiting host stop)
  61. static bool g_haptic82On = false;
  62. // millis of last translated host rumble (0x80), per-slot (4 XInput interfaces each have their own stream)
  63. static unsigned long g_rumble80Ms[NSLOT] = { 0 };
  64. // Steam/Triton rumble is latched on until an explicit zero report; tracked per-slot so each controller's
  65. // stuck-rumble watchdog is independent
  66. static bool g_rumble80On[NSLOT] = { false, false, false, false };
  67. // ---- relay rings: one per bond slot. Multi-producer (USB ISR + loop-context console/xinput), one consumer
  68. // per slot (rfConnFlushRelay on that slot's poll turn). Producers serialize under PRIMASK.
  69. struct RelayMsg {
  70. uint8_t rid, len;
  71. uint8_t data[RELAY_MAXP];
  72. };
  73. // deep enough to hold a full Steam settings/LED transaction burst without loss
  74. #define RELAY_QLEN 32
  75. static RelayMsg g_rq[NSLOT][RELAY_QLEN];
  76. static volatile uint8_t g_rqHead[NSLOT];
  77. static volatile uint8_t
  78. g_rqTail[NSLOT]; // head=next write, tail=next read; empty when equal
  79. static inline uint8_t rqNext(uint8_t i)
  80. {
  81. return (uint8_t)((i + 1) % RELAY_QLEN);
  82. }
  83. // Counts times a ring-drain loop hit its iteration cap = head/tail were desynced or corrupted (e.g. an
  84. // out-of-range g_rqHead from a stray write/stack overflow). These loops run with IRQs DISABLED, so an
  85. // unterminated one spins forever with interrupts off -> millis()/USB/SOF all freeze and only the hardware
  86. // watchdog recovers (an invisible "watchdog (hang)" -- the live stall monitor can't see it because the SOF
  87. // IRQ is dead). The cap turns that into a logged, recovered event instead of a hang. Surfaced on the panel.
  88. volatile uint16_t g_ringFault = 0;
  89. bool relayPending()
  90. {
  91. // check the current slot's queue; called from rfConnQueueHapticRelay which runs with g_curSlot set
  92. int cur = (g_curSlot >= 0 && g_curSlot < NSLOT) ? g_curSlot : 0;
  93. return g_rqHead[cur] != g_rqTail[cur];
  94. }
  95. bool relayEnqueue(uint8_t rid, const uint8_t *payload, uint8_t plen,
  96. uint8_t slot)
  97. {
  98. if (plen > RELAY_MAXP)
  99. plen = RELAY_MAXP;
  100. if (slot != 0xFF && slot >= NSLOT)
  101. return false;
  102. uint32_t pm = __get_PRIMASK();
  103. __disable_irq();
  104. // slot=0xFF: broadcast -- enqueue into every slot's ring.
  105. // Full queue: evict the oldest entry, never the newest. Steam bursts end with the commit/stop, so
  106. // dropping the oldest keeps the most-recent (meaningful) frame.
  107. uint8_t s0 = (slot == 0xFF) ? 0 : slot;
  108. uint8_t s1 = (slot == 0xFF) ? NSLOT : slot + 1;
  109. for (uint8_t s = s0; s < s1; s++) {
  110. uint8_t h = g_rqHead[s], nx = rqNext(h);
  111. if (nx == g_rqTail[s])
  112. g_rqTail[s] = rqNext(g_rqTail[s]);
  113. g_rq[s][h].rid = rid;
  114. g_rq[s][h].len = plen;
  115. if (plen)
  116. memcpy(g_rq[s][h].data, payload, plen);
  117. g_rqHead[s] = nx;
  118. }
  119. // Track last-haptic time for the Steam-mode quiet timeout (marks the 0x82 stream inactive after silence).
  120. if (rid == 0x82 || rid == 0x80)
  121. g_haptic82Ms = millis();
  122. __set_PRIMASK(pm);
  123. faultDiagTrace(FR_RELAY, (uint16_t)((slot << 8) | rid));
  124. return true;
  125. }
  126. #if OPK_LOG
  127. // diagnostic capture: a ring of the last OUTPUT reports Steam sends (rid/slot/bytes/ms), dumped with 'H'.
  128. struct HapLog {
  129. uint32_t ms;
  130. uint8_t slot, rid, n, b[16];
  131. }; // 16 payload bytes: capture full 0x87 settings frames
  132. // Big always-on ring: log EVERYTHING from boot (Steam writes, our TX-to-controller, link edges) so a rare
  133. // reconnect-buzz can be caught after the fact -- the trigger happens moments after boot, while this RAM is
  134. // fresh, and we dump it once the panel reconnects. 4096 * 20B ~= 80KB.
  135. #define HAPLOG_N 4096
  136. static HapLog g_hapLog[HAPLOG_N];
  137. static uint16_t g_hapHead = 0;
  138. static uint16_t g_hapTail =
  139. 0; // live/dump drain cursor (loop-context reader; chases g_hapHead)
  140. void hapLogAdd(uint8_t slot, uint8_t rid, const uint8_t *b, uint16_t n)
  141. {
  142. // Written from the USB SET ISR (handleSet) AND loop context (relay flush / link edges) -> guard g_hapHead.
  143. // Special slot markers for the diagnostic capture: 0xFE = a frame WE transmitted to the controller (TX
  144. // relay); 0xFD = a link state edge (b[0]=1 up, 0 down). Real Steam writes use the interface index (0..3).
  145. uint32_t pm = __get_PRIMASK();
  146. __disable_irq();
  147. HapLog &e = g_hapLog[g_hapHead];
  148. e.ms = millis();
  149. e.slot = slot;
  150. e.rid = rid;
  151. e.n = (uint8_t)(n > 255 ? 255 : n);
  152. for (int i = 0; i < 16; i++)
  153. e.b[i] = (i < (int)n) ? b[i] : 0;
  154. // uint16_t, NOT uint8_t: HAPLOG_N is 4096, so a uint8_t cast truncated the head to 0..255 and only the
  155. // first 256 ring slots were ever used (capture lost ~94% of its depth).
  156. g_hapHead = (uint16_t)((g_hapHead + 1) %
  157. (sizeof g_hapLog / sizeof g_hapLog[0]));
  158. __set_PRIMASK(pm);
  159. }
  160. void hapticDumpLog()
  161. {
  162. const uint16_t N = HAPLOG_N;
  163. uint32_t now = millis();
  164. Serial.printf("# --- capture history (now=%lu, curSlot=%d) ---\n",
  165. (unsigned long)now, g_curSlot);
  166. for (uint16_t i = 0; i < N; i++) {
  167. HapLog &e = g_hapLog[(uint16_t)((g_hapHead + i) % N)];
  168. if (!e.ms && !e.rid)
  169. continue;
  170. Serial.printf("# -%lums if%u rid=%02X n=%u:",
  171. (unsigned long)(now - e.ms), e.slot, e.rid, e.n);
  172. for (uint8_t j = 0; j < 16 && j < e.n; j++)
  173. Serial.printf(" %02X", e.b[j]);
  174. Serial.println();
  175. }
  176. Serial.println("# --- end ---");
  177. }
  178. // ---- drain cursor: stream entries to the WebUSB panel. resetDrain(false)=from "now" (live only);
  179. // resetDrain(true)=from the OLDEST entry (dump the whole ring from boot). pull skips empty slots. ----
  180. void hapLogResetDrain(bool fromBoot)
  181. {
  182. // oldest slot (the next-to-overwrite holds it)
  183. g_hapTail = fromBoot ? (uint16_t)((g_hapHead + 1) % HAPLOG_N) :
  184. // "now"
  185. g_hapHead;
  186. }
  187. bool hapLogPull(uint32_t *logMs, uint8_t *slot, uint8_t *rid, uint8_t *n,
  188. uint8_t bytes16[16])
  189. {
  190. while (g_hapTail != g_hapHead) {
  191. HapLog &e = g_hapLog[g_hapTail];
  192. g_hapTail = (uint16_t)((g_hapTail + 1) % HAPLOG_N);
  193. if (!e.ms && !e.rid)
  194. continue; // skip empty slot (ring not yet full)
  195. // Return the ABSOLUTE log time (millis since boot), not "age now". The panel drains in batches 100ms
  196. // apart, so an age computed here would jump between batches; the panel computes age vs the newest entry.
  197. *logMs = e.ms;
  198. *slot = e.slot;
  199. *rid = e.rid;
  200. *n = (e.n > 16) ? 16 : e.n;
  201. memcpy(bytes16, e.b, 16);
  202. return true;
  203. }
  204. return false;
  205. }
  206. #endif // OPK_LOG
  207. // Per-slot helpers. slot==-1 (default) checks the CURRENT poll slot (g_curSlot), used by flush-time code
  208. // paths that don't have a slot in hand. Callers with a real slot pass it in.
  209. bool hapticLinkUp(int slot)
  210. {
  211. int s = (slot >= 0) ? slot : g_curSlot;
  212. if (s < 0 || s >= NSLOT)
  213. return false;
  214. return g_slot[s].used && (millis() - g_connReplyMs[s]) < 300;
  215. }
  216. bool haptic82Blocked(int slot)
  217. {
  218. int s = (slot >= 0) ? slot : g_curSlot;
  219. if (s < 0 || s >= NSLOT)
  220. return true;
  221. return !hapticLinkUp(s) ||
  222. (g_hapticBlockUntil[s] &&
  223. (int32_t)(millis() - g_hapticBlockUntil[s]) < 0);
  224. }
  225. // "Is haptics from this USB interface's slot allowed through?" -- the slot must be currently connected.
  226. bool hapticRelaySlotOk(int slot)
  227. {
  228. return slot >= 0 && slot < NSLOT && hapticLinkUp(slot);
  229. }
  230. static bool haptic82PayloadOn(const uint8_t *p, uint16_t n)
  231. {
  232. if (n < 3)
  233. return false;
  234. for (uint16_t i = 2; i < n; i++)
  235. if (p[i])
  236. // observed form is [01 01 gain], but treat any trailing non-zero as active
  237. return true;
  238. return false;
  239. }
  240. static void hapticCancelPendingOn(int slot)
  241. {
  242. // void queued ON entries (stale haptics / rumble across a reconnect). Per-slot: only the reconnected
  243. // slot's queue is scrubbed -- another controller's pending haptics are its own business. slot=-1 keeps
  244. // the old scrub-everything behavior (boot).
  245. int c0 = (slot >= 0 && slot < NSLOT) ? slot : 0;
  246. int c1 = (slot >= 0 && slot < NSLOT) ? slot + 1 : NSLOT;
  247. uint32_t pm = __get_PRIMASK();
  248. __disable_irq();
  249. for (int s = c0; s < c1; s++) {
  250. uint8_t guard = RELAY_QLEN + 1;
  251. for (uint8_t i = g_rqTail[s]; i != g_rqHead[s]; i = rqNext(i)) {
  252. if (!guard--) { // desynced/corrupt ring -> recover, don't spin IRQs-off
  253. g_rqHead[s] = g_rqTail[s] = 0;
  254. g_ringFault++;
  255. faultDiagTrace(FR_RINGF, g_ringFault);
  256. break;
  257. }
  258. RelayMsg &m = g_rq[s][i];
  259. if (m.rid == 0x82) {
  260. bool on = false;
  261. for (uint8_t j = 2; j < m.len; j++)
  262. if (m.data[j]) {
  263. on = true;
  264. break;
  265. }
  266. if (on)
  267. m.rid = 0;
  268. }
  269. if (m.rid == 0x80) {
  270. bool on = false;
  271. for (uint8_t j = 0; j < m.len; j++)
  272. if (m.data[j]) {
  273. on = true;
  274. break;
  275. }
  276. if (on)
  277. m.rid = 0;
  278. }
  279. }
  280. }
  281. __set_PRIMASK(pm);
  282. }
  283. void haptic82HostReport(const uint8_t *p, uint16_t n)
  284. {
  285. if (n < 3)
  286. return;
  287. g_haptic82Ms = millis();
  288. // Track on/off only. Do NOT synthesize a stop burst: Steam's own stop is forwarded verbatim, and each extra
  289. // 0x82 is a discrete pad click -- the spurious end-of-movement "click"/buzz the real puck never produces.
  290. g_haptic82On = haptic82PayloadOn(p, n);
  291. }
  292. bool hapticSteamRumble(uint16_t lowFreq, uint16_t highFreq, uint8_t slot)
  293. {
  294. if (slot >= NSLOT)
  295. return false;
  296. // user rumble-strength scale (percent; 200 = double). Clamp to 16-bit.
  297. if (g_rumbleScale != 100) {
  298. uint32_t l = (uint32_t)lowFreq * g_rumbleScale / 100,
  299. h = (uint32_t)highFreq * g_rumbleScale / 100;
  300. lowFreq = (l > 0xFFFF) ? 0xFFFF : (uint16_t)l;
  301. highFreq = (h > 0xFFFF) ? 0xFFFF : (uint16_t)h;
  302. }
  303. bool on = lowFreq || highFreq;
  304. // Per-slot settle gate (the per-slot reconnect block + link-up check). 0x82 haptics in Steam mode use the
  305. // same gate; for XInput, the host only sends a stream while a controller is connected, so this also doubles
  306. // as "no controller here, no relay".
  307. if (on && haptic82Blocked(slot))
  308. return false;
  309. if (!on && !hapticLinkUp(slot))
  310. return false;
  311. // SDL's current Steam/Triton structs define output report 0x80 as:
  312. // type, uint16 intensity, {uint16 speed, int8 gain} left/right.
  313. // We map conventional gamepad low/high-frequency motors to left/right speeds and use max as intensity.
  314. uint16_t intensity = lowFreq > highFreq ? lowFreq : highFreq;
  315. uint8_t p[9];
  316. // haptic_type_t::HAPTIC_TYPE_RUMBLE; 0 is the off/zero report
  317. p[0] = on ? 0x04 : 0x00;
  318. p[1] = (uint8_t)(intensity & 0xFF);
  319. p[2] = (uint8_t)(intensity >> 8);
  320. p[3] = (uint8_t)(lowFreq & 0xFF);
  321. p[4] = (uint8_t)(lowFreq >> 8);
  322. p[5] = 0;
  323. p[6] = (uint8_t)(highFreq & 0xFF);
  324. p[7] = (uint8_t)(highFreq >> 8);
  325. p[8] = 0;
  326. if (!relayEnqueue(0x80, p, sizeof p, slot))
  327. return false;
  328. g_rumble80Ms[slot] = millis();
  329. g_rumble80On[slot] = on;
  330. return true;
  331. }
  332. // Queue a pending test-haptic / stop relay (runs inside the poll cadence -- never at raw loop rate). Test
  333. // haptics broadcast to all connected slots (slot 0xFF); the stop frame is broadcast too (a stuck latch can
  334. // affect any controller, and the haptic-engine clear-re-init is settings-only so it's harmless on healthy
  335. // ones).
  336. // Stability-test keepalive: while g_stabTest, buzz every connected controller for ~150ms once per 10s so an
  337. // unattended uptime measurement isn't ended by a controller idle-sleeping. Toggled by WebUSB cmd 0x0F; the
  338. // panel times uptime-until-reset. Reboots clear g_stabTest (the panel re-arms it on reconnect).
  339. bool g_stabTest = false;
  340. void hapticStabTask()
  341. {
  342. if (!g_stabTest)
  343. return;
  344. static const uint8_t on[3] = { 0x01, 0x01, 0xF7 };
  345. static const uint8_t off[3] = { 0x01, 0x01, 0x00 };
  346. static unsigned long lastOn = 0, offAt = 0;
  347. unsigned long now = millis();
  348. // Buzz only slots whose controller is actually answering polls (same 300ms liveness the panel/0x79 use).
  349. // The old 0xFF broadcast kept stuffing a powered-off controller's relay ring -- pure eviction churn plus
  350. // wasted TX at a radio that can't hear it, right inside the power-off hang window (issue #72 repro).
  351. auto enqLive = [&](const uint8_t *p) {
  352. for (uint8_t s = 0; s < NSLOT; s++)
  353. if (g_slot[s].used && g_connReplyMs[s] &&
  354. (unsigned long)(now - g_connReplyMs[s]) < 300u)
  355. relayEnqueue(0x82, p, 3, s);
  356. };
  357. if (lastOn == 0 || (uint32_t)(now - lastOn) >= 10000u) {
  358. lastOn = now;
  359. enqLive(on);
  360. offAt = now + 150;
  361. }
  362. if (offAt && (int32_t)(now - offAt) >= 0) {
  363. enqLive(off);
  364. offAt = 0;
  365. }
  366. }
  367. void rfConnQueueHapticRelay()
  368. {
  369. if (relayPending())
  370. return; // host relays first; injectables wait for an idle cycle
  371. static const uint8_t HAP_ON[3] = { 0x01, 0x01, 0xF7 };
  372. static const uint8_t HAP_OFF[3] = { 0x01, 0x01, 0x00 };
  373. if (g_testHaptic) {
  374. if (relayEnqueue(0x82, HAP_ON, 3, 0xFF))
  375. g_testHaptic--;
  376. } else if (g_hapticStop && !g_xbox) {
  377. if (relayEnqueue(0x82, HAP_OFF, 3, 0xFF))
  378. g_hapticStop--;
  379. }
  380. }
  381. // rfConnFlushRelay(ch, s1): drain one entry from the current slot's relay queue and TX it. Each slot's queue
  382. // is independent, so each controller only sees its own commands. With N connected slots the per-slot relay
  383. // rate is 1/N of the per-cycle rate; sustained buzz streams are still 1 packet/cycle/slot.
  384. bool rfConnFlushRelay(uint8_t ch, uint8_t s1)
  385. {
  386. int cur = (g_curSlot >= 0 && g_curSlot < NSLOT) ? g_curSlot : 0;
  387. // Snapshot one entry under a short critical section. relayEnqueue() (the producer) runs on the
  388. // high-priority usbd task and, when the ring is full, evicts the oldest by advancing g_rqTail itself --
  389. // the same variable this consumer reads/advances. Reading the entry while a producer could overwrite it
  390. // is a torn read (and dual-writing g_rqTail desyncs head/tail), so copy the entry out and consume the
  391. // slot atomically here, then do the (slow) RF TX on the copy with interrupts enabled.
  392. RelayMsg msg;
  393. bool have = false;
  394. uint32_t pm = __get_PRIMASK();
  395. __disable_irq();
  396. uint8_t guard = RELAY_QLEN + 1;
  397. while (g_rqTail[cur] != g_rqHead[cur]) {
  398. if (!guard--) { // desynced/corrupt ring -> recover, don't spin IRQs-off (watchdog-hang class)
  399. g_rqHead[cur] = g_rqTail[cur] = 0;
  400. g_ringFault++;
  401. faultDiagTrace(FR_RINGF, g_ringFault);
  402. break;
  403. }
  404. RelayMsg &m = g_rq[cur][g_rqTail[cur]];
  405. g_rqTail[cur] = rqNext(g_rqTail[cur]); // consume the slot
  406. // rid 0 = entry voided by hapticCancelPendingOn -> skip
  407. if (m.rid) {
  408. msg = m; // copy out before the producer can reuse the slot
  409. have = true;
  410. break;
  411. }
  412. }
  413. __set_PRIMASK(pm);
  414. if (have) {
  415. RelayMsg &m = msg;
  416. {
  417. uint8_t rl = m.len;
  418. if (rl > RELAY_MAXP)
  419. rl = RELAY_MAXP;
  420. // On-air sub-TLV framing. CONFIRMED from real puck<->controller sniffs: a command LANDS on
  421. // the controller only with the type-01 + inner-len form E3 [2+rl][01][rid][innerlen][data];
  422. // the legacy form E3 [1+rl][05][rid][data] makes the controller DISCARD any 0x87+ command.
  423. //
  424. // Whitelist type-01 to exactly three commands: LED brightness (0x87 reg 0x2D), power-off
  425. // (0x9F), and the STANDALONE lizard-suppression keepalive (0x87 [09 00 00] -- rl==3 so a
  426. // multi-register block that merely STARTS with 0x09 can't smuggle other registers into
  427. // landing). Setting index 9 = digital-mappings/lizard-active (ibex FUN_0001f554 decomp);
  428. // the real puck lands id9=0 every 3s -- without it the controller's revert timer fires,
  429. // re-enables autonomous mode and resets ALL settings to defaults (audible amp pop +
  430. // autonomous touchpad ticks = the spurious mid-session buzz). Other 0x87 writes (e.g. reg
  431. // 0x30 IMU enable, 0x34/0x35 haptic amplitude) must stay on legacy form -- landing 0x30
  432. // freezes the gyro; landing 0x34/0x35 causes the connect buzz.
  433. // Amp/haptic-config registers (0x18/0x2E/0x34/0x35): LAND these so the controller's amplifier is
  434. // configured the way Steam intends -> haptics (0x82 ticks, connect cue) play as clean ticks
  435. // instead of the default-amp BUZZ we get when the config is discarded. Steam sends these grouped
  436. // in 0x87 blocks that START with one of those regs and do NOT contain 0x30 (the gyro reg, which
  437. // must NOT land -- it freezes the gyro), so gating on data[0] lands the amp block without 0x30.
  438. // (g_landAmp, console "AMP"; on by default. The old "landing 0x34/0x35 buzzes" note was really the
  439. // 0x81 storm, now removed.)
  440. bool ampReg = (m.data[0] == 0x18 || m.data[0] == 0x2E ||
  441. m.data[0] == 0x34 || m.data[0] == 0x35);
  442. bool land01 =
  443. (m.rid == 0x9F) ||
  444. (m.rid == 0x87 && rl >= 1 &&
  445. m.data[0] == 0x2D) ||
  446. (m.rid == 0x87 && rl == 3 &&
  447. m.data[0] == 0x09) ||
  448. (g_landAmp && m.rid == 0x87 && rl >= 1 &&
  449. ampReg) ||
  450. // experiment: land EVERY 0x87 verbatim (real-puck relay) when enabled
  451. (g_landAll87 && m.rid == 0x87);
  452. uint8_t p[5 + RELAY_MAXP], plen;
  453. if (land01) {
  454. p[0] = g_relayOp;
  455. p[1] = (uint8_t)(2 + rl);
  456. p[2] = 0x01;
  457. p[3] = m.rid;
  458. p[4] = rl;
  459. memcpy(p + 5, m.data, rl);
  460. plen = (uint8_t)(5 + rl);
  461. } else {
  462. p[0] = g_relayOp;
  463. p[1] = (uint8_t)(1 + rl);
  464. p[2] = 0x05;
  465. p[3] = m.rid;
  466. memcpy(p + 4, m.data, rl);
  467. plen = (uint8_t)(4 + rl);
  468. }
  469. hapLogAdd(0xFE, m.rid, m.data, rl);
  470. // Lifecycle log (CDC debug boot): EXACTLY what we TX to the controller, so a capture shows
  471. // whether OpenPuck (or Steam in the background) pokes the controller right before a buzz
  472. // latches -- the piece the I45 stream (controller->us) can't show. Low rate outside a haptic
  473. // burst; guarded so it never blocks the loop. cur = target slot.
  474. if (Serial.availableForWrite() > 60) {
  475. // boosted: this print runs at relay-flood rate and CDC flush enters the same
  476. // TinyUSB DMA claim window as HID sends (the issue-72 livelock; see usb_tx.cpp)
  477. usbTxBoost();
  478. Serial.printf("# TX t=%lu slot%d %s rid=%02X:",
  479. (unsigned long)millis(), cur,
  480. land01 ? "L01" : "l05", m.rid);
  481. for (uint8_t i = 0; i < rl && i < 8; i++)
  482. Serial.printf(" %02X", m.data[i]);
  483. Serial.println();
  484. usbTxUnboost();
  485. }
  486. // slot was already consumed under the critical section above.
  487. // s1 carries a PID distinct from the GET poll (caller cycles it) so the controller's ESB
  488. // dedup never treats the GET as a retransmit of this relay. 80us RX: relay is NO-ACK.
  489. rfConnTx(ch, s1, p, plen,
  490. 80); // one relay per poll cycle
  491. }
  492. }
  493. return have; // true = a relay frame went out this cycle (steals a reply window from the E3 poll)
  494. }
  495. // Haptic-subsystem re-init: the captured sequence Steam sends when it (re)takes control (0x81 reset + 0x87
  496. // register writes). Brightness (reg 0x2D) is omitted to avoid stomping the LED. The 0x87 frames go out on
  497. // legacy framing so the controller discards them; the three 0x81 frames are the effective reset. slot=0xFF
  498. // broadcasts to all connected controllers (the re-init is settings-only and harmless on healthy controllers).
  499. // One-shot SET_SETTINGS (0x87) write of the controller's GLOBAL trackpad-haptics enable. The controller plays
  500. // touchpad haptic sequences autonomously (haptics-sequencer-touchpad) gated by settings/haptics/enabled; in the
  501. // emulated (non-Steam) modes the host never sends SC haptic reports, so the only way to silence the pad buzz is
  502. // to write this setting. Wire format [id][val u16 LE] -- confirmed from the controller's SET_SETTINGS handler
  503. // (decomp FUN_0001f61c; id 0x30 == settings/sensors/imu/mode is the cross-check anchor in the same id space).
  504. // The exact id for settings/haptics/enabled needs a one-time `scmd labels` HW read (candidates from the captured
  505. // reinit: 0x18 / 0x2e / 0x34 / 0x35). Until it is set, SETTING_HAPTICS_ENABLED stays 0xFF and this is inert.
  506. #define SETTING_HAPTICS_ENABLED 0xFF
  507. void hapticSetPadEnabled(uint8_t slot, bool on)
  508. {
  509. #if SETTING_HAPTICS_ENABLED != 0xFF
  510. uint8_t pl[3] = { SETTING_HAPTICS_ENABLED, (uint8_t)(on ? 1 : 0), 0 };
  511. relayEnqueue(0x87, pl, 3, slot);
  512. #else
  513. (void)slot;
  514. (void)on;
  515. #endif
  516. }
  517. void hapticReinit(uint8_t slot)
  518. {
  519. static const uint8_t H30[] = { 0x30, 0x00, 0x00, 0x07, 0x07,
  520. 0x00, 0x08, 0x07, 0x00, 0x31,
  521. 0x02, 0x00, 0x52, 0x03, 0x00 };
  522. static const uint8_t H18[] = { 0x18, 0x00, 0x00, 0x2e, 0x00,
  523. 0x00, 0x34, 0xff, 0xff, 0x35,
  524. 0xff, 0xff, 0x34, 0xff, 0xff };
  525. static const uint8_t H35[] = { 0x35, 0xff, 0xff, 0x2e, 0x00, 0x00 };
  526. static const uint8_t T81A[] = {
  527. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  528. };
  529. static const uint8_t T81B[] = {
  530. 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  531. };
  532. // reset action (FUN_0001f554) -- Steam sends this first
  533. relayEnqueue(0x81, nullptr, 0, slot);
  534. relayEnqueue(0x87, H30, sizeof H30, slot);
  535. // haptic config (enabled/amplifier/gain): the part that clears a latch
  536. relayEnqueue(0x87, H18, sizeof H18, slot);
  537. relayEnqueue(0x87, H35, sizeof H35, slot);
  538. relayEnqueue(0x81, T81A, sizeof T81A, slot);
  539. relayEnqueue(0x81, T81B, sizeof T81B, slot);
  540. // Re-apply the active emulated type's trackpad-haptics preference last (after the haptic-config writes
  541. // above, which would otherwise re-enable it). Default-on types send "enable"; Switch (padHaptics=0)
  542. // disables. Inert until the setting id is captured.
  543. hapticSetPadEnabled(slot, g_padHaptics != 0);
  544. // Apply the configured LED brightness for the active emulated type. Steam sets the
  545. // brightness each session; emulated modes never do, so the controller comes up at
  546. // full brightness. 0 = no override (preserve controller default).
  547. if (g_etype < ET_COUNT && g_ledBright > 0) {
  548. uint8_t pl[3] = { 0x2D, g_ledBright, 0x00 };
  549. relayEnqueue(0x87, pl, sizeof pl, slot);
  550. }
  551. }
  552. void hapticInit()
  553. {
  554. g_haptic82On = false;
  555. g_hapticStop = 0;
  556. for (int s = 0; s < NSLOT; s++) {
  557. g_rqHead[s] = g_rqTail[s] = 0;
  558. g_rumble80On[s] = false;
  559. g_rumble80Ms[s] = 0;
  560. // post-connect haptic block is permanently disabled (not armed, not configurable)
  561. g_hapticBlockUntil[s] = 0;
  562. }
  563. }
  564. // Schedule the clearing re-init for ONE slot. Called on the reliable first-reply signal from rf_link and
  565. // again from hapticTask's link-up edge detector. Strictly per-slot: only the reconnected controller gets
  566. // re-inits / its pending haptics scrubbed -- the other controllers hear nothing about it.
  567. void hapticOnReconnect(int slot)
  568. {
  569. if (slot < 0 || slot >= NSLOT)
  570. return;
  571. // post-connect haptic block is permanently disabled -- relay haptics immediately on (re)connect
  572. g_hapticBlockUntil[slot] = 0;
  573. g_haptic82On = false;
  574. g_rumble80On[slot] = false;
  575. g_rumble80Ms[slot] = 0;
  576. // Scrub haptics queued before the link came up (stale across the reconnect) -- this slot only.
  577. hapticCancelPendingOn(slot);
  578. // NO automatic haptic re-init. hapticReinit lands 0x81 (CLEAR DIGITAL MAPPINGS -- rid < 0x87 so it
  579. // EXECUTES even on legacy framing). 0x81 is NON-IDEMPOTENT (ibex FUN_0001f554): EVERY call re-runs the
  580. // lizard-disable event + func_0x0001bbf0 (a hardware peripheral re-arm unique to the 0x81 path) -- so
  581. // firing 8 across the connect window = 8 audible clicks = the "repeated non-periodic clicks at connect"
  582. // the real puck (which clears ONCE then holds) never produces. The clearing re-init stays available on
  583. // demand (WebUSB "Clear stuck buzz" -> hapticReinit), just not sprayed at connect.
  584. uint8_t mk = 2;
  585. hapLogAdd(0xFD, 0xEE, &mk, 1);
  586. }
  587. void hapticTask()
  588. {
  589. // id9 steering (SET_SETTINGS index 9 = digital-mappings / the controller's AUTONOMOUS mapping+haptic
  590. // engine). Two regimes, switched by who is actually driving:
  591. // - Steam DRIVING (MODE_STEAM + heartbeat alive): hold id9=0 every LIZKEEP_MS, the way the real puck
  592. // does (sniff1.json) -- keeps the autonomous engine off so Steam owns haptics and the engine can't
  593. // latch the "deep-inside" reconnect buzz. 0x87 is change-guarded in the controller, so the repeat
  594. // is silent (no 0x81-style click).
  595. // - lizard PRESENTING (pure MODE_LIZARD, or MODE_STEAM with Steam closed): land id9=1 ONCE per
  596. // connect/lizard episode. id9 gates the whole autonomous pad layer INCLUDING the trackpad ticks --
  597. // the old always-in-MODE_STEAM id9=0 hold is why Steam-closed lizard lost its ticks, and a stale
  598. // id9=0 from a previous Steam session (mode switch without a controller power cycle) is why pure
  599. // lizard could come up tickless too. Landing 1 explicitly restores the pad layer immediately
  600. // instead of waiting for the controller's revert timer (which also resets settings = audible pop).
  601. // Emulated modes (Xbox/Switch/DS) are untouched: lizardActive() is false there and the id9=0 hold
  602. // stays scoped to MODE_STEAM, exactly as before.
  603. if (g_lizKeep && modeIsPuck(g_usbMode)) {
  604. static unsigned long lastKeep[NSLOT] = { 0 };
  605. static bool landedAuto[NSLOT] = { false };
  606. static const uint8_t K0[3] = { 0x09, 0x00, 0x00 };
  607. static const uint8_t K1[3] = { 0x09, 0x01, 0x00 };
  608. bool liz = puckLizardActive();
  609. for (int s = 0; s < NSLOT; s++) {
  610. if (!g_slot[s].used || !hapticLinkUp(s)) {
  611. // re-land id9=1 on the next (re)connect: a fresh controller defaults to
  612. // autonomous, but one carrying our previous session's id9=0 does not
  613. landedAuto[s] = false;
  614. lastKeep[s] = 0;
  615. continue;
  616. }
  617. if (liz) {
  618. if (!landedAuto[s]) {
  619. landedAuto[s] = true;
  620. relayEnqueue(0x87, K1, sizeof K1,
  621. (uint8_t)s);
  622. }
  623. } else {
  624. landedAuto[s] = false;
  625. if (lastKeep[s] &&
  626. (uint32_t)(millis() - lastKeep[s]) <
  627. LIZKEEP_MS)
  628. continue;
  629. lastKeep[s] = millis();
  630. relayEnqueue(0x87, K0, sizeof K0, (uint8_t)s);
  631. }
  632. }
  633. }
  634. // Per-slot link-edge detect (backup for hapticOnReconnect in rf_link).
  635. static bool wasHapticLinkUp[NSLOT] = { 0 };
  636. for (int s = 0; s < NSLOT; s++) {
  637. if (!g_slot[s].used)
  638. continue;
  639. bool up = hapticLinkUp(s);
  640. if (up && !wasHapticLinkUp[s]) {
  641. uint8_t mk = 1;
  642. hapLogAdd(0xFD, 0xEE, &mk, 1);
  643. hapticOnReconnect(s);
  644. }
  645. if (!up && wasHapticLinkUp[s]) {
  646. uint8_t mk = 0;
  647. hapLogAdd(0xFD, 0xEE, &mk, 1);
  648. // Lifecycle log (CDC debug boot): the 300ms link-up watchdog saw this slot go silent. Pairs
  649. // with the CONNECT/RECONNECT lines from rf_link so a session of cycles shows the full
  650. // down->up cadence -- how often the link actually drops (churn) vs stays up.
  651. if (Serial.availableForWrite() > 50)
  652. Serial.printf("# LC t=%lu slot%d link DOWN\n",
  653. (unsigned long)millis(), s);
  654. }
  655. wasHapticLinkUp[s] = up;
  656. }
  657. // (No automatic re-init firing -- see hapticOnReconnect: the connect-time 0x81 storm was the click train
  658. // the real puck never makes. hapticReinit is on-demand only, via the WebUSB "Clear stuck buzz" button.)
  659. // Power-off on host sleep: only when VBUS is present (genuine sleep, not a cable unplug which also
  660. // trips the suspend edge briefly) AND the suspend has PERSISTED >= SUSPEND_OFF_MS. A brief USB
  661. // selective-suspend (host idle power-management) resumes in <1s; firing the power-off on its edge
  662. // powered the controllers off ourselves -> random drop/reconnect churn. Arm only on a genuine
  663. // resume->suspend edge (wasSusp=true at boot suppresses a false fire on boot-into-suspended).
  664. static bool wasSusp = true;
  665. static unsigned long suspSinceMs = 0;
  666. static bool suspArmed = false;
  667. bool susp = USBDevice.suspended();
  668. bool vbus = (NRF_POWER->USBREGSTATUS &
  669. POWER_USBREGSTATUS_VBUSDETECT_Msk) != 0;
  670. if (susp && !wasSusp) {
  671. suspSinceMs = millis();
  672. suspArmed = true;
  673. faultDiagTrace(FR_SUSP, 0);
  674. }
  675. if (!susp) {
  676. if (wasSusp)
  677. faultDiagTrace(FR_RESUME, 0);
  678. suspArmed = false;
  679. }
  680. if (suspArmed && vbus && (millis() - suspSinceMs) >= SUSPEND_OFF_MS) {
  681. hapticSendShutdown();
  682. suspArmed = false; // fire once per suspend
  683. }
  684. wasSusp = susp;
  685. // Steam-mode quiet timeout: mark 0x82 stream inactive. No synthesized stop -- Steam forwards its own.
  686. if (!g_xbox && g_haptic82On &&
  687. millis() - g_haptic82Ms > HAPTIC_QUIET_MS)
  688. g_haptic82On = false;
  689. // Per-slot stuck-rumble watchdog: force zero after 2.5s without a refresh.
  690. for (int s = 0; s < NSLOT; s++) {
  691. if (g_rumble80On[s] && millis() - g_rumble80Ms[s] > 2500u)
  692. hapticSteamRumble(0, 0, (uint8_t)s);
  693. }
  694. // (No automatic idle-clear re-init either: same 0x81-click reason. A genuinely stuck buzz is cleared
  695. // on demand from the panel. Verbatim relay -- like the real puck -- is the steady-state behavior.)
  696. }