rf_link.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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. bool g_connVerbose = false;
  23. // poll RX-window (us); shorter=more polls/s but may miss DELAYED replies. Tunable 'r'.
  24. uint32_t g_rxWin = 1200;
  25. unsigned long g_connCooldown = 0;
  26. uint8_t g_connSt = 0; // 0=announce awake, 1=poll loop
  27. uint8_t g_connStep = 0; // repeat counter within a state
  28. uint16_t g_connPoll = 0; // poll counter (re-assert awake every 32nd)
  29. uint32_t g_connF1 = 0;
  30. uint8_t g_connF3v = 0xFF;
  31. uint8_t g_qos = 0;
  32. // clean, spread channels (from the puck's RSSI/PER scan)
  33. static const uint8_t g_hopCand[] = { 18, 46, 76, 22, 68 };
  34. uint8_t g_hopIdx = 0;
  35. volatile uint16_t g_qosBad = 0;
  36. unsigned long g_qosCheckMs = 0, g_qosLastHopMs = 0;
  37. uint16_t g_f1ps = 0;
  38. uint16_t g_newps = 0;
  39. // polls/s (GET+relay TXs) last second -- distinguishes loop-starvation from reply-loss
  40. uint16_t g_pollsps = 0;
  41. // measured avg us between GET-poll fires (vs intended g_pollUs)
  42. uint16_t g_pollPeriodUs = 0;
  43. static uint32_t g_pollDtSum = 0;
  44. static uint16_t g_pollDtCnt = 0;
  45. // smoothed |dBm| of the controller's replies (0 = none yet)
  46. volatile uint8_t g_linkRssi = 0;
  47. // battery % from the controller's report 0x43 (body[1]); 0 = none yet
  48. volatile uint8_t g_battery = 0;
  49. // ---- internal counters / timers ----
  50. static uint8_t g_e3pid = 0;
  51. static uint32_t g_stPoll = 0, g_stF1 = 0, g_stF3 = 0;
  52. static unsigned long g_stMs = 0;
  53. static uint8_t g_lastSeq = 0;
  54. static uint32_t g_stNew = 0;
  55. static uint32_t g_stCrc = 0, g_stNoRx = 0;
  56. static uint32_t g_chF1[3] = { 0, 0, 0 };
  57. static uint32_t g_lastPollUs = 0;
  58. static uint32_t g_connRx = 0;
  59. static unsigned long g_lastSessBeacon = 0, g_lastDisc = 0;
  60. static unsigned long g_lastStream = 0;
  61. // HOST FRAME the bonded controller waits for (IBEX FUN_00019000 verify: b[0]=0x12, b[5]=0xE1, b[6..10]=
  62. // proteus_uuid, b[10..14]=ibex_uuid). Built like PROTEUS FUN_00027e9a. Sent on the shared rendezvous addr;
  63. // the controller filters by the uuids in the payload, then connects.
  64. // Transmit one host frame. `discovery`=true sends it on the SHARED rendezvous address ("ibex"/ch2) where a
  65. // searching controller looks; =false sends it on this puck's unique SESSION address (the keepalive once the
  66. // controller has adopted the session). EITHER way the payload advertises the session base/prefix/channel, so
  67. // the controller always learns the unique address to connect on.
  68. static void rfHostFrameOnce(int slot, bool discovery)
  69. {
  70. if (slot < 0 || slot >= NSLOT || !g_slot[slot].used)
  71. return;
  72. // [proteus_uuid 4][ibex_uuid 4][serial 16]
  73. uint8_t *rec = g_slot[slot].rec;
  74. // CRC-VALIDATED frame (decoded from real puck): ESB-DPL RAM = [LENGTH][S1=PID][payload(18)]. payload:
  75. // [0]=0xE1, [1..5]=proteus_uuid LE, [5..9]=ibex_uuid LE, [9]=session channel, [10..13]=0, [13..17]=session
  76. // base, [17]=session prefix. Radio auto-appends CRC16 0x11021.
  77. memset(rftx, 0, sizeof rftx);
  78. // LENGTH = 18 (controller's buf[0]==0x12 check validates this)
  79. rftx[0] = 0x12;
  80. // S1 = PID<<1 | noack0 (matches real puck 00/02/04/06)
  81. rftx[1] = (uint8_t)((g_pid++ & 3) << 1);
  82. rftx[2] = 0xE1; // payload[0] marker
  83. // payload[1..5] proteus_uuid (LE, as bonded)
  84. memcpy(rftx + 3, rec + 0, 4);
  85. memcpy(rftx + 7, rec + 4, 4); // payload[5..9] ibex_uuid
  86. // payload[9] session channel: controller runs the session on this clean
  87. // channel (adopts buf[0xe]); discovery beacon still TXes on ch2
  88. rftx[11] = g_sessCh;
  89. // payload[13..17] session base (the per-device UNIQUE address)
  90. memcpy(rftx + 15, g_sessBase, 4);
  91. rftx[19] = g_sessPrefix; // payload[17] session prefix
  92. // TX address: discovery uses the shared "ibex" rendezvous; the session keepalive uses our unique address
  93. // (where the controller now listens). The advertised session params (above) are identical either way.
  94. const uint8_t *txBase = discovery ? g_rfBase : g_sessBase;
  95. uint8_t txPfx = discovery ? g_rfPrefix : g_sessPrefix;
  96. rfConfig(g_rfCh);
  97. rfSetAddr(txBase, txPfx);
  98. NRF_RADIO->PACKETPTR = (uint32_t)rftx;
  99. NRF_RADIO->SHORTS = RADIO_SHORTS_READY_START_Msk |
  100. RADIO_SHORTS_END_DISABLE_Msk;
  101. NRF_RADIO->EVENTS_DISABLED = 0;
  102. NRF_RADIO->TASKS_TXEN = 1;
  103. RWAIT_DISABLED();
  104. NRF_RADIO->EVENTS_DISABLED = 0;
  105. NRF_RADIO->PACKETPTR = (uint32_t)rfrx;
  106. rfrx[0] = 0;
  107. NRF_RADIO->SHORTS = RADIO_SHORTS_READY_START_Msk;
  108. NRF_RADIO->EVENTS_END = 0;
  109. NRF_RADIO->TASKS_RXEN = 1;
  110. // Discovery/pairing beacons listen for the controller's response (matters for RE/pairing); the connected
  111. // session keepalive expects NO response (the controller answers E3 polls, not the beacon), so don't burn
  112. // 800us of dead air per frame -- that was the bulk of the idle poll-rate deficit (40 beacons/s x slots).
  113. uint16_t bwin = discovery ? 800u : 150u;
  114. uint32_t t0 = micros();
  115. while (!NRF_RADIO->EVENTS_END && (micros() - t0) < bwin) {
  116. }
  117. if (NRF_RADIO->EVENTS_END) {
  118. // any reception = controller answered our frame
  119. NRF_RADIO->EVENTS_END = 0;
  120. g_rfRxCount++;
  121. bool crcok = NRF_RADIO->CRCSTATUS & 1;
  122. uint8_t len = rfrx[0];
  123. // non-blocking: don't stall the loop on CDC backpressure
  124. if (Serial.availableForWrite() > 90) {
  125. Serial.printf(
  126. "*** RESP#%lu ch%u crc%d rxmatch%lu len%u: ",
  127. (unsigned long)g_rfRxCount, g_rfCh, crcok,
  128. (unsigned long)NRF_RADIO->RXMATCH, len);
  129. for (uint8_t i = 0; i < (len < 40 ? len + 2 : 40); i++)
  130. Serial.printf("%02X ", rfrx[i]);
  131. Serial.println();
  132. }
  133. }
  134. NRF_RADIO->TASKS_DISABLE = 1;
  135. RWAIT_DISABLED();
  136. NRF_RADIO->EVENTS_DISABLED = 0;
  137. }
  138. void rfHopTo(uint8_t newCh)
  139. {
  140. if (g_connSlot < 0 || newCh == g_sessCh)
  141. return;
  142. uint8_t cur = g_sessCh, savedRfCh = g_rfCh;
  143. g_sessCh = newCh;
  144. // host frame now advertises newCh but is TXed on cur (session addr)
  145. g_rfCh = cur;
  146. for (int k = 0; k < 6; k++) {
  147. rfHostFrameOnce(g_connSlot, false);
  148. delayMicroseconds(700);
  149. }
  150. g_rfCh = savedRfCh; // poll + session beacon now run on g_sessCh=newCh
  151. }
  152. uint8_t rfConnTx(uint8_t ch, uint8_t s1, const uint8_t *payload, uint8_t plen,
  153. uint16_t rxWinUs)
  154. {
  155. // relays pass a tiny window (no reply expected); polls use g_rxWin
  156. uint16_t win = rxWinUs ? rxWinUs : g_rxWin;
  157. memset(rftx, 0, sizeof rftx);
  158. rftx[0] = plen; // LENGTH = payload byte count
  159. rftx[1] = s1; // S1 (type-specific)
  160. memcpy(rftx + 2, payload, plen); // payload[0]=type byte, then data/TLVs
  161. rfConfig(ch);
  162. // connected poll runs on this puck's UNIQUE session addr
  163. rfSetAddr(g_sessBase, g_sessPrefix);
  164. NRF_RADIO->PACKETPTR = (uint32_t)rftx;
  165. NRF_RADIO->SHORTS = RADIO_SHORTS_READY_START_Msk |
  166. RADIO_SHORTS_END_DISABLE_Msk;
  167. NRF_RADIO->EVENTS_DISABLED = 0;
  168. NRF_RADIO->TASKS_TXEN = 1;
  169. RWAIT_DISABLED();
  170. NRF_RADIO->EVENTS_DISABLED = 0;
  171. NRF_RADIO->PACKETPTR = (uint32_t)rfrx;
  172. rfrx[0] = 0;
  173. // RXEN->READY->START; catch the reply. ADDRESS->RSSISTART samples the reply's signal strength (read from
  174. // RSSISAMPLE below, surfaced to Steam via report 0x7B); DISABLED->RSSISTOP closes the measurement.
  175. NRF_RADIO->SHORTS = RADIO_SHORTS_READY_START_Msk |
  176. RADIO_SHORTS_ADDRESS_RSSISTART_Msk |
  177. RADIO_SHORTS_DISABLED_RSSISTOP_Msk;
  178. NRF_RADIO->EVENTS_END = 0;
  179. NRF_RADIO->TASKS_RXEN = 1;
  180. g_stPoll++;
  181. uint32_t t0 = micros();
  182. while (!NRF_RADIO->EVENTS_END && (micros() - t0) < win) {
  183. } // RX window (tunable 'r'; or relay override)
  184. uint8_t rxlen = 0;
  185. if (NRF_RADIO->EVENTS_END) {
  186. NRF_RADIO->EVENTS_END = 0;
  187. bool crcok = NRF_RADIO->CRCSTATUS & 1;
  188. rxlen = rfrx[0];
  189. // reply arrived but CRC failed -> RF quality (channel/interference)
  190. if (!crcok) {
  191. g_stCrc++;
  192. g_qosBad++;
  193. }
  194. // F1 input ~46B; 0x43-augmented ~66B -> allow up to MAXLEN(96)
  195. if (crcok && rxlen && rxlen <= 96) {
  196. // reply type byte (proven offset from captures)
  197. uint8_t rtype = rfrx[2];
  198. // Only OUR controller's replies (F-type: 0xF1 input / 0xF2 disconnect / 0xF3 status) mark the link
  199. // alive. Every OpenPuck shares the same RF address "ibex" + CRC config, and a puck transmits host-frame
  200. // beacons (0xE1) + polls (0xE2/E3/E7) -- all E-type. Without this gate, puck A receives a SECOND puck's
  201. // 0xE1 beacon (e.g. one just plugged into another computer), bumps g_connReplyMs, and the "new RF
  202. // connection" wake in rfLinkTask() fires -> the second puck spuriously wakes this sleeping host.
  203. if (rtype >= 0xF0) {
  204. // A reply after a long gap (or the first ever) = a (re)connect. Arm the haptic block + re-init HERE,
  205. // directly off the reply stream -- reliable even when hapticTask's 300ms link-up edge doesn't fire
  206. // (e.g. a power-cycled controller that reconnects without us cleanly seeing the link drop).
  207. if (g_connReplyMs == 0 ||
  208. (uint32_t)(millis() - g_connReplyMs) >
  209. 1500u)
  210. hapticOnReconnect();
  211. g_connRx++;
  212. // link alive -> loop() suppresses the redundant E1 beacon
  213. g_connReplyMs = millis();
  214. // |dBm| of this reply (started by the ADDRESS short)
  215. uint8_t rs =
  216. (uint8_t)(NRF_RADIO->RSSISAMPLE & 0x7F);
  217. // EWMA, ~8-sample horizon
  218. if (rs)
  219. g_linkRssi =
  220. g_linkRssi ?
  221. (uint8_t)((g_linkRssi *
  222. 7u +
  223. rs + 4u) /
  224. 8u) :
  225. rs;
  226. }
  227. if (rtype == 0xF1)
  228. g_stF1++;
  229. // controller disconnecting/powering off -> back off 2.5s
  230. if (rtype == 0xF2)
  231. g_connCooldown = millis();
  232. // F3 = controller status/version reply (reply to E7 handshake, byte[6]=version)
  233. if (rtype == 0xF3) {
  234. g_stF3++;
  235. g_connF3v = rfrx[6];
  236. if (g_connVerbose &&
  237. Serial.availableForWrite() > 40) {
  238. Serial.print(" F3 ");
  239. for (uint8_t i = 0;
  240. i <
  241. (rxlen + 2 < 32 ? rxlen + 2 : 32);
  242. i++)
  243. Serial.printf("%02X", rfrx[i]);
  244. Serial.println();
  245. }
  246. }
  247. bool isF1 = (rtype == 0xF1);
  248. if (isF1) {
  249. g_connF1++;
  250. // walk ALL type6 TLVs (= HID report 0x45); taking only [0] halves the rate. idx is INT,
  251. // not uint8_t: tlen 0xFE would make idx+=tlen+2 wrap mod-256 -> infinite loop -> USB hang.
  252. int idx = 3, end = rxlen + 2;
  253. const uint8_t *lastRep = nullptr;
  254. uint8_t lastTlen = 0;
  255. while (idx + 1 < end) {
  256. uint8_t tlen = rfrx[idx],
  257. ttype = rfrx[idx + 1];
  258. if (tlen == 0)
  259. break;
  260. // Only a FULL 0x45 report that fits entirely in rfrx: a short or late/garbled TLV must not let the
  261. // decode read past the RF buffer (corrupts rftx/RAM -> eventual crash).
  262. if (ttype == 6 && tlen >= 28 &&
  263. (size_t)(idx + 2) + tlen <=
  264. sizeof(rfrx) &&
  265. rfrx[idx + 2] == 0x45) {
  266. // report 0x45: [0x45][seq][buttons u32]...
  267. const uint8_t *rep =
  268. &rfrx[idx + 2];
  269. bool fresh =
  270. (rep[1] != g_lastSeq);
  271. // genuine new report vs stale poll-repeat
  272. if (fresh) {
  273. g_stNew++;
  274. g_lastSeq = rep[1];
  275. }
  276. uint32_t bb = btnsOf(rep);
  277. // USB remote wakeup on Steam button short press (down + up within 1 s). A long press likely means
  278. // the user is powering off the controller, so we ignore it.
  279. {
  280. static bool steamWasDown =
  281. false;
  282. static unsigned long
  283. steamDownMs = 0;
  284. if (fresh) {
  285. bool steamNow =
  286. (bb &
  287. TB_STEAM) !=
  288. 0;
  289. // rising edge: record press time
  290. if (steamNow &&
  291. !steamWasDown)
  292. steamDownMs =
  293. millis();
  294. // falling edge within 1 s -> short press -> wake
  295. if (!steamNow &&
  296. steamWasDown &&
  297. millis() - steamDownMs <
  298. 1000u &&
  299. USBDevice
  300. .suspended()) {
  301. USBDevice
  302. .remoteWakeup();
  303. ledWakePulse();
  304. // post-resume nudge (host needs real input to actually wake)
  305. if (g_active)
  306. g_active->wakeEvent();
  307. }
  308. steamWasDown =
  309. steamNow;
  310. }
  311. }
  312. // Decode the report into the shared g_in (one source, read by every IController).
  313. g_in.buttons = bb;
  314. // Global power-off chord: Steam + Y held 2 s -> shut the controller down (any mode). Detect on the raw
  315. // `bb` (pre-mask), time-based (poll rate varies), fires once per hold, re-arms only after release. While
  316. // held, mask Steam+Y out of g_in.buttons so the press doesn't leak to the host -- in EVERY mode except
  317. // regular Steam (mode 0 forwards the raw 0x45 to Steam, which owns the Steam button). Runs before
  318. // onReport45 below so push modes (Xbox) see the mask too; stream modes read g_in in task() (also masked).
  319. {
  320. static unsigned long
  321. offHoldMs = 0;
  322. static bool offFired =
  323. false;
  324. if ((bb & (TB_STEAM |
  325. TB_Y)) ==
  326. (TB_STEAM | TB_Y)) {
  327. if (offHoldMs ==
  328. 0)
  329. offHoldMs =
  330. millis();
  331. else if (
  332. !offFired &&
  333. (unsigned long)(millis() -
  334. offHoldMs) >=
  335. 2000u) {
  336. offFired =
  337. true;
  338. hapticSendShutdown();
  339. }
  340. if (g_usbMode !=
  341. MODE_STEAM) {
  342. // stream modes read g_in
  343. g_in.buttons &=
  344. ~(uint32_t)(TB_STEAM |
  345. TB_Y);
  346. // push modes read btnsOf(rep): TB_Y in rep[2],
  347. ((uint8_t *)
  348. rep)
  349. [2] &=
  350. ~(uint8_t)
  351. TB_Y;
  352. // TB_STEAM in rep[4]
  353. ((uint8_t *)
  354. rep)
  355. [4] &=
  356. ~(uint8_t)(TB_STEAM >>
  357. 16);
  358. }
  359. } else {
  360. offHoldMs = 0;
  361. offFired =
  362. false;
  363. }
  364. }
  365. g_in.lx =
  366. (int16_t)s16off(rep, 8);
  367. g_in.ly = (int16_t)s16off(rep,
  368. 10);
  369. g_in.rx = (int16_t)s16off(rep,
  370. 12);
  371. g_in.ry = (int16_t)s16off(rep,
  372. 14);
  373. g_in.lt =
  374. trigU8(u16off(rep, 4));
  375. // for the Switch digital-trigger threshold
  376. g_in.rt =
  377. trigU8(u16off(rep, 6));
  378. g_in.lpx = (int16_t)s16off(rep,
  379. 16);
  380. g_in.lpy = (int16_t)s16off(rep,
  381. 18);
  382. g_in.rpx = (int16_t)s16off(rep,
  383. 22);
  384. g_in.rpy = (int16_t)s16off(rep,
  385. 24);
  386. // IMU lives at report bytes 0x22..0x2D (rep[34..45]). Decode it ONLY when a FULL 46-byte report was
  387. // actually received -- bounded by `end` (the received length), NOT sizeof(rfrx). The outer gate is
  388. // tlen>=28 (enough for buttons/sticks/pads, which end at rep[27]), so a short 0x45 (button-only, or
  389. // one whose IMU tail was lost) still passes it; without this guard imuFrom45 would read STALE bytes
  390. // past the received data and clobber g_in's gyro/accel. On a short frame, hold the last good IMU.
  391. if (tlen >= 46 &&
  392. (size_t)(idx + 2) + 46 <=
  393. (size_t)end)
  394. imuFrom45(rep, &g_in.ax,
  395. &g_in.ay,
  396. &g_in.az,
  397. &g_in.gx,
  398. &g_in.gy,
  399. &g_in.gz);
  400. // Mode-switch chord (all 4 back + face): don't leak the face press to the host. g_in.buttons stays
  401. // intact so the chord detector still fires; per-mode builders mask the same bits while back-4 held.
  402. if ((bb & CHORD_BACK4) ==
  403. CHORD_BACK4)
  404. ((uint8_t *)rep)[2] &= ~(
  405. uint8_t)(TB_A |
  406. TB_B |
  407. TB_X |
  408. TB_Y);
  409. // Hand the report to the active controller. STREAM modes ignore it (they emit from task() reading
  410. // g_in); PUSH modes (Xbox, puck/lizard) build + send their host report here.
  411. if (g_active)
  412. g_active->onReport45(
  413. rep, fresh,
  414. tlen);
  415. lastRep = rep;
  416. lastTlen = tlen;
  417. } else if (ttype == 6 &&
  418. (size_t)(idx + 2) + tlen <=
  419. sizeof(rfrx) &&
  420. tlen >= 2 &&
  421. (rfrx[idx + 2] == 0x43 ||
  422. rfrx[idx + 2] == 0x44)) {
  423. // Controller STATUS reports (0x43 = periodic power/battery, ~every 2s; 0x44 = status event). The real
  424. // puck forwards these verbatim (onAuxReport) -- that's how Steam reads battery; also snapshot the
  425. // battery % for the WebUSB panel.
  426. // [rid][body...]
  427. const uint8_t *rep =
  428. &rfrx[idx + 2];
  429. // 0x43 body[1] (~0x5e=94) reads as battery % (sniff-derived)
  430. if (rep[0] == 0x43 && tlen >= 3)
  431. g_battery = rep[2];
  432. if (g_active)
  433. g_active->onAuxReport(
  434. rep[0], rep + 1,
  435. (uint8_t)(tlen -
  436. 1));
  437. }
  438. idx += tlen + 2;
  439. }
  440. // mode-switch chord (back4 + face): A=always Steam; B/X/Y=configurable (g_chordBtn[]). Debounced.
  441. {
  442. static uint8_t chWant = 0xFF, chCnt = 0;
  443. uint8_t want = 0xFF;
  444. if ((g_in.buttons & CHORD_BACK4) ==
  445. CHORD_BACK4) {
  446. if (g_in.buttons & TB_A)
  447. want = MODE_STEAM;
  448. else if (g_in.buttons & TB_B)
  449. want = g_chordBtn[0];
  450. else if (g_in.buttons & TB_X)
  451. want = g_chordBtn[1];
  452. else if (g_in.buttons & TB_Y)
  453. want = g_chordBtn[2];
  454. }
  455. if (want != 0xFF && want == chWant) {
  456. if (++chCnt >= 12 &&
  457. want != g_usbMode &&
  458. modeValid(want) &&
  459. !USBDevice.suspended()) {
  460. saveMode(want);
  461. delay(40);
  462. NVIC_SystemReset();
  463. }
  464. } else {
  465. chWant = want;
  466. chCnt = (want != 0xFF) ? 1 : 0;
  467. }
  468. }
  469. // compact stream for rf_controller_ui.py -- NON-BLOCKING: skip if CDC TX is backed up (a blocking
  470. // Serial.print stalls the RF+USB loop -> jaggy input). One line/frame using the last record.
  471. if (lastRep && !g_connVerbose &&
  472. Serial.availableForWrite() > 110 &&
  473. millis() - g_lastStream >= 4) {
  474. g_lastStream = millis();
  475. Serial.print("I45 ");
  476. for (uint8_t i = 0; i < lastTlen; i++)
  477. Serial.printf("%02X",
  478. lastRep[i]);
  479. Serial.println();
  480. }
  481. }
  482. if (g_connVerbose) {
  483. Serial.printf(
  484. "%s CRX#%lu txtype%02X ch%u len%u: ",
  485. isF1 ? "<<<F1" :
  486. (rtype == 0xF3 ? " F3" :
  487. " rx"),
  488. (unsigned long)g_connRx, payload[0], ch,
  489. rxlen);
  490. for (uint8_t i = 0;
  491. i < (rxlen + 2 <= 66 ? rxlen + 2 : 66);
  492. i++)
  493. Serial.printf("%02X", rfrx[i]);
  494. Serial.println();
  495. }
  496. } else
  497. rxlen = 0;
  498. // RX window expired with no packet at all
  499. } else {
  500. g_stNoRx++;
  501. g_qosBad++;
  502. }
  503. NRF_RADIO->TASKS_DISABLE = 1;
  504. RWAIT_DISABLED();
  505. NRF_RADIO->EVENTS_DISABLED = 0;
  506. return rxlen;
  507. }
  508. // Drive the connected-mode sequence one step per call. Camps on g_sessCh (the host-frame channel the
  509. // controller connected on); the host-frame beacon runs in parallel as keepalive.
  510. static void rfConnStep()
  511. {
  512. g_connSlot = -1;
  513. for (int s = 0; s < NSLOT; s++)
  514. if (g_slot[s].used) {
  515. g_connSlot = s;
  516. break;
  517. }
  518. // need a bonded slot (session established by host frame)
  519. if (g_connSlot < 0)
  520. return;
  521. uint8_t ch = g_sessCh;
  522. // announce HOST AWAKE: E7 00 00, a few times
  523. if (g_connSt == 0) {
  524. uint8_t p[3] = { 0xE7, 0x00, g_e7b };
  525. rfConnTx(ch, 0x01, p, 3);
  526. if (++g_connStep >= 4) {
  527. g_connSt = 1;
  528. g_connStep = 0;
  529. Serial.println(
  530. "# CONN: awake announced -> polling GET report 0x45");
  531. }
  532. // poll loop: E3 + GET report 0x45 every poll; re-assert awake periodically
  533. } else {
  534. // CONTROLLED CADENCE: poll ~every g_pollUs
  535. if ((uint32_t)(micros() - g_lastPollUs) < g_pollUs)
  536. return;
  537. // FIXED-RATE schedule: advance the deadline by exactly one interval (NOT reset-to-now, which would add
  538. // each cycle's ~1ms of poll work + loop jitter to the next interval -- the period drifts to ~5000us
  539. // instead of the 4000us target). The resync guard prevents a catch-up burst after a real stall.
  540. {
  541. uint32_t now = micros();
  542. static uint32_t lastFire = 0;
  543. // MEASURED actual period
  544. if (lastFire) {
  545. g_pollDtSum += (uint32_t)(now - lastFire);
  546. g_pollDtCnt++;
  547. }
  548. lastFire = now;
  549. g_lastPollUs += g_pollUs;
  550. // fell >1 interval behind -> resync
  551. if ((uint32_t)(now - g_lastPollUs) >= g_pollUs)
  552. g_lastPollUs = now;
  553. }
  554. if ((g_connPoll & 0x1F) == 0) {
  555. uint8_t pa[3] = { 0xE7, 0x00, g_e7b };
  556. rfConnTx(ch, 0x01, pa, 3);
  557. } // re-assert awake/version
  558. rfConnQueueHapticRelay();
  559. // Relay (if any) gets its OWN cycled PID, then the GET poll gets the NEXT one -- so they're always distinct
  560. // and the controller never dedups the GET as a retransmit of the relay (that was dropping ~half the replies
  561. // during haptics). Advancing g_e3pid even when no relay is pending just skips a PID value (harmless).
  562. {
  563. uint8_t rs1 = (uint8_t)((((g_e3pid++) & 3) << 1) | 1);
  564. rfConnFlushRelay(ch, rs1);
  565. }
  566. {
  567. // E3 + TLV [len=02][subtype=01 GET][id=0x45][param]
  568. uint8_t p[5] = { 0xE3, 0x02, 0x01, 0x45, g_getParam };
  569. // cycle PID (S1 1,3,5,7), NO_ACK=1
  570. // cycle PID (S1 0,2,4,6), NO_ACK=0
  571. // fixed (matches captured puck poll)
  572. uint8_t s1 =
  573. (g_e3mode == 1) ?
  574. (uint8_t)((((g_e3pid++) & 3) << 1) |
  575. 1) :
  576. (g_e3mode == 2) ?
  577. (uint8_t)(((g_e3pid++) & 3) << 1) :
  578. 0x07;
  579. uint8_t rx = rfConnTx(ch, s1, p, 5);
  580. if (rx)
  581. g_chF1[0]++;
  582. }
  583. g_connPoll++;
  584. }
  585. }
  586. void rfLinkTask()
  587. {
  588. // Host-frame beacon: sent continuously, INCLUDING while connected. The controller uses the periodic E1 (the
  589. // real puck's per-hop-cycle announce) to stay synced and keep answering polls at full rate; suppressing it
  590. // drops the reply rate from ~210/s to ~38/s. Paused only during the post-disconnect cooldown so a controller
  591. // that's powering off isn't immediately re-woken/reconnected.
  592. if (g_rfHost && millis() - g_connCooldown > 2500) {
  593. bool connNow =
  594. (g_connSlot >= 0 && millis() - g_connReplyMs < 300);
  595. // session keepalive on the clean channel: every loop while connecting (fast), every 25ms once connected
  596. // (every-loop beaconing also hammers the session ch and steals reply slots from the poll)
  597. if (millis() - g_lastSessBeacon >= (connNow ? 25u : 0u)) {
  598. g_lastSessBeacon = millis();
  599. g_rfCh = g_sessCh;
  600. for (int s = 0; s < NSLOT; s++)
  601. rfHostFrameOnce(s, false);
  602. }
  603. // discovery beacon on ch2 (where a searching controller looks): every loop when down, occasionally when up
  604. if (millis() - g_lastDisc >= (connNow ? 200u : 0u)) {
  605. g_lastDisc = millis();
  606. g_rfCh = 2;
  607. for (int s = 0; s < NSLOT; s++)
  608. rfHostFrameOnce(s, true);
  609. }
  610. }
  611. if (g_connOn && millis() - g_connCooldown > 2500) {
  612. rfConnStep();
  613. } // connected-mode: poll controller, read input
  614. {
  615. // remote wakeup on new RF controller connection
  616. static bool wasRfConn = false;
  617. bool nowRfConn =
  618. (g_connSlot >= 0 && millis() - g_connReplyMs < 300);
  619. if (nowRfConn && !wasRfConn && USBDevice.suspended()) {
  620. USBDevice.remoteWakeup();
  621. ledWakePulse();
  622. // post-resume nudge (host needs real input to actually wake)
  623. if (g_active)
  624. g_active->wakeEvent();
  625. }
  626. wasRfConn = nowRfConn;
  627. }
  628. // QoS: if the current channel is degrading (crcfail+noRx), hop to the next clean candidate (conservative).
  629. if (g_qos && g_connSlot >= 0 && millis() - g_qosCheckMs >= 600) {
  630. uint16_t bad = g_qosBad;
  631. g_qosBad = 0;
  632. g_qosCheckMs = millis();
  633. if (bad > 20 && millis() - g_qosLastHopMs > 2000) {
  634. for (int k = 0; k < (int)sizeof g_hopCand; k++) {
  635. g_hopIdx = (g_hopIdx + 1) % (sizeof g_hopCand);
  636. if (g_hopCand[g_hopIdx] != g_sessCh)
  637. break;
  638. }
  639. if (Serial.availableForWrite() > 60)
  640. Serial.printf(
  641. "# QoS: ch%u bad=%u -> hop ch%u\n",
  642. g_sessCh, bad, g_hopCand[g_hopIdx]);
  643. rfHopTo(g_hopCand[g_hopIdx]);
  644. g_qosLastHopMs = millis();
  645. }
  646. }
  647. if (g_connOn && millis() - g_stMs >= 1000) {
  648. g_f1ps = g_stF1;
  649. g_newps = g_stNew;
  650. g_pollsps = (uint16_t)g_stPoll;
  651. g_pollPeriodUs =
  652. g_pollDtCnt ? (uint16_t)(g_pollDtSum / g_pollDtCnt) : 0;
  653. g_pollDtSum = 0;
  654. g_pollDtCnt = 0;
  655. if (Serial.availableForWrite() > 70)
  656. Serial.printf(
  657. "# stat polls=%lu/s F1=%lu/s new=%lu/s F3=%lu/s(v%d) e7b=%u crcfail=%lu noRx=%lu slot=%d\n",
  658. (unsigned long)g_stPoll, (unsigned long)g_stF1,
  659. (unsigned long)g_stNew, (unsigned long)g_stF3,
  660. (int8_t)g_connF3v, g_e7b,
  661. (unsigned long)g_stCrc, (unsigned long)g_stNoRx,
  662. g_connSlot);
  663. g_stPoll = 0;
  664. g_stF1 = 0;
  665. g_stNew = 0;
  666. g_stF3 = 0;
  667. g_stCrc = 0;
  668. g_stNoRx = 0;
  669. g_chF1[0] = g_chF1[1] = g_chF1[2] = 0;
  670. g_stMs = millis();
  671. }
  672. }