puck_hid.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. #include "puck_hid.h"
  2. #include "bonds.h"
  3. #include "config.h"
  4. #include "identity.h"
  5. #include "haptics.h"
  6. #include "fault_diag.h"
  7. #include "rf_link.h"
  8. #include "triton.h"
  9. #include "mode_lizard.h"
  10. #include "wake_hid.h"
  11. #include "usb_tx.h"
  12. #include <Adafruit_TinyUSB.h>
  13. #include <Arduino.h>
  14. #include <string.h>
  15. uint8_t g_fwdNewOnly = 1;
  16. // Content dedup for the Steam input forward: only forward a 0x45/0x42 report when its body EXCLUDING the
  17. // counter byte differs from the last one forwarded on that slot. The controller's counter (rep[1]) FREE-RUNS
  18. // -- it advances on every reply even with static input -- so the seq-based g_fwdNewOnly can't suppress true
  19. // repeats, and a poll rate above the controller's ~250 Hz sample rate forwards identical inputs with only the
  20. // counter bumped (host tester reads >250/s for a <=250 Hz controller). Content dedup is what the real puck
  21. // effectively does. On by default; console "CD" toggles for A/B.
  22. uint8_t g_fwdContentDedup = 1;
  23. SteamPuckController g_steamPuck;
  24. // Cloned puck HID report descriptor: mouse(0x40)+keyboard(0x41)+vendor(FF00) with the 63-byte FEATURE
  25. // command reports on report id 1/2. Each of the 4 interfaces uses this.
  26. static const uint8_t PUCK_HID_DESC[] = {
  27. 0x05, 0x01, 0x09, 0x02, 0xA1, 0x01, 0x85, 0x40, 0x09, 0x01, 0xA1, 0x00,
  28. 0x05, 0x09, 0x19, 0x01, 0x29, 0x02, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01,
  29. 0x95, 0x02, 0x81, 0x02, 0x75, 0x06, 0x95, 0x01, 0x81, 0x01, 0x05, 0x01,
  30. 0x09, 0x30, 0x09, 0x31, 0x15, 0x81, 0x25, 0x7F, 0x75, 0x08, 0x95, 0x02,
  31. 0x81, 0x06, 0x95, 0x01, 0x09, 0x38, 0x81, 0x06, 0x05, 0x0C, 0x0A, 0x38,
  32. 0x02, 0x95, 0x01, 0x81, 0x06, 0xC0, 0xC0, 0x05, 0x01, 0x09, 0x06, 0xA1,
  33. 0x01, 0x85, 0x41, 0x05, 0x07, 0x19, 0xE0, 0x29, 0xE7, 0x15, 0x00, 0x25,
  34. 0x01, 0x75, 0x01, 0x95, 0x08, 0x81, 0x02, 0x81, 0x01, 0x19, 0x00, 0x29,
  35. 0x65, 0x15, 0x00, 0x25, 0x65, 0x75, 0x08, 0x95, 0x06, 0x81, 0x00, 0xC0,
  36. 0x06, 0x00, 0xFF, 0x09, 0x01, 0xA1, 0x01, 0x85, 0x42, 0x15, 0x00, 0x26,
  37. 0xFF, 0x00, 0x75, 0x08, 0x95, 0x35, 0x09, 0x42, 0x81, 0x02, 0x85, 0x44,
  38. 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x05, 0x09, 0x44, 0x81,
  39. 0x02, 0x85, 0x79, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x01,
  40. 0x09, 0x79, 0x81, 0x02, 0x85, 0x43, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75,
  41. 0x08, 0x95, 0x0E, 0x09, 0x43, 0x81, 0x02, 0x85, 0x7B, 0x15, 0x00, 0x26,
  42. 0xFF, 0x00, 0x75, 0x08, 0x95, 0x0C, 0x09, 0x7B, 0x81, 0x02, 0x85, 0x45,
  43. 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x2D, 0x09, 0x45, 0x81,
  44. 0x02, 0x85, 0x80, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x09,
  45. 0x09, 0x80, 0x91, 0x02, 0x85, 0x81, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75,
  46. 0x08, 0x95, 0x07, 0x09, 0x81, 0x91, 0x02, 0x85, 0x82, 0x15, 0x00, 0x26,
  47. 0xFF, 0x00, 0x75, 0x08, 0x95, 0x03, 0x09, 0x82, 0x91, 0x02, 0x85, 0x83,
  48. 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x09, 0x09, 0x83, 0x91,
  49. 0x02, 0x85, 0x84, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x08,
  50. 0x09, 0x84, 0x91, 0x02, 0x85, 0x85, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75,
  51. 0x08, 0x95, 0x03, 0x09, 0x85, 0x91, 0x02, 0x85, 0x86, 0x15, 0x00, 0x26,
  52. 0xFF, 0x00, 0x75, 0x08, 0x95, 0x03, 0x09, 0x86, 0x91, 0x02, 0x85, 0x87,
  53. 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x3F, 0x09, 0x87, 0x91,
  54. 0x02, 0x85, 0x89, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x3F,
  55. 0x09, 0x89, 0x91, 0x02, 0x85, 0x88, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75,
  56. 0x08, 0x95, 0x3F, 0x09, 0x88, 0x91, 0x02, 0x85, 0x01, 0x95, 0x3F, 0x09,
  57. 0x01, 0xB1, 0x02, 0x85, 0x02, 0x95, 0x3F, 0x09, 0x01, 0xB1, 0x02, 0xC0
  58. };
  59. // Pure MODE_LIZARD only: same puck/lizard descriptor plus a tiny Consumer Control report for media keys.
  60. // MODE_STEAM must keep PUCK_HID_DESC verbatim so Steam's controller/haptics path sees the normal puck shape.
  61. static const uint8_t PUCK_LIZARD_HID_DESC[] = {
  62. 0x05, 0x01, 0x09, 0x02, 0xA1, 0x01, 0x85, 0x40, 0x09, 0x01, 0xA1, 0x00,
  63. 0x05, 0x09, 0x19, 0x01, 0x29, 0x02, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01,
  64. 0x95, 0x02, 0x81, 0x02, 0x75, 0x06, 0x95, 0x01, 0x81, 0x01, 0x05, 0x01,
  65. 0x09, 0x30, 0x09, 0x31, 0x15, 0x81, 0x25, 0x7F, 0x75, 0x08, 0x95, 0x02,
  66. 0x81, 0x06, 0x95, 0x01, 0x09, 0x38, 0x81, 0x06, 0x05, 0x0C, 0x0A, 0x38,
  67. 0x02, 0x95, 0x01, 0x81, 0x06, 0xC0, 0xC0, 0x05, 0x01, 0x09, 0x06, 0xA1,
  68. 0x01, 0x85, 0x41, 0x05, 0x07, 0x19, 0xE0, 0x29, 0xE7, 0x15, 0x00, 0x25,
  69. 0x01, 0x75, 0x01, 0x95, 0x08, 0x81, 0x02, 0x81, 0x01, 0x19, 0x00, 0x29,
  70. 0x65, 0x15, 0x00, 0x25, 0x65, 0x75, 0x08, 0x95, 0x06, 0x81, 0x00, 0xC0,
  71. 0x06, 0x00, 0xFF, 0x09, 0x01, 0xA1, 0x01, 0x85, 0x42, 0x15, 0x00, 0x26,
  72. 0xFF, 0x00, 0x75, 0x08, 0x95, 0x35, 0x09, 0x42, 0x81, 0x02, 0x85, 0x44,
  73. 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x05, 0x09, 0x44, 0x81,
  74. 0x02, 0x85, 0x79, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x01,
  75. 0x09, 0x79, 0x81, 0x02, 0x85, 0x43, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75,
  76. 0x08, 0x95, 0x0E, 0x09, 0x43, 0x81, 0x02, 0x85, 0x7B, 0x15, 0x00, 0x26,
  77. 0xFF, 0x00, 0x75, 0x08, 0x95, 0x0C, 0x09, 0x7B, 0x81, 0x02, 0x85, 0x45,
  78. 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x2D, 0x09, 0x45, 0x81,
  79. 0x02, 0x85, 0x80, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x09,
  80. 0x09, 0x80, 0x91, 0x02, 0x85, 0x81, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75,
  81. 0x08, 0x95, 0x07, 0x09, 0x81, 0x91, 0x02, 0x85, 0x82, 0x15, 0x00, 0x26,
  82. 0xFF, 0x00, 0x75, 0x08, 0x95, 0x03, 0x09, 0x82, 0x91, 0x02, 0x85, 0x83,
  83. 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x09, 0x09, 0x83, 0x91,
  84. 0x02, 0x85, 0x84, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x08,
  85. 0x09, 0x84, 0x91, 0x02, 0x85, 0x85, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75,
  86. 0x08, 0x95, 0x03, 0x09, 0x85, 0x91, 0x02, 0x85, 0x86, 0x15, 0x00, 0x26,
  87. 0xFF, 0x00, 0x75, 0x08, 0x95, 0x03, 0x09, 0x86, 0x91, 0x02, 0x85, 0x87,
  88. 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x3F, 0x09, 0x87, 0x91,
  89. 0x02, 0x85, 0x89, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x3F,
  90. 0x09, 0x89, 0x91, 0x02, 0x85, 0x88, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75,
  91. 0x08, 0x95, 0x3F, 0x09, 0x88, 0x91, 0x02, 0x85, 0x01, 0x95, 0x3F, 0x09,
  92. 0x01, 0xB1, 0x02, 0x85, 0x02, 0x95, 0x3F, 0x09, 0x01, 0xB1, 0x02, 0xC0,
  93. 0x05, 0x0C, 0x09, 0x01, 0xA1, 0x01, 0x85, 0x03, 0x15, 0x00, 0x25, 0x01,
  94. 0x09, 0xE9, 0x09, 0xEA, 0x75, 0x01, 0x95, 0x02, 0x81, 0x02, 0x75, 0x06,
  95. 0x95, 0x01, 0x81, 0x01, 0xC0
  96. };
  97. static Adafruit_USBD_HID hid[NSLOT];
  98. // Drop Steam's relayed 0x81 CLEAR_DIGITAL_MAPPINGS in Steam mode (console "S81" toggles; on by default). It's
  99. // the confirmed amp-clicker in Steam's per-connect config and OpenPuck doesn't need it (own input translation
  100. // + id9=0 keepalive). Reversible from the console if it regresses.
  101. bool g_drop81 = true;
  102. // Per-slot shadow of the controller's SET_SETTINGS_VALUES array (id-indexed u16, ids 0..0x52). Steam writes
  103. // it with 0x87 and READS IT BACK with 0x89 to verify its config "took"; on the real puck the controller
  104. // answers 0x89 from this array. OpenPuck can't relay-and-return over the NO-ACK RF link, so it maintains the
  105. // shadow here and answers 0x89 from it -- WITHOUT this, Steam's verify never matches and it re-clears (0x81)
  106. // + re-writes (0x87) forever = the connect config storm that buzzes the amp and floods the usbd task.
  107. static uint16_t g_setShadow[NSLOT][0x53];
  108. // ---- feature-command capture (diagnostic) ---------------------------------------------------------------
  109. // Log the USB feature command channel (Steam's SET/GET) to serial to see the connect handshake -- WITHOUT a
  110. // Serial.printf on the fragile 800B usbd task (that path can blow the stack -> LOCKUP; it's why production
  111. // avoids printf here). handleSet/handleGet (usbd task) push a compact record under PRIMASK; puckCmdLogDrain()
  112. // prints them from loop() context. When g_cmdCapture is on, the high-rate I45 input stream is also suppressed
  113. // (rf_link) so the command sequence is readable. Toggle from the console with "FC".
  114. bool g_cmdCapture = true;
  115. struct FCmdRec {
  116. uint8_t dir; // 0 = SET (host->puck write), 1 = GET (host read)
  117. uint8_t iface; // HID interface index = bond slot the command hit
  118. uint8_t rid, cmd, len, b[10];
  119. };
  120. static FCmdRec g_fc[32];
  121. static volatile uint8_t g_fcHead, g_fcTail;
  122. static void fcPush(uint8_t dir, int iface, uint8_t rid, uint8_t cmd,
  123. uint8_t len, const uint8_t *b, uint8_t n)
  124. {
  125. if (!g_cmdCapture)
  126. return;
  127. uint32_t pm = __get_PRIMASK();
  128. __disable_irq();
  129. uint8_t h = g_fcHead, nx = (uint8_t)((h + 1) & 31);
  130. if (nx !=
  131. g_fcTail) { // drop-newest when full (loop drains fast); never block the usbd task
  132. g_fc[h].dir = dir;
  133. g_fc[h].iface = (uint8_t)iface;
  134. g_fc[h].rid = rid;
  135. g_fc[h].cmd = cmd;
  136. g_fc[h].len = len;
  137. for (uint8_t i = 0; i < 10; i++)
  138. g_fc[h].b[i] = (i < n) ? b[i] : 0;
  139. g_fcHead = nx;
  140. }
  141. __set_PRIMASK(pm);
  142. }
  143. void puckCmdLogDrain(void)
  144. {
  145. // boosted: runs at Steam's feature-storm rate and CDC flush enters the same TinyUSB DMA claim window
  146. // as HID sends (the issue-72 livelock; see usb_tx.cpp)
  147. usbTxBoost();
  148. while (g_fcHead != g_fcTail) {
  149. if (Serial.availableForWrite() < 70)
  150. break; // don't stall loop on CDC backpressure; resume next iteration
  151. FCmdRec r = g_fc[g_fcTail];
  152. g_fcTail = (uint8_t)((g_fcTail + 1) & 31);
  153. Serial.printf("# FC %s if=%u rid=%u cmd=%02X len=%u:",
  154. r.dir ? "GET" : "SET", r.iface, r.rid, r.cmd,
  155. r.len);
  156. for (uint8_t i = 0; i < 10; i++)
  157. Serial.printf(" %02X", r.b[i]);
  158. Serial.println();
  159. }
  160. usbTxUnboost();
  161. }
  162. // ===================== seamless LIZARD decision =====================
  163. // Steam, while running, re-sends settings report 0x87 (lizard-off) every ~3s as a heartbeat (captured on HW),
  164. // and ANY OUTPUT report likewise stamps g_steamAliveMs. When the heartbeat stops we fall back to lizard, so the
  165. // controller drives desktop keyboard+mouse whenever Steam isn't running. MODE_LIZARD forces lizard always.
  166. // millis of last Steam OUTPUT/settings write; 0 at boot => lizard until Steam appears
  167. static unsigned long g_steamAliveMs = 0;
  168. // Fall back to lizard this long after Steam's ~3s settings heartbeat stops. Keep >2x the cadence: the haptic
  169. // relay is gated by !lizardActive(), so a shorter window lets a jittered/delayed heartbeat flip lizard
  170. // mid-session while Steam is still running -> a haptic arriving in that window gets gated out (dropped). 7s
  171. // tolerates one missed beat. Do not shorten without a lizard trigger independent of the heartbeat timeout.
  172. #define LIZARD_WD_MS 7000u
  173. static bool g_autoLizard =
  174. true; // master switch; false => Steam mode always forwards 0x45
  175. // Single source of truth, shared by the USB input path AND the haptic relay gate: if we ever relay a 0x82 to
  176. // the controller while presenting lizard (Steam isn't reading 0x45 back), Steam loops the same haptic -> buzz.
  177. static inline bool steamDrivingGamepad()
  178. {
  179. return g_steamAliveMs && (millis() - g_steamAliveMs < LIZARD_WD_MS);
  180. }
  181. static inline bool lizardActive()
  182. {
  183. return modeIsPuck(g_usbMode) &&
  184. (g_usbMode == MODE_LIZARD ||
  185. (g_autoLizard && !steamDrivingGamepad()));
  186. }
  187. // Public accessor for the haptic layer (haptics.cpp gates the lizard-suppression keepalive on this).
  188. bool puckLizardActive()
  189. {
  190. return lizardActive();
  191. }
  192. static inline void hostStampAlive()
  193. {
  194. g_steamAliveMs = millis();
  195. }
  196. // Right after the host resumes from suspend, MUTE input forwarding briefly. Otherwise the controller's input
  197. // in that instant (a trackpad click/trigger, or residual button state from the wake gesture) gets forwarded
  198. // as a real click/keypress into the just-woken desktop. Set when task() sees the suspended->active transition.
  199. static unsigned long g_resumeMs = 0;
  200. #define POST_RESUME_MUTE_MS 1500u
  201. // How long to keep re-asserting the 0x79 DISCONNECT edge to Steam after a controller drops, so a single
  202. // lost report can't strand Steam in "connected" (see task()). Bounded to avoid forever-spamming disc.
  203. #define DISC_RESEND_MS 6000u
  204. // ===================== puck feature command channel =====================
  205. // `slot` is the interface index (interface N == bond slot N).
  206. static void handleSet(int slot, uint8_t rid, hid_report_type_t type,
  207. uint8_t const *b, uint16_t n)
  208. {
  209. // Steam OUTPUT reports 0x80-0x89. The haptic/actuator reports (0x80-0x86) are relayed to the controller,
  210. // and ONLY when they arrive on the CONNECTED slot's interface: we have one controller but expose 4 puck
  211. // slots, and a report aimed at a DIFFERENT slot made the controller buzz at random (the slot gate below
  212. // fixes that). Must NOT clamp to 0x82-only: ping/grip/test haptics ride other report IDs (0x85/0x86). The
  213. // 63-byte settings/config reports 0x87/0x88/0x89 are NOT haptics and reach the controller via the
  214. // feature-0x01 passthrough path instead.
  215. if (type == HID_REPORT_TYPE_OUTPUT) {
  216. if (rid >= 0x80 && rid <= 0x89) {
  217. // capture ALL OUTPUT reports (even un-relayed) for the 'H' dump
  218. hapLogAdd((uint8_t)slot, rid, b, n);
  219. // ANY Steam OUTPUT report (not just the 0x87 heartbeat) means Steam is present and driving ->
  220. // leave lizard for gamepad NOW, so a haptic arriving before the first 0x87 isn't relayed while
  221. // we're still presenting lizard (-> buzz loop).
  222. hostStampAlive();
  223. }
  224. // Post-resume mute also gates haptics: while onReport45 is muted Steam reads NO 0x45 back, which is the
  225. // exact condition under which Steam loops the same haptic command (-> connect/wake buzz loop).
  226. bool muted = g_resumeMs &&
  227. millis() - g_resumeMs < POST_RESUME_MUTE_MS;
  228. // Drop the OUTPUT-report form of 0x81 too (Steam's haptic-reset action, a 7-byte report id 0x81 with
  229. // payloads 00../01..). Same amp-clicker as the feature-0x01 0x81; g_drop81 only covered the feature
  230. // path, so this OUTPUT form was still leaking through and clicking. OpenPuck doesn't need it.
  231. bool dropOut81 =
  232. (g_drop81 && g_usbMode == MODE_STEAM && rid == 0x81);
  233. if (g_hapticRelay && rid >= 0x80 && rid <= 0x86 && !dropOut81 &&
  234. n >= 1 && hapticRelaySlotOk(slot) && !lizardActive() &&
  235. !muted) {
  236. if (!haptic82Blocked(slot)) {
  237. relayEnqueue(rid, b,
  238. (uint8_t)(n > RELAY_MAXP ?
  239. RELAY_MAXP :
  240. n),
  241. (uint8_t)slot);
  242. // Track on/off from what was actually RELAYED (= the controller's believed state): a
  243. // BLOCKED stop must leave "on" set (controller may be latched -> reconnect stop-burst),
  244. // a blocked ON must not set it (nothing reached the controller -> no spurious clicks).
  245. if (rid == 0x82)
  246. haptic82HostReport(b, n);
  247. }
  248. }
  249. #if OPK_LOG
  250. // Per-report Serial echo: gated to the diagnostic build only. handleSet runs on the TinyUSB device
  251. // task, whose FreeRTOS stack is just 800 bytes; a Serial.printf there costs 200-500B and, stacked
  252. // under TinyUSB's control-transfer frames + a preempting USB ISR, can blow the stack -> the exact
  253. // SP-corruption-during-exception-entry that shows up as RR_LOCKUP. Production keeps this path
  254. // printf-free; the same data is already in the OPK_LOG capture ring (hapLogAdd) for the WebUSB panel.
  255. if (Serial.availableForWrite() > 80) {
  256. Serial.printf("# OUT if%d rid=%02X n=%u:", slot, rid,
  257. n);
  258. for (uint16_t i = 0; i < n && i < 14; i++)
  259. Serial.printf(" %02X", b[i]);
  260. Serial.println();
  261. }
  262. #endif
  263. return;
  264. }
  265. if (type != HID_REPORT_TYPE_FEATURE || n < 1)
  266. return;
  267. Slot &S = g_slot[slot];
  268. uint8_t cmd = b[0], len = (n > 1) ? b[1] : 0;
  269. const uint8_t *pl = b + 2;
  270. uint16_t pln = (n >= 2) ? n - 2 : 0;
  271. // Capture EVERY feature SET (the whole cmd channel: 0x83 attr, 0xAE strings, 0xB4 conn, 0xA2/A3 bond, the
  272. // feature-1 relay, AND any host battery query) to the WebUSB ring so the panel's capture view shows it.
  273. hapLogAdd((uint8_t)slot, cmd, b, n);
  274. // ...and to the serial feature-command capture (diagnostic; drained in loop, see puckCmdLogDrain).
  275. fcPush(0, slot, rid, cmd, len, pl, pln > 10 ? 10 : (uint8_t)pln);
  276. // ...and to the flight recorder (survives a watchdog reset). This runs ON the fragile usbd task, so the
  277. // command flood that (theory) overflows it lands in the post-mortem trail rather than being lost with USB.
  278. faultDiagTrace(FR_SET, (uint16_t)((rid << 8) | cmd));
  279. // settings/haptic/LED report (incl. 0x87 lizard-off heartbeat, SDL Triton lizard-disable)
  280. if (cmd >= 0x80 && cmd <= 0x89)
  281. hostStampAlive();
  282. // Controller power-off: Steam's "turn off controller" is feature-0x01 frame 9F 04 6F 66 66 21 ("off!"),
  283. // confirmed from a real puck capture. The feature-0x01 relay below forwards it once; hapticSendShutdown
  284. // bursts it for NO-ACK reliability. Slot-targeted: the command arrived on THIS controller's interface,
  285. // so only this controller powers off (broadcasting killed all connected controllers at once).
  286. if (rid == 1 && cmd == 0x9F)
  287. hapticSendShutdown((uint8_t)slot);
  288. // report 0x01 = raw passthrough -> queue for RF relay to the controller
  289. if (rid == 1 && n >= 2) {
  290. // (feature-1 commands -- haptics, LED, 0x87 settings, 0x9F power-off -- are captured by the
  291. // general feature-SET hapLogAdd above.)
  292. bool haptic82 = (cmd == 0x82 && len <= pln);
  293. bool muted = g_resumeMs &&
  294. millis() - g_resumeMs < POST_RESUME_MUTE_MS;
  295. // Steam-mode: DROP the relayed 0x81 CLEAR_DIGITAL_MAPPINGS (g_drop81, console "S81"). It EXECUTES on
  296. // the controller (rid<0x87, legacy framing) and each one re-arms the haptic amp (non-idempotent, ibex
  297. // func_0x0001bbf0) = the connect click/buzz; Steam sends ~13 in its per-connect config. OpenPuck does
  298. // its OWN input translation and holds mappings cleared via the id9=0 keepalive, so it does NOT need the
  299. // controller's mapping engine -> Steam's 0x81 is pure downside here. The manual "Clear stuck buzz"
  300. // (hapticReinit) sends its own 0x81 via relayEnqueue directly, so that cure path is unaffected.
  301. bool drop =
  302. (g_drop81 && g_usbMode == MODE_STEAM && cmd == 0x81);
  303. // Do NOT relay commands OpenPuck answers LOCALLY (identity/bond/settings READS). Relaying them to the
  304. // controller is pointless (their reply can't come back over the NO-ACK RF link -- we answer from the
  305. // handleSet/handleGet switch), and 0x83 GET_ATTRIBUTES in particular is < 0x87 so it EXECUTES on the
  306. // controller -- captured as the remaining periodic CLICK, fired every time Steam re-polls identity
  307. // (0x83/0xAE on all 4 interfaces). Only actuator/config commands (0x80-0x82/0x84-0x88 haptics+config,
  308. // 0x9F power) should reach the controller.
  309. bool localAnswer = (cmd == 0x83 || cmd == 0x89 || cmd == 0xAE ||
  310. cmd == 0xA2 || cmd == 0xA3 || cmd == 0xAD ||
  311. cmd == 0xB4 || cmd == 0xED || cmd == 0xA4);
  312. // never push haptics while presenting lizard (Steam isn't reading 0x45 -> would buzz-loop).
  313. // HR toggle (g_hapticRelay): when off, suppress the actuator/haptic range (0x80-0x86) -- the
  314. // trackpad texture-feedback stream Steam pushes while dragging -- to isolate its cost on drag
  315. // smoothness. Config (0x87/0x88) and power-off (0x9F) still relay so nothing else regresses.
  316. bool hapticCmd = (cmd >= 0x80 && cmd <= 0x86);
  317. bool relayOk = hapticRelaySlotOk(slot) && !drop &&
  318. !localAnswer &&
  319. !(haptic82 && (lizardActive() || muted)) &&
  320. !(hapticCmd && !g_hapticRelay);
  321. if (relayOk && (!haptic82 || !haptic82Blocked(slot))) {
  322. // Relay the DECLARED length (up to the 60B RF frame ceiling), not a truncation: Steam's
  323. // multi-register 0x87 settings blocks (LED brightness) and calibration writes exceed the old
  324. // 18B cap, and the chopped frames were why those settings never landed on the controller.
  325. uint8_t rl = (len <= pln) ? len : (uint8_t)pln;
  326. #if OPK_LOG
  327. if (len > RELAY_MAXP && Serial.availableForWrite() > 60)
  328. Serial.printf(
  329. "# RELAY TRUNC cmd=%02X len=%u>%u\n",
  330. cmd, len, (unsigned)RELAY_MAXP);
  331. #endif
  332. relayEnqueue(cmd, pl, rl, (uint8_t)slot);
  333. // track from RELAYED frames only (see the OUTPUT path)
  334. if (haptic82)
  335. haptic82HostReport(pl, len);
  336. }
  337. }
  338. #if OPK_LOG
  339. // Diagnostic-build only -- see the OUTPUT-path note: no Serial.printf on the 800B usbd-task stack in
  340. // production (LOCKUP mitigation). The feature SET is already captured to the OPK_LOG ring above.
  341. if (Serial.availableForWrite() > 80) {
  342. Serial.printf("# SET if%d rid=%02X cmd=%02X len=%u:", slot, rid,
  343. cmd, len);
  344. for (uint16_t i = 0; i < n && i < 14; i++)
  345. Serial.printf(" %02X", b[i]);
  346. Serial.println();
  347. }
  348. #endif
  349. memset(S.resp, 0, sizeof S.resp);
  350. S.resp_len = 0;
  351. switch (cmd) {
  352. case 0x83:
  353. S.resp[0] = 0x83;
  354. S.resp[1] = sizeof ATTR83;
  355. memcpy(S.resp + 2, ATTR83, sizeof ATTR83);
  356. // Report-id 1 = an attributes query RELAYED to the bonded CONTROLLER; it must report the CONTROLLER's
  357. // product id (0x1302), NOT the puck/dongle's (0x1304) -- else Steam sees "a controller with a dongle's
  358. // id" (HANDOFF.md) and drops to the LEGACY 0x81 CLEAR_DIGITAL_MAPPINGS init path, whose rapid re-arm
  359. // storm is the connect buzz; with the correct id Steam uses the modern quiet 0x87 id9=0 path. Report-id
  360. // 2 stays the puck (0x1304). ATTR83 stores product as u32 LE at offset 1, so only the low byte flips
  361. // (0x04 -> 0x02); everything else in the blob is identical.
  362. if (rid == 1)
  363. S.resp[2 + 1] =
  364. 0x02; // product 0x1304 -> 0x1302 (controller)
  365. S.resp_len = 63;
  366. break;
  367. case 0xAE: {
  368. uint8_t idx = pln > 0 ? pl[0] : 1;
  369. // Report-id 1 = string attributes of the bonded CONTROLLER, not the puck. Steam matches the connected
  370. // controller to its bond by SERIAL: it reads the controller's serial here (rid 1) and compares to the
  371. // 16-byte serial in the bond record it reads via 0xA3. OpenPuck was returning the PUCK's serial (g_unit,
  372. // "FXB..."), which never matches any bond's controller serial ("FXA...") -> Steam can't associate the
  373. // controller with a puck -> "paired to" list is EMPTY -> Steam treats it as unconfigured and re-runs the
  374. // 0x81/0x87 config storm every connect (the buzz). So on rid 1, answer with the CONTROLLER's serial from
  375. // this interface's bond record (rec[8..24], the same 16-byte serial 0xA3 returns). Captured: Steam
  376. // hammered this read (AE x39 on rid1) exactly because the identity never matched. rid 2 = puck (unchanged).
  377. // idx 0/1/4 = board/unit/alt serial (real controller returns the SAME serial for 0 and 4; the clone
  378. // was returning "NA" for idx 4, which failed Steam's read -> retry).
  379. S.resp[0] = 0xAE;
  380. S.resp[1] = 0x14;
  381. S.resp[2] = idx;
  382. memset(S.resp + 3, 0, 60);
  383. if (rid == 1 && slot >= 0 && slot < NSLOT &&
  384. g_slot[slot].used && (idx == 0 || idx == 1 || idx == 4)) {
  385. // THIS slot's paired-controller serial, straight from its bond record (rec[8..24], the same
  386. // 16-byte serial 0xA3 returns) -- per device, nothing hardcoded. Copied without a stack temp
  387. // (this runs on the fragile 800B usbd task; every byte off the stack helps under a Steam
  388. // re-enumeration burst).
  389. memcpy(S.resp + 3, g_slot[slot].rec + 8, 16);
  390. } else {
  391. // rid 2 = the puck's own board/unit serials (device-derived). Any other idx -> "NA".
  392. const char *s = (rid == 1) ? "NA" :
  393. (idx == 0 || idx == 4) ? g_board :
  394. (idx == 1) ? g_unit :
  395. "NA";
  396. memcpy(S.resp + 3, s, strlen(s));
  397. }
  398. S.resp_len = 63;
  399. break;
  400. }
  401. // connection/version state per slot: value 0x02 = controller connected, 0x01 = not
  402. case 0xB4:
  403. // SDL Triton polls this on init; treat like Steam contact so we forward 0x45
  404. hostStampAlive();
  405. S.resp[0] = 0xB4;
  406. S.resp[1] = 0x01;
  407. S.resp[2] = (slot >= 0 && slot < NSLOT && !g_xbox &&
  408. g_slot[slot].used &&
  409. (millis() - g_connReplyMs[slot] < 500)) ?
  410. 0x02 :
  411. 0x01;
  412. S.resp_len = 63;
  413. break;
  414. case 0xAD:
  415. g_pairing = (pln > 0 && pl[0] != 0);
  416. #if OPK_LOG
  417. Serial.printf("# pairing %s\n", g_pairing ? "ON" : "off");
  418. #endif
  419. S.resp[0] = 0xAD;
  420. S.resp[1] = 0;
  421. S.resp_len = 63;
  422. break;
  423. case 0xA2: // write/clear THIS interface's slot
  424. if (len >= 24 && pln >= 24) {
  425. if (recEmpty(pl)) {
  426. S.used = false;
  427. memset(S.rec, 0, 24);
  428. } else {
  429. memcpy(S.rec, pl, 24);
  430. S.used = true;
  431. }
  432. g_dirty = true;
  433. #if OPK_LOG
  434. Serial.printf("# slot %d %s\n", slot,
  435. recEmpty(pl) ? "cleared" : "bonded");
  436. #endif
  437. }
  438. S.resp[0] = 0xA2;
  439. S.resp[1] = 0;
  440. S.resp_len = 63;
  441. break;
  442. case 0xA3: // read THIS interface's slot
  443. S.resp[0] = 0xA3;
  444. S.resp[1] = 0x18;
  445. memset(S.resp + 2, 0, 24);
  446. if (S.used)
  447. memcpy(S.resp + 2, S.rec, 24);
  448. S.resp_len = 63;
  449. break;
  450. case 0x87:
  451. // SET_SETTINGS_VALUES: payload = N x [id][val16 LE]. Shadow each into g_setShadow[slot] so the 0x89
  452. // read-back below matches what Steam wrote -- this is THE fix that stops Steam's endless config-verify
  453. // retry (the 0x81/0x87 storm that buzzes the amp). (Still relayed to the controller by the feature-1
  454. // path above; this just maintains the dongle-side shadow the real controller would return on 0x89.)
  455. // ACK with [0x87][0], not the default payload echo (a clean success reply, like the real dongle).
  456. if (slot >= 0 && slot < NSLOT)
  457. for (uint16_t i = 0; i + 2 < pln; i += 3) {
  458. uint8_t id = pl[i];
  459. if (id < 0x53)
  460. g_setShadow[slot][id] =
  461. (uint16_t)(pl[i + 1] |
  462. (pl[i + 2] << 8));
  463. }
  464. S.resp[0] = 0x87;
  465. S.resp[1] = 0;
  466. S.resp_len = 63;
  467. break;
  468. case 0x89: {
  469. // GET_SETTINGS_VALUES: Steam reads back setting `id` (payload[0]) from the id-indexed array. Answer
  470. // from the shadow 0x87 populated: [0x89][3][id][val16 LE]. (Steam didn't use 0x89 in the captured
  471. // session -- it provisions via 0xED below -- but this is the correct real-dongle behavior; harmless.)
  472. uint8_t id = (pln > 0) ? pl[0] : 0;
  473. uint16_t v = (slot >= 0 && slot < NSLOT && id < 0x53) ?
  474. g_setShadow[slot][id] :
  475. 0;
  476. S.resp[0] = 0x89;
  477. S.resp[1] = 3;
  478. S.resp[2] = id;
  479. S.resp[3] = (uint8_t)v;
  480. S.resp[4] = (uint8_t)(v >> 8);
  481. S.resp_len = 63;
  482. break;
  483. }
  484. case 0xED: {
  485. // GET-SETTING-BY-PATH (keyed). Steam SETs the path string, then GETs the value; the REAL controller
  486. // returns the setting's value, but OpenPuck was ECHOING the path -> Steam sees the controller as
  487. // un-provisioned/un-bonded and re-runs its full LEGACY config every connect (0x81 CLEAR_DIGITAL_MAPPINGS
  488. // = the amp clicks/buzz; captured: 0xED reads of "esb/bond"/"user/wireless_transport" that got echoed).
  489. // Answer the paths Steam checks at connect so it treats the controller as provisioned + bonded:
  490. // esb/bond -> this slot's 24-byte bond record (the controller's record of ITS puck)
  491. // esb/bond_2 -> a 2nd-puck bond; OpenPuck bonds one puck per slot -> absent (empty)
  492. // user/wireless_transport -> 1 byte = the ACTIVE (connected) slot's transport code (see below)
  493. // Anything else -> empty ([0xED][0]) rather than a garbage path echo.
  494. const char *p = (const char *)pl;
  495. uint16_t pl_n = pln;
  496. auto pathIs = [&](const char *k) -> bool {
  497. uint16_t kl = (uint16_t)strlen(k);
  498. return pl_n >= kl && memcmp(p, k, kl) == 0 &&
  499. (pl_n == kl || p[kl] == 0);
  500. };
  501. S.resp[0] = 0xED;
  502. if (slot >= 0 && slot < NSLOT && g_slot[slot].used &&
  503. pathIs("esb/bond")) {
  504. S.resp[1] = 0x18;
  505. memcpy(S.resp + 2, g_slot[slot].rec, 24);
  506. } else if (pathIs("user/wireless_transport")) {
  507. // Steam reads this (a CONTROLLER setting, relayed rid1) to mark which bond slot is ACTIVE in the
  508. // pairing list, mapping active_slot = value XOR 2 (HANDOFF: slot0->0x02, slot1->0x03, slot2->0x00,
  509. // slot3->0x01). It's a single DONGLE-WIDE value = the currently-connected slot, NOT this
  510. // interface's own index (returning the raw index made Steam mark slot^2 active -> the live puck
  511. // showed "Inactive"). Report the connected slot's code so Steam marks the live puck active.
  512. int act = 0;
  513. unsigned long best = 0, now = millis();
  514. for (int s2 = 0; s2 < NSLOT; s2++)
  515. if (g_slot[s2].used && g_connReplyMs[s2] &&
  516. (now - g_connReplyMs[s2]) < 1200u &&
  517. (best == 0 || g_connReplyMs[s2] > best)) {
  518. best = g_connReplyMs[s2];
  519. act = s2;
  520. }
  521. S.resp[1] = 1;
  522. S.resp[2] = (uint8_t)(act ^ 2);
  523. } else {
  524. S.resp[1] =
  525. 0; // absent/empty -- valid "no value" reply, not a path echo
  526. }
  527. S.resp_len = 63;
  528. break;
  529. }
  530. default:
  531. S.resp[0] = cmd;
  532. S.resp[1] = len;
  533. if (pln)
  534. memcpy(S.resp + 2, pl, pln > 60 ? 60 : pln);
  535. S.resp_len = 63;
  536. break;
  537. }
  538. }
  539. static uint16_t handleGet(int slot, uint8_t rid, hid_report_type_t type,
  540. uint8_t *buf, uint16_t reqlen)
  541. {
  542. (void)rid;
  543. if (type != HID_REPORT_TYPE_FEATURE)
  544. return 0;
  545. // Do NOT treat a feature GET as "Steam is driving." A bare read is weak evidence: on Linux the kernel
  546. // hid-steam driver (and any hidapi enumerator) issues GET_FEATURE probes even with Steam's window closed,
  547. // which pinned steamDrivingGamepad() true forever and blocked the Steam-closed lizard fallback (keyboard/
  548. // mouse dead, and the lizard-off writes those readers pair with the probe also killed the autonomous
  549. // touchpad haptics). Steam actually taking over is detected by its OUTPUT/SET WRITES (the 0x87 lizard-off
  550. // heartbeat ~every 3s, and 0x82 haptics), which stamp g_steamAliveMs on the handleSet paths. So drop the
  551. // GET-based stamp entirely; a read alone no longer suppresses lizard.
  552. Slot &S = g_slot[slot];
  553. uint16_t n = S.resp_len ? S.resp_len : 63;
  554. if (n > reqlen)
  555. n = reqlen;
  556. memcpy(buf, S.resp, n);
  557. // Flight recorder (every GET, un-deduped): a read STORM -- e.g. the "AE x39" identity hammering seen before
  558. // the identity fix -- is itself a wedge signal, so we want it filling the post-mortem trail if it happens.
  559. faultDiagTrace(FR_GET, (uint16_t)((rid << 8) | S.resp[0]));
  560. // Battery diagnostic: in gamepad (Steam) mode battery is read host-side via the feature channel, NOT the
  561. // forwarded 0x43 (that path is verbatim-identical to lizard mode, where battery works). Capture what Steam
  562. // GETs so a WebUSB-panel (or CDC) capture in Steam mode shows the report id it polls for battery (then we
  563. // answer it with g_battery in handleSet). De-duped by report id so the high-rate polling doesn't flood the
  564. // ring/console -- a freshly-requested id is logged once, then again only after 1s.
  565. {
  566. // Dedup by (rid, interface, response-cmd) so each interface's GET is captured (not collapsed to one
  567. // line across all 4 slots) -- the per-interface bond/identity responses are exactly what we need to
  568. // see -- while still not flooding on high-rate same-report polling.
  569. static uint8_t lastRid = 0xFF, lastSlot = 0xFF, lastCmd = 0xFF;
  570. static unsigned long lastMs = 0;
  571. if (rid != lastRid || (uint8_t)slot != lastSlot ||
  572. S.resp[0] != lastCmd || millis() - lastMs > 1000) {
  573. lastRid = rid;
  574. lastSlot = (uint8_t)slot;
  575. lastCmd = S.resp[0];
  576. lastMs = millis();
  577. // ring marker 0xFC = "host feature GET" (panel renders it as "GET rid=.."); payload = what we returned
  578. hapLogAdd(0xFC, rid, S.resp, n);
  579. // serial feature-command capture: what Steam READ on this interface + our answer
  580. fcPush(1, slot, rid, S.resp[0], (uint8_t)n, S.resp + 2,
  581. 10);
  582. #if OPK_LOG
  583. // Diagnostic build only -- no Serial.printf on the 800B usbd-task stack in production (LOCKUP
  584. // mitigation). The GET is captured to the OPK_LOG ring above for the WebUSB panel.
  585. if (Serial.availableForWrite() > 80)
  586. Serial.printf(
  587. "# GET if%d rid=%02X reqlen=%u -> %02X %02X %02X (batt=%u%%)\n",
  588. slot, rid, reqlen, S.resp[0], S.resp[1],
  589. S.resp[2],
  590. (slot >= 0 && slot < NSLOT) ?
  591. g_battery[slot] :
  592. 0);
  593. #endif
  594. }
  595. }
  596. return n;
  597. }
  598. // one callback pair per interface (the Adafruit core routes by interface to the matching object)
  599. #define SLOTCB(N) \
  600. static void setcb##N(uint8_t r, hid_report_type_t t, uint8_t const *b, \
  601. uint16_t n) \
  602. { \
  603. handleSet(N, r, t, b, n); \
  604. } \
  605. static uint16_t getcb##N(uint8_t r, hid_report_type_t t, uint8_t *bf, \
  606. uint16_t rl) \
  607. { \
  608. return handleGet(N, r, t, bf, rl); \
  609. }
  610. // clang-format off
  611. SLOTCB(0)
  612. SLOTCB(1)
  613. SLOTCB(2)
  614. SLOTCB(3)
  615. // clang-format on
  616. typedef uint16_t (*getcb_t)(uint8_t, hid_report_type_t, uint8_t *, uint16_t);
  617. typedef void (*setcb_t)(uint8_t, hid_report_type_t, uint8_t const *, uint16_t);
  618. static getcb_t GETCB[NSLOT] = { getcb0, getcb1, getcb2, getcb3 };
  619. static setcb_t SETCB[NSLOT] = { setcb0, setcb1, setcb2, setcb3 };
  620. // ===================== IController =====================
  621. void SteamPuckController::begin()
  622. {
  623. USBDevice.setID(0x28DE, 0x1304);
  624. // Distinct bcdDevice so Windows keys a FRESH usbflags entry (cache is VID:PID:bcdDevice) and actually runs
  625. // MS OS 2.0 / WinUSB binding for the WebUSB vendor interface, instead of reusing a stale "no WinUSB" entry
  626. // tied to the real Steam Controller (28DE:1304, no WebUSB interface). The normal (wake-mouse) and one-shot
  627. // debug (CDC) boots present DIFFERENT interface sets, so they need DIFFERENT bcdDevice values or Windows
  628. // serves one's cached descriptor for the other across a reboot.
  629. USBDevice.setDeviceVersion(
  630. g_debugCdcThisBoot ?
  631. 0x0212 :
  632. (g_usbMode == MODE_LIZARD ? 0x0213 : 0x0211));
  633. USBDevice.setManufacturerDescriptor("Valve Software");
  634. USBDevice.setProductDescriptor("Steam Controller Puck");
  635. const uint8_t *desc = (g_usbMode == MODE_LIZARD) ?
  636. PUCK_LIZARD_HID_DESC :
  637. PUCK_HID_DESC;
  638. const uint16_t descLen = (g_usbMode == MODE_LIZARD) ?
  639. sizeof PUCK_LIZARD_HID_DESC :
  640. sizeof PUCK_HID_DESC;
  641. for (int i = 0; i < NSLOT; i++) {
  642. hid[i].setReportDescriptor(desc, descLen);
  643. hid[i].setReportCallback(GETCB[i], SETCB[i]);
  644. // 1ms USB poll (was default 10ms = 100/s cap -> choppy)
  645. hid[i].setPollInterval(1);
  646. hid[i].begin();
  647. }
  648. }
  649. // Forward the controller's report 0x45 to Steam, or drive lizard kb/mouse when Steam is closed. PURELY a
  650. // USB-side decision -- changes nothing about the RF poll or the host->controller relay. Per-slot: each
  651. // controller's 0x45 goes to its OWN hid[slot], so Steam sees four independent inputs. Lizard, by contrast,
  652. // presents ONE mouse + keyboard (a desktop can only consume one): rfLizard merges every bonded controller's
  653. // input (g_in[] across all used slots, populated by the per-slot decode) onto hid[0], so all connected
  654. // controllers drive the same cursor/keys together -- and it works regardless of which bond slot is live.
  655. void SteamPuckController::onReport45(int slot, const uint8_t *rep, bool fresh,
  656. uint8_t bodyTlen)
  657. {
  658. (void)fresh;
  659. (void)bodyTlen;
  660. // Host asleep -> forward NOTHING. While suspended, every sendReport attempt can translate into a host wake,
  661. // making the PC wake on any controller movement. Waking is an explicit gesture only (Steam-button short
  662. // press / controller connect), handled in rf_link.cpp via the device-level USB resume signal.
  663. if (USBDevice.suspended())
  664. return;
  665. // Just woke? Hold off forwarding so the wake gesture's residual controller input doesn't click/type into
  666. // the freshly-woken desktop.
  667. if (g_resumeMs && millis() - g_resumeMs < POST_RESUME_MUTE_MS)
  668. return;
  669. if (slot < 0 || slot >= NSLOT)
  670. return;
  671. if (!g_slot[slot].used)
  672. return;
  673. // Report id: 0x45 = legacy main input; 0x42 = new-firmware (SC2 beta ~2026-07) main input (53B). Forward
  674. // whichever the controller actually sent, verbatim, under its own id -- both are declared in PUCK_HID_DESC
  675. // and this is exactly what the real puck does. rep[0] is the id byte (rep points at it in the F1 TLV).
  676. const uint8_t rid = rep[0];
  677. if (lizardActive()) {
  678. // All bonded controllers share ONE desktop mouse/keyboard (mounted on hid[0] regardless of
  679. // which RF slots are in use). rfLizard merges g_in[] across every used slot internally, so we
  680. // fire it ONCE per cycle -- gated on the lowest CONNECTED slot's report so it runs at a steady
  681. // cadence (not once per slot, which would multiply the output rate). g_in[] is populated by the
  682. // per-slot decode for BOTH report 0x45 and the beta 0x42 (byte-identical front section), so
  683. // lizard works on new-firmware controllers too without reading rep[] here.
  684. // Gate on the lowest RECENTLY-REPLYING slot, not merely the lowest bonded one: a bonded-but-
  685. // offline low slot (e.g. a stale/phantom bond from a cloned backup) must not starve lizard when
  686. // a higher slot is the live controller (main's #98 fix -- do not regress it). onReport45 only
  687. // runs for a slot that just decoded a report, so the reporting slot is itself connected.
  688. unsigned long now = millis();
  689. int lizSlot = -1;
  690. for (int s = 0; s < NSLOT; s++)
  691. if (g_slot[s].used && g_connReplyMs[s] &&
  692. (now - g_connReplyMs[s]) < 1200u) {
  693. lizSlot = s;
  694. break;
  695. }
  696. if (slot == lizSlot)
  697. rfLizard(&hid[0], &hid[0], 0x40, 0x41);
  698. } else {
  699. // body length after the id byte, clamped to the descriptor's declared size for this report id
  700. // (0x42 = 53B vendor input, 0x45 = 45B input).
  701. uint8_t maxb = (rid == 0x42) ? 53 : 45;
  702. uint8_t blen = bodyTlen - 1;
  703. if (blen > maxb)
  704. blen = maxb;
  705. // forward the puck's raw pad coords untouched (Steam does its own interpolation/smoothing). Forward
  706. // only FRESH reports: the real puck dedupes, so stale repeats make Steam's velocity/smoothing
  707. // stair-step. g_fwdNewOnly toggles for A/B.
  708. //
  709. // Do NOT gate on hid[slot].ready() here: usbTxHid enqueues into a ring buffer (drop-oldest)
  710. // that exists precisely to hold a report while the endpoint is briefly busy -- usbTxDrain
  711. // sends it the instant the host next polls. Gating on ready() at enqueue time DROPPED every
  712. // fresh report that landed while the endpoint was busy (~1 ms after each send), which at
  713. // 300+ captured reports/s silently discarded ~a third of them (measured: RF new/s ~313 but
  714. // host delivered ~180). Always enqueue; the ring paces delivery to the host without loss.
  715. bool send = (fresh || !g_fwdNewOnly);
  716. // Content dedup: the counter byte (rep[1]) free-runs, so drop a report whose body AFTER the
  717. // counter is byte-identical to the last one forwarded on this slot -- a true repeat (same
  718. // physical input, bumped counter), not a new sample. Caps delivery at the controller's real
  719. // distinct-report rate instead of the (higher) poll rate. See g_fwdContentDedup above.
  720. if (send && g_fwdContentDedup && blen >= 2) {
  721. static uint8_t lastBody[NSLOT][53];
  722. static uint8_t lastBodyLen[NSLOT] = { 0 };
  723. uint8_t clen =
  724. (uint8_t)(blen - 1); // bytes after the counter
  725. if (clen > sizeof lastBody[0])
  726. clen = sizeof lastBody[0];
  727. if (lastBodyLen[slot] == clen &&
  728. memcmp(lastBody[slot], rep + 2, clen) == 0)
  729. send = false; // identical input, only the counter moved
  730. else {
  731. lastBodyLen[slot] = clen;
  732. memcpy(lastBody[slot], rep + 2, clen);
  733. }
  734. }
  735. if (send)
  736. usbTxHid(
  737. &hid[slot], rid, rep + 1,
  738. blen); // Steam/SDL Triton: input report 0x45 (old) / 0x42 (new fw)
  739. }
  740. }
  741. // Forward the controller's NON-input status reports (0x43 power/battery, 0x44) to Steam verbatim -- the real
  742. // puck does this and it's how Steam reads battery. Same host-asleep / post-resume gating as 0x45; no lizard
  743. // path (status reports aren't input, so they forward regardless of the lizard decision). Per-slot: each
  744. // controller's status goes to its own hid[slot].
  745. void SteamPuckController::onAuxReport(int slot, uint8_t rid,
  746. const uint8_t *data, uint8_t n)
  747. {
  748. if (USBDevice.suspended())
  749. return;
  750. if (g_resumeMs && millis() - g_resumeMs < POST_RESUME_MUTE_MS)
  751. return;
  752. if (slot < 0 || slot >= NSLOT)
  753. return;
  754. // Forward the controller's status report VERBATIM (the real puck does this; it's how the host reads
  755. // battery). Padding the report to the descriptor-declared length broke battery in both lizard and
  756. // Steam, so it's reverted -- send exactly what the controller sent.
  757. if (g_slot[slot].used && hid[slot].ready()) {
  758. // capture the pushed status report (0x43 battery / 0x44) device->host for the WebUSB panel: this is
  759. // the channel Steam actually reads battery from; marker 0xFB = "->host push".
  760. hapLogAdd(0xFB, rid, data, n);
  761. usbTxHid(&hid[slot], rid, data, n);
  762. }
  763. }
  764. // wake nudge: a bare USB resume signal is NOT enough to wake some hosts (Windows in particular) -- they only
  765. // wake when actual mouse/keyboard input follows. So on a deliberate wake gesture we play a HARMLESS mouse
  766. // JIGGLE (move a few px right, then back -- NET ZERO cursor, NO button): real mouse activity wakes the host
  767. // but clicks/activates nothing (an open Start menu stays open). Queued by wakeEvent() (rf_link, on a Steam
  768. // short press / controller connect while suspended); delivered once the suspended bus has resumed. Per-slot
  769. // so every connected interface gets the jiggle (Windows can credit any of them with the wake).
  770. static uint8_t g_nudgeStep[NSLOT] = { 0 }; // 0=idle; 1=jiggle+, 2=jiggle-
  771. static unsigned long g_nudgeMs[NSLOT] = { 0 };
  772. #define NUDGE_JIGGLE_PX 10
  773. void SteamPuckController::wakeEvent()
  774. {
  775. // arm the jiggle on every connected slot -- any one of them is enough to wake Windows
  776. for (int s = 0; s < NSLOT; s++) {
  777. if (g_slot[s].used) {
  778. g_nudgeStep[s] = 1;
  779. g_nudgeMs[s] = millis();
  780. }
  781. }
  782. }
  783. static void wakeNudgeTask()
  784. {
  785. if (USBDevice.suspended())
  786. return; // wait for resume; reports can't cross a suspended bus
  787. // Expire stale arms (bus never resumed) and see if any slot still wants a wake nudge.
  788. bool armed = false;
  789. for (int s = 0; s < NSLOT; s++) {
  790. if (!g_nudgeStep[s])
  791. continue;
  792. if (millis() - g_nudgeMs[s] > 5000) {
  793. g_nudgeStep[s] = 0;
  794. continue;
  795. }
  796. armed = true;
  797. }
  798. if (!armed)
  799. return;
  800. // Ride the BOOT MOUSE -- the interface Windows armed as the wake source; a gamepad-slot report does not
  801. // wake Modern Standby. A single jiggle on it wakes the host regardless of how many slots are connected.
  802. if (wakeHidPresent()) {
  803. if (!wakeHidReady())
  804. return;
  805. static unsigned long stepMs = 0;
  806. static uint8_t step = 1;
  807. if (millis() - stepMs < 15)
  808. return; // pace the edges
  809. stepMs = millis();
  810. wakeHidMove((step == 1) ? NUDGE_JIGGLE_PX : -NUDGE_JIGGLE_PX,
  811. 0);
  812. if (step >=
  813. 2) { // jiggle (right, then back) delivered -> disarm every slot
  814. step = 1;
  815. for (int s = 0; s < NSLOT; s++)
  816. g_nudgeStep[s] = 0;
  817. } else
  818. step++;
  819. return;
  820. }
  821. // Fallback (debug-CDC boot: no wake mouse): per-slot jiggle on the gamepad slot HIDs.
  822. static unsigned long stepMs[NSLOT] = { 0 };
  823. for (int s = 0; s < NSLOT; s++) {
  824. if (!g_nudgeStep[s])
  825. continue;
  826. if (!hid[s].ready())
  827. continue;
  828. if (millis() - stepMs[s] < 15)
  829. continue; // pace the edges
  830. stepMs[s] = millis();
  831. hid_mouse_report_t m;
  832. m.buttons = 0;
  833. m.x = (g_nudgeStep[s] == 1) ? NUDGE_JIGGLE_PX :
  834. -NUDGE_JIGGLE_PX;
  835. m.y = 0;
  836. m.wheel = 0;
  837. m.pan = 0;
  838. usbTxHid(&hid[s], 0x40, &m,
  839. sizeof m); // jiggle right, then back
  840. g_nudgeStep[s] = (g_nudgeStep[s] >= 2) ?
  841. 0 :
  842. (uint8_t)(g_nudgeStep[s] + 1);
  843. }
  844. }
  845. // USB connection presentation (like the real dongle): report 0x79 = connection state (01=disc, 02=conn),
  846. // edge-triggered, + periodic 0x7B status. Live-captured: this is what Steam reads to mark the controller
  847. // connected. Without it Steam shows disconnected even though 0x45 input is streaming.
  848. void SteamPuckController::task()
  849. {
  850. wakeNudgeTask();
  851. {
  852. static bool wasSusp = false;
  853. // stamp the suspended->active edge for the post-resume mute
  854. bool susp = USBDevice.suspended();
  855. if (wasSusp && !susp)
  856. g_resumeMs = millis();
  857. wasSusp = susp;
  858. }
  859. // no periodic 0x79/0x7B while the host sleeps -- those sends can wake it too
  860. if (USBDevice.suspended())
  861. return;
  862. // Lizard<->Steam handoff: release whatever the OUTGOING path was holding. lizardActive() is a pure
  863. // runtime decision -- Steam opening/closing (its ~3s settings heartbeat starting/stopping) flips it with
  864. // NO USB re-enumeration -- so a key/mouse-button held when Steam TAKES OVER, or a gamepad button held
  865. // when Steam CLOSES, is otherwise never released and sticks on the host until a reconnect or power-cycle
  866. // (the reported "stuck input after switching modes"). The link-drop neutral in rf_link only covers an RF
  867. // outage, not this handoff. Fire a neutral through the path we're leaving on each edge. Placed after the
  868. // suspend early-return: while suspended nothing can be sent, and a flip across a sleep is covered on
  869. // resume (this edge fires once, plus the post-resume input mute). MODE_LIZARD never leaves lizard, so
  870. // this is inert there.
  871. {
  872. static bool wasLizard = lizardActive();
  873. bool nowLizard = lizardActive();
  874. if (nowLizard != wasLizard) {
  875. if (wasLizard) {
  876. // leaving lizard -> release held desktop keyboard/mouse/consumer
  877. rfLizardRelease(&hid[0], &hid[0], 0x40, 0x41);
  878. } else {
  879. // leaving gamepad-forward -> release held 0x45 buttons/sticks/triggers on every slot
  880. static const uint8_t neutral45[45] = { 0 };
  881. for (int s = 0; s < NSLOT; s++)
  882. if (g_slot[s].used && hid[s].ready())
  883. usbTxHid(&hid[s], 0x45,
  884. neutral45,
  885. sizeof neutral45);
  886. }
  887. wasLizard = nowLizard;
  888. }
  889. }
  890. // Per-slot 0x79/0x7B: each connected slot reports its OWN edge and its OWN status. State arrays are
  891. // per-slot so each controller's "connected" edge fires once and is re-sent only until Steam acks THAT
  892. // slot. The real puck's per-slot edge-triggered 0x79 prevents re-triggering Steam's connect-chime loop.
  893. static bool usbConn[NSLOT] = { 0 };
  894. static unsigned long last79[NSLOT] = { 0 }, last7B[NSLOT] = { 0 },
  895. connEdgeMs[NSLOT] = { 0 }, discEdgeMs[NSLOT] = { 0 },
  896. last43[NSLOT] = { 0 };
  897. for (int s = 0; s < NSLOT; s++) {
  898. if (!g_slot[s].used || !hid[s].ready())
  899. continue;
  900. bool conn = (millis() - g_connReplyMs[s] < 300);
  901. // 0x79 connection state: on edge, then repeated every 750ms ONLY until Steam reacts (its first OUTPUT/
  902. // settings write after the edge -- g_steamAliveMs). The real puck sends 0x79 ONCE, edge-triggered; an
  903. // unconditional forever-resend re-triggers Steam's connect handling (connect chime) every 750ms before
  904. // Steam consumes 0x45 -> a loop of connect-time haptic buzzes. Resending until acked still covers
  905. // "Steam missed the edge".
  906. bool steamAcked = g_steamAliveMs &&
  907. (int32_t)(g_steamAliveMs - connEdgeMs[s]) >=
  908. 0;
  909. // The DISCONNECT edge (0x79=01) also needs resending: it used to be sent exactly ONCE, so a single
  910. // dropped report left Steam believing the controller was still connected indefinitely -- observed as
  911. // "WebUSB panel shows the slot DOWN (g_connReplyMs stale) while Steam still lists it connected, and the
  912. // controller light is solid (it re-adopted the beacon) but no input flows." Resend disc every 750ms but
  913. // BOUNDED to DISC_RESEND_MS so a lost packet converges without the forever-spam the "real puck sends
  914. // 0x79 once" note warns against.
  915. bool discResend =
  916. !conn && (millis() - discEdgeMs[s] < DISC_RESEND_MS);
  917. if (conn != usbConn[s] ||
  918. (conn && !steamAcked && millis() - last79[s] >= 750) ||
  919. (discResend && millis() - last79[s] >= 750)) {
  920. if (conn && !usbConn[s])
  921. connEdgeMs[s] = millis();
  922. if (!conn && usbConn[s]) // connect->disc edge: anchor the resend window
  923. discEdgeMs[s] = millis();
  924. uint8_t st = conn ? 0x02 : 0x01;
  925. hapLogAdd(0xFB, 0x79, &st, 1); // ->host push (capture)
  926. usbTxHid(&hid[s], 0x79, &st, 1);
  927. usbConn[s] = conn;
  928. last79[s] = millis();
  929. } else if (conn && millis() - last7B[s] >= 2000) {
  930. // 0x7B status, live-captured template. Byte 8 is the controller->puck signal strength as signed
  931. // dBm (capture showed 0xDD = -35) -- patch in the smoothed RSSI the radio samples on each
  932. // controller reply (rf_link). 0 = no sample yet -> keep the capture value rather than garbage.
  933. //
  934. // CALIBRATION: our raw RSSISAMPLE reads ~RSSI_DBM_OFFSET dB lower than the real Valve puck at the
  935. // same distance (Pro Micro PCB-trace antenna vs Valve's tuned front-end). The 2Mbit ESB link has
  936. // ~55dB margin, so a -75dBm reading still works across a house, but Steam's bar maps raw dBm to
  937. // "weak" long before that. The offset lines our close-range value up with the puck's captured -35
  938. // so the bar tracks usable range, not antenna gain. Clamp keeps it in a sane window.
  939. uint8_t s7b[12] = { 0xF7, 0x01, 0x89, 0x00, 0x00, 0x00,
  940. 0x03, 0x00, 0xDD, 0x00, 0x3A, 0x02 };
  941. if (g_linkRssi[s]) {
  942. int mag = (int)g_linkRssi[s] - RSSI_DBM_OFFSET;
  943. if (mag < 25)
  944. mag = 25;
  945. else if (mag > 95)
  946. mag = 95;
  947. s7b[8] = (uint8_t)(0u - (uint8_t)mag);
  948. }
  949. hapLogAdd(0xFB, 0x7B, s7b, 12); // ->host push (capture)
  950. usbTxHid(&hid[s], 0x7B, s7b, 12);
  951. last7B[s] = millis();
  952. }
  953. // Synthesized 0x43 = ID_TRITON_BATTERY_STATUS for SDL/Steam's gamepad driver. The verbatim forward of
  954. // the controller's own 0x43 (onAuxReport) is what the LIZARD/kernel path reads, but SDL's Triton driver
  955. // requires the FULL TritonBatteryStatus_t length (r >= 1 + 14) and lapses to the "wired" glyph without a
  956. // fresh one -- so we push a clean 14-byte report from g_battery every 2s. Body: [ucChargeState][ucBattery
  957. // Level][voltages/current/temp = 0]; SDL only reads the first two. Map unknown/reset state -> discharging
  958. // so it shows ON_BATTERY + % rather than UNKNOWN. Skipped until the controller has reported a level.
  959. if (conn && g_battery[s] && millis() - last43[s] >= 2000) {
  960. uint8_t st = g_batteryState[s];
  961. // EChargeState discharging -> SDL_POWERSTATE_ON_BATTERY
  962. if (st != 1 && st != 2 && st != 4)
  963. st = 1;
  964. uint8_t b43[14] = { 0 };
  965. b43[0] = st; // ucChargeState
  966. b43[1] = g_battery[s]; // ucBatteryLevel (percent)
  967. hapLogAdd(0xFB, 0x43, b43, 14); // ->host push (capture)
  968. usbTxHid(&hid[s], 0x43, b43, sizeof b43);
  969. last43[s] = millis();
  970. }
  971. }
  972. // Reset edge state for slots that are no longer used/ready (so a re-bond sees a fresh edge).
  973. for (int s = 0; s < NSLOT; s++)
  974. if (!g_slot[s].used || !hid[s].ready())
  975. usbConn[s] = false;
  976. }