rf_link.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168
  1. #include "rf_link.h"
  2. #include "radio.h"
  3. #include "bonds.h"
  4. #include "config.h"
  5. #include "triton.h"
  6. #include "haptics.h"
  7. #include "puck_hid.h" // g_cmdCapture (suppress I45 during feature-command capture)
  8. #include "controllers.h"
  9. #include "status_led.h"
  10. #include "fault_diag.h"
  11. #include "usb_mount.h" // modeSwitchReboot()
  12. #include <Adafruit_TinyUSB.h>
  13. #include <Arduino.h>
  14. #include <string.h>
  15. bool g_rfHost = true;
  16. bool g_connOn = true;
  17. uint8_t g_connType = 0xE7; // start with protocol-version handshake, then 0xE3
  18. // 0=current(slow/awake), 1=protocol-version-1. 'V<n>' to toggle.
  19. uint8_t g_e7b = 0;
  20. uint8_t g_connLen = 0x08;
  21. // GET report 0x45 param byte. 'q' cmd.
  22. uint8_t g_getParam = 0x00;
  23. // cycling the ESB PID drains the controller's report queue (~400 new/s vs ~60 with a fixed PID). 'e<n>' selects.
  24. uint8_t g_e3mode = 1;
  25. // ---- real-puck alignment (sniff1.json: a bonded controller RECONNECTING) ----
  26. // The live air capture of a real puck<->controller reconnect shows the controller streams 0xF1 input in
  27. // response to a BARE 0xE3 poll (1-byte payload, just the opcode) with NO 0xE7 awake-announce and NO
  28. // GET-report-0x45 sub-TLV -- 1857 of the puck's 2003 polls were bare E3, and the very first session frame
  29. // (a bare E3) was answered by F1 immediately. That contradicts the earlier RE "recipe" (rf_link.h) which
  30. // assumed E7 + GET-0x45 were required. So these now default to the real-puck behavior; flip them at runtime
  31. // ('d'/'n' console cmds) to fall back to the legacy GET/E7 path for an A/B comparison on hardware.
  32. bool g_pollGet =
  33. false; // false = bare E3 poll (real puck); true = append GET-report-0x45 TLV (legacy)
  34. bool g_e7announce =
  35. false; // false = no E7 awake-announce (real puck); true = announce host-awake (legacy)
  36. // Session-channel E1 host-frame keepalive. The real puck sends NO E1 on its session channel (the bonded
  37. // controller already knows the per-bond address and just resumes). OpenPuck still needs E1 because it runs
  38. // the SHARED "ibex" address, not the (un-reversed) per-bond address -- E1 is how the controller learns this
  39. // puck's session base/prefix/channel. So this defaults ON; turn it off ('m') to test the real-puck "no
  40. // session E1" model once per-bond addressing exists. Discovery on ch2 is separate and always runs.
  41. bool g_e1keepalive = true;
  42. bool g_connVerbose = false;
  43. // poll RX-window (us): the poll BUSY-WAITS up to this long for the controller's reply. The reply returns
  44. // EARLY (EVENTS_END) on a successful poll, so this window is only paid IN FULL on a genuine no-reply --
  45. // one slot needs (g_rxWin + overhead) < g_pollUs(4000) so a no-reply poll still fits inside the 250 Hz
  46. // cycle. 1200 is the proven value; it was briefly raised to 2000 (issue-72, delayed-reply tolerance) which
  47. // dropped the rate. FIXED + not configurable (like g_pollUs): there is no good reason to raise it in the
  48. // field, and doing so silently starves the poll cycle. Any persisted/old value is ignored.
  49. const uint32_t g_rxWin = 1200;
  50. unsigned long g_connCooldown = 0;
  51. uint8_t g_connSt = 0; // 0=announce awake, 1=poll loop
  52. uint8_t g_connStep = 0; // repeat counter within a state
  53. uint16_t g_connPoll = 0; // poll counter (re-assert awake every 32nd)
  54. uint32_t g_connF1 = 0;
  55. uint8_t g_connF3v = 0xFF;
  56. uint8_t g_qos = 0;
  57. // clean, spread channels (from the puck's RSSI/PER scan)
  58. static const uint8_t g_hopCand[] = { 18, 46, 76, 22, 68 };
  59. uint8_t g_hopIdx = 0;
  60. volatile uint16_t g_qosBad = 0;
  61. unsigned long g_qosCheckMs = 0, g_qosLastHopMs = 0;
  62. uint16_t g_f1ps = 0;
  63. uint16_t g_newps = 0;
  64. // polls/s (GET+relay TXs) last second -- distinguishes loop-starvation from reply-loss
  65. uint16_t g_pollsps = 0;
  66. // last second's CRC-fail and no-reply-in-window counts (wedge diagnosis)
  67. uint16_t g_crcps = 0, g_norxps = 0;
  68. uint16_t g_rfStallRecover = 0;
  69. // RF-stall self-heal thresholds. A genuine worst-case reply gap during normal play is ~1.5s (the
  70. // hapticOnReconnect re-init window); past RF_STALL_MS with us still actively polling, the whole link is wedged,
  71. // not merely blipping. RF_RECOVER_MS rate-limits the recovery so it can't thrash while a stalled link re-syncs.
  72. #define RF_STALL_MS 2500u
  73. #define RF_RECOVER_MS 2000u
  74. // A genuinely WEDGED radio recovers within a power-cycle or two; a controller that is simply OFF / out of
  75. // range never comes back no matter how many times we power-cycle. So after RF_STALL_GIVEUP consecutive
  76. // recoveries that restored NO link, treat it as "controller absent" and stop hammering: back the power-cycle
  77. // off to RF_STALL_BACKOFF_MS (a slow safety-net kick). Discovery beacons keep running throughout, so a
  78. // returning controller still reconnects normally without the power-cycle -- and the aggressive 2s cadence was
  79. // both wasteful and able to disrupt a controller mid-reconnect. The counter resets the moment any slot replies.
  80. #define RF_STALL_GIVEUP 3u
  81. #define RF_STALL_BACKOFF_MS 30000u
  82. // measured avg us between GET-poll fires (vs intended g_pollUs)
  83. uint16_t g_pollPeriodUs = 0;
  84. static uint32_t g_pollDtSum = 0;
  85. static uint16_t g_pollDtCnt = 0;
  86. // smoothed |dBm| of the controller's replies, per slot (0 = none yet)
  87. volatile uint8_t g_linkRssi[NSLOT] = { 0 };
  88. // battery % from the controller's report 0x43 (body[1]); 0 = none yet. Per-slot -- the active controller's
  89. // battery is the most recently seen one (other slots' values stay in their own array slots).
  90. volatile uint8_t g_battery[NSLOT] = { 0 };
  91. // charge state from report 0x43 body[0] (EChargeState: 1=discharging 2=charging 4=charging-done; 0=unknown).
  92. volatile uint8_t g_batteryState[NSLOT] = { 0 };
  93. // Slot the poll loop is currently driving. Set by rfConnStep before each E7/relay/E3, consumed by the
  94. // decode (g_in[g_curSlot]), the haptic flush (per-slot session address), and the per-second stat dump.
  95. int g_curSlot = -1;
  96. // ---- internal counters / timers ----
  97. // ESB PID is 2 bits. The controller dequeues a FRESH report only when the poll's PID differs from the
  98. // last one it saw on that pipe; a repeated PID reads as a retransmit and returns the SAME (stale) report.
  99. // PER SLOT, because a single shared counter advances by (2 * nWarm) per cycle -- with 2 controllers that's
  100. // +4 per cycle = 0 mod 4, so each slot's GET PID is constant => the controller never dequeues => ~60 new/s
  101. // instead of ~400. Each slot's counter increments once per poll-of-that-slot so it cycles 0,1,2,3 cleanly.
  102. static uint8_t g_pollPid[NSLOT] = {};
  103. // Relay PID is offset by 2 from poll PID so the two never share the same
  104. // 2-bit PID value in the same cycle. Both counters advance once per cycle;
  105. // starting 2 apart keeps them 2 apart (mod 4) forever, preventing the
  106. // controller from deduplicating the E3 GET as a retransmit of the relay.
  107. static uint8_t g_relayPid[NSLOT] = { 2, 2, 2, 2 };
  108. // All link statistics are PER SLOT: each controller's polls/replies/errors are counted (and reported --
  109. // serial stat line, WebUSB blob v13) against that controller only. The old scalar counters merged every
  110. // slot into one number, so the panel couldn't tell "controller B is drowning" from "everything is slow".
  111. // The legacy aggregate snapshots (g_pollsps & co) are now sums over slots, kept for the serial line and the
  112. // blob's pre-v13 fields.
  113. static uint32_t g_stPoll[NSLOT] = {}, g_stF1[NSLOT] = {};
  114. static uint32_t g_stF3 = 0;
  115. // g_stPoll counts true poll CYCLES (one E3 GET per warm slot per cycle). g_stRelay counts relay frames TX'd
  116. // (host/haptic output reports). They were conflated before (every rfConnTx bumped one counter), which made
  117. // "Polls/s" read ~540 (250 polls + ~290 relays) and hid that each relay steals a reply window from its poll.
  118. static uint32_t g_stRelay[NSLOT] = {};
  119. uint16_t g_relayps = 0;
  120. // per-slot per-second snapshots (WebUSB blob v13 / per-controller panel stats)
  121. uint16_t g_slotPollsps[NSLOT] = {}, g_slotF1ps[NSLOT] = {},
  122. g_slotNewps[NSLOT] = {};
  123. uint8_t g_slotCrcps[NSLOT] = {}, g_slotNoRxps[NSLOT] = {},
  124. g_slotRelayps[NSLOT] = {};
  125. static unsigned long g_stMs = 0;
  126. // Per-slot dedupe seq + per-slot new-report counter (the real puck sends 0x45 per controller; merging all
  127. // slots into a single sequence makes one controller "swallow" the other's frame).
  128. static uint8_t g_lastSeq[NSLOT] = { 0 };
  129. static uint32_t g_stNew[NSLOT] = {};
  130. static uint32_t g_stCrc[NSLOT] = {}, g_stNoRx[NSLOT] = {};
  131. static uint32_t g_chF1[3] = { 0, 0, 0 };
  132. // Cycle gate: fires once per g_pollUs; each fire polls every warm slot so all run at ~250 Hz (oversampling
  133. // the controller's ~270 Hz report generation so no fresh trackpad sample is dropped -- see config.h).
  134. static uint32_t g_lastPollUs = 0;
  135. static uint32_t g_connRx = 0;
  136. static unsigned long g_lastSessBeacon = 0, g_lastDisc = 0;
  137. static unsigned long g_lastStream = 0;
  138. // HOST FRAME the bonded controller waits for (IBEX FUN_00019000 verify: b[0]=0x12, b[5]=0xE1, b[6..10]=
  139. // proteus_uuid, b[10..14]=ibex_uuid). Built like PROTEUS FUN_00027e9a. Sent on the shared rendezvous addr;
  140. // the controller filters by the uuids in the payload, then connects.
  141. // Transmit one host frame. `discovery`=true sends it on the SHARED rendezvous address ("ibex"/ch2) where a
  142. // searching controller looks; =false sends it on this slot's unique SESSION address (the keepalive once the
  143. // controller has adopted the session). EITHER way the payload advertises the session base/prefix/channel,
  144. // so the controller always learns the unique address to connect on.
  145. // Any-slot link helper: true if ANY bonded slot is currently hearing F-type replies (within 300 ms).
  146. // Used for the "we're connected to at least one controller" decisions (beacon pacing, wake detect).
  147. bool anySlotLinkUp()
  148. {
  149. for (int s = 0; s < NSLOT; s++)
  150. if (g_slot[s].used && millis() - g_connReplyMs[s] < 300)
  151. return true;
  152. return false;
  153. }
  154. static void rfHostFrameOnce(int slot, bool discovery)
  155. {
  156. if (slot < 0 || slot >= NSLOT || !g_slot[slot].used)
  157. return;
  158. // [proteus_uuid 4][ibex_uuid 4][serial 16]
  159. uint8_t *rec = g_slot[slot].rec;
  160. // CRC-VALIDATED frame (decoded from real puck): ESB-DPL RAM = [LENGTH][S1=PID][payload(18)]. payload:
  161. // [0]=0xE1, [1..5]=proteus_uuid LE, [5..9]=ibex_uuid LE, [9]=session channel, [10..13]=0, [13..17]=session
  162. // base, [17]=session prefix. Radio auto-appends CRC16 0x11021.
  163. memset(rftx, 0, sizeof rftx);
  164. // LENGTH = 18 (controller's buf[0]==0x12 check validates this)
  165. rftx[0] = 0x12;
  166. // S1 = PID<<1 | noack0 (matches real puck 00/02/04/06)
  167. rftx[1] = (uint8_t)((g_pid++ & 3) << 1);
  168. rftx[2] = 0xE1; // payload[0] marker
  169. // payload[1..5] proteus_uuid (LE, as bonded)
  170. memcpy(rftx + 3, rec + 0, 4);
  171. memcpy(rftx + 7, rec + 4, 4); // payload[5..9] ibex_uuid
  172. // payload[9] session channel: controller runs the session on this clean
  173. // channel (adopts buf[0xe]); discovery beacon still TXes on ch2
  174. rftx[11] = g_sessCh;
  175. // payload[13..17] session base (the per-bond UNIQUE address; each controller adopts its own)
  176. memcpy(rftx + 15, g_sessBase[slot], 4);
  177. rftx[19] = g_sessPrefix[slot]; // payload[17] session prefix
  178. // TX address: discovery uses the shared "ibex" rendezvous; the session keepalive uses this slot's
  179. // unique address (where THIS controller now listens). The advertised session params (above) are
  180. // identical either way -- so the discovery frame can also double as a re-advertisement if needed.
  181. const uint8_t *txBase = discovery ? g_rfBase : g_sessBase[slot];
  182. uint8_t txPfx = discovery ? g_rfPrefix : g_sessPrefix[slot];
  183. rfConfig(g_rfCh);
  184. rfSetAddr(txBase, txPfx);
  185. NRF_RADIO->PACKETPTR = (uint32_t)rftx;
  186. NRF_RADIO->SHORTS = RADIO_SHORTS_READY_START_Msk |
  187. RADIO_SHORTS_END_DISABLE_Msk;
  188. NRF_RADIO->EVENTS_DISABLED = 0;
  189. NRF_RADIO->TASKS_TXEN = 1;
  190. RWAIT_DISABLED();
  191. NRF_RADIO->EVENTS_DISABLED = 0;
  192. // Session keepalive: the controller answers E3 polls, not beacons.
  193. // No reply arrives here; radio is already disabled from the TX
  194. // END_DISABLE short, so skip the RX window entirely.
  195. if (!discovery)
  196. return;
  197. // Discovery/pairing beacons listen for the controller's response.
  198. NRF_RADIO->PACKETPTR = (uint32_t)rfrx;
  199. rfrx[0] = 0;
  200. NRF_RADIO->SHORTS = RADIO_SHORTS_READY_START_Msk;
  201. NRF_RADIO->EVENTS_END = 0;
  202. NRF_RADIO->TASKS_RXEN = 1;
  203. uint32_t t0 = micros();
  204. while (!NRF_RADIO->EVENTS_END && (micros() - t0) < 800u) {
  205. }
  206. if (NRF_RADIO->EVENTS_END) {
  207. // any reception = controller answered our frame
  208. NRF_RADIO->EVENTS_END = 0;
  209. g_rfRxCount++;
  210. bool crcok = NRF_RADIO->CRCSTATUS & 1;
  211. uint8_t len = rfrx[0];
  212. // non-blocking: don't stall the loop on CDC backpressure (whole line ~165B; CDC write() has no timeout)
  213. if (Serial.availableForWrite() > 180) {
  214. Serial.printf(
  215. "*** RESP#%lu ch%u crc%d rxmatch%lu len%u: ",
  216. (unsigned long)g_rfRxCount, g_rfCh, crcok,
  217. (unsigned long)NRF_RADIO->RXMATCH, len);
  218. for (uint8_t i = 0; i < (len < 40 ? len + 2 : 40); i++)
  219. Serial.printf("%02X ", rfrx[i]);
  220. Serial.println();
  221. }
  222. }
  223. NRF_RADIO->TASKS_DISABLE = 1;
  224. RWAIT_DISABLED();
  225. NRF_RADIO->EVENTS_DISABLED = 0;
  226. }
  227. void rfHopTo(uint8_t newCh)
  228. {
  229. // QoS hop is shared across all slots -- we run all connected sessions on the same channel for simplicity.
  230. // The per-slot session ADDRESS is what isolates the controllers from each other; the channel is global.
  231. if (g_curSlot < 0 || newCh == g_sessCh)
  232. return;
  233. uint8_t cur = g_sessCh, savedRfCh = g_rfCh;
  234. g_sessCh = newCh;
  235. // host frame now advertises newCh but is TXed on cur (per-slot session addr)
  236. g_rfCh = cur;
  237. for (int s = 0; s < NSLOT; s++)
  238. for (int k = 0; k < 6; k++) {
  239. rfHostFrameOnce(s, false);
  240. delayMicroseconds(700);
  241. }
  242. g_rfCh = savedRfCh; // poll + session beacon now run on g_sessCh=newCh
  243. }
  244. // TX one connected packet [LEN][S1][payload] on channel ch, then RX the reply into rfrx; decodes 0xF1.
  245. // rxWinUs overrides the reply-wait window (0 = use g_rxWin). Pass a tiny value for NO-ACK relays that expect
  246. // no reply, so they don't burn a full ~1.2ms window of dead air per haptic. Per-slot: the connected poll runs
  247. // on this slot's UNIQUE session address (one address per bonded controller); replies are demuxed by which
  248. // address the controller answers on (each controller only hears its own).
  249. uint8_t rfConnTx(uint8_t ch, uint8_t s1, const uint8_t *payload, uint8_t plen,
  250. uint16_t rxWinUs)
  251. {
  252. // relays pass a tiny window (no reply expected); polls use g_rxWin
  253. uint16_t win = rxWinUs ? rxWinUs : g_rxWin;
  254. memset(rftx, 0, sizeof rftx);
  255. rftx[0] = plen; // LENGTH = payload byte count
  256. rftx[1] = s1; // S1 (type-specific)
  257. memcpy(rftx + 2, payload, plen); // payload[0]=type byte, then data/TLVs
  258. rfConfig(ch);
  259. // connected poll runs on this slot's UNIQUE session addr (per-bond). g_curSlot is set by rfConnStep
  260. // before each call; fall back to slot 0 if not (e.g. rf_diag paths).
  261. int slot = (g_curSlot >= 0 && g_curSlot < NSLOT) ? g_curSlot : 0;
  262. rfSetAddr(g_sessBase[slot], g_sessPrefix[slot]);
  263. NRF_RADIO->PACKETPTR = (uint32_t)rftx;
  264. NRF_RADIO->SHORTS = RADIO_SHORTS_READY_START_Msk |
  265. RADIO_SHORTS_END_DISABLE_Msk;
  266. NRF_RADIO->EVENTS_DISABLED = 0;
  267. NRF_RADIO->TASKS_TXEN = 1;
  268. RWAIT_DISABLED();
  269. NRF_RADIO->EVENTS_DISABLED = 0;
  270. NRF_RADIO->PACKETPTR = (uint32_t)rfrx;
  271. rfrx[0] = 0;
  272. // RXEN->READY->START; catch the reply. ADDRESS->RSSISTART samples the reply's signal strength (read from
  273. // RSSISAMPLE below, surfaced to Steam via report 0x7B); DISABLED->RSSISTOP closes the measurement.
  274. NRF_RADIO->SHORTS = RADIO_SHORTS_READY_START_Msk |
  275. RADIO_SHORTS_ADDRESS_RSSISTART_Msk |
  276. RADIO_SHORTS_DISABLED_RSSISTOP_Msk;
  277. NRF_RADIO->EVENTS_END = 0;
  278. NRF_RADIO->TASKS_RXEN = 1;
  279. uint32_t t0 = micros();
  280. while (!NRF_RADIO->EVENTS_END && (micros() - t0) < win) {
  281. } // RX window (tunable 'r'; or relay override)
  282. uint8_t rxlen = 0;
  283. if (NRF_RADIO->EVENTS_END) {
  284. NRF_RADIO->EVENTS_END = 0;
  285. bool crcok = NRF_RADIO->CRCSTATUS & 1;
  286. rxlen = rfrx[0];
  287. // reply arrived but CRC failed -> RF quality (channel/interference)
  288. if (!crcok) {
  289. g_stCrc[slot]++;
  290. g_qosBad++;
  291. }
  292. // F1 input ~46B; 0x43-augmented ~66B -> allow up to MAXLEN(96)
  293. if (crcok && rxlen && rxlen <= 96) {
  294. // reply type byte (proven offset from captures)
  295. uint8_t rtype = rfrx[2];
  296. // Only OUR controller's replies (F-type: 0xF1 input / 0xF2 disconnect / 0xF3 status) mark the link
  297. // alive. Every OpenPuck shares the same RF address "ibex" + CRC config, and a puck transmits host-frame
  298. // beacons (0xE1) + polls (0xE2/E3/E7) -- all E-type. Without this gate, puck A receives a SECOND puck's
  299. // 0xE1 beacon (e.g. one just plugged into another computer), bumps g_connReplyMs, and the "new RF
  300. // connection" wake in rfLinkTask() fires -> the second puck spuriously wakes this sleeping host.
  301. if (rtype >= 0xF0) {
  302. int s = (g_curSlot >= 0 && g_curSlot < NSLOT) ?
  303. g_curSlot :
  304. 0;
  305. // A reply after a long gap (or the first ever) = a (re)connect. Arm the haptic block + re-init HERE,
  306. // directly off the reply stream -- reliable even when hapticTask's 300ms link-up edge doesn't fire
  307. // (e.g. a power-cycled controller that reconnects without us cleanly seeing the link drop).
  308. if (g_connReplyMs[s] == 0 ||
  309. (uint32_t)(millis() - g_connReplyMs[s]) >
  310. 1500u) {
  311. // Lifecycle log (CDC debug boot): distinguish a first-ever connect from a reconnect and
  312. // print the silent gap -- lets a long session of connect/disconnect cycles be diffed to
  313. // see whether each cycle re-establishes (churn / boot-haptic click) vs stays linked.
  314. if (Serial.availableForWrite() > 130) {
  315. uint32_t gap =
  316. g_connReplyMs[s] ?
  317. (uint32_t)(millis() -
  318. g_connReplyMs
  319. [s]) :
  320. 0;
  321. Serial.printf(
  322. "# LC t=%lu slot%d %s gap=%lums rtype=%02X cd=%lums\n",
  323. (unsigned long)millis(),
  324. s,
  325. g_connReplyMs[s] ?
  326. "RECONNECT" :
  327. "CONNECT",
  328. (unsigned long)gap,
  329. rtype,
  330. (unsigned long)(millis() -
  331. g_connCooldown));
  332. }
  333. hapticOnReconnect(s);
  334. faultDiagTrace(FR_RFUP, s);
  335. }
  336. g_connRx++;
  337. // link alive -> loop() suppresses the redundant E1 beacon
  338. g_connReplyMs[s] = millis();
  339. // |dBm| of this reply (started by the ADDRESS short)
  340. uint8_t rs =
  341. (uint8_t)(NRF_RADIO->RSSISAMPLE & 0x7F);
  342. // EWMA, ~8-sample horizon, per-slot
  343. if (rs)
  344. g_linkRssi[s] =
  345. g_linkRssi[s] ?
  346. (uint8_t)((g_linkRssi[s] *
  347. 7u +
  348. rs + 4u) /
  349. 8u) :
  350. rs;
  351. }
  352. if (rtype == 0xF1)
  353. g_stF1[slot]++;
  354. // controller disconnecting/powering off -> back off 2.5s so we don't immediately re-wake it.
  355. // BUT only when no OTHER slot is still live: g_connCooldown is global and gates ALL polling +
  356. // beacons, so backing off because ONE controller powered off would drop every other connected
  357. // controller for 2.5s (a real multi-controller disconnect). The powering-off slot goes silent
  358. // and ages out via SLOT_COLD on its own.
  359. if (rtype == 0xF2) {
  360. int others = 0;
  361. for (int i = 0; i < NSLOT; i++)
  362. if (i != g_curSlot && g_slot[i].used &&
  363. millis() - g_connReplyMs[i] < 300)
  364. others++;
  365. faultDiagTrace(FR_RFDN,
  366. (uint16_t)((g_curSlot << 8) |
  367. (others & 0xFF)));
  368. if (others == 0)
  369. g_connCooldown = millis();
  370. // Lifecycle log: the controller sent F2 (disconnect/power-off). Note whether it armed the
  371. // 2.5s cooldown (which pauses ALL beacon+poll -> the controller can lose the session and
  372. // reboot on the next reconnect = a boot-haptic click). Prime suspect for the connect buzz.
  373. if (Serial.availableForWrite() > 130)
  374. Serial.printf(
  375. "# LC t=%lu slot%d F2 DISCONNECT others=%d%s\n",
  376. (unsigned long)millis(),
  377. g_curSlot, others,
  378. others == 0 ?
  379. " -> cooldown 2.5s (beacon+poll paused)" :
  380. "");
  381. }
  382. // F3 = controller status/version reply (reply to E7 handshake, byte[6]=version)
  383. if (rtype == 0xF3) {
  384. g_stF3++;
  385. g_connF3v = rfrx[6];
  386. if (g_connVerbose &&
  387. Serial.availableForWrite() > 40) {
  388. Serial.print(" F3 ");
  389. for (uint8_t i = 0;
  390. i <
  391. (rxlen + 2 < 32 ? rxlen + 2 : 32);
  392. i++)
  393. Serial.printf("%02X", rfrx[i]);
  394. Serial.println();
  395. }
  396. }
  397. bool isF1 = (rtype == 0xF1);
  398. // Every rfConnTx caller (rfConnStep) sets g_curSlot to a valid 0..NSLOT-1 before a poll, so it
  399. // IS in range here today. But this block does ~50 unguarded g_curSlot array writes (g_in[],
  400. // g_lastSeq[], and several static per-slot arrays) -- if any future/edge caller ever left
  401. // g_curSlot at -1, those become out-of-bounds writes that corrupt RAM (the stack-smash / LOCKUP
  402. // class we're chasing). Guard once at the top so the decode is robust by construction.
  403. if (isF1 && (g_curSlot < 0 || g_curSlot >= NSLOT))
  404. isF1 = false;
  405. if (isF1) {
  406. g_connF1++;
  407. // walk ALL type6 TLVs (= HID report 0x45); taking only [0] halves the rate. idx is INT,
  408. // not uint8_t: tlen 0xFE would make idx+=tlen+2 wrap mod-256 -> infinite loop -> USB hang.
  409. int idx = 3, end = rxlen + 2;
  410. const uint8_t *lastRep = nullptr;
  411. uint8_t lastTlen = 0;
  412. while (idx + 1 < end) {
  413. uint8_t tlen = rfrx[idx],
  414. ttype = rfrx[idx + 1];
  415. if (tlen == 0)
  416. break;
  417. // Only a FULL input report that fits entirely in rfrx: a short or late/garbled TLV must not let
  418. // the decode read past the RF buffer (corrupts rftx/RAM -> eventual crash).
  419. // Main input report id: 0x45 (legacy, 45B body) OR 0x42 (SC2 beta update ~2026-07, 53B body).
  420. // VERIFIED from live captures of both: the 0x42 body [0..45] is byte-for-byte the SAME layout as
  421. // 0x45 (buttons/triggers/sticks/pads/IMU at identical offsets) -- it just adds 8 trailing bytes
  422. // ([46..47]=0x7FFF const, [48..53]=0) and sets two extra always-on status bits (28/29) that no
  423. // mode reads. So both decode through this ONE path unchanged; rep[0] carries the id downstream
  424. // (Steam forwards it verbatim under the right id/length in onReport45).
  425. if (ttype == 6 && tlen >= 28 &&
  426. (size_t)(idx + 2) + tlen <=
  427. sizeof(rfrx) &&
  428. (rfrx[idx + 2] == 0x45 ||
  429. rfrx[idx + 2] == 0x42)) {
  430. // report 0x45/0x42: [id][seq][buttons u32]...
  431. const uint8_t *rep =
  432. &rfrx[idx + 2];
  433. bool fresh =
  434. (rep[1] !=
  435. g_lastSeq[g_curSlot]);
  436. // genuine new report vs stale poll-repeat
  437. if (fresh) {
  438. g_stNew[g_curSlot]++;
  439. g_lastSeq[g_curSlot] =
  440. rep[1];
  441. }
  442. uint32_t bb = btnsOf(rep);
  443. // USB remote wakeup on Steam button short press (down + up within 1 s). A long press likely means
  444. // the user is powering off the controller, so we ignore it.
  445. {
  446. // per-slot: with round-robin polling, a shared static gets
  447. // reset by other slots' reports between press and release.
  448. static bool steamWasDown
  449. [NSLOT] = {};
  450. static unsigned long steamDownMs
  451. [NSLOT] = {};
  452. if (fresh) {
  453. bool steamNow =
  454. (bb &
  455. TB_STEAM) !=
  456. 0;
  457. if (steamNow &&
  458. !steamWasDown
  459. [g_curSlot])
  460. steamDownMs[g_curSlot] =
  461. millis();
  462. if (!steamNow &&
  463. steamWasDown
  464. [g_curSlot] &&
  465. millis() - steamDownMs[g_curSlot] <
  466. 1000u &&
  467. USBDevice
  468. .suspended()) {
  469. USBDevice
  470. .remoteWakeup();
  471. ledWakePulse();
  472. if (g_active)
  473. g_active->wakeEvent();
  474. }
  475. steamWasDown[g_curSlot] =
  476. steamNow;
  477. }
  478. }
  479. // Decode the report into the shared g_in (one source, read by every IController).
  480. g_in[g_curSlot].buttons = bb;
  481. // Global power-off chord: Steam + Y held 2 s -> shut the controller down (any mode). Detect on the raw
  482. // `bb` (pre-mask), time-based (poll rate varies), fires once per hold, re-arms only after release. While
  483. // held, mask Steam+Y out of g_in[g_curSlot].buttons so the press doesn't leak to the host -- in EVERY mode except
  484. // regular Steam (mode 0 forwards the raw 0x45 to Steam, which owns the Steam button). Runs before
  485. // onReport45 below so push modes (Xbox) see the mask too; stream modes read g_in in task() (also masked).
  486. {
  487. // Per-slot: each controller's Steam+Y hold is independent, so the debounce timer must
  488. // be per-slot. With multiple controllers, a shared timer gets reset every time ANOTHER
  489. // slot's poll (without the hold) runs -- and the round-robin poll cycles through every
  490. // used slot, so the timer never reaches 2s.
  491. static unsigned long
  492. offHoldMs[NSLOT] = {
  493. 0, 0, 0,
  494. 0
  495. };
  496. static bool offFired
  497. [NSLOT] = {
  498. false,
  499. false,
  500. false,
  501. false
  502. };
  503. if ((bb & (TB_STEAM |
  504. TB_Y)) ==
  505. (TB_STEAM | TB_Y)) {
  506. if (offHoldMs[g_curSlot] ==
  507. 0)
  508. offHoldMs[g_curSlot] =
  509. millis();
  510. else if (
  511. !offFired[g_curSlot] &&
  512. (unsigned long)(millis() -
  513. offHoldMs[g_curSlot]) >=
  514. 2000u) {
  515. offFired[g_curSlot] =
  516. true;
  517. hapticSendShutdown();
  518. }
  519. if (g_usbMode !=
  520. MODE_STEAM) {
  521. // stream modes read g_in
  522. g_in[g_curSlot]
  523. .buttons &=
  524. ~(uint32_t)(TB_STEAM |
  525. TB_Y);
  526. // push modes read btnsOf(rep): TB_Y in rep[2],
  527. ((uint8_t *)
  528. rep)
  529. [2] &=
  530. ~(uint8_t)
  531. TB_Y;
  532. // TB_STEAM in rep[4]
  533. ((uint8_t *)
  534. rep)
  535. [4] &=
  536. ~(uint8_t)(TB_STEAM >>
  537. 16);
  538. }
  539. } else {
  540. offHoldMs[g_curSlot] =
  541. 0;
  542. offFired[g_curSlot] =
  543. false;
  544. }
  545. }
  546. g_in[g_curSlot].lx =
  547. (int16_t)s16off(rep, 8);
  548. g_in[g_curSlot].ly =
  549. (int16_t)s16off(rep,
  550. 10);
  551. g_in[g_curSlot].rx =
  552. (int16_t)s16off(rep,
  553. 12);
  554. g_in[g_curSlot].ry =
  555. (int16_t)s16off(rep,
  556. 14);
  557. g_in[g_curSlot].lt =
  558. trigU8(u16off(rep, 4));
  559. // for the Switch digital-trigger threshold
  560. g_in[g_curSlot].rt =
  561. trigU8(u16off(rep, 6));
  562. g_in[g_curSlot].lpx =
  563. (int16_t)s16off(rep,
  564. 16);
  565. g_in[g_curSlot].lpy =
  566. (int16_t)s16off(rep,
  567. 18);
  568. g_in[g_curSlot].rpx =
  569. (int16_t)s16off(rep,
  570. 22);
  571. g_in[g_curSlot].rpy =
  572. (int16_t)s16off(rep,
  573. 24);
  574. // IMU lives at report bytes 0x22..0x2D (rep[34..45]). Decode it ONLY when a FULL 46-byte report was
  575. // actually received -- bounded by `end` (the received length), NOT sizeof(rfrx). The outer gate is
  576. // tlen>=28 (enough for buttons/sticks/pads, which end at rep[27]), so a short 0x45 (button-only, or
  577. // one whose IMU tail was lost) still passes it; without this guard imuFrom45 would read STALE bytes
  578. // past the received data and clobber g_in's gyro/accel. On a short frame, hold the last good IMU.
  579. if (tlen >= 46 &&
  580. (size_t)(idx + 2) + 46 <=
  581. (size_t)end)
  582. imuFrom45(
  583. rep,
  584. &g_in[g_curSlot]
  585. .ax,
  586. &g_in[g_curSlot]
  587. .ay,
  588. &g_in[g_curSlot]
  589. .az,
  590. &g_in[g_curSlot]
  591. .gx,
  592. &g_in[g_curSlot]
  593. .gy,
  594. &g_in[g_curSlot]
  595. .gz);
  596. // Mode-switch chord (all 4 back + face/dpad): don't leak the press to the host. g_in[g_curSlot].buttons stays
  597. // intact so the chord detector still fires; per-mode builders mask the same bits while back-4 held.
  598. if ((bb & CHORD_BACK4) ==
  599. CHORD_BACK4) {
  600. ((uint8_t *)rep)[2] &= ~(
  601. uint8_t)(TB_A |
  602. TB_B |
  603. TB_X |
  604. TB_Y);
  605. ((uint8_t *)rep)[3] &= ~(
  606. uint8_t)((TB_DDN |
  607. TB_DRT |
  608. TB_DLF |
  609. TB_DUP) >>
  610. 8);
  611. }
  612. // Hand the report to the active controller. STREAM modes ignore it (they emit from task() reading
  613. // g_in); PUSH modes (Xbox, puck/lizard) build + send their host report here.
  614. if (g_active)
  615. g_active->onReport45(
  616. g_curSlot, rep,
  617. fresh, tlen);
  618. lastRep = rep;
  619. lastTlen = tlen;
  620. } else if (ttype == 6 &&
  621. (size_t)(idx + 2) + tlen <=
  622. sizeof(rfrx) &&
  623. tlen >= 2 &&
  624. (rfrx[idx + 2] == 0x43 ||
  625. rfrx[idx + 2] == 0x44)) {
  626. // Controller STATUS reports (0x43 = periodic power/battery, ~every 2s; 0x44 = status event). The real
  627. // puck forwards these verbatim (onAuxReport) -- that's how Steam reads battery; also snapshot the
  628. // battery % for the WebUSB panel.
  629. // [rid][body...]
  630. const uint8_t *rep =
  631. &rfrx[idx + 2];
  632. // 0x43 body[0] = ucChargeState (EChargeState), body[1] = ucBatteryLevel % (sniff-derived).
  633. // rep[0]=rid, rep[1]=body[0], rep[2]=body[1]. Snapshot both for the WebUSB panel and the
  634. // synthesized full-length 0x43 the puck pushes for SDL (see puck_hid.cpp task()).
  635. if (rep[0] == 0x43 &&
  636. tlen >= 3 &&
  637. g_curSlot >= 0 &&
  638. g_curSlot < NSLOT) {
  639. g_batteryState[g_curSlot] =
  640. rep[1];
  641. g_battery[g_curSlot] =
  642. rep[2];
  643. }
  644. if (g_active)
  645. g_active->onAuxReport(
  646. g_curSlot,
  647. rep[0], rep + 1,
  648. (uint8_t)(tlen -
  649. 1));
  650. } else if (ttype == 6 &&
  651. (size_t)(idx + 2) + tlen <=
  652. sizeof(rfrx) &&
  653. tlen >= 1) {
  654. // DIAGNOSTIC (beta-update RE): a type-6 HID-report TLV whose report id we
  655. // DON'T decode (not 0x45 input, not 0x43/0x44 status). If the new controller
  656. // firmware moved input off 0x45, its record shows up here. Log rid + full body,
  657. // rate-limited + non-blocking so it can't stall the loop. Remove once pinned.
  658. static unsigned long lastUnk =
  659. 0;
  660. if (Serial.availableForWrite() >
  661. 150 &&
  662. millis() - lastUnk >= 200) {
  663. lastUnk = millis();
  664. Serial.printf(
  665. "UNK rid=%02X tlen=%u: ",
  666. rfrx[idx + 2],
  667. tlen);
  668. for (uint8_t i = 0;
  669. i < tlen; i++)
  670. Serial.printf(
  671. "%02X",
  672. rfrx[idx +
  673. 2 +
  674. i]);
  675. Serial.println();
  676. }
  677. }
  678. idx += tlen + 2;
  679. }
  680. // mode-switch chord (back4 + face/dpad): A=always Steam; B/X/Y=configurable (g_chordBtn[]);
  681. // dpad left/up/right/down=configurable (g_chordDpad[], defaults PS3/DS4/PS5/Switch). Debounced.
  682. {
  683. // Per-slot debounce: the chord input is per-slot (g_in[g_curSlot]), so the debounce counter
  684. // must be too. The shared-static form worked with 1 controller because slot 0 polled
  685. // back-to-back; with N>1, the round-robin poll cycles through every used slot, and the OTHER
  686. // slots' non-chord reports reset the counter on every iteration. The counter could never
  687. // reach 12 with multiple controllers, making the chord effectively dead.
  688. static uint8_t chWant[NSLOT] = {
  689. 0xFF, 0xFF, 0xFF, 0xFF
  690. };
  691. static uint8_t chCnt[NSLOT] = { 0, 0, 0,
  692. 0 };
  693. uint8_t want = 0xFF;
  694. if ((g_in[g_curSlot].buttons &
  695. CHORD_BACK4) == CHORD_BACK4) {
  696. if (g_in[g_curSlot].buttons &
  697. TB_A)
  698. want = MODE_STEAM;
  699. else if (g_in[g_curSlot].buttons &
  700. TB_B)
  701. want = g_chordBtn[0];
  702. else if (g_in[g_curSlot].buttons &
  703. TB_X)
  704. want = g_chordBtn[1];
  705. else if (g_in[g_curSlot].buttons &
  706. TB_Y)
  707. want = g_chordBtn[2];
  708. else if (g_in[g_curSlot].buttons &
  709. TB_DLF)
  710. want = g_chordDpad[CHD_LEFT];
  711. else if (g_in[g_curSlot].buttons &
  712. TB_DUP)
  713. want = g_chordDpad[CHD_UP];
  714. else if (g_in[g_curSlot].buttons &
  715. TB_DRT)
  716. want = g_chordDpad[CHD_RIGHT];
  717. else if (g_in[g_curSlot].buttons &
  718. TB_DDN)
  719. want = g_chordDpad[CHD_DOWN];
  720. }
  721. if (want != 0xFF &&
  722. want == chWant[g_curSlot]) {
  723. if (++chCnt[g_curSlot] >= 12 &&
  724. want != g_usbMode &&
  725. modeValid(want) &&
  726. !USBDevice.suspended()) {
  727. // clean detach + reboot into the new mode (releases any held
  728. // input on the outgoing device -- see modeSwitchReboot)
  729. modeSwitchReboot(want);
  730. }
  731. } else {
  732. chWant[g_curSlot] = want;
  733. chCnt[g_curSlot] =
  734. (want != 0xFF) ? 1 : 0;
  735. }
  736. }
  737. // compact stream for rf_controller_ui.py -- NON-BLOCKING: skip if CDC TX is backed up (a blocking
  738. // Serial.print stalls the RF+USB loop -> jaggy input). One line/frame using the last record.
  739. if (lastRep && !g_connVerbose &&
  740. !g_cmdCapture &&
  741. Serial.availableForWrite() > 150 &&
  742. millis() - g_lastStream >= 4) {
  743. g_lastStream = millis();
  744. Serial.print("I45 ");
  745. for (uint8_t i = 0; i < lastTlen; i++)
  746. Serial.printf("%02X",
  747. lastRep[i]);
  748. Serial.println();
  749. }
  750. }
  751. if (g_connVerbose && Serial.availableForWrite() > 180) {
  752. Serial.printf(
  753. "%s CRX#%lu txtype%02X ch%u len%u: ",
  754. isF1 ? "<<<F1" :
  755. (rtype == 0xF3 ? " F3" :
  756. " rx"),
  757. (unsigned long)g_connRx, payload[0], ch,
  758. rxlen);
  759. for (uint8_t i = 0;
  760. i < (rxlen + 2 <= 66 ? rxlen + 2 : 66);
  761. i++)
  762. Serial.printf("%02X", rfrx[i]);
  763. Serial.println();
  764. }
  765. } else
  766. rxlen = 0;
  767. // RX window expired with no packet at all
  768. } else {
  769. g_stNoRx[slot]++;
  770. g_qosBad++;
  771. }
  772. NRF_RADIO->TASKS_DISABLE = 1;
  773. RWAIT_DISABLED();
  774. NRF_RADIO->EVENTS_DISABLED = 0;
  775. return rxlen;
  776. }
  777. // Throttle: bonded slots that haven't replied in SLOT_COLD_MS are polled at most every SLOT_COLD_RETRY_MS
  778. // instead of every cycle. This keeps the online controllers at full 250 Hz while barely touching offline ones.
  779. #define SLOT_COLD_MS 5000u
  780. #define SLOT_COLD_RETRY_MS 2000u
  781. // Quiet tier: a slot that WAS replying but has been silent past SLOT_QUIET_MS (controller powering off, out
  782. // of range) backs off to SLOT_QUIET_RETRY_MS retries instead of full-rate polling until SLOT_COLD_MS demotes
  783. // it. Without this, a power-off left the slot at 250 Hz for 5 s with EVERY poll burning the whole g_rxWin
  784. // (~2 ms) waiting for a reply that never comes -- with two controllers powered off together that is ~100%
  785. // radio duty, the churn window the power-off watchdog hang (issue #72 repro) lives in. Recovery stays snappy:
  786. // the first reply re-warms the slot to full rate, so a controller returning from a fade waits <= one retry.
  787. #define SLOT_QUIET_MS 300u
  788. #define SLOT_QUIET_RETRY_MS 50u
  789. static unsigned long g_slotLastAttemptMs[NSLOT] = {};
  790. // Drive the connected-mode sequence. The cycle gate fires once per g_pollUs (250 Hz); each fire
  791. // polls EVERY warm slot back-to-back so all bonded controllers run at full rate regardless of count.
  792. // "Cold" means the slot WAS connected but has been silent for > SLOT_COLD_MS; slots that have never
  793. // replied stay warm so new controllers can connect at any time after boot. Cold slots retry every
  794. // SLOT_COLD_RETRY_MS.
  795. static void rfConnStep()
  796. {
  797. int firstUsed = -1;
  798. for (int k = 0; k < NSLOT; k++)
  799. if (g_slot[k].used) {
  800. firstUsed = k;
  801. break;
  802. }
  803. if (firstUsed < 0) {
  804. g_curSlot = -1;
  805. return;
  806. }
  807. uint8_t ch = g_sessCh;
  808. // announce HOST AWAKE: E7 00 00, a few times. The real puck does NOT do this (the controller streams F1 to a
  809. // bare E3 with no E7) -- skipped unless g_e7announce ('n') re-enables the legacy handshake.
  810. if (g_connSt == 0) {
  811. g_curSlot = firstUsed;
  812. if (g_e7announce) {
  813. uint8_t p[3] = { 0xE7, 0x00, g_e7b };
  814. rfConnTx(ch, 0x01, p, 3);
  815. if (++g_connStep >= 4) {
  816. g_connSt = 1;
  817. g_connStep = 0;
  818. Serial.println(
  819. "# CONN: awake announced -> polling");
  820. }
  821. } else {
  822. // real-puck path: straight to the bare-E3 poll loop, no E7
  823. g_connSt = 1;
  824. g_connStep = 0;
  825. }
  826. return;
  827. }
  828. // Cycle gate: fires once per g_pollUs (250 Hz). On each fire we poll EVERY warm slot
  829. // back-to-back so all bonded controllers run at full rate -- the real puck services all
  830. // controllers per cycle. Polling one-slot-per-call instead tied the per-slot rate to the
  831. // loop frequency AND split it across slots, collapsing 2 controllers to ~90 Hz.
  832. uint32_t nowUs = micros();
  833. if ((uint32_t)(nowUs - g_lastPollUs) < (uint32_t)g_pollUs)
  834. return;
  835. {
  836. // Cycle period stat: time between gate fires (= each slot's poll period, intended g_pollUs).
  837. static uint32_t lastCycleUs = 0;
  838. if (lastCycleUs) {
  839. g_pollDtSum += (uint32_t)(nowUs - lastCycleUs);
  840. g_pollDtCnt++;
  841. }
  842. lastCycleUs = nowUs;
  843. }
  844. g_lastPollUs += g_pollUs;
  845. if ((uint32_t)(nowUs - g_lastPollUs) >= (uint32_t)g_pollUs)
  846. g_lastPollUs = nowUs; // catch-up reset when a cycle overran
  847. unsigned long nowMs = millis();
  848. // Inline poll helper; emits E7 re-assert (every 32 polls, bounded reply window so a
  849. // missed F3 doesn't burn the whole slot budget), queues haptics, flushes relay, sends E3 GET.
  850. auto doPoll = [&](int k) {
  851. g_slotLastAttemptMs[k] = nowMs;
  852. g_curSlot = k;
  853. // re-assert awake/version every 32 polls (legacy; real puck never sends E7 -- gated by g_e7announce)
  854. if (g_e7announce && (g_connPoll & 0x1F) == 0) {
  855. uint8_t pa[3] = { 0xE7, 0x00, g_e7b };
  856. rfConnTx(ch, 0x01, pa, 3, 600);
  857. }
  858. rfConnQueueHapticRelay();
  859. {
  860. uint8_t rs1 =
  861. (uint8_t)((((g_relayPid[k]++) & 3) << 1) | 1);
  862. if (rfConnFlushRelay(ch, rs1))
  863. g_stRelay[k]++;
  864. }
  865. // per-slot PID cycle so each bonded controller's polls stay distinct
  866. uint8_t pidv = g_pollPid[k]++;
  867. uint8_t s1 = (g_e3mode == 1) ?
  868. (uint8_t)(((pidv & 3) << 1) | 1) :
  869. (g_e3mode == 2) ? (uint8_t)((pidv & 3) << 1) :
  870. 0x07;
  871. uint8_t rx;
  872. if (g_pollGet) {
  873. // legacy: E3 + TLV [len=02][subtype=01 GET][id=0x45][param]
  874. uint8_t p[5] = { 0xE3, 0x02, 0x01, 0x45, g_getParam };
  875. rx = rfConnTx(ch, s1, p, 5);
  876. } else {
  877. // real puck: BARE E3 (just the opcode) -- the controller streams F1 to any E3 ack
  878. uint8_t p[1] = { 0xE3 };
  879. rx = rfConnTx(ch, s1, p, 1);
  880. }
  881. if (rx)
  882. g_chF1[0]++;
  883. g_stPoll[k]++; // one true poll cycle for this slot
  884. g_connPoll++;
  885. };
  886. bool linkUp = anySlotLinkUp();
  887. if (!linkUp) {
  888. // (RE)ACQUIRE MODE -- nothing is linked. Poll used slots to catch a (re)connecting controller fast,
  889. // but ROUND-ROBIN: exactly ONE slot per cycle, so radio duty stays bounded to a single ~g_rxWin no-reply
  890. // wait per cycle no matter how many bonds are absent.
  891. //
  892. // Why not poll every absent slot per cycle: doing so was the fix for the solid-light reconnect livelock
  893. // (a slot silent > SLOT_COLD_MS had dropped to a 2s poll that kept missing the controller's re-adopt
  894. // window), BUT with two bonds absent it put TWO full ~g_rxWin no-reply waits + the every-loop beaconing
  895. // on every cycle -- a radio-duty spike that starved loop()/USB into a watchdog reset. The puck then
  896. // re-enumerated on every disconnect, so Steam saw a "new controller" and popped its setup wizard every
  897. // time. One slot per cycle keeps acquire snappy (N bonds => each polled at 250/N Hz, still far faster
  898. // than the old 2s cold cadence) while capping duty. A single used slot is still polled every cycle.
  899. static int acqIdx = 0;
  900. for (int n = 0; n < NSLOT; n++) {
  901. int k = (acqIdx + n) % NSLOT;
  902. if (g_slot[k].used) {
  903. acqIdx = (k + 1) % NSLOT;
  904. doPoll(k);
  905. break;
  906. }
  907. }
  908. } else {
  909. // CONNECTED -- at least one controller is live. Poll every WARM slot per cycle (all bonded controllers
  910. // at full rate -- the real puck services them all per cycle), and throttle the SILENT ones so they don't
  911. // steal reply windows from the live controller(s) (the issue-#72 radio-duty concern):
  912. // - "cold": WAS connected but silent > SLOT_COLD_MS (controller powered off / out of range);
  913. // - "quiet": briefly silent (fade) -> back off to SLOT_QUIET_RETRY_MS until it recovers or goes cold;
  914. // - "phantom": NEVER replied while another controller is live (e.g. a stale bond from a cloned backup).
  915. for (int k = 0; k < NSLOT; k++) {
  916. if (!g_slot[k].used)
  917. continue;
  918. bool everReplied = g_connReplyMs[k] != 0;
  919. unsigned long silentMs =
  920. everReplied ? (nowMs - g_connReplyMs[k]) : 0;
  921. bool cold = everReplied && silentMs > SLOT_COLD_MS;
  922. bool quiet = everReplied && !cold &&
  923. silentMs > SLOT_QUIET_MS;
  924. bool phantom = !everReplied;
  925. unsigned long retry = (cold || phantom) ?
  926. SLOT_COLD_RETRY_MS :
  927. quiet ? SLOT_QUIET_RETRY_MS :
  928. 0;
  929. if (retry && nowMs - g_slotLastAttemptMs[k] < retry)
  930. continue;
  931. doPoll(k);
  932. }
  933. }
  934. }
  935. void rfLinkTask()
  936. {
  937. // Poll before beacons: the cycle gate must fire as close to its
  938. // 4 ms deadline as possible; beacon TX (up to 3.6 ms for 4 slots)
  939. // runs after so it never delays the current poll.
  940. if (g_connOn && millis() - g_connCooldown > 2500) {
  941. rfConnStep();
  942. } // connected-mode: poll controller, read input
  943. // Host-frame beacon: sent continuously, INCLUDING while connected. The controller uses the periodic E1 (the
  944. // real puck's per-hop-cycle announce) to stay synced and keep answering polls at full rate; suppressing it
  945. // drops the reply rate from ~210/s to ~38/s. Paused only during the post-disconnect cooldown so a controller
  946. // that's powering off isn't immediately re-woken/reconnected.
  947. if (g_rfHost && millis() - g_connCooldown > 2500) {
  948. bool connNow = anySlotLinkUp();
  949. // session keepalive on the clean channel: every loop while connecting (fast), every 25ms once connected
  950. // (every-loop beaconing also hammers the session ch and steals reply slots from the poll). The real puck
  951. // sends NO E1 on its session channel; gated by g_e1keepalive ('m') so this can be A/B'd on hardware --
  952. // but it stays ON by default because OpenPuck's shared-address model relies on E1 to advertise the session.
  953. if (g_e1keepalive &&
  954. millis() - g_lastSessBeacon >= (connNow ? 25u : 0u)) {
  955. g_lastSessBeacon = millis();
  956. g_rfCh = g_sessCh;
  957. for (int s = 0; s < NSLOT; s++)
  958. rfHostFrameOnce(s, false);
  959. }
  960. // discovery beacon on ch2 (where a searching controller looks): every loop when nothing is
  961. // connected (fastest cold-boot/late-joiner connect), every 200ms once ANY controller is linked.
  962. // Matches main: while a slot is connected, ch2 discovery shares g_sessCh's air budget, so beaconing
  963. // faster than 200ms (the old allUp-gated 40ms path) just steals reply windows from the connected
  964. // controller -> reply-rate sag -> >1500ms gaps -> spurious hapticOnReconnect re-init. A late joiner
  965. // still enumerates within ~1s at 200ms.
  966. if (millis() - g_lastDisc >= (connNow ? 200u : 0u)) {
  967. g_lastDisc = millis();
  968. g_rfCh = 2;
  969. for (int s = 0; s < NSLOT; s++)
  970. rfHostFrameOnce(s, true);
  971. }
  972. }
  973. // Release stale input on a per-slot link-drop edge. g_in[s] is refreshed ONLY
  974. // by the 0x45 decode on a fresh reply, so once a controller goes silent the
  975. // last-decoded input is frozen in place: STREAM modes (Switch Hori/Pro, PS5,
  976. // DS4-gyro) keep emitting it every cycle, and PUSH modes (Steam/puck, Xbox)
  977. // leave the host holding their last report -- a feathered trigger, or a
  978. // "release" frame that was the one lost in the gap, stays asserted for the
  979. // whole outage (the stuck / false-trigger symptom, most visible on the analog
  980. // triggers). On the up->down edge, zero g_in[s] (neutralizes the stream modes)
  981. // and push one synthetic neutral 0x45 through the active push mode's normal
  982. // build path (neutralizes Steam/puck -- including held lizard keys/mouse --
  983. // and Xbox; a no-op for stream modes, which don't override onReport45). The
  984. // next real 0x45 on reconnect refills everything. PS3 already streams its own
  985. // neutral when no slot is live, so it needs nothing here.
  986. {
  987. static bool wasUp[NSLOT] = {};
  988. static const uint8_t neutral45[46] = { 0x45 };
  989. for (int s = 0; s < NSLOT; s++) {
  990. bool up = g_slot[s].used && g_connReplyMs[s] != 0 &&
  991. (millis() - g_connReplyMs[s] < 300u);
  992. if (wasUp[s] && !up) {
  993. memset(&g_in[s], 0, sizeof g_in[s]);
  994. if (g_active)
  995. g_active->onReport45(s, neutral45, true,
  996. sizeof neutral45);
  997. }
  998. wasUp[s] = up;
  999. }
  1000. }
  1001. // ---- RF stall self-heal -------------------------------------------------------------------------------
  1002. // Field wedge: the controllers stay powered and show a SOLID (connected) light, the puck keeps issuing E3
  1003. // polls + E1 beacons (radio TX is provably alive -- a power-cycled controller still re-adopts the session
  1004. // and goes solid against this puck), yet NOT ONE slot decodes a reply for seconds. The link reads down, no
  1005. // input reaches the host, and it never recovers on its own -- only a puck REPLUG fixes it. rfConfig() already
  1006. // re-disables (TASKS_DISABLE) the radio before every poll, so whatever this is survives a TASKS_DISABLE; the
  1007. // only thing that clears it is a full peripheral reset -- exactly what the replug does. So when the WHOLE
  1008. // link has been silent past RF_STALL_MS while we're still actively polling a slot that WAS connected, do the
  1009. // replug's job for the radio: power-cycle NRF_RADIO (POWER=0/1 clears every RADIO register; the next
  1010. // rfConnTx/rfHostFrameOnce re-applies all config via rfConfig()) and drop the connected-mode latches so
  1011. // polling/beaconing resume and the handshake re-runs from a clean slate. Gated on EVERY used+previously-
  1012. // connected slot being stalled, so one controller walking off (others still live) never trips it; the
  1013. // cooldown gate keeps it from firing while a controller is intentionally powering off; rate-limited so it
  1014. // cannot thrash. g_rfStallRecover is surfaced to the panel so the wedge -- and its recovery -- is observable.
  1015. if (g_connOn && g_curSlot >= 0 && millis() - g_connCooldown > 2500) {
  1016. static unsigned long lastRecoverMs = 0;
  1017. static uint8_t consecStall = 0;
  1018. unsigned long nowMs2 = millis();
  1019. bool anyEverConnected = false, allStalled = true;
  1020. for (int s = 0; s < NSLOT; s++) {
  1021. if (!(g_slot[s].used && g_connReplyMs[s] != 0))
  1022. continue;
  1023. anyEverConnected = true;
  1024. if ((uint32_t)(nowMs2 - g_connReplyMs[s]) < RF_STALL_MS)
  1025. allStalled = false;
  1026. }
  1027. // Any slot alive -> a recovery worked (or we were never stalled): reset the give-up counter.
  1028. if (!allStalled)
  1029. consecStall = 0;
  1030. // Back off once we've power-cycled RF_STALL_GIVEUP times with nothing coming back (controller absent,
  1031. // not a wedged radio): slow the retry to RF_STALL_BACKOFF_MS instead of hammering every RF_RECOVER_MS.
  1032. uint32_t interval = (consecStall < RF_STALL_GIVEUP) ?
  1033. RF_RECOVER_MS :
  1034. RF_STALL_BACKOFF_MS;
  1035. if (anyEverConnected && allStalled &&
  1036. (uint32_t)(nowMs2 - lastRecoverMs) > interval) {
  1037. lastRecoverMs = nowMs2;
  1038. g_rfStallRecover++;
  1039. faultDiagTrace(FR_HEAL, g_rfStallRecover);
  1040. if (consecStall < 255)
  1041. consecStall++;
  1042. NRF_RADIO->POWER = 0;
  1043. NRF_RADIO->POWER = 1;
  1044. g_connCooldown = 0;
  1045. g_connSt = 0;
  1046. g_connStep = 0;
  1047. if (Serial.availableForWrite() > 110)
  1048. Serial.printf(
  1049. "# RF STALL (#%u consec=%u%s) -> radio power-cycle + reconnect\n",
  1050. g_rfStallRecover, consecStall,
  1051. consecStall >= RF_STALL_GIVEUP ?
  1052. " BACKOFF" :
  1053. "");
  1054. }
  1055. }
  1056. {
  1057. // remote wakeup on new RF controller connection (any slot)
  1058. static bool wasRfConn = false;
  1059. bool nowRfConn = anySlotLinkUp();
  1060. if (nowRfConn && !wasRfConn && USBDevice.suspended()) {
  1061. USBDevice.remoteWakeup();
  1062. ledWakePulse();
  1063. // post-resume nudge (host needs real input to actually wake)
  1064. if (g_active)
  1065. g_active->wakeEvent();
  1066. }
  1067. wasRfConn = nowRfConn;
  1068. }
  1069. // QoS: if the current channel is degrading (crcfail+noRx), hop to the next clean candidate (conservative).
  1070. if (g_qos && g_curSlot >= 0 && millis() - g_qosCheckMs >= 600) {
  1071. uint16_t bad = g_qosBad;
  1072. g_qosBad = 0;
  1073. g_qosCheckMs = millis();
  1074. if (bad > 20 && millis() - g_qosLastHopMs > 2000) {
  1075. for (int k = 0; k < (int)sizeof g_hopCand; k++) {
  1076. g_hopIdx = (g_hopIdx + 1) % (sizeof g_hopCand);
  1077. if (g_hopCand[g_hopIdx] != g_sessCh)
  1078. break;
  1079. }
  1080. if (Serial.availableForWrite() > 60)
  1081. Serial.printf(
  1082. "# QoS: ch%u bad=%u -> hop ch%u\n",
  1083. g_sessCh, bad, g_hopCand[g_hopIdx]);
  1084. rfHopTo(g_hopCand[g_hopIdx]);
  1085. g_qosLastHopMs = millis();
  1086. }
  1087. }
  1088. if (g_connOn && millis() - g_stMs >= 1000) {
  1089. // Per-slot snapshots first (blob v13 / per-controller panel stats), then the legacy aggregates as
  1090. // their sums (serial stat line + pre-v13 blob fields).
  1091. uint32_t tPoll = 0, tF1 = 0, tNew = 0, tCrc = 0, tNoRx = 0,
  1092. tRelay = 0;
  1093. for (int s = 0; s < NSLOT; s++) {
  1094. g_slotPollsps[s] = (uint16_t)g_stPoll[s];
  1095. g_slotF1ps[s] = (uint16_t)g_stF1[s];
  1096. g_slotNewps[s] = (uint16_t)g_stNew[s];
  1097. g_slotCrcps[s] =
  1098. (uint8_t)(g_stCrc[s] > 255 ? 255 : g_stCrc[s]);
  1099. g_slotNoRxps[s] = (uint8_t)(g_stNoRx[s] > 255 ?
  1100. 255 :
  1101. g_stNoRx[s]);
  1102. g_slotRelayps[s] = (uint8_t)(g_stRelay[s] > 255 ?
  1103. 255 :
  1104. g_stRelay[s]);
  1105. tPoll += g_stPoll[s];
  1106. tF1 += g_stF1[s];
  1107. tNew += g_stNew[s];
  1108. tCrc += g_stCrc[s];
  1109. tNoRx += g_stNoRx[s];
  1110. tRelay += g_stRelay[s];
  1111. g_stPoll[s] = g_stF1[s] = g_stNew[s] = 0;
  1112. g_stCrc[s] = g_stNoRx[s] = g_stRelay[s] = 0;
  1113. }
  1114. g_f1ps = (uint16_t)tF1;
  1115. g_newps = (uint16_t)tNew;
  1116. g_pollsps = (uint16_t)tPoll;
  1117. g_relayps = (uint16_t)tRelay;
  1118. g_crcps = (uint16_t)tCrc;
  1119. g_norxps = (uint16_t)tNoRx;
  1120. g_pollPeriodUs =
  1121. g_pollDtCnt ? (uint16_t)(g_pollDtSum / g_pollDtCnt) : 0;
  1122. g_pollDtSum = 0;
  1123. g_pollDtCnt = 0;
  1124. // Require room for the WHOLE line (~85B): CDC write() has NO timeout -- it spins yield() until the host
  1125. // drains, so a guard smaller than the line lets write() start, fill the FIFO mid-line, then spin loop()
  1126. // forever if the serial host stalls -> watchdog hang. (This exact line, guarded at >70 for an ~85B line,
  1127. // was the confirmed diagnostic-induced hang: the capture ended truncated mid-"# stat".)
  1128. if (Serial.availableForWrite() > 130)
  1129. Serial.printf(
  1130. "# stat polls=%lu/s F1=%lu/s new=%lu/s F3=%lu/s(v%d) e7b=%u crcfail=%lu noRx=%lu slot=%d\n",
  1131. (unsigned long)tPoll, (unsigned long)tF1,
  1132. (unsigned long)tNew, (unsigned long)g_stF3,
  1133. (int8_t)g_connF3v, g_e7b, (unsigned long)tCrc,
  1134. (unsigned long)tNoRx, g_curSlot);
  1135. g_stF3 = 0;
  1136. g_chF1[0] = g_chF1[1] = g_chF1[2] = 0;
  1137. g_stMs = millis();
  1138. }
  1139. }