rf_link.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  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 "controllers.h"
  8. #include "status_led.h"
  9. #include "fault_diag.h"
  10. #include <Adafruit_TinyUSB.h>
  11. #include <Arduino.h>
  12. #include <string.h>
  13. bool g_rfHost = true;
  14. bool g_connOn = true;
  15. uint8_t g_connType = 0xE7; // start with protocol-version handshake, then 0xE3
  16. // 0=current(slow/awake), 1=protocol-version-1. 'V<n>' to toggle.
  17. uint8_t g_e7b = 0;
  18. uint8_t g_connLen = 0x08;
  19. // GET report 0x45 param byte. 'q' cmd.
  20. uint8_t g_getParam = 0x00;
  21. // cycling the ESB PID drains the controller's report queue (~400 new/s vs ~60 with a fixed PID). 'e<n>' selects.
  22. uint8_t g_e3mode = 1;
  23. // ---- real-puck alignment (sniff1.json: a bonded controller RECONNECTING) ----
  24. // The live air capture of a real puck<->controller reconnect shows the controller streams 0xF1 input in
  25. // response to a BARE 0xE3 poll (1-byte payload, just the opcode) with NO 0xE7 awake-announce and NO
  26. // GET-report-0x45 sub-TLV -- 1857 of the puck's 2003 polls were bare E3, and the very first session frame
  27. // (a bare E3) was answered by F1 immediately. That contradicts the earlier RE "recipe" (rf_link.h) which
  28. // assumed E7 + GET-0x45 were required. So these now default to the real-puck behavior; flip them at runtime
  29. // ('d'/'n' console cmds) to fall back to the legacy GET/E7 path for an A/B comparison on hardware.
  30. bool g_pollGet =
  31. false; // false = bare E3 poll (real puck); true = append GET-report-0x45 TLV (legacy)
  32. bool g_e7announce =
  33. false; // false = no E7 awake-announce (real puck); true = announce host-awake (legacy)
  34. // Session-channel E1 host-frame keepalive. The real puck sends NO E1 on its session channel (the bonded
  35. // controller already knows the per-bond address and just resumes). OpenPuck still needs E1 because it runs
  36. // the SHARED "ibex" address, not the (un-reversed) per-bond address -- E1 is how the controller learns this
  37. // puck's session base/prefix/channel. So this defaults ON; turn it off ('m') to test the real-puck "no
  38. // session E1" model once per-bond addressing exists. Discovery on ch2 is separate and always runs.
  39. bool g_e1keepalive = true;
  40. bool g_connVerbose = false;
  41. // poll RX-window (us); shorter=more polls/s but may miss DELAYED replies. Persisted + panel-adjustable; 'r'.
  42. uint32_t g_rxWin = 2000;
  43. unsigned long g_connCooldown = 0;
  44. uint8_t g_connSt = 0; // 0=announce awake, 1=poll loop
  45. uint8_t g_connStep = 0; // repeat counter within a state
  46. uint16_t g_connPoll = 0; // poll counter (re-assert awake every 32nd)
  47. uint32_t g_connF1 = 0;
  48. uint8_t g_connF3v = 0xFF;
  49. uint8_t g_qos = 0;
  50. // clean, spread channels (from the puck's RSSI/PER scan)
  51. static const uint8_t g_hopCand[] = { 18, 46, 76, 22, 68 };
  52. uint8_t g_hopIdx = 0;
  53. volatile uint16_t g_qosBad = 0;
  54. unsigned long g_qosCheckMs = 0, g_qosLastHopMs = 0;
  55. uint16_t g_f1ps = 0;
  56. uint16_t g_newps = 0;
  57. // polls/s (GET+relay TXs) last second -- distinguishes loop-starvation from reply-loss
  58. uint16_t g_pollsps = 0;
  59. // measured avg us between GET-poll fires (vs intended g_pollUs)
  60. uint16_t g_pollPeriodUs = 0;
  61. static uint32_t g_pollDtSum = 0;
  62. static uint16_t g_pollDtCnt = 0;
  63. // smoothed |dBm| of the controller's replies, per slot (0 = none yet)
  64. volatile uint8_t g_linkRssi[NSLOT] = { 0 };
  65. // battery % from the controller's report 0x43 (body[1]); 0 = none yet. Per-slot -- the active controller's
  66. // battery is the most recently seen one (other slots' values stay in their own array slots).
  67. volatile uint8_t g_battery[NSLOT] = { 0 };
  68. // charge state from report 0x43 body[0] (EChargeState: 1=discharging 2=charging 4=charging-done; 0=unknown).
  69. volatile uint8_t g_batteryState[NSLOT] = { 0 };
  70. // Slot the poll loop is currently driving. Set by rfConnStep before each E7/relay/E3, consumed by the
  71. // decode (g_in[g_curSlot]), the haptic flush (per-slot session address), and the per-second stat dump.
  72. int g_curSlot = -1;
  73. // ---- internal counters / timers ----
  74. // ESB PID is 2 bits. The controller dequeues a FRESH report only when the poll's PID differs from the
  75. // last one it saw on that pipe; a repeated PID reads as a retransmit and returns the SAME (stale) report.
  76. // PER SLOT, because a single shared counter advances by (2 * nWarm) per cycle -- with 2 controllers that's
  77. // +4 per cycle = 0 mod 4, so each slot's GET PID is constant => the controller never dequeues => ~60 new/s
  78. // instead of ~400. Each slot's counter increments once per poll-of-that-slot so it cycles 0,1,2,3 cleanly.
  79. static uint8_t g_pollPid[NSLOT] = {};
  80. static uint8_t g_relayPid[NSLOT] = {};
  81. static uint32_t g_stPoll = 0, g_stF1 = 0, g_stF3 = 0;
  82. static unsigned long g_stMs = 0;
  83. // Per-slot dedupe seq + per-slot new-report counter (the real puck sends 0x45 per controller; merging all
  84. // slots into a single sequence makes one controller "swallow" the other's frame).
  85. static uint8_t g_lastSeq[NSLOT] = { 0 };
  86. static uint32_t g_stNew = 0;
  87. static uint32_t g_stCrc = 0, g_stNoRx = 0;
  88. static uint32_t g_chF1[3] = { 0, 0, 0 };
  89. // Cycle gate: fires once per g_pollUs; each fire polls every warm slot so all run at ~250 Hz.
  90. static uint32_t g_lastPollUs = 0;
  91. static uint32_t g_connRx = 0;
  92. static unsigned long g_lastSessBeacon = 0, g_lastDisc = 0;
  93. static unsigned long g_lastStream = 0;
  94. // HOST FRAME the bonded controller waits for (IBEX FUN_00019000 verify: b[0]=0x12, b[5]=0xE1, b[6..10]=
  95. // proteus_uuid, b[10..14]=ibex_uuid). Built like PROTEUS FUN_00027e9a. Sent on the shared rendezvous addr;
  96. // the controller filters by the uuids in the payload, then connects.
  97. // Transmit one host frame. `discovery`=true sends it on the SHARED rendezvous address ("ibex"/ch2) where a
  98. // searching controller looks; =false sends it on this slot's unique SESSION address (the keepalive once the
  99. // controller has adopted the session). EITHER way the payload advertises the session base/prefix/channel,
  100. // so the controller always learns the unique address to connect on.
  101. // Any-slot link helper: true if ANY bonded slot is currently hearing F-type replies (within 300 ms).
  102. // Used for the "we're connected to at least one controller" decisions (beacon pacing, wake detect).
  103. bool anySlotLinkUp()
  104. {
  105. for (int s = 0; s < NSLOT; s++)
  106. if (g_slot[s].used && millis() - g_connReplyMs[s] < 300)
  107. return true;
  108. return false;
  109. }
  110. static void rfHostFrameOnce(int slot, bool discovery)
  111. {
  112. if (slot < 0 || slot >= NSLOT || !g_slot[slot].used)
  113. return;
  114. // [proteus_uuid 4][ibex_uuid 4][serial 16]
  115. uint8_t *rec = g_slot[slot].rec;
  116. // CRC-VALIDATED frame (decoded from real puck): ESB-DPL RAM = [LENGTH][S1=PID][payload(18)]. payload:
  117. // [0]=0xE1, [1..5]=proteus_uuid LE, [5..9]=ibex_uuid LE, [9]=session channel, [10..13]=0, [13..17]=session
  118. // base, [17]=session prefix. Radio auto-appends CRC16 0x11021.
  119. memset(rftx, 0, sizeof rftx);
  120. // LENGTH = 18 (controller's buf[0]==0x12 check validates this)
  121. rftx[0] = 0x12;
  122. // S1 = PID<<1 | noack0 (matches real puck 00/02/04/06)
  123. rftx[1] = (uint8_t)((g_pid++ & 3) << 1);
  124. rftx[2] = 0xE1; // payload[0] marker
  125. // payload[1..5] proteus_uuid (LE, as bonded)
  126. memcpy(rftx + 3, rec + 0, 4);
  127. memcpy(rftx + 7, rec + 4, 4); // payload[5..9] ibex_uuid
  128. // payload[9] session channel: controller runs the session on this clean
  129. // channel (adopts buf[0xe]); discovery beacon still TXes on ch2
  130. rftx[11] = g_sessCh;
  131. // payload[13..17] session base (the per-bond UNIQUE address; each controller adopts its own)
  132. memcpy(rftx + 15, g_sessBase[slot], 4);
  133. rftx[19] = g_sessPrefix[slot]; // payload[17] session prefix
  134. // TX address: discovery uses the shared "ibex" rendezvous; the session keepalive uses this slot's
  135. // unique address (where THIS controller now listens). The advertised session params (above) are
  136. // identical either way -- so the discovery frame can also double as a re-advertisement if needed.
  137. const uint8_t *txBase = discovery ? g_rfBase : g_sessBase[slot];
  138. uint8_t txPfx = discovery ? g_rfPrefix : g_sessPrefix[slot];
  139. rfConfig(g_rfCh);
  140. rfSetAddr(txBase, txPfx);
  141. NRF_RADIO->PACKETPTR = (uint32_t)rftx;
  142. NRF_RADIO->SHORTS = RADIO_SHORTS_READY_START_Msk |
  143. RADIO_SHORTS_END_DISABLE_Msk;
  144. NRF_RADIO->EVENTS_DISABLED = 0;
  145. NRF_RADIO->TASKS_TXEN = 1;
  146. RWAIT_DISABLED();
  147. NRF_RADIO->EVENTS_DISABLED = 0;
  148. NRF_RADIO->PACKETPTR = (uint32_t)rfrx;
  149. rfrx[0] = 0;
  150. NRF_RADIO->SHORTS = RADIO_SHORTS_READY_START_Msk;
  151. NRF_RADIO->EVENTS_END = 0;
  152. NRF_RADIO->TASKS_RXEN = 1;
  153. // Discovery/pairing beacons listen for the controller's response (matters for RE/pairing); the connected
  154. // session keepalive expects NO response (the controller answers E3 polls, not the beacon), so don't burn
  155. // 800us of dead air per frame -- that was the bulk of the idle poll-rate deficit (40 beacons/s x slots).
  156. uint16_t bwin = discovery ? 800u : 150u;
  157. uint32_t t0 = micros();
  158. while (!NRF_RADIO->EVENTS_END && (micros() - t0) < bwin) {
  159. }
  160. if (NRF_RADIO->EVENTS_END) {
  161. // any reception = controller answered our frame
  162. NRF_RADIO->EVENTS_END = 0;
  163. g_rfRxCount++;
  164. bool crcok = NRF_RADIO->CRCSTATUS & 1;
  165. uint8_t len = rfrx[0];
  166. // non-blocking: don't stall the loop on CDC backpressure
  167. if (Serial.availableForWrite() > 90) {
  168. Serial.printf(
  169. "*** RESP#%lu ch%u crc%d rxmatch%lu len%u: ",
  170. (unsigned long)g_rfRxCount, g_rfCh, crcok,
  171. (unsigned long)NRF_RADIO->RXMATCH, len);
  172. for (uint8_t i = 0; i < (len < 40 ? len + 2 : 40); i++)
  173. Serial.printf("%02X ", rfrx[i]);
  174. Serial.println();
  175. }
  176. }
  177. NRF_RADIO->TASKS_DISABLE = 1;
  178. RWAIT_DISABLED();
  179. NRF_RADIO->EVENTS_DISABLED = 0;
  180. }
  181. void rfHopTo(uint8_t newCh)
  182. {
  183. // QoS hop is shared across all slots -- we run all connected sessions on the same channel for simplicity.
  184. // The per-slot session ADDRESS is what isolates the controllers from each other; the channel is global.
  185. if (g_curSlot < 0 || newCh == g_sessCh)
  186. return;
  187. uint8_t cur = g_sessCh, savedRfCh = g_rfCh;
  188. g_sessCh = newCh;
  189. // host frame now advertises newCh but is TXed on cur (per-slot session addr)
  190. g_rfCh = cur;
  191. for (int s = 0; s < NSLOT; s++)
  192. for (int k = 0; k < 6; k++) {
  193. rfHostFrameOnce(s, false);
  194. delayMicroseconds(700);
  195. }
  196. g_rfCh = savedRfCh; // poll + session beacon now run on g_sessCh=newCh
  197. }
  198. // TX one connected packet [LEN][S1][payload] on channel ch, then RX the reply into rfrx; decodes 0xF1.
  199. // rxWinUs overrides the reply-wait window (0 = use g_rxWin). Pass a tiny value for NO-ACK relays that expect
  200. // no reply, so they don't burn a full ~1.2ms window of dead air per haptic. Per-slot: the connected poll runs
  201. // on this slot's UNIQUE session address (one address per bonded controller); replies are demuxed by which
  202. // address the controller answers on (each controller only hears its own).
  203. uint8_t rfConnTx(uint8_t ch, uint8_t s1, const uint8_t *payload, uint8_t plen,
  204. uint16_t rxWinUs)
  205. {
  206. // relays pass a tiny window (no reply expected); polls use g_rxWin
  207. uint16_t win = rxWinUs ? rxWinUs : g_rxWin;
  208. memset(rftx, 0, sizeof rftx);
  209. rftx[0] = plen; // LENGTH = payload byte count
  210. rftx[1] = s1; // S1 (type-specific)
  211. memcpy(rftx + 2, payload, plen); // payload[0]=type byte, then data/TLVs
  212. rfConfig(ch);
  213. // connected poll runs on this slot's UNIQUE session addr (per-bond). g_curSlot is set by rfConnStep
  214. // before each call; fall back to slot 0 if not (e.g. rf_diag paths).
  215. int slot = (g_curSlot >= 0 && g_curSlot < NSLOT) ? g_curSlot : 0;
  216. rfSetAddr(g_sessBase[slot], g_sessPrefix[slot]);
  217. NRF_RADIO->PACKETPTR = (uint32_t)rftx;
  218. NRF_RADIO->SHORTS = RADIO_SHORTS_READY_START_Msk |
  219. RADIO_SHORTS_END_DISABLE_Msk;
  220. NRF_RADIO->EVENTS_DISABLED = 0;
  221. NRF_RADIO->TASKS_TXEN = 1;
  222. RWAIT_DISABLED();
  223. NRF_RADIO->EVENTS_DISABLED = 0;
  224. NRF_RADIO->PACKETPTR = (uint32_t)rfrx;
  225. rfrx[0] = 0;
  226. // RXEN->READY->START; catch the reply. ADDRESS->RSSISTART samples the reply's signal strength (read from
  227. // RSSISAMPLE below, surfaced to Steam via report 0x7B); DISABLED->RSSISTOP closes the measurement.
  228. NRF_RADIO->SHORTS = RADIO_SHORTS_READY_START_Msk |
  229. RADIO_SHORTS_ADDRESS_RSSISTART_Msk |
  230. RADIO_SHORTS_DISABLED_RSSISTOP_Msk;
  231. NRF_RADIO->EVENTS_END = 0;
  232. NRF_RADIO->TASKS_RXEN = 1;
  233. g_stPoll++;
  234. uint32_t t0 = micros();
  235. while (!NRF_RADIO->EVENTS_END && (micros() - t0) < win) {
  236. } // RX window (tunable 'r'; or relay override)
  237. uint8_t rxlen = 0;
  238. if (NRF_RADIO->EVENTS_END) {
  239. NRF_RADIO->EVENTS_END = 0;
  240. bool crcok = NRF_RADIO->CRCSTATUS & 1;
  241. rxlen = rfrx[0];
  242. // reply arrived but CRC failed -> RF quality (channel/interference)
  243. if (!crcok) {
  244. g_stCrc++;
  245. g_qosBad++;
  246. }
  247. // F1 input ~46B; 0x43-augmented ~66B -> allow up to MAXLEN(96)
  248. if (crcok && rxlen && rxlen <= 96) {
  249. // reply type byte (proven offset from captures)
  250. uint8_t rtype = rfrx[2];
  251. // Only OUR controller's replies (F-type: 0xF1 input / 0xF2 disconnect / 0xF3 status) mark the link
  252. // alive. Every OpenPuck shares the same RF address "ibex" + CRC config, and a puck transmits host-frame
  253. // beacons (0xE1) + polls (0xE2/E3/E7) -- all E-type. Without this gate, puck A receives a SECOND puck's
  254. // 0xE1 beacon (e.g. one just plugged into another computer), bumps g_connReplyMs, and the "new RF
  255. // connection" wake in rfLinkTask() fires -> the second puck spuriously wakes this sleeping host.
  256. if (rtype >= 0xF0) {
  257. int s = (g_curSlot >= 0 && g_curSlot < NSLOT) ?
  258. g_curSlot :
  259. 0;
  260. // A reply after a long gap (or the first ever) = a (re)connect. Arm the haptic block + re-init HERE,
  261. // directly off the reply stream -- reliable even when hapticTask's 300ms link-up edge doesn't fire
  262. // (e.g. a power-cycled controller that reconnects without us cleanly seeing the link drop).
  263. if (g_connReplyMs[s] == 0 ||
  264. (uint32_t)(millis() - g_connReplyMs[s]) >
  265. 1500u)
  266. hapticOnReconnect(s);
  267. g_connRx++;
  268. // link alive -> loop() suppresses the redundant E1 beacon
  269. g_connReplyMs[s] = millis();
  270. // |dBm| of this reply (started by the ADDRESS short)
  271. uint8_t rs =
  272. (uint8_t)(NRF_RADIO->RSSISAMPLE & 0x7F);
  273. // EWMA, ~8-sample horizon, per-slot
  274. if (rs)
  275. g_linkRssi[s] =
  276. g_linkRssi[s] ?
  277. (uint8_t)((g_linkRssi[s] *
  278. 7u +
  279. rs + 4u) /
  280. 8u) :
  281. rs;
  282. }
  283. if (rtype == 0xF1)
  284. g_stF1++;
  285. // controller disconnecting/powering off -> back off 2.5s so we don't immediately re-wake it.
  286. // BUT only when no OTHER slot is still live: g_connCooldown is global and gates ALL polling +
  287. // beacons, so backing off because ONE controller powered off would drop every other connected
  288. // controller for 2.5s (a real multi-controller disconnect). The powering-off slot goes silent
  289. // and ages out via SLOT_COLD on its own.
  290. if (rtype == 0xF2) {
  291. int others = 0;
  292. for (int i = 0; i < NSLOT; i++)
  293. if (i != g_curSlot && g_slot[i].used &&
  294. millis() - g_connReplyMs[i] < 300)
  295. others++;
  296. if (others == 0)
  297. g_connCooldown = millis();
  298. }
  299. // F3 = controller status/version reply (reply to E7 handshake, byte[6]=version)
  300. if (rtype == 0xF3) {
  301. g_stF3++;
  302. g_connF3v = rfrx[6];
  303. if (g_connVerbose &&
  304. Serial.availableForWrite() > 40) {
  305. Serial.print(" F3 ");
  306. for (uint8_t i = 0;
  307. i <
  308. (rxlen + 2 < 32 ? rxlen + 2 : 32);
  309. i++)
  310. Serial.printf("%02X", rfrx[i]);
  311. Serial.println();
  312. }
  313. }
  314. bool isF1 = (rtype == 0xF1);
  315. // Every rfConnTx caller (rfConnStep) sets g_curSlot to a valid 0..NSLOT-1 before a poll, so it
  316. // IS in range here today. But this block does ~50 unguarded g_curSlot array writes (g_in[],
  317. // g_lastSeq[], and several static per-slot arrays) -- if any future/edge caller ever left
  318. // g_curSlot at -1, those become out-of-bounds writes that corrupt RAM (the stack-smash / LOCKUP
  319. // class we're chasing). Guard once at the top so the decode is robust by construction.
  320. if (isF1 && (g_curSlot < 0 || g_curSlot >= NSLOT))
  321. isF1 = false;
  322. if (isF1) {
  323. g_connF1++;
  324. // walk ALL type6 TLVs (= HID report 0x45); taking only [0] halves the rate. idx is INT,
  325. // not uint8_t: tlen 0xFE would make idx+=tlen+2 wrap mod-256 -> infinite loop -> USB hang.
  326. int idx = 3, end = rxlen + 2;
  327. const uint8_t *lastRep = nullptr;
  328. uint8_t lastTlen = 0;
  329. while (idx + 1 < end) {
  330. uint8_t tlen = rfrx[idx],
  331. ttype = rfrx[idx + 1];
  332. if (tlen == 0)
  333. break;
  334. // Only a FULL 0x45 report that fits entirely in rfrx: a short or late/garbled TLV must not let the
  335. // decode read past the RF buffer (corrupts rftx/RAM -> eventual crash).
  336. if (ttype == 6 && tlen >= 28 &&
  337. (size_t)(idx + 2) + tlen <=
  338. sizeof(rfrx) &&
  339. rfrx[idx + 2] == 0x45) {
  340. // report 0x45: [0x45][seq][buttons u32]...
  341. const uint8_t *rep =
  342. &rfrx[idx + 2];
  343. bool fresh =
  344. (rep[1] !=
  345. g_lastSeq[g_curSlot]);
  346. // genuine new report vs stale poll-repeat
  347. if (fresh) {
  348. g_stNew++;
  349. g_lastSeq[g_curSlot] =
  350. rep[1];
  351. }
  352. uint32_t bb = btnsOf(rep);
  353. // USB remote wakeup on Steam button short press (down + up within 1 s). A long press likely means
  354. // the user is powering off the controller, so we ignore it.
  355. {
  356. // per-slot: with round-robin polling, a shared static gets
  357. // reset by other slots' reports between press and release.
  358. static bool steamWasDown
  359. [NSLOT] = {};
  360. static unsigned long steamDownMs
  361. [NSLOT] = {};
  362. if (fresh) {
  363. bool steamNow =
  364. (bb &
  365. TB_STEAM) !=
  366. 0;
  367. if (steamNow &&
  368. !steamWasDown
  369. [g_curSlot])
  370. steamDownMs[g_curSlot] =
  371. millis();
  372. if (!steamNow &&
  373. steamWasDown
  374. [g_curSlot] &&
  375. millis() - steamDownMs[g_curSlot] <
  376. 1000u &&
  377. USBDevice
  378. .suspended()) {
  379. USBDevice
  380. .remoteWakeup();
  381. ledWakePulse();
  382. if (g_active)
  383. g_active->wakeEvent();
  384. }
  385. steamWasDown[g_curSlot] =
  386. steamNow;
  387. }
  388. }
  389. // Decode the report into the shared g_in (one source, read by every IController).
  390. g_in[g_curSlot].buttons = bb;
  391. // Global power-off chord: Steam + Y held 2 s -> shut the controller down (any mode). Detect on the raw
  392. // `bb` (pre-mask), time-based (poll rate varies), fires once per hold, re-arms only after release. While
  393. // held, mask Steam+Y out of g_in[g_curSlot].buttons so the press doesn't leak to the host -- in EVERY mode except
  394. // regular Steam (mode 0 forwards the raw 0x45 to Steam, which owns the Steam button). Runs before
  395. // onReport45 below so push modes (Xbox) see the mask too; stream modes read g_in in task() (also masked).
  396. {
  397. // Per-slot: each controller's Steam+Y hold is independent, so the debounce timer must
  398. // be per-slot. With multiple controllers, a shared timer gets reset every time ANOTHER
  399. // slot's poll (without the hold) runs -- and the round-robin poll cycles through every
  400. // used slot, so the timer never reaches 2s.
  401. static unsigned long
  402. offHoldMs[NSLOT] = {
  403. 0, 0, 0,
  404. 0
  405. };
  406. static bool offFired
  407. [NSLOT] = {
  408. false,
  409. false,
  410. false,
  411. false
  412. };
  413. if ((bb & (TB_STEAM |
  414. TB_Y)) ==
  415. (TB_STEAM | TB_Y)) {
  416. if (offHoldMs[g_curSlot] ==
  417. 0)
  418. offHoldMs[g_curSlot] =
  419. millis();
  420. else if (
  421. !offFired[g_curSlot] &&
  422. (unsigned long)(millis() -
  423. offHoldMs[g_curSlot]) >=
  424. 2000u) {
  425. offFired[g_curSlot] =
  426. true;
  427. hapticSendShutdown();
  428. }
  429. if (g_usbMode !=
  430. MODE_STEAM) {
  431. // stream modes read g_in
  432. g_in[g_curSlot]
  433. .buttons &=
  434. ~(uint32_t)(TB_STEAM |
  435. TB_Y);
  436. // push modes read btnsOf(rep): TB_Y in rep[2],
  437. ((uint8_t *)
  438. rep)
  439. [2] &=
  440. ~(uint8_t)
  441. TB_Y;
  442. // TB_STEAM in rep[4]
  443. ((uint8_t *)
  444. rep)
  445. [4] &=
  446. ~(uint8_t)(TB_STEAM >>
  447. 16);
  448. }
  449. } else {
  450. offHoldMs[g_curSlot] =
  451. 0;
  452. offFired[g_curSlot] =
  453. false;
  454. }
  455. }
  456. g_in[g_curSlot].lx =
  457. (int16_t)s16off(rep, 8);
  458. g_in[g_curSlot].ly =
  459. (int16_t)s16off(rep,
  460. 10);
  461. g_in[g_curSlot].rx =
  462. (int16_t)s16off(rep,
  463. 12);
  464. g_in[g_curSlot].ry =
  465. (int16_t)s16off(rep,
  466. 14);
  467. g_in[g_curSlot].lt =
  468. trigU8(u16off(rep, 4));
  469. // for the Switch digital-trigger threshold
  470. g_in[g_curSlot].rt =
  471. trigU8(u16off(rep, 6));
  472. g_in[g_curSlot].lpx =
  473. (int16_t)s16off(rep,
  474. 16);
  475. g_in[g_curSlot].lpy =
  476. (int16_t)s16off(rep,
  477. 18);
  478. g_in[g_curSlot].rpx =
  479. (int16_t)s16off(rep,
  480. 22);
  481. g_in[g_curSlot].rpy =
  482. (int16_t)s16off(rep,
  483. 24);
  484. // IMU lives at report bytes 0x22..0x2D (rep[34..45]). Decode it ONLY when a FULL 46-byte report was
  485. // actually received -- bounded by `end` (the received length), NOT sizeof(rfrx). The outer gate is
  486. // tlen>=28 (enough for buttons/sticks/pads, which end at rep[27]), so a short 0x45 (button-only, or
  487. // one whose IMU tail was lost) still passes it; without this guard imuFrom45 would read STALE bytes
  488. // past the received data and clobber g_in's gyro/accel. On a short frame, hold the last good IMU.
  489. if (tlen >= 46 &&
  490. (size_t)(idx + 2) + 46 <=
  491. (size_t)end)
  492. imuFrom45(
  493. rep,
  494. &g_in[g_curSlot]
  495. .ax,
  496. &g_in[g_curSlot]
  497. .ay,
  498. &g_in[g_curSlot]
  499. .az,
  500. &g_in[g_curSlot]
  501. .gx,
  502. &g_in[g_curSlot]
  503. .gy,
  504. &g_in[g_curSlot]
  505. .gz);
  506. // Mode-switch chord (all 4 back + face): don't leak the face press to the host. g_in[g_curSlot].buttons stays
  507. // intact so the chord detector still fires; per-mode builders mask the same bits while back-4 held.
  508. if ((bb & CHORD_BACK4) ==
  509. CHORD_BACK4)
  510. ((uint8_t *)rep)[2] &= ~(
  511. uint8_t)(TB_A |
  512. TB_B |
  513. TB_X |
  514. TB_Y);
  515. // Hand the report to the active controller. STREAM modes ignore it (they emit from task() reading
  516. // g_in); PUSH modes (Xbox, puck/lizard) build + send their host report here.
  517. if (g_active)
  518. g_active->onReport45(
  519. g_curSlot, rep,
  520. fresh, tlen);
  521. lastRep = rep;
  522. lastTlen = tlen;
  523. } else if (ttype == 6 &&
  524. (size_t)(idx + 2) + tlen <=
  525. sizeof(rfrx) &&
  526. tlen >= 2 &&
  527. (rfrx[idx + 2] == 0x43 ||
  528. rfrx[idx + 2] == 0x44)) {
  529. // Controller STATUS reports (0x43 = periodic power/battery, ~every 2s; 0x44 = status event). The real
  530. // puck forwards these verbatim (onAuxReport) -- that's how Steam reads battery; also snapshot the
  531. // battery % for the WebUSB panel.
  532. // [rid][body...]
  533. const uint8_t *rep =
  534. &rfrx[idx + 2];
  535. // 0x43 body[0] = ucChargeState (EChargeState), body[1] = ucBatteryLevel % (sniff-derived).
  536. // rep[0]=rid, rep[1]=body[0], rep[2]=body[1]. Snapshot both for the WebUSB panel and the
  537. // synthesized full-length 0x43 the puck pushes for SDL (see puck_hid.cpp task()).
  538. if (rep[0] == 0x43 &&
  539. tlen >= 3 &&
  540. g_curSlot >= 0 &&
  541. g_curSlot < NSLOT) {
  542. g_batteryState[g_curSlot] =
  543. rep[1];
  544. g_battery[g_curSlot] =
  545. rep[2];
  546. }
  547. if (g_active)
  548. g_active->onAuxReport(
  549. g_curSlot,
  550. rep[0], rep + 1,
  551. (uint8_t)(tlen -
  552. 1));
  553. }
  554. idx += tlen + 2;
  555. }
  556. // mode-switch chord (back4 + face): A=always Steam; B/X/Y=configurable (g_chordBtn[]). Debounced.
  557. {
  558. // Per-slot debounce: the chord input is per-slot (g_in[g_curSlot]), so the debounce counter
  559. // must be too. The shared-static form worked with 1 controller because slot 0 polled
  560. // back-to-back; with N>1, the round-robin poll cycles through every used slot, and the OTHER
  561. // slots' non-chord reports reset the counter on every iteration. The counter could never
  562. // reach 12 with multiple controllers, making the chord effectively dead.
  563. static uint8_t chWant[NSLOT] = {
  564. 0xFF, 0xFF, 0xFF, 0xFF
  565. };
  566. static uint8_t chCnt[NSLOT] = { 0, 0, 0,
  567. 0 };
  568. uint8_t want = 0xFF;
  569. if ((g_in[g_curSlot].buttons &
  570. CHORD_BACK4) == CHORD_BACK4) {
  571. if (g_in[g_curSlot].buttons &
  572. TB_A)
  573. want = MODE_STEAM;
  574. else if (g_in[g_curSlot].buttons &
  575. TB_B)
  576. want = g_chordBtn[0];
  577. else if (g_in[g_curSlot].buttons &
  578. TB_X)
  579. want = g_chordBtn[1];
  580. else if (g_in[g_curSlot].buttons &
  581. TB_Y)
  582. want = g_chordBtn[2];
  583. }
  584. if (want != 0xFF &&
  585. want == chWant[g_curSlot]) {
  586. if (++chCnt[g_curSlot] >= 12 &&
  587. want != g_usbMode &&
  588. modeValid(want) &&
  589. !USBDevice.suspended()) {
  590. saveMode(want);
  591. delay(40);
  592. faultDiagArmIntentionalReset();
  593. NVIC_SystemReset();
  594. }
  595. } else {
  596. chWant[g_curSlot] = want;
  597. chCnt[g_curSlot] =
  598. (want != 0xFF) ? 1 : 0;
  599. }
  600. }
  601. // compact stream for rf_controller_ui.py -- NON-BLOCKING: skip if CDC TX is backed up (a blocking
  602. // Serial.print stalls the RF+USB loop -> jaggy input). One line/frame using the last record.
  603. if (lastRep && !g_connVerbose &&
  604. Serial.availableForWrite() > 110 &&
  605. millis() - g_lastStream >= 4) {
  606. g_lastStream = millis();
  607. Serial.print("I45 ");
  608. for (uint8_t i = 0; i < lastTlen; i++)
  609. Serial.printf("%02X",
  610. lastRep[i]);
  611. Serial.println();
  612. }
  613. }
  614. if (g_connVerbose) {
  615. Serial.printf(
  616. "%s CRX#%lu txtype%02X ch%u len%u: ",
  617. isF1 ? "<<<F1" :
  618. (rtype == 0xF3 ? " F3" :
  619. " rx"),
  620. (unsigned long)g_connRx, payload[0], ch,
  621. rxlen);
  622. for (uint8_t i = 0;
  623. i < (rxlen + 2 <= 66 ? rxlen + 2 : 66);
  624. i++)
  625. Serial.printf("%02X", rfrx[i]);
  626. Serial.println();
  627. }
  628. } else
  629. rxlen = 0;
  630. // RX window expired with no packet at all
  631. } else {
  632. g_stNoRx++;
  633. g_qosBad++;
  634. }
  635. NRF_RADIO->TASKS_DISABLE = 1;
  636. RWAIT_DISABLED();
  637. NRF_RADIO->EVENTS_DISABLED = 0;
  638. return rxlen;
  639. }
  640. // Throttle: bonded slots that haven't replied in SLOT_COLD_MS are polled at most every SLOT_COLD_RETRY_MS
  641. // instead of every cycle. This keeps the online controllers at full 250 Hz while barely touching offline ones.
  642. #define SLOT_COLD_MS 5000u
  643. #define SLOT_COLD_RETRY_MS 2000u
  644. static unsigned long g_slotLastAttemptMs[NSLOT] = {};
  645. // Drive the connected-mode sequence. The cycle gate fires once per g_pollUs (250 Hz); each fire
  646. // polls EVERY warm slot back-to-back so all bonded controllers run at full rate regardless of count.
  647. // "Cold" means the slot WAS connected but has been silent for > SLOT_COLD_MS; slots that have never
  648. // replied stay warm so new controllers can connect at any time after boot. Cold slots retry every
  649. // SLOT_COLD_RETRY_MS.
  650. static void rfConnStep()
  651. {
  652. int firstUsed = -1;
  653. for (int k = 0; k < NSLOT; k++)
  654. if (g_slot[k].used) {
  655. firstUsed = k;
  656. break;
  657. }
  658. if (firstUsed < 0) {
  659. g_curSlot = -1;
  660. return;
  661. }
  662. uint8_t ch = g_sessCh;
  663. // announce HOST AWAKE: E7 00 00, a few times. The real puck does NOT do this (the controller streams F1 to a
  664. // bare E3 with no E7) -- skipped unless g_e7announce ('n') re-enables the legacy handshake.
  665. if (g_connSt == 0) {
  666. g_curSlot = firstUsed;
  667. if (g_e7announce) {
  668. uint8_t p[3] = { 0xE7, 0x00, g_e7b };
  669. rfConnTx(ch, 0x01, p, 3);
  670. if (++g_connStep >= 4) {
  671. g_connSt = 1;
  672. g_connStep = 0;
  673. Serial.println(
  674. "# CONN: awake announced -> polling");
  675. }
  676. } else {
  677. // real-puck path: straight to the bare-E3 poll loop, no E7
  678. g_connSt = 1;
  679. g_connStep = 0;
  680. }
  681. return;
  682. }
  683. // Cycle gate: fires once per g_pollUs (250 Hz). On each fire we poll EVERY warm slot
  684. // back-to-back so all bonded controllers run at full rate -- the real puck services all
  685. // controllers per cycle. Polling one-slot-per-call instead tied the per-slot rate to the
  686. // loop frequency AND split it across slots, collapsing 2 controllers to ~90 Hz.
  687. uint32_t nowUs = micros();
  688. if ((uint32_t)(nowUs - g_lastPollUs) < (uint32_t)g_pollUs)
  689. return;
  690. {
  691. // Cycle period stat: time between gate fires (= each slot's poll period, intended g_pollUs).
  692. static uint32_t lastCycleUs = 0;
  693. if (lastCycleUs) {
  694. g_pollDtSum += (uint32_t)(nowUs - lastCycleUs);
  695. g_pollDtCnt++;
  696. }
  697. lastCycleUs = nowUs;
  698. }
  699. g_lastPollUs += g_pollUs;
  700. if ((uint32_t)(nowUs - g_lastPollUs) >= (uint32_t)g_pollUs)
  701. g_lastPollUs = nowUs; // catch-up reset when a cycle overran
  702. unsigned long nowMs = millis();
  703. // Inline poll helper; emits E7 re-assert (every 32 polls, bounded reply window so a
  704. // missed F3 doesn't burn the whole slot budget), queues haptics, flushes relay, sends E3 GET.
  705. auto doPoll = [&](int k) {
  706. g_slotLastAttemptMs[k] = nowMs;
  707. g_curSlot = k;
  708. // re-assert awake/version every 32 polls (legacy; real puck never sends E7 -- gated by g_e7announce)
  709. if (g_e7announce && (g_connPoll & 0x1F) == 0) {
  710. uint8_t pa[3] = { 0xE7, 0x00, g_e7b };
  711. rfConnTx(ch, 0x01, pa, 3, 600);
  712. }
  713. rfConnQueueHapticRelay();
  714. {
  715. uint8_t rs1 =
  716. (uint8_t)((((g_relayPid[k]++) & 3) << 1) | 1);
  717. rfConnFlushRelay(ch, rs1);
  718. }
  719. // per-slot PID cycle so each bonded controller's polls stay distinct
  720. uint8_t pidv = g_pollPid[k]++;
  721. uint8_t s1 = (g_e3mode == 1) ?
  722. (uint8_t)(((pidv & 3) << 1) | 1) :
  723. (g_e3mode == 2) ? (uint8_t)((pidv & 3) << 1) :
  724. 0x07;
  725. uint8_t rx;
  726. if (g_pollGet) {
  727. // legacy: E3 + TLV [len=02][subtype=01 GET][id=0x45][param]
  728. uint8_t p[5] = { 0xE3, 0x02, 0x01, 0x45, g_getParam };
  729. rx = rfConnTx(ch, s1, p, 5);
  730. } else {
  731. // real puck: BARE E3 (just the opcode) -- the controller streams F1 to any E3 ack
  732. uint8_t p[1] = { 0xE3 };
  733. rx = rfConnTx(ch, s1, p, 1);
  734. }
  735. if (rx)
  736. g_chF1[0]++;
  737. g_connPoll++;
  738. };
  739. // Poll every warm slot this cycle. "Cold" = was connected, now silent > SLOT_COLD_MS;
  740. // those are retried only every SLOT_COLD_RETRY_MS. Never-replied slots count as warm so
  741. // a controller that connects at any time gets the full poll rate to establish its link.
  742. for (int k = 0; k < NSLOT; k++) {
  743. if (!g_slot[k].used)
  744. continue;
  745. bool cold = g_connReplyMs[k] != 0 &&
  746. nowMs - g_connReplyMs[k] > SLOT_COLD_MS;
  747. if (cold && nowMs - g_slotLastAttemptMs[k] < SLOT_COLD_RETRY_MS)
  748. continue;
  749. doPoll(k);
  750. }
  751. }
  752. void rfLinkTask()
  753. {
  754. // Host-frame beacon: sent continuously, INCLUDING while connected. The controller uses the periodic E1 (the
  755. // real puck's per-hop-cycle announce) to stay synced and keep answering polls at full rate; suppressing it
  756. // drops the reply rate from ~210/s to ~38/s. Paused only during the post-disconnect cooldown so a controller
  757. // that's powering off isn't immediately re-woken/reconnected.
  758. if (g_rfHost && millis() - g_connCooldown > 2500) {
  759. bool connNow = anySlotLinkUp();
  760. // session keepalive on the clean channel: every loop while connecting (fast), every 25ms once connected
  761. // (every-loop beaconing also hammers the session ch and steals reply slots from the poll). The real puck
  762. // sends NO E1 on its session channel; gated by g_e1keepalive ('m') so this can be A/B'd on hardware --
  763. // but it stays ON by default because OpenPuck's shared-address model relies on E1 to advertise the session.
  764. if (g_e1keepalive &&
  765. millis() - g_lastSessBeacon >= (connNow ? 25u : 0u)) {
  766. g_lastSessBeacon = millis();
  767. g_rfCh = g_sessCh;
  768. for (int s = 0; s < NSLOT; s++)
  769. rfHostFrameOnce(s, false);
  770. }
  771. // discovery beacon on ch2 (where a searching controller looks): every loop when nothing is
  772. // connected (fastest cold-boot/late-joiner connect), every 200ms once ANY controller is linked.
  773. // Matches main: while a slot is connected, ch2 discovery shares g_sessCh's air budget, so beaconing
  774. // faster than 200ms (the old allUp-gated 40ms path) just steals reply windows from the connected
  775. // controller -> reply-rate sag -> >1500ms gaps -> spurious hapticOnReconnect re-init. A late joiner
  776. // still enumerates within ~1s at 200ms.
  777. if (millis() - g_lastDisc >= (connNow ? 200u : 0u)) {
  778. g_lastDisc = millis();
  779. g_rfCh = 2;
  780. for (int s = 0; s < NSLOT; s++)
  781. rfHostFrameOnce(s, true);
  782. }
  783. }
  784. if (g_connOn && millis() - g_connCooldown > 2500) {
  785. rfConnStep();
  786. } // connected-mode: poll controller, read input
  787. {
  788. // remote wakeup on new RF controller connection (any slot)
  789. static bool wasRfConn = false;
  790. bool nowRfConn = anySlotLinkUp();
  791. if (nowRfConn && !wasRfConn && USBDevice.suspended()) {
  792. USBDevice.remoteWakeup();
  793. ledWakePulse();
  794. // post-resume nudge (host needs real input to actually wake)
  795. if (g_active)
  796. g_active->wakeEvent();
  797. }
  798. wasRfConn = nowRfConn;
  799. }
  800. // QoS: if the current channel is degrading (crcfail+noRx), hop to the next clean candidate (conservative).
  801. if (g_qos && g_curSlot >= 0 && millis() - g_qosCheckMs >= 600) {
  802. uint16_t bad = g_qosBad;
  803. g_qosBad = 0;
  804. g_qosCheckMs = millis();
  805. if (bad > 20 && millis() - g_qosLastHopMs > 2000) {
  806. for (int k = 0; k < (int)sizeof g_hopCand; k++) {
  807. g_hopIdx = (g_hopIdx + 1) % (sizeof g_hopCand);
  808. if (g_hopCand[g_hopIdx] != g_sessCh)
  809. break;
  810. }
  811. if (Serial.availableForWrite() > 60)
  812. Serial.printf(
  813. "# QoS: ch%u bad=%u -> hop ch%u\n",
  814. g_sessCh, bad, g_hopCand[g_hopIdx]);
  815. rfHopTo(g_hopCand[g_hopIdx]);
  816. g_qosLastHopMs = millis();
  817. }
  818. }
  819. if (g_connOn && millis() - g_stMs >= 1000) {
  820. g_f1ps = g_stF1;
  821. g_newps = g_stNew;
  822. g_pollsps = (uint16_t)g_stPoll;
  823. g_pollPeriodUs =
  824. g_pollDtCnt ? (uint16_t)(g_pollDtSum / g_pollDtCnt) : 0;
  825. g_pollDtSum = 0;
  826. g_pollDtCnt = 0;
  827. if (Serial.availableForWrite() > 70)
  828. Serial.printf(
  829. "# stat polls=%lu/s F1=%lu/s new=%lu/s F3=%lu/s(v%d) e7b=%u crcfail=%lu noRx=%lu slot=%d\n",
  830. (unsigned long)g_stPoll, (unsigned long)g_stF1,
  831. (unsigned long)g_stNew, (unsigned long)g_stF3,
  832. (int8_t)g_connF3v, g_e7b,
  833. (unsigned long)g_stCrc, (unsigned long)g_stNoRx,
  834. g_curSlot);
  835. g_stPoll = 0;
  836. g_stF1 = 0;
  837. g_stNew = 0;
  838. g_stF3 = 0;
  839. g_stCrc = 0;
  840. g_stNoRx = 0;
  841. g_chF1[0] = g_chF1[1] = g_chF1[2] = 0;
  842. g_stMs = millis();
  843. }
  844. }