puck_hid.cpp 44 KB

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