webusb_config.cpp 38 KB

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