webusb_config.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  1. #include "webusb_config.h"
  2. #include "config.h"
  3. #include "bonds.h"
  4. #include "rf_link.h"
  5. #include "haptics.h"
  6. #include "puck_hid.h"
  7. #include "triton.h" // g_in raw IMU (diagnostic readout)
  8. #include "lizard_map.h"
  9. #include "build_info.h"
  10. #include "fault_diag.h"
  11. #include "fw_update.h"
  12. #include "usb_tx.h"
  13. #include <Arduino.h>
  14. #include <string.h>
  15. Adafruit_USBD_WebUSB usb_web;
  16. // Panel-blob send is deferred to the usbd task: webusbPoll() (loop) just sets this, and webusbSofDrain()
  17. // (registered with usb_tx, runs from tud_sof_cb on the usbd task) does the actual write+flush. usb_web.flush()
  18. // goes through the same blocking osd_queue_send path as HID sends, so doing it from loop() could stall the
  19. // loop and trip the watchdog under load -- with the panel open during heavy use that was a live risk.
  20. static volatile bool g_blobRequest = false;
  21. // Bond export ("clone" backup): a 0x09 panel command asks for a one-shot dump of all four bond slots so the
  22. // browser can save them to a file and restore them onto a second puck. Like the status blob, the actual send
  23. // is deferred to the usbd task (webusbSofDrain) so usb_web.write()/flush() never block loop().
  24. static volatile bool g_bondExportRequest = false;
  25. // Firmware-update ack ([0xAB][5][status][nextOff u32 LE]). Like the blob it is written from the usbd task
  26. // (webusbSofDrain), but unlike the blob it is NEVER dropped -- the panel's transfer flow-control is strict
  27. // ping-pong on these acks, so an unsent ack just stays pending until the FIFO has room (the panel is
  28. // actively draining the IN pipe during an update, so that is at most a few SOFs).
  29. static volatile bool g_fwupAckPend = false;
  30. static volatile uint8_t g_fwupAckStatus = 0;
  31. static volatile uint32_t g_fwupAckOff = 0;
  32. static void fwupAckPost(uint8_t status)
  33. {
  34. g_fwupAckStatus = status;
  35. g_fwupAckOff = fwupNextOff();
  36. g_fwupAckPend = true;
  37. }
  38. // blob payload = [ver=10][mode][mDiv][mFric][qamMap(active)][abSwap(active)][back0..3(active)][connSlot(0xFF=none)][linkUp]
  39. // [f1ps_lo][f1ps_hi][pollU100][newps_lo][newps_hi][e7b][relayOp][relaySub][fwdNewOnly]
  40. // [qos][persistMode][chordBtn B][chordBtn X][chordBtn Y][pollsps_lo][pollsps_hi]
  41. // [loopPeriod_lo][loopPeriod_hi][loopWorstIdx][loopWorstUs_lo][loopWorstUs_hi]
  42. // [pollPeriod_lo][pollPeriod_hi][logEnabled][battery%][rssi|dBm|]
  43. // [gitDirty][buildId 12B ASCII, NUL-padded][rumbleScale][swPro120][swGyroScale10][raw accel ax ay az 3x s16 LE]
  44. // [bondedCount][slot0_up][slot0_batt][slot0_rssi]...[slot3_up][slot3_batt][slot3_rssi]
  45. // [v10: per-type cfg, 4x8B: ET_XBOX/SWITCH/DS4/DS5 each {back0..3, qam, abSwap, padHaptics, ledBright}]
  46. // [v11: resetReason(RR_* code)][resetReas raw u32 LE][rxWin/10 us][hapticBlockOn][hapticBlock s]
  47. // p[6]/p[7]/p[8..11] mirror the ACTIVE type (legacy display). v11 extends to 113 bytes (115 total incl header);
  48. // browser reads with transferIn(128) to span the two USB-FS packets.
  49. // [diag: crc/s][noRx/s][rfStallRecover count]
  50. // [v12: relayps(lo,hi)][clkLfSrc][clkHfSrc][usPerMs(lo,hi)][hangStage][curStage][stallMs/40][ringFault(lo,hi)][hangPC u32][hangLR u32][usbdStackFree(lo,hi)][loopStackFree(lo,hi)]
  51. // [v13: per-slot link stats, 4x9B from p[141]: {pollsps u16, f1ps u16, newps u16, crc/s u8,
  52. // noRx/s u8, relay/s u8} -- each controller's own rates (the v4 aggregates are their sums)]
  53. // [v14: p[177] landAll87 (verbatim-0x87-relay experiment toggle)]
  54. #define WB_PAYLEN 176
  55. // The blob send is drop-on-full (never blocks loop), so the vendor TX FIFO MUST be able to hold a whole blob
  56. // -- otherwise tud_vendor_write_available() never reaches the frame size and EVERY frame is dropped (blank
  57. // panel / stale mappings). The Makefile sets -DCFG_TUD_VENDOR_TX_BUFSIZE=256; guard it here so a build without
  58. // that flag (or a future blob that outgrows the FIFO) fails loudly instead of shipping a dead panel.
  59. static_assert(CFG_TUD_VENDOR_TX_BUFSIZE >= 2 + WB_PAYLEN,
  60. "CFG_TUD_VENDOR_TX_BUFSIZE too small to hold a WebUSB blob in one "
  61. "write -- build via `make build` (sets 256), or raise the flag.");
  62. static void webusbSendBlob()
  63. {
  64. if (!usb_web.connected())
  65. return;
  66. // "connected" = the most recent poll cycle's slot had a fresh F-reply (matches what the firmware
  67. // presents to Steam on 0x79). The blob is sent on the panel's poll, so the slot + up flag change
  68. // every ~250ms in normal use.
  69. int cs = (g_curSlot >= 0 && g_curSlot < NSLOT) ? g_curSlot : 0;
  70. bool up = (g_curSlot >= 0 && (millis() - g_connReplyMs[cs]) < 300);
  71. // STATIC, not stack: this runs on the usbd task, whose 800B stack (hardcoded USBD_STACK_SZ in the
  72. // Adafruit core, not growable from the sketch) is the prime overflow suspect behind the issue-72
  73. // watchdog hangs (hang boots report usbd stack free = 0). A 178B frame on that stack was the single
  74. // biggest consumer. Single-writer (SOF drain only), so a static buffer is race-free.
  75. static uint8_t p[2 + WB_PAYLEN];
  76. p[0] = 0xA5;
  77. p[1] = WB_PAYLEN;
  78. // protocol version (16 = +configurable lizard-map ops 0x11..0x15 / 0xAA frame, payload unchanged -- the
  79. // panel MUST see >=16 before it dares send 0x11, or a blocking readLizard() would hang forever against a
  80. // firmware that silently drops the unknown op; 15 = +staged firmware-update ops 0x20..0x24; 14 = +landAll87
  81. // toggle; 13 = +per-slot link stats; 12 = +relay rate + clock fingerprint; 11 = +reset cause; 10 =
  82. // +ledBright per type; 9 = +per-type cfg; 8 = +per-slot link status; 7 = +raw accel; 6 = +swPro120/gyroScale)
  83. p[2] = 16;
  84. p[3] = g_usbMode;
  85. p[4] = (uint8_t)g_mDiv;
  86. p[5] = (uint8_t)g_mFric;
  87. p[6] = g_qamMap;
  88. p[7] = g_abSwap;
  89. p[8] = g_back[0];
  90. p[9] = g_back[1];
  91. p[10] = g_back[2];
  92. p[11] = g_back[3];
  93. p[12] = (g_curSlot >= 0) ? (uint8_t)g_curSlot : 0xFF;
  94. p[13] = up ? 1 : 0;
  95. p[14] = (uint8_t)g_f1ps;
  96. p[15] = (uint8_t)(g_f1ps >> 8);
  97. p[16] = (uint8_t)(g_pollUs / 100);
  98. p[17] = (uint8_t)g_newps;
  99. p[18] = (uint8_t)(g_newps >> 8);
  100. p[19] = g_e7b;
  101. p[20] = g_relayOp;
  102. p[21] = g_relaySub;
  103. p[22] = g_fwdNewOnly;
  104. p[23] = g_qos;
  105. p[24] = g_persistMode ? 1 : 0;
  106. p[25] = g_chordBtn[0];
  107. p[26] = g_chordBtn[1];
  108. p[27] = g_chordBtn[2];
  109. p[28] = (uint8_t)g_pollsps;
  110. // poll TX rate (vs delivered/new -> starvation vs reply-loss)
  111. p[29] = (uint8_t)(g_pollsps >> 8);
  112. p[30] = (uint8_t)g_loopPeriodUs;
  113. p[31] = (uint8_t)(g_loopPeriodUs >> 8); // avg loop iteration time
  114. p[32] = g_loopWorst;
  115. p[33] = (uint8_t)g_loopWorstUs;
  116. p[34] = (uint8_t)(g_loopWorstUs >> 8);
  117. p[35] = (uint8_t)g_pollPeriodUs;
  118. p[36] = (uint8_t)(g_pollPeriodUs >>
  119. 8); // measured poll period (intended 4000)
  120. p[37] = OPK_LOG; // logging build? panel shows/hides its log UI
  121. p[38] = g_battery
  122. [g_curSlot >= 0 && g_curSlot < NSLOT ?
  123. g_curSlot :
  124. 0]; // controller battery % (report 0x43); 0=unknown
  125. p[39] = g_linkRssi[g_curSlot >= 0 && g_curSlot < NSLOT ?
  126. g_curSlot :
  127. 0]; // RAW signal strength |dBm| (0=no sample)
  128. // Release builds are tagged and easier to trace by semver; local/dev builds
  129. // still expose git hash when no version tag is available.
  130. p[40] = OPK_GIT_DIRTY ? 1 : 0;
  131. memset(&p[41], 0, 12); // 12B ASCII build ID, NUL-padded
  132. {
  133. const char *buildId = OPK_BUILD_VERSION;
  134. if (buildId[0] == '\0')
  135. buildId = OPK_GIT_HASH;
  136. for (uint8_t i = 0; i < 12 && buildId[i]; i++)
  137. p[41 + i] = (uint8_t)buildId[i];
  138. }
  139. p[53] = g_rumbleScale; // rumble strength % (protocol v5)
  140. // Switch Pro report rate 0=66/1=120/2=full (protocol v6)
  141. p[54] = g_swProRate;
  142. // Switch Pro gyro sensitivity x10 (protocol v6)
  143. p[55] = g_swGyroScale10;
  144. {
  145. // Read the ACTIVE slot's accel, not a hardcoded g_in[0]: a controller bonded to a non-zero
  146. // slot leaves g_in[0] zeroed, which made this readout (and lizard) look dead.
  147. int16_t a[3] = { g_in[cs].ax, g_in[cs].ay, g_in[cs].az };
  148. memcpy(&p[56], a, 6);
  149. } // raw accelerometer for scale diagnostics (protocol v7)
  150. // per-slot link status for all bond slots (protocol v8)
  151. p[62] = (uint8_t)bondedSlotCount();
  152. {
  153. unsigned long nowMs = millis();
  154. for (int s = 0; s < NSLOT; s++) {
  155. bool sup = g_slot[s].used && g_connReplyMs[s] != 0 &&
  156. (nowMs - g_connReplyMs[s]) < 300u;
  157. p[63 + s * 3] = sup ? 1 : 0;
  158. p[64 + s * 3] = g_battery[s];
  159. p[65 + s * 3] = g_linkRssi[s];
  160. }
  161. }
  162. // per-emulated-type button config (protocol v10): 4 types x 8 bytes from p[75]
  163. for (int et = 0; et < ET_COUNT; et++) {
  164. uint8_t *q = &p[75 + et * 8];
  165. q[0] = g_type[et].back[0];
  166. q[1] = g_type[et].back[1];
  167. q[2] = g_type[et].back[2];
  168. q[3] = g_type[et].back[3];
  169. q[4] = g_type[et].qamMap;
  170. q[5] = g_type[et].abSwap;
  171. q[6] = g_type[et].padHaptics;
  172. q[7] = g_type[et].ledBright;
  173. }
  174. // last-boot reset cause (protocol v11): why we (re)booted -- watchdog hang vs HardFault vs intentional
  175. // reboot vs power-on (issue #72). p[107] = RR_* code; p[108..111] = raw RESETREAS for the curious.
  176. p[107] = faultDiagReason();
  177. uint32_t rr = faultDiagResetReas();
  178. p[108] = (uint8_t)rr;
  179. p[109] = (uint8_t)(rr >> 8);
  180. p[110] = (uint8_t)(rr >> 16);
  181. p[111] = (uint8_t)(rr >> 24);
  182. // Connection tunables (protocol v11): poll RX window in 10us units, post-connect haptic block enable,
  183. // and block duration in seconds.
  184. p[112] = (uint8_t)(g_rxWin / 10);
  185. p[113] = g_hapticBlockOn;
  186. p[114] = (uint8_t)(g_hapticBlockMs / 1000);
  187. // RF wedge diagnostics (always populated, even when the link reads down): CRC-fail/s and no-reply/s,
  188. // capped at 255. With Polls/s this distinguishes poll-loop-stopped vs RX-dead vs corrupt-replies.
  189. p[115] = (uint8_t)(g_crcps > 255 ? 255 : g_crcps);
  190. p[116] = (uint8_t)(g_norxps > 255 ? 255 : g_norxps);
  191. p[117] = (uint8_t)(g_rfStallRecover > 255 ? 255 : g_rfStallRecover);
  192. // v12: relay-frame TX rate (separated from true poll cycles -- Polls/s now reads ~250, Relay/s exposes the
  193. // host output-report flood that steals reply windows), and the clock fingerprint for clone-board triage.
  194. p[118] = (uint8_t)g_relayps;
  195. p[119] = (uint8_t)(g_relayps >> 8);
  196. p[120] = clockLfSrc();
  197. p[121] = clockHfSrc();
  198. uint16_t upm = clockUsPerMs();
  199. p[122] = (uint8_t)upm;
  200. p[123] = (uint8_t)(upm >> 8);
  201. // last hang's loop stage (0xFF = last boot wasn't a watchdog/lockup hang, or GPREGRET2 didn't survive)
  202. p[124] = faultDiagHangStage();
  203. // LIVE hang localization: current loop stage + how long loop() has been stuck (40ms units, capped). When
  204. // loop() wedges these keep updating because the blob is sent from the SOF interrupt, not loop().
  205. p[125] = faultDiagCurStage();
  206. uint32_t sms = faultDiagStallMs();
  207. p[126] = (uint8_t)(sms / 40 > 255 ? 255 : sms / 40);
  208. // relay-ring fault count: non-zero = we caught+recovered a desynced/corrupt ring that would otherwise be an
  209. // invisible IRQ-off watchdog hang. A climbing count points at the haptic relay path / memory corruption.
  210. p[127] = (uint8_t)g_ringFault;
  211. p[128] = (uint8_t)(g_ringFault >> 8);
  212. // PC/LR of the stuck code captured by the WDT pre-reset ISR on the last watchdog hang (0 = none captured =
  213. // the hang hard-masked interrupts). Map with addr2line on the .elf to name the function.
  214. uint32_t hpc = faultDiagHangPC(), hlr = faultDiagHangLR();
  215. p[129] = (uint8_t)hpc;
  216. p[130] = (uint8_t)(hpc >> 8);
  217. p[131] = (uint8_t)(hpc >> 16);
  218. p[132] = (uint8_t)(hpc >> 24);
  219. p[133] = (uint8_t)hlr;
  220. p[134] = (uint8_t)(hlr >> 8);
  221. p[135] = (uint8_t)(hlr >> 16);
  222. p[136] = (uint8_t)(hlr >> 24);
  223. // least-ever free stack (words) on the usbd task (800B total) and loop task -- usbd trending to 0 confirms
  224. // the overflow. words, not bytes.
  225. uint16_t usbdFree = faultDiagUsbdStackFree(),
  226. loopFree = faultDiagLoopStackFree();
  227. p[137] = (uint8_t)usbdFree;
  228. p[138] = (uint8_t)(usbdFree >> 8);
  229. p[139] = (uint8_t)loopFree;
  230. p[140] = (uint8_t)(loopFree >> 8);
  231. // v13: per-slot link stats -- each controller's own poll/reply/error rates, so the panel's per-slot tabs
  232. // no longer conflate every controller into the aggregate numbers above.
  233. for (int s = 0; s < NSLOT; s++) {
  234. uint8_t *q = &p[141 + s * 9];
  235. q[0] = (uint8_t)g_slotPollsps[s];
  236. q[1] = (uint8_t)(g_slotPollsps[s] >> 8);
  237. q[2] = (uint8_t)g_slotF1ps[s];
  238. q[3] = (uint8_t)(g_slotF1ps[s] >> 8);
  239. q[4] = (uint8_t)g_slotNewps[s];
  240. q[5] = (uint8_t)(g_slotNewps[s] >> 8);
  241. q[6] = g_slotCrcps[s];
  242. q[7] = g_slotNoRxps[s];
  243. q[8] = g_slotRelayps[s];
  244. }
  245. // v14: verbatim-0x87-relay experiment toggle (panel reflects + toggles it)
  246. p[177] = g_landAll87;
  247. // CRITICAL: usb_web.write() SPINS (`while (remain && _connected) yield();`) until the IN FIFO drains or the
  248. // panel disconnects. If the panel holds the WebUSB interface open but stops reading its IN endpoint -- a
  249. // backgrounded tab, or the host briefly not servicing transferIn under load -- the FIFO never empties and
  250. // that spin hangs loop() until the ~8s watchdog resets us (RESETREAS=watchdog/hang). This is the ONE
  251. // cross-task tud_ call the marshalling refactor left able to block loop() (HID goes through the drop-oldest
  252. // ring; this didn't). So DROP the blob whenever the FIFO can't take it whole -- a status panel missing an
  253. // occasional frame is invisible, and loop() can never stall here again. (Matches the closing-the-panel
  254. // "fix": that just flips _connected=false to break the same spin.)
  255. if (tud_vendor_write_available() >= sizeof p) {
  256. usb_web.write(p, sizeof p);
  257. usb_web.flush();
  258. }
  259. }
  260. // Bond export frame (panel "Export config to file"). One self-describing frame carrying all four bond slots so
  261. // the browser can clone a puck onto another without re-pairing:
  262. // [0xA7][len][ver=1][usedMask][slot0 rec 24]...[slot3 rec 24] (len = 2 + NSLOT*24 = 98)
  263. // usedMask bit s = slot s bonded. The session RF address is NOT exported: each puck re-derives it from the bond
  264. // UUID + its own FICR DEVICEID at boot, and the bonded controller relearns it from the E1 host beacon on every
  265. // reconnect (rf_link.cpp) -- so the 24-byte record is the whole portable identity. 98+2 < transferIn(128) and
  266. // < CFG_TUD_VENDOR_TX_BUFSIZE (256), so it sends whole in one drop-on-full write like the status blob.
  267. #define WB_BOND_PAYLEN (2 + NSLOT * 24)
  268. static void webusbSendBondExport()
  269. {
  270. if (!usb_web.connected())
  271. return;
  272. // static for the same reason as the status blob: keep the 100B frame off the 800B usbd-task stack.
  273. static uint8_t p[2 + WB_BOND_PAYLEN];
  274. p[0] = 0xA7;
  275. p[1] = WB_BOND_PAYLEN;
  276. p[2] = 1; // format version
  277. uint8_t mask = 0;
  278. for (int s = 0; s < NSLOT; s++) {
  279. if (g_slot[s].used)
  280. mask |= (uint8_t)(1u << s);
  281. memcpy(&p[4 + s * 24], g_slot[s].rec, 24);
  282. }
  283. p[3] = mask;
  284. // Same anti-hang rule as the status blob: drop the frame if the FIFO can't take it whole, never spin.
  285. if (tud_vendor_write_available() >= sizeof p) {
  286. usb_web.write(p, sizeof p);
  287. usb_web.flush();
  288. }
  289. }
  290. // Stream the saved (pre-reset) flight-recorder trail to the panel as 0xA8 frames. Always compiled -- the
  291. // recorder is not OPK_LOG-gated (field hangs happen on release builds too). Frame layout mirrors the 0xA6
  292. // capture drain so the same drop-on-full discipline applies (a write only issues when the FIFO can take the
  293. // whole frame -> usb_web.write() never spins -> loop() never stalls here):
  294. // header: [0xA8][29][T=2][count u16][total u16][loopPerSec u16][stallMs][curStage][usbdStk u16][loopStk u16]
  295. // [heapUsed u32][pollsps u16][relayps u16][crc u8][norx u8][heal u16][ringF u16]
  296. // entry: [0xA8][9][T=1][dtMs u32][evt][stage][arg u16] (dtMs = ms before the last recorded crumb)
  297. // end: [0xA8][1][T=0]
  298. // The panel sends 0x10 with buf[1]=1 to (re)start (emits the header + rewinds the cursor), then 0x10 buf[1]=0
  299. // repeatedly; each call streams a budgeted chunk and the final call appends the end frame.
  300. #define WB_FLIGHT_HDR 29
  301. // RAII boost: these drains run from loop() and push many usb_web.write()s per call -- each enters TinyUSB's
  302. // dcd DMA claim window (the issue-72 livelock; see usb_tx.cpp), so the whole burst runs boosted.
  303. struct TxBoostScope {
  304. TxBoostScope()
  305. {
  306. usbTxBoost();
  307. }
  308. ~TxBoostScope()
  309. {
  310. usbTxUnboost();
  311. }
  312. };
  313. static void webusbDrainFlight(bool restart)
  314. {
  315. if (!usb_web.connected())
  316. return;
  317. TxBoostScope boost;
  318. if (restart) {
  319. faultDiagFlightDrainReset();
  320. if (tud_vendor_write_available() >= 2 + WB_FLIGHT_HDR) {
  321. struct FaultFlightVitals v;
  322. bool have = faultDiagFlightVitals(&v);
  323. if (!have)
  324. memset(&v, 0, sizeof v);
  325. uint16_t cnt = faultDiagFlightCount();
  326. uint16_t tot = faultDiagFlightTotal();
  327. uint8_t f[2 + WB_FLIGHT_HDR];
  328. f[0] = 0xA8;
  329. f[1] = WB_FLIGHT_HDR;
  330. f[2] = 2; // header type
  331. f[3] = (uint8_t)cnt;
  332. f[4] = (uint8_t)(cnt >> 8);
  333. f[5] = (uint8_t)tot;
  334. f[6] = (uint8_t)(tot >> 8);
  335. f[7] = (uint8_t)v.loopPerSec;
  336. f[8] = (uint8_t)(v.loopPerSec >> 8);
  337. f[9] = v.stallMs;
  338. f[10] = v.curStage;
  339. f[11] = (uint8_t)v.usbdStkFree;
  340. f[12] = (uint8_t)(v.usbdStkFree >> 8);
  341. f[13] = (uint8_t)v.loopStkFree;
  342. f[14] = (uint8_t)(v.loopStkFree >> 8);
  343. f[15] = (uint8_t)v.heapUsed;
  344. f[16] = (uint8_t)(v.heapUsed >> 8);
  345. f[17] = (uint8_t)(v.heapUsed >> 16);
  346. f[18] = (uint8_t)(v.heapUsed >> 24);
  347. f[19] = (uint8_t)v.pollsps;
  348. f[20] = (uint8_t)(v.pollsps >> 8);
  349. f[21] = (uint8_t)v.relayps;
  350. f[22] = (uint8_t)(v.relayps >> 8);
  351. f[23] = (uint8_t)(v.crcps > 255 ? 255 : v.crcps);
  352. f[24] = (uint8_t)(v.norxps > 255 ? 255 : v.norxps);
  353. f[25] = (uint8_t)v.rfHeal;
  354. f[26] = (uint8_t)(v.rfHeal >> 8);
  355. f[27] = (uint8_t)v.ringFault;
  356. f[28] = (uint8_t)(v.ringFault >> 8);
  357. f[29] = (uint8_t)0; // reserved / pad to header len
  358. f[30] = (uint8_t)0;
  359. usb_web.write(f, sizeof f);
  360. usb_web.flush();
  361. }
  362. }
  363. uint32_t dt = 0;
  364. uint8_t evt = 0, stage = 0;
  365. uint16_t arg = 0;
  366. uint16_t budget = 64;
  367. bool done = false;
  368. while (budget--) {
  369. if (tud_vendor_write_available() < 2 + 9)
  370. break; // FIFO full -> resume on the panel's next 0x10 poll
  371. if (!faultDiagFlightPull(&dt, &evt, &stage, &arg)) {
  372. done = true;
  373. break;
  374. }
  375. uint8_t f[2 + 9];
  376. f[0] = 0xA8;
  377. f[1] = 9;
  378. f[2] = 1; // entry type
  379. f[3] = (uint8_t)dt;
  380. f[4] = (uint8_t)(dt >> 8);
  381. f[5] = (uint8_t)(dt >> 16);
  382. f[6] = (uint8_t)(dt >> 24);
  383. f[7] = evt;
  384. f[8] = stage;
  385. f[9] = (uint8_t)arg;
  386. f[10] = (uint8_t)(arg >> 8);
  387. usb_web.write(f, sizeof f);
  388. usb_web.flush();
  389. }
  390. if (done && tud_vendor_write_available() >= 3) {
  391. uint8_t e[3] = { 0xA8, 1, 0 };
  392. usb_web.write(e, 3);
  393. usb_web.flush();
  394. }
  395. }
  396. // Runs on the usbd task (registered via usbTxRegisterDrain -> tud_sof_cb). Sends the blob if loop() asked for
  397. // one. Keeps every usb_web write/flush off the loop task so it can't block on the device event queue.
  398. static void webusbSofDrain(void)
  399. {
  400. // If loop() has stopped beating, it's wedged -- keep pushing the blob (which carries the live stuck stage)
  401. // so the panel shows WHERE it hung during the ~8s before the watchdog fires. This runs on the SOF IRQ, so
  402. // it works even though loop() is dead. drop-on-full in webusbSendBlob keeps it from ever blocking.
  403. if (faultDiagStallMs() > 300)
  404. g_blobRequest = true;
  405. // firmware-update ack first: the panel is blocked on it (ping-pong), and it must never be dropped --
  406. // retry every SOF until the FIFO has room.
  407. if (g_fwupAckPend && tud_vendor_write_available() >= 7) {
  408. uint8_t f[7] = { 0xAB,
  409. 5,
  410. g_fwupAckStatus,
  411. (uint8_t)(g_fwupAckOff),
  412. (uint8_t)(g_fwupAckOff >> 8),
  413. (uint8_t)(g_fwupAckOff >> 16),
  414. (uint8_t)(g_fwupAckOff >> 24) };
  415. usb_web.write(f, sizeof f);
  416. usb_web.flush();
  417. g_fwupAckPend = false;
  418. }
  419. if (g_blobRequest) {
  420. g_blobRequest = false;
  421. webusbSendBlob();
  422. }
  423. if (g_bondExportRequest) {
  424. g_bondExportRequest = false;
  425. webusbSendBondExport();
  426. }
  427. }
  428. // ---- live wedge reporter (0xA9) --------------------------------------------------------------------------
  429. // THE one channel that survives a loop() wedge on boards that wipe .noinit/GPREGRET across the watchdog reset
  430. // (Teyleten): tud_sof_cb runs on the usbd task, which is HIGHER priority than the loop() task, so the USB
  431. // stack keeps dispatching it even while loop() is wedged (spinning or blocked) -- as long as interrupts aren't
  432. // hard-masked (PRIMASK). When loop() has been stuck a while, emit a tiny frame carrying the stuck loop stage so
  433. // the panel can log WHERE it hung, live, during the ~8s before the watchdog fires. Zero traffic when healthy
  434. // (returns immediately unless stalled); rate-limited; drop-on-full so it never spins the usbd task.
  435. // frame: [0xA9][3][stuck stage][stallMs lo][stallMs hi]
  436. extern "C" void tud_sof_cb(uint32_t frame_count)
  437. {
  438. (void)frame_count;
  439. uint32_t stall = faultDiagStallMs();
  440. if (stall <
  441. 1000) // loop() healthy -> nothing to report (the common case: near-zero overhead)
  442. return;
  443. static uint32_t lastMs = 0;
  444. uint32_t now = millis();
  445. if ((uint32_t)(now - lastMs) < 200) // ~5 Hz cap
  446. return;
  447. lastMs = now;
  448. if (!usb_web.connected())
  449. return;
  450. uint8_t f[2 + 3];
  451. f[0] = 0xA9;
  452. f[1] = 3;
  453. f[2] = faultDiagCurStage();
  454. uint16_t s = (stall > 0xFFFFu) ? 0xFFFFu : (uint16_t)stall;
  455. f[3] = (uint8_t)s;
  456. f[4] = (uint8_t)(s >> 8);
  457. if (tud_vendor_write_available() >= sizeof f) {
  458. usb_web.write(f, sizeof f);
  459. usb_web.flush();
  460. }
  461. }
  462. // Register the SOF drain. Call once from setup() (harmless even if WebUSB isn't enumerated -- webusbSendBlob
  463. // no-ops while disconnected, and g_blobRequest is only ever set by panel traffic, which needs a connection).
  464. void webusbInit(void)
  465. {
  466. usbTxRegisterDrain(webusbSofDrain);
  467. // Enable SOF-callback dispatch so tud_sof_cb() above fires -- our only live view into a loop() wedge on
  468. // boards whose bootloader wipes retained RAM. Cheap: the callback no-ops unless loop() is already stalled.
  469. tud_sof_cb_enable(true);
  470. }
  471. // Send the whole lizard binding table as one 0xAA frame so the panel can edit it:
  472. // [0xAA][count][ per binding (16B): outType, outData[0..6], trigMask LE(4), holdMask LE(4) ]
  473. // Total = 2 + count*16 (max 2 + 32*16 = 514). The panel reads byte[1]=count and accumulates
  474. // transferIn packets until it has the full frame.
  475. static void webusbSendLizard()
  476. {
  477. if (!usb_web.connected())
  478. return;
  479. uint8_t count = g_lizardMap.count;
  480. if (count > LZ_MAX_BINDINGS)
  481. count = LZ_MAX_BINDINGS;
  482. // static (not stack): 514 B is large for the USB task stack, and webusbPoll is single-threaded.
  483. static uint8_t f[2 + LZ_MAX_BINDINGS * 16];
  484. // 0xAA, NOT 0xA7/0xA8: main claimed 0xA7 (bond export) and 0xA8 (flight recorder), plus 0xA9 (wedge
  485. // reporter) and 0xAB (fwup ack) -- 0xAA is the free device->host marker for the lizard map.
  486. f[0] = 0xAA;
  487. f[1] = count;
  488. for (uint8_t i = 0; i < count; i++) {
  489. const LizardBinding &b = g_lizardMap.bindings[i];
  490. uint8_t *q = &f[2 + i * 16];
  491. q[0] = b.outType;
  492. for (int k = 0; k < 7; k++)
  493. q[1 + k] = b.outData[k];
  494. q[8] = (uint8_t)b.trigMask;
  495. q[9] = (uint8_t)(b.trigMask >> 8);
  496. q[10] = (uint8_t)(b.trigMask >> 16);
  497. q[11] = (uint8_t)(b.trigMask >> 24);
  498. q[12] = (uint8_t)b.holdMask;
  499. q[13] = (uint8_t)(b.holdMask >> 8);
  500. q[14] = (uint8_t)(b.holdMask >> 16);
  501. q[15] = (uint8_t)(b.holdMask >> 24);
  502. }
  503. usb_web.write(f, (uint16_t)(2 + count * 16));
  504. usb_web.flush();
  505. }
  506. #if OPK_LOG
  507. // Stream the capture ring (haptics / relayed host commands) to the panel as 0xA6 frames. Frame formats:
  508. // entry: [0xA6][L][T=1][age u32 LE][slot][rid][n][bytes n] (L = 8 + n)
  509. // end: [0xA6][1][T=0]
  510. static void webusbCapFrame(uint32_t ms, uint8_t slot, uint8_t rid, uint8_t nb,
  511. const uint8_t *b)
  512. {
  513. if (nb > 16)
  514. nb = 16;
  515. uint8_t f[2 + 9 + 16];
  516. uint8_t L = (uint8_t)(8 + nb);
  517. f[0] = 0xA6;
  518. f[1] = L;
  519. f[2] = 1;
  520. f[3] = (uint8_t)ms;
  521. f[4] = (uint8_t)(ms >> 8);
  522. f[5] = (uint8_t)(ms >> 16);
  523. f[6] = (uint8_t)(ms >> 24); // absolute log time
  524. f[7] = slot;
  525. f[8] = rid;
  526. f[9] = nb;
  527. memcpy(f + 10, b, nb);
  528. usb_web.write(f, (uint16_t)(2 + L));
  529. usb_web.flush();
  530. }
  531. static void webusbCapEnd()
  532. {
  533. uint8_t e[3] = { 0xA6, 1, 0 };
  534. usb_web.write(e, 3);
  535. usb_web.flush();
  536. }
  537. // 0x06: drain entries since the last drain (or since the 0x05 start/rewind). The panel polls this on a
  538. // timer and accumulates, so a dump-from-boot of the whole ring streams over many polls without blocking the
  539. // loop. A per-call budget bounds how long one poll spends here.
  540. static void webusbDrainCapture()
  541. {
  542. if (!usb_web.connected())
  543. return;
  544. TxBoostScope
  545. boost; // capture streams at flood rate through the same dcd DMA window
  546. uint32_t ms = 0;
  547. uint8_t slot = 0, rid = 0, nb = 0, b[16];
  548. uint16_t budget = 128;
  549. // Same anti-hang rule as the blob: webusbCapFrame's usb_web.write() spins until the FIFO drains, so stop
  550. // pulling the moment the FIFO can't hold a max-size frame (2+9+16=27 B) -- the panel resumes the drain on
  551. // its next 0x06 poll. Never let a backed-up panel hang loop() here.
  552. while (budget-- && tud_vendor_write_available() >= 27 &&
  553. hapLogPull(&ms, &slot, &rid, &nb, b))
  554. webusbCapFrame(ms, slot, rid, nb, b);
  555. if (tud_vendor_write_available() >= 3)
  556. webusbCapEnd();
  557. }
  558. #endif // OPK_LOG
  559. void webusbPoll()
  560. {
  561. // 160 B holds the largest command: a firmware-update data chunk 0x21 = [op][off u32][len][<=128 data]
  562. // = 134 B (spans USB-FS packets; the byte-wise accumulation below reassembles it). Next-largest are the
  563. // 0x0D bond-slot write (27 B) and the 0x12 lizard set-binding (18 B); everything else is <= 9 B.
  564. static uint8_t buf[160];
  565. static uint8_t n = 0;
  566. while (usb_web.available()) {
  567. int c = usb_web.read();
  568. if (c < 0)
  569. break;
  570. if (n < sizeof buf)
  571. buf[n++] = (uint8_t)c;
  572. // process complete commands from the front of buf
  573. for (;;) {
  574. if (n == 0)
  575. break;
  576. uint8_t op = buf[0];
  577. if ((op < 0x01 || op > 0x15) &&
  578. (op < 0x20 || op > 0x24)) { // resync: drop one byte
  579. memmove(buf, buf + 1, --n);
  580. continue;
  581. }
  582. // 0x21 (fwup data) carries its own length at [5]; sanity-gate it BEFORE trusting it as a
  583. // command length so a corrupt byte can only cost a one-byte resync, never a stuck parser.
  584. if (op == 0x21 && n >= 6) {
  585. uint8_t dl = buf[5];
  586. if (dl == 0 || dl > 128 || (dl & 3)) {
  587. memmove(buf, buf + 1, --n);
  588. continue;
  589. }
  590. }
  591. // Command length (fixed per opcode). 0x0D = write-one-bond-slot (27 B); 0x12 = set-one-lizard-
  592. // binding (18 B); 0x05/0x0E/0x0F/0x10/0x13 carry one value byte; 0x02 a field+value; 0x0A a
  593. // 3-byte magic. Firmware update: 0x20 begin [size u32][crc32 u32], 0x21 data (6 B header +
  594. // payload), 0x22/0x23/0x24 bare. (0x11/0x14/0x15 are bare lizard opcodes -> default 1.)
  595. uint8_t need =
  596. (op == 0x0D) ? 27 :
  597. (op == 0x12) ? 18 :
  598. (op == 0x02) ? 3 :
  599. (op == 0x03 || op == 0x05 || op == 0x0E ||
  600. op == 0x0F || op == 0x10 || op == 0x13) ?
  601. 2 :
  602. (op == 0x0A) ? 4 :
  603. (op == 0x20) ? 9 :
  604. (op == 0x21) ? (uint8_t)(6 + (n >= 6 ? buf[5] :
  605. 0)) :
  606. 1;
  607. if (n < need)
  608. break; // wait for more bytes
  609. if (op == 0x01) {
  610. g_blobRequest =
  611. true; // sent from the usbd task (webusbSofDrain)
  612. }
  613. // 0x09: export all bond slots (clone backup). One 0xA7 frame, sent from the usbd task.
  614. else if (op == 0x09) {
  615. g_bondExportRequest = true;
  616. }
  617. // 0x0F: stability test on/off. Puck->controller haptics do NOT reset the controller's own
  618. // user-input idle auto-off (we already poll it every 4ms without keeping it awake), so instead
  619. // signal host-awake: enable the E7 announce (0xE7 00 00 = host-awake vs 00 01 = suspended, per
  620. // the RE) so the controller is told the host is active and (hopefully) doesn't power-save. The
  621. // 10s buzz stays -- it also exercises the haptic-relay path that correlates with the hang.
  622. else if (op == 0x0F) {
  623. g_stabTest = (buf[1] != 0);
  624. g_e7b = 0; // byte2=0 => host-awake
  625. g_e7announce = g_stabTest;
  626. }
  627. // 0x10: stream the saved flight-recorder trail (0xA8 frames). buf[1]=1 restarts (header + rewind),
  628. // buf[1]=0 continues the drain. Drained straight from loop context like the 0x06 capture drain --
  629. // webusbDrainFlight is drop-on-full so it never blocks. Always available (recorder isn't OPK_LOG).
  630. else if (op == 0x10) {
  631. webusbDrainFlight(buf[1] != 0);
  632. }
  633. #if OPK_LOG
  634. // rewind drain: buf[1]=1 from boot (whole ring), 0 from now
  635. else if (op == 0x05) {
  636. hapLogResetDrain(buf[1] != 0);
  637. } else if (op == 0x06) {
  638. webusbDrainCapture();
  639. } // drain entries since the rewind (panel polls this)
  640. #endif
  641. // clear a stuck/latched haptic buzz on the controller
  642. else if (op == 0x07) {
  643. hapticReinit();
  644. }
  645. // trigger controller power-off (same path Steam 0x9F / host-suspend use)
  646. else if (op == 0x08) {
  647. hapticSendShutdown();
  648. }
  649. // factory wipe: erase cfg.bin + bonds.bin, reboot to clean defaults.
  650. // Guarded by a 3-byte magic ("ERS") so a stray/corrupt byte can never trigger it.
  651. // Irreversible -- the controller must be re-paired afterwards.
  652. else if (op == 0x0A) {
  653. if (buf[1] == 0x45 && buf[2] == 0x52 &&
  654. buf[3] == 0x53) {
  655. usb_web.flush();
  656. factoryErase();
  657. delay(40);
  658. faultDiagArmIntentionalReset();
  659. NVIC_SystemReset();
  660. }
  661. // reboot into serial DFU (adafruit-nrfutil)
  662. } else if (op == 0x0B) {
  663. usb_web.flush();
  664. delay(40);
  665. faultDiagArmIntentionalReset();
  666. enterSerialDfu();
  667. // reboot into UF2 bootloader (USB mass storage)
  668. } else if (op == 0x0C) {
  669. usb_web.flush();
  670. delay(40);
  671. faultDiagArmIntentionalReset();
  672. enterUf2Dfu();
  673. // 0x0D: write ONE bond slot into RAM -- the "clone onto this puck" side of Export/Import.
  674. // [0x0D][slot][used][24 rec]. used=0 (or an empty record) clears the slot. The panel sends
  675. // one of these per slot, then a 0x0E to persist + reboot. Kept to a single small command
  676. // (<=27 B) so it never spans a USB packet, and acked with a status blob so the panel's
  677. // read-after-write keeps the OUT pipe flowing (same shape as the proven 0x02 setters).
  678. } else if (op == 0x0D) {
  679. uint8_t slot = buf[1], used = buf[2];
  680. if (slot < NSLOT) {
  681. if (used && !recEmpty(buf + 3)) {
  682. memcpy(g_slot[slot].rec,
  683. buf + 3, 24);
  684. g_slot[slot].used = true;
  685. } else {
  686. memset(g_slot[slot].rec, 0, 24);
  687. g_slot[slot].used = false;
  688. }
  689. }
  690. g_blobRequest = true; // ack
  691. // 0x0E: commit an import -- persist the bond slots written by 0x0D, optionally apply a USB
  692. // mode ([0x0E][mode]; 0xFF = leave unchanged), then reboot so the RF session addresses
  693. // regenerate from the new bond UUIDs.
  694. } else if (op == 0x0E) {
  695. uint8_t mode = buf[1];
  696. saveBonds();
  697. if (modeValid(mode))
  698. saveMode(mode);
  699. usb_web.flush();
  700. delay(40);
  701. faultDiagArmIntentionalReset();
  702. NVIC_SystemReset();
  703. // ---- lizard (desktop) binding map editor ----
  704. // Renumbered to 0x11..0x15 on the merge with main: main already owns 0x0D (bond-slot
  705. // write), 0x0E (import commit), 0x0F (stability test) and 0x10 (flight-recorder drain),
  706. // which the pre-merge branch had collided with. The panel JS uses the same 0x11..0x15.
  707. // 0x11: dump the current map as a 0xAA frame.
  708. } else if (op == 0x11) {
  709. webusbSendLizard();
  710. // 0x13 [count]: BEGIN a map edit -- set the binding count (clamped). The
  711. // panel then sends one 0x12 per binding (0..count-1) and a 0x14 to persist.
  712. } else if (op == 0x13) {
  713. g_lizardMap.count =
  714. (buf[1] <= LZ_MAX_BINDINGS) ?
  715. buf[1] :
  716. LZ_MAX_BINDINGS;
  717. // 0x12 [idx][outType][od0..6][trig LE4][hold LE4]: set one binding.
  718. } else if (op == 0x12) {
  719. uint8_t idx = buf[1];
  720. if (idx < LZ_MAX_BINDINGS) {
  721. LizardBinding &b =
  722. g_lizardMap.bindings[idx];
  723. b.outType = buf[2];
  724. for (int k = 0; k < 7; k++)
  725. b.outData[k] = buf[3 + k];
  726. b.trigMask = (uint32_t)buf[10] |
  727. ((uint32_t)buf[11] << 8) |
  728. ((uint32_t)buf[12] << 16) |
  729. ((uint32_t)buf[13] << 24);
  730. b.holdMask = (uint32_t)buf[14] |
  731. ((uint32_t)buf[15] << 8) |
  732. ((uint32_t)buf[16] << 16) |
  733. ((uint32_t)buf[17] << 24);
  734. }
  735. // 0x14: COMMIT the edited map to flash and echo it back.
  736. } else if (op == 0x14) {
  737. saveLizardMap();
  738. webusbSendLizard();
  739. // 0x15: reset the map to the built-in defaults, persist, echo back.
  740. } else if (op == 0x15) {
  741. defaultLizardMap();
  742. saveLizardMap();
  743. webusbSendLizard();
  744. // 0x20..0x24: staged firmware update (see fw_update.h). Each op is acked with an 0xAB
  745. // frame from the usbd task; the panel ping-pongs on those acks, so at most one command
  746. // is ever in flight (also what bounds the flash-stall per loop() pass to one page erase).
  747. } else if (op == 0x20) {
  748. uint32_t sz = (uint32_t)buf[1] |
  749. ((uint32_t)buf[2] << 8) |
  750. ((uint32_t)buf[3] << 16) |
  751. ((uint32_t)buf[4] << 24);
  752. uint32_t crc = (uint32_t)buf[5] |
  753. ((uint32_t)buf[6] << 8) |
  754. ((uint32_t)buf[7] << 16) |
  755. ((uint32_t)buf[8] << 24);
  756. fwupAckPost(fwupBegin(sz, crc));
  757. } else if (op == 0x21) {
  758. uint32_t off = (uint32_t)buf[1] |
  759. ((uint32_t)buf[2] << 8) |
  760. ((uint32_t)buf[3] << 16) |
  761. ((uint32_t)buf[4] << 24);
  762. fwupAckPost(fwupChunk(off, buf + 6, buf[5]));
  763. } else if (op == 0x22) {
  764. fwupAckPost(fwupEnd());
  765. // 0x23: plain clean reboot. After a committed 0x22 the boot path applies the staged
  766. // image; unarmed it is just a normal restart.
  767. } else if (op == 0x23) {
  768. usb_web.flush();
  769. delay(40);
  770. faultDiagArmIntentionalReset();
  771. NVIC_SystemReset();
  772. } else if (op == 0x24) {
  773. fwupAbort();
  774. fwupAckPost(FWUP_OK);
  775. } else if (op == 0x02) {
  776. uint8_t f = buf[1], v = buf[2];
  777. // every settable field persists (poll rate is no longer settable)
  778. bool persist = true;
  779. // per-type cfg writes (protocol v10): field = 40 + et*8 + k, k: 0..3 back, 4 qam, 5 abSwap,
  780. // 6 padHaptics, 7 ledBright. Edits g_type[et]; refresh the live mirrors if it's the active type.
  781. if (f >= 40 && f < 40 + ET_COUNT * 8) {
  782. uint8_t et = (uint8_t)((f - 40) / 8),
  783. k = (uint8_t)((f - 40) % 8);
  784. if (et < ET_COUNT) {
  785. if (k < 4)
  786. g_type[et].back[k] = v;
  787. else if (k == 4)
  788. g_type[et].qamMap = v;
  789. else if (k == 5)
  790. g_type[et].abSwap =
  791. v ? 1 : 0;
  792. else if (k == 6)
  793. g_type[et].padHaptics =
  794. v ? 1 : 0;
  795. else if (k == 7)
  796. g_type[et].ledBright =
  797. v > 100 ? 100 :
  798. v;
  799. if (et == g_etype)
  800. applyActiveType();
  801. }
  802. saveCfg();
  803. g_blobRequest = true;
  804. memmove(buf, buf + need, n - need);
  805. n -= need;
  806. continue;
  807. }
  808. switch (f) {
  809. case 1:
  810. g_mDiv = v < 4 ? 4 : v;
  811. break;
  812. case 2:
  813. g_mFric = v > 99 ? 99 : v;
  814. break;
  815. // case 3 (padSmooth) removed -- Steam-mode pad coords are forwarded raw; Steam does its own smoothing.
  816. // Legacy single-value fields (4 abSwap, 5-8 back, 21 qam) edit the ACTIVE emulated type.
  817. case 4:
  818. if (g_etype < ET_COUNT) {
  819. g_type[g_etype].abSwap = v ? 1 :
  820. 0;
  821. applyActiveType();
  822. }
  823. break;
  824. case 5:
  825. case 6:
  826. case 7:
  827. case 8:
  828. if (g_etype < ET_COUNT) {
  829. g_type[g_etype].back[f - 5] = v;
  830. applyActiveType();
  831. }
  832. break;
  833. // case 9 (pollU100) removed -- poll rate is fixed at POLL_US_DEFAULT and no longer configurable.
  834. // E7 protocol-version B-byte (experimental v1 fast)
  835. case 10:
  836. g_e7b = v ? 1 : 0;
  837. break;
  838. // haptic-relay opcode
  839. case 11:
  840. g_relayOp = v;
  841. break;
  842. // haptic-relay sub-type
  843. case 12:
  844. g_relaySub = v;
  845. break;
  846. case 13:
  847. g_testHaptic = v ? v : 40;
  848. break; // inject v test haptics (0->40)
  849. // Steam: forward only fresh reports (dedupe)
  850. case 14:
  851. g_fwdNewOnly = v ? 1 : 0;
  852. break;
  853. case 15:
  854. g_qos = v ? 1 : 0;
  855. g_hopIdx = 0;
  856. g_qosBad = 0;
  857. g_qosCheckMs = millis();
  858. break; // QoS adaptive channel hopping
  859. // persist last mode across reboots (else always boot Steam)
  860. case 16:
  861. g_persistMode = v ? true : false;
  862. break;
  863. // back4+B/X/Y mode assignments
  864. case 17:
  865. case 18:
  866. case 19:
  867. if (modeValid(v))
  868. g_chordBtn[f - 17] = v;
  869. break;
  870. // reboot once WITH the CDC serial console (puck mode), then auto-revert
  871. case 20:
  872. armDebugCdcNextBoot();
  873. usb_web.flush();
  874. delay(40);
  875. faultDiagArmIntentionalReset();
  876. NVIC_SystemReset();
  877. break;
  878. // QAM physical button remap code (0=default/unmapped) -- active emulated type
  879. case 21:
  880. if (g_etype < ET_COUNT) {
  881. g_type[g_etype].qamMap = v;
  882. applyActiveType();
  883. }
  884. break;
  885. // rumble strength % (0=off, 100=1x, 200=double)
  886. case 22:
  887. g_rumbleScale = v;
  888. break;
  889. // Switch Pro report rate (0=66Hz,1=120Hz,2=full)
  890. case 23:
  891. g_swProRate = (v <= 2) ? v : 2;
  892. swProSaveCfg();
  893. persist = false;
  894. break;
  895. case 24:
  896. g_swGyroScale10 =
  897. (v >= 5 && v <= 30) ? v : 10;
  898. swProSaveCfg();
  899. persist = false;
  900. break; // Switch Pro gyro scale x10
  901. // (field 25, poll RX window, removed -- g_rxWin is now FIXED/not configurable)
  902. // (fields 27/28, post-connect haptic block, removed -- permanently disabled)
  903. // EXPERIMENT: land ALL relayed 0x87 config verbatim (real-puck relay)
  904. // instead of the discard-whitelist. Persisted; blob p[177] reflects state.
  905. case 29:
  906. g_landAll87 = v ? 1 : 0;
  907. break;
  908. }
  909. if (persist)
  910. saveCfg();
  911. g_blobRequest = true;
  912. } else if (op == 0x03) {
  913. uint8_t m = buf[1];
  914. if (modeValid(m) && !USBDevice.suspended()) {
  915. // best-effort status to the panel before the reboot; the SOF drain
  916. // sends it during the delay(40) below (no blocking flush on loop()).
  917. g_blobRequest = true;
  918. saveMode(m);
  919. delay(40);
  920. faultDiagArmIntentionalReset();
  921. NVIC_SystemReset();
  922. }
  923. }
  924. memmove(buf, buf + need, n - need);
  925. n -= need;
  926. }
  927. }
  928. }