webusb_config.cpp 13 KB

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