webusb_config.cpp 40 KB

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