rf_link.cpp 33 KB

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