webusb_config.cpp 43 KB

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