puck_hid.cpp 48 KB

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