Files
seismo-relay/sfm/static/device_routing.js
T
serversdownandClaude Opus 5.5 84c142f36c feat(sfm): the page's Call Home tab by serial -- state and audited On / Off (phase 4)
device_routing.js (Node-tested): call_home_state / call_home_on / call_home_off
routes (serial required); controlsFor gains callHomeChange (by serial, a
confirmed Series 3 or 4) and callHomeRead now covers a Series 4 by serial;
serialPanes gains callHomeForm / callHomeBox; callHomeRows renders the switch
(On / Off / 'Unknown (byte 5 = 0xNN)'), dial string and series;
changeErrorText takes the whole label ('Start monitoring', 'Enable call-home').

sfm_webapp.js: by serial the Call Home tab hides the legacy multi-field form
(Series 3 by host only) and shows the unit's switch with On / Off.  Each asks
confirm(), sends one audited change, reports it with changeSummary /
changeErrorText, then re-reads quietly so the change's own result stays on
screen.  A different unit's switch is never left showing.  The new buttons are
wired with addEventListener, not onclick= (no inline JS).

Checked in jsdom against the real page: placeholder, read, Off (confirm, the
disable route, 'confirmed -- enabled -> disabled'), a serial edit clearing it,
legacy mode unchanged, no script errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-02 17:05:00 -05:00

212 lines
10 KiB
JavaScript

/* <device-routing> */
// 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],
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, 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: false,
callHomeWrite: false,
reasons: { configWrite: 'Coming in phase 5 (#46)',
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.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 => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[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 sw = s.enabled === true ? 'On' : s.enabled === false ? 'Off'
: `Unknown (byte 5 = ${(s.detail || {}).byte5 ?? '?'})`;
return [['Call-home', sw], ['Dial string', s.dial_string || '—'], ['Series', s.series]];
}
/* </device-routing> */