OpenPuck.ino 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. // OpenPuck.ino -- Steam Controller 2 ("Triton") puck reimplementation for an nRF52840.
  2. //
  3. // This firmware impersonates the Valve puck over USB, maintains puck-style bond slots, speaks the
  4. // reverse-engineered RF protocol to the controller, and re-enumerates into Steam, Xbox, Switch, PS5, or DS4
  5. // personalities. Build with `make build` (bakes in the required CFG_TUD_HID=4 + CFG_TUD_TASK_QUEUE_SZ=64).
  6. //
  7. // This file is just the entry point: setup() builds the USB presentation for the persisted mode and arms the
  8. // hardware watchdog; loop() pumps each subsystem. Everything substantive lives in the modules below -- see
  9. // ARCHITECTURE.md for the full map. The short version:
  10. // config / identity / bonds -- persisted settings, device serial, the four controller bond slots
  11. // radio / rf_link / rf_diag -- bare-metal nRF52 RADIO, the operational puck protocol, and RE tooling
  12. // triton / gamepad_util -- the decoded controller input (g_in) + shared host-report build helpers
  13. // controllers + mode_* -- one IController per USB personality (puck/lizard, xbox, switch, ps5, ds4)
  14. // haptics / webusb_config / serial_console -- haptic relay, the browser config channel, the CDC debug CLI
  15. //
  16. // Protocol reference: docs/PROTOCOL.md. Bond record = [8 uuid][16 serial].
  17. #include <Adafruit_TinyUSB.h>
  18. #include <Adafruit_LittleFS.h>
  19. #include <InternalFileSystem.h>
  20. using namespace Adafruit_LittleFS_Namespace;
  21. #include "config.h"
  22. // OPK_GIT_HASH: tags the one-time factory-reset build
  23. #include "build_info.h"
  24. #include "identity.h"
  25. #include "bonds.h"
  26. #include "radio.h"
  27. #include "controllers.h"
  28. #include "haptics.h"
  29. #include "rf_link.h"
  30. #include "rf_diag.h"
  31. #include "webusb_config.h"
  32. #include "serial_console.h"
  33. #include "wake_hid.h"
  34. #include "status_led.h"
  35. #include "usb_mount.h"
  36. #include "identity.h"
  37. #include "fault_diag.h"
  38. #include "usb_tx.h"
  39. #include <stdio.h>
  40. #if CFG_TUD_HID < 4
  41. #error "CFG_TUD_HID must be >= 4 (up to 4 HID interfaces per mode). Build with `make build` (bakes it in), or pass -DCFG_TUD_HID=4 in build.extra_flags."
  42. #endif
  43. // The TinyUSB device-stack event queue (_usbd_q) defaults to 16 entries. tud_task() runs in the dedicated
  44. // high-priority "usbd" FreeRTOS task, but this firmware emits HID reports from the LOW-priority loop() task
  45. // (every mode: 0x45 forwards, per-slot 0x79/0x7B/0x43 status, streamed gamepad reports). A cross-task
  46. // sendReport whose EasyDMA is momentarily busy takes TinyUSB's usbd_defer_func() path, which does a BLOCKING
  47. // osal_queue_send (xQueueSendToBack WAIT_FOREVER) onto _usbd_q. Under a comms burst (haptics/trackpad floods,
  48. // the connect-time re-init storm, 4 slots at once) the 16-deep queue saturates; the loop task then blocks
  49. // posting to it and stops feeding the ~8 s watchdog -> the MCU resets and the controller "disconnects". A
  50. // deeper queue absorbs realistic bursts so the loop never blocks. Must be set on the build command (it is a
  51. // TinyUSB-internal #ifndef default, so a sketch header cannot reach usbd.c) -- enforce it here so a build that
  52. // omits the flag fails loudly instead of shipping the deadlock.
  53. #if !defined(CFG_TUD_TASK_QUEUE_SZ) || CFG_TUD_TASK_QUEUE_SZ < 32
  54. #error "CFG_TUD_TASK_QUEUE_SZ must be >= 32: the default 16-deep usbd event queue deadlocks the loop task under comms load -> watchdog reset. Build with `make build` (bakes in 64), or pass -DCFG_TUD_TASK_QUEUE_SZ=64 in build.extra_flags."
  55. #endif
  56. // puck composite (4 HID + WebUSB) exceeds the default 256 B config buffer
  57. static uint8_t g_usbCfgDesc[512];
  58. // Per-mode USB serial suffix (modes 1..8: X=xbox N=hori L=lizard P=swpro S=ps5 G=hidgyro Q=ps5game D=ds4game).
  59. static const char MODE_SUFFIX[] = { 'X', 'N', 'L', 'P', 'S', 'G', 'Q', 'D' };
  60. // Fixed-interface flags captured at boot so usbReenumerate (dynamic mount, no reboot) replays them.
  61. static bool s_dynWantWebusb = false, s_dynWantWakeMouse = false;
  62. // Dynamic re-enumeration (NO MCU reboot): tear down + rebuild the config descriptor presenting `k` connected-
  63. // controller slots, replaying the fixed interfaces in locked HID-instance order (wake mouse = instance 0,
  64. // before the slot pool; WebUSB is vendor-class so order-free), then re-attach. RF/firmware state survives.
  65. // g_usbToBond must already be built for k connected controllers. Called at boot and by usb_mount's watcher.
  66. void usbReenumerate(uint8_t k)
  67. {
  68. USBDevice.detach();
  69. delay(20);
  70. USBDevice.clearConfiguration();
  71. USBDevice.setConfigurationBuffer(g_usbCfgDesc, sizeof g_usbCfgDesc);
  72. g_active->usbIdentity(); // clearConfiguration reset VID/PID/strings -- restore them
  73. // serial carries the mounted count so the host invalidates its cached config descriptor on a change
  74. snprintf(
  75. g_usbSerial, sizeof g_usbSerial, "%s%c%u", g_unit,
  76. MODE_SUFFIX[(g_usbMode >= 1 && g_usbMode <= 8) ? g_usbMode - 1 :
  77. 0],
  78. (unsigned)k);
  79. USBDevice.setSerialDescriptor(g_usbSerial);
  80. if (s_dynWantWakeMouse)
  81. wakeHidAddInterface(); // HID instance 0
  82. g_active->mountSlots(
  83. k); // mode's fixed HIDs (if any) + k slot interfaces
  84. if (s_dynWantWebusb)
  85. USBDevice.addInterface(usb_web);
  86. USBDevice.setConfigurationAttribute(0x80 | 0x20);
  87. USBDevice.attach();
  88. }
  89. void setup()
  90. {
  91. genSerial();
  92. ledInit();
  93. // seed defaults so unbonded slots don't share the discovery address
  94. for (int s = 0; s < NSLOT; s++)
  95. rfGenSessionAddr(s);
  96. InternalFS.begin();
  97. #if OPK_FACTORY_RESET
  98. // Recovery build (-DOPK_FACTORY_RESET=1): wipe ALL persistent storage ONCE on the first boot after flashing,
  99. // then persist normally (tracked by a git-hash tag so it does NOT wipe every boot). See config.h / config.cpp.
  100. factoryResetOnce(OPK_GIT_HASH);
  101. #endif
  102. loadCfg();
  103. loadBonds();
  104. // regenerate per-slot session addresses from each bond UUID (deterministic, stable across reboots)
  105. for (int s = 0; s < NSLOT; s++)
  106. if (g_slot[s].used)
  107. rfGenSessionAddr(s);
  108. // decide USB presentation BEFORE registering interfaces
  109. g_xbox = !modeIsPuck(g_usbMode);
  110. g_active = controllerFor(g_usbMode);
  111. // ---- USB descriptor rebuild ----
  112. // Puck mode drops the CDC serial console (clearConfiguration) to free a USB endpoint for the wake-mouse
  113. // interface that wakes a sleeping Windows host. The one-shot debug arm (g_debugCdcThisBoot, set via WebUSB
  114. // panel / CDC 'D', auto-reverting after one boot) instead KEEPS the boot CDC composite and skips the wake
  115. // mouse (no endpoint room for both). Clean modes always rebuild bare.
  116. const bool puckMode = g_active->isPuck();
  117. const bool keepCdc = puckMode && g_debugCdcThisBoot;
  118. // The "game" PlayStation modes enumerate as a CLEAN single HID gamepad so games that classify off the raw HID
  119. // device (Fortnite/UE GameInput, Windows.Gaming.Input) recognise them as PlayStation. A real Sony pad is just
  120. // the gamepad HID (+ a USB-audio interface); our extra wake-mouse HID and WebUSB vendor interface make those
  121. // classifiers refuse the PS glyph path even with the correct VID/PID (SDL/Steam tolerate the extras). So
  122. // clean-PS modes skip BOTH the wake mouse and WebUSB -- no config panel / host-wake; chord back to Steam
  123. // (back-paddle 4 + A) to reach the panel. Normal MODE_PS5 / MODE_HIDGYRO keep wake + panel.
  124. const bool psClean = modeIsCleanPS(g_usbMode);
  125. const bool dynamic = g_active->dynamicMount();
  126. if (dynamic) {
  127. // Dynamic mount: present only ACTIVELY-CONNECTED controllers; usbReenumerate re-attaches (no reboot)
  128. // as the set changes. Emulated modes are never puck; clean-PS drops the wake mouse + WebUSB.
  129. s_dynWantWakeMouse = !psClean;
  130. s_dynWantWebusb = !psClean;
  131. USBDevice.detach();
  132. delay(30);
  133. USBDevice.clearConfiguration();
  134. USBDevice.setConfigurationBuffer(g_usbCfgDesc,
  135. sizeof g_usbCfgDesc);
  136. // Lock TinyUSB HID instance indices ONCE, canonical order: wake mouse (HID 0) then the mode's pool.
  137. if (s_dynWantWakeMouse)
  138. wakeHidBegin();
  139. g_active->beginPool();
  140. if (s_dynWantWebusb)
  141. usb_web.begin();
  142. usbMountEnable(true, g_active->maxSlots());
  143. usbMountRebuildMap(); // initial connected set (usually empty at cold boot)
  144. usbReenumerate(
  145. g_usbMountCount); // build the live descriptor + attach
  146. } else {
  147. USBDevice.detach();
  148. delay(30);
  149. if (keepCdc) {
  150. USBDevice.setConfigurationBuffer(g_usbCfgDesc,
  151. sizeof g_usbCfgDesc);
  152. } else {
  153. USBDevice.clearConfiguration();
  154. // headroom over the default 256 B cap
  155. USBDevice.setConfigurationBuffer(g_usbCfgDesc,
  156. sizeof g_usbCfgDesc);
  157. }
  158. // Distinct USB serial PER MODE (must be set AFTER clearConfiguration, which nulls it). Hosts cache USB
  159. // identity by VID:PID:serial; reusing one serial under a changing VID:PID can make a host refuse the new
  160. // identity. Steam keeps the exact unit serial (its pairing identity); the others get a 1-char suffix.
  161. if (puckMode) {
  162. USBDevice.setSerialDescriptor(g_unit);
  163. } else {
  164. // Bond count in serial so Windows invalidates its cached config descriptor if the count changes.
  165. snprintf(g_usbSerial, sizeof g_usbSerial, "%s%c%d",
  166. g_unit, MODE_SUFFIX[g_usbMode - 1],
  167. bondedSlotCount() > 0 ? bondedSlotCount() : 1);
  168. USBDevice.setSerialDescriptor(g_usbSerial);
  169. }
  170. // SDL3's Proteus/Triton HIDAPI driver only binds slot HIDs on USB interfaces 2..5. Register WebUSB (IF 0)
  171. // and the wake mouse (IF 1) before the four puck slots so hid[0..3] land on IF 2..5 like the real puck.
  172. if (puckMode)
  173. usb_web.begin();
  174. if (puckMode && !keepCdc)
  175. wakeHidBegin();
  176. g_active->begin();
  177. // Boot-mouse wake interface for clean (non-puck) modes, and for puck on the one-shot debug boot (CDC on,
  178. // no endpoint room for wake mouse on a normal puck boot -- wake is registered above instead). Skipped for PS
  179. // modes so the device stays a single clean HID gamepad (see psClean above).
  180. if (!puckMode && !keepCdc && !psClean)
  181. wakeHidBegin();
  182. // WebUSB config panel -- every mode EXCEPT the PlayStation modes. Puck: registered above (IF 0) before wake +
  183. // slots; other clean modes after controller. PS modes omit it to present a genuine single-HID PS controller.
  184. if (!puckMode && !psClean)
  185. usb_web.begin();
  186. // bmAttributes: required(0x80) | remote_wakeup(0x20). Remote Wakeup lets us signal wake-from-sleep.
  187. USBDevice.setConfigurationAttribute(0x80 | 0x20);
  188. // re-attach with the final descriptor (host re-reads it fresh -> deterministic enumeration)
  189. USBDevice.attach();
  190. }
  191. Serial.begin(115200);
  192. for (int i = 0; i < 300 && !USBDevice.mounted(); i++)
  193. delay(10); // wait up to 3s for USB mount, but NEVER hang
  194. if (USBDevice.suspended()) {
  195. USBDevice.remoteWakeup();
  196. ledWakePulse();
  197. } // wake host if bus was sleeping when we (re-)attached
  198. // Route all device->host HID sends through the usbd task (SOF drain) so loop() never calls tud_* directly
  199. // -> the cross-task blocking-defer that deadlocked the loop under comms load can no longer happen.
  200. usbTxBegin();
  201. webusbInit(); // also drain the WebUSB status blob from the usbd task (its flush() can block loop() too)
  202. hapticInit();
  203. static const char *MODE_NAME[] = {
  204. "STEAM(puck)", "XBOX(xinput+mouse)",
  205. "SWITCH(horipad)", "LIZARD(puck kb/mouse)",
  206. "SWITCH(pro+gyro)", "PS5(dualsense)",
  207. "HIDGYRO(ds4+motion)", "PS5(dualsense,game/clean)",
  208. "DS4(ds4,game/clean)"
  209. };
  210. Serial.printf("# copycat up: unit=%s board=%s, mode=%s\n", g_unit,
  211. g_board,
  212. MODE_NAME[g_usbMode <= MODE_MAX ? g_usbMode : 0]);
  213. // Classify why we (re)booted: distinguishes a watchdog hang from a HardFault from an intentional reboot
  214. // (issue #72 -- those are conflated in the field). Surfaced on the WebUSB panel too.
  215. faultDiagBoot();
  216. if (puckMode)
  217. Serial.printf(
  218. "# puck USB: %s\n",
  219. keepCdc ?
  220. "DEBUG boot (CDC console on, wake mouse off; reverts next boot)" :
  221. "normal (CDC off, wake mouse on)");
  222. Serial.printf(
  223. "# session ch%u (discovery on ibex/ch2); per-slot session addrs:\n",
  224. g_sessCh);
  225. for (int s = 0; s < NSLOT; s++) {
  226. if (g_slot[s].used) {
  227. Serial.printf(
  228. "# slot %d: %02X%02X%02X%02X/%02X (uuid %02X%02X%02X%02X %02X%02X%02X%02X)\n",
  229. s, g_sessBase[s][0], g_sessBase[s][1],
  230. g_sessBase[s][2], g_sessBase[s][3],
  231. g_sessPrefix[s], g_slot[s].rec[0],
  232. g_slot[s].rec[1], g_slot[s].rec[2],
  233. g_slot[s].rec[3], g_slot[s].rec[4],
  234. g_slot[s].rec[5], g_slot[s].rec[6],
  235. g_slot[s].rec[7]);
  236. }
  237. }
  238. // Hardware watchdog: if loop() ever stops feeding it (wedged radio busy-wait, HardFault spin, blocked CDC
  239. // write) the WDT resets the nRF52 after ~8s, re-enumerating USB + re-initialising RF, so a hang no longer
  240. // needs a physical replug. RUN keeps it counting in sleep; PAUSE freezes it under a debugger.
  241. NRF_WDT->CONFIG = (WDT_CONFIG_HALT_Pause << WDT_CONFIG_HALT_Pos) |
  242. (WDT_CONFIG_SLEEP_Run << WDT_CONFIG_SLEEP_Pos);
  243. NRF_WDT->CRV = 8UL * 32768UL - 1; // timeout in 32.768 kHz ticks (~8 s)
  244. NRF_WDT->RREN = WDT_RREN_RR0_Msk; // arm reload register 0
  245. NRF_WDT->TASKS_START = 1;
  246. }
  247. // loop-timing diagnostics: poll rate is capped by loop ITERATION time (pacing wants 4000us but the poll only
  248. // fires as often as the loop comes around). Per-section us accumulates and each second the avg loop period +
  249. // slowest section are published for the WebUSB panel.
  250. // avg loop iteration time last second (1e6/iterations)
  251. uint16_t g_loopPeriodUs = 0;
  252. // index of the slowest section: 0=webusb 1=ctrl.task 2=serial 3=rfdiag 4=rflink 5=haptic 6=led
  253. uint8_t g_loopWorst = 0;
  254. uint16_t g_loopWorstUs = 0; // that section's avg us per iteration
  255. void loop()
  256. {
  257. // feed the watchdog; if we ever stop, the ~8s WDT auto-resets us
  258. NRF_WDT->RR[0] = WDT_RR_RR_Reload;
  259. if (g_dirty) {
  260. g_dirty = false;
  261. saveBonds();
  262. }
  263. #if OPK_LOG
  264. // Diagnostic build: time each loop section so the panel can show the slowest one + the loop period.
  265. static uint32_t acc[7] = { 0 };
  266. static uint32_t loops = 0;
  267. static unsigned long secMs = 0;
  268. uint32_t t;
  269. t = micros();
  270. webusbPoll();
  271. acc[0] += (uint32_t)(micros() - t);
  272. t = micros();
  273. if (g_active)
  274. g_active->task();
  275. acc[1] += (uint32_t)(micros() - t);
  276. t = micros();
  277. serialConsolePoll();
  278. acc[2] += (uint32_t)(micros() - t);
  279. t = micros();
  280. rfDiagTask();
  281. acc[3] += (uint32_t)(micros() - t);
  282. t = micros();
  283. rfLinkTask();
  284. acc[4] += (uint32_t)(micros() - t);
  285. t = micros();
  286. hapticTask();
  287. acc[5] += (uint32_t)(micros() - t);
  288. t = micros();
  289. ledTask();
  290. acc[6] += (uint32_t)(micros() - t);
  291. usbMountTask(); // dynamic mount/unmount of connected controllers (no-op unless enabled)
  292. usbTxPump(); // drain queued device->host reports HERE, in loop -- never off-loop (jitters the RF poll)
  293. loops++;
  294. if (millis() - secMs >= 1000) {
  295. g_loopPeriodUs = loops ? (uint16_t)(1000000UL / loops) : 0;
  296. uint8_t wi = 0;
  297. uint32_t wv = 0;
  298. for (int i = 0; i < 7; i++) {
  299. if (acc[i] > wv) {
  300. wv = acc[i];
  301. wi = i;
  302. }
  303. acc[i] = 0;
  304. }
  305. g_loopWorst = wi;
  306. g_loopWorstUs = loops ? (uint16_t)(wv / loops) : 0;
  307. loops = 0;
  308. secMs = millis();
  309. }
  310. #else
  311. webusbPoll();
  312. if (g_active)
  313. g_active->task();
  314. serialConsolePoll();
  315. rfDiagTask();
  316. rfLinkTask();
  317. hapticTask();
  318. ledTask();
  319. usbMountTask(); // dynamic mount/unmount of connected controllers (no-op unless enabled)
  320. usbTxPump(); // drain queued device->host reports HERE, in loop -- never off-loop (jitters the RF poll)
  321. #endif
  322. }