webusb_config.cpp 38 KB

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