From 44d6e754bd16d2f126ac7fe2bd3e7330138d9638 Mon Sep 17 00:00:00 2001 From: serversdown Date: Thu, 29 Oct 2026 11:50:24 -0400 Subject: [PATCH] feat(webapp): name a unit by serial; series badge from the unit's own answer; Hang up for Series 4 - A Serial field beside host/port. With one, the Live tabs use the serial-based endpoints (both series); without, every read behaves as before. - The series badge, Hang up (Series 4), Diagnostics (Series 3), call-home read and the disabled config/call-home writes all follow applyControls() <- controlsFor() on the unit's own /device/info answer; editing the serial, host or port drops the confirmation. Erase additionally needs a confirmed Series 3. - Every /device/ request goes through deviceRequest/deviceFetch <- deviceUrl (a static test enforces it); the legacy per-event routes joined deviceUrl (event_waveform / event_file, index in the path). - The status panel and Device tab read both shapes (shared and legacy). - In serial mode the connect skips the legacy storage_range read (one connection fewer; a Micromate has no such route). Start/stop without a serial behave as before; with one, only for a confirmed series. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 --- sfm/sfm_webapp.html | 220 +++++++++++++++++++--------- tests/test_webapp_device_routing.py | 19 +++ 2 files changed, 166 insertions(+), 73 deletions(-) diff --git a/sfm/sfm_webapp.html b/sfm/sfm_webapp.html index 6e6caad..5d4c9b7 100644 --- a/sfm/sfm_webapp.html +++ b/sfm/sfm_webapp.html @@ -147,6 +147,15 @@ } #monitor-panel.monitoring { border-left: 3px solid var(--green); } #monitor-panel.idle { border-left: 3px solid var(--text-mute); } + .series-badge { + font-size: 12px; + font-weight: 700; + padding: 2px 10px; + border-radius: 10px; + border: 1px solid var(--accent, #58a6ff); + color: var(--accent, #58a6ff); + align-self: center; + } .mon-status-badge { font-size: 12px; font-weight: 700; @@ -843,7 +852,13 @@ + + + + @@ -1485,16 +1500,25 @@ const DEVICE_ROUTES = { call_home_read: ['GET', '/device/call_home', false], call_home_write: ['POST', '/device/call_home', false], config_write: ['POST', '/device/config', false], + event_waveform: ['GET', '/device/event/{index}/waveform', false], + event_file: ['GET', '/device/event/{index}/blastware_file', false], }; function deviceUrl(action, unit, params = {}) { const route = DEVICE_ROUTES[action]; if (!route) throw new Error(`unknown device action: ${action}`); - const [method, path, needsSerial] = route; + const [method, template, needsSerial] = route; if (needsSerial && !normSerial(unit.serial)) return null; + const rest = { ...params }; + let path = template; + if (path.includes('{index}')) { // the legacy per-event routes + if (rest.index === undefined) throw new Error(`${action} needs params.index`); + path = path.replace('{index}', encodeURIComponent(rest.index)); + delete rest.index; + } // Hang-up releases whatever line is held at the address: no serial. let query = action === 'hangup' ? unitQuery({ ...unit, serial: '' }) : unitQuery(unit); - for (const [k, v] of Object.entries(params)) query += `&${k}=${encodeURIComponent(v)}`; + for (const [k, v] of Object.entries(rest)) query += `&${k}=${encodeURIComponent(v)}`; return { method, path: `${path}?${query}` }; } @@ -1590,9 +1614,63 @@ function onForceToggle() { document.getElementById('force-toggle').classList.toggle('active', forceRefresh); } -function deviceParams() { - const base = `host=${encodeURIComponent(devHost())}&tcp_port=${devPort()}`; - return forceRefresh ? `${base}&force=true` : base; +// The unit as named in the bar. `confirmed` is the unit's own /device/info +// answer ({serial, series}); it is cleared whenever the serial, host or port is +// edited, so a series-specific control never outlives the identify behind it. +let unitConfirmed = null; + +function currentUnit() { + return { serial: document.getElementById('dev-serial').value, + host: devHost(), tcpPort: devPort(), confirmed: unitConfirmed }; +} + +function serialMode() { return Boolean(normSerial(currentUnit().serial)); } + +// Every device request goes through deviceUrl (the device-routing block). +async function deviceRequest(action, params = {}, opts = {}) { + const extra = forceRefresh && (DEVICE_ROUTES[action] || [])[0] === 'GET' ? { ...params, force: 'true' } : params; + const u = deviceUrl(action, currentUnit(), extra); + if (!u) throw new Error(`${action} needs a serial`); + return fetch(`${api()}${u.path}`, { method: u.method, ...opts }); +} + +async function deviceFetch(action, params = {}, opts = {}) { + const r = await deviceRequest(action, params, opts); + const body = await r.json().catch(() => ({})); + if (!r.ok) { + const d = body.detail; + const err = new Error(typeof d === 'string' ? d : (d && d.message) || r.statusText); + err.status = r.status; err.body = body; + throw err; + } + return body; +} + +// Every series-specific control, from controlsFor (the device-routing block). +function applyControls() { + const unit = currentUnit(); + const c = controlsFor(unit); + const series = confirmedSeries(unit); + const badge = document.getElementById('series-badge'); + badge.hidden = series == null; + badge.textContent = series ? `Series ${series}` : ''; + document.getElementById('hangup-btn').hidden = !c.hangup; + setDiagButtonsEnabled(c.diagnostics); + const cw = document.getElementById('cfg-write-btn'); + cw.disabled = !c.configWrite; cw.title = c.reasons.configWrite; + const hw = document.getElementById('ch-write-btn'); + hw.disabled = !c.callHomeWrite; hw.title = c.reasons.callHomeWrite; + document.getElementById('ch-read-btn').disabled = !c.callHomeRead; + setMonitorButtons(); +} + +async function hangUp() { + try { + const r = await deviceFetch('hangup'); + setStatus(r.hung_up ? 'Line released.' : 'No line was being held.', 'ok'); + } catch (e) { + setStatus(`Hang up failed: ${e.message}`, 'error'); + } } // ── Section switching ───────────────────────────────────────────────────────── @@ -1657,13 +1735,15 @@ async function connectUnit() { setStatus('Connecting — reading device info…', 'loading'); try { - const r = await fetch(`${api()}/device/info?${deviceParams()}`); - if (!r.ok) { const e = await r.json().catch(() => ({})); throw new Error(e.detail || r.statusText); } - unitInfo = await r.json(); + unitInfo = await deviceFetch('info'); } catch (e) { setStatus(`Connection failed: ${e.message}`, 'error'); btn.disabled = false; btn.textContent = 'Connect'; return; } + // The unit's own answer confirms its series; a legacy identify (no serial + // typed) answers with its serial alone. + unitConfirmed = { serial: unitInfo.serial, + series: unitInfo.series ?? seriesFromSerial(unitInfo.serial) }; // Connecting deliberately does NOT walk the event chain. That walk reads // every event header over the cellular link and can take minutes — or fail @@ -1671,7 +1751,9 @@ async function connectUnit() { // probes instead; the event list is opt-in via loadEventList(). eventList = []; eventsLoaded = false; setStatus('Reading device state…', 'loading'); - storageInfo = await fetchJson(`/device/events/storage_range`).catch(() => null); + // A legacy MiniMate read: skipped in serial mode (one connection fewer, and a + // Micromate has no such route). + storageInfo = serialMode() ? null : await deviceFetch('storage_range').catch(() => null); populateDeviceBar(); populateDeviceTab(); @@ -1682,11 +1764,8 @@ async function connectUnit() { document.getElementById('monitor-panel').style.display = 'flex'; setEventButtonsEnabled(); document.getElementById('load-events-btn').disabled = false; - setDiagButtonsEnabled(true); document.getElementById('cfg-read-btn').disabled = false; - document.getElementById('cfg-write-btn').disabled = false; - document.getElementById('ch-read-btn').disabled = false; - document.getElementById('ch-write-btn').disabled = false; + applyControls(); btn.disabled = false; btn.textContent = 'Reconnect'; @@ -1705,13 +1784,6 @@ async function connectUnit() { } // ── Shared fetch helper ──────────────────────────────────────────────────────── -async function fetchJson(path, opts) { - const sep = path.includes('?') ? '&' : '?'; - const r = await fetch(`${api()}${path}${sep}${deviceParams()}`, opts); - const body = await r.json().catch(() => ({})); - if (!r.ok) throw new Error(body.detail || r.statusText); - return body; -} function setEventButtonsEnabled() { const n = eventList.length; @@ -1729,7 +1801,7 @@ async function loadEventList() { btn.disabled = true; setStatus('Walking the event chain — this can take a while…', 'loading'); try { - const evData = await fetchJson('/device/events'); + const evData = await deviceFetch('events'); eventList = evData.events || []; eventsLoaded = true; // /device/events re-reads compliance; fold it in. @@ -1749,7 +1821,7 @@ async function loadEventList() { // ── Device bar ───────────────────────────────────────────────────────────────── function populateDeviceBar() { qs('di-serial').textContent = unitInfo.serial || '—'; - qs('di-fw').textContent = unitInfo.firmware_version || '—'; + qs('di-fw').textContent = unitInfo.firmware_version || unitInfo.firmware || '—'; const cc = unitInfo.compliance_config || {}; qs('di-sr').textContent = cc.sample_rate ? `${cc.sample_rate} sps` : '—'; qs('di-rt').textContent = cc.record_time != null ? `${cc.record_time.toFixed(1)} s` : '—'; @@ -1765,9 +1837,7 @@ function populateDeviceBar() { async function refreshMonitorStatus() { if (!devHost()) return null; try { - const r = await fetch(`${api()}/device/monitor/status?${deviceParams()}`); - if (!r.ok) return null; - const s = await r.json(); + const s = await deviceFetch('status'); updateMonitorPanel(s); return s; } catch (_) { return null; } @@ -1779,27 +1849,37 @@ function updateMonitorPanel(s) { const batEl = document.getElementById('mon-battery'); const memTEl = document.getElementById('mon-mem-total'); const memFEl = document.getElementById('mon-mem-free'); - const startB = document.getElementById('mon-start-btn'); - const stopB = document.getElementById('mon-stop-btn'); - - if (s.is_monitoring) { + // Two shapes: the shared model (serial mode) and the legacy one. + const monitoring = s.monitoring ?? s.is_monitoring; + lastMonitoring = monitoring; + if (monitoring) { badge.textContent = 'MONITORING'; badge.className = 'mon-status-badge monitoring'; panel.className = 'monitoring'; - startB.disabled = true; - stopB.disabled = false; } else { badge.textContent = 'IDLE'; badge.className = 'mon-status-badge idle'; panel.className = 'idle'; - startB.disabled = false; - stopB.disabled = true; } + setMonitorButtons(); // Battery and memory are available in both states — update if present, // keep previous value if this was an optimistic update with no real data. - if (s.battery_v != null) batEl.textContent = `${s.battery_v.toFixed(2)} V`; - if (s.memory_total_kb != null) memTEl.textContent = `${s.memory_total_kb} KB`; - if (s.memory_free_kb != null) memFEl.textContent = `${s.memory_free_kb} KB`; + const volts = s.battery_volts ?? s.battery_v; + const kb = (bytes, k) => bytes != null ? Math.round(bytes / 1024) : k; + const totalKb = kb(s.memory_total_bytes, s.memory_total_kb); + const freeKb = kb(s.memory_free_bytes, s.memory_free_kb); + if (volts != null) batEl.textContent = `${volts.toFixed(2)} V`; + if (totalKb != null) memTEl.textContent = `${totalKb} KB`; + if (freeKb != null) memFEl.textContent = `${freeKb} KB`; +} + +// Start/stop: in serial mode only for a unit whose series its own answer +// confirmed; without a serial, as before (0x96/0x97 mean the same on both). +let lastMonitoring = null; +function setMonitorButtons() { + const allowed = serialMode() ? controlsFor(currentUnit()).startStop : Boolean(devHost()); + document.getElementById('mon-start-btn').disabled = !allowed || lastMonitoring === true; + document.getElementById('mon-stop-btn').disabled = !allowed || lastMonitoring === false; } async function startMonitoring() { @@ -1808,8 +1888,7 @@ async function startMonitoring() { btn.disabled = true; btn.textContent = '…'; setStatus('Starting monitoring…', 'loading'); try { - const r = await fetch(`${api()}/device/monitor/start?${deviceParams()}`, { method: 'POST' }); - if (!r.ok) { const e = await r.json().catch(() => ({})); throw new Error(e.detail || r.statusText); } + await deviceFetch('start'); // Optimistically show MONITORING immediately. The unit may run a ~40s on-device // sensor check before fully entering monitor mode. We poll status every 5s for @@ -1859,8 +1938,7 @@ async function stopMonitoring() { btn.disabled = true; btn.textContent = '…'; setStatus('Stopping monitoring…', 'loading'); try { - const r = await fetch(`${api()}/device/monitor/stop?${deviceParams()}`, { method: 'POST' }); - if (!r.ok) { const e = await r.json().catch(() => ({})); throw new Error(e.detail || r.statusText); } + await deviceFetch('stop'); setStatus('Monitoring stopped.', 'ok'); await refreshMonitorStatus(); } catch (e) { @@ -1880,10 +1958,12 @@ function populateDeviceTab() { cards.innerHTML = ''; const cardData = [ { label:'Serial Number', value: unitInfo.serial || '—' }, - { label:'Firmware', value: unitInfo.firmware_version || '—' }, - { label:'DSP', value: unitInfo.dsp_version || '—' }, + { label:'Series', value: confirmedSeries(currentUnit()) ?? '—' }, + { label:'Firmware', value: unitInfo.firmware_version || unitInfo.firmware || '—' }, + { label:'DSP', value: unitInfo.dsp_version || (unitInfo.detail || {}).dsp_version || '—' }, { label:'Model', value: unitInfo.model || '—' }, - { label:'Manufacturer', value: unitInfo.manufacturer || '—' }, + { label:'Manufacturer', value: unitInfo.manufacturer || (unitInfo.detail || {}).manufacturer || '—' }, + { label:'Active Setup', value: unitInfo.active_setup || '—' }, { label:'Stored Events', value: eventsLoaded ? eventList.length : 'not loaded' }, { label:'Storage Used', value: storageUsedLabel() }, ]; @@ -1958,7 +2038,8 @@ function diagCheckEraseConfirm() { const btn = document.getElementById('diag-erase-btn'); if (!box || !btn) return; const serial = (unitInfo && unitInfo.serial) || ''; - btn.disabled = !serial || box.value.trim().toUpperCase() !== serial.toUpperCase(); + btn.disabled = !serial || box.value.trim().toUpperCase() !== serial.toUpperCase() + || !controlsFor(currentUnit()).diagnostics; } function diagResult(id, text, cls) { @@ -1974,9 +2055,9 @@ async function refreshDiagnostics() { if (st) { st.textContent = 'Reading…'; st.className = 'loading'; } const [mon, store, idx] = await Promise.all([ - fetchJson('/device/monitor/status?force=true').catch(e => ({ _err: e.message })), - fetchJson('/device/events/storage_range').catch(e => ({ _err: e.message })), - fetchJson('/device/events/index').catch(e => ({ _err: e.message })), + deviceFetch('status', { force: 'true' }).catch(e => ({ _err: e.message })), + deviceFetch('storage_range').catch(e => ({ _err: e.message })), + deviceFetch('index').catch(e => ({ _err: e.message })), ]); if (!store._err) storageInfo = store; @@ -1985,9 +2066,10 @@ async function refreshDiagnostics() { const rows = []; rows.push(['Monitoring', mon._err ? err(mon._err) - : (mon.is_monitoring ? 'MONITORING' : 'idle')]); + : ((mon.monitoring ?? mon.is_monitoring) ? 'MONITORING' : 'idle')]); if (!mon._err) { - rows.push(['Battery', mon.battery_v != null ? `${mon.battery_v.toFixed(2)} V` : '—']); + const volts = mon.battery_volts ?? mon.battery_v; + rows.push(['Battery', volts != null ? `${volts.toFixed(2)} V` : '—']); if (mon.memory_total_bytes) { const used = mon.memory_total_bytes - (mon.memory_free_bytes ?? 0); const pct = (used / mon.memory_total_bytes * 100).toFixed(1); @@ -2012,7 +2094,7 @@ async function diagStopMonitoring() { const btn = document.getElementById('diag-stop-btn'); btn.disabled = true; diagResult('diag-stop-result', 'Sending…'); try { - await fetchJson('/device/monitor/stop', { method: 'POST' }); + await deviceFetch('stop'); diagResult('diag-stop-result', 'Stop acknowledged — recording halted.', 'ok'); refreshDiagnostics(); } catch (e) { @@ -2025,7 +2107,7 @@ async function diagDisableAch() { const btn = document.getElementById('diag-ach-btn'); btn.disabled = true; diagResult('diag-ach-result', 'Writing call-home config…'); try { - const r = await fetchJson('/device/rescue?erase=false', { method: 'POST' }); + const r = await deviceFetch('rescue', { erase: 'false' }); const steps = (r.steps || []).map(s => s.step).join(' → ') || 'done'; diagResult('diag-ach-result', `ACH disabled (${steps}). Events untouched.`, 'ok'); } catch (e) { @@ -2040,7 +2122,7 @@ async function diagEraseEvents() { const btn = document.getElementById('diag-erase-btn'); btn.disabled = true; diagResult('diag-erase-result', 'Erasing…'); try { - await fetchJson('/device/events/erase', { method: 'POST' }); + await deviceFetch('erase'); diagResult('diag-erase-result', 'Events erased — chain reset to 0x01110000.', 'ok'); document.getElementById('diag-erase-confirm').value = ''; eventList = []; eventsLoaded = false; @@ -2057,8 +2139,7 @@ async function diagSlowDrip() { btn.disabled = true; diagResult('diag-drip-result', 'Holding a session for 120 s…'); try { - const r = await fetchJson('/device/stop_monitoring_slow_drip?duration_s=120&interval_s=3', - { method: 'POST' }); + const r = await deviceFetch('slow_drip', { duration_s: 120, interval_s: 3 }); const good = (r.bytes_received || 0) > 0; diagResult('diag-drip-result', `drips ${r.drips_sent} · held ${r.duration_s}s · bytes back ${r.bytes_received}` + @@ -2075,7 +2156,7 @@ async function diagBlindStop() { const btn = document.getElementById('diag-blind-btn'); btn.disabled = true; diagResult('diag-blind-result', 'Sending…'); try { - const r = await fetchJson('/device/stop_monitoring_blind', { method: 'POST' }); + const r = await deviceFetch('blind_stop'); diagResult('diag-blind-result', `Sent ${r.bytes_sent ?? '?'} bytes, no response read (fire-and-forget).`, 'ok'); } catch (e) { @@ -2115,9 +2196,7 @@ async function readConfig() { setCfgStatus('Reading config from device…'); document.getElementById('cfg-read-btn').disabled = true; try { - const r = await fetch(`${api()}/device/info?${deviceParams()}`); - if (!r.ok) { const e = await r.json().catch(()=>({})); throw new Error(e.detail || r.statusText); } - unitInfo = await r.json(); + unitInfo = await deviceFetch('info'); populateConfigFromDeviceInfo(); populateDeviceBar(); populateDeviceTab(); @@ -2169,13 +2248,10 @@ async function writeConfig() { document.getElementById('cfg-write-btn').disabled = true; try { - const r = await fetch(`${api()}/device/config?${deviceParams()}`, { - method: 'POST', + await deviceFetch('config_write', {}, { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }); - if (!r.ok) { const e = await r.json().catch(()=>({})); throw new Error(e.detail || r.statusText); } - const result = await r.json(); setCfgStatus(`Written: ${fieldsStr}`, 'ok'); // Re-read device info so Device tab and bar refresh await readConfig(); @@ -2235,9 +2311,7 @@ async function readCallHome() { setChStatus('Reading call home config from device…'); document.getElementById('ch-read-btn').disabled = true; try { - const r = await fetch(`${api()}/device/call_home?${deviceParams()}`); - if (!r.ok) { const e = await r.json().catch(()=>({})); throw new Error(e.detail || r.statusText); } - const ch = await r.json(); + const ch = await deviceFetch('call_home_read'); populateCallHomeForm(ch); setChStatus('Call home config loaded from device.', 'ok'); } catch(e) { @@ -2298,12 +2372,10 @@ async function writeCallHome() { document.getElementById('ch-write-btn').disabled = true; try { - const r = await fetch(`${api()}/device/call_home?${deviceParams()}`, { - method: 'POST', + await deviceFetch('call_home_write', {}, { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }); - if (!r.ok) { const e = await r.json().catch(()=>({})); throw new Error(e.detail || r.statusText); } setChStatus(`Written: ${fieldsStr}`, 'ok'); // Re-read to confirm changes await readCallHome(); @@ -2366,9 +2438,7 @@ async function loadWaveform() { let data; try { - const r = await fetch(`${api()}/device/event/${idx}/waveform?${deviceParams()}`); - if (!r.ok) { const e = await r.json().catch(()=>({})); throw new Error(e.detail || r.statusText); } - data = await r.json(); + data = await deviceFetch('event_waveform', { index: idx }); } catch(e) { setStatus(`Waveform error: ${e.message}`, 'error'); document.getElementById('load-btn').disabled = false; @@ -2399,7 +2469,7 @@ async function saveEventToDb() { setStatus(`Downloading event #${idx} and saving to DB…`, 'loading'); try { - const r = await fetch(`${api()}/device/event/${idx}/blastware_file?${deviceParams()}`); + const r = await deviceRequest('event_file', { index: idx }); if (!r.ok) { const e = await r.json().catch(() => ({})); throw new Error(e.detail || r.statusText); @@ -2426,7 +2496,7 @@ async function saveEventToDb() { function downloadEventFile() { if (!devHost()) { setStatus('Enter device host first.', 'error'); return; } const idx = currentEvent; - const url = `${api()}/device/event/${idx}/blastware_file?${deviceParams()}`; + const url = `${api()}${deviceUrl('event_file', currentUnit(), { index: idx }).path}`; setStatus(`Downloading event #${idx}…`, 'loading'); // Hidden iframe avoids navigating away from the SPA. FastAPI's FileResponse // sets Content-Disposition: attachment so the browser saves rather than displays. @@ -3594,6 +3664,10 @@ document.addEventListener('keydown', e => { // Default API base to wherever this page was served from — works whether you // hit localhost:8200, 10.0.0.44:8200, or anything else. document.getElementById('api-base').value = window.location.origin; +for (const id of ['dev-serial', 'dev-host', 'dev-port']) { + document.getElementById(id).addEventListener('input', () => { unitConfirmed = null; applyControls(); }); +} +applyControls(); // Reflect any persisted mic-unit preference in the header pill on load _refreshMicUnitToggleLabel(); diff --git a/tests/test_webapp_device_routing.py b/tests/test_webapp_device_routing.py index 0561eaa..1ef84e3 100644 --- a/tests/test_webapp_device_routing.py +++ b/tests/test_webapp_device_routing.py @@ -169,3 +169,22 @@ def test_the_page_scripts_parse_together(tmp_path): js.write_text("\n;\n".join(scripts)) r = subprocess.run([NODE, "--check", str(js)], capture_output=True, text=True, timeout=30) assert r.returncode == 0, r.stderr + + +def test_every_device_url_is_built_by_deviceUrl(): + """One place builds /device/ URLs, so the series rules cannot be bypassed: + outside the device-routing block the page holds no hand-built device path.""" + src = PAGE.read_text() + outside = re.sub(r"/\* \*/.*?/\* \*/", "", src, flags=re.S) + hand_built = [m.group(0) for m in re.finditer(r"(`\$\{api\(\)\}/device/[^`]*`|'/device/[^']*'|\"/device/[^\"]*\")", outside)] + assert hand_built == [], hand_built + + +def test_device_url_puts_an_event_index_in_the_path(): + # the legacy per-event routes carry the index in the path, not the query + r = run(["deviceUrl", ["event_waveform", BLANK, {"index": 3}]], + ["deviceUrl", ["event_file", S3, {"index": 0}]], + ["deviceUrl", ["event_file", S3]]) + assert r[0] == {"method": "GET", "path": "/device/event/3/waveform?host=h&tcp_port=9034"} + assert r[1] == {"method": "GET", "path": "/device/event/0/blastware_file?serial=BE9441&host=h&tcp_port=9034"} + assert "throws" in r[2]