index.html 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1">
  6. <title>OpenPuck Config</title>
  7. <style>
  8. :root{ --bg:#11131a; --card:#1b1f2b; --fg:#e7ecf3; --mut:#8a93a6; --acc:#5bd6a0; --acc2:#5b9bd6; --bad:#d65b6e; }
  9. *{box-sizing:border-box}
  10. body{margin:0;font:14px/1.5 -apple-system,Segoe UI,Roboto,sans-serif;background:var(--bg);color:var(--fg);padding:24px}
  11. h1{font-size:20px;margin:0 0 4px}
  12. .sub{color:var(--mut);margin:0 0 20px}
  13. .wrap{max-width:680px;margin:0 auto}
  14. .card{background:var(--card);border:1px solid #272d3d;border-radius:12px;padding:18px 20px;margin-bottom:16px}
  15. .card h2{font-size:13px;text-transform:uppercase;letter-spacing:.06em;color:var(--mut);margin:0 0 14px}
  16. .row{display:flex;align-items:center;gap:14px;margin:12px 0}
  17. .row label{flex:0 0 150px;color:var(--fg)}
  18. .row .val{flex:0 0 64px;text-align:right;color:var(--acc);font-variant-numeric:tabular-nums}
  19. input[type=range]{flex:1;accent-color:var(--acc)}
  20. select{background:#0e1017;color:var(--fg);border:1px solid #313a4f;border-radius:8px;padding:6px 8px;flex:1}
  21. button{background:#222a3a;color:var(--fg);border:1px solid #36405a;border-radius:8px;padding:9px 14px;cursor:pointer;font:inherit}
  22. button:hover{border-color:var(--acc2)}
  23. button.primary{background:var(--acc2);border-color:var(--acc2);color:#06121f;font-weight:600}
  24. button.active{background:var(--acc);border-color:var(--acc);color:#062018;font-weight:600}
  25. button:disabled{opacity:.4;cursor:default}
  26. .pill{display:inline-block;padding:2px 9px;border-radius:99px;font-size:12px;font-weight:600}
  27. .pill.up{background:#143626;color:var(--acc)} .pill.dn{background:#3a1822;color:var(--bad)}
  28. .statgrid{display:grid;grid-template-columns:repeat(3,1fr);gap:10px}
  29. .stat{background:#0e1017;border:1px solid #232a3a;border-radius:8px;padding:10px}
  30. .stat .k{color:var(--mut);font-size:11px;text-transform:uppercase;letter-spacing:.05em}
  31. .stat .v{font-size:18px;margin-top:2px}
  32. .modes{display:flex;gap:10px}
  33. .note{color:var(--mut);font-size:12px;margin-top:10px}
  34. #log{font:12px ui-monospace,Menlo,monospace;color:var(--mut);white-space:pre-wrap;margin-top:8px;max-height:120px;overflow:auto}
  35. .hide{display:none}
  36. /* ---- controller slot tabs ---- */
  37. .slot-tabs{display:flex;gap:6px;margin:0 0 14px;flex-wrap:wrap}
  38. .slot-tab{display:flex;align-items:center;gap:7px;padding:5px 14px;border-radius:8px;font-size:12px;font-weight:600;background:#0e1017;border:1px solid #232a3a;color:var(--mut);cursor:pointer;transition:border-color .15s,color .15s,background .15s}
  39. .slot-tab:hover{border-color:var(--acc2);color:var(--fg)}
  40. .slot-tab.active{background:#111c2e;border-color:var(--acc2);color:var(--fg)}
  41. .slot-tab .dot{width:7px;height:7px;border-radius:50%;background:var(--bad);flex-shrink:0;transition:background .3s}
  42. .slot-tab .dot.up{background:var(--acc);animation:pulse-link 2.2s ease-in-out infinite}
  43. @keyframes pulse-link{
  44. 0%,100%{box-shadow:0 0 0 0 rgba(91,214,160,.5)}
  45. 55%{box-shadow:0 0 0 5px rgba(91,214,160,0)}
  46. }
  47. @media(prefers-reduced-motion:reduce){.slot-tab .dot.up{animation:none}}
  48. .per-slot-grid{margin-bottom:12px}
  49. </style>
  50. </head>
  51. <body>
  52. <div class="wrap">
  53. <h1>OpenPuck Config</h1>
  54. <p class="sub">nRF52840 Steam Controller 2 puck reimplementation — WebUSB. Chrome/Edge only.</p>
  55. <div class="card" id="connectCard">
  56. <div class="row" style="margin:0">
  57. <button id="connectBtn" class="primary">Connect to copycat</button>
  58. <span id="connState" class="pill dn">disconnected</span>
  59. </div>
  60. <p class="note">If nothing appears in the device picker, the copycat may be busy (quit any app holding it) or needs a replug.</p>
  61. </div>
  62. <div id="panel" class="hide">
  63. <div class="card">
  64. <h2>USB mode</h2>
  65. <div class="modes" style="flex-wrap:wrap">
  66. <button data-mode="0" class="modebtn">Steam (puck)</button>
  67. <button data-mode="1" class="modebtn">Xbox 360</button>
  68. <button data-mode="2" class="modebtn">Switch (HORIPAD)</button>
  69. <button data-mode="3" class="modebtn">Lizard (always)</button>
  70. <button data-mode="4" class="modebtn">Switch Pro + gyro</button>
  71. <button data-mode="5" class="modebtn">PS5 DualSense</button>
  72. <button data-mode="6" class="modebtn">HID gyro (DS4)</button>
  73. </div>
  74. <p class="note">Switching reboots the copycat and re-enumerates USB (~2 s). WebUSB works in every mode, including Steam/Lizard with Steam running (Chrome claims the vendor interface; Steam keeps the HID slots). Switch HORIPAD + WebUSB is PC-only.</p>
  75. <div class="row"><label>Persist last mode</label>
  76. <button id="persistMode">off</button>
  77. <span class="note" style="flex:1">Off (default): every restart / fresh reconnect boots into Steam mode. On: remembers the last mode you selected.</span>
  78. </div>
  79. </div>
  80. <div class="card">
  81. <h2>Back4 + face button chords</h2>
  82. <p class="note" style="margin-top:0">Hold all four back paddles (L4+R4+L5+R5) plus a face button to switch mode without the WebUI. <strong>A is always Steam.</strong> B / X / Y are configurable below (defaults: B=Lizard, X=Xbox, Y=Switch HORIPAD).</p>
  83. <div class="row"><label>B + back4 →</label><select class="chord" data-i="0"></select></div>
  84. <div class="row"><label>X + back4 →</label><select class="chord" data-i="1"></select></div>
  85. <div class="row"><label>Y + back4 →</label><select class="chord" data-i="2"></select></div>
  86. </div>
  87. <div class="card">
  88. <h2>Link status</h2>
  89. <!-- Per-controller tabs: visible only when 2+ controllers are bonded -->
  90. <div class="slot-tabs" id="slotTabs" style="display:none"></div>
  91. <!-- Per-slot: RF link / Battery / Signal -->
  92. <div class="statgrid per-slot-grid">
  93. <div class="stat"><div class="k">RF link</div><div class="v" id="stLink">—</div></div>
  94. <div class="stat"><div class="k">Battery</div><div class="v" id="stBatt">—</div></div>
  95. <div class="stat"><div class="k">Signal</div><div class="v" id="stRssi">—</div></div>
  96. </div>
  97. <!-- Global stats -->
  98. <div class="statgrid">
  99. <div class="stat"><div class="k">Delivered</div><div class="v" id="stRate">—</div></div>
  100. <div class="stat"><div class="k">New reports</div><div class="v" id="stNew">—</div></div>
  101. <div class="stat"><div class="k">Polls/s</div><div class="v" id="stPolls">—</div></div>
  102. <div class="stat"><div class="k">Relay/s</div><div class="v" id="stRelay">—</div></div>
  103. <div class="stat"><div class="k">RF fails/s (crc·noRx·heal)</div><div class="v" id="stRfFail">—</div></div>
  104. <div class="stat"><div class="k">Clock LF / HF</div><div class="v" id="stClock">—</div></div>
  105. <div class="stat"><div class="k">µs per ms (ideal 1000)</div><div class="v" id="stUsPerMs">—</div></div>
  106. <div class="stat"><div class="k">Loop</div><div class="v" id="stLoopState">—</div></div>
  107. <div class="stat logonly"><div class="k">Loop period</div><div class="v" id="stLoop">—</div></div>
  108. <div class="stat logonly"><div class="k">Slowest stage</div><div class="v" id="stWorst">—</div></div>
  109. <div class="stat logonly"><div class="k">Poll period act/want</div><div class="v" id="stPollPer">—</div></div>
  110. <div class="stat"><div class="k">Build (git)</div><div class="v" id="stBuild">—</div></div>
  111. <div class="stat"><div class="k">Last reset</div><div class="v" id="stReset">—</div></div>
  112. </div>
  113. <p class="note" style="margin-top:6px"><strong>Reset detail:</strong> <span id="resetHist" style="font-family:ui-monospace,Menlo,monospace">—</span><br>
  114. <em>watchdog (hang)</em>/<em>CPU lockup</em>/<em>HARDFAULT</em> = a fault worth reporting (issue #72); <em>reboot</em> = an intentional reset (mode change / config); <em>power-on</em> &amp; <em>pin/replug</em> = normal plug-in.</p>
  115. <p class="note" style="margin-top:8px"><strong>IMU (raw):</strong> <span id="stImu" style="font-family:ui-monospace,Menlo,monospace">—</span><br>
  116. Raw SC2 accel (before scaling). This controller is a ±2 g sensor (~16384 = 1 g); the Switch report divides it by 4 to present the genuine ±8 g (4096 = 1 g) scale so the console's gravity-correction engages and the gyro stops drifting.</p>
  117. <p class="note logonly">Polls/s ≈ 250 expected; it's capped by Loop period (≈4000 µs needed). "Slowest stage" is the loop section eating the most time per iteration.</p>
  118. <div class="row" style="margin:14px 0 0;border-top:1px solid #272d3d;padding-top:14px"><button id="hapClear">Clear stuck buzz</button>
  119. <span class="note" style="flex:1">If the controller's haptics get stuck/buzzing, this re-inits them (same as pressing Steam).</span>
  120. </div>
  121. <div class="row" style="margin:10px 0 0"><button id="ctlrOff">Turn off controller</button>
  122. <span class="note" style="flex:1">Fires the controller power-off (0x9F "off!", x3) — the same path Steam's "turn off controller" and host-suspend use. Watch the link status to see it disconnect.</span>
  123. </div>
  124. <div class="row" style="margin:10px 0 0;border-top:1px solid #272d3d;padding-top:14px">
  125. <button id="dfuSerial">Reboot to Serial DFU</button>
  126. <span class="note" style="flex:1">Reboots the puck into serial DFU mode (adafruit-nrfutil). The device drops off USB — flash with <code>adafruit-nrfutil dfu serial …</code> then replug.</span>
  127. </div>
  128. <div class="row" style="margin:10px 0 0">
  129. <button id="dfuUf2">Reboot to UF2 Bootloader</button>
  130. <span class="note" style="flex:1">Reboots the puck into the UF2 mass-storage bootloader. It mounts as a USB drive — drag the <code>.uf2</code> file onto it to flash, then it reboots automatically.</span>
  131. </div>
  132. <div class="row" style="margin:18px 0 0;border-top:1px solid #4a2030;padding-top:14px">
  133. <button id="factoryErase" style="background:#3a1420;border-color:#7a2233;color:#ff9bb0;font-weight:600">⚠ Factory erase</button>
  134. <span class="note" style="flex:1"><strong style="color:#ff9bb0">Danger:</strong> wipes <em>all</em> persistent storage on the copycat — the paired controller bond <em>and</em> every saved setting (mode, chords, back-paddle map, sensitivity). The copycat reboots to factory defaults and you must <strong>re-pair the controller</strong>. This cannot be undone.</span>
  135. </div>
  136. </div>
  137. <div class="card" id="mouseCard">
  138. <h2>Trackpad mouse (lizard + Xbox)</h2>
  139. <div class="row"><label>Sensitivity</label><input type="range" id="mDiv" min="4" max="200" step="1"><span class="val" id="mDivV"></span></div>
  140. <div class="row"><label>Glide / friction</label><input type="range" id="mFric" min="0" max="99" step="1"><span class="val" id="mFricV"></span></div>
  141. <p class="note">Right-pad cursor in Steam-mode lizard (Steam closed) and in Xbox mode. Sensitivity is a divisor — lower = faster pointer. Glide = how long the cursor coasts after a flick.</p>
  142. </div>
  143. <div class="card">
  144. <h2>Rumble</h2>
  145. <div class="row"><label>Strength</label><input type="range" id="rumble" min="0" max="255" step="5"><span class="val" id="rumbleV"></span></div>
  146. <p class="note">Scales rumble amplitude across all modes (100% = native, 200% = double, 0% = off).</p>
  147. </div>
  148. <div class="card">
  149. <h2>Switch Pro motion</h2>
  150. <div class="row"><label>Report rate</label><select id="swRate"></select></div>
  151. <p class="note" style="margin:0 0 6px">Full rate (~250 Hz, default) is lowest-latency. 120 Hz is low-latency and drift-free. 66 Hz is a genuine-cadence compatibility fallback — drop to it only if your console rejects the faster rates.</p>
  152. <div class="row"><label>Gyro scale</label><select id="swGyro"></select></div>
  153. <p class="note">Gyro sensitivity multiplier for Switch Pro mode (1.0× = unchanged).</p>
  154. </div>
  155. <div class="card">
  156. <h2>Button mapping</h2>
  157. <p class="note" style="margin-top:0">Separate mappings per emulated controller type — each only offers targets that exist on that controller. The type matching the current mode is highlighted. Steam &amp; Lizard are native puck modes (Steam does its own remapping) and aren't configured here.</p>
  158. <div id="typeCfgs"></div>
  159. </div>
  160. <div class="card">
  161. <h2>Backup &amp; clone</h2>
  162. <p class="note" style="margin-top:0">Save this puck's controller pairings <em>and</em> every setting to a file, then restore them onto another puck. The other puck becomes a clone — any controller paired to this one connects to it with <strong>no re-pairing</strong>. (Also a plain backup: re-import after a factory erase to get everything back.)</p>
  163. <div class="row" style="margin:0;flex-wrap:wrap">
  164. <button id="backupExport" class="primary">Export to file…</button>
  165. <button id="backupImport">Import from file…</button>
  166. <input type="file" id="backupFile" accept="application/json,.json" style="display:none">
  167. </div>
  168. <p class="note">Import <strong>overwrites</strong> all pairings and settings on the connected puck, then reboots it (~2 s — reconnect after). Tip: pair every controller to one puck, export once, then import onto each spare.</p>
  169. </div>
  170. <div class="card logonly">
  171. <h2>Capture — host → controller commands</h2>
  172. <p class="note" style="margin-top:0">The firmware logs everything from boot into a big RAM ring: Steam's writes (<code>ifN</code>), the frames we transmit to the controller (<code>TX→ctlr</code>), and RF <code>LINK UP/DOWN</code> edges. For the reconnect buzz: trigger it (it appears moments after the puck boots / the controller reconnects), then connect here and click <b>Dump from boot</b> — the trigger is still in the ring. (Only present in a logging build, <code>-DOPK_LOG=1</code>.)</p>
  173. <div class="row" style="margin:0;flex-wrap:wrap">
  174. <button id="capStart" class="primary">Dump from boot</button>
  175. <button id="capStop" disabled>Stop</button>
  176. <button id="capDl">Download .txt</button>
  177. </div>
  178. <p class="note">Dump streams the whole ring (oldest→newest) and then keeps live-updating until you press Stop. <code>cmd</code> is the command/report byte, then the raw bytes.</p>
  179. <pre id="capOut" style="font:12px ui-monospace,Menlo,monospace;color:var(--fg);background:#0e1017;border:1px solid #232a3a;border-radius:8px;padding:10px;margin-top:10px;max-height:260px;overflow:auto;white-space:pre-wrap"></pre>
  180. </div>
  181. <div id="log"></div>
  182. </div>
  183. </div>
  184. <script>
  185. const MODE_NAMES = ["Steam (puck)","Xbox 360","Switch (HORIPAD)","Lizard (always)","Switch Pro + gyro","PS5 DualSense","HID gyro (DS4)","PS5 (game/clean)","DS4 (game/clean)"];
  186. const CHORD_FIELD = [17, 18, 19];
  187. let dev=null, epIn=0, epOut=0, ifNum=0, polling=false, capturing=false, backupBusy=false;
  188. let lastP=null; // most recent status-blob payload (config source for Export)
  189. const $ = s=>document.querySelector(s);
  190. function log(m){ const l=$("#log"); l.textContent=(new Date().toLocaleTimeString()+" "+m+"\n"+l.textContent).slice(0,2000); }
  191. // Per-emulated-type config (must match firmware ET_* order: Xbox=0, Switch=1, DS4=2, DS5=3). Each type lists
  192. // only the remap targets that exist on that controller. Field id sent to firmware = 40 + et*8 + k
  193. // (k: 0..3 back paddles, 4 QAM, 5 A/B-swap, 6 trackpad-haptics, 7 LED brightness). Blob v10 reads them back at p[73 + et*8 + ...].
  194. const DPAD = {12:"D-pad Up",13:"D-pad Down",14:"D-pad Left",15:"D-pad Right"};
  195. const TYPE_DEFS = [
  196. {key:"XBOX", name:"Xbox", labels:{1:"A",2:"B",3:"X",4:"Y",5:"LB",6:"RB",7:"L3",8:"R3",9:"Back",10:"Start",11:"Guide",19:"LT",20:"RT",...DPAD}},
  197. {key:"SWITCH", name:"Switch", labels:{1:"A",2:"B",3:"X",4:"Y",5:"L",6:"R",7:"L-Stick",8:"R-Stick",9:"Minus",10:"Plus",11:"Home",19:"ZL",20:"ZR",...DPAD,18:"Capture / Screenshot"}},
  198. {key:"DS4", name:"DS4", labels:{1:"Cross",2:"Circle",3:"Square",4:"Triangle",5:"L1",6:"R1",7:"L3",8:"R3",9:"Create",10:"Options",11:"PS",19:"L2",20:"R2",...DPAD,16:"Touchpad Click"}},
  199. {key:"DS5", name:"DS5", labels:{1:"Cross",2:"Circle",3:"Square",4:"Triangle",5:"L1",6:"R1",7:"L3",8:"R3",9:"Create",10:"Options",11:"PS",19:"L2",20:"R2",...DPAD,16:"Touchpad Click",17:"Mute"}},
  200. ];
  201. // Which emulated type a USB mode belongs to (mirror of firmware etypeForMode); -1 = puck mode (no type).
  202. function etypeForMode(m){ switch(m){case 1:return 0; case 2:case 4:return 1; case 6:case 8:return 2; case 5:case 7:return 3; default:return -1;} }
  203. const BACK_LABELS = ["L4 (back upper-left)","R4 (back upper-right)","L5 (back lower-left)","R5 (back lower-right)"];
  204. const typeEls = []; // one entry per TYPE_DEFS: {sec, tab, activeDot, back[], qam, abSwap, pad, led, ledV}
  205. function mkSelect(def, includeNone){
  206. const sel=document.createElement("select");
  207. if(includeNone){ const o=document.createElement("option"); o.value=0; o.textContent="— none —"; sel.appendChild(o); }
  208. else { const o=document.createElement("option"); o.value=0; o.textContent="Default (per-mode)"; sel.appendChild(o); }
  209. for(const c of Object.keys(def.labels).map(Number).sort((a,b)=>a-b)){
  210. const o=document.createElement("option"); o.value=c; o.textContent=def.labels[c]; sel.appendChild(o); }
  211. return sel;
  212. }
  213. let curTab=0, tabInited=false;
  214. function setTab(et){
  215. curTab=et;
  216. typeEls.forEach((rec,i)=>{
  217. rec.sec.style.display = (i===et) ? "" : "none";
  218. rec.tab.classList.toggle("active", i===et);
  219. });
  220. }
  221. (function buildTypeCfgs(){
  222. const host=document.getElementById("typeCfgs");
  223. const bar=document.createElement("div"); bar.style.cssText="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:12px";
  224. host.appendChild(bar);
  225. TYPE_DEFS.forEach((def,et)=>{
  226. // tab button
  227. const tab=document.createElement("button"); tab.className="slot-tab"; tab.style.cursor="pointer";
  228. tab.innerHTML='<span>'+def.name+'</span><span class="active-dot" style="display:none;font-size:11px;color:var(--acc)"> ●</span>';
  229. tab.onclick=()=>setTab(et); bar.appendChild(tab);
  230. // panel
  231. const sec=document.createElement("div"); sec.style.cssText="background:#0e1017;border:1px solid #232a3a;border-radius:8px;padding:12px 14px;display:none";
  232. const rec={sec,tab,activeDot:tab.querySelector(".active-dot"),back:[],qam:null,abSwap:null,pad:null,led:null,ledV:null};
  233. // A/B swap + trackpad haptics toggles
  234. const tog=document.createElement("div"); tog.className="row";
  235. tog.innerHTML='<label>A/B + X/Y swap</label>';
  236. const ab=document.createElement("button"); ab.textContent="off"; tog.appendChild(ab);
  237. const padLbl=document.createElement("label"); padLbl.textContent="Trackpad haptics"; padLbl.style.marginLeft="14px"; tog.appendChild(padLbl);
  238. const pad=document.createElement("button"); pad.textContent="on"; tog.appendChild(pad);
  239. sec.appendChild(tog);
  240. rec.abSwap=ab; rec.pad=pad;
  241. ab.onclick=()=>{ const on=ab.classList.contains("active"); setField(40+et*8+5, on?0:1); };
  242. pad.onclick=()=>{ const on=pad.classList.contains("active"); setField(40+et*8+6, on?0:1); };
  243. // back paddles
  244. for(let i=0;i<4;i++){
  245. const row=document.createElement("div"); row.className="row";
  246. const lab=document.createElement("label"); lab.textContent=BACK_LABELS[i]; row.appendChild(lab);
  247. const sel=mkSelect(def,true); row.appendChild(sel); sec.appendChild(row);
  248. sel.addEventListener("change",()=>setField(40+et*8+i, +sel.value));
  249. rec.back.push(sel);
  250. }
  251. // QAM
  252. { const row=document.createElement("div"); row.className="row";
  253. const lab=document.createElement("label"); lab.textContent="QAM (3 dots)"; row.appendChild(lab);
  254. const sel=mkSelect(def,false); row.appendChild(sel); sec.appendChild(row);
  255. sel.addEventListener("change",()=>setField(40+et*8+4, +sel.value));
  256. rec.qam=sel; }
  257. // LED brightness
  258. { const row=document.createElement("div"); row.className="row";
  259. const lab=document.createElement("label"); lab.textContent="LED brightness"; row.appendChild(lab);
  260. const sl=document.createElement("input"); sl.type="range"; sl.min=0; sl.max=100; sl.step=5; row.appendChild(sl);
  261. const vspan=document.createElement("span"); vspan.className="val"; row.appendChild(vspan);
  262. function fmtLed(v){ return (+v===0)?"Auto":v+"%"; }
  263. sl.addEventListener("input",()=>{ vspan.textContent=fmtLed(sl.value); });
  264. sl.addEventListener("change",()=>setField(40+et*8+7, +sl.value));
  265. sec.appendChild(row);
  266. rec.led=sl; rec.ledV=vspan; }
  267. host.appendChild(sec); typeEls.push(rec);
  268. });
  269. setTab(0);
  270. })();
  271. for(const sel of document.querySelectorAll("select.chord")){
  272. MODE_NAMES.forEach((n,i)=>{ if(i===7||i===8) return;
  273. const o=document.createElement("option"); o.value=i; o.textContent=n; sel.appendChild(o); });
  274. }
  275. { const sel=document.getElementById("swRate");
  276. for(const [lbl,v] of [["Full rate (~250 Hz, default)",2],["120 Hz",1],["66 Hz (compatibility)",0]]){
  277. const o=document.createElement("option"); o.value=v; o.textContent=lbl; sel.appendChild(o); }
  278. }
  279. { const sel=document.getElementById("swGyro");
  280. for(const [lbl,v] of [["0.5×",5],["1.0×",10],["1.5×",15],["2.0×",20],["2.5×",25],["3.0×",30]]){
  281. const o=document.createElement("option"); o.value=v; o.textContent=lbl; sel.appendChild(o); }
  282. }
  283. // ---- per-slot tab state ----
  284. let g_activeSlot = 0;
  285. let g_slotData = []; // [{up, battery, rssi}] indexed by slot 0..3, only set for bonded slots
  286. function updateSlotDisplay(slotIdx) {
  287. const d = g_slotData[slotIdx];
  288. if (!d) { $("#stLink").innerHTML="—"; $("#stBatt").textContent="—"; $("#stRssi").textContent="—"; return; }
  289. $("#stLink").innerHTML = d.up ? '<span class="pill up">up</span>' : '<span class="pill dn">down</span>';
  290. $("#stBatt").textContent = (d.up && d.battery) ? d.battery+"%" : "—";
  291. $("#stRssi").textContent = (d.up && d.rssi) ? ("-"+d.rssi+" dBm") : "—";
  292. }
  293. function renderSlotTabs(bondedCount) {
  294. const bar = $("#slotTabs");
  295. if (bondedCount <= 1) { bar.style.display="none"; updateSlotDisplay(g_activeSlot); return; }
  296. bar.style.display="flex";
  297. bar.innerHTML="";
  298. for (let s=0; s<4; s++) {
  299. const d = g_slotData[s];
  300. if (!d) continue;
  301. const btn = document.createElement("button");
  302. btn.className = "slot-tab" + (s===g_activeSlot ? " active" : "");
  303. const dot = document.createElement("span");
  304. dot.className = "dot" + (d.up ? " up" : "");
  305. btn.appendChild(dot);
  306. btn.appendChild(document.createTextNode("Controller "+(s+1)));
  307. btn.onclick = () => { g_activeSlot=s; renderSlotTabs(bondedCount); };
  308. bar.appendChild(btn);
  309. }
  310. updateSlotDisplay(g_activeSlot);
  311. }
  312. const USB_FILTERS=[{vendorId:0x28DE},{vendorId:0x045E},{vendorId:0x057E},{vendorId:0x0F0D},{vendorId:0x054C}];
  313. // Acquire+set up an already-chosen USBDevice (shared by the manual picker and the no-picker auto-reconnect).
  314. async function openDevice(d){
  315. try{
  316. dev=d;
  317. await dev.open();
  318. if(dev.configuration===null) await dev.selectConfiguration(1);
  319. let found=null;
  320. for(const itf of dev.configuration.interfaces){
  321. const a=itf.alternate;
  322. if(a.interfaceClass!==0xFF) continue;
  323. if(a.interfaceSubClass===0x5D) continue;
  324. let bin=0,bout=0;
  325. for(const e of a.endpoints){ if(e.type==="bulk"){ if(e.direction==="in")bin=e.endpointNumber; else bout=e.endpointNumber; } }
  326. if(bin&&bout){ found={ifNum:itf.interfaceNumber, epIn:bin, epOut:bout}; break; }
  327. }
  328. if(!found){ log("no WebUSB bulk vendor interface — reflash firmware with WebUSB enabled, or another app may be holding the device"); dev=null; return false; }
  329. ifNum=found.ifNum; epIn=found.epIn; epOut=found.epOut;
  330. await dev.claimInterface(ifNum);
  331. await dev.controlTransferOut({requestType:"class", recipient:"interface", request:0x22, value:0x01, index:ifNum});
  332. $("#connState").textContent="connected"; $("#connState").className="pill up";
  333. $("#connState").title = dev.serialNumber ? ("puck serial "+dev.serialNumber) : "";
  334. $("#connectBtn").textContent="Reconnect";
  335. $("#panel").classList.remove("hide");
  336. log(`connected — puck ${dev.serialNumber||"?"} (VID ${dev.vendorId.toString(16)} iface ${ifNum})`);
  337. startPolling();
  338. return true;
  339. }catch(e){ log("connect failed: "+e.message); dev=null; return false; }
  340. }
  341. // Manual connect: shows the Chrome device picker (needed once, to authorize the device).
  342. async function connect(){
  343. try{ const d = await navigator.usb.requestDevice({filters:USB_FILTERS}); await openDevice(d); }
  344. catch(e){ log("connect failed: "+e.message); }
  345. }
  346. // No-picker reconnect: reopen a device already authorized this browser. Returns true if it connected.
  347. async function autoConnect(){
  348. if(dev) return true;
  349. try{
  350. const ds = await navigator.usb.getDevices();
  351. const d = ds.find(x=>USB_FILTERS.some(f=>f.vendorId===x.vendorId));
  352. if(d) return await openDevice(d);
  353. }catch(e){}
  354. return false;
  355. }
  356. function onGone(){
  357. polling=false; dev=null; tabInited=false; // re-default the config tab to the mode on next connect
  358. $("#connState").textContent="reconnecting…"; $("#connState").className="pill dn";
  359. $("#panel").classList.add("hide");
  360. log("device disconnected (mode-switch / watchdog reboot) — auto-reconnecting when it returns");
  361. // The puck re-enumerates after a reboot; retry without the picker. The "connect" event also triggers this,
  362. // but poll a few times in case the event is missed.
  363. let tries=0;
  364. const iv=setInterval(async()=>{ if(dev||tries++>40){ clearInterval(iv); return; } if(await autoConnect()) clearInterval(iv); }, 500);
  365. }
  366. // Auto-reconnect when an authorized puck (re)appears — no button, no picker.
  367. navigator.usb && navigator.usb.addEventListener("connect", e=>{ if(!dev) autoConnect(); });
  368. navigator.usb && navigator.usb.addEventListener("disconnect", e=>{ if(e.device===dev) onGone(); });
  369. async function send(bytes){
  370. if(!dev) return;
  371. try{ await dev.transferOut(epOut, new Uint8Array(bytes)); }
  372. catch(e){ log("write err: "+e.message); }
  373. }
  374. // Read one framed reply and return its payload (with the 2-byte [marker][len] header stripped). The blob and
  375. // the bond-export dump share the same framing, distinguished by the marker byte (0xA5 status, 0xA7 bonds).
  376. async function readFrame(marker, minLen){
  377. try{
  378. // largest frame (status blob) spans multiple USB-FS packets; read generously to capture it in one call.
  379. const r = await dev.transferIn(epIn, 192);
  380. if(r.status!=="ok"||r.data.byteLength<2) return null;
  381. const d=new Uint8Array(r.data.buffer);
  382. let i=0; while(i<d.length && d[i]!==marker) i++;
  383. if(i+2>d.length) return null;
  384. const len=d[i+1]; const p=d.slice(i+2, i+2+len);
  385. return p.length>=(minLen||0) ? p : null;
  386. }catch(e){ if(dev) log("read err: "+e.message); return null; }
  387. }
  388. async function readBlob(){ return readFrame(0xA5, 12); }
  389. function applyBlob(p){
  390. lastP=p; // remember for Export (carries every config field the panel shows)
  391. const mode=p[1], mDiv=p[2], mFric=p[3]; // p[4..11] mirror the active type (per-type block below is authoritative)
  392. const slot=p[10], up=p[11], f1=(p[12]|(p[13]<<8));
  393. const newps=(p.length>16?(p[15]|(p[16]<<8)):0), persistMode=(p.length>22?p[22]:0);
  394. const chord=(p.length>25)?[p[23],p[24],p[25]]:[3,1,4];
  395. const polls=(p.length>27?(p[26]|(p[27]<<8)):0);
  396. const loopUs=(p.length>29?(p[28]|(p[29]<<8)):0);
  397. const worstIdx=(p.length>30?p[30]:0), worstUs=(p.length>32?(p[31]|(p[32]<<8)):0);
  398. const WORST=["webusb","ctrl.task","serial","rfdiag","rflink","haptic","led"];
  399. const pollUs=(p.length>34?(p[33]|(p[34]<<8)):0);
  400. const pollIntended=(p.length>14?p[14]*100:0);
  401. const logEnabled=(p.length>35?p[35]:0);
  402. for(const el of document.querySelectorAll(".logonly")) el.style.display = logEnabled ? "" : "none";
  403. for(const b of document.querySelectorAll(".modebtn")) b.classList.toggle("active", +b.dataset.mode===mode);
  404. $("#mouseCard").style.opacity = (mode===1||mode===3)?1:0.5;
  405. const battery=(p.length>36?p[36]:0);
  406. const rumbleScale=(p.length>51?p[51]:200);
  407. const swProRate=(p.length>52?p[52]:2);
  408. const swGyro10=(p.length>53?p[53]:10);
  409. const rssi=(p.length>37?p[37]:0);
  410. // per-slot link status (protocol v8, p.length >= 73)
  411. const hasSlotsData = p.length >= 73;
  412. if (hasSlotsData) {
  413. const bondedN = p[60];
  414. g_slotData = [];
  415. for (let s=0; s<4; s++) {
  416. const base = 61 + s*3;
  417. if (p.length >= base+3) {
  418. // only include bonded slots (a slot with up=0 could be bonded but offline)
  419. // check if the slot appears at all in the bonded map by checking if bondedN covers it;
  420. // the firmware only sets non-zero battery/rssi for actually-bonded slots
  421. const slotUp = !!p[base];
  422. const slotBatt = p[base+1];
  423. const slotRssi = p[base+2];
  424. // slot is "bonded" if firmware included it in bondedN coverage
  425. // we populate slotData for all 4 and renderSlotTabs skips gaps
  426. g_slotData[s] = {up: slotUp, battery: slotBatt, rssi: slotRssi};
  427. }
  428. }
  429. // keep only bonded slots by cross-referencing bondedN
  430. // firmware sends bondedSlotCount but not a slot bitmask; use battery>0 || rssi>0 || up as presence hint
  431. // simpler: just count how many of the 4 slots have any non-zero data OR are marked up
  432. // Actually the firmware always writes all 4 slots; we filter by the bond system's "used" flag via presence.
  433. // For clean display: we'll show tabs only for slots that have ever had a reply OR are bonded (battery/rssi set).
  434. // The firmware sets g_battery[s]=0 and g_linkRssi[s]=0 for unused slots, so 0/0/0 = not bonded.
  435. // But a bonded offline slot also has 0/0/0 initially. We rely on bondedN for count and show the first bondedN slots
  436. // that have g_slot[s].used — but we can't easily know which slots are used from the blob.
  437. // Best heuristic: show all 4 slots if bondedN==4, otherwise use slot indices where battery or rssi != 0 OR up==1,
  438. // OR fall back to showing slots 0..bondedN-1 if none have data yet (device just booted).
  439. let bondedSlots = [];
  440. for (let s=0; s<4; s++) {
  441. if (g_slotData[s] && (g_slotData[s].up || g_slotData[s].battery || g_slotData[s].rssi)) bondedSlots.push(s);
  442. }
  443. // fallback: if no data yet (all offline, just booted), show slots 0..bondedN-1
  444. if (bondedSlots.length === 0 && bondedN > 0) {
  445. for (let s=0; s<bondedN; s++) bondedSlots.push(s);
  446. }
  447. // remove slotData for non-bonded slots so tabs don't appear for them
  448. const bondedSet = new Set(bondedSlots);
  449. for (let s=0; s<4; s++) { if (!bondedSet.has(s)) g_slotData[s] = null; }
  450. // clamp active slot to a valid bonded slot
  451. if (!g_slotData[g_activeSlot]) g_activeSlot = bondedSlots[0] || 0;
  452. renderSlotTabs(bondedN);
  453. } else {
  454. // old firmware: single-slot display
  455. $("#slotTabs").style.display="none";
  456. $("#stLink").innerHTML = up? '<span class="pill up">up</span>' : '<span class="pill dn">down</span>';
  457. $("#stBatt").textContent = (up && battery)? battery+"%" : "—";
  458. $("#stRssi").textContent = (up && rssi)? ("-"+rssi+" dBm") : "—";
  459. }
  460. // global stats
  461. $("#stRate").textContent = up? f1+" /s" : "—";
  462. $("#stNew").textContent = up? newps+" /s" : "—";
  463. // Poll TX + RF-fail counts: shown ALWAYS (even when the link reads down) so a wedge is diagnosable --
  464. // polls>0 here while Delivered is "—" means the puck is still polling but getting no usable replies.
  465. $("#stPolls").textContent = polls+" /s";
  466. { const crc=(p.length>113?p[113]:0), norx=(p.length>114?p[114]:0), heal=(p.length>115?p[115]:0);
  467. const rf=(p.length>126?(p[125]|(p[126]<<8)):0);
  468. $("#stRfFail").innerHTML = crc+" · "+norx+" · "+heal + (rf?' · <span class="pill dn">ring '+rf+'</span>':"");
  469. // ring fault = we caught+recovered a relay-ring corruption that would otherwise be an invisible IRQ-off
  470. // watchdog hang. Log each new one (persists across the device reset + panel reconnect).
  471. if(rf>(window._ringFault||0)) log("⚠ RING FAULT #"+rf+" recovered — caught a relay-ring desync/corruption (would have hung loop with IRQs off)");
  472. window._ringFault=rf; }
  473. // v12: relay-frame rate + clock fingerprint (browser index = firmware index − 2)
  474. { const relay=(p.length>117?(p[116]|(p[117]<<8)):null);
  475. $("#stRelay").textContent = relay==null ? "—" : (relay+" /s"); }
  476. if(p.length>121){
  477. const LF=["stopped","RC","xtal","synth"], HF=["RC","?","xtal","?"];
  478. const lf=p[118], hf=p[119], upm=(p[120]|(p[121]<<8));
  479. const lfBad=(lf!==2), hfBad=(hf!==2), upmBad=(upm && (upm<985||upm>1015));
  480. const tag=(t,bad)=> bad ? '<span class="pill dn">'+t+'</span>' : t;
  481. $("#stClock").innerHTML = tag(LF[lf]||lf, lfBad)+" / "+tag(HF[hf]||hf, hfBad);
  482. $("#stUsPerMs").innerHTML = upm ? tag(""+upm, upmBad) : "—";
  483. }
  484. // v12: LIVE loop heartbeat — curStage (firmware p[125]) + ms-since-beat (p[126], 40ms units). Updates even
  485. // while loop() is wedged (blob is pushed from the SOF interrupt), so a hang shows "STALLED @ <stage>" live.
  486. if(p.length>124){
  487. const STAGE=["webusb","ctrl.task","serial","rfdiag","rflink","haptic","led","usbmount","usbtx"];
  488. const cur=p[123], stallMs=p[124]*40, name=(STAGE[cur]||("stage "+cur));
  489. if(stallMs>=200){
  490. $("#stLoopState").innerHTML='<span class="pill dn">STALLED @ '+name+' '+stallMs+'ms</span>';
  491. // Latch+log the stall so it survives the imminent watchdog reset + panel reconnect (host-side log
  492. // persists). Log once per episode + keep escalating if it climbs toward the ~8s watchdog.
  493. if(!window._stallEpisode || stallMs>window._stallPeak+800){
  494. window._stallEpisode=true; window._stallPeak=stallMs;
  495. log("⚠ LOOP STALL @ "+name+" ("+stallMs+"ms) — watchdog reset imminent");
  496. }
  497. } else {
  498. window._stallEpisode=false; window._stallPeak=0;
  499. $("#stLoopState").innerHTML='<span class="pill up">running</span>';
  500. }
  501. }
  502. $("#stLoop").textContent = loopUs? loopUs+" µs" : "—";
  503. $("#stWorst").textContent = loopUs? (WORST[worstIdx]||worstIdx)+" "+worstUs+"µs" : "—";
  504. $("#stPollPer").textContent = up? (pollUs+" / "+pollIntended+" µs") : "—";
  505. // last-boot reset cause (protocol v11): a single classified code (firmware classifies it from RESETREAS +
  506. // a GPREGRET2 marker) plus the raw RESETREAS. Codes match RR_* in fault_diag.h. Earlier firmware (<v11)
  507. // didn't send this -> guard on length and leave the tile blank.
  508. const RR_NAMES = ["unknown","power-on","pin/replug","watchdog (hang)","CPU lockup",
  509. "HARDFAULT","reboot","soft reset","wake-from-off"];
  510. const RR_FAULT = new Set([3,4,5]); // watchdog / lockup / hardfault = a real crash worth reporting (#72)
  511. if (p.length > 109) {
  512. const code = p[105];
  513. const raw = ((p[106]|(p[107]<<8)|(p[108]<<16)|(p[109]<<24))>>>0);
  514. const name = RR_NAMES[code] || ("code "+code);
  515. // v12: which loop stage was stuck when the last watchdog/lockup hang fired (0xFF = last boot wasn't a hang)
  516. const STAGE_NAMES = ["webusb","ctrl.task","serial","rfdiag","rflink","haptic","led","usbmount","usbtx"];
  517. const hangStage = (p.length>122 ? p[122] : 0xFF);
  518. let label = name;
  519. if (hangStage!==0xFF) label += " @ "+(STAGE_NAMES[hangStage]||("stage "+hangStage));
  520. $("#stReset").innerHTML = RR_FAULT.has(code) ? ('<span class="pill dn">'+label+'</span>') : label;
  521. const el = $("#resetHist");
  522. if (el) el.textContent = "RESETREAS=0x"+raw.toString(16).padStart(8,"0")
  523. + (hangStage!==0xFF ? " hung in: "+(STAGE_NAMES[hangStage]||hangStage) : "");
  524. }
  525. const gitDirty=(p.length>38?p[38]:0); let gitHash="";
  526. for(let i=39;i<51 && i<p.length && p[i];i++) gitHash+=String.fromCharCode(p[i]);
  527. $("#stBuild").innerHTML = gitHash
  528. ? (gitHash + (gitDirty ? ' <span class="pill dn">dirty</span>' : ' <span class="pill up">clean</span>'))
  529. : "—";
  530. setSlider("mDiv",mDiv); setSlider("mFric",mFric); setSlider("rumble",rumbleScale);
  531. $("#persistMode").textContent = persistMode? "on":"off"; $("#persistMode").classList.toggle("active",!!persistMode);
  532. // per-type button config (blob v10): 4 types x 8 bytes. readBlob() strips the 2-byte [0xA5][len] header, so
  533. // the firmware's buffer index 75 lands at JS index 73 here.
  534. if(p.length>=73+TYPE_DEFS.length*8){
  535. const activeEt=etypeForMode(mode);
  536. typeEls.forEach((rec,et)=>{
  537. const q=73+et*8;
  538. const back=[p[q],p[q+1],p[q+2],p[q+3]], qam=p[q+4], ab=p[q+5], pad=p[q+6], led=p[q+7];
  539. rec.back.forEach((sel,i)=>{ if(document.activeElement!==sel) sel.value=back[i]; });
  540. if(document.activeElement!==rec.qam) rec.qam.value=qam;
  541. rec.abSwap.textContent=ab?"on":"off"; rec.abSwap.classList.toggle("active",!!ab);
  542. rec.pad.textContent=pad?"on":"off"; rec.pad.classList.toggle("active",!!pad);
  543. if(document.activeElement!==rec.led){ rec.led.value=led; rec.ledV.textContent=(led===0)?"Auto":led+"%"; }
  544. // dot marks the type matching the current puck mode
  545. rec.activeDot.style.display = (et===activeEt) ? "" : "none";
  546. });
  547. // open the tab for the current mode's type on first load (then leave the user's choice alone)
  548. if(!tabInited){ tabInited=true; setTab(activeEt>=0?activeEt:0); }
  549. }
  550. if(p.length>=60){ const s16=(o)=>{ let v=p[o]|(p[o+1]<<8); return v>32767?v-65536:v; };
  551. const ax=s16(54),ay=s16(56),az=s16(58);
  552. const amag=Math.round(Math.sqrt(ax*ax+ay*ay+az*az));
  553. $("#stImu").textContent = `a=(${ax}, ${ay}, ${az}) |a|=${amag}`;
  554. }
  555. { const sel=$("#swRate"); if(document.activeElement!==sel) sel.value=swProRate; }
  556. { const sel=$("#swGyro"); if(document.activeElement!==sel) sel.value=swGyro10; }
  557. for(const sel of document.querySelectorAll("select.chord")){ if(document.activeElement!==sel) sel.value=chord[+sel.dataset.i]; }
  558. }
  559. function fmtSlider(id,v){ return id==="rumble" ? v+"%" : ""+v; }
  560. function setSlider(id,v){ const el=$("#"+id); if(document.activeElement!==el){ el.value=v; } $("#"+id+"V").textContent=fmtSlider(id,el.value); }
  561. let inflight=false;
  562. async function refresh(){
  563. if(!dev||inflight||capturing||backupBusy) return; inflight=true;
  564. await send([0x01]); const p=await readBlob(); if(p) applyBlob(p);
  565. inflight=false;
  566. }
  567. // ---- Backup / clone ----
  568. // A backup file is { magic, version, bonds[4], config{} }. bonds come from the 0x09 export (0xA7 frame); the
  569. // config fields come from the status blob the panel already reads. Restoring replays every setting via the
  570. // normal 0x02 setters, then sends the 0x0D bond-import which writes the pairings, applies the mode and reboots.
  571. function hexEnc(arr){ return [...arr].map(x=>x.toString(16).padStart(2,"0")).join(""); }
  572. function hexDec(h){ const a=[]; if(!h) return a; for(let i=0;i+1<h.length;i+=2) a.push(parseInt(h.substr(i,2),16)); return a; }
  573. function buildBackup(p, bp){
  574. const mask=bp[1], bonds=[];
  575. for(let s=0;s<4;s++){ const rec=bp.slice(2+s*24, 2+s*24+24);
  576. bonds.push({slot:s, used:!!((mask>>s)&1), rec:hexEnc(rec)}); }
  577. const types=[];
  578. for(let et=0; et<TYPE_DEFS.length; et++){ const q=73+et*8;
  579. types.push({back:[p[q],p[q+1],p[q+2],p[q+3]], qam:p[q+4], abSwap:p[q+5], pad:p[q+6], led:p[q+7]}); }
  580. return { magic:"openpuck-backup", version:1, bonds,
  581. config:{ mode:p[1], mDiv:p[2], mFric:p[3], persistMode:p[22], chord:[p[23],p[24],p[25]],
  582. rumble:p[51], swProRate:p[52], swGyro10:p[53], types } };
  583. }
  584. function downloadBackup(obj){
  585. const ts=new Date().toISOString().slice(0,19).replace(/[:T]/g,"-");
  586. const a=document.createElement("a");
  587. a.href=URL.createObjectURL(new Blob([JSON.stringify(obj,null,2)],{type:"application/json"}));
  588. a.download="openpuck-backup-"+ts+".json"; a.click();
  589. }
  590. // let any in-flight poll read settle before we drive the shared endpoints ourselves
  591. async function waitIdle(){ for(let i=0;i<60 && inflight;i++) await new Promise(r=>setTimeout(r,5)); }
  592. async function exportBackup(){
  593. if(!dev){ log("not connected"); return; }
  594. backupBusy=true; await waitIdle();
  595. try{
  596. // grab a fresh config snapshot, then the bond dump
  597. await send([0x01]); const cfg=await readBlob(); if(cfg) lastP=cfg;
  598. if(!lastP){ log("export: no config snapshot yet — wait a second and retry"); return; }
  599. await send([0x09]);
  600. let bp=null;
  601. for(let t=0; t<8 && !bp; t++) bp=await readFrame(0xA7, 2+4*24);
  602. if(!bp){ log("export: no bond data (firmware too old for 0x09 export — reflash)"); return; }
  603. const backup=buildBackup(lastP, bp);
  604. downloadBackup(backup);
  605. const n=backup.bonds.filter(b=>b.used).length;
  606. log("exported backup — "+n+" bonded controller slot(s) + all settings");
  607. } finally { backupBusy=false; }
  608. }
  609. async function importBackup(file){
  610. if(!dev){ log("not connected"); return; }
  611. let obj; try{ obj=JSON.parse(await file.text()); }
  612. catch(e){ log("import: not valid JSON"); return; }
  613. if(obj.magic!=="openpuck-backup" || !obj.bonds || !obj.config){ log("import: unrecognized backup file"); return; }
  614. const bondedN=obj.bonds.filter(b=>b.used).length;
  615. if(!confirm("Restore this backup onto the CONNECTED puck (serial "+(dev.serialNumber||"?")+")?\n\nMake sure this is the TARGET puck, not the one you exported from — the panel only talks to the puck you last connected.\n\nThis OVERWRITES its "+bondedN+" controller pairing(s) and ALL settings, then reboots it.\n\nResult: any controller paired to the original puck will connect to this one with no re-pairing.")) return;
  616. log("importing onto puck "+(dev.serialNumber||"?"));
  617. backupBusy=true; await waitIdle();
  618. try{
  619. // Capability probe: the connected puck MUST run firmware new enough to answer 0x09 with a 0xA7 frame,
  620. // otherwise it will silently ignore the 0x0D bond-import below. This is the #1 import failure: the panel
  621. // is connected to a puck still on old firmware. Catch it loudly instead of "nothing happened".
  622. await send([0x09]);
  623. let probe=null; for(let t=0;t<8 && !probe;t++) probe=await readFrame(0xA7, 2+4*24);
  624. if(!probe){
  625. log("import ABORTED — the connected puck does not support import (old firmware).");
  626. alert("This puck's firmware is too old to import a backup.\n\nFlash it with the latest OpenPuck build (the same one that produced the export), reconnect, then import again.");
  627. return;
  628. }
  629. const c=obj.config;
  630. // Every step is a write-then-read transaction (same shape as the proven 0x02 sliders): the firmware acks
  631. // each with a status blob, which we read back to keep the OUT pipe flowing and naturally pace the writes.
  632. const w=async(bytes)=>{ await send(bytes); await readBlob(); };
  633. const sf=async(f,v)=>{ await w([0x02, f, (v|0)&0xff]); };
  634. // replay every setting (each persists; none reboot). mode is applied by the 0x0E commit below.
  635. await sf(1,c.mDiv); await sf(2,c.mFric); await sf(22,c.rumble); await sf(16,c.persistMode?1:0);
  636. await sf(17,c.chord[0]); await sf(18,c.chord[1]); await sf(19,c.chord[2]);
  637. await sf(23,c.swProRate); await sf(24,c.swGyro10);
  638. for(let et=0; et<c.types.length && et<4; et++){ const t=c.types[et];
  639. for(let k=0;k<4;k++) await sf(40+et*8+k, t.back[k]);
  640. await sf(40+et*8+4, t.qam); await sf(40+et*8+5, t.abSwap?1:0);
  641. await sf(40+et*8+6, t.pad?1:0); await sf(40+et*8+7, t.led); }
  642. log("settings replayed ("+(9+c.types.length*8)+" fields)");
  643. // write each bond slot with its own small command [0x0D][slot][used][24-byte rec]
  644. let n=0;
  645. for(let s=0;s<4;s++){
  646. const b=obj.bonds.find(x=>x.slot===s) || {used:false, rec:""};
  647. const rec=hexDec(b.rec), r24=new Array(24).fill(0);
  648. for(let i=0;i<24 && i<rec.length;i++) r24[i]=rec[i];
  649. const used=(b.used && rec.length===24)?1:0; if(used) n++;
  650. await w([0x0D, s, used, ...r24]);
  651. }
  652. log("wrote "+n+" bond slot(s) — committing + rebooting");
  653. // commit: persist bonds, apply mode, reboot (no ack — the device reboots)
  654. await send([0x0E, (c.mode!==undefined?c.mode:0xFF)&0xff]);
  655. log("import sent — puck is cloning and rebooting. Reconnect after it returns.");
  656. } finally { backupBusy=false; }
  657. }
  658. async function setField(field,value){
  659. await send([0x02, field, value&0xff]); const p=await readBlob(); if(p) applyBlob(p);
  660. }
  661. function fmtCapEntry(e,maxMs){
  662. const hex=e.bytes.map(x=>x.toString(16).padStart(2,"0")).join(" ");
  663. const t = `-${String(maxMs-e.ms).padStart(6," ")}ms `;
  664. if(e.slot===0xFD){ const k=e.bytes[0]; return `${t}════════ ${k===2?"RECONNECT (block+reinit armed)":k===1?"RF LINK UP":"RF LINK DOWN"} ════════`; }
  665. if(e.slot===0xFC){ return `${t}GET←host rid=${e.rid.toString(16).padStart(2,"0")} n=${e.nb}: ${hex}`; } // host feature GET (battery poll lives here)
  666. if(e.slot===0xFB){ return `${t}→host rid=${e.rid.toString(16).padStart(2,"0")} n=${e.nb}: ${hex}`; } // pushed device→host status (0x43 battery / 0x7B / 0x79)
  667. const who = (e.slot===0xFE) ? "TX→ctlr " : `if${e.slot} `;
  668. return `${t}${who} cmd=${e.rid.toString(16).padStart(2,"0")} n=${e.nb}: ${hex}`;
  669. }
  670. function downloadCap(){
  671. const t=window._lastCap||$("#capOut").textContent||"";
  672. const a=document.createElement("a");
  673. a.href=URL.createObjectURL(new Blob([t],{type:"text/plain"}));
  674. a.download="puck-capture.txt"; a.click();
  675. }
  676. let liveTimer=null, draining=false, capLines=[];
  677. function renderCap(){
  678. if(!capLines.length){ $("#capOut").textContent="(nothing captured yet)"; window._lastCap=""; return; }
  679. const maxMs=capLines[capLines.length-1].ms;
  680. const t=capLines.map(e=>fmtCapEntry(e,maxMs)).join("\n");
  681. $("#capOut").textContent=t; window._lastCap=t;
  682. }
  683. async function drainTick(){
  684. if(!dev||draining) return; draining=true;
  685. let acc=new Uint8Array(0);
  686. try{
  687. await send([0x06]);
  688. let done=false, guard=0;
  689. while(!done && guard++<400){
  690. const r=await dev.transferIn(epIn,64);
  691. if(r.status!=="ok") break;
  692. const d=new Uint8Array(r.data.buffer);
  693. const m=new Uint8Array(acc.length+d.length); m.set(acc); m.set(d,acc.length); acc=m;
  694. let i=0;
  695. while(i<acc.length){
  696. if(acc[i]!==0xA6){ i++; continue; }
  697. if(i+2>acc.length) break;
  698. const L=acc[i+1]; if(i+2+L>acc.length) break;
  699. const f=acc.slice(i+2,i+2+L); i+=2+L;
  700. if(f[0]===0){ done=true; break; }
  701. if(f[0]===1 && L>=8){
  702. const ms=((f[1])|(f[2]<<8)|(f[3]<<16)|(f[4]<<24))>>>0;
  703. capLines.push({ms, slot:f[5], rid:f[6], nb:f[7], bytes:[...f.slice(8,8+f[7])]});
  704. }
  705. }
  706. acc=acc.slice(i);
  707. }
  708. }catch(e){ log("drain err: "+e.message); }
  709. draining=false;
  710. if(liveTimer){ const el=$("#capOut"); const atBottom=el.scrollTop+el.clientHeight>=el.scrollHeight-4; renderCap(); if(atBottom) el.scrollTop=el.scrollHeight; }
  711. }
  712. async function startCapture(){
  713. if(!dev||capturing) return;
  714. capturing=true; capLines=[];
  715. $("#capOut").textContent="(dumping ring from boot, then live — press Stop when done)";
  716. $("#capStart").disabled=true; $("#capStop").disabled=false;
  717. await send([0x05,1]);
  718. liveTimer=setInterval(drainTick,100);
  719. }
  720. async function stopCapture(){
  721. if(liveTimer){ clearInterval(liveTimer); liveTimer=null; }
  722. await drainTick();
  723. try{ await send([0x05,0]); }catch(e){}
  724. capturing=false;
  725. $("#capStart").disabled=false; $("#capStop").disabled=true;
  726. renderCap(); log(`capture stopped — ${capLines.length} entries`);
  727. }
  728. async function startPolling(){
  729. polling=true; await refresh();
  730. while(polling && dev){ await new Promise(r=>setTimeout(r,600)); await refresh(); }
  731. }
  732. // UI wiring
  733. $("#connectBtn").onclick=connect;
  734. $("#backupExport").onclick=exportBackup;
  735. $("#backupImport").onclick=()=>$("#backupFile").click();
  736. $("#backupFile").onchange=async(e)=>{ const f=e.target.files[0]; if(f) await importBackup(f); e.target.value=""; };
  737. $("#capDl").onclick=downloadCap;
  738. $("#capStart").onclick=startCapture;
  739. $("#capStop").onclick=stopCapture;
  740. $("#hapClear").onclick=async()=>{ if(dev){ await send([0x07]); log("haptic re-init sent (clear stuck buzz)"); } };
  741. $("#ctlrOff").onclick=async()=>{ if(dev){ await send([0x08]); log("controller power-off attempt sent — watch link status"); } };
  742. $("#dfuSerial").onclick=async()=>{
  743. if(!dev){ log("not connected"); return; }
  744. if(!confirm("Reboot into serial DFU?\n\nThe puck will disconnect immediately. Flash with adafruit-nrfutil, then replug.")) return;
  745. await send([0x0B]); log("serial DFU reboot sent — device disconnecting");
  746. };
  747. $("#dfuUf2").onclick=async()=>{
  748. if(!dev){ log("not connected"); return; }
  749. if(!confirm("Reboot into UF2 bootloader?\n\nThe puck will disconnect and mount as a USB drive. Drag the .uf2 file onto it to flash.")) return;
  750. await send([0x0C]); log("UF2 bootloader reboot sent — device disconnecting");
  751. };
  752. $("#factoryErase").onclick=async()=>{
  753. if(!dev){ log("not connected"); return; }
  754. if(!confirm("Factory erase?\n\nThis wipes ALL persistent storage on the copycat:\n • the paired-controller bond (you'll have to re-pair)\n • every saved setting (mode, chords, back paddles, sensitivity)\n\nThe copycat reboots to factory defaults. This CANNOT be undone.")) return;
  755. if(!confirm("Are you absolutely sure?\n\nThere is no recovery. The controller bond and all settings will be gone.")) return;
  756. const typed=prompt('Final confirmation — type ERASE (all caps) to wipe everything:');
  757. if(typed!=="ERASE"){ log("factory erase cancelled (confirmation text did not match)"); return; }
  758. await send([0x0A,0x45,0x52,0x53]);
  759. log("FACTORY ERASE sent — copycat is reformatting and rebooting to defaults. Re-pair the controller, then reconnect.");
  760. };
  761. $("#persistMode").onclick=()=>{ const on=$("#persistMode").classList.contains("active"); setField(16, on?0:1); };
  762. // Connection tuning: post-connect haptic block on (field 27) + seconds (field 28). (poll RX window is fixed.)
  763. for(const id of ["mDiv","mFric","rumble"]){
  764. const field={mDiv:1,mFric:2,rumble:22}[id];
  765. $("#"+id).addEventListener("input", ()=>{ $("#"+id+"V").textContent=fmtSlider(id,$("#"+id).value); });
  766. $("#"+id).addEventListener("change", ()=>setField(field, +$("#"+id).value));
  767. }
  768. // per-type back/QAM/A-B-swap/haptics handlers are wired in buildTypeCfgs()
  769. $("#swRate").addEventListener("change", ()=>setField(23, +$("#swRate").value));
  770. $("#swGyro").addEventListener("change", ()=>setField(24, +$("#swGyro").value));
  771. for(const sel of document.querySelectorAll("select.chord")){
  772. sel.addEventListener("change", ()=>setField(CHORD_FIELD[+sel.dataset.i], +sel.value));
  773. }
  774. for(const b of document.querySelectorAll(".modebtn")){
  775. b.onclick=()=>{ const m=+b.dataset.mode;
  776. const clean=(m===7||m===8);
  777. const msg="Switch to "+MODE_NAMES[m]+"? The copycat will reboot."+(clean?"\n\nNOTE: the game/clean PlayStation modes drop WebUSB + host-wake, so THIS PANEL WILL DISCONNECT and can't reach the device while it's in this mode. To get back, chord on the controller: hold back-paddle 4 + A to return to Steam mode.":"");
  778. if(confirm(msg)){ send([0x03, m]); log("mode switch requested — device will reboot"); } };
  779. }
  780. if(!("usb" in navigator)) $("#connectBtn").outerHTML='<b style="color:var(--bad)">WebUSB not supported — use Chrome or Edge.</b>';
  781. else autoConnect(); // reopen an already-authorized puck on load, no picker (first-ever connect still needs the button)
  782. </script>
  783. </body>
  784. </html>