rf_link.cpp 47 KB

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