main
John Lauer Software 1.3.1: test-stage firmware (J4 TMC2209, HOME, limits, self-test), Stage tab and Calibrate in smi-dash (simulat… c0c5c9b
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
<!doctype html>
<html lang="en" data-scheme="studio">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Interferometer</title>
<link rel="icon" href="icon.svg">
<style>
:root{
  --bg:#161b22;--surface:#0d1117;--elevated:#1c2128;--overlay:#21262d;--border:#30363d;
  --text:#e6edf3;--text-body:#c9d1d9;--text-2:#c9d1d9;--text-3:#6e7681;
  --accent:#00b8b1;--accent-hover:#00d4cb;--accent-bright:#00e6dc;--on-accent:#05221f;
  --blue:#64abff;--purple:#8c6bf7;--green:#3fb950;--red:#f85149;--yellow:#d29922;
  --f-head:"Familjen Grotesk","Satoshi",system-ui,-apple-system,"Segoe UI",sans-serif;
  --f-body:"Satoshi",system-ui,-apple-system,"Segoe UI",sans-serif;
  --f-mono:"JetBrains Mono",ui-monospace,"Cascadia Mono",Consolas,monospace;
  --away:#00b8b1;--toward:#8c6bf7;--ch2:#64abff;--sync:#d0d7de;
}
*{box-sizing:border-box;margin:0;padding:0}
html,body{height:100%;overflow:hidden;background:var(--bg);color:var(--text-body);font:13px/1.35 var(--f-body)}
*::-webkit-scrollbar{display:none}*{scrollbar-width:none}
button{font:inherit;color:inherit;background:none;border:0;cursor:pointer}
#app{display:grid;grid-template-rows:44px minmax(0,1fr) 24px;height:100vh;overflow:hidden}
/* header */
header{display:flex;align-items:center;gap:12px;padding:0 12px;background:var(--surface);border-bottom:1px solid var(--border)}
.brand{display:flex;align-items:center;gap:8px;font:600 14px var(--f-head);color:var(--accent);white-space:nowrap;cursor:default}
.brand .sub{color:var(--text-2);font-weight:500}
.vsep{width:1px;height:22px;background:var(--border)}
.subject{display:flex;align-items:baseline;gap:10px;min-width:0;flex:1}
.subject b{color:var(--text);font:600 14px var(--f-head);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.subject .meta{font:11px var(--f-mono);color:var(--text-3);white-space:nowrap}
@media (max-width:720px){.subject .meta{display:none}}
.actions{display:flex;gap:4px;margin-left:auto}
.ib{width:32px;height:32px;display:grid;place-items:center;border-radius:6px;border:1px solid transparent}
.ib:hover{background:var(--elevated);border-color:var(--border)}
.ib svg{width:16px;height:16px;stroke:var(--text);fill:none;stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round}
.ib.is-on{background:color-mix(in srgb,var(--accent) 22%,transparent);border-color:var(--accent);box-shadow:inset 0 0 0 1px var(--accent)}
.ib.is-on svg{stroke:var(--accent-bright)}
.ib.rec-on{background:color-mix(in srgb,var(--accent) 22%,transparent);border-color:var(--accent)}
.ib.rec-on svg circle{fill:var(--accent-bright);stroke:var(--accent-bright);animation:pulse 1s infinite}
@keyframes pulse{50%{opacity:.35}}
/* body */
main{display:grid;grid-template-columns:minmax(0,1fr) clamp(260px,22vw,330px);gap:8px;padding:8px;min-height:0}
.plots{display:grid;grid-template-rows:1.3fr .85fr 1.1fr .9fr;gap:8px;min-height:0;min-width:0}
.card{background:var(--surface);border:1px solid var(--border);border-radius:8px;min-height:0;min-width:0;display:flex;flex-direction:column;overflow:hidden}
.ct{display:flex;align-items:center;gap:10px;padding:5px 10px 2px;font:600 12px var(--f-head);color:var(--text);white-space:nowrap}
.ct .lg{display:flex;gap:10px;font:500 11px var(--f-body);color:var(--text-2);overflow:hidden}
.ct .lg i{display:inline-block;width:10px;height:3px;border-radius:2px;margin-right:4px;vertical-align:middle}
.ct .r{margin-left:auto;font:11px var(--f-mono);color:var(--text-3)}
.cv{flex:1;min-height:0;position:relative}
.cv canvas{position:absolute;inset:0;width:100%;height:100%}
/* side panel */
aside{display:flex;flex-direction:column;gap:8px;min-height:0;overflow:hidden}
.panel{background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:6px 9px;display:flex;flex-direction:column;gap:5px}
.big{font:600 clamp(22px,2.2vw,32px)/1.05 var(--f-mono);color:var(--text);letter-spacing:-.5px}
.lbl{font:500 11px var(--f-body);color:var(--text-2)}
.sub2{font:12px var(--f-mono);color:var(--text-3)}
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:3px 10px}
.kv .v{font:600 14px var(--f-mono);color:var(--text)}
.dirpill{display:inline-flex;align-items:center;gap:4px;font:600 11px var(--f-body);padding:1px 7px;border-radius:10px;border:1px solid var(--border)}
.dirpill svg{width:11px;height:11px;fill:currentColor}
.seg{display:flex;background:var(--bg);border:1px solid var(--border);border-radius:6px;padding:2px;gap:2px}
.seg button{flex:1;padding:3px 2px;border-radius:4px;font:500 12px var(--f-body);color:var(--text-2);white-space:nowrap}
.seg button:hover{background:var(--elevated);color:var(--text)}
.seg button.is-on{background:color-mix(in srgb,var(--accent) 24%,var(--elevated));color:var(--accent-bright);box-shadow:inset 0 0 0 1px var(--accent)}
.row{display:flex;align-items:center;gap:8px}
.slider{display:grid;grid-template-columns:78px 1fr 80px;align-items:center;gap:6px}
.slider span{font:11px var(--f-body);color:var(--text-2)}
.slider output{font:11px var(--f-mono);color:var(--text);text-align:right}
input[type=range]{-webkit-appearance:none;appearance:none;width:100%;height:4px;background:var(--border);border-radius:2px;outline:none}
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:13px;height:13px;border-radius:50%;background:var(--accent);border:2px solid var(--surface)}
input[type=range]::-moz-range-thumb{width:12px;height:12px;border-radius:50%;background:var(--accent);border:2px solid var(--surface)}
.toggle{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:4px 8px;border-radius:6px;border:1px solid var(--border);background:var(--bg);font:500 12px var(--f-body);color:var(--text-2)}
.toggle .sw{width:30px;height:16px;border-radius:8px;background:var(--border);position:relative;transition:.15s}
.toggle .sw::after{content:"";position:absolute;top:2px;left:2px;width:12px;height:12px;border-radius:50%;background:var(--text-3);transition:.15s}
.toggle.is-on{border-color:var(--accent);color:var(--accent-bright);background:color-mix(in srgb,var(--accent) 12%,var(--bg))}
.toggle.is-on .sw{background:var(--accent)}
.toggle.is-on .sw::after{left:16px;background:var(--on-accent)}
.btn{padding:6px 10px;border-radius:6px;border:1px solid var(--border);background:var(--elevated);font:600 12px var(--f-body);color:var(--text)}
.btn:hover{border-color:var(--accent)}
.btn.primary{background:var(--accent);color:var(--on-accent);border-color:var(--accent)}
.btn.primary:hover{background:var(--accent-hover)}
select{font:12px var(--f-body);background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:6px;padding:4px 6px}
.hide{display:none!important}
.hint{font:11px var(--f-body);color:var(--text-3)}
/* status bar */
footer{display:flex;align-items:center;gap:14px;padding:0 12px;background:var(--surface);border-top:1px solid var(--border);font:11px var(--f-mono);color:var(--text-3);white-space:nowrap;overflow:hidden}
.led{width:8px;height:8px;border-radius:50%;background:var(--text-3);display:inline-block;margin-right:6px;vertical-align:middle}
.led.ok{background:var(--green)}.led.bad{background:var(--red)}.led.warn{background:var(--yellow)}
/* toasts, tooltips, cursor, modal */
#toasts{position:fixed;left:50%;bottom:36px;transform:translateX(-50%);display:flex;flex-direction:column-reverse;gap:6px;z-index:9000;pointer-events:none}
.toast{pointer-events:auto;min-width:240px;max-width:560px;padding:8px 12px;border-radius:8px;background:var(--overlay);border:1px solid var(--border);border-left:3px solid var(--accent);color:var(--text);font:13px var(--f-body);box-shadow:0 8px 24px rgba(0,0,0,.45);animation:tin .18s ease}
.toast.error{border-left-color:var(--red)}.toast.success{border-left-color:var(--green)}
@keyframes tin{from{opacity:0;transform:translateY(6px)}}
#tt{position:fixed;z-index:99999;max-width:300px;padding:7px 10px;border-radius:6px;background:var(--overlay);border:1px solid var(--border);color:var(--text-body);font:12px/1.4 var(--f-body);text-transform:none;pointer-events:none;opacity:0;transition:opacity .18s ease,transform .18s ease;transform:translateY(3px)}
#tt.show{opacity:1;transform:none}
#cursor{position:fixed;z-index:99998;left:-40px;top:-40px;pointer-events:none;transition:left .3s ease,top .3s ease;display:none}
#cursor svg{width:20px;height:20px;filter:drop-shadow(0 2px 3px rgba(0,0,0,.6))}
#cursor .lab{position:absolute;left:18px;top:16px;background:var(--accent);color:var(--on-accent);font:600 11px var(--f-body);padding:2px 6px;border-radius:4px;white-space:nowrap}
#modal{position:fixed;inset:0;background:rgba(1,4,9,.6);display:none;place-items:center;z-index:9500}
#modal.show{display:grid}
.dlg{width:min(480px,92vw);max-height:90vh;overflow:auto;background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:14px 16px;display:flex;flex-direction:column;gap:10px}
.dlg h2{font:600 16px var(--f-head);color:var(--text)}
.srow{display:grid;grid-template-columns:1fr 170px;align-items:center;gap:10px}
.srow label{font:12px var(--f-body);color:var(--text-body)}
.srow input[type=text],.srow input[type=number]{font:12px var(--f-mono);background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:6px;padding:4px 6px;width:100%}
.ver{font:11px var(--f-mono);color:var(--text-3)}
@media (max-width:900px){main{grid-template-columns:minmax(0,1fr) 250px}.slider{grid-template-columns:64px 1fr 64px}.sw-row{grid-template-columns:80px 1fr}}
/* narrow panes: the side panel becomes a drawer opened from the header */
#btn-panel{display:none}
@media (max-width:620px){main{grid-template-columns:1fr}aside{display:none}#btn-panel{display:grid}
  aside.open{display:flex;position:fixed;right:0;top:44px;bottom:24px;width:min(330px,94vw);z-index:60;background:var(--bg);padding:8px;border-left:1px solid var(--border);box-shadow:-12px 0 24px rgba(0,0,0,.45)}}
@media (max-height:520px){.plots{grid-template-rows:1.3fr .8fr 1fr 0fr}#card-spec{display:none}}
/* aside tabs and the board Controls panel */
.ro-line{display:none;font:600 13px var(--f-mono);color:var(--text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
aside.board-mode #p-readout{flex-direction:row;align-items:baseline;gap:10px;padding:5px 9px}
aside.board-mode #p-readout .big,aside.board-mode #p-readout .sub2,aside.board-mode #p-readout .grid2{display:none}
aside.board-mode #p-readout .ro-line{display:block}
aside.board-mode #p-readout>.lbl{display:none}
aside.board-mode .panel{padding:5px 9px;gap:4px}
.tabs{display:flex;gap:2px;background:var(--bg);border:1px solid var(--border);border-radius:7px;padding:2px}
.tabs button{flex:1;padding:4px 6px;border-radius:5px;font:600 12px var(--f-head);color:var(--text-2)}
.tabs button.is-on{background:var(--elevated);color:var(--text);box-shadow:inset 0 -2px 0 var(--accent)}
.tabbody{display:flex;flex-direction:column;gap:8px;min-height:0}
.ph{display:flex;align-items:center;gap:8px}
.ph .lbl{font:600 12px var(--f-head);color:var(--text)}
.pill{margin-left:auto;font:600 10px var(--f-mono);letter-spacing:.4px;padding:1px 7px;border-radius:10px;border:1px solid var(--border);color:var(--text-3)}
.pill.on{color:#ffb4a8;border-color:var(--red);background:color-mix(in srgb,var(--red) 18%,transparent)}
.pill.ramp{color:var(--yellow);border-color:var(--yellow)}
.pill.fault{color:#fff;background:var(--red);border-color:var(--red)}
.ilock{display:flex;align-items:center;gap:7px;font:12px var(--f-body);color:var(--text-body);cursor:pointer;user-select:none}
.ilock .box{width:15px;height:15px;border-radius:4px;border:1.5px solid var(--text-3);display:grid;place-items:center;flex:none}
.ilock.is-on .box{border-color:var(--yellow);background:color-mix(in srgb,var(--yellow) 25%,transparent)}
.ilock.is-on .box::after{content:"";width:7px;height:4px;border-left:2px solid var(--yellow);border-bottom:2px solid var(--yellow);transform:rotate(-45deg) translate(1px,-1px)}
.lrow{display:grid;grid-template-columns:1fr 1fr;gap:6px}
.hold{position:relative;overflow:hidden;padding:7px 8px;border-radius:6px;border:1px solid var(--red);background:color-mix(in srgb,var(--red) 10%,var(--elevated));font:600 12px var(--f-body);color:#ffd0c9}
.hold:disabled{opacity:.4;cursor:not-allowed}
.hold .fill{position:absolute;inset:0;width:0;background:color-mix(in srgb,var(--red) 45%,transparent);transition:width .05s linear}
.hold span{position:relative}
.btn.off{border-color:var(--border);background:var(--elevated)}
.kv3{display:grid;grid-template-columns:repeat(3,1fr);gap:4px}
.kv3 .v{font:600 12px var(--f-mono);color:var(--text)}
.kv3 .v.meas{color:var(--accent-bright)}
.numrow{display:grid;grid-template-columns:96px 1fr 66px;align-items:center;gap:6px}
.numrow span{font:11px var(--f-body);color:var(--text-2);white-space:nowrap}
.numrow input[type=number]{font:12px var(--f-mono);background:var(--bg);color:var(--text);border:1px solid var(--border);border-radius:5px;padding:2px 5px;width:100%}
.spark{height:24px;position:relative}.spark canvas{position:absolute;inset:0;width:100%;height:100%}
.sw-row{display:grid;grid-template-columns:78px 1fr;align-items:center;gap:6px}
.sw-row>span{font:11px var(--f-body);color:var(--text-2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.sw-row .seg button{font-size:11px;padding:1px 2px}
#switch-rows{display:flex;flex-direction:column;gap:2px}
aside.board-mode .seg{padding:1px}
aside.board-mode .tunebar{display:none}
aside.board-mode #tune-msg{display:none}
#tune-t{font:11px var(--f-mono);color:var(--text-2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0}
#offset-rows{display:flex;flex-direction:column;gap:3px}
.sw-row.locked .seg{opacity:.45}
.sw-row.locked>span{color:var(--text-3)}
.tunebar{height:4px;border-radius:2px;background:var(--border);overflow:hidden}.tunebar i{display:block;height:100%;width:0;background:var(--accent);transition:width .3s}
.warnline{font:11px var(--f-body);color:var(--yellow)}
.faultline{display:flex;align-items:center;gap:8px;font:12px var(--f-body);color:#ffb4a8}
/* Stage tab */
.plots.stage-mode{grid-template-rows:1fr .55fr .75fr 1.7fr}
.plots.stage-mode #card-spec{display:none}
#card-stage{display:none}.plots.stage-mode #card-stage{display:flex}
.simtag{font:600 10px var(--f-mono);letter-spacing:.4px;padding:1px 6px;border-radius:10px;color:var(--yellow);border:1px solid color-mix(in srgb,var(--yellow) 60%,transparent);background:color-mix(in srgb,var(--yellow) 10%,transparent)}
.pill.move{color:var(--accent-bright);border-color:var(--accent)}
.pill.idle{color:var(--green);border-color:var(--green)}
.btnrow{display:grid;grid-template-columns:repeat(3,1fr);gap:5px}
.btnrow .btn,.dirrow .btn{padding:4px 6px;font-size:12px}
.dirrow{display:grid;grid-template-columns:1fr 1fr;gap:5px}
.resline{font:11px var(--f-mono);color:var(--text-body);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.resline b{color:var(--text);font-weight:600}
.resline.warn{color:var(--yellow);white-space:normal}
table.ba{width:100%;border-collapse:collapse;font:11px var(--f-mono)}
table.ba td{padding:1px 2px;white-space:nowrap}
table.ba td:first-child{font:11px var(--f-body);color:var(--text-2);overflow:hidden;text-overflow:ellipsis;max-width:120px}
table.ba td.n{text-align:right;color:var(--text)}
table.ba td.n.good{color:var(--accent-bright)}
table.ba th{font:600 10px var(--f-body);color:var(--text-3);text-align:right;padding:0 2px}
/* ?frame=16x9: an exact 16:9 stage, letterboxed in black, for screen recordings */
html.framed,html.framed body{background:#000}
html.framed #app{position:absolute;inset:0;margin:auto;width:min(100vw,177.7778vh);height:min(56.25vw,100vh);background:var(--bg)}
</style>
</head>
<body>
<div id="app">
<header>
  <div class="brand" id="brand" data-tip="Self-mixing interferometer dashboard. Reads the Raspberry Pi Pico over USB, or simulates the laser, optics and analog chain.">
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"><path d="M1 8h3"/><path d="M4 5.5v5"/><path d="M6 8c1-3 2 3 3 0s2 3 3 0 1 2 2.5 0"/></svg>
    Interferometer <span class="sub">· SMI dashboard</span>
  </div>
  <div class="vsep"></div>
  <div class="subject"><b id="subj">Simulator</b><span class="meta" id="subj-meta">250 ksps per channel · λ 658 nm · 1 fringe = 329 nm</span></div>
  <div class="actions">
    <button class="ib" id="btn-pause" data-tip="Freeze the plots. Acquisition and the displacement count keep running. While frozen, drag a channel plot to look back up to 2 s." aria-pressed="false">
      <svg viewBox="0 0 16 16"><path d="M5 3v10M11 3v10"/></svg></button>
    <button class="ib" id="btn-zero" data-tip="Set the running displacement to zero here. The fringe count restarts; recorded data is not changed.">
      <svg viewBox="0 0 16 16"><circle cx="8" cy="8" r="5"/><path d="M8 1v3M8 12v3M1 8h3M12 8h3"/></svg></button>
    <button class="ib" id="btn-record" data-tip="Record both channels, SYNC, fringes and displacement. Format and folder are in Settings. Click again to stop and save." aria-pressed="false">
      <svg viewBox="0 0 16 16"><circle cx="8" cy="8" r="4.5"/></svg></button>
    <button class="ib" id="btn-panel" data-tip="Show the side panel: readouts, the board Controls, source and simulator." aria-pressed="false">
      <svg viewBox="0 0 16 16"><rect x="2" y="3" width="12" height="10" rx="1.5"/><path d="M10 3v10"/></svg></button>
    <button class="ib" id="btn-settings" data-tip="Settings: frame rate, units, recording format and folder, detector tuning, idle shutdown.">
      <svg viewBox="0 0 16 16"><circle cx="8" cy="8" r="2.2"/><path d="M8 1.5v2M8 12.5v2M1.5 8h2M12.5 8h2M3.4 3.4l1.4 1.4M11.2 11.2l1.4 1.4M3.4 12.6l1.4-1.4M11.2 4.8l1.4-1.4"/></svg></button>
  </div>
</header>
<main>
  <section class="plots">
    <div class="card" id="card-ch1">
      <div class="ct">Channel 1 · laser monitor photodiode (ADC0)
        <span class="lg"><span><i style="background:var(--accent)"></i>ADC</span><span><i style="background:var(--accent-bright)"></i>low-passed</span><span><i style="background:var(--away)"></i>fringe, away</span><span><i style="background:var(--toward)"></i>fringe, towards</span><span><i style="background:var(--sync)"></i>SYNC</span></span>
        <span class="r" id="ch1-r"></span></div>
      <div class="cv" data-tip="Scroll to zoom the time window (0.1 ms to 2 s). Double-click resets to 10 ms. When frozen, drag to look back."><canvas id="cv-ch1"></canvas></div>
    </div>
    <div class="card" id="card-ch2">
      <div class="ct">Channel 2 · external photodiode (ADC1)<span class="r" id="ch2-r"></span></div>
      <div class="cv" data-tip="Same time window as channel 1. Sampled 2 us after channel 1 in each pair."><canvas id="cv-ch2"></canvas></div>
    </div>
    <div class="card" id="card-disp">
      <div class="ct">Displacement
        <span class="lg"><span><i style="background:var(--accent)"></i>counted</span><span id="lg-truth"><i style="background:var(--text-3)"></i>simulator truth</span></span>
        <span class="r" id="disp-r"></span></div>
      <div class="cv" data-tip="Running position from the fringe count, lambda/2 per fringe. Scroll to change the span (0.5 to 120 s)."><canvas id="cv-disp"></canvas></div>
    </div>
    <div class="card" id="card-stage">
      <div class="ct">Stage position
        <span class="lg"><span><i style="background:var(--yellow)"></i>commanded</span><span><i style="background:var(--accent)"></i>counted from fringes</span><span id="lg-stage-truth"><i style="background:var(--text-3)"></i>simulated mirror</span></span>
        <span class="r" id="stage-r"></span></div>
      <div class="cv" data-tip="Last 30 s. Commanded: the stage position in pulses times the scale (nominal 15.625 nm/pulse until Calibrate fits it). Counted: the fringe count times 329 nm, placed on the commanded trace where the stage last finished homing (Align moves that point to now)."><canvas id="cv-stage"></canvas></div>
    </div>
    <div class="card" id="card-spec">
      <div class="ct">Spectrum
        <span class="lg"><span><i style="background:var(--accent)"></i>channel 1</span><span><i style="background:var(--ch2)"></i>channel 2</span></span>
        <span class="r" id="spec-r"></span></div>
      <div class="cv" data-tip="Hann-windowed FFT of the last 8192 samples (33 ms) per channel, dB relative to ADC full scale. The fringe frequency times lambda/2 is the speed."><canvas id="cv-spec"></canvas></div>
    </div>
  </section>
  <aside>
    <div class="panel" id="p-readout">
      <div class="lbl">Displacement</div>
      <div class="ro-line" id="ro-line" data-tip="Counted displacement, velocity and direction. The full readouts are on the Source and simulator tab."></div>
      <div class="big" id="ro-disp">0 nm</div>
      <div class="sub2" id="ro-disp2">0.000 µm</div>
      <div class="grid2">
        <div class="kv"><div class="lbl">Velocity</div><div class="v" id="ro-vel">0</div></div>
        <div class="kv"><div class="lbl">Fringe rate</div><div class="v" id="ro-rate">0 Hz</div></div>
        <div class="kv"><div class="lbl">Fringes</div><div class="v" id="ro-count">0</div></div>
        <div class="kv"><div class="lbl">Direction</div><div class="v"><span class="dirpill" id="ro-dir">none</span></div></div>
      </div>
    </div>
    <div class="tabs" role="tablist">
      <button id="tab-board" class="is-on" data-tip="Board 1.3: laser, offsets, gains and bias, set from software. Every control is also a CLI verb (smi-dash laser, offset, gain, bias, tune).">Controls</button>
      <button id="tab-stage" data-tip="Test stage on the STAGE connector (board 1.3 J4): home, step, stop, self-test and Calibrate. Also `smi-dash stage` and `smi-dash calibrate`.">Stage</button>
      <button id="tab-sim" data-tip="Data source, fringe detector and the simulated target.">Source and simulator</button>
    </div>
    <div class="tabbody" id="body-board">
      <div class="panel" id="p-laser">
        <div class="ph"><span class="lbl">Laser</span><span class="hint" id="laser-why"></span><span class="pill" id="laser-pill">OFF</span></div>
        <div class="ilock" id="laser-interlock" role="checkbox" aria-checked="false" data-tip="Interlock. The HL6501MG is a class 3B laser: enclose the beam path or wear 658 nm eyewear before enabling. Ticking this arms the Enable button; it clears itself when the laser goes off.">
          <span class="box"></span><span>Beam path enclosed or eyewear on</span></div>
        <div class="lrow">
          <button class="hold" id="laser-hold" disabled data-tip="Hold for one second to enable the laser. The firmware writes the set-point to the head DAC, reads it back, and only then starts the enable carrier; the head's soft-start ramps the current."><i class="fill" id="laser-fill"></i><span id="laser-hold-t">Hold to enable</span></button>
          <button class="btn off" id="laser-off" data-tip="Laser off at once: the hardware enable drops and the set-point returns to 0 mA.">Laser off</button>
        </div>
        <div class="numrow" data-tip="Laser current set-point, sent when you release the slider or press Enter. Each write disarms the head, is read back, and re-arms; the head's soft-start ramps the current. The firmware refuses anything above its limit (the head DAC's top less its guard band)."><span>Current</span><input type="range" id="cur-slider" min="0" max="119" step="0.1"><input type="number" id="cur-input" min="0" step="0.5"></div>
        <div class="kv3">
          <div class="kv" data-tip="What you asked for."><div class="lbl">Target</div><div class="v" id="ro-target">0 mA</div></div>
          <div class="kv" data-tip="The set-point the head DAC holds now (verified by readback every 2 ms while on)."><div class="lbl">Set-point</div><div class="v" id="ro-setp">0 mA</div></div>
          <div class="kv" data-tip="Laser current measured on the laser head by its ADS1115 across the 2 ohm shunt (0.0078 mA per code), read by the Pico over I2C; zero code calibrated with the laser off."><div class="lbl">Measured</div><div class="v meas" id="ro-meas">n/a</div></div>
        </div>
        <div class="spark" data-tip="Last 20 s: set-point (grey) and measured current (teal)."><canvas id="cv-cur"></canvas></div>
        <div class="faultline hide" id="fault-line"><span id="fault-text"></span><button class="btn" id="btn-clear-fault">Clear fault</button></div>
        <div class="warnline hide" id="map-warn">The firmware's control map differs from this dashboard's. Flash the matching smi_pico.uf2.</div>
      </div>
      <div class="panel" id="p-offsets">
        <div class="ph"><span class="lbl">Offsets</span><button class="btn" id="btn-centre" style="margin-left:auto;padding:3px 9px" data-tip="Servo each channel's mean to mid-scale (code 2048) with its offset DAC. Uses the board's stage equation, Vstage = (1 + K) Voffset - K Vbuffer, then refines on the measured slope. With the laser on it turns it off for each offset write and back on at the same set-point (board rule).">Auto-centre</button></div>
        <div id="offset-rows"></div>
      </div>
      <div class="panel" id="p-gains">
        <div class="ph"><span class="lbl">Gains and bias</span></div>
        <div id="switch-rows"></div>
      </div>
      <div class="panel" id="p-tune">
        <div class="ph"><span class="lbl">Tune</span><span id="tune-t"></span>
          <button class="btn primary" style="margin-left:auto;padding:3px 12px" id="btn-tune" data-tip="Steps the laser current, re-centres, scores fringe contrast (swing over noise, clipping penalised), then tries the second-stage gains. Move the target while it runs: this board's laser current cannot be dithered. Needs the laser on; never turns it on.">Tune</button>
          <button class="btn" style="padding:3px 9px" id="btn-tune-stop" data-tip="Stop tuning; the last setting stays.">Stop</button>
        </div>
        <div class="tunebar"><i id="tune-bar"></i></div>
        <div class="hint" id="tune-msg" data-tip="Score = fringe swing / noise, clipping penalised. TIA gain and bias are left to you: the board says change them with the laser off.">Steps current and stage-2 gain; TIA and bias stay yours.</div>
      </div>
    </div>
    <div class="tabbody hide" id="body-stage">
      <div class="panel" id="p-stage">
        <div class="ph"><span class="lbl">Stage</span><span class="simtag" id="stage-sim" data-tip="The simulated stage runs the firmware's own stage code (smi_stage.c) against a simulated TMC2209 and mechanism. Nothing is assembled yet: no number here is a measurement.">SIMULATED</span><span class="pill" id="stage-pill">OFF</span></div>
        <div class="kv3">
          <div class="kv" data-tip="Pulses from HOME (0 to 1600), one microstep each."><div class="lbl">Position</div><div class="v" id="st-pos">n/a</div></div>
          <div class="kv" data-tip="Position times the scale: nominal 15.625 nm/pulse until Calibrate fits it."><div class="lbl">Commanded</div><div class="v" id="st-cmd">n/a</div></div>
          <div class="kv" data-tip="Counted from the fringes (329 nm each), placed on the commanded position at the last home."><div class="lbl">Counted</div><div class="v meas" id="st-meas">n/a</div></div>
        </div>
        <div class="hint" id="st-line"></div>
        <div class="btnrow">
          <button class="btn primary" id="st-home" data-tip="Configure the TMC2209 over its UART (every write checked against IFCNT), enable it, and home: 80 pulses/s to the switch, back off, 32 pulses/s to its opening edge, which is zero.">Home</button>
          <button class="btn" id="st-stop" data-tip="Stop motion now. The driver stays enabled and the position stays valid.">Stop</button>
          <button class="btn off" id="st-off" data-tip="Disable the driver (EN_N high). The position becomes invalid until the next home.">Off</button>
        </div>
        <div class="sw-row" data-tip="Pulses per step. Nominal 15.625 nm per pulse at the mirror; 21 pulses is about one fringe."><span>Step</span><div class="seg" id="st-sizes"></div></div>
        <div class="dirrow">
          <button class="btn" id="st-neg" data-tip="Step towards HOME (negative). Refused below 0.">◀ towards HOME</button>
          <button class="btn" id="st-posb" data-tip="Step away from HOME (positive). Refused above 1600 pulses.">away ▶</button>
        </div>
        <div class="sw-row" data-tip="Step rate. The stage map's default is 160 pulses/s (2.5 µm/s nominal), its maximum 640."><span>Speed</span><div class="seg" id="st-speeds"></div></div>
      </div>
      <div class="panel" id="p-selftest">
        <div class="ph"><span class="lbl">Self-test</span><span id="st-test-t" class="hint"></span>
          <button class="btn primary" style="margin-left:auto;padding:3px 12px" id="st-test" data-tip="The stage map's sequence: to pulse 128, then +128 four times and -128 four times, 1 s at each plateau (about 17 s). Reports the scale fitted to the counted fringe edges, the plateau fit with drift, the reversal errors and the return residual. Needs the laser on to count fringes.">Run</button></div>
        <div class="resline" id="st-r1">Steps out and back; reports the residual in nm.</div>
        <div class="resline" id="st-r2"></div>
        <div class="resline" id="st-r3"></div>
      </div>
      <div class="panel" id="p-cal">
        <div class="ph"><span class="lbl">Calibrate</span><span id="cal-t" class="hint"></span>
          <button class="btn primary" style="margin-left:auto;padding:3px 12px" id="cal-go" disabled data-tip="Uses the stage as the moving target: homes, checks a 1024-pulse step as things are, zeroes the current readback with the laser off, turns it back on, auto-centres, tunes while the stage moves back and forth, checks the step again, and reports before and after. Simulator only for now.">Calibrate</button></div>
        <div class="ilock" id="cal-interlock" role="checkbox" aria-checked="false" data-tip="Calibrate turns the class 3B laser off and on. Enclose the beam path or wear 658 nm eyewear first."><span class="box"></span><span>Beam path enclosed or eyewear on</span></div>
        <div class="tunebar"><i id="cal-bar"></i></div>
        <table class="ba" id="cal-table"></table>
      </div>
    </div>
    <div class="tabbody hide" id="body-sim">
    <div class="panel" id="p-truth" data-tip="Only with the simulator: the counted displacement compared with the simulated target's true position. Counting resolves one fringe, 329 nm, so errors up to that size are expected.">
      <div class="grid2">
        <div class="kv"><div class="lbl">Simulator truth</div><div class="v" id="ro-truth">0</div></div>
        <div class="kv"><div class="lbl">Error now</div><div class="v" id="ro-err">0</div></div>
        <div class="kv"><div class="lbl">RMS error (trace)</div><div class="v" id="ro-rms">0</div></div>
        <div class="kv"><div class="lbl">Max error (trace)</div><div class="v" id="ro-max">0</div></div>
      </div>
    </div>
    <div class="panel">
      <div class="lbl">Source</div>
      <div class="seg">
        <button id="src-sim" data-tip="Generate physically modelled signals: self-mixing optics, the board's analog chain and the RP2040 ADC.">Simulator</button>
        <button id="src-serial" data-tip="Read the Raspberry Pi Pico running smi_pico.uf2 over USB serial. Picks the first Pico port found.">Pico (USB)</button>
      </div>
      <div class="slider" data-tip="Low-pass corner of the fringe detector. Keep the fringe rate below about two thirds of it; raise it for fast moves, at the cost of more noise."><span>Detector LP</span><input type="range" id="lp-slider" min="0" max="1000" step="1"><output id="lp-out"></output></div>
    </div>
    <div class="panel" id="p-sim">
      <div class="lbl">Target motion</div>
      <div class="seg" id="profiles">
        <button data-profile="constant" data-tip="Constant speed, reversing at the ends of the travel range.">Constant</button>
        <button data-profile="sine" data-tip="Sinusoidal back-and-forth around the start point.">Sine</button>
        <button data-profile="step" data-tip="Smooth step out, dwell, and return to the start.">Step</button>
        <button data-profile="hand" data-tip="A hand-held target: slow wander plus a 9 Hz tremor.">Hand</button>
        <button data-profile="hold" data-tip="Target held still.">Hold</button>
        <button data-profile="stage" data-tip="The target is the test stage's mirror, moved from the Stage tab.">Stage</button>
      </div>
      <div id="motion-sliders"></div>
      <div class="slider" data-tip="Optical feedback strength C. Below 1 the fringes are near-sinusoidal; above 1 they become sawteeth that lean with the direction of motion."><span>Feedback C</span><input type="range" id="c-slider" min="0" max="8" step="0.05"><output id="c-out"></output></div>
      <div class="slider" data-tip="Extra intensity and mechanical noise, times a clean bench."><span>Noise</span><input type="range" id="noise-slider" min="0" max="20" step="0.5"><output id="noise-out"></output></div>
      <div class="toggle" id="mm-toggle" role="switch" aria-pressed="false" data-tip="Add a second longitudinal mode. The two fringe patterns beat and the signal fades every 1.46 mm of travel, the problem a single-mode laser like the HL6501MG removes."><span>Multimode laser (1.46 mm beat)</span><span class="sw"></span></div>
      <div class="toggle" id="board-toggle" role="switch" aria-pressed="true" data-tip="Model board 1.3 (software controls since 1.2): the laser current, gains, offsets and bias come from the Controls tab, through the firmware's own control code. Off: the v1.1 board with screwdriver trims."><span>Board 1.3 model</span><span class="sw"></span></div>
    </div>
    </div>
  </aside>
</main>
<footer>
  <span><span class="led" id="led"></span><span id="st-link">connecting</span></span>
  <span id="st-rate"></span><span id="st-frames"></span><span id="st-err"></span><span id="st-fps"></span>
  <span id="rec-hint">Not recording</span>
  <span id="st-rail" data-tip="Main board 5.3 V analog rail, read by the Pico on ADC2 (GPIO28) through a 1:2 divider, once a second."></span>
  <span style="margin-left:auto" id="st-ver"></span>
</footer>
</div>
<div id="toasts"></div>
<div id="tt"></div>
<div id="cursor"><svg viewBox="0 0 20 20"><path d="M2 2l6 15 2.2-6.2L16.5 8.5z" fill="#00e6dc" stroke="#05221f" stroke-width="1.2"/></svg><span class="lab" id="cursor-lab">AI</span></div>
<div id="modal"><div class="dlg">
  <h2>Settings</h2>
  <div class="srow"><label data-tip="Frames per second pushed to this page. Lower it on a slow machine.">Display frame rate</label><input type="number" id="s-fps" min="5" max="60" step="1"></div>
  <div class="srow"><label data-tip="Auto shows nm below 10 um and um above.">Displacement units</label><select id="s-units"><option value="auto">Auto</option><option value="nm">nm</option><option value="um">µm</option></select></div>
  <div class="srow"><label data-tip="CSV streams to disk as it records. HDF5 holds the data in memory and writes on stop, up to 120 s.">Recording format</label><select id="s-format"><option value="csv">CSV</option><option value="h5">HDF5</option></select></div>
  <div class="srow"><label data-tip="Folder for recordings. A leading ~ means your home folder.">Recording folder</label><input type="text" id="s-dir"></div>
  <div class="srow"><label data-tip="A jump counts as a fringe when it is larger than this fraction of the fringe amplitude.">Detector threshold</label><input type="number" id="s-thr" min="0.05" max="0.95" step="0.05"></div>
  <div class="srow"><label data-tip="Flip which way counts as away. Depends on the photodiode jumpers and which way your stage moves.">Invert direction</label><div class="toggle" id="s-invert" role="switch"><span>Inverted</span><span class="sw"></span></div></div>
  <div class="srow"><label data-tip="The server saves its state and exits after this many idle hours. Your settings are kept.">Idle shutdown (hours)</label><input type="number" id="s-ttl" min="0.1" step="1"></div>
  <div class="srow"><label data-tip="Where smi-dash show opens this page.">Default display</label><select id="s-surface"><option value="wv">Hydrogen webview</option><option value="pup">pup browser</option></select></div>
  <div class="row" style="justify-content:space-between"><span class="ver" id="s-ver"></span><button class="btn primary" id="s-close">Done</button></div>
</div></div>
<script>
"use strict";
if(new URLSearchParams(location.search).get("frame")==="16x9") document.documentElement.classList.add("framed");
const $=s=>document.querySelector(s);
const LSB=3.3/4096;
let S=null, F=null, fpsEMA=0, dragging=null, renderPending=false; const frameTimes=[];

// console capture: the AI reads it with `smi-dash console`
(function(){
  for(const lv of ["log","warn","error"]){
    const o=console[lv].bind(console);
    console[lv]=(...a)=>{o(...a);post("console",{level:lv,text:a.map(x=>typeof x==="string"?x:JSON.stringify(x)).join(" "),t:Date.now()},true)};
  }
  window.addEventListener("error",e=>console.error("onerror: "+e.message+" @"+e.lineno));
  window.addEventListener("unhandledrejection",e=>console.error("unhandled: "+(e.reason&&e.reason.message||e.reason)));
})();

function post(path,body,quiet){
  return fetch(path,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body||{})})
    .then(r=>r.json()).then(j=>{ if(j.status==="error"&&!quiet){toast(j.error+(j.hints&&j.hints.length?". "+j.hints[0]:""),"error")} return j})
    .catch(e=>{ if(!quiet) toast("Server not reachable: "+e.message,"error") });
}
const throttles={};
function postSoon(path,body,ms=90){
  const t=throttles[path]||(throttles[path]={timer:0,body:{}});
  Object.assign(t.body,body); clearTimeout(t.timer);
  t.timer=setTimeout(()=>{const b=t.body;t.body={};post(path,b)},ms);
}

// toasts
function toast(text,kind="info"){
  const d=document.createElement("div"); d.className="toast "+kind; d.textContent=text;
  const box=$("#toasts"); box.appendChild(d); while(box.children.length>4) box.firstChild.remove();
  let left=kind==="error"?12000:4000, t0=Date.now(), paused=false;
  d.onmouseenter=()=>{paused=true;left-=Date.now()-t0}; d.onmouseleave=()=>{paused=false;t0=Date.now();arm()};
  d.onclick=()=>d.remove();
  const arm=()=>setTimeout(()=>{if(!paused)d.remove()},left); arm();
}

// tooltips: body-appended, 600 ms delay, clamped to the viewport on both axes
(function(){
  const tt=$("#tt"); let timer=0, cur=null, mx=0, my=0;
  document.addEventListener("mousemove",e=>{mx=e.clientX;my=e.clientY});
  document.addEventListener("mouseover",e=>{
    const el=e.target.closest("[data-tip]"); if(el===cur) return; cur=el; clearTimeout(timer); tt.classList.remove("show");
    if(!el) return;
    timer=setTimeout(()=>{
      tt.textContent=el.dataset.tip; tt.style.left="0px"; tt.style.top="0px"; tt.classList.add("show");
      const M=8, w=tt.offsetWidth, h=tt.offsetHeight, W=document.documentElement.clientWidth, H=document.documentElement.clientHeight;
      let x=mx+14, y=my+14;
      if(x+w>W-M) x=mx-14-w; if(y+h>H-M) y=my-14-h;
      x=Math.max(M,Math.min(x,W-w-M)); y=Math.max(M,Math.min(y,H-h-M));
      tt.style.left=x+"px"; tt.style.top=y+"px";
    },600);
  });
  document.addEventListener("mousedown",()=>{clearTimeout(timer);tt.classList.remove("show")});
})();

// AI cursor
function aiCursor(sel,label,then){
  const el=document.querySelector(sel); if(!el){console.warn("cursor: no element "+sel);return}
  const r=el.getBoundingClientRect(), c=$("#cursor"); c.style.display="block";
  $("#cursor-lab").textContent=label||"AI";
  c.style.left=(r.left+r.width/2)+"px"; c.style.top=(r.top+r.height/2)+"px";
  setTimeout(()=>{ if(then) then(el); setTimeout(()=>{c.style.display="none"},1500) },380);
}

// formatting
function units(){return S&&S.settings?S.settings.units:"auto"}
function fmtDisp(nm){
  const u=units();
  if(u==="nm"||(u==="auto"&&Math.abs(nm)<10000)) return Math.round(nm).toLocaleString("en-US")+" nm";
  return (nm/1000).toFixed(3)+" µm";
}
function fmtVel(v){ if(!isFinite(v)) return "n/a"; return Math.abs(v)>=1000?(v/1000).toFixed(3)+" mm/s":v.toFixed(1)+" µm/s" }
function fmtHz(f){ return f>=1000?(f/1000).toFixed(2)+" kHz":Math.round(f)+" Hz" }

// canvas helpers
function ctxOf(id){
  const c=document.getElementById(id), r=c.getBoundingClientRect(), dpr=window.devicePixelRatio||1;
  const W=Math.max(1,Math.round(r.width*dpr)), H=Math.max(1,Math.round(r.height*dpr));
  if(c.width!==W||c.height!==H){c.width=W;c.height=H}
  const g=c.getContext("2d"); g.setTransform(dpr,0,0,dpr,0,0); g.clearRect(0,0,r.width,r.height);
  return {g,w:r.width,h:r.height};
}
// Theme colours, read once (getComputedStyle in a draw loop forces a style recalc per call).
const cssCache={};
const css=n=>cssCache[n]||(cssCache[n]=getComputedStyle(document.documentElement).getPropertyValue(n).trim());
function niceStep(range,n){const raw=range/n, p=Math.pow(10,Math.floor(Math.log10(raw))), m=raw/p; return (m<1.5?1:m<3.5?2:m<7.5?5:10)*p}
function axes(g,x0,y0,w,h,ylo,yhi,yfmt,xlo,xhi,xfmt){
  g.strokeStyle=css("--border"); g.lineWidth=1; g.fillStyle=css("--text-3"); g.font="10px "+css("--f-mono");
  const ys=niceStep(yhi-ylo,4);
  g.textAlign="right"; g.textBaseline="middle";
  for(let v=Math.ceil(ylo/ys)*ys; v<=yhi+1e-9; v+=ys){
    const y=y0+h-(v-ylo)/(yhi-ylo)*h; g.globalAlpha=.55; g.beginPath(); g.moveTo(x0,y+.5); g.lineTo(x0+w,y+.5); g.stroke(); g.globalAlpha=1;
    g.fillText(yfmt(v),x0-4,y);
  }
  const xs=niceStep(xhi-xlo,6), dec=Math.max(0,-Math.floor(Math.log10(xs)+1e-9)); g.textBaseline="top";
  for(let v=Math.ceil(xlo/xs)*xs; v<=xhi+1e-9; v+=xs){
    const x=x0+(v-xlo)/(xhi-xlo)*w; g.globalAlpha=.35; g.beginPath(); g.moveTo(x+.5,y0); g.lineTo(x+.5,y0+h); g.stroke(); g.globalAlpha=1;
    g.textAlign=x>x0+w-30?"right":x<x0+30?"left":"center";
    g.fillText(xfmt(Math.abs(v)<xs*1e-6?0:v,dec),x,y0+h+3);
  }
}
const scales={};
function autoscale(key,lo,hi,minSpan){
  const s=scales[key]||(scales[key]={lo,hi});
  const span=Math.max(hi-lo,minSpan), mid=(hi+lo)/2; let tlo=mid-span*0.6, thi=mid+span*0.6;
  // expand at once, shrink slowly
  s.lo=tlo<s.lo?tlo:s.lo+(tlo-s.lo)*0.06; s.hi=thi>s.hi?thi:s.hi+(thi-s.hi)*0.06;
  return s;
}
const PADL=44, PADB=16, PADT=6, PADR=8;

function drawChannel(id,ch,key,color,withMarks){
  const {g,w,h}=ctxOf(id); if(!F) return;
  const x0=PADL,y0=PADT,pw=w-PADL-PADR,ph=h-PADT-PADB, n=F.cols;
  let lo=4095,hi=0; for(let i=0;i<n;i++){ if(ch.mn[i]<lo)lo=ch.mn[i]; if(ch.mx[i]>hi)hi=ch.mx[i] }
  const sc=autoscale(key,lo*LSB,hi*LSB,0.02);
  const winms=F.win_ms;
  axes(g,x0,y0,pw,ph,sc.lo,sc.hi,v=>v.toFixed(sc.hi-sc.lo<0.2?3:2)+"",-winms,0,(v,d)=>v.toFixed(d)+" ms");
  const Y=v=>y0+ph-(v*LSB-sc.lo)/(sc.hi-sc.lo)*ph, X=i=>x0+(i+0.5)/n*pw;
  g.save(); g.beginPath(); g.rect(x0,y0,pw,ph); g.clip();
  // SYNC markers
  g.strokeStyle=css("--sync"); g.setLineDash([4,3]); g.lineWidth=1;
  for(const [c,lv] of F.sy){ const x=x0+c/n*pw; g.globalAlpha=lv?0.9:0.35; g.beginPath(); g.moveTo(x,y0); g.lineTo(x,y0+ph); g.stroke() }
  g.setLineDash([]); g.globalAlpha=1;
  // envelope
  g.strokeStyle=color; g.fillStyle=color; g.lineWidth=1.2;
  if(n<pw*0.9){ g.beginPath(); for(let i=0;i<n;i++){const x=X(i),y=Y((ch.mn[i]+ch.mx[i])/2); i?g.lineTo(x,y):g.moveTo(x,y)} g.stroke() }
  else { g.globalAlpha=.85; g.beginPath(); for(let i=0;i<n;i++){const x=X(i); g.moveTo(x,Y(ch.mx[i])-0.5); g.lineTo(x,Y(ch.mn[i])+0.5)} g.lineWidth=Math.max(1,pw/n); g.stroke(); g.globalAlpha=1 }
  if(withMarks){
    if(ch.f){ g.strokeStyle=css("--accent-bright"); g.lineWidth=1.3; g.globalAlpha=.9; g.beginPath(); for(let i=0;i<n;i++){const x=X(i),y=Y(ch.f[i]); i?g.lineTo(x,y):g.moveTo(x,y)} g.stroke(); g.globalAlpha=1 }
    const few=F.fr.length<=120, cAway=css("--away"), cToward=css("--toward");
    for(const [c,d] of F.fr){
      const x=x0+c/n*pw, col=d>0?cAway:cToward;
      if(few){ g.strokeStyle=col; g.globalAlpha=.28; g.lineWidth=1; g.beginPath(); g.moveTo(x,y0+12); g.lineTo(x,y0+ph); g.stroke(); g.globalAlpha=1 }
      g.fillStyle=col; g.beginPath();
      if(d>0){ g.moveTo(x,y0+1); g.lineTo(x-4,y0+9); g.lineTo(x+4,y0+9) } else { g.moveTo(x,y0+9); g.lineTo(x-4,y0+1); g.lineTo(x+4,y0+1) }
      g.fill();
    }
  }
  if(withMarks&&F.board&&!F.board.laser.on){
    const msg="Laser off · enable it in Controls"; g.font="600 13px "+css("--f-head"); const tw=g.measureText(msg).width;
    g.fillStyle=css("--surface"); g.globalAlpha=.88; g.fillRect(x0+pw/2-tw/2-12,y0+ph/2-14,tw+24,28); g.globalAlpha=1;
    g.strokeStyle=css("--border"); g.strokeRect(x0+pw/2-tw/2-12+.5,y0+ph/2-14+.5,tw+24,28);
    g.fillStyle=css("--text-2"); g.textAlign="center"; g.textBaseline="middle"; g.fillText(msg,x0+pw/2,y0+ph/2) }
  g.restore();
}

function drawDisp(){
  const {g,w,h}=ctxOf("cv-disp"); if(!F) return;
  const d=F.disp, m=d.meas, t=d.truth, n=m.length; if(n<2) return;
  let lo=Infinity,hi=-Infinity; for(let i=0;i<n;i++){ lo=Math.min(lo,m[i]); hi=Math.max(hi,m[i]); if(t[i]!=null){lo=Math.min(lo,t[i]);hi=Math.max(hi,t[i])} }
  const um=units()==="um"||(units()==="auto"&&Math.max(Math.abs(lo),Math.abs(hi))>=10000);
  const k=um?1/1000:1, sc=autoscale("disp",lo*k,hi*k,um?1:400);
  const x0=PADL+8,y0=PADT,pw=w-x0-PADR,ph=h-PADT-PADB, span=d.span_s||n*d.dt_s;
  axes(g,x0,y0,pw,ph,sc.lo,sc.hi,v=>um?v.toFixed(Math.abs(sc.hi-sc.lo)<5?2:0)+"µm":Math.round(v)+"nm",-span,0,(v,d)=>v.toFixed(d)+" s");
  const X=i=>x0+i/(n-1)*pw, Y=v=>y0+ph-(v*k-sc.lo)/(sc.hi-sc.lo)*ph;
  g.save(); g.beginPath(); g.rect(x0,y0,pw,ph); g.clip();
  if(t.some(v=>v!=null)){ g.strokeStyle=css("--text-3"); g.lineWidth=1.4; g.setLineDash([5,4]); g.beginPath(); let st=false; for(let i=0;i<n;i++){ if(t[i]==null){st=false;continue} const x=X(i),y=Y(t[i]); st?g.lineTo(x,y):g.moveTo(x,y); st=true } g.stroke(); g.setLineDash([]) }
  g.strokeStyle=css("--accent"); g.lineWidth=1.8; g.beginPath(); for(let i=0;i<n;i++){const x=X(i),y=Y(m[i]); i?g.lineTo(x,y):g.moveTo(x,y)} g.stroke();
  // zero line
  const yz=Y(0); if(yz>y0&&yz<y0+ph){ g.strokeStyle=css("--text-3"); g.globalAlpha=.6; g.beginPath(); g.moveTo(x0,yz+.5); g.lineTo(x0+pw,yz+.5); g.stroke(); g.globalAlpha=1 }
  g.restore();
}

function drawSpec(){
  const {g,w,h}=ctxOf("cv-spec"); if(!F||!F.spec||!F.spec.ch1) return;
  const x0=PADL,y0=PADT,pw=w-PADL-PADR,ph=h-PADT-PADB, fmax=F.spec.f_max/1000;
  const lo=-110, hi=0;
  axes(g,x0,y0,pw,ph,lo,hi,v=>v+"",0,fmax,(v,d)=>v.toFixed(d)+" kHz");
  const draw=(a,col)=>{ const n=a.length; g.strokeStyle=col; g.lineWidth=1.2; g.beginPath(); for(let i=0;i<n;i++){const x=x0+(i+.5)/n*pw, y=y0+ph-(Math.max(lo,Math.min(hi,a[i]))-lo)/(hi-lo)*ph; i?g.lineTo(x,y):g.moveTo(x,y)} g.stroke() };
  g.save(); g.beginPath(); g.rect(x0,y0,pw,ph); g.clip();
  draw(F.spec.ch2,css("--ch2")); draw(F.spec.ch1,css("--accent"));
  const px=x0+F.spec.peak_hz/1000/fmax*pw; g.strokeStyle=css("--text-2"); g.setLineDash([2,3]); g.beginPath(); g.moveTo(px,y0); g.lineTo(px,y0+ph); g.stroke(); g.setLineDash([]);
  g.restore();
}

function render(){
  if(!F) return;
  drawChannel("cv-ch1",F.ch1,"ch1",css("--accent"),true);
  drawChannel("cv-ch2",F.ch2,"ch2",css("--ch2"),false);
  drawDisp(); drawSpec();
  const r=F.readout;
  $("#ro-disp").textContent=fmtDisp(r.disp_nm);
  $("#ro-disp2").textContent=Math.abs(r.disp_nm)<10000?(r.disp_nm/1000).toFixed(3)+" µm":Math.round(r.disp_nm).toLocaleString("en-US")+" nm";
  $("#ro-vel").textContent=fmtVel(r.vel_um_s);
  $("#ro-line").textContent=fmtDisp(r.disp_nm)+"  "+fmtVel(r.vel_um_s);
  $("#ro-rate").textContent=fmtHz(r.fringe_rate_hz);
  $("#ro-count").textContent=r.count.toLocaleString("en-US");
  const dp=$("#ro-dir"), moving=Math.abs(r.vel_um_s)>0.4*r.half_wave_nm/1000*10;
  if(!moving){dp.innerHTML="still";dp.style.color="var(--text-2)";dp.style.borderColor="var(--border)"}
  else if(r.vel_um_s>0){dp.innerHTML='<svg viewBox="0 0 10 10"><path d="M5 1l4 7H1z"/></svg>away';dp.style.color="var(--away)";dp.style.borderColor="var(--away)"}
  else {dp.innerHTML='<svg viewBox="0 0 10 10"><path d="M5 9L1 2h8z"/></svg>towards';dp.style.color="var(--toward)";dp.style.borderColor="var(--toward)"}
  const hasT=r.truth_nm!=null; $("#p-truth").classList.toggle("hide",!hasT); $("#lg-truth").classList.toggle("hide",!hasT);
  if(hasT){ $("#ro-truth").textContent=fmtDisp(r.truth_nm); $("#ro-err").textContent=Math.round(r.err_nm)+" nm"; $("#ro-rms").textContent=Math.round(r.rms_err_nm)+" nm"; $("#ro-max").textContent=Math.round(r.max_err_nm)+" nm" }
  const weak=F.board&&F.board.laser.on&&F.swing&&F.swing[0]<1.25*F.min_pp_codes;
  $("#ch1-r").innerHTML=(weak?`<span style="color:var(--yellow)" data-tip="The fringe swing is ${F.swing[0]} codes; the detector needs at least ${F.min_pp_codes}. Raise the second-stage gain or run Tune.">signal small · raise gain or Tune</span> · `:"")+F.win_ms.toFixed(F.win_ms<1?2:F.win_ms<10?1:0)+" ms window"+(F.paused?" · frozen":"");
  $("#ch2-r").textContent=(F.ch2.mx.length?"":"");
  $("#disp-r").textContent=F.disp.span_s.toFixed(1)+" s";
  $("#spec-r").textContent=F.spec&&F.spec.peak_hz?"peak "+fmtHz(F.spec.peak_hz)+" · "+fmtVel(F.spec.peak_hz*r.half_wave_nm/1000):"";
  const L=F.link, led=$("#led");
  const serial=S&&S.source&&S.source.kind==="serial";
  led.className="led "+(L.error?"bad":(L.connected?((L.crc_errors||L.gaps||L.dropped_bufs)?"warn":"ok"):"warn"));
  $("#st-link").textContent=L.error?L.error:(serial?(L.connected?"Pico streaming":"waiting for Pico"):"simulator running");
  $("#st-rate").textContent=(L.rate_sps/1000).toFixed(0)+" ksps total";
  $("#st-frames").textContent=serial?("frames "+L.frames):"";
  $("#st-err").textContent=serial?("crc "+L.crc_errors+" · gaps "+L.gaps+" · dropped "+L.dropped_bufs):"";
  $("#st-fps").textContent=fpsEMA.toFixed(0)+" fps";
  $("#st-rail").textContent=F.rail_v!=null?("analog rail "+F.rail_v.toFixed(2)+" V"+(serial?"":" (sim)")):"";
  const rec=F.rec, rb=$("#btn-record"); rb.classList.toggle("rec-on",!!rec); rb.setAttribute("aria-pressed",!!rec);
  $("#rec-hint").textContent=rec?("Recording "+rec.seconds.toFixed(1)+" s"+(rec.limit_seconds?" of "+rec.limit_seconds.toFixed(0):"")+" to "+rec.path.split(/[\\/]/).pop()):(F.rec_error?("Recording error: "+F.rec_error):"Not recording");
  const pb=$("#btn-pause"); pb.classList.toggle("is-on",F.paused); pb.setAttribute("aria-pressed",F.paused);
  renderBoard();
  renderStage();
}

// motion sliders per profile
const LOG=(lo,hi)=>({to:v=>Math.log(v/lo)/Math.log(hi/lo)*1000, from:x=>lo*Math.pow(hi/lo,x/1000)});
const MOTION={
  constant:[["speed_um_s","Speed",LOG(10,10000),v=>fmtVel(v),"Target speed. Fringe rate = speed / 329 nm."],["range_um","Travel",LOG(5,5000),v=>v>=1000?(v/1000).toFixed(2)+" mm":v.toFixed(0)+" µm","Travel before each reversal."]],
  sine:[["amp_um","Amplitude",LOG(0.5,200),v=>v.toFixed(v<10?1:0)+" µm","Zero-to-peak amplitude."],["freq_hz","Frequency",LOG(0.1,20),v=>v.toFixed(v<1?2:1)+" Hz","Cycles per second."]],
  step:[["step_um","Step",LOG(1,100),v=>v.toFixed(v<10?1:0)+" µm","Step size; the target returns after each dwell."],["dwell_s","Dwell",LOG(0.05,3),v=>v.toFixed(2)+" s","Time held at each end."]],
  hand:[["jitter_um","Wander",LOG(0.2,10),v=>v.toFixed(1)+" µm","RMS slow wander of a hand-held target."],["tremor_um","Tremor",LOG(0.02,2),v=>v.toFixed(2)+" µm","9 Hz tremor amplitude."]],
  hold:[],
  stage:[],
};
let builtFor=null;
function buildMotion(prof){
  if(builtFor===prof) return; builtFor=prof;
  const box=$("#motion-sliders"); box.innerHTML="";
  if(!MOTION[prof].length){ box.innerHTML=prof==="stage"?'<div class="hint">The target is the stage mirror: move it from the Stage tab.</div>':'<div class="hint">Target is still. Watch the noise floor and drift.</div>'; return }
  for(const [key,label,map,fmt,tip] of MOTION[prof]){
    const d=document.createElement("div"); d.className="slider"; d.dataset.tip=tip;
    d.innerHTML=`<span>${label}</span><input type="range" min="0" max="1000" step="1" id="${key==="speed_um_s"?"speed-slider":key+"-slider"}"><output></output>`;
    const inp=d.querySelector("input"), out=d.querySelector("output");
    inp.oninput=()=>{dragging=inp; const v=map.from(+inp.value); out.textContent=fmt(v); postSoon("sim",{[key]:+v.toPrecision(4)})};
    inp.onchange=()=>{dragging=null};
    inp._sync=()=>{ if(dragging===inp||!S) return; const v=S.sim[key]; inp.value=map.to(v); out.textContent=fmt(v) };
    box.appendChild(d);
  }
}
const LPMAP=LOG(2000,80000);
function applyState(){
  if(!S) return;
  const sim=S.sim, serial=S.source.kind==="serial";
  $("#src-sim").classList.toggle("is-on",!serial); $("#src-serial").classList.toggle("is-on",serial);
  $("#p-sim").classList.toggle("hide",serial);
  buildControls();
  $("#subj").textContent=serial?"Pico on "+S.source.port:"Simulator";
  $("#subj-meta").textContent=`250 ksps per channel · λ ${sim.wavelength_nm} nm · 1 fringe = ${sim.wavelength_nm/2} nm`+(serial?"":` · C ${sim.c}`+(sim.multimode?" · multimode":"")+(sim.board?" · board 1.3":" · board v1.1"));
  for(const b of document.querySelectorAll("[data-profile]")) b.classList.toggle("is-on",b.dataset.profile===sim.profile);
  buildMotion(sim.profile);
  for(const i of document.querySelectorAll("#motion-sliders input")) i._sync&&i._sync();
  if(dragging!==$("#c-slider")){ $("#c-slider").value=sim.c; } $("#c-out").textContent=(+sim.c).toFixed(2);
  if(dragging!==$("#noise-slider")){ $("#noise-slider").value=sim.noise; } $("#noise-out").textContent="x"+(+sim.noise).toFixed(1);
  const mm=$("#mm-toggle"); mm.classList.toggle("is-on",sim.multimode); mm.setAttribute("aria-pressed",sim.multimode);
  const bt=$("#board-toggle"); bt.classList.toggle("is-on",!!sim.board); bt.setAttribute("aria-pressed",!!sim.board);
  if(dragging!==$("#lp-slider")) $("#lp-slider").value=LPMAP.to(S.detect.lp_hz); $("#lp-out").textContent=fmtHz(S.detect.lp_hz);
  const st=S.settings; $("#s-fps").value=st.fps; $("#s-units").value=st.units; $("#s-format").value=st.record_format; $("#s-dir").value=st.record_dir;
  $("#s-thr").value=S.detect.threshold; $("#s-ttl").value=st.ttl_hours; $("#s-surface").value=st.surface;
  const inv=$("#s-invert"); inv.classList.toggle("is-on",S.detect.invert); inv.setAttribute("aria-pressed",S.detect.invert);
  $("#s-ver").textContent="smi-dash "+S.version+" · port "+S.port+" · thread "+S.thread;
  $("#st-ver").textContent="smi-dash "+S.version;
  syncWakeLock();
}
// Screen wake lock, only while the server's view.keep_awake is on (unattended recordings).
let wakeLock=null;
async function syncWakeLock(){
  const want=!!(S&&S.view&&S.view.keep_awake)&&document.visibilityState==="visible";
  if(want&&!wakeLock){
    if(!("wakeLock" in navigator)){console.warn("wake lock: not supported here");return}
    try{ wakeLock=await navigator.wakeLock.request("screen"); console.log("wake lock: held");
      wakeLock.addEventListener("release",()=>{console.log("wake lock: released");wakeLock=null}) }
    catch(e){ console.warn("wake lock: refused, "+e.name+": "+e.message) }
  } else if(!want&&wakeLock){ const w=wakeLock; wakeLock=null; await w.release() }
}
document.addEventListener("visibilitychange",syncWakeLock);

// controls
$("#src-sim").onclick=()=>post("source",{kind:"sim"});
$("#src-serial").onclick=()=>post("source",{kind:"serial"}).then(j=>{ if(j&&j.status==="ok") toast("Reading the Pico on "+j.data.port) });
for(const b of document.querySelectorAll("[data-profile]")) b.onclick=()=>post("sim",{profile:b.dataset.profile}).then(()=>post("zero",{},true));
$("#c-slider").oninput=e=>{dragging=e.target; $("#c-out").textContent=(+e.target.value).toFixed(2); postSoon("sim",{c:+e.target.value})};
$("#noise-slider").oninput=e=>{dragging=e.target; $("#noise-out").textContent="x"+(+e.target.value).toFixed(1); postSoon("sim",{noise:+e.target.value})};
$("#lp-slider").oninput=e=>{dragging=e.target; const v=Math.round(LPMAP.from(+e.target.value)/100)*100; $("#lp-out").textContent=fmtHz(v); postSoon("detect",{lp_hz:v})};
for(const id of ["#c-slider","#noise-slider","#lp-slider"]) $(id).onchange=()=>{dragging=null};
$("#mm-toggle").onclick=()=>{ const on=!S.sim.multimode; post("sim",{multimode:on}).then(()=>toast(on?"Second longitudinal mode on: fringes now fade every 1.46 mm":"Single longitudinal mode: steady fringe amplitude")) };
$("#btn-pause").onclick=()=>post("view",{paused:!F.paused});
$("#btn-zero").onclick=()=>post("zero",{});
$("#btn-record").onclick=()=>{ if(F&&F.rec) post("record/stop",{}); else post("record/start",{}) };
$("#btn-settings").onclick=()=>$("#modal").classList.add("show");
$("#btn-panel").onclick=()=>{ const a=document.querySelector("aside"), o=!a.classList.contains("open"); a.classList.toggle("open",o); $("#btn-panel").classList.toggle("is-on",o); $("#btn-panel").setAttribute("aria-pressed",o) };
$("#s-close").onclick=()=>$("#modal").classList.remove("show");
$("#modal").onclick=e=>{ if(e.target.id==="modal") $("#modal").classList.remove("show") };
const setS=(k,v)=>post("settings",{[k]:v}).then(j=>{ if(j&&j.status==="ok") toast("Saved: "+k.replace("_"," ")) });
$("#s-fps").onchange=e=>setS("fps",+e.target.value);
$("#s-units").onchange=e=>setS("units",e.target.value);
$("#s-format").onchange=e=>setS("record_format",e.target.value);
$("#s-dir").onchange=e=>setS("record_dir",e.target.value);
$("#s-ttl").onchange=e=>setS("ttl_hours",+e.target.value);
$("#s-surface").onchange=e=>setS("surface",e.target.value);
$("#s-thr").onchange=e=>post("detect",{threshold:+e.target.value}).then(()=>toast("Saved: detector threshold"));
$("#s-invert").onclick=()=>post("detect",{invert:!S.detect.invert}).then(()=>toast("Saved: direction "+(S.detect.invert?"normal":"inverted")));


// ---------------------------------------------------------------- Controls --
const BS=()=>F&&F.board, MAP=()=>S&&S.board_map;
function ctlIdx(role,ch,stage){const m=MAP(); if(!m) return -1; return m.controls.findIndex(c=>c.role===role&&(ch==null||c.channel===ch)&&(stage==null||c.stage===stage))}
function setTab(t){ if(!["board","stage","sim"].includes(t)) t="board";
  for(const k of ["board","stage","sim"]){ $("#tab-"+k).classList.toggle("is-on",t===k); $("#body-"+k).classList.toggle("hide",t!==k) }
  document.querySelector("aside").classList.toggle("board-mode",t!=="sim"); document.querySelector(".plots").classList.toggle("stage-mode",t==="stage");
  localStorage.setItem("smi-tab",t); requestAnimationFrame(render) }
$("#tab-board").onclick=()=>setTab("board"); $("#tab-stage").onclick=()=>setTab("stage"); $("#tab-sim").onclick=()=>setTab("sim"); setTab(localStorage.getItem("smi-tab")||"board");
const setCtl=(id,value,unit)=>post("board/set",{id,value,unit:unit||"units"});
let builtMap=null;
function buildControls(){
  const m=MAP(); if(!m||builtMap===S.board_map_hash) return; builtMap=S.board_map_hash;
  const li=ctlIdx("laser"), L=m.controls[li];
  const lim=Math.min(L.max,L.rated||L.max); $("#cur-slider").max=lim.toFixed(2); $("#cur-input").max=lim.toFixed(2);
  // Every set-point write on this board disarms the head and restarts its
  // soft-start, so the slider sends once, on release.
  $("#cur-slider").oninput=e=>{dragging=e.target; $("#cur-input").value=(+e.target.value).toFixed(1)};
  $("#cur-slider").onchange=e=>{dragging=null; setCtl(L.id,+e.target.value)};
  $("#cur-input").onchange=e=>{ const v=+e.target.value; setCtl(L.id,v).then(j=>{ if(j&&j.status==="ok") toast(L.ramp_per_s?("Laser set-point "+v.toFixed(2)+" mA, ramping at "+L.ramp_per_s+" mA/s"):("Laser set-point "+v.toFixed(2)+" mA; the head's soft-start ramps it")) }) };
  const box=$("#offset-rows"); box.innerHTML="";
  for(const ch of [1,2]){ const i=ctlIdx("offset",ch); if(i<0) continue; const c=m.controls[i];
    const d=document.createElement("div"); d.className="numrow"; d.dataset.tip=`${c.label}: offset DAC, ${c.min} to ${c.max.toFixed(3)} V. Mean of the channel shown on the right (mid-scale is 2048).`;
    d.innerHTML=`<span>Ch ${ch} <b id="off${ch}-mean" style="font:500 10px var(--f-mono);color:var(--text-3);white-space:nowrap"></b></span><input type="range" min="${c.min}" max="${c.max}" step="${c.per_code}" id="off${ch}-slider"><output id="off${ch}-out" style="font:11px var(--f-mono);color:var(--text);text-align:right"></output>`;
    const inp=d.querySelector("input"); inp.oninput=()=>{dragging=inp}; inp.onchange=()=>{dragging=null; setCtl(c.id,+inp.value)};
    d.dataset.ctlOffset=c.id;
    box.appendChild(d) }
  const sw=$("#switch-rows"); sw.innerHTML="";
  for(const c of m.controls){ if(c.kind!=="switch") continue;
    const seen=new Set(), sets=c.settings.filter(x=>{ if(seen.has(x.value)) return false; seen.add(x.value); return true });
    const r=document.createElement("div"); r.className="sw-row"; r.dataset.ctl=c.id;
    r.dataset.tip=c.label+(c.safety?". Board note: "+c.safety:"")+(c.requires_laser_off?" Locked while the laser is on.":"");
    const short=c.role==="bias"?"Mon. bias":`Ch ${c.channel} ${c.stage==="tia"?"TIA":"stage 2"}`;
    r.innerHTML=`<span>${short}</span><div class="seg">${sets.map(x=>`<button data-ctl="${c.id}" data-v="${x.value}" data-tip="${c.label}: ${x.label}">${c.role==="bias"?x.label.split(" ")[0]:x.label}</button>`).join("")}</div>`;
    for(const b of r.querySelectorAll("button")) b.onclick=()=>{ if(r.classList.contains("locked")){toast(c.label+": turn the laser off first (board rule)","error");return}
      setCtl(c.id,+b.dataset.v).then(j=>{ if(j&&j.status==="ok"&&c.stage==="amp") toast(c.label+" "+b.textContent+". Auto-centre to re-centre the channel.") }) };
    sw.appendChild(r) }
}
// interlock + hold-to-enable
let armed=false, holdT=0, holdRaf=0;
function setArmed(a){ armed=a; const il=$("#laser-interlock"); il.classList.toggle("is-on",a); il.setAttribute("aria-checked",a); $("#laser-hold").disabled=!a }
$("#laser-interlock").onclick=()=>setArmed(!armed);
const hb=$("#laser-hold");
function holdStop(){ cancelAnimationFrame(holdRaf); holdT=0; $("#laser-fill").style.width="0" }
hb.addEventListener("pointerdown",e=>{ if(hb.disabled) return; holdT=performance.now(); hb.setPointerCapture(e.pointerId);
  const step=()=>{ const k=(performance.now()-holdT)/1000; $("#laser-fill").style.width=Math.min(100,k*100)+"%";
    if(k>=1){ holdStop(); post("board/laser",{on:true,confirm:"beam-safe"}) } else holdRaf=requestAnimationFrame(step) }; holdRaf=requestAnimationFrame(step) });
hb.addEventListener("pointerup",holdStop); hb.addEventListener("pointercancel",holdStop);
hb.addEventListener("click",e=>{ if(!e.isTrusted) toast("Enabling needs a one-second hold (or `smi-dash laser on --beam-safe`)","error") });
$("#laser-off").onclick=()=>post("board/laser",{on:false});
$("#btn-clear-fault").onclick=()=>post("board/clear_fault",{});
$("#btn-centre").onclick=()=>{ $("#btn-centre").textContent="Centring…"; post("board/auto_centre",{channels:[1,2]}).finally(()=>{$("#btn-centre").textContent="Auto-centre"}) };
$("#btn-tune").onclick=()=>post("board/tune",{}).then(j=>{ if(j&&j.status==="ok") toast("Tuning: stepping the laser current and scoring fringes") });
$("#btn-tune-stop").onclick=()=>post("board/tune/stop",{});
$("#board-toggle").onclick=()=>post("sim",{board:!S.sim.board});
const curHist=[];
function drawCur(lim){
  const {g,w,h}=ctxOf("cv-cur"); if(curHist.length<2) return;
  const t1=curHist[curHist.length-1][0], t0=t1-20000, X=t=>(t-t0)/20000*w, Y=v=>h-2-(v/lim)*(h-4);
  g.strokeStyle=css("--border"); g.beginPath(); g.moveTo(0,Y(0)+.5); g.lineTo(w,Y(0)+.5); g.stroke();
  for(const [k,col,lw] of [[1,css("--text-3"),1.2],[2,css("--accent-bright"),1.5]]){ g.strokeStyle=col; g.lineWidth=lw; g.beginPath(); let st=false;
    for(const p of curHist){ if(p[k]==null){st=false;continue} const x=X(p[0]),y=Y(p[k]); st?g.lineTo(x,y):g.moveTo(x,y); st=true } g.stroke() }
}
function renderBoard(){
  const b=BS(), has=!!b; $("#p-laser").style.opacity=has?1:.5;
  for(const id of ["#p-offsets","#p-gains","#p-tune"]) $(id).style.opacity=has?1:.5;
  if(!has){ $("#laser-pill").textContent="NO BOARD"; $("#laser-pill").className="pill"; $("#laser-why").textContent=S&&S.source.kind==="sim"?"v1.1 model":"no STATE from the Pico"; return }
  buildControls();
  const m=MAP(), li=ctlIdx("laser"), L=m.controls[li], l=b.laser, lim=Math.min(L.max,L.rated||L.max);
  const pill=$("#laser-pill");
  if(b.fault){pill.textContent="FAULT";pill.className="pill fault"} else if(l.on&&l.ramping){pill.textContent="WRITING";pill.className="pill ramp"} else if(l.on){pill.textContent="ON";pill.className="pill on"} else {pill.textContent="OFF";pill.className="pill"}
  $("#laser-why").textContent=l.on?"":l.state.replace(/^off: /,"").replace("off since power-up","since power-up");
  if(!l.on&&armed&&!holdT&&lastOn) setArmed(false); lastOn=l.on;
  $("#laser-hold-t").textContent=l.on?"Laser is on":"Hold to enable"; if(l.on) $("#laser-hold").disabled=true; else $("#laser-hold").disabled=!armed;
  $("#ro-target").textContent=l.target_mA.toFixed(2)+" mA"; $("#ro-setp").textContent=l.setpoint_mA.toFixed(2)+" mA";
  $("#ro-meas").textContent=l.measured_mA==null?"n/a":l.measured_mA.toFixed(2)+" mA";
  if(dragging!==$("#cur-slider")) $("#cur-slider").value=l.target_mA;
  if(document.activeElement!==$("#cur-input")) $("#cur-input").value=l.target_mA.toFixed(1);
  const now=performance.now(); if(!curHist.length||now-curHist[curHist.length-1][0]>100){ curHist.push([now,l.on?l.setpoint_mA:0,l.measured_mA]); while(curHist.length&&curHist[0][0]<now-21000) curHist.shift() }
  drawCur(Math.max(lim,1));
  $("#fault-line").classList.toggle("hide",!b.fault); $("#fault-text").textContent="Fault: "+b.fault_text;
  $("#map-warn").classList.toggle("hide",b.map_match!==false);
  for(const ch of [1,2]){ const i=ctlIdx("offset",ch); if(i<0) continue; const c=b.controls[i], sl=$("#off"+ch+"-slider"); if(!sl) continue;
    if(dragging!==sl) sl.value=c.applied;
    const lockO=!!(m.controls[i].requires_laser_off&&l.on); sl.disabled=lockO; sl.closest(".numrow").style.opacity=lockO?.5:1;
    sl.closest(".numrow").dataset.tip=lockO?"Locked while the laser is on (board rule: no writes while armed). Auto-centre turns it off, writes and turns it back on.":sl.closest(".numrow").dataset.tip; $("#off"+ch+"-out").textContent=c.applied.toFixed(3)+" V"; $("#off"+ch+"-mean").textContent=F.means?"mean "+F.means[ch-1]:"" }
  for(const r of document.querySelectorAll(".sw-row[data-ctl]")){ const i=m.controls.findIndex(c=>c.id===r.dataset.ctl); const c=b.controls[i]; const mc=m.controls[i];
    r.classList.toggle("locked",!!(mc.requires_laser_off&&l.on));
    for(const btn of r.querySelectorAll("button")) btn.classList.toggle("is-on",Math.abs(+btn.dataset.v-c.target)<=Math.abs(c.target)*1e-3+1e-9) }
  const t=F.tune||{}, n=(t.steps||[]).length;
  $("#tune-bar").style.width=(t.status==="done"?100:t.status==="running"?Math.min(95,n/19*100):0)+"%";
  if(t.status==="running"&&t.last) $("#tune-msg").textContent=`${t.phase}: ${t.last.set_mA.toFixed(1)} mA, score ${t.last.score}`+(t.last.gain!=null?`, gain ${t.last.gain}`:"");
  else if(t.status==="done") $("#tune-msg").textContent=`Best ${t.best_mA.toFixed(2)} mA, score ${t.final_score.toFixed(1)}`+(t.gain&&t.gain.label?`, ${t.gain.label}`:"")+` (${n} steps, ${t.seconds.toFixed(1)} s)`;
  else if(t.status==="failed") $("#tune-msg").textContent="Stopped: "+t.error;
  $("#tune-t").textContent=t.status==="running"&&t.last?`${t.last.set_mA.toFixed(1)} mA`:t.status==="done"?`${t.best_mA.toFixed(1)} mA`+(t.gain&&t.gain.label?` · ${t.gain.label}`:""):t.status==="failed"?"stopped":"";
  $("#tune-t").dataset.tip=$("#tune-msg").textContent;
  $("#btn-tune").disabled=!l.on||t.status==="running"; $("#btn-tune").style.opacity=$("#btn-tune").disabled?.5:1;
}
let lastOn=false;

// ------------------------------------------------------------------- Stage --
const STEP_SIZES=[1,8,32,128,512], SPEEDS=[80,160,320,640];
let stepSize=+(localStorage.getItem("smi-step")||128);
const stageCmd=(action,value)=>post("stage/cmd",value==null?{action}:{action,value});
(function(){
  const sz=$("#st-sizes"); sz.innerHTML=STEP_SIZES.map(n=>`<button data-n="${n}" data-tip="${n} pulse${n>1?"s":""}, ${(n*15.625).toFixed(n<8?1:0)} nm nominal">${n}</button>`).join("");
  for(const b of sz.querySelectorAll("button")) b.onclick=()=>{ stepSize=+b.dataset.n; localStorage.setItem("smi-step",stepSize); renderStage() };
  const sp=$("#st-speeds"); sp.innerHTML=SPEEDS.map(n=>`<button data-n="${n}" data-tip="${n} pulses/s, ${(n*15.625/1000).toFixed(2)} µm/s nominal">${n}</button>`).join("");
  for(const b of sp.querySelectorAll("button")) b.onclick=()=>stageCmd("speed",+b.dataset.n);
})();
$("#st-home").onclick=()=>stageCmd("home").then(j=>{ if(j&&j.status==="ok") toast("Homing: configuring the TMC2209, then seeking the HOME edge") });
$("#st-stop").onclick=()=>stageCmd("stop");
$("#st-off").onclick=()=>stageCmd("off").then(j=>{ if(j&&j.status==="ok") toast("Stage driver off; home again before moving") });
$("#st-neg").onclick=()=>stageCmd("step",-stepSize);
$("#st-posb").onclick=()=>stageCmd("step",stepSize);
$("#st-test").onclick=()=>stageCmd("selftest").then(j=>{ if(j&&j.status==="ok") toast("Self-test: to 128, +128 four times, -128 four times, 1 s plateaus") });
let calArmed=false;
function setCalArmed(a){ calArmed=a; const il=$("#cal-interlock"); il.classList.toggle("is-on",a); il.setAttribute("aria-checked",a); $("#cal-go").disabled=!a }
$("#cal-interlock").onclick=()=>setCalArmed(!calArmed);
$("#cal-go").onclick=()=>{ if(!calArmed) return; post("calibrate",{confirm:"beam-safe"}).then(j=>{ if(j&&j.status==="ok") toast("Calibrate: the stage is the moving target") }) };
const nmFmt=v=>v==null||!isFinite(v)?"n/a":Math.abs(v)>=10000?(v/1000).toFixed(2)+" µm":Math.round(v).toLocaleString("en-US")+" nm";
function drawStage(){
  const {g,w,h}=ctxOf("cv-stage"); const st=F&&F.stage; if(!st) return;
  const tr=st.trace, n=tr.t.length;
  const x0=PADL+14,y0=PADT,pw=w-x0-PADR,ph=h-PADT-PADB;
  if(n<2){ axes(g,x0,y0,pw,ph,0,25,v=>v+"µm",-30,0,(v,d)=>v.toFixed(d)+" s"); return }
  let lo=Infinity,hi=-Infinity; for(const a of [tr.cmd,tr.meas,tr.truth]) for(const v of a){ if(v==null) continue; lo=Math.min(lo,v); hi=Math.max(hi,v) }
  const sc=autoscale("stage",lo/1000,hi/1000,2);
  axes(g,x0,y0,pw,ph,sc.lo,sc.hi,v=>(Math.abs(sc.hi-sc.lo)<6?v.toFixed(1):v.toFixed(0))+"µm",-30,0,(v,d)=>v.toFixed(d)+" s");
  const X=t=>x0+(t+30)/30*pw, Y=v=>y0+ph-(v/1000-sc.lo)/(sc.hi-sc.lo)*ph;
  g.save(); g.beginPath(); g.rect(x0,y0,pw,ph); g.clip();
  const line=(a,col,lw,dash,step)=>{ g.strokeStyle=col; g.lineWidth=lw; g.setLineDash(dash||[]); g.beginPath(); let on=false, py=0;
    for(let i=0;i<n;i++){ if(a[i]==null){on=false;continue} const x=X(tr.t[i]), y=Y(a[i]); if(!on){g.moveTo(x,y);on=true} else { if(step) g.lineTo(x,py); g.lineTo(x,y) } py=y } g.stroke(); g.setLineDash([]) };
  if(tr.truth.some(v=>v!=null)) line(tr.truth,css("--text-3"),1.3,[5,4]);
  line(tr.cmd,css("--yellow"),1.6,null,false);
  line(tr.meas,css("--accent"),2,null,true);
  g.restore();
}
function renderStage(){
  const st=F&&F.stage; if(!st) return;
  if(!$("#card-stage").offsetParent&&$("#body-stage").classList.contains("hide")) { /* not shown */ } else drawStage();
  $("#stage-sim").classList.toggle("hide",!st.simulated); $("#lg-stage-truth").classList.toggle("hide",!st.simulated);
  const s=st.state, pill=$("#stage-pill");
  for(const b of document.querySelectorAll("#st-sizes button")) b.classList.toggle("is-on",+b.dataset.n===stepSize);
  $("#st-neg").textContent="◀ "+stepSize+" towards HOME"; $("#st-posb").textContent="away "+stepSize+" ▶";
  if(!s){ pill.textContent="NO STAGE"; pill.className="pill"; $("#st-line").textContent="No STAGE frames: the Pico needs firmware 1.3.1"; return }
  pill.textContent=s.state.toUpperCase(); pill.className="pill "+(s.state==="faulted"?"fault":s.moving?"move":s.state==="idle"?"idle":"");
  for(const b of document.querySelectorAll("#st-speeds button")) b.classList.toggle("is-on",+b.dataset.n===s.rate_pps);
  const scale=st.scale_nm_per_pulse, tr=st.trace, k=tr.t.length-1;
  $("#st-pos").textContent=s.homed?s.pos_pulses+" p":"not homed";
  $("#st-cmd").textContent=s.homed?nmFmt(s.pos_pulses*scale):"n/a";
  $("#st-meas").textContent=k>=0&&s.homed?nmFmt(tr.meas[k]):"n/a";
  $("#st-line").textContent=(s.fault?"Fault: "+s.fault_text:(s.enabled?(s.homed?"Homed":"Enabled, not homed"):"Driver off (disabled at boot)"))+" · HOME "+(s.home_in?"open":"closed")+" · "+s.rate_pps+" pulses/s · "+scale.toFixed(3)+" nm/pulse"+(st.calibrated?" (calibrated)":" (nominal)");
  const busy=s.moving||s.state==="homing"||s.state==="selftest", ready=s.homed&&s.enabled&&!busy;
  $("#st-neg").disabled=!ready; $("#st-posb").disabled=!ready; $("#st-test").disabled=busy;
  for(const id of ["#st-neg","#st-posb","#st-test"]) $(id).style.opacity=$(id).disabled?.5:1;
  $("#stage-r").textContent=(st.simulated?"simulated · ":"")+scale.toFixed(3)+" nm/pulse"+(st.calibrated?" (calibrated)":" nominal");
  // self-test
  const t=st.selftest||{};
  if(t.status==="running"){ $("#st-test-t").textContent="rung "+(t.rung||0)+" of 8"; $("#st-r1").textContent="Running: origin 128, ±128 pulse rungs, 1 s plateaus"; $("#st-r2").textContent=""; $("#st-r3").textContent=""; $("#st-r1").className="resline" }
  else if(t.status==="done"){ const c=t.counted, lab=t.label;
    $("#st-test-t").textContent=lab;
    if(t.scale_nm_per_pulse!=null){ $("#st-r1").innerHTML=`Scale <b>${t.scale_nm_per_pulse.toFixed(3)} nm/pulse</b> (${((t.scale_nm_per_pulse/15.625-1)*100).toFixed(1)} %), ${t.scale_edges} edges`; $("#st-r1").className="resline" }
    else { $("#st-r1").textContent=t.warning||"Fringes were missed"; $("#st-r1").className="resline warn" }
    $("#st-r2").innerHTML=`Return residual <b>${Math.round(c.return_residual_nm)} nm</b> counted (±${Math.round(t.resolution_nm)} nm resolution)`;
    $("#st-r3").textContent=t.truth?`Simulated mirror: ${t.truth.return_residual_drift_corrected_nm.toFixed(1)} nm return, ${t.truth.nm_per_pulse.toFixed(3)} nm/pulse`:`Plateau fit ${c.nm_per_pulse.toFixed(3)} nm/pulse, drift ${c.drift_nm_s.toFixed(1)} nm/s`;
    $("#st-r1").dataset.tip=t.note; }
  else if(t.status==="failed"){ $("#st-test-t").textContent="failed"; $("#st-r1").textContent=t.error; $("#st-r1").className="resline warn"; $("#st-r2").textContent=""; $("#st-r3").textContent="" }
  // calibrate
  const c=st.calib||{};
  $("#cal-bar").style.width=(c.status==="done"?100:c.status==="running"?Math.min(95,(c.step_n||0)/(c.steps_total||6)*100):0)+"%";
  $("#cal-t").textContent=c.status==="running"?(c.step_n+"/"+c.steps_total+" "+c.step):c.status==="done"?(c.label+", "+Math.round(c.seconds)+" s"):c.status==="failed"?"stopped":"";
  if(c.status==="running"||c.status==="done") $("#cal-go").disabled=true; else $("#cal-go").disabled=!calArmed;
  if(c.status==="done"&&calArmed) setCalArmed(false);
  const tb=$("#cal-table");
  if(c.status==="done"){ const b=c.before, a=c.after, f=(v,d)=>v==null||!isFinite(v)?"n/a":(+v).toFixed(d);
    const rows=[["Laser current, mA",f(b.settings.laser_mA,1),f(a.settings.laser_mA,1)],["Ch 1 stage-2 gain",f(b.settings.ch1_gain,0),f(a.settings.ch1_gain,0)],
      ["Fringe score, moving",f(b.check.moving_score,1),f(a.check.moving_score,1)],["Step "+b.check.pulses+" p, counted",nmFmt(b.check.counted_nm),nmFmt(a.check.counted_nm)],
      ["Fringes counted",f(b.check.counted_fringes,0),f(a.check.counted_fringes,0)],["Scale, nm/pulse",f(b.check.nm_per_pulse_edge_fit,3),f(a.check.nm_per_pulse_edge_fit,3)]];
    if(c.simulated) rows.push(["Simulated mirror",nmFmt(b.check.truth_nm),nmFmt(a.check.truth_nm)]);
    tb.innerHTML=`<tr><td></td><th>before</th><th>after</th></tr>`+rows.map((r,i)=>`<tr><td>${r[0]}</td><td class="n">${r[1]}</td><td class="n${i>=2&&i<=5?" good":""}">${r[2]}</td></tr>`).join("");
    tb.dataset.tip=(c.scale_note||"")+". "+(c.note||"") }
  else if(c.status==="running"&&c.before){ tb.innerHTML=`<tr><td>Before: step ${c.before.check.pulses} p counted</td><td class="n">${nmFmt(c.before.check.counted_nm)}</td></tr><tr><td>Fringes counted</td><td class="n">${c.before.check.counted_fringes}</td></tr>` }
  else if(c.status==="failed") tb.innerHTML=`<tr><td style="color:var(--yellow);white-space:normal">${c.error}</td></tr>`;
  else if(c.status!=="running") tb.innerHTML="";
}

// zoom and pan
function wheelOn(id,fn){ document.getElementById(id).parentElement.addEventListener("wheel",e=>{e.preventDefault();fn(e.deltaY>0?1.25:0.8)},{passive:false}) }
let pendingWin=null;
const zoomWin=f=>{ const cur=pendingWin||S.view.window_ms; pendingWin=Math.max(0.1,Math.min(2000,cur*f)); postSoon("view",{window_ms:+pendingWin.toPrecision(3)},60); setTimeout(()=>{pendingWin=null},400) };
wheelOn("cv-ch1",zoomWin); wheelOn("cv-ch2",zoomWin);
wheelOn("cv-disp",f=>postSoon("view",{history_s:Math.max(0.5,Math.min(120,S.view.history_s*f))},60));
for(const id of ["cv-ch1","cv-ch2"]){
  const el=document.getElementById(id).parentElement;
  el.addEventListener("dblclick",()=>post("view",{window_ms:10}));
  let drag=null;
  el.addEventListener("mousedown",e=>{ if(F&&F.paused) drag={x:e.clientX,pan:S.view.pan_ms,w:el.clientWidth} });
  window.addEventListener("mousemove",e=>{ if(!drag) return; const ms=(e.clientX-drag.x)/drag.w*F.win_ms; postSoon("view",{pan_ms:Math.max(0,drag.pan+ms)},40) });
  window.addEventListener("mouseup",()=>{drag=null});
}

// live channel
function connect(){
  const es=new EventSource("events");
  es.addEventListener("state",e=>{ S=JSON.parse(e.data); applyState() });
  es.addEventListener("frame",e=>{ F=JSON.parse(e.data); const now=performance.now(); frameTimes.push(now); while(frameTimes.length&&frameTimes[0]<now-1000) frameTimes.shift(); fpsEMA=frameTimes.length; if(!renderPending){renderPending=true; requestAnimationFrame(()=>{renderPending=false; render()})} });
  es.addEventListener("toast",e=>{ const d=JSON.parse(e.data); toast(d.text,d.kind) });
  es.addEventListener("click",e=>{ const d=JSON.parse(e.data); aiCursor(d.selector,d.label||"AI",el=>el.click()) });
  es.addEventListener("cursor",e=>{ const d=JSON.parse(e.data); aiCursor(d.selector,d.label||"AI") });
  es.addEventListener("reveal",e=>{ const d=JSON.parse(e.data); const el=document.querySelector(d.selector); if(!el) return console.warn("reveal: no "+d.selector); if(el.closest("#modal")) $("#modal").classList.add("show"); el.scrollIntoView({block:"nearest"}); aiCursor(d.selector,d.label||"here") });
  es.addEventListener("reload",()=>location.reload());
  es.addEventListener("tab",e=>setTab(JSON.parse(e.data).tab));
  es.addEventListener("fullscreen",e=>{ const on=JSON.parse(e.data).on;
    const p=on?document.documentElement.requestFullscreen():(document.fullscreenElement?document.exitFullscreen():Promise.resolve());
    p.then(()=>console.log("fullscreen "+(on?"on":"off"))).catch(err=>console.warn("fullscreen refused: "+err.message)) });
  es.onerror=()=>{ $("#led").className="led bad"; $("#st-link").textContent="server not reachable, retrying" };
}
window.addEventListener("resize",()=>requestAnimationFrame(render));
document.addEventListener("visibilitychange",()=>console.log("visibility "+document.visibilityState));
let rafCount=0; (function tick(){rafCount++; requestAnimationFrame(tick)})();
setInterval(()=>{console.log(`heartbeat: ${fpsEMA} frames/s received, ${rafCount} animation frames in 10 s, visibility ${document.visibilityState}`); rafCount=0},10000);
connect();
</script>
</body>
</html>