webusb_config.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. #include "webusb_config.h"
  2. #include "config.h"
  3. #include "bonds.h"
  4. #include "rf_link.h"
  5. #include "haptics.h"
  6. #include "puck_hid.h"
  7. #include "triton.h" // g_in raw IMU (diagnostic readout)
  8. #include "build_info.h"
  9. #include "fault_diag.h"
  10. #include "usb_tx.h"
  11. #include <Arduino.h>
  12. #include <string.h>
  13. Adafruit_USBD_WebUSB usb_web;
  14. // Panel-blob send is deferred to the usbd task: webusbPoll() (loop) just sets this, and webusbSofDrain()
  15. // (registered with usb_tx, runs from tud_sof_cb on the usbd task) does the actual write+flush. usb_web.flush()
  16. // goes through the same blocking osd_queue_send path as HID sends, so doing it from loop() could stall the
  17. // loop and trip the watchdog under load -- with the panel open during heavy use that was a live risk.
  18. static volatile bool g_blobRequest = false;
  19. // blob payload = [ver=10][mode][mDiv][mFric][qamMap(active)][abSwap(active)][back0..3(active)][connSlot(0xFF=none)][linkUp]
  20. // [f1ps_lo][f1ps_hi][pollU100][newps_lo][newps_hi][e7b][relayOp][relaySub][fwdNewOnly]
  21. // [qos][persistMode][chordBtn B][chordBtn X][chordBtn Y][pollsps_lo][pollsps_hi]
  22. // [loopPeriod_lo][loopPeriod_hi][loopWorstIdx][loopWorstUs_lo][loopWorstUs_hi]
  23. // [pollPeriod_lo][pollPeriod_hi][logEnabled][battery%][rssi|dBm|]
  24. // [gitDirty][gitHash 12B ASCII, NUL-padded][rumbleScale][swPro120][swGyroScale10][raw accel ax ay az 3x s16 LE]
  25. // [bondedCount][slot0_up][slot0_batt][slot0_rssi]...[slot3_up][slot3_batt][slot3_rssi]
  26. // [v10: per-type cfg, 4x8B: ET_XBOX/SWITCH/DS4/DS5 each {back0..3, qam, abSwap, padHaptics, ledBright}]
  27. // [v11: resetReason(RR_* code)][resetReas raw u32 LE][rxWin/10 us][hapticBlockOn][hapticBlock s]
  28. // p[6]/p[7]/p[8..11] mirror the ACTIVE type (legacy display). v11 extends to 113 bytes (115 total incl header);
  29. // browser reads with transferIn(128) to span the two USB-FS packets.
  30. #define WB_PAYLEN 113
  31. static void webusbSendBlob()
  32. {
  33. if (!usb_web.connected())
  34. return;
  35. // "connected" = the most recent poll cycle's slot had a fresh F-reply (matches what the firmware
  36. // presents to Steam on 0x79). The blob is sent on the panel's poll, so the slot + up flag change
  37. // every ~250ms in normal use.
  38. int cs = (g_curSlot >= 0 && g_curSlot < NSLOT) ? g_curSlot : 0;
  39. bool up = (g_curSlot >= 0 && (millis() - g_connReplyMs[cs]) < 300);
  40. uint8_t p[2 + WB_PAYLEN];
  41. p[0] = 0xA5;
  42. p[1] = WB_PAYLEN;
  43. // protocol version (11 = +reset cause; 10 = +ledBright per type; 9 = +per-type cfg; 8 = +per-slot link status; 7 = +raw accel; 6 = +swPro120/gyroScale)
  44. p[2] = 11;
  45. p[3] = g_usbMode;
  46. p[4] = (uint8_t)g_mDiv;
  47. p[5] = (uint8_t)g_mFric;
  48. p[6] = g_qamMap;
  49. p[7] = g_abSwap;
  50. p[8] = g_back[0];
  51. p[9] = g_back[1];
  52. p[10] = g_back[2];
  53. p[11] = g_back[3];
  54. p[12] = (g_curSlot >= 0) ? (uint8_t)g_curSlot : 0xFF;
  55. p[13] = up ? 1 : 0;
  56. p[14] = (uint8_t)g_f1ps;
  57. p[15] = (uint8_t)(g_f1ps >> 8);
  58. p[16] = (uint8_t)(g_pollUs / 100);
  59. p[17] = (uint8_t)g_newps;
  60. p[18] = (uint8_t)(g_newps >> 8);
  61. p[19] = g_e7b;
  62. p[20] = g_relayOp;
  63. p[21] = g_relaySub;
  64. p[22] = g_fwdNewOnly;
  65. p[23] = g_qos;
  66. p[24] = g_persistMode ? 1 : 0;
  67. p[25] = g_chordBtn[0];
  68. p[26] = g_chordBtn[1];
  69. p[27] = g_chordBtn[2];
  70. p[28] = (uint8_t)g_pollsps;
  71. // poll TX rate (vs delivered/new -> starvation vs reply-loss)
  72. p[29] = (uint8_t)(g_pollsps >> 8);
  73. p[30] = (uint8_t)g_loopPeriodUs;
  74. p[31] = (uint8_t)(g_loopPeriodUs >> 8); // avg loop iteration time
  75. p[32] = g_loopWorst;
  76. p[33] = (uint8_t)g_loopWorstUs;
  77. p[34] = (uint8_t)(g_loopWorstUs >> 8);
  78. p[35] = (uint8_t)g_pollPeriodUs;
  79. p[36] = (uint8_t)(g_pollPeriodUs >>
  80. 8); // measured poll period (intended 4000)
  81. p[37] = OPK_LOG; // logging build? panel shows/hides its log UI
  82. p[38] = g_battery
  83. [g_curSlot >= 0 && g_curSlot < NSLOT ?
  84. g_curSlot :
  85. 0]; // controller battery % (report 0x43); 0=unknown
  86. p[39] = g_linkRssi[g_curSlot >= 0 && g_curSlot < NSLOT ?
  87. g_curSlot :
  88. 0]; // RAW signal strength |dBm| (0=no sample)
  89. // git commit this firmware was built from + dirty flag; injected at build time
  90. // (build_info.h / gen_version.sh); "unknown" if the version header wasn't generated.
  91. p[40] = OPK_GIT_DIRTY ? 1 : 0;
  92. memset(&p[41], 0, 12); // 12B ASCII git hash, NUL-padded
  93. {
  94. const char *h = OPK_GIT_HASH;
  95. for (uint8_t i = 0; i < 12 && h[i]; i++)
  96. p[41 + i] = (uint8_t)h[i];
  97. }
  98. p[53] = g_rumbleScale; // rumble strength % (protocol v5)
  99. // Switch Pro report rate 0=66/1=120/2=full (protocol v6)
  100. p[54] = g_swProRate;
  101. // Switch Pro gyro sensitivity x10 (protocol v6)
  102. p[55] = g_swGyroScale10;
  103. {
  104. int16_t a[3] = { g_in[0].ax, g_in[0].ay, g_in[0].az };
  105. memcpy(&p[56], a, 6);
  106. } // raw accelerometer for scale diagnostics (protocol v7)
  107. // per-slot link status for all bond slots (protocol v8)
  108. p[62] = (uint8_t)bondedSlotCount();
  109. {
  110. unsigned long nowMs = millis();
  111. for (int s = 0; s < NSLOT; s++) {
  112. bool sup = g_slot[s].used && g_connReplyMs[s] != 0 &&
  113. (nowMs - g_connReplyMs[s]) < 300u;
  114. p[63 + s * 3] = sup ? 1 : 0;
  115. p[64 + s * 3] = g_battery[s];
  116. p[65 + s * 3] = g_linkRssi[s];
  117. }
  118. }
  119. // per-emulated-type button config (protocol v10): 4 types x 8 bytes from p[75]
  120. for (int et = 0; et < ET_COUNT; et++) {
  121. uint8_t *q = &p[75 + et * 8];
  122. q[0] = g_type[et].back[0];
  123. q[1] = g_type[et].back[1];
  124. q[2] = g_type[et].back[2];
  125. q[3] = g_type[et].back[3];
  126. q[4] = g_type[et].qamMap;
  127. q[5] = g_type[et].abSwap;
  128. q[6] = g_type[et].padHaptics;
  129. q[7] = g_type[et].ledBright;
  130. }
  131. // last-boot reset cause (protocol v11): why we (re)booted -- watchdog hang vs HardFault vs intentional
  132. // reboot vs power-on (issue #72). p[107] = RR_* code; p[108..111] = raw RESETREAS for the curious.
  133. p[107] = faultDiagReason();
  134. uint32_t rr = faultDiagResetReas();
  135. p[108] = (uint8_t)rr;
  136. p[109] = (uint8_t)(rr >> 8);
  137. p[110] = (uint8_t)(rr >> 16);
  138. p[111] = (uint8_t)(rr >> 24);
  139. // Connection tunables (protocol v11): poll RX window in 10us units, post-connect haptic block enable,
  140. // and block duration in seconds.
  141. p[112] = (uint8_t)(g_rxWin / 10);
  142. p[113] = g_hapticBlockOn;
  143. p[114] = (uint8_t)(g_hapticBlockMs / 1000);
  144. usb_web.write(p, sizeof p);
  145. usb_web.flush();
  146. }
  147. // Runs on the usbd task (registered via usbTxRegisterDrain -> tud_sof_cb). Sends the blob if loop() asked for
  148. // one. Keeps every usb_web write/flush off the loop task so it can't block on the device event queue.
  149. static void webusbSofDrain(void)
  150. {
  151. if (g_blobRequest) {
  152. g_blobRequest = false;
  153. webusbSendBlob();
  154. }
  155. }
  156. // Register the SOF drain. Call once from setup() (harmless even if WebUSB isn't enumerated -- webusbSendBlob
  157. // no-ops while disconnected, and g_blobRequest is only ever set by panel traffic, which needs a connection).
  158. void webusbInit(void)
  159. {
  160. usbTxRegisterDrain(webusbSofDrain);
  161. }
  162. #if OPK_LOG
  163. // Stream the capture ring (haptics / relayed host commands) to the panel as 0xA6 frames. Frame formats:
  164. // entry: [0xA6][L][T=1][age u32 LE][slot][rid][n][bytes n] (L = 8 + n)
  165. // end: [0xA6][1][T=0]
  166. static void webusbCapFrame(uint32_t ms, uint8_t slot, uint8_t rid, uint8_t nb,
  167. const uint8_t *b)
  168. {
  169. if (nb > 16)
  170. nb = 16;
  171. uint8_t f[2 + 9 + 16];
  172. uint8_t L = (uint8_t)(8 + nb);
  173. f[0] = 0xA6;
  174. f[1] = L;
  175. f[2] = 1;
  176. f[3] = (uint8_t)ms;
  177. f[4] = (uint8_t)(ms >> 8);
  178. f[5] = (uint8_t)(ms >> 16);
  179. f[6] = (uint8_t)(ms >> 24); // absolute log time
  180. f[7] = slot;
  181. f[8] = rid;
  182. f[9] = nb;
  183. memcpy(f + 10, b, nb);
  184. usb_web.write(f, (uint16_t)(2 + L));
  185. usb_web.flush();
  186. }
  187. static void webusbCapEnd()
  188. {
  189. uint8_t e[3] = { 0xA6, 1, 0 };
  190. usb_web.write(e, 3);
  191. usb_web.flush();
  192. }
  193. // 0x06: drain entries since the last drain (or since the 0x05 start/rewind). The panel polls this on a
  194. // timer and accumulates, so a dump-from-boot of the whole ring streams over many polls without blocking the
  195. // loop. A per-call budget bounds how long one poll spends here.
  196. static void webusbDrainCapture()
  197. {
  198. if (!usb_web.connected())
  199. return;
  200. uint32_t ms = 0;
  201. uint8_t slot = 0, rid = 0, nb = 0, b[16];
  202. uint16_t budget = 128;
  203. while (budget-- && hapLogPull(&ms, &slot, &rid, &nb, b))
  204. webusbCapFrame(ms, slot, rid, nb, b);
  205. webusbCapEnd();
  206. }
  207. #endif // OPK_LOG
  208. void webusbPoll()
  209. {
  210. static uint8_t buf[16];
  211. static uint8_t n = 0;
  212. while (usb_web.available()) {
  213. int c = usb_web.read();
  214. if (c < 0)
  215. break;
  216. if (n < sizeof buf)
  217. buf[n++] = (uint8_t)c;
  218. // process complete commands from the front of buf
  219. for (;;) {
  220. if (n == 0)
  221. break;
  222. uint8_t op = buf[0];
  223. // 0x05 carries a value byte; 0x0A carries a 3-byte magic
  224. uint8_t need = (op == 0x02) ? 3 :
  225. (op == 0x03 || op == 0x05) ? 2 :
  226. (op == 0x0A) ? 4 :
  227. 1;
  228. if (op < 0x01 || op > 0x0C) { // resync: drop one byte
  229. memmove(buf, buf + 1, --n);
  230. continue;
  231. }
  232. if (n < need)
  233. break; // wait for more bytes
  234. if (op == 0x01) {
  235. g_blobRequest =
  236. true; // sent from the usbd task (webusbSofDrain)
  237. }
  238. #if OPK_LOG
  239. // rewind drain: buf[1]=1 from boot (whole ring), 0 from now
  240. else if (op == 0x05) {
  241. hapLogResetDrain(buf[1] != 0);
  242. } else if (op == 0x06) {
  243. webusbDrainCapture();
  244. } // drain entries since the rewind (panel polls this)
  245. #endif
  246. // clear a stuck/latched haptic buzz on the controller
  247. else if (op == 0x07) {
  248. hapticReinit();
  249. }
  250. // trigger controller power-off (same path Steam 0x9F / host-suspend use)
  251. else if (op == 0x08) {
  252. hapticSendShutdown();
  253. }
  254. // factory wipe: erase cfg.bin + bonds.bin, reboot to clean defaults.
  255. // Guarded by a 3-byte magic ("ERS") so a stray/corrupt byte can never trigger it.
  256. // Irreversible -- the controller must be re-paired afterwards.
  257. else if (op == 0x0A) {
  258. if (buf[1] == 0x45 && buf[2] == 0x52 &&
  259. buf[3] == 0x53) {
  260. usb_web.flush();
  261. factoryErase();
  262. delay(40);
  263. faultDiagArmIntentionalReset();
  264. NVIC_SystemReset();
  265. }
  266. // reboot into serial DFU (adafruit-nrfutil)
  267. } else if (op == 0x0B) {
  268. usb_web.flush();
  269. delay(40);
  270. faultDiagArmIntentionalReset();
  271. enterSerialDfu();
  272. // reboot into UF2 bootloader (USB mass storage)
  273. } else if (op == 0x0C) {
  274. usb_web.flush();
  275. delay(40);
  276. faultDiagArmIntentionalReset();
  277. enterUf2Dfu();
  278. } else if (op == 0x02) {
  279. uint8_t f = buf[1], v = buf[2];
  280. // every settable field persists (poll rate is no longer settable)
  281. bool persist = true;
  282. // per-type cfg writes (protocol v10): field = 40 + et*8 + k, k: 0..3 back, 4 qam, 5 abSwap,
  283. // 6 padHaptics, 7 ledBright. Edits g_type[et]; refresh the live mirrors if it's the active type.
  284. if (f >= 40 && f < 40 + ET_COUNT * 8) {
  285. uint8_t et = (uint8_t)((f - 40) / 8),
  286. k = (uint8_t)((f - 40) % 8);
  287. if (et < ET_COUNT) {
  288. if (k < 4)
  289. g_type[et].back[k] = v;
  290. else if (k == 4)
  291. g_type[et].qamMap = v;
  292. else if (k == 5)
  293. g_type[et].abSwap =
  294. v ? 1 : 0;
  295. else if (k == 6)
  296. g_type[et].padHaptics =
  297. v ? 1 : 0;
  298. else if (k == 7)
  299. g_type[et].ledBright =
  300. v > 100 ? 100 :
  301. v;
  302. if (et == g_etype)
  303. applyActiveType();
  304. }
  305. saveCfg();
  306. g_blobRequest = true;
  307. memmove(buf, buf + need, n - need);
  308. n -= need;
  309. continue;
  310. }
  311. switch (f) {
  312. case 1:
  313. g_mDiv = v < 4 ? 4 : v;
  314. break;
  315. case 2:
  316. g_mFric = v > 99 ? 99 : v;
  317. break;
  318. // case 3 (padSmooth) removed -- Steam-mode pad coords are forwarded raw; Steam does its own smoothing.
  319. // Legacy single-value fields (4 abSwap, 5-8 back, 21 qam) edit the ACTIVE emulated type.
  320. case 4:
  321. if (g_etype < ET_COUNT) {
  322. g_type[g_etype].abSwap = v ? 1 :
  323. 0;
  324. applyActiveType();
  325. }
  326. break;
  327. case 5:
  328. case 6:
  329. case 7:
  330. case 8:
  331. if (g_etype < ET_COUNT) {
  332. g_type[g_etype].back[f - 5] = v;
  333. applyActiveType();
  334. }
  335. break;
  336. // case 9 (pollU100) removed -- poll rate is fixed at POLL_US_DEFAULT and no longer configurable.
  337. // E7 protocol-version B-byte (experimental v1 fast)
  338. case 10:
  339. g_e7b = v ? 1 : 0;
  340. break;
  341. // haptic-relay opcode
  342. case 11:
  343. g_relayOp = v;
  344. break;
  345. // haptic-relay sub-type
  346. case 12:
  347. g_relaySub = v;
  348. break;
  349. case 13:
  350. g_testHaptic = v ? v : 40;
  351. break; // inject v test haptics (0->40)
  352. // Steam: forward only fresh reports (dedupe)
  353. case 14:
  354. g_fwdNewOnly = v ? 1 : 0;
  355. break;
  356. case 15:
  357. g_qos = v ? 1 : 0;
  358. g_hopIdx = 0;
  359. g_qosBad = 0;
  360. g_qosCheckMs = millis();
  361. break; // QoS adaptive channel hopping
  362. // persist last mode across reboots (else always boot Steam)
  363. case 16:
  364. g_persistMode = v ? true : false;
  365. break;
  366. // back4+B/X/Y mode assignments
  367. case 17:
  368. case 18:
  369. case 19:
  370. if (modeValid(v))
  371. g_chordBtn[f - 17] = v;
  372. break;
  373. // reboot once WITH the CDC serial console (puck mode), then auto-revert
  374. case 20:
  375. armDebugCdcNextBoot();
  376. usb_web.flush();
  377. delay(40);
  378. faultDiagArmIntentionalReset();
  379. NVIC_SystemReset();
  380. break;
  381. // QAM physical button remap code (0=default/unmapped) -- active emulated type
  382. case 21:
  383. if (g_etype < ET_COUNT) {
  384. g_type[g_etype].qamMap = v;
  385. applyActiveType();
  386. }
  387. break;
  388. // rumble strength % (0=off, 100=1x, 200=double)
  389. case 22:
  390. g_rumbleScale = v;
  391. break;
  392. // Switch Pro report rate (0=66Hz,1=120Hz,2=full)
  393. case 23:
  394. g_swProRate = (v <= 2) ? v : 2;
  395. swProSaveCfg();
  396. persist = false;
  397. break;
  398. case 24:
  399. g_swGyroScale10 =
  400. (v >= 5 && v <= 30) ? v : 10;
  401. swProSaveCfg();
  402. persist = false;
  403. break; // Switch Pro gyro scale x10
  404. // connected-poll RX window, in 10us units: wider window catches a controller reply that
  405. // lands late under haptic load; narrower allows a higher poll rate. Clamp 600..3000us.
  406. case 25: {
  407. uint32_t w = (uint32_t)v * 10;
  408. g_rxWin = w < 600 ? 600 :
  409. w > 3000 ? 3000 :
  410. w;
  411. break;
  412. }
  413. // post-connect haptic block enable: drop Steam haptics for g_hapticBlockMs after a connect
  414. case 27:
  415. g_hapticBlockOn = v ? 1 : 0;
  416. break;
  417. // post-connect haptic block duration, in seconds (clamp 0..60)
  418. case 28:
  419. g_hapticBlockMs =
  420. (uint16_t)((v > 60 ? 60 : v) *
  421. 1000u);
  422. break;
  423. }
  424. if (persist)
  425. saveCfg();
  426. g_blobRequest = true;
  427. } else if (op == 0x03) {
  428. uint8_t m = buf[1];
  429. if (modeValid(m) && !USBDevice.suspended()) {
  430. // best-effort status to the panel before the reboot; the SOF drain
  431. // sends it during the delay(40) below (no blocking flush on loop()).
  432. g_blobRequest = true;
  433. saveMode(m);
  434. delay(40);
  435. faultDiagArmIntentionalReset();
  436. NVIC_SystemReset();
  437. }
  438. }
  439. memmove(buf, buf + need, n - need);
  440. n -= need;
  441. }
  442. }
  443. }