rf_link.cpp 44 KB

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