rf_link.cpp 37 KB

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