/* */ // Every rule that decides where a /device/ request goes, or whether a // series-specific control is live. Pure functions -- no DOM, no fetch -- so // tests/test_webapp_device_routing.py runs them in Node (phase 1c, 2026-10-29). // A control follows the unit's own /device/info answer, never a typed serial // alone: 0xA2 is CONFIRM ERASE on a MiniMate and ends a call-home on a Micromate. const SERIES_BY_PREFIX = [['UM', 4], ['BE', 3], ['BA', 3]]; // sfm/device_access/series.py function normSerial(serial) { return String(serial || '').trim().toUpperCase(); } function seriesFromSerial(serial) { const s = normSerial(serial); for (const [prefix, series] of SERIES_BY_PREFIX) { if (s.startsWith(prefix) && s.length > prefix.length) return series; } return null; } function unitQuery(unit) { const parts = []; const s = normSerial(unit.serial); if (s) parts.push(`serial=${encodeURIComponent(s)}`); parts.push(`host=${encodeURIComponent(unit.host || '')}`); parts.push(`tcp_port=${encodeURIComponent(unit.tcpPort)}`); return parts.join('&'); } // action -> [method, path, needs a serial (no legacy equivalent)] const DEVICE_ROUTES = { info: ['GET', '/device/info', false], status: ['GET', '/device/monitor/status', false], settings: ['GET', '/device/settings', true], events: ['GET', '/device/events', false], download: ['POST', '/device/events/download', true], start: ['POST', '/device/monitor/start', false], stop: ['POST', '/device/monitor/stop', false], hangup: ['POST', '/device/hangup', true], storage_range: ['GET', '/device/events/storage_range', false], index: ['GET', '/device/events/index', false], erase: ['POST', '/device/events/erase', false], rescue: ['POST', '/device/rescue', false], blind_stop: ['POST', '/device/stop_monitoring_blind', false], slow_drip: ['POST', '/device/stop_monitoring_slow_drip', false], call_home_read: ['GET', '/device/call_home', false], call_home_write: ['POST', '/device/call_home', false], call_home_state: ['GET', '/device/call_home/state', true], call_home_on: ['POST', '/device/call_home/enable', true], call_home_off: ['POST', '/device/call_home/disable', true], settings_change: ['POST', '/device/settings/change', true], 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, 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(rest)) query += `&${k}=${encodeURIComponent(v)}`; return { method, path: `${path}?${query}` }; } function confirmedSeries(unit) { const c = unit.confirmed; if (!c) return null; const typed = normSerial(unit.serial); if (!typed) return c.series; // a legacy identify, no serial typed return typed === normSerial(c.serial) ? c.series : null; } function controlsFor(unit) { const series = confirmedSeries(unit); const serialMode = Boolean(normSerial(unit.serial)); return { startStop: serialMode && (series === 3 || series === 4), hangup: series === 4, diagnostics: series === 3, // by host, the legacy read is Series 3's; by serial, both series (phase 4) callHomeRead: series === 3 || (serialMode && series === 4), callHomeChange: serialMode && (series === 3 || series === 4), configWrite: serialMode && (series === 3 || series === 4), callHomeWrite: false, reasons: { configWrite: 'By serial only: Preview, then Send (audited).', callHomeWrite: 'By serial: use Call-home On / Off (audited). Other call-home fields wait for the THOR round.' }, }; } function changeSummary(body) { const id8 = String(body.audit_id || '').slice(0, 8); if (body.outcome === 'dry_run') { const subs = ((body.plan || {}).steps || []).map(s => s.sub).join(', '); return `${body.action}: dry run — would send ${subs}`; } if (body.action === 'change settings') { // phase 5: the state is a read-back verdict if (body.outcome === 'skipped') return 'change settings: the unit already holds these — nothing sent'; if (body.outcome === 'sent' && body.verified === 'ok') { return `change settings: confirmed — the unit holds what was sent (audit ${id8})`; } if (body.verified === 'mismatch') { return `change settings: sent, but the unit reads ${body.state_after} — see what it holds (audit ${id8})`; } } if (body.outcome === 'skipped') return `${body.action}: already ${body.state_before} — nothing sent`; if (body.outcome === 'sent' && body.verified === 'ok') { return `${body.action}: confirmed — ${body.state_before} → ${body.state_after} (audit ${id8})`; } return `${body.action}: ${body.outcome}, ${body.verified} (audit ${id8})`; } // What a chip and the peaks bar show for an event, from either shape: the // shared EventRef (serial mode) or the legacy event (host/port mode). function eventView(ev) { const label = typeof ev.timestamp === 'string' ? ev.timestamp.replace('T', ' ') : (ev.timestamp && ev.timestamp.display) || `Event ${ev.index}`; let peaks = null; if (ev.peaks_ips || ev.peak_vector_sum_ips != null) { const p = ev.peaks_ips || {}; peaks = { tran: p.tran ?? null, vert: p.vert ?? null, long: p.long ?? null, pvs: ev.peak_vector_sum_ips ?? null, micPsi: null }; } else if (ev.peak_values) { const pv = ev.peak_values; peaks = { tran: pv.tran_in_s ?? null, vert: pv.vert_in_s ?? null, long: pv.long_in_s ?? null, pvs: pv.peak_vector_sum ?? null, micPsi: pv.micl_psi ?? null }; } return { label, title: ev.record_type || '', peaks }; } // What the Config tab's serial-mode Read shows for a UnitSettings reply. function settingsRows(st) { const dash = v => (v == null || v === '' ? '—' : v); const hi = st.histogram_interval_s; const rows = [ ['Setup Name', dash(st.setup_name)], ['Record Mode', dash(st.record_mode)], ['Sample Rate', st.sample_rate != null ? `${st.sample_rate} sps` : '—'], ['Record Time', st.record_time_s != null ? `${st.record_time_s.toFixed(2)} s` : '—'], ['Histogram Interval', hi == null ? '—' : hi < 60 ? `${hi} s` : `${hi / 60} min`], ['Geo Trigger', st.geo_trigger_ips != null ? `${st.geo_trigger_ips.toFixed(4)} in/s` : '—'], ]; const notes = Object.entries(st.notes || {}); if (!notes.length) rows.push(['Notes', '—']); for (const [k, v] of notes) rows.push([`Note: ${k}`, dash(v)]); return rows; } // The legacy per-index routes (Load / Save / Download, prev/next, the arrow // keys) address events by position on the MiniMate path: live only for a list // loaded without a serial that has events. function perIndexLive({ bySerial, count }) { return !bySerial && count > 0; } // A unit's own string (setup name, project, an error naming a serial) placed // into markup must stay text. function escapeHtml(v) { return String(v ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); } function downloadSummary(body) { if (body.inserted === false) return `already stored — ${body.stored_filename}`; return `stored ${body.stored_filename}, ${body.filesize} bytes, check: ${(body.detail || {}).check}`; } // A Micromate's version string lives in 0x01, undecoded; which firmware line it // runs comes free with every reply (bench finding #12). const FIRMWARE_LINES = { thor: 'Thor line (version not read)', blastware: 'Blastware line (version not read)' }; function firmwareLabel(info) { const i = info || {}; return i.firmware_version || i.firmware || FIRMWARE_LINES[(i.detail || {}).firmware_line] || '—'; } // A failed device request's message. A 504 is a unit that took the connection // but never answered: while THOR polls a Micromate, SFM's connection is accepted // and gets 0 bytes (measured 2026-10-29, bench finding #16). The hint is left // off once a change was sent -- its own message says what happened. const NO_REPLY_HINT = 'the connection opened, so the modem is reachable — another program (THOR or ' + "Blastware) may be holding this unit's line, or the unit is busy (e.g. its sensor check)"; function errorDetail(body, statusText) { const b = body || {}, d = b.detail; return b.outcome ? changeSummary(b) : typeof d === 'string' ? d : d ? (d.message || JSON.stringify(d)) : statusText; } function deviceErrorText(status, body, unit, statusText) { const text = errorDetail(body, statusText); return status === 504 && !(body || {}).sent && unit && unit.host ? `${text} — ${NO_REPLY_HINT}` : text; } // A change that went out (or may have) is not "failed": its body carries `sent` // (ChangeUnconfirmed, bench finding #10), and its message says what the unit // did and names the audit record. `label` is the whole name: "Start monitoring", // "Enable call-home". function changeErrorText(label, status, body, unit, statusText) { if ((body || {}).sent) return `${label} not confirmed: ${errorDetail(body, statusText)}`; return `${label} failed: ${deviceErrorText(status, body, unit, statusText)}`; } // By serial, settings are read-only until phase 5: no empty legacy edit form or // legacy tables, and the settings box shows from the start (#6, #12). function serialPanes(bySerial, settingsRead) { return { configForm: !bySerial, settingsBox: bySerial, settingsPlaceholder: bySerial && !settingsRead, legacyDeviceTables: !bySerial, callHomeForm: !bySerial, callHomeBox: bySerial }; } // A unit's call-home switch, read by serial (phase 4). `enabled` null is an // enable byte never measured -- shown with the byte, never as On or Off. function callHomeRows(state) { const s = state || {}; const d = s.detail || {}; const sw = s.enabled === true ? 'On' : s.enabled === false ? 'Off' : d.reason || `Unknown (byte 5 = ${d.byte5 ?? '?'})`; return [['Call-home', sw], ['Dial string', s.dial_string || '—'], ['Series', s.series]]; } // ── The Config tab's edit form, by serial (phase 5) ────────────────────────── // The fields the server says this unit can change, in its order, with their // limits (UnitSettings.detail.editable). function settingsFormFields(st) { return (((st || {}).detail || {}).editable || []).map(f => ({ ...f })); } // Only what the operator changed, typed as the server expects. Numbers compare // as numbers (0.30 is 0.3); a number that does not parse is left out (the // preview shows exactly what would change); read-only fields never count. function settingsChanges(fields, edited) { const out = {}; const e = edited || {}; for (const f of fields || []) { if (f.readonly || !(f.field in e)) continue; let v = e[f.field]; if (f.kind === 'number' || (f.kind === 'choice' && typeof f.value === 'number')) { if (v === '' || v == null) continue; v = Number(v); if (!Number.isFinite(v) || v === Number(f.value)) continue; } else if (f.kind === 'bool') { v = Boolean(v); if (v === Boolean(f.value)) continue; } else { v = String(v); if (v === String(f.value == null ? '' : f.value)) continue; } out[f.field] = v; } return out; } const _dash = v => (v == null || v === '' ? '—' : v); // A preview (dry run): one row per field, [label, the unit holds, it would get]. function settingsPreviewRows(body) { return Object.values(((body || {}).plan || {}).fields || {}).map(r => [r.label, _dash(r.old), _dash(r.new)]); } // Why a preview would not be sent ('' when nothing blocks it). function settingsBlockedText(body) { return (((body || {}).plan || {}).blocked || []).join('; '); } // After a send: [label, the unit held, SFM sent, the unit now holds]. function settingsResultRows(body) { const fields = ((((body || {}).detail || {}).snapshot || {}).fields) || {}; return Object.values(fields).map(r => [r.label, _dash(r.old), _dash(r.new), _dash(r.now)]); } /* */