rf_link.cpp 47 KB

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