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
2358 lines
100 KiB
JavaScript
2358 lines
100 KiB
JavaScript
'use strict';
|
|
|
|
// ── State ──────────────────────────────────────────────────────────────────────
|
|
let unitInfo = null;
|
|
let eventList = [];
|
|
let storageInfo = null; // /device/events/storage_range — cheap, read on connect
|
|
let eventsLoaded = false;
|
|
let eventsBySerial = false; // the list came from the serial-based /device/events (EventRef shape) // the event chain walk is opt-in; see loadEventList()
|
|
let currentEvent = 0;
|
|
let charts = {};
|
|
let geoAdcScale = 6.206;
|
|
const DBL_REF = 2.9e-9; // 20 µPa in psi — reference pressure for dBL
|
|
const CHANNEL_COLORS = { Tran:'#58a6ff', Vert:'#3fb950', Long:'#d29922', MicL:'#bc8cff' };
|
|
|
|
// ── Helpers ────────────────────────────────────────────────────────────────────
|
|
function api() { return document.getElementById('api-base').value.replace(/\/$/, ''); }
|
|
function devHost() { return document.getElementById('dev-host').value.trim(); }
|
|
function devPort() { return document.getElementById('dev-port').value; }
|
|
function qs(sel, val) { const el = document.getElementById(sel); if (val !== undefined) el.value = val; return el; }
|
|
|
|
function setStatus(msg, cls = '') {
|
|
const bar = document.getElementById('status-bar');
|
|
bar.innerHTML = '';
|
|
bar.className = cls;
|
|
bar.textContent = msg;
|
|
}
|
|
function addPill(text) {
|
|
const bar = document.getElementById('status-bar');
|
|
const p = document.createElement('span');
|
|
p.className = 'meta-pill';
|
|
p.textContent = text;
|
|
bar.appendChild(p);
|
|
}
|
|
function setCfgStatus(msg, cls = '') {
|
|
const el = document.getElementById('cfg-status');
|
|
el.textContent = msg;
|
|
el.className = cls;
|
|
}
|
|
|
|
// "Force refresh" override — when enabled, every live-device request is
|
|
// sent with ?force=true so the server bypasses its in-memory + persistent
|
|
// caches and re-reads from the device. Manual escape hatch for cases where
|
|
// the cache has gone stale (e.g. post-erase key reuse — see ach_server.py
|
|
// and sfm/cache.py for the eviction logic).
|
|
let forceRefresh = false;
|
|
|
|
function onForceToggle() {
|
|
forceRefresh = document.getElementById('force-cb').checked;
|
|
document.getElementById('force-toggle').classList.toggle('active', forceRefresh);
|
|
}
|
|
|
|
// 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 err = new Error(deviceErrorText(r.status, body, currentUnit(), 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;
|
|
const chr = document.getElementById('ch-read-btn');
|
|
chr.disabled = !c.callHomeRead;
|
|
const s4 = series === 4 && !c.callHomeRead ? "Series 4: type the unit's serial to read its call-home" : '';
|
|
chr.title = s4;
|
|
document.getElementById('ch-series-note').textContent = s4;
|
|
for (const id of ['ch-on-btn', 'ch-off-btn']) {
|
|
document.getElementById(id).disabled = !c.callHomeChange || changeInFlight;
|
|
}
|
|
setMonitorButtons();
|
|
applyConfigPanes();
|
|
applyCallHomePanes();
|
|
}
|
|
|
|
// The Call Home tab by serial (phase 4): the unit's switch and audited On / Off;
|
|
// the legacy multi-field form is Series 3 by host only.
|
|
let callHomeShownFor = null;
|
|
function applyCallHomePanes() {
|
|
const serial = normSerial(currentUnit().serial);
|
|
const p = serialPanes(Boolean(serial), false);
|
|
document.getElementById('ch-legacy').style.display = p.callHomeForm ? '' : 'none';
|
|
document.getElementById('ch-serial').style.display = p.callHomeBox ? 'block' : 'none';
|
|
document.getElementById('ch-write-btn').hidden = !p.callHomeForm;
|
|
document.getElementById('ch-clear-btn').hidden = !p.callHomeForm;
|
|
if (p.callHomeBox && callHomeShownFor !== serial) {
|
|
callHomeShownFor = null;
|
|
renderTextTable('ch-state', [['Call-home', 'Not read yet — press Read from Device']]);
|
|
}
|
|
}
|
|
|
|
// `quiet`: the re-read after a change -- the change's own result stays on screen.
|
|
async function readCallHomeBySerial({ quiet = false } = {}) {
|
|
const btn = document.getElementById('ch-read-btn');
|
|
btn.disabled = true;
|
|
if (!quiet) setChStatus('Reading call-home from the unit…');
|
|
try {
|
|
const st = await deviceFetch('call_home_state');
|
|
renderTextTable('ch-state', callHomeRows(st));
|
|
callHomeShownFor = normSerial(st.serial);
|
|
if (!quiet) setChStatus(`Call-home read from ${st.serial}.`, 'ok');
|
|
} catch (e) {
|
|
if (!quiet) setChStatus(`Read failed: ${e.message}`, 'error');
|
|
else renderTextTable('ch-state', [['Call-home', `Re-read failed: ${e.message}`]]);
|
|
} finally {
|
|
btn.disabled = false;
|
|
}
|
|
}
|
|
|
|
// One audited send, never retried; the body says what the unit did.
|
|
async function changeCallHome(on) {
|
|
const serial = normSerial(currentUnit().serial);
|
|
const label = on ? 'Enable call-home' : 'Disable call-home';
|
|
if (!confirm(`Turn call-home ${on ? 'ON' : 'OFF'} on ${serial}?`)) return;
|
|
changeInFlight = true; applyControls();
|
|
setChStatus(`${label}…`);
|
|
try {
|
|
const r = await deviceRequest(on ? 'call_home_on' : 'call_home_off');
|
|
const body = await r.json().catch(() => ({}));
|
|
setChStatus(body.outcome ? changeSummary(body)
|
|
: changeErrorText(label, r.status, body, currentUnit(), r.statusText),
|
|
r.ok ? 'ok' : 'error');
|
|
} catch (e) {
|
|
// No reply is not "nothing sent": the request may have reached the unit.
|
|
setChStatus(`${label}: no reply from SFM (${e.message}) — it may have been sent; `
|
|
+ `check the unit's state and GET /db/device_commands`, 'error');
|
|
}
|
|
changeInFlight = false; applyControls();
|
|
await readCallHomeBySerial({ quiet: true });
|
|
}
|
|
|
|
// The Config tab by serial (#6): settings are read-only until phase 5, so the
|
|
// empty legacy edit form stays hidden and the settings box shows from the start.
|
|
// A different unit's settings are never left on screen.
|
|
let settingsShownFor = null;
|
|
function applyConfigPanes() {
|
|
const serial = normSerial(currentUnit().serial);
|
|
const p = serialPanes(Boolean(serial), Boolean(serial) && settingsShownFor === serial);
|
|
document.getElementById('cfg-form').style.display = p.configForm ? '' : 'none';
|
|
document.getElementById('cfg-settings').style.display = p.settingsBox ? 'block' : 'none';
|
|
if (p.settingsPlaceholder) {
|
|
settingsShownFor = null;
|
|
renderTextTable('cfg-settings-table', [['Settings', 'Not read yet — press Read from Device']]);
|
|
}
|
|
}
|
|
|
|
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 ─────────────────────────────────────────────────────────
|
|
// Default to Database — most users land here to browse stored events.
|
|
// Live Device is opt-in (click the tab to talk to a unit).
|
|
let currentSection = 'db';
|
|
|
|
function switchSection(name) {
|
|
currentSection = name;
|
|
document.querySelectorAll('.section-btn').forEach(b => {
|
|
b.classList.toggle('active', b.textContent.toLowerCase().startsWith(name === 'live' ? 'live' : 'data'));
|
|
});
|
|
document.getElementById('section-live').style.display = name === 'live' ? 'flex' : 'none';
|
|
document.getElementById('section-db').style.display = name === 'db' ? 'flex' : 'none';
|
|
|
|
// Auto-load DB section on first visit
|
|
if (name === 'db') {
|
|
if (!histLoaded) loadHistory();
|
|
if (!unitsLoaded) loadUnits();
|
|
}
|
|
}
|
|
|
|
// ── Tab switching ──────────────────────────────────────────────────────────────
|
|
function switchTab(name) {
|
|
// Activate the matching tab button within its own tab bar
|
|
const btn = document.querySelector(`.tab-btn[data-tab="${name}"]`);
|
|
if (btn) {
|
|
btn.closest('.tab-bar').querySelectorAll('.tab-btn')
|
|
.forEach(b => b.classList.remove('active'));
|
|
btn.classList.add('active');
|
|
}
|
|
|
|
// Hide all panes in both sections, then show the target
|
|
document.querySelectorAll('.tab-pane').forEach(p => {
|
|
p.classList.remove('active');
|
|
if (p.style.display === 'flex') p.style.display = 'none';
|
|
});
|
|
const pane = document.getElementById(`tab-${name}`);
|
|
if (!pane) return;
|
|
const needsFlex = pane.id === 'tab-events' || pane.classList.contains('db-tab-pane');
|
|
if (needsFlex) {
|
|
pane.style.display = 'flex';
|
|
} else {
|
|
pane.classList.add('active');
|
|
}
|
|
|
|
// Auto-load DB tabs on first switch
|
|
if (name === 'history') { if (!histLoaded) loadHistory(); }
|
|
if (name === 'units') { if (!unitsLoaded) loadUnits(); }
|
|
if (name === 'monlog') { if (!monlogLoaded) loadMonitorLog(); }
|
|
if (name === 'sessions') { if (!sessLoaded) loadSessions(); }
|
|
if (name === 'diagnostics' && devHost() && unitInfo) refreshDiagnostics();
|
|
}
|
|
|
|
// ── Connect ────────────────────────────────────────────────────────────────────
|
|
async function connectUnit() {
|
|
if (!devHost()) { setStatus('Enter a device host first.', 'error'); return; }
|
|
// Whatever answered last time no longer counts: only this identify confirms.
|
|
unitConfirmed = null;
|
|
applyControls();
|
|
|
|
const btn = document.getElementById('connect-btn');
|
|
btn.disabled = true;
|
|
btn.textContent = 'Connecting…';
|
|
setStatus('Connecting — reading device info…', 'loading');
|
|
|
|
try {
|
|
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
|
|
// outright on a unit whose buffer has wrapped past 0xFFFF. Use the ~2 s
|
|
// probes instead; the event list is opt-in via loadEventList().
|
|
eventList = []; eventsLoaded = false;
|
|
setStatus('Reading device state…', 'loading');
|
|
// 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();
|
|
populateEventChips();
|
|
populateConfigFromDeviceInfo();
|
|
|
|
document.getElementById('device-bar').style.display = 'flex';
|
|
document.getElementById('monitor-panel').style.display = 'flex';
|
|
setEventButtonsEnabled();
|
|
document.getElementById('load-events-btn').disabled = false;
|
|
document.getElementById('cfg-read-btn').disabled = false;
|
|
applyControls();
|
|
|
|
btn.disabled = false; btn.textContent = 'Reconnect';
|
|
|
|
setStatus(storageInfo && storageInfo.is_empty
|
|
? 'Connected — no events stored.'
|
|
: 'Connected. Event list not loaded (Events → Load events).', 'ok');
|
|
|
|
// Fetch monitor status in background (non-blocking)
|
|
refreshMonitorStatus().catch(() => {});
|
|
|
|
const cc = unitInfo.compliance_config;
|
|
if (cc) {
|
|
if (cc.sample_rate) addPill(`${cc.sample_rate} sps`);
|
|
if (cc.trigger_level_geo != null) addPill(`trig ${cc.trigger_level_geo.toFixed(3)} in/s`);
|
|
}
|
|
}
|
|
|
|
// ── Shared fetch helper ────────────────────────────────────────────────────────
|
|
|
|
function setEventButtonsEnabled() {
|
|
const n = eventList.length;
|
|
// A list loaded by serial is downloaded row by row (by event_id); these
|
|
// per-index buttons belong to the legacy list.
|
|
const bySerial = eventsBySerial;
|
|
const live = perIndexLive({ bySerial, count: n });
|
|
for (const id of ['load-btn', 'save-btn', 'download-btn']) {
|
|
const el = document.getElementById(id);
|
|
if (el.dataset.legacyTitle === undefined) el.dataset.legacyTitle = el.title;
|
|
el.disabled = !live;
|
|
el.title = bySerial ? 'For a list loaded without a serial — use a row\'s Download' : el.dataset.legacyTitle;
|
|
}
|
|
document.getElementById('prev-btn').disabled = true;
|
|
document.getElementById('next-btn').disabled = !live || n <= 1;
|
|
}
|
|
|
|
// ── Event list (opt-in — this is the slow chain walk) ──────────────────────────
|
|
async function loadEventList() {
|
|
if (!devHost()) { setStatus('Connect to a device first.', 'error'); return; }
|
|
const btn = document.getElementById('load-events-btn');
|
|
btn.disabled = true;
|
|
setStatus(serialMode() ? 'Listing events…' : 'Walking the event chain — this can take a while…', 'loading');
|
|
try {
|
|
const evData = await deviceFetch('events');
|
|
eventList = evData.events || [];
|
|
eventsLoaded = true;
|
|
eventsBySerial = serialMode();
|
|
// /device/events re-reads compliance; fold it in.
|
|
if (evData.device) unitInfo = { ...unitInfo, ...evData.device };
|
|
} catch (e) {
|
|
setStatus(`Event fetch failed: ${e.message}`, 'error');
|
|
btn.disabled = false; return;
|
|
}
|
|
populateDeviceBar();
|
|
populateDeviceTab();
|
|
populateEventChips();
|
|
setEventButtonsEnabled();
|
|
btn.disabled = false;
|
|
setStatus(`${eventList.length} event${eventList.length !== 1 ? 's' : ''} stored.`, 'ok');
|
|
}
|
|
|
|
// ── Device bar ─────────────────────────────────────────────────────────────────
|
|
function populateDeviceBar() {
|
|
qs('di-serial').textContent = unitInfo.serial || '—';
|
|
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` : '—';
|
|
qs('di-trig').textContent = cc.trigger_level_geo != null ? `${cc.trigger_level_geo.toFixed(3)} in/s` : '—';
|
|
qs('di-count').textContent = eventsLoaded ? eventList.length : '—';
|
|
qs('di-project').textContent = cc.project || '—';
|
|
qs('di-client').textContent = cc.client || '—';
|
|
qs('di-operator').textContent = cc.operator || '—';
|
|
geoAdcScale = cc.geo_adc_scale ?? 6.206;
|
|
}
|
|
|
|
// ── Monitoring ─────────────────────────────────────────────────────────────────
|
|
async function refreshMonitorStatus() {
|
|
if (!devHost()) return null;
|
|
try {
|
|
const s = await deviceFetch('status');
|
|
updateMonitorPanel(s);
|
|
return s;
|
|
} catch (_) { return null; }
|
|
}
|
|
|
|
function updateMonitorPanel(s) {
|
|
const panel = document.getElementById('monitor-panel');
|
|
const badge = document.getElementById('mon-badge');
|
|
const batEl = document.getElementById('mon-battery');
|
|
const memTEl = document.getElementById('mon-mem-total');
|
|
const memFEl = document.getElementById('mon-mem-free');
|
|
// 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';
|
|
} else {
|
|
badge.textContent = 'IDLE';
|
|
badge.className = 'mon-status-badge idle';
|
|
panel.className = 'idle';
|
|
}
|
|
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.
|
|
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);
|
|
// The unit's clock and event count come only in the shared shape (serial
|
|
// mode); Series 3 reports both as null.
|
|
const shared = 'monitoring' in s;
|
|
for (const [id, v] of [['mon-time', s.device_time ? s.device_time.replace('T', ' ') : '—'],
|
|
['mon-events', s.event_count ?? '—']]) {
|
|
const el = document.getElementById(id);
|
|
if (shared) el.textContent = v;
|
|
el.parentElement.style.display = shared ? '' : 'none';
|
|
}
|
|
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;
|
|
let changeInFlight = false; // one start/stop at a time: a double click must not send twice
|
|
function setMonitorButtons() {
|
|
const allowed = !changeInFlight
|
|
&& (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() {
|
|
if (!devHost()) return;
|
|
if (serialMode()) { await changeMonitoring('start'); return; }
|
|
const btn = document.getElementById('mon-start-btn');
|
|
btn.disabled = true; btn.textContent = '…';
|
|
setStatus('Starting monitoring…', 'loading');
|
|
try {
|
|
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
|
|
// up to 60s, updating the badge when is_monitoring flips to true.
|
|
updateMonitorPanel({ is_monitoring: true });
|
|
setStatus('Monitoring started — sensor check in progress (~40s)…', 'loading');
|
|
btn.textContent = '▶ Start';
|
|
|
|
_pollMonitorConfirm(0);
|
|
|
|
} catch (e) {
|
|
setStatus(`Start monitoring failed: ${e.message}`, 'error');
|
|
btn.disabled = false;
|
|
btn.textContent = '▶ Start';
|
|
}
|
|
}
|
|
|
|
async function _pollMonitorConfirm(attempt) {
|
|
// Poll /device/monitor/status every 5s for up to 60s after startMonitoring().
|
|
// Updates the panel on each successful poll. Resolves once is_monitoring is true
|
|
// or after 12 attempts (60s), whichever comes first.
|
|
const MAX_ATTEMPTS = 12;
|
|
const INTERVAL_MS = 5000;
|
|
if (attempt >= MAX_ATTEMPTS) {
|
|
const s = await refreshMonitorStatus();
|
|
if (!s || !s.is_monitoring) {
|
|
setStatus('Warning: unit did not confirm monitoring state after 60s. Check device.', 'error');
|
|
} else {
|
|
setStatus('Monitoring active.', 'ok');
|
|
}
|
|
return;
|
|
}
|
|
await new Promise(res => setTimeout(res, INTERVAL_MS));
|
|
const s = await refreshMonitorStatus();
|
|
if (s && s.is_monitoring) {
|
|
setStatus('Monitoring active.', 'ok');
|
|
} else {
|
|
const elapsed = (attempt + 1) * 5;
|
|
setStatus(`Sensor check in progress… (${elapsed}s elapsed)`, 'loading');
|
|
_pollMonitorConfirm(attempt + 1);
|
|
}
|
|
}
|
|
|
|
async function stopMonitoring() {
|
|
if (!devHost()) return;
|
|
if (serialMode()) { await changeMonitoring('stop'); return; }
|
|
const btn = document.getElementById('mon-stop-btn');
|
|
btn.disabled = true; btn.textContent = '…';
|
|
setStatus('Stopping monitoring…', 'loading');
|
|
try {
|
|
await deviceFetch('stop');
|
|
setStatus('Monitoring stopped.', 'ok');
|
|
await refreshMonitorStatus();
|
|
} catch (e) {
|
|
setStatus(`Stop monitoring failed: ${e.message}`, 'error');
|
|
btn.disabled = false;
|
|
}
|
|
btn.textContent = '■ Stop';
|
|
}
|
|
|
|
// Serial mode: SFM's audited change -- identity and state read first, one send,
|
|
// never retried, then read back. The result body says what the unit did, on a
|
|
// 409/502 too; only the read that follows decides the panel.
|
|
async function changeMonitoring(action) {
|
|
const serial = normSerial(currentUnit().serial);
|
|
const verb = action === 'start' ? 'Start' : 'Stop';
|
|
if (!confirm(`${verb} monitoring on ${serial}?`)) return;
|
|
const btn = document.getElementById(action === 'start' ? 'mon-start-btn' : 'mon-stop-btn');
|
|
const label = btn.textContent;
|
|
changeInFlight = true; setMonitorButtons(); btn.textContent = '…';
|
|
setStatus(action === 'start' ? 'Starting — the unit runs its sensor check first (about 35 s)'
|
|
: 'Stopping…', 'loading');
|
|
try {
|
|
const r = await deviceRequest(action);
|
|
const body = await r.json().catch(() => ({}));
|
|
if (body.outcome) {
|
|
setStatus(changeSummary(body), r.ok ? 'ok' : 'error');
|
|
} else {
|
|
setStatus(changeErrorText(`${verb} monitoring`, r.status, body, currentUnit(), r.statusText), 'error');
|
|
}
|
|
} catch (e) {
|
|
// No reply is not "nothing sent": the request may have reached the unit.
|
|
setStatus(`${verb} monitoring: no reply from SFM (${e.message}) — it may have been sent; `
|
|
+ `check the unit's state and GET /db/device_commands`, 'error');
|
|
}
|
|
changeInFlight = false; btn.textContent = label;
|
|
await refreshMonitorStatus();
|
|
setMonitorButtons();
|
|
}
|
|
|
|
// ── Device tab ─────────────────────────────────────────────────────────────────
|
|
function populateDeviceTab() {
|
|
document.getElementById('no-device-msg').style.display = 'none';
|
|
document.getElementById('device-detail').style.display = 'block';
|
|
|
|
// Identity cards
|
|
const cards = document.getElementById('dev-cards');
|
|
cards.innerHTML = '';
|
|
const cardData = [
|
|
{ label:'Serial Number', value: unitInfo.serial || '—' },
|
|
{ label:'Series', value: confirmedSeries(currentUnit()) ?? '—' },
|
|
{ label:'Firmware', value: firmwareLabel(unitInfo) },
|
|
{ label:'DSP', value: unitInfo.dsp_version || (unitInfo.detail || {}).dsp_version || '—' },
|
|
{ label:'Model', value: unitInfo.model || '—' },
|
|
{ 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() },
|
|
];
|
|
for (const {label, value} of cardData) {
|
|
const c = document.createElement('div');
|
|
c.className = 'dev-card';
|
|
const l = document.createElement('div'); l.className = 'dev-card-label'; l.textContent = label;
|
|
const v = document.createElement('div'); v.className = 'dev-card-value'; v.textContent = value;
|
|
c.append(l, v);
|
|
cards.appendChild(c);
|
|
}
|
|
|
|
// The legacy settings tables are empty by serial (#12); the Config tab reads them.
|
|
const legacy = serialPanes(serialMode(), false).legacyDeviceTables;
|
|
document.getElementById('dev-legacy-tables').hidden = !legacy;
|
|
document.getElementById('dev-serial-note').hidden = legacy;
|
|
|
|
// Compliance table
|
|
const cc = unitInfo.compliance_config || {};
|
|
const RECORDING_MODE_LABELS = {0: 'Single Shot', 1: 'Continuous', 3: 'Histogram', 4: 'Histogram + Continuous'};
|
|
const complianceRows = [
|
|
['Recording Mode', cc.recording_mode != null ? (RECORDING_MODE_LABELS[cc.recording_mode] || `0x${cc.recording_mode.toString(16).padStart(2,'0')}`) : '—'],
|
|
['Sample Rate', cc.sample_rate != null ? `${cc.sample_rate} sps` : '—'],
|
|
['Histogram Interval', cc.histogram_interval_sec != null ? (() => { const s = cc.histogram_interval_sec; return s < 60 ? `${s}s` : `${s/60}m`; })() : '—'],
|
|
['Record Time', cc.record_time != null ? `${cc.record_time.toFixed(2)} s` : '—'],
|
|
['Trigger Level (geo)', cc.trigger_level_geo != null ? `${cc.trigger_level_geo.toFixed(4)} in/s` : '—'],
|
|
['Alarm Level (geo)', cc.alarm_level_geo != null ? `${cc.alarm_level_geo.toFixed(4)} in/s` : '—'],
|
|
['Max Range (geo)', cc.geo_range != null ? (cc.geo_range === 0 ? 'Normal — 10.000 in/s' : cc.geo_range === 1 ? 'Sensitive — 1.250 in/s' : `0x${cc.geo_range.toString(16).padStart(2,'0')}`) : '—'],
|
|
['ADC Scale Factor (geo)', cc.geo_adc_scale != null ? `${cc.geo_adc_scale.toFixed(4)} in/s` : '—'],
|
|
['Setup Name', cc.setup_name || '—'],
|
|
];
|
|
renderTextTable('compliance-table', complianceRows);
|
|
|
|
// Project table
|
|
const projectRows = [
|
|
['Project', cc.project || '—'],
|
|
['Client', cc.client || '—'],
|
|
['Operator', cc.operator || '—'],
|
|
['Sensor Location', cc.sensor_location || '—'],
|
|
['Notes', cc.notes || '—'],
|
|
];
|
|
renderTextTable('project-table', projectRows);
|
|
}
|
|
|
|
function renderTextTable(id, rows) {
|
|
const el = document.getElementById(id);
|
|
el.innerHTML = '';
|
|
for (const [label, value] of rows) {
|
|
const row = document.createElement('div');
|
|
row.className = 'dev-table-row';
|
|
const l = document.createElement('div'); l.className = 'dtr-label'; l.textContent = label;
|
|
const v = document.createElement('div'); v.className = 'dtr-value'; v.textContent = value;
|
|
row.append(l, v);
|
|
el.appendChild(row);
|
|
}
|
|
}
|
|
|
|
function renderTable(id, rows) {
|
|
const el = document.getElementById(id);
|
|
el.innerHTML = '';
|
|
for (const [label, value] of rows) {
|
|
const row = document.createElement('div');
|
|
row.className = 'dev-table-row';
|
|
row.innerHTML = `<div class="dtr-label">${label}</div><div class="dtr-value">${value}</div>`;
|
|
el.appendChild(row);
|
|
}
|
|
}
|
|
|
|
// ── Diagnostics ────────────────────────────────────────────────────────────────
|
|
// Everything here is a cheap probe (POLL + one read) or a single write. None of
|
|
// it walks the event chain. See docs/runbooks/wedged_unit_recovery.md.
|
|
|
|
function storageUsedLabel() {
|
|
if (!storageInfo) return '—';
|
|
if (storageInfo.is_empty) return 'empty';
|
|
const f = storageInfo.first_key, l = storageInfo.last_key;
|
|
return (f && l) ? `${f} → ${l}` : '—';
|
|
}
|
|
|
|
function setDiagButtonsEnabled(on) {
|
|
for (const id of ['diag-refresh-btn','diag-stop-btn','diag-ach-btn',
|
|
'diag-drip-btn','diag-blind-btn']) {
|
|
const el = document.getElementById(id);
|
|
if (el) el.disabled = !on;
|
|
}
|
|
diagCheckEraseConfirm();
|
|
}
|
|
|
|
// Erase is guarded by typing the serial — auth answers "who", not "did you mean it".
|
|
function diagCheckEraseConfirm() {
|
|
const box = document.getElementById('diag-erase-confirm');
|
|
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()
|
|
|| !controlsFor(currentUnit()).diagnostics;
|
|
}
|
|
|
|
function diagResult(id, text, cls) {
|
|
const el = document.getElementById(id);
|
|
if (!el) return;
|
|
el.textContent = text;
|
|
el.className = 'diag-result' + (cls ? ' ' + cls : '');
|
|
}
|
|
|
|
async function refreshDiagnostics() {
|
|
if (!devHost()) return;
|
|
const st = document.getElementById('diag-status');
|
|
if (!controlsFor(currentUnit()).diagnostics) {
|
|
if (st) { st.textContent = 'Diagnostics are MiniMate tools: connect to a Series-3 unit first.'; st.className = ''; }
|
|
return;
|
|
}
|
|
if (st) { st.textContent = 'Reading…'; st.className = 'loading'; }
|
|
|
|
const [mon, store, idx] = await Promise.all([
|
|
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;
|
|
|
|
const err = v => `<span style="color:var(--red)">${escapeHtml(v)}</span>`;
|
|
const rows = [];
|
|
|
|
rows.push(['Monitoring', mon._err ? err(mon._err)
|
|
: ((mon.monitoring ?? mon.is_monitoring) ? '<b>MONITORING</b>' : 'idle')]);
|
|
if (!mon._err) {
|
|
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);
|
|
rows.push(['Memory used', `${used.toLocaleString()} / ${mon.memory_total_bytes.toLocaleString()} bytes (${pct}%)`]);
|
|
}
|
|
}
|
|
|
|
rows.push(['Event chain', store._err ? err(store._err) : storageUsedLabel()]);
|
|
if (!store._err) rows.push(['Chain empty', store.is_empty ? 'yes' : 'no']);
|
|
|
|
// SUB 0x08. Known to report 0 on units with years of history — suspected
|
|
// field-offset bug in the decode, so show it but do not trust it.
|
|
rows.push(['Lifetime events', idx._err ? err(idx._err)
|
|
: `${idx.lifetime_count} <span class="hint" style="display:inline">(unreliable — see CHANGELOG)</span>`]);
|
|
|
|
renderTable('diag-table', rows);
|
|
populateDeviceTab();
|
|
if (st) { st.textContent = ''; st.className = ''; }
|
|
}
|
|
|
|
async function diagStopMonitoring() {
|
|
const btn = document.getElementById('diag-stop-btn');
|
|
btn.disabled = true; diagResult('diag-stop-result', 'Sending…');
|
|
try {
|
|
const r = await deviceFetch('stop');
|
|
diagResult('diag-stop-result', r.outcome ? changeSummary(r) : 'Stop acknowledged — recording halted.', 'ok');
|
|
refreshDiagnostics();
|
|
} catch (e) {
|
|
diagResult('diag-stop-result', `Failed: ${e.message}`, 'error');
|
|
}
|
|
btn.disabled = false;
|
|
}
|
|
|
|
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 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) {
|
|
diagResult('diag-ach-result', `Failed: ${e.message}`, 'error');
|
|
}
|
|
btn.disabled = false;
|
|
}
|
|
|
|
async function diagEraseEvents() {
|
|
const serial = (unitInfo && unitInfo.serial) || 'this unit';
|
|
if (!confirm(`Permanently erase ALL events on ${serial}?\n\nThis cannot be undone.`)) return;
|
|
const btn = document.getElementById('diag-erase-btn');
|
|
btn.disabled = true; diagResult('diag-erase-result', 'Erasing…');
|
|
try {
|
|
await deviceFetch('erase');
|
|
diagResult('diag-erase-result', 'Events erased — chain reset to 0x01110000.', 'ok');
|
|
document.getElementById('diag-erase-confirm').value = '';
|
|
eventList = []; eventsLoaded = false;
|
|
setEventButtonsEnabled(); populateEventChips();
|
|
refreshDiagnostics();
|
|
} catch (e) {
|
|
diagResult('diag-erase-result', `Failed: ${e.message}`, 'error');
|
|
}
|
|
diagCheckEraseConfirm();
|
|
}
|
|
|
|
async function diagSlowDrip() {
|
|
const btn = document.getElementById('diag-drip-btn');
|
|
btn.disabled = true;
|
|
diagResult('diag-drip-result', 'Holding a session for 120 s…');
|
|
try {
|
|
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}` +
|
|
(r.send_error ? ` · ${r.send_error}` : '') +
|
|
(good ? ' → device responded' : ' → no response; the modem may not be bridging'),
|
|
good ? 'ok' : 'error');
|
|
} catch (e) {
|
|
diagResult('diag-drip-result', `Failed: ${e.message}`, 'error');
|
|
}
|
|
btn.disabled = false;
|
|
}
|
|
|
|
async function diagBlindStop() {
|
|
const btn = document.getElementById('diag-blind-btn');
|
|
btn.disabled = true; diagResult('diag-blind-result', 'Sending…');
|
|
try {
|
|
const r = await deviceFetch('blind_stop');
|
|
diagResult('diag-blind-result',
|
|
`Sent ${r.bytes_sent ?? '?'} bytes, no response read (fire-and-forget).`, 'ok');
|
|
} catch (e) {
|
|
diagResult('diag-blind-result', `Failed: ${e.message}`, 'error');
|
|
}
|
|
btn.disabled = false;
|
|
}
|
|
|
|
// ── Config form ────────────────────────────────────────────────────────────────
|
|
function populateConfigFromDeviceInfo() {
|
|
if (!unitInfo) return;
|
|
const cc = unitInfo.compliance_config || {};
|
|
if (cc.recording_mode != null) qs('cfg-recording-mode', String(cc.recording_mode));
|
|
if (cc.sample_rate) qs('cfg-sample-rate', String(cc.sample_rate));
|
|
if (cc.histogram_interval_sec != null) qs('cfg-histogram-interval', String(cc.histogram_interval_sec));
|
|
if (cc.record_time != null) qs('cfg-record-time', cc.record_time.toFixed(1));
|
|
if (cc.trigger_level_geo != null) qs('cfg-trigger', cc.trigger_level_geo.toFixed(4));
|
|
if (cc.alarm_level_geo != null) qs('cfg-alarm', cc.alarm_level_geo.toFixed(4));
|
|
if (cc.geo_range != null) qs('cfg-geo-range', String(cc.geo_range));
|
|
if (cc.project) qs('cfg-project', cc.project);
|
|
if (cc.client) qs('cfg-client', cc.client);
|
|
if (cc.operator) qs('cfg-operator', cc.operator);
|
|
if (cc.sensor_location) qs('cfg-seis-loc', cc.sensor_location);
|
|
if (cc.notes) qs('cfg-notes', cc.notes);
|
|
}
|
|
|
|
function clearConfigForm() {
|
|
['cfg-sample-rate','cfg-record-time','cfg-trigger','cfg-alarm',
|
|
'cfg-project','cfg-client','cfg-operator','cfg-seis-loc','cfg-notes',
|
|
'cfg-recording-mode','cfg-histogram-interval','cfg-geo-range']
|
|
.forEach(id => { const el = qs(id); el.tagName === 'SELECT' ? el.selectedIndex = 0 : el.value = ''; });
|
|
setCfgStatus('');
|
|
}
|
|
|
|
// Serial mode: the shared UnitSettings, read-only (writes wait for phase 5).
|
|
async function readSettingsBySerial() {
|
|
const btn = document.getElementById('cfg-read-btn');
|
|
btn.disabled = true;
|
|
setCfgStatus('Reading settings from the unit…');
|
|
try {
|
|
const st = await deviceFetch('settings');
|
|
renderTextTable('cfg-settings-table', settingsRows(st));
|
|
settingsShownFor = normSerial(st.serial);
|
|
document.getElementById('cfg-settings').style.display = 'block';
|
|
document.getElementById('cfg-form').style.display = 'none';
|
|
setCfgStatus(`Settings read from ${st.serial}.`, 'ok');
|
|
} catch (e) {
|
|
setCfgStatus(`Read failed: ${e.message}`, 'error');
|
|
} finally {
|
|
btn.disabled = false;
|
|
}
|
|
}
|
|
|
|
async function readConfig() {
|
|
if (!devHost()) { setCfgStatus('Not connected.', 'error'); return; }
|
|
if (serialMode()) { await readSettingsBySerial(); return; }
|
|
document.getElementById('cfg-settings').style.display = 'none';
|
|
document.getElementById('cfg-form').style.display = '';
|
|
setCfgStatus('Reading config from device…');
|
|
document.getElementById('cfg-read-btn').disabled = true;
|
|
try {
|
|
unitInfo = await deviceFetch('info');
|
|
populateConfigFromDeviceInfo();
|
|
populateDeviceBar();
|
|
populateDeviceTab();
|
|
setCfgStatus('Config loaded from device.', 'ok');
|
|
} catch(e) {
|
|
setCfgStatus(`Read failed: ${e.message}`, 'error');
|
|
} finally {
|
|
document.getElementById('cfg-read-btn').disabled = false;
|
|
}
|
|
}
|
|
|
|
async function writeConfig() {
|
|
if (!devHost()) { setCfgStatus('Not connected.', 'error'); return; }
|
|
|
|
// Build body — only include fields that have values
|
|
const body = {};
|
|
const rm = qs('cfg-recording-mode').value;
|
|
if (rm !== '') body.recording_mode = parseInt(rm, 10);
|
|
const sr = qs('cfg-sample-rate').value;
|
|
if (sr) body.sample_rate = parseInt(sr, 10);
|
|
const hi = qs('cfg-histogram-interval').value;
|
|
if (hi !== '') body.histogram_interval_sec = parseInt(hi, 10);
|
|
const rt = qs('cfg-record-time').value;
|
|
if (rt) body.record_time = parseFloat(rt);
|
|
const trig = qs('cfg-trigger').value;
|
|
if (trig) body.trigger_level_geo = parseFloat(trig);
|
|
const alarm = qs('cfg-alarm').value;
|
|
if (alarm) body.alarm_level_geo = parseFloat(alarm);
|
|
const gr = qs('cfg-geo-range').value;
|
|
if (gr !== '') body.geo_range = parseInt(gr, 10);
|
|
const proj = qs('cfg-project').value.trim();
|
|
if (proj) body.project = proj;
|
|
const cli = qs('cfg-client').value.trim();
|
|
if (cli) body.client_name = cli;
|
|
const op = qs('cfg-operator').value.trim();
|
|
if (op) body.operator = op;
|
|
const sl = qs('cfg-seis-loc').value.trim();
|
|
if (sl) body.seis_loc = sl;
|
|
const notes = qs('cfg-notes').value.trim();
|
|
if (notes) body.notes = notes;
|
|
|
|
if (Object.keys(body).length === 0) {
|
|
setCfgStatus('No fields to write — fill in at least one field.', 'error');
|
|
return;
|
|
}
|
|
|
|
const fieldsStr = Object.keys(body).join(', ');
|
|
setCfgStatus(`Writing ${Object.keys(body).length} field(s)…`);
|
|
document.getElementById('cfg-write-btn').disabled = true;
|
|
|
|
try {
|
|
await deviceFetch('config_write', {}, {
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(body),
|
|
});
|
|
setCfgStatus(`Written: ${fieldsStr}`, 'ok');
|
|
// Re-read device info so Device tab and bar refresh
|
|
await readConfig();
|
|
} catch(e) {
|
|
setCfgStatus(`Write failed: ${e.message}`, 'error');
|
|
} finally {
|
|
document.getElementById('cfg-write-btn').disabled = false;
|
|
}
|
|
}
|
|
|
|
// ── Call Home form ─────────────────────────────────────────────────────────────
|
|
function setChStatus(msg, type) {
|
|
const el = document.getElementById('ch-status');
|
|
el.textContent = msg;
|
|
el.style.color = type === 'ok' ? '#4caf50' : type === 'error' ? '#f44336' : '#aaa';
|
|
}
|
|
|
|
function populateCallHomeForm(ch) {
|
|
if (!ch) return;
|
|
const qs2 = id => document.getElementById(id);
|
|
|
|
// Read-only display fields
|
|
if (ch.dial_string != null) qs2('ch-dial-string').value = ch.dial_string || '';
|
|
if (ch.num_retries != null) qs2('ch-num-retries').value = ch.num_retries;
|
|
if (ch.time_between_retries_sec != null) qs2('ch-retry-gap').value = ch.time_between_retries_sec;
|
|
if (ch.wait_for_connection_sec != null) qs2('ch-wait-conn').value = ch.wait_for_connection_sec;
|
|
if (ch.warm_up_time_sec != null) qs2('ch-warmup').value = ch.warm_up_time_sec;
|
|
|
|
// Editable select/input fields (use "" for "unchanged" state when value is null)
|
|
function setBool(id, val) {
|
|
if (val != null) document.getElementById(id).value = val ? 'true' : 'false';
|
|
}
|
|
setBool('ch-enabled', ch.auto_call_home_enabled);
|
|
setBool('ch-after-event', ch.after_event_recorded);
|
|
setBool('ch-at-times', ch.at_specified_times);
|
|
setBool('ch-t1-enabled', ch.time1_enabled);
|
|
setBool('ch-t2-enabled', ch.time2_enabled);
|
|
if (ch.time1_hour != null) qs2('ch-t1-hour').value = ch.time1_hour;
|
|
if (ch.time1_min != null) qs2('ch-t1-min').value = ch.time1_min;
|
|
if (ch.time2_hour != null) qs2('ch-t2-hour').value = ch.time2_hour;
|
|
if (ch.time2_min != null) qs2('ch-t2-min').value = ch.time2_min;
|
|
}
|
|
|
|
function clearCallHomeForm() {
|
|
['ch-enabled','ch-after-event','ch-at-times','ch-t1-enabled','ch-t2-enabled']
|
|
.forEach(id => { document.getElementById(id).selectedIndex = 0; });
|
|
['ch-t1-hour','ch-t1-min','ch-t2-hour','ch-t2-min']
|
|
.forEach(id => { document.getElementById(id).value = ''; });
|
|
// Keep read-only display fields but clear them too
|
|
['ch-dial-string','ch-num-retries','ch-retry-gap','ch-wait-conn','ch-warmup']
|
|
.forEach(id => { document.getElementById(id).value = ''; });
|
|
setChStatus('');
|
|
}
|
|
|
|
async function readCallHome() {
|
|
if (!devHost()) { setChStatus('Not connected.', 'error'); return; }
|
|
if (serialMode()) { await readCallHomeBySerial(); return; }
|
|
setChStatus('Reading call home config from device…');
|
|
document.getElementById('ch-read-btn').disabled = true;
|
|
try {
|
|
const ch = await deviceFetch('call_home_read');
|
|
populateCallHomeForm(ch);
|
|
setChStatus('Call home config loaded from device.', 'ok');
|
|
} catch(e) {
|
|
setChStatus(`Read failed: ${e.message}`, 'error');
|
|
} finally {
|
|
document.getElementById('ch-read-btn').disabled = false;
|
|
}
|
|
}
|
|
|
|
async function writeCallHome() {
|
|
if (!devHost()) { setChStatus('Not connected.', 'error'); return; }
|
|
|
|
// Build body — only include fields that have values
|
|
const body = {};
|
|
|
|
function getBool(id) {
|
|
const v = document.getElementById(id).value;
|
|
return v === '' ? null : v === 'true';
|
|
}
|
|
function getIntField(id) {
|
|
const v = document.getElementById(id).value.trim();
|
|
return v === '' ? null : parseInt(v, 10);
|
|
}
|
|
|
|
const en = getBool('ch-enabled');
|
|
if (en !== null) body.auto_call_home_enabled = en;
|
|
const ae = getBool('ch-after-event');
|
|
if (ae !== null) body.after_event_recorded = ae;
|
|
const at = getBool('ch-at-times');
|
|
if (at !== null) body.at_specified_times = at;
|
|
const t1e = getBool('ch-t1-enabled');
|
|
if (t1e !== null) body.time1_enabled = t1e;
|
|
const t1h = getIntField('ch-t1-hour');
|
|
if (t1h !== null) body.time1_hour = t1h;
|
|
const t1m = getIntField('ch-t1-min');
|
|
if (t1m !== null) body.time1_min = t1m;
|
|
const t2e = getBool('ch-t2-enabled');
|
|
if (t2e !== null) body.time2_enabled = t2e;
|
|
const t2h = getIntField('ch-t2-hour');
|
|
if (t2h !== null) body.time2_hour = t2h;
|
|
const t2m = getIntField('ch-t2-min');
|
|
if (t2m !== null) body.time2_min = t2m;
|
|
|
|
if (Object.keys(body).length === 0) {
|
|
setChStatus('No fields to write — change at least one field.', 'error');
|
|
return;
|
|
}
|
|
|
|
// Warn about value 3 in hour/min fields
|
|
const hourMinFields = [body.time1_hour, body.time1_min, body.time2_hour, body.time2_min];
|
|
if (hourMinFields.some(v => v === 3)) {
|
|
setChStatus('Error: value 3 in hour/minute fields is not supported (DLE protocol limitation).', 'error');
|
|
return;
|
|
}
|
|
|
|
const fieldsStr = Object.keys(body).join(', ');
|
|
setChStatus(`Writing ${Object.keys(body).length} field(s)…`);
|
|
document.getElementById('ch-write-btn').disabled = true;
|
|
|
|
try {
|
|
await deviceFetch('call_home_write', {}, {
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(body),
|
|
});
|
|
setChStatus(`Written: ${fieldsStr}`, 'ok');
|
|
// Re-read to confirm changes
|
|
await readCallHome();
|
|
} catch(e) {
|
|
setChStatus(`Write failed: ${e.message}`, 'error');
|
|
} finally {
|
|
document.getElementById('ch-write-btn').disabled = false;
|
|
}
|
|
}
|
|
|
|
// ── Events ─────────────────────────────────────────────────────────────────────
|
|
function populateEventChips() {
|
|
const el = document.getElementById('event-chips');
|
|
el.innerHTML = '';
|
|
const wrap = document.getElementById('serial-events-wrap');
|
|
wrap.style.display = eventsBySerial && eventList.length ? 'block' : 'none';
|
|
if (eventsBySerial) {
|
|
populateSerialEventTable();
|
|
document.getElementById('empty-state').style.display = eventList.length ? 'none' : 'flex';
|
|
updatePeaksBar(null);
|
|
return;
|
|
}
|
|
eventList.forEach((ev, i) => {
|
|
const chip = document.createElement('button');
|
|
chip.className = 'event-chip' + (i === 0 ? ' active' : '');
|
|
const view = eventView(ev);
|
|
chip.textContent = view.label;
|
|
chip.title = view.title;
|
|
chip.onclick = () => selectEvent(i);
|
|
el.appendChild(chip);
|
|
});
|
|
|
|
// Show peak values from the event list header (no waveform needed)
|
|
if (eventList.length > 0) updatePeaksBar(eventList[0]);
|
|
}
|
|
|
|
function populateSerialEventTable() {
|
|
const tbody = document.getElementById('serial-events-tbody');
|
|
tbody.innerHTML = '';
|
|
const ips = v => v != null ? v.toFixed(5) : '—';
|
|
eventList.forEach((ev, i) => {
|
|
const view = eventView(ev);
|
|
const pk = view.peaks || {};
|
|
const tr = document.createElement('tr');
|
|
for (const text of [ev.index, view.label, view.title || '—', ips(pk.pvs), ips(pk.tran), ips(pk.vert), ips(pk.long)]) {
|
|
const td = document.createElement('td');
|
|
td.textContent = text;
|
|
tr.appendChild(td);
|
|
}
|
|
const td = document.createElement('td');
|
|
const btn = document.createElement('button');
|
|
btn.className = 'btn btn-ghost';
|
|
btn.textContent = '⬇ Download';
|
|
btn.title = 'Download this event from the unit, check it and store it; then open it';
|
|
btn.onclick = () => downloadEventBySerial(i, btn);
|
|
td.appendChild(btn);
|
|
tr.appendChild(td);
|
|
tbody.appendChild(tr);
|
|
});
|
|
}
|
|
|
|
function selectEvent(idx) {
|
|
// The arrow keys reach here too: they obey the same rule as the buttons.
|
|
if (!perIndexLive({ bySerial: eventsBySerial, count: eventList.length })) return;
|
|
currentEvent = idx;
|
|
document.querySelectorAll('.event-chip').forEach((c, i) => c.classList.toggle('active', i === idx));
|
|
document.getElementById('prev-btn').disabled = idx <= 0;
|
|
document.getElementById('next-btn').disabled = idx >= eventList.length - 1;
|
|
if (eventList[idx]) updatePeaksBar(eventList[idx]);
|
|
loadWaveform();
|
|
}
|
|
|
|
function stepEvent(delta) {
|
|
const next = Math.max(0, Math.min(eventList.length - 1, currentEvent + delta));
|
|
selectEvent(next);
|
|
}
|
|
|
|
function updatePeaksBar(ev) {
|
|
const pk = ev ? eventView(ev).peaks : null;
|
|
const bar = document.getElementById('peaks-bar');
|
|
if (!pk) { bar.classList.remove('visible'); return; }
|
|
bar.classList.add('visible');
|
|
const ips = v => v != null ? `${v.toFixed(5)} in/s` : '—';
|
|
qs('pk-tran').textContent = ips(pk.tran);
|
|
qs('pk-vert').textContent = ips(pk.vert);
|
|
qs('pk-long').textContent = ips(pk.long);
|
|
const micDbl = pk.micPsi != null && pk.micPsi > 0 ? 20 * Math.log10(pk.micPsi / DBL_REF) : null;
|
|
qs('pk-mic').textContent = micDbl != null ? `${micDbl.toFixed(1)} dBL` : '—';
|
|
qs('pk-pvs').textContent = ips(pk.pvs);
|
|
}
|
|
|
|
async function loadWaveform() {
|
|
if (!devHost()) { setStatus('Enter device host first.', 'error'); return; }
|
|
const idx = currentEvent;
|
|
document.getElementById('load-btn').disabled = true;
|
|
setStatus('Fetching waveform…', 'loading');
|
|
|
|
let data;
|
|
try {
|
|
data = await deviceFetch('event_waveform', { index: idx });
|
|
} catch(e) {
|
|
setStatus(`Waveform error: ${e.message}`, 'error');
|
|
document.getElementById('load-btn').disabled = false;
|
|
return;
|
|
}
|
|
|
|
renderWaveform(data);
|
|
document.getElementById('load-btn').disabled = false;
|
|
}
|
|
|
|
// ── Persist current event to the SFM database + waveform store ──────────────
|
|
//
|
|
// Calls /device/event/{idx}/blastware_file, which on the server side:
|
|
// 1. Downloads the full waveform from the device (5A bulk stream)
|
|
// 2. Writes the Blastware-format event file into <db_dir>/waveforms/<serial>/
|
|
// 3. Writes the .a5.pkl sidecar next to it (so the file can be regenerated)
|
|
// 4. Upserts a row into seismo_relay.db `events` table (dedup'd on serial+timestamp)
|
|
//
|
|
// We discard the response body — the side effects are what we want. The
|
|
// filename comes back in the Content-Disposition header for confirmation.
|
|
async function saveEventToDb() {
|
|
if (!devHost()) { setStatus('Enter device host first.', 'error'); return; }
|
|
const idx = currentEvent;
|
|
const btn = document.getElementById('save-btn');
|
|
btn.disabled = true;
|
|
const orig = btn.textContent;
|
|
btn.textContent = '⏳ Saving…';
|
|
setStatus(`Downloading event #${idx} and saving to DB…`, 'loading');
|
|
|
|
try {
|
|
const r = await deviceRequest('event_file', { index: idx });
|
|
if (!r.ok) {
|
|
const e = await r.json().catch(() => ({}));
|
|
throw new Error(e.detail || r.statusText);
|
|
}
|
|
// Pull the body to completion so the connection releases promptly,
|
|
// then drop it on the floor — we just want the server-side persist.
|
|
await r.blob();
|
|
const filename = parseFilenameFromContentDisposition(r.headers.get('Content-Disposition'))
|
|
|| `event ${idx}`;
|
|
setStatus(`Saved ${filename} to database + waveform store`, 'ok');
|
|
} catch (e) {
|
|
setStatus(`Save error: ${e.message}`, 'error');
|
|
} finally {
|
|
btn.disabled = false;
|
|
btn.textContent = orig;
|
|
}
|
|
}
|
|
|
|
// A list loaded by serial: download one event by its event_id -- SFM checks it
|
|
// and stores it -- then open it from the store. An event already stored says so.
|
|
async function downloadEventBySerial(i, btn) {
|
|
const ev = eventList[i];
|
|
btn.disabled = true;
|
|
setStatus(`Downloading event #${ev.index} (${eventView(ev).label})…`, 'loading');
|
|
try {
|
|
const body = await deviceFetch('download', { event_id: ev.event_id });
|
|
setStatus(downloadSummary(body), 'ok');
|
|
if (body.db_event_id) openSidecarModal(body.db_event_id);
|
|
} catch (e) {
|
|
setStatus(`Download failed: ${e.message}`, 'error');
|
|
} finally {
|
|
btn.disabled = false;
|
|
}
|
|
}
|
|
|
|
// ── Download the event file to the user's computer ──────────────────────────
|
|
//
|
|
// Uses a transient anchor + click trick so the browser surfaces its native
|
|
// "Save As" / Downloads behaviour. Same backend endpoint as Save to DB —
|
|
// the file is also persisted to the server store as a side effect.
|
|
function downloadEventFile() {
|
|
if (!devHost()) { setStatus('Enter device host first.', 'error'); return; }
|
|
const idx = currentEvent;
|
|
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.
|
|
const a = document.createElement('a');
|
|
a.href = url;
|
|
a.style.display = 'none';
|
|
document.body.appendChild(a);
|
|
a.click();
|
|
document.body.removeChild(a);
|
|
// We can't reliably detect when the browser finishes downloading; show a
|
|
// soft confirmation immediately. Errors will surface as a download failure
|
|
// dialog from the browser itself.
|
|
setTimeout(() => setStatus(`Download started for event #${idx} (also saved server-side)`, 'ok'), 250);
|
|
}
|
|
|
|
function parseFilenameFromContentDisposition(header) {
|
|
if (!header) return null;
|
|
// RFC 6266: `attachment; filename="M529LKIQ.7M0W"` (or filename*=UTF-8''…)
|
|
const m = /filename\*?=(?:UTF-8'')?["']?([^"';]+)["']?/i.exec(header);
|
|
return m ? decodeURIComponent(m[1]) : null;
|
|
}
|
|
|
|
// renderWaveform consumes the `sfm.plot.v1` JSON shape:
|
|
// {
|
|
// schema: "sfm.plot.v1",
|
|
// time_axis: { sample_rate, pretrig_samples, t0_ms, dt_ms, n_samples, ... },
|
|
// channels: { Tran|Vert|Long|MicL: { unit, values, peak, peak_t_ms } },
|
|
// geo_range, geo_full_scale_ips, trigger_ms, peak_values, ...
|
|
// }
|
|
//
|
|
// All sample arrays are already in PHYSICAL UNITS (in/s for geo, psi for
|
|
// mic) — the server applied the right scaling for the unit's geo_range.
|
|
// The viewer used to multiply ADC ints by `geoAdcScale / 32767` here,
|
|
// which silently scaled every plot ~38% too low because `geoAdcScale` is
|
|
// the in/s-per-V hardware constant, not the ADC-counts-to-velocity
|
|
// factor. No scaling happens client-side now.
|
|
function renderWaveform(data) {
|
|
// Backward-compat shim: if we ever get the legacy shape from a stale
|
|
// cache, normalise it on the client so the viewer still works.
|
|
if (!data.schema && data.channels && Array.isArray(data.channels.Tran)) {
|
|
data = _legacyWaveformToPlotV1(data);
|
|
}
|
|
|
|
const t = data.time_axis || {};
|
|
const sr = t.sample_rate || 1024;
|
|
const pretrig = t.pretrig_samples || 0;
|
|
const total = t.total_samples || t.n_samples || 0;
|
|
const decoded = t.n_samples || 0;
|
|
const t0 = t.t0_ms ?? -(pretrig / sr * 1000);
|
|
const dt = t.dt_ms ?? (1000 / sr);
|
|
const channels = data.channels || {};
|
|
|
|
// Status bar
|
|
const bar = document.getElementById('status-bar');
|
|
bar.innerHTML = '';
|
|
bar.className = 'ok';
|
|
const ts = data.timestamp;
|
|
// Title prefers `index` (live device, 0-based slot on the unit) and
|
|
// falls back to event_id (DB lookup) when index is absent.
|
|
const eventLabel = (data.index != null) ? `#${data.index}` : (data.event_id || '');
|
|
bar.textContent = ts ? `Event ${eventLabel} — ${ts} ` : `Event ${eventLabel} `;
|
|
addPill(`${data.record_type || '?'}`);
|
|
addPill(`${sr} sps`);
|
|
addPill(`${decoded.toLocaleString()} / ${total.toLocaleString()} samples`);
|
|
addPill(`pretrig ${pretrig}`);
|
|
addPill(`${t.rectime_seconds ?? '?'} s`);
|
|
if (data.geo_range) addPill(`geo: ${data.geo_range} (${data.geo_full_scale_ips} in/s FS)`);
|
|
|
|
// Any record_type starting with "Waveform" is a viewable triggered
|
|
// event (the timestamp-header byte layout varies across firmware but
|
|
// doesn't change the sample stream). Only block when there's actually
|
|
// no waveform payload to plot.
|
|
const isWaveformLike = !!(data.record_type || '').match(/^Waveform/i);
|
|
if (decoded === 0) {
|
|
document.getElementById('empty-state').style.display = 'flex';
|
|
document.getElementById('empty-state').querySelector('p').textContent =
|
|
isWaveformLike
|
|
? 'No samples decoded — check server logs'
|
|
: `Record type "${data.record_type}" — not a waveform event`;
|
|
document.getElementById('charts').style.display = 'none';
|
|
Object.values(charts).forEach(c => c.destroy()); charts = {};
|
|
return;
|
|
}
|
|
|
|
// Time axis: explicit ms values from t0_ms + i*dt_ms. More precise
|
|
// than the old (i - pretrig) / sr * 1000 since dt_ms came from the
|
|
// server with full float precision.
|
|
const times = Array.from({length: decoded}, (_, i) => (t0 + i * dt).toFixed(2));
|
|
document.getElementById('empty-state').style.display = 'none';
|
|
const chartsDiv = document.getElementById('charts');
|
|
chartsDiv.style.display = 'flex';
|
|
chartsDiv.innerHTML = '';
|
|
Object.values(charts).forEach(c => c.destroy()); charts = {};
|
|
|
|
for (const [ch, color] of Object.entries(CHANNEL_COLORS)) {
|
|
const chData = channels[ch];
|
|
if (!chData || !chData.values || chData.values.length === 0) continue;
|
|
|
|
const plotData = chData.values;
|
|
const unit = chData.unit || (ch === 'MicL' ? 'psi' : 'in/s');
|
|
const peak = chData.peak;
|
|
const peakTms = chData.peak_t_ms;
|
|
|
|
let peakLabel, ttFmt, tickFmt;
|
|
if (unit === 'psi') {
|
|
const peakDbl = (peak != null && peak > 0)
|
|
? 20 * Math.log10(peak / DBL_REF) : -Infinity;
|
|
peakLabel = `${peakDbl.toFixed(1)} dBL (${peak != null ? peak.toExponential(2) : '—'} psi)`;
|
|
ttFmt = v => `${v.toExponential(3)} psi`;
|
|
tickFmt = v => v.toExponential(1);
|
|
} else {
|
|
peakLabel = peak != null ? `${peak.toFixed(5)} in/s` : '—';
|
|
ttFmt = v => `${ch}: ${v.toFixed(5)} in/s`;
|
|
tickFmt = v => v.toFixed(4);
|
|
}
|
|
|
|
// Downsample for display when the chart would otherwise have to
|
|
// rasterise tens of thousands of points. Uses every-Nth — fine for
|
|
// monthly-summary glance work; analysis tools should use the .h5 file.
|
|
const MAX_PTS = 4000;
|
|
let rTimes = times, rData = plotData, peakPlotIdx = -1;
|
|
if (plotData.length > MAX_PTS) {
|
|
const step = Math.ceil(plotData.length / MAX_PTS);
|
|
rTimes = times.filter((_, i) => i % step === 0);
|
|
rData = plotData.filter((_, i) => i % step === 0);
|
|
// Try to keep the peak sample from being downsampled away.
|
|
if (peakTms != null) {
|
|
const exactIdx = Math.round((peakTms - t0) / dt);
|
|
if (exactIdx >= 0 && exactIdx < plotData.length) {
|
|
peakPlotIdx = Math.floor(exactIdx / step);
|
|
}
|
|
}
|
|
} else if (peakTms != null) {
|
|
peakPlotIdx = Math.round((peakTms - t0) / dt);
|
|
}
|
|
|
|
const wrap = document.createElement('div');
|
|
wrap.className = 'chart-wrap';
|
|
const lbl = document.createElement('div');
|
|
lbl.className = `chart-label ch-${ch.toLowerCase()}`;
|
|
lbl.textContent = `${ch} — peak ${peakLabel}`;
|
|
wrap.appendChild(lbl);
|
|
const cw = document.createElement('div');
|
|
cw.className = 'chart-canvas-wrap';
|
|
const canvas = document.createElement('canvas');
|
|
cw.appendChild(canvas); wrap.appendChild(cw); chartsDiv.appendChild(wrap);
|
|
|
|
charts[ch] = new Chart(canvas, {
|
|
type: 'line',
|
|
data: { labels: rTimes, datasets: [{ data: rData, borderColor: color, borderWidth: 1, pointRadius: 0, tension: 0 }] },
|
|
options: {
|
|
animation: false, responsive: true, maintainAspectRatio: false,
|
|
plugins: {
|
|
legend: { display: false },
|
|
tooltip: {
|
|
mode: 'index', intersect: false,
|
|
callbacks: { title: items => `t = ${items[0].label} ms`, label: item => ttFmt(item.raw) },
|
|
},
|
|
},
|
|
scales: {
|
|
x: { type: 'category', ticks: { color:'#484f58', maxTicksLimit:10, maxRotation:0, callback:(v,i) => rTimes[i]+' ms' }, grid: { color:'#21262d' } },
|
|
y: { ticks: { color:'#484f58', maxTicksLimit:5, callback: v => tickFmt(v) }, grid: { color:'#21262d' }, title: { display:true, text:unit, color:'#484f58', font:{size:10} } },
|
|
},
|
|
},
|
|
plugins: [{
|
|
id: 'triggerAndPeakMarkers',
|
|
afterDraw(chart) {
|
|
const { ctx, scales: {x, y} } = chart;
|
|
// Trigger line at t = trigger_ms (typically 0).
|
|
const triggerMs = data.trigger_ms ?? 0;
|
|
const zeroIdx = rTimes.findIndex(s => parseFloat(s) >= triggerMs);
|
|
if (zeroIdx >= 0) {
|
|
const px = x.getPixelForValue(zeroIdx);
|
|
ctx.save();
|
|
ctx.beginPath();
|
|
ctx.moveTo(px, y.top); ctx.lineTo(px, y.bottom);
|
|
ctx.strokeStyle = 'rgba(248,81,73,0.7)'; ctx.lineWidth = 1.5;
|
|
ctx.setLineDash([4, 3]); ctx.stroke(); ctx.restore();
|
|
}
|
|
// Peak marker (dot at the channel's peak sample).
|
|
if (peakPlotIdx >= 0 && peakPlotIdx < rData.length) {
|
|
const px = x.getPixelForValue(peakPlotIdx);
|
|
const py = y.getPixelForValue(rData[peakPlotIdx]);
|
|
ctx.save();
|
|
ctx.beginPath();
|
|
ctx.arc(px, py, 3.2, 0, Math.PI * 2);
|
|
ctx.fillStyle = color;
|
|
ctx.strokeStyle = '#0d1117';
|
|
ctx.lineWidth = 1.5;
|
|
ctx.fill(); ctx.stroke();
|
|
ctx.restore();
|
|
}
|
|
},
|
|
}],
|
|
});
|
|
}
|
|
}
|
|
|
|
// One-time normaliser for the legacy /device/event/{idx}/waveform shape
|
|
// (samples as int16 ADC counts in `channels.{ch}: [...]`). Bridges the
|
|
// gap if a stale cache or non-upgraded server returns the old format.
|
|
function _legacyWaveformToPlotV1(data) {
|
|
const sr = data.sample_rate || 1024;
|
|
const pretrig = data.pretrig_samples || 0;
|
|
const decoded = data.samples_decoded || 0;
|
|
const total = data.total_samples || decoded;
|
|
const dt = 1000 / sr;
|
|
const t0 = -pretrig * dt;
|
|
|
|
// Apply the CORRECT scale: 10 in/s full-scale for Normal range.
|
|
const geoFs = 10.0;
|
|
const geoScale = geoFs / 32768;
|
|
const ch = data.channels || {};
|
|
const micPeak = data.peak_values?.micl_psi ?? null;
|
|
const micPeakCounts = (ch.MicL || ch.Mic || []).reduce((m, v) => Math.max(m, Math.abs(v)), 0);
|
|
const micScale = (micPeak != null && micPeakCounts > 0) ? micPeak / micPeakCounts : 1.0;
|
|
|
|
const mkGeo = (counts) => {
|
|
if (!counts || !counts.length) return [];
|
|
return counts.map(c => c * geoScale);
|
|
};
|
|
const mkMic = (counts) => {
|
|
if (!counts || !counts.length) return [];
|
|
return counts.map(c => c * micScale);
|
|
};
|
|
|
|
return {
|
|
schema: 'sfm.plot.v1',
|
|
event_id: data.event_id || null,
|
|
serial: data.serial || '',
|
|
timestamp: data.timestamp?.display || data.timestamp || '',
|
|
record_type: data.record_type,
|
|
waveform_key: null,
|
|
time_axis: {
|
|
sample_rate: sr, pretrig_samples: pretrig, total_samples: total,
|
|
n_samples: decoded, t0_ms: t0, dt_ms: dt,
|
|
rectime_seconds: data.rectime_seconds || 0,
|
|
},
|
|
geo_range: 'normal', geo_full_scale_ips: geoFs, trigger_ms: 0,
|
|
channels: {
|
|
Tran: { unit:'in/s', values: mkGeo(ch.Tran), peak: data.peak_values?.tran_in_s ?? null, peak_t_ms: null },
|
|
Vert: { unit:'in/s', values: mkGeo(ch.Vert), peak: data.peak_values?.vert_in_s ?? null, peak_t_ms: null },
|
|
Long: { unit:'in/s', values: mkGeo(ch.Long), peak: data.peak_values?.long_in_s ?? null, peak_t_ms: null },
|
|
MicL: { unit:'psi', values: mkMic(ch.MicL || ch.Mic), peak: micPeak, peak_t_ms: null },
|
|
},
|
|
peak_values: data.peak_values || {},
|
|
};
|
|
}
|
|
|
|
// ── DB tabs ────────────────────────────────────────────────────────────────────
|
|
let histLoaded = false;
|
|
let unitsLoaded = false;
|
|
let monlogLoaded = false;
|
|
let sessLoaded = false;
|
|
|
|
// Shared serial filter options — populated from /db/units
|
|
const _unitSerials = new Set();
|
|
|
|
function _ppvClass(v) {
|
|
const n = (v == null) ? null : Number(v);
|
|
if (n == null || !isFinite(n)) return '';
|
|
if (n >= 2.0) return 'ppv-high';
|
|
if (n >= 0.5) return 'ppv-warn';
|
|
return 'ppv-ok';
|
|
}
|
|
function _ppvFmt(v) {
|
|
if (v == null) return '—';
|
|
const n = typeof v === 'number' ? v : Number(v);
|
|
return isFinite(n) ? n.toFixed(5) : String(v);
|
|
}
|
|
function _fmtTs(ts) {
|
|
if (!ts) return '—';
|
|
// ts is ISO string; show date + time, strip trailing seconds if all zeros
|
|
const d = new Date(ts);
|
|
return d.toLocaleString();
|
|
}
|
|
function _fmtDur(sec) {
|
|
if (sec == null) return '—';
|
|
const h = Math.floor(sec / 3600);
|
|
const m = Math.floor((sec % 3600) / 60);
|
|
const s = Math.floor(sec % 60);
|
|
if (h > 0) return `${h}h ${m}m ${s}s`;
|
|
if (m > 0) return `${m}m ${s}s`;
|
|
return `${s}s`;
|
|
}
|
|
|
|
function _populateSerialDropdown(selectId, currentVal) {
|
|
const sel = document.getElementById(selectId);
|
|
const prev = currentVal ?? sel.value;
|
|
sel.innerHTML = '<option value="">All units</option>';
|
|
for (const sn of [..._unitSerials].sort()) {
|
|
const opt = document.createElement('option');
|
|
opt.value = sn; opt.textContent = sn;
|
|
sel.appendChild(opt);
|
|
}
|
|
if (prev) sel.value = prev;
|
|
}
|
|
|
|
async function _fetchUnits() {
|
|
try {
|
|
const r = await fetch(`${api()}/db/units`);
|
|
if (!r.ok) return [];
|
|
return await r.json();
|
|
} catch { return []; }
|
|
}
|
|
|
|
// ── History tab ────────────────────────────────────────────────────────────────
|
|
// Module-level state for the history table — preserved across re-sorts.
|
|
// We sort + re-render without re-fetching.
|
|
let _histEvents = [];
|
|
let _histSortKey = 'timestamp';
|
|
let _histSortDir = 'desc'; // 'asc' | 'desc'
|
|
|
|
async function loadHistory() {
|
|
histLoaded = true;
|
|
const serial = document.getElementById('hist-serial-filter').value;
|
|
const from_dt = document.getElementById('hist-from').value;
|
|
const to_dt = document.getElementById('hist-to').value;
|
|
const hideFT = document.getElementById('hist-hide-ft').checked;
|
|
|
|
let url = `${api()}/db/events?limit=500`;
|
|
if (serial) url += `&serial=${encodeURIComponent(serial)}`;
|
|
if (from_dt) url += `&from_dt=${encodeURIComponent(from_dt)}`;
|
|
if (to_dt) url += `&to_dt=${encodeURIComponent(to_dt + 'T23:59:59')}`;
|
|
|
|
let data;
|
|
try {
|
|
const r = await fetch(url);
|
|
if (!r.ok) throw new Error(r.statusText);
|
|
data = await r.json();
|
|
} catch (e) {
|
|
document.getElementById('hist-count').textContent = `Error: ${e.message}`;
|
|
return;
|
|
}
|
|
|
|
let events = data.events || [];
|
|
if (hideFT) events = events.filter(ev => !ev.false_trigger);
|
|
|
|
// Update serial dropdowns with any new serials seen
|
|
events.forEach(ev => { if (ev.serial) _unitSerials.add(ev.serial); });
|
|
_populateSerialDropdown('hist-serial-filter');
|
|
_populateSerialDropdown('monlog-serial-filter');
|
|
_populateSerialDropdown('sess-serial-filter');
|
|
|
|
_histEvents = events;
|
|
renderHistTable();
|
|
}
|
|
|
|
// Re-render the history table from `_histEvents` using the current sort
|
|
// state. Pulled out of `loadHistory` so column-header clicks can re-sort
|
|
// in-memory without re-fetching from the server.
|
|
function renderHistTable() {
|
|
const events = _histEvents;
|
|
document.getElementById('hist-count').textContent =
|
|
`${events.length} event${events.length !== 1 ? 's' : ''}`;
|
|
|
|
const tbody = document.getElementById('hist-tbody');
|
|
tbody.innerHTML = '';
|
|
if (events.length === 0) {
|
|
document.getElementById('hist-empty').style.display = 'block';
|
|
document.getElementById('hist-table-wrap').style.display = 'none';
|
|
return;
|
|
}
|
|
document.getElementById('hist-empty').style.display = 'none';
|
|
document.getElementById('hist-table-wrap').style.display = 'block';
|
|
|
|
// Sort in-place by current key + direction. Nulls sink to the bottom
|
|
// regardless of direction.
|
|
const k = _histSortKey;
|
|
const dir = _histSortDir === 'asc' ? 1 : -1;
|
|
const sorted = [...events].sort((a, b) => {
|
|
const av = a[k], bv = b[k];
|
|
if (av == null && bv == null) return 0;
|
|
if (av == null) return 1;
|
|
if (bv == null) return -1;
|
|
if (typeof av === 'number' && typeof bv === 'number') return (av - bv) * dir;
|
|
return String(av).localeCompare(String(bv)) * dir;
|
|
});
|
|
|
|
// Update arrow indicators in the headers
|
|
document.querySelectorAll('#hist-header-row th[data-sort]').forEach(th => {
|
|
const arrow = th.querySelector('.sort-arrow');
|
|
if (!arrow) return;
|
|
arrow.textContent = th.dataset.sort === k ? (_histSortDir === 'asc' ? '↑' : '↓') : '';
|
|
});
|
|
|
|
for (const ev of sorted) {
|
|
const tr = document.createElement('tr');
|
|
const pvs = ev.peak_vector_sum;
|
|
tr.classList.add('clickable');
|
|
tr.title = 'Click to view waveform + sidecar';
|
|
tr.dataset.eventId = ev.id;
|
|
tr.innerHTML = `
|
|
<td>${_fmtTs(ev.timestamp)}</td>
|
|
<td class="td-key">${ev.serial ?? '—'}</td>
|
|
<td class="${_ppvClass(ev.tran_ppv)}">${_ppvFmt(ev.tran_ppv)}</td>
|
|
<td class="${_ppvClass(ev.vert_ppv)}">${_ppvFmt(ev.vert_ppv)}</td>
|
|
<td class="${_ppvClass(ev.long_ppv)}">${_ppvFmt(ev.long_ppv)}</td>
|
|
<td class="${_ppvClass(pvs)}">${_ppvFmt(pvs)}</td>
|
|
<td class="td-dim">${(() => {
|
|
const m = ev.mic_ppv == null ? null : Number(ev.mic_ppv);
|
|
if (m == null || !isFinite(m) || m <= 0) return '—';
|
|
// Series III (MiniMate Plus / BW) stores mic_ppv as psi → convert.
|
|
// Series IV (Micromate / Thor) already stores dB(L) → display direct.
|
|
if (ev.device_family === 'series4') return m.toFixed(1) + ' dBL';
|
|
return (20 * Math.log10(m / DBL_REF)).toFixed(1) + ' dBL';
|
|
})()}</td>
|
|
<td class="td-text">${ev.project ?? '—'}</td>
|
|
<td class="td-text">${ev.client ?? '—'}</td>
|
|
<td class="td-dim">${ev.record_type ?? '—'}</td>
|
|
<td class="td-dim" style="font-size:10px">${ev.waveform_key ?? '—'}</td>
|
|
<td>${ev.false_trigger ? '<span class="ft-badge">FALSE</span>' : ''}</td>
|
|
`;
|
|
tr.addEventListener('click', () => openSidecarModal(ev.id));
|
|
tbody.appendChild(tr);
|
|
}
|
|
}
|
|
|
|
// Click a column header → toggle sort. Click another → set sort to that column.
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
const headerRow = document.getElementById('hist-header-row');
|
|
if (!headerRow) return;
|
|
headerRow.querySelectorAll('th[data-sort]').forEach(th => {
|
|
th.style.cursor = 'pointer';
|
|
th.style.userSelect = 'none';
|
|
th.addEventListener('click', () => {
|
|
const k = th.dataset.sort;
|
|
if (_histSortKey === k) {
|
|
_histSortDir = _histSortDir === 'asc' ? 'desc' : 'asc';
|
|
} else {
|
|
_histSortKey = k;
|
|
// Default direction: 'desc' for numbers + timestamps (biggest/newest first),
|
|
// 'asc' for text columns (alphabetical).
|
|
_histSortDir = ['serial','project','client','record_type','waveform_key'].includes(k) ? 'asc' : 'desc';
|
|
}
|
|
renderHistTable();
|
|
});
|
|
});
|
|
});
|
|
|
|
// ── Sidecar review modal ───────────────────────────────────────────────────────
|
|
//
|
|
// Opens on row click in the History table. Loads the .sfm.json sidecar
|
|
// for the event via GET /db/events/{id}/sidecar, lets the user toggle
|
|
// false_trigger / edit notes / set reviewer, and saves via PATCH on the
|
|
// same URL. This mirrors the workflow used by the monthly vibration
|
|
// summary process — most of the rich review UX lives in Terra-View;
|
|
// this is the SFM-standalone equivalent for testing / direct edits.
|
|
|
|
let _scCurrentEventId = null;
|
|
let _scCurrentSidecar = null;
|
|
|
|
async function openSidecarModal(eventId) {
|
|
_scCurrentEventId = eventId;
|
|
_scCurrentSidecar = null;
|
|
document.getElementById('sc-status').textContent = 'Loading sidecar…';
|
|
document.getElementById('sc-status').className = 'sc-status';
|
|
document.getElementById('sc-overlay').classList.add('visible');
|
|
// Reset edit fields
|
|
document.getElementById('sc-edit-ft').checked = false;
|
|
document.getElementById('sc-edit-reviewer').value = '';
|
|
document.getElementById('sc-edit-notes').value = '';
|
|
// Reset waveform area
|
|
document.getElementById('sc-waveform-status').textContent = 'Loading waveform…';
|
|
document.getElementById('sc-waveform-charts').innerHTML = '';
|
|
_destroyScCharts();
|
|
|
|
// Sidecar + waveform fetched in parallel — neither blocks the other.
|
|
const sidecarP = fetch(`${api()}/db/events/${eventId}/sidecar`)
|
|
.then(async r => {
|
|
if (!r.ok) { const e = await r.json().catch(() => ({})); throw new Error(e.detail || r.statusText); }
|
|
return r.json();
|
|
});
|
|
const waveformP = fetch(`${api()}/db/events/${eventId}/waveform.json`)
|
|
.then(async r => {
|
|
if (r.status === 404) return null; // no waveform available — render empty state
|
|
if (!r.ok) { const e = await r.json().catch(() => ({})); throw new Error(e.detail || r.statusText); }
|
|
return r.json();
|
|
});
|
|
|
|
// Sidecar usually loads first (smaller payload). Each one renders
|
|
// independently so the modal becomes useful as soon as either lands.
|
|
sidecarP.then(data => {
|
|
_scCurrentSidecar = data;
|
|
_renderSidecar(data);
|
|
document.getElementById('sc-status').textContent = '';
|
|
}).catch(e => {
|
|
document.getElementById('sc-status').className = 'sc-status error';
|
|
document.getElementById('sc-status').textContent = `Sidecar load failed: ${e.message}`;
|
|
});
|
|
|
|
waveformP.then(data => {
|
|
if (!data) {
|
|
document.getElementById('sc-waveform-status').textContent = 'No waveform data for this event.';
|
|
return;
|
|
}
|
|
_renderScWaveform(data);
|
|
}).catch(e => {
|
|
document.getElementById('sc-waveform-status').textContent = `Waveform load failed: ${e.message}`;
|
|
});
|
|
}
|
|
|
|
// ── Sidecar-modal waveform plot ──────────────────────────────────────────────
|
|
// Renders the 4-channel decoded waveform fetched from
|
|
// /db/events/{id}/waveform.json — MicL on top, Tran on bottom (matches
|
|
// Instantel BW Event Report layout). Uses Chart.js (loaded at the top of
|
|
// the page for the live-device viewer).
|
|
const _SC_CHANNEL_COLORS = {
|
|
MicL: '#e066ff',
|
|
Long: '#3a80ff',
|
|
Vert: '#3fb950',
|
|
Tran: '#f85149',
|
|
};
|
|
const _SC_CHANNEL_ORDER = ['MicL', 'Long', 'Vert', 'Tran'];
|
|
let _scCharts = {};
|
|
|
|
// User preference for how mic is displayed in plots — dBL (default,
|
|
// matches BW printout convention + the rest of SFM) or psi (the raw
|
|
// sample unit). Toggleable via the header pill; persists in localStorage.
|
|
function _getMicUnit() {
|
|
return localStorage.getItem('sfm_mic_unit') === 'psi' ? 'psi' : 'dBL';
|
|
}
|
|
function _setMicUnit(u) {
|
|
localStorage.setItem('sfm_mic_unit', u === 'psi' ? 'psi' : 'dBL');
|
|
_refreshMicUnitToggleLabel();
|
|
// Re-render the open modal so the change is immediately visible.
|
|
if (_scCurrentEventId) openSidecarModal(_scCurrentEventId);
|
|
}
|
|
function _refreshMicUnitToggleLabel() {
|
|
const b = document.getElementById('mic-unit-toggle');
|
|
if (b) b.textContent = `Mic: ${_getMicUnit()}`;
|
|
}
|
|
// Convert a psi value to dB(L). Returns null for non-positive values
|
|
// (log of zero is undefined) — Chart.js handles null as a gap in the line.
|
|
function _psiToDbl(psi) {
|
|
if (psi == null || !(psi > 0)) return null;
|
|
return 20 * Math.log10(psi / DBL_REF);
|
|
}
|
|
|
|
// Per-sample mic display floor. Sound pressure AC samples spend most
|
|
// of their time at the digitization noise floor (1-2 ADC counts ≈ ~20-40
|
|
// dBL). Rendering each one as null/-inf produces a spikey discontinuous
|
|
// chart of "moments when sound briefly exceeded 80 dBL" — confusing.
|
|
// Instead we rectify (abs the AC waveform), convert to dBL, and floor
|
|
// anything below MIC_DBL_FLOOR so the chart has a continuous baseline
|
|
// with peaks rising above it. Matches how acoustic engineers expect to
|
|
// see SPL-vs-time.
|
|
const MIC_DBL_FLOOR = 60;
|
|
function _psiToDblForChart(psi) {
|
|
if (psi == null) return MIC_DBL_FLOOR;
|
|
const a = Math.abs(psi);
|
|
if (a === 0) return MIC_DBL_FLOOR;
|
|
const dbl = 20 * Math.log10(a / DBL_REF);
|
|
return dbl > MIC_DBL_FLOOR ? dbl : MIC_DBL_FLOOR;
|
|
}
|
|
|
|
// Adaptive decimal formatter — scientific notation is reserved for truly
|
|
// extreme values (10000+ or sub-0.0001). Normal-range values (most peaks
|
|
// fall here) render as decimals with sensible precision. Replaces the
|
|
// previous .toExponential(3) call that turned every peak into ugly "2.500E-2".
|
|
function _fmtPeak(v, unit) {
|
|
if (v == null || (typeof v === 'number' && !isFinite(v))) return '';
|
|
if (typeof v !== 'number') return String(v) + (unit ? ' ' + unit : '');
|
|
if (v === 0) return '0' + (unit ? ' ' + unit : '');
|
|
const a = Math.abs(v);
|
|
const u = unit ? ' ' + unit : '';
|
|
if (a >= 0.0001 && a < 10000) {
|
|
const d = a >= 100 ? 1 : a >= 10 ? 2 : a >= 1 ? 3 : a >= 0.1 ? 4 : 5;
|
|
return v.toFixed(d) + u;
|
|
}
|
|
return v.toExponential(2) + u;
|
|
}
|
|
|
|
function _destroyScCharts() {
|
|
Object.values(_scCharts).forEach(c => { try { c.destroy(); } catch {} });
|
|
_scCharts = {};
|
|
}
|
|
|
|
function _renderScWaveform(data) {
|
|
document.getElementById('sc-waveform-status').textContent = '';
|
|
const chartsDiv = document.getElementById('sc-waveform-charts');
|
|
chartsDiv.innerHTML = '';
|
|
_destroyScCharts();
|
|
|
|
const channels = data.channels || {};
|
|
// time_axis is METADATA, not an array — it carries sample_rate,
|
|
// pretrig_samples, t0_ms (first-sample time relative to trigger,
|
|
// negative when pretrig samples exist), and dt_ms. Trigger is at
|
|
// t=0 by convention.
|
|
const ta = data.time_axis || {};
|
|
const sr = ta.sample_rate || 1024;
|
|
const dtMs = ta.dt_ms || (1000.0 / sr);
|
|
const t0Ms = ta.t0_ms != null ? ta.t0_ms : 0;
|
|
// Histogram events have per-interval peaks, not per-sample data.
|
|
// Render as bars (one per interval) instead of a connected line, and
|
|
// suppress trigger/zero overlays which don't apply. X-axis becomes
|
|
// interval index since the sample_rate-based time math is meaningless
|
|
// here (each "sample" is one interval, typically 1-5 minutes long).
|
|
const isHistogram = String(data.record_type || '').toLowerCase().includes('histogram');
|
|
|
|
// Which channels have data — determines which one renders the shared bottom axis.
|
|
const withData = _SC_CHANNEL_ORDER.filter(ch =>
|
|
channels[ch] && (channels[ch].values || []).length > 0
|
|
);
|
|
const lastCh = withData[withData.length - 1];
|
|
|
|
const micUnit = _getMicUnit(); // user preference: 'dBL' or 'psi'
|
|
|
|
for (const ch of _SC_CHANNEL_ORDER) {
|
|
const chData = channels[ch];
|
|
if (!chData) continue;
|
|
let values = chData.values || [];
|
|
let chUnit = chData.unit || '';
|
|
let chPeak = chData.peak;
|
|
|
|
// Mic channel: convert from raw psi to dB(L) when user prefers dBL
|
|
// (default). Per-sample values use _psiToDblForChart which rectifies
|
|
// (abs) the AC waveform and floors at MIC_DBL_FLOOR so the chart is
|
|
// continuous with a baseline + peaks above it, instead of a sparse
|
|
// pattern of isolated spikes for "moments when sound briefly exceeded
|
|
// the Y-axis bottom". The peak label uses _psiToDbl with the
|
|
// unrectified peak (preserves the true measurement).
|
|
if (ch === 'MicL' && chUnit === 'psi' && micUnit === 'dBL') {
|
|
values = values.map(_psiToDblForChart);
|
|
chPeak = _psiToDbl(chPeak);
|
|
chUnit = 'dB(L)';
|
|
}
|
|
|
|
const wrap = document.createElement('div');
|
|
wrap.style.cssText = 'background:var(--surface);border:1px solid var(--border2);border-radius:6px;padding:6px 30px 4px 10px';
|
|
const lbl = document.createElement('div');
|
|
lbl.style.cssText = `font-size:10px;font-weight:600;letter-spacing:0.05em;text-transform:uppercase;margin-bottom:2px;color:${_SC_CHANNEL_COLORS[ch]};display:flex;justify-content:space-between`;
|
|
const peakStr = chPeak != null
|
|
? `peak ${_fmtPeak(chPeak, chUnit)}`
|
|
: '';
|
|
lbl.innerHTML = `<span>${ch}</span><span style="color:var(--text-dim);font-weight:normal">${peakStr}</span>`;
|
|
wrap.appendChild(lbl);
|
|
|
|
if (values.length === 0) {
|
|
const e = document.createElement('div');
|
|
e.style.cssText = 'height:80px;display:flex;align-items:center;justify-content:center;color:var(--text-dim);font-size:11px';
|
|
e.textContent = 'no samples decoded';
|
|
wrap.appendChild(e);
|
|
chartsDiv.appendChild(wrap);
|
|
continue;
|
|
}
|
|
|
|
const canvasWrap = document.createElement('div');
|
|
canvasWrap.style.cssText = 'position:relative;height:100px';
|
|
const canvas = document.createElement('canvas');
|
|
canvasWrap.appendChild(canvas);
|
|
wrap.appendChild(canvasWrap);
|
|
chartsDiv.appendChild(wrap);
|
|
|
|
// Waveform: per-sample time in ms relative to trigger (negative for pretrig).
|
|
// Histogram: when the server has aggregated to BW-reported intervals AND
|
|
// provides per-interval timestamps, use those as x-axis labels (HH:MM:SS).
|
|
// Falls back to interval index.
|
|
let times;
|
|
if (isHistogram) {
|
|
const intervalTimes = ta.interval_times || [];
|
|
times = (intervalTimes.length === values.length)
|
|
? intervalTimes
|
|
: values.map((_, i) => i + 1);
|
|
} else {
|
|
times = values.map((_, i) => t0Ms + i * dtMs);
|
|
}
|
|
|
|
// Downsample for rendering when very long.
|
|
const MAX = 3000;
|
|
let rT = times, rV = values;
|
|
if (values.length > MAX) {
|
|
const step = Math.ceil(values.length / MAX);
|
|
rT = times.filter((_, i) => i % step === 0);
|
|
rV = values.filter((_, i) => i % step === 0);
|
|
}
|
|
const showX = (ch === lastCh);
|
|
|
|
// Tick label formatter: snap floats to 1 decimal place so we don't get
|
|
// "11.7187040000000002 ms" garbage from accumulated floating-point error.
|
|
const xAxisLabel = isHistogram ? '' : ' ms';
|
|
const fmtTick = i => {
|
|
const v = rT[i];
|
|
if (typeof v === 'number') {
|
|
// Whole numbers (intervals) → no decimals. Sub-integer ms → 1 decimal.
|
|
const s = Number.isInteger(v) ? String(v) : v.toFixed(1);
|
|
return s + xAxisLabel;
|
|
}
|
|
return String(v) + xAxisLabel;
|
|
};
|
|
|
|
// Y-axis bounds. Convention:
|
|
// - Geophones (Tran/Vert/Long) on waveform-mode events:
|
|
// symmetric around zero so the zero line sits in the middle and
|
|
// positive/negative excursions are visually balanced.
|
|
// - Mic (always positive sound pressure) + histograms (per-interval
|
|
// peaks, always positive): default auto-scale, zero at the bottom.
|
|
let yBounds = {};
|
|
const isGeo = ch !== 'MicL';
|
|
if (isGeo && !isHistogram) {
|
|
// Waveform geo: symmetric around zero, full zoom to shape detail.
|
|
let absMax = 0;
|
|
for (const v of values) {
|
|
const a = Math.abs(v);
|
|
if (a > absMax) absMax = a;
|
|
}
|
|
const padded = (absMax || 1) * 1.10;
|
|
yBounds = { min: -padded, max: padded };
|
|
} else if (isGeo && isHistogram) {
|
|
// Histogram geo: enforce a minimum chart range so a quiet
|
|
// 0.005 in/s event renders as ~10% of chart height instead of
|
|
// filling the panel. Matches BW's near-fixed-scale convention
|
|
// (their footer is "Geo: 0.002 in/s/div" — a chart-relative scale,
|
|
// not auto-zoom).
|
|
const HIST_GEO_MIN_INS = 0.05;
|
|
let peak = 0;
|
|
for (const v of values) { const a = Math.abs(v); if (a > peak) peak = a; }
|
|
yBounds = { min: 0, max: Math.max(peak * 1.10, HIST_GEO_MIN_INS) };
|
|
} else if (ch === 'MicL' && micUnit === 'dBL') {
|
|
// Mic in dBL — pin baseline at noise-floor minimum (where we floored
|
|
// quiet samples), top at actual peak + a few dB headroom.
|
|
const peakDbl = (typeof chPeak === 'number' && isFinite(chPeak))
|
|
? chPeak + 5
|
|
: 100;
|
|
yBounds = { min: MIC_DBL_FLOOR, max: Math.max(peakDbl, MIC_DBL_FLOOR + 20) };
|
|
} else if (ch === 'MicL' && isHistogram && micUnit === 'psi') {
|
|
// Mic histogram in psi — same minimum-range treatment as geo.
|
|
// 0.001 psi ≈ 110 dBL — typical "loud" mic peak. Quiet events
|
|
// sit near the bottom.
|
|
const HIST_MIC_MIN_PSI = 0.001;
|
|
let peak = 0;
|
|
for (const v of values) { const a = Math.abs(v); if (a > peak) peak = a; }
|
|
yBounds = { min: 0, max: Math.max(peak * 1.10, HIST_MIC_MIN_PSI) };
|
|
}
|
|
|
|
_scCharts[ch] = new Chart(canvas, {
|
|
type: isHistogram ? 'bar' : 'line',
|
|
data: {
|
|
labels: rT.map(t => (typeof t === 'number' ? (Number.isInteger(t) ? String(t) : t.toFixed(2)) : t)),
|
|
datasets: isHistogram ? [{
|
|
data: rV,
|
|
backgroundColor: _SC_CHANNEL_COLORS[ch],
|
|
borderWidth: 0,
|
|
barPercentage: 1.0,
|
|
categoryPercentage: 1.0, // bars touch — "tight bargraph" look
|
|
}] : [{
|
|
data: rV,
|
|
borderColor: _SC_CHANNEL_COLORS[ch],
|
|
borderWidth: 1,
|
|
pointRadius: 0,
|
|
tension: 0,
|
|
}],
|
|
},
|
|
options: {
|
|
animation: false, responsive: true, maintainAspectRatio: false,
|
|
plugins: {
|
|
legend: { display: false },
|
|
tooltip: {
|
|
mode: 'index', intersect: false,
|
|
callbacks: {
|
|
title: items => isHistogram
|
|
? `interval ${items[0].label}`
|
|
: `t = ${items[0].label} ms`,
|
|
label: item => `${ch}: ${_fmtPeak(item.raw, chUnit)}`,
|
|
},
|
|
},
|
|
},
|
|
scales: {
|
|
x: {
|
|
type: 'category', display: showX,
|
|
ticks: { color: '#484f58', maxTicksLimit: 8, maxRotation: 0, callback: (v, i) => fmtTick(i) },
|
|
grid: { color: '#21262d', drawTicks: showX },
|
|
},
|
|
y: {
|
|
...yBounds,
|
|
ticks: { color: '#484f58', maxTicksLimit: 4 },
|
|
grid: { color: '#21262d' },
|
|
title: { display: true, text: chUnit, color: '#484f58', font: { size: 9 } },
|
|
},
|
|
},
|
|
},
|
|
plugins: isHistogram ? [] : [{
|
|
// Trigger line + triangle markers + zero baseline — only meaningful
|
|
// for waveform-mode events. Histograms have no trigger.
|
|
id: 'overlays',
|
|
afterDraw(chart) {
|
|
const ctx = chart.ctx, x = chart.scales.x, y = chart.scales.y;
|
|
// Dashed trigger line at t=0
|
|
const zi = rT.findIndex(t => parseFloat(t) >= 0);
|
|
if (zi >= 0) {
|
|
const px = x.getPixelForValue(zi);
|
|
ctx.save();
|
|
ctx.beginPath(); ctx.moveTo(px, y.top); ctx.lineTo(px, y.bottom);
|
|
ctx.strokeStyle = 'rgba(248,81,73,0.8)'; ctx.lineWidth = 1.2;
|
|
ctx.setLineDash([4, 3]); ctx.stroke(); ctx.restore();
|
|
// Triangle markers above and below the chart
|
|
ctx.save();
|
|
ctx.fillStyle = '#f85149';
|
|
ctx.beginPath();
|
|
ctx.moveTo(px - 4, y.top - 7); ctx.lineTo(px + 4, y.top - 7); ctx.lineTo(px, y.top - 1);
|
|
ctx.closePath(); ctx.fill();
|
|
ctx.beginPath();
|
|
ctx.moveTo(px - 4, y.bottom + 7); ctx.lineTo(px + 4, y.bottom + 7); ctx.lineTo(px, y.bottom + 1);
|
|
ctx.closePath(); ctx.fill();
|
|
ctx.restore();
|
|
}
|
|
// Zero baseline + label
|
|
const zy = y.getPixelForValue(0);
|
|
if (zy >= y.top && zy <= y.bottom) {
|
|
ctx.save();
|
|
ctx.strokeStyle = '#30363d'; ctx.lineWidth = 0.8;
|
|
ctx.setLineDash([2, 2]);
|
|
ctx.beginPath(); ctx.moveTo(x.left, zy); ctx.lineTo(x.right, zy); ctx.stroke();
|
|
ctx.restore();
|
|
ctx.save();
|
|
ctx.fillStyle = '#c9d1d9'; ctx.font = '10px monospace';
|
|
ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
|
|
ctx.fillText('0.0', x.right + 6, zy);
|
|
ctx.restore();
|
|
}
|
|
},
|
|
}],
|
|
});
|
|
}
|
|
}
|
|
|
|
// Make sure charts get cleaned up when the modal closes.
|
|
function _scCleanupOnClose() { _destroyScCharts(); }
|
|
|
|
function _renderSidecar(data) {
|
|
const ev = data.event || {};
|
|
const pv = data.peak_values || {};
|
|
const pi = data.project_info || {};
|
|
const bw = data.blastware || {};
|
|
const src = data.source || {};
|
|
const rev = data.review || {};
|
|
// bw_report carries the per-channel ASCII-derived stats (ZC Freq,
|
|
// saturation flags, peak time, etc.). Only present on events
|
|
// ingested with a preserved .TXT (post-2026-05-27); falls back to
|
|
// empty for legacy events.
|
|
const bwrPeaks = (data.bw_report || {}).peaks || {};
|
|
const bwrMic = (data.bw_report || {}).mic || {};
|
|
|
|
document.getElementById('sc-title').textContent = `Event — ${bw.filename || ev.waveform_key || 'unknown'}`;
|
|
|
|
const fmtPpv = v => {
|
|
if (v == null) return '—';
|
|
const n = Number(v);
|
|
return isFinite(n) ? n.toFixed(5) + ' in/s' : String(v);
|
|
};
|
|
// Map sidecar source.kind → device family (Series IV ingest path is
|
|
// "idf-import"; everything else is Series III today). The events-list
|
|
// table uses ev.device_family from the DB row, but sidecars don't carry
|
|
// that column — source.kind is the equivalent signal here.
|
|
const family = ((src.kind || '') === 'idf-import') ? 'series4' : 'series3';
|
|
const fmtMic = v => {
|
|
if (v == null) return '—';
|
|
const n = Number(v);
|
|
if (!isFinite(n) || n <= 0) return '—';
|
|
// Series IV (Micromate / Thor) stores mic as dB(L); Series III (BW)
|
|
// stores it as psi and we render both for cross-reference.
|
|
if (family === 'series4') return `${n.toFixed(1)} dBL`;
|
|
const dbl = 20 * Math.log10(n / DBL_REF);
|
|
return `${dbl.toFixed(1)} dBL (${n.toExponential(2)} psi)`;
|
|
};
|
|
|
|
document.getElementById('sc-f-serial').textContent = ev.serial || '—';
|
|
// Route through _fmtTs so the unit-local naive timestamp shows as
|
|
// "5/27/2026, 6:00:13 AM" instead of "2026-05-27T06:00:13".
|
|
document.getElementById('sc-f-ts').textContent = _fmtTs(ev.timestamp);
|
|
document.getElementById('sc-f-rt').textContent = ev.record_type || '—';
|
|
document.getElementById('sc-f-sr').textContent = (ev.sample_rate ?? '—') + (ev.sample_rate ? ' sps' : '');
|
|
document.getElementById('sc-f-key').textContent = ev.waveform_key || '—';
|
|
|
|
// Suffix with " · {prefix}{N} Hz" when bw_report has a ZC Freq.
|
|
// Above-range ZC peaks (BW ">100 Hz") get a literal ">" prefix so
|
|
// operators see the same indicator the PDF shows.
|
|
const fmtZc = bwr => {
|
|
if (!bwr || bwr.zc_freq_hz == null) return '';
|
|
const prefix = bwr.zc_freq_above_range ? '>' : '';
|
|
return ` · ${prefix}${Math.round(bwr.zc_freq_hz)} Hz`;
|
|
};
|
|
document.getElementById('sc-f-tran').textContent = fmtPpv(pv.transverse) + fmtZc(bwrPeaks.tran);
|
|
document.getElementById('sc-f-vert').textContent = fmtPpv(pv.vertical) + fmtZc(bwrPeaks.vert);
|
|
document.getElementById('sc-f-long').textContent = fmtPpv(pv.longitudinal) + fmtZc(bwrPeaks.long);
|
|
document.getElementById('sc-f-pvs').textContent = fmtPpv(pv.vector_sum);
|
|
document.getElementById('sc-f-mic').textContent = fmtMic(pv.mic_psi) + fmtZc(bwrMic);
|
|
|
|
document.getElementById('sc-f-project').textContent = pi.project || '—';
|
|
document.getElementById('sc-f-client').textContent = pi.client || '—';
|
|
document.getElementById('sc-f-operator').textContent = pi.operator || '—';
|
|
document.getElementById('sc-f-loc').textContent = pi.sensor_location || '—';
|
|
|
|
// Filename rendered as a clickable download link for the original BW
|
|
// binary. Same endpoint the live-device viewer uses for stored events
|
|
// (/db/events/{id}/blastware_file).
|
|
const bwCell = document.getElementById('sc-f-bw');
|
|
bwCell.innerHTML = '';
|
|
if (bw.filename && _scCurrentEventId) {
|
|
const a = document.createElement('a');
|
|
a.href = `${api()}/db/events/${_scCurrentEventId}/blastware_file`;
|
|
a.textContent = bw.filename;
|
|
a.download = bw.filename;
|
|
a.title = 'Download original BW event binary';
|
|
a.style.color = 'var(--accent, #58a6ff)';
|
|
a.style.textDecoration = 'underline';
|
|
bwCell.appendChild(a);
|
|
} else {
|
|
bwCell.textContent = '—';
|
|
}
|
|
document.getElementById('sc-f-bwsize').textContent = bw.filesize != null ? `${bw.filesize} bytes` : '—';
|
|
document.getElementById('sc-f-sha').textContent = bw.sha256 || '—';
|
|
// Source kind + a download link for the preserved BW ASCII report
|
|
// (.TXT), when available. Only events ingested after 2026-05-27
|
|
// have the .TXT preserved; older events show "—".
|
|
const srcCell = document.getElementById('sc-f-src');
|
|
srcCell.innerHTML = '';
|
|
srcCell.appendChild(document.createTextNode(src.kind || '—'));
|
|
if (src.txt_filename && _scCurrentEventId) {
|
|
const a = document.createElement('a');
|
|
a.href = `${api()}/db/events/${_scCurrentEventId}/ascii_report.txt`;
|
|
a.textContent = ' (download .TXT)';
|
|
a.download = src.txt_filename;
|
|
a.title = 'Download preserved BW ASCII report';
|
|
a.style.color = 'var(--accent, #58a6ff)';
|
|
a.style.marginLeft = '8px';
|
|
a.style.fontSize = '11px';
|
|
srcCell.appendChild(a);
|
|
}
|
|
// captured_at has a "Z" suffix (UTC); _fmtTs converts to browser local
|
|
// — matches the BW-reported recorded-at, no more "21:59:57 vs it's 6 PM"
|
|
// confusion from operators reading the raw UTC value.
|
|
document.getElementById('sc-f-cap').textContent = _fmtTs(src.captured_at);
|
|
|
|
document.getElementById('sc-edit-ft').checked = !!rev.false_trigger;
|
|
document.getElementById('sc-edit-reviewer').value = rev.reviewer || '';
|
|
document.getElementById('sc-edit-notes').value = rev.notes || '';
|
|
|
|
document.getElementById('sc-raw-json').textContent = JSON.stringify(data, null, 2);
|
|
}
|
|
|
|
function closeSidecarModal() {
|
|
document.getElementById('sc-overlay').classList.remove('visible');
|
|
_scCurrentEventId = null;
|
|
_scCurrentSidecar = null;
|
|
_destroyScCharts();
|
|
}
|
|
|
|
// Trigger a PDF download for the currently-open event. The browser
|
|
// handles the actual save dialog from the Content-Disposition header
|
|
// the server sends.
|
|
function downloadEventReport() {
|
|
if (!_scCurrentEventId) return;
|
|
const url = `${api()}/db/events/${_scCurrentEventId}/report.pdf`;
|
|
// Open in a new tab — browser prompts to save or displays inline,
|
|
// and a failed fetch (e.g. 404 for events with no waveform) shows
|
|
// its JSON error in-page rather than silently failing.
|
|
window.open(url, '_blank');
|
|
}
|
|
|
|
function onSidecarOverlayClick(e) {
|
|
// Click on the dimmed backdrop (but NOT on the modal itself) closes.
|
|
if (e.target.id === 'sc-overlay') closeSidecarModal();
|
|
}
|
|
|
|
async function saveSidecarReview() {
|
|
if (!_scCurrentEventId) return;
|
|
const btn = document.getElementById('sc-save-btn');
|
|
const status = document.getElementById('sc-status');
|
|
btn.disabled = true;
|
|
status.className = 'sc-status';
|
|
status.textContent = 'Saving…';
|
|
|
|
const review = {
|
|
false_trigger: document.getElementById('sc-edit-ft').checked,
|
|
reviewer: document.getElementById('sc-edit-reviewer').value.trim() || null,
|
|
notes: document.getElementById('sc-edit-notes').value,
|
|
};
|
|
|
|
try {
|
|
const r = await fetch(`${api()}/db/events/${_scCurrentEventId}/sidecar`, {
|
|
method: 'PATCH',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ review }),
|
|
});
|
|
if (!r.ok) {
|
|
const e = await r.json().catch(() => ({}));
|
|
throw new Error(e.detail || r.statusText);
|
|
}
|
|
const updated = await r.json();
|
|
_scCurrentSidecar = updated;
|
|
_renderSidecar(updated);
|
|
status.className = 'sc-status ok';
|
|
status.textContent = 'Saved.';
|
|
// Refresh the History table so the false_trigger badge reflects the change.
|
|
if (typeof loadHistory === 'function') loadHistory();
|
|
setTimeout(closeSidecarModal, 600);
|
|
} catch (e) {
|
|
status.className = 'sc-status error';
|
|
status.textContent = `Save failed: ${e.message}`;
|
|
} finally {
|
|
btn.disabled = false;
|
|
}
|
|
}
|
|
|
|
// Esc closes the modal.
|
|
document.addEventListener('keydown', (e) => {
|
|
if (e.key === 'Escape' && document.getElementById('sc-overlay').classList.contains('visible')) {
|
|
closeSidecarModal();
|
|
}
|
|
});
|
|
|
|
// ── Units tab ──────────────────────────────────────────────────────────────────
|
|
async function loadUnits() {
|
|
unitsLoaded = true;
|
|
const units = await _fetchUnits();
|
|
|
|
units.forEach(u => { if (u.serial) _unitSerials.add(u.serial); });
|
|
_populateSerialDropdown('hist-serial-filter');
|
|
_populateSerialDropdown('monlog-serial-filter');
|
|
_populateSerialDropdown('sess-serial-filter');
|
|
|
|
document.getElementById('units-count').textContent = `${units.length} unit${units.length !== 1 ? 's' : ''}`;
|
|
const grid = document.getElementById('units-grid');
|
|
grid.innerHTML = '';
|
|
|
|
if (units.length === 0) {
|
|
document.getElementById('units-empty').style.display = 'block';
|
|
return;
|
|
}
|
|
document.getElementById('units-empty').style.display = 'none';
|
|
|
|
for (const u of units) {
|
|
const card = document.createElement('div');
|
|
card.className = 'unit-card';
|
|
card.title = 'Click to filter History by this unit';
|
|
card.onclick = () => {
|
|
_populateSerialDropdown('hist-serial-filter', u.serial);
|
|
switchTab('history');
|
|
loadHistory();
|
|
};
|
|
const lastSeen = u.last_seen ? new Date(u.last_seen).toLocaleDateString() : '—';
|
|
card.innerHTML = `
|
|
<div class="uc-serial">${u.serial}</div>
|
|
<div class="uc-stat"><span class="uc-label">Events</span><span class="uc-val">${u.total_events ?? 0}</span></div>
|
|
<div class="uc-stat"><span class="uc-label">Monitor entries</span><span class="uc-val">${u.total_monitor_entries ?? 0}</span></div>
|
|
<div class="uc-stat"><span class="uc-label">Sessions</span><span class="uc-val">${u.total_sessions ?? 0}</span></div>
|
|
<div class="uc-stat"><span class="uc-label">Last seen</span><span class="uc-val">${lastSeen}</span></div>
|
|
`;
|
|
grid.appendChild(card);
|
|
}
|
|
}
|
|
|
|
// ── Monitor Log tab ────────────────────────────────────────────────────────────
|
|
async function loadMonitorLog() {
|
|
monlogLoaded = true;
|
|
const serial = document.getElementById('monlog-serial-filter').value;
|
|
const from_dt = document.getElementById('monlog-from').value;
|
|
const to_dt = document.getElementById('monlog-to').value;
|
|
|
|
let url = `${api()}/db/monitor_log?`;
|
|
if (serial) url += `serial=${encodeURIComponent(serial)}&`;
|
|
if (from_dt) url += `from_dt=${encodeURIComponent(from_dt)}&`;
|
|
if (to_dt) url += `to_dt=${encodeURIComponent(to_dt + 'T23:59:59')}&`;
|
|
|
|
let data;
|
|
try {
|
|
const r = await fetch(url);
|
|
if (!r.ok) throw new Error(r.statusText);
|
|
data = await r.json();
|
|
} catch (e) {
|
|
document.getElementById('monlog-count').textContent = `Error: ${e.message}`;
|
|
return;
|
|
}
|
|
|
|
const entries = data.entries || [];
|
|
entries.forEach(e => { if (e.serial) _unitSerials.add(e.serial); });
|
|
_populateSerialDropdown('hist-serial-filter');
|
|
_populateSerialDropdown('monlog-serial-filter');
|
|
_populateSerialDropdown('sess-serial-filter');
|
|
|
|
document.getElementById('monlog-count').textContent = `${entries.length} entr${entries.length !== 1 ? 'ies' : 'y'}`;
|
|
const tbody = document.getElementById('monlog-tbody');
|
|
tbody.innerHTML = '';
|
|
|
|
if (entries.length === 0) {
|
|
document.getElementById('monlog-empty').style.display = 'block';
|
|
document.getElementById('monlog-table-wrap').style.display = 'none';
|
|
return;
|
|
}
|
|
document.getElementById('monlog-empty').style.display = 'none';
|
|
document.getElementById('monlog-table-wrap').style.display = 'block';
|
|
|
|
for (const e of entries) {
|
|
const tr = document.createElement('tr');
|
|
tr.innerHTML = `
|
|
<td>${_fmtTs(e.start_time)}</td>
|
|
<td>${_fmtTs(e.stop_time)}</td>
|
|
<td>${_fmtDur(e.duration_seconds)}</td>
|
|
<td class="td-key">${e.serial ?? '—'}</td>
|
|
<td>${e.geo_threshold_ips != null ? e.geo_threshold_ips.toFixed(4) + ' in/s' : '—'}</td>
|
|
<td class="td-dim" style="font-size:10px">${e.key ?? '—'}</td>
|
|
`;
|
|
tbody.appendChild(tr);
|
|
}
|
|
}
|
|
|
|
// ── Sessions tab ───────────────────────────────────────────────────────────────
|
|
async function loadSessions() {
|
|
sessLoaded = true;
|
|
const serial = document.getElementById('sess-serial-filter').value;
|
|
|
|
let url = `${api()}/db/sessions?limit=200`;
|
|
if (serial) url += `&serial=${encodeURIComponent(serial)}`;
|
|
|
|
let data;
|
|
try {
|
|
const r = await fetch(url);
|
|
if (!r.ok) throw new Error(r.statusText);
|
|
data = await r.json();
|
|
} catch (e) {
|
|
document.getElementById('sess-count').textContent = `Error: ${e.message}`;
|
|
return;
|
|
}
|
|
|
|
const sessions = data.sessions || [];
|
|
sessions.forEach(s => { if (s.serial) _unitSerials.add(s.serial); });
|
|
_populateSerialDropdown('hist-serial-filter');
|
|
_populateSerialDropdown('monlog-serial-filter');
|
|
_populateSerialDropdown('sess-serial-filter');
|
|
|
|
document.getElementById('sess-count').textContent = `${sessions.length} session${sessions.length !== 1 ? 's' : ''}`;
|
|
const tbody = document.getElementById('sess-tbody');
|
|
tbody.innerHTML = '';
|
|
|
|
if (sessions.length === 0) {
|
|
document.getElementById('sess-empty').style.display = 'block';
|
|
document.getElementById('sess-table-wrap').style.display = 'none';
|
|
return;
|
|
}
|
|
document.getElementById('sess-empty').style.display = 'none';
|
|
document.getElementById('sess-table-wrap').style.display = 'block';
|
|
|
|
for (const s of sessions) {
|
|
const tr = document.createElement('tr');
|
|
tr.innerHTML = `
|
|
<td>${_fmtTs(s.session_time)}</td>
|
|
<td class="td-key">${s.serial ?? '—'}</td>
|
|
<td class="td-dim">${s.peer ?? '—'}</td>
|
|
<td>${s.events_downloaded ?? 0}</td>
|
|
<td>${s.monitor_entries ?? 0}</td>
|
|
<td>${s.duration_seconds != null ? s.duration_seconds.toFixed(1) : '—'}</td>
|
|
`;
|
|
tbody.appendChild(tr);
|
|
}
|
|
}
|
|
|
|
// ── Keyboard shortcuts ─────────────────────────────────────────────────────────
|
|
document.addEventListener('keydown', e => {
|
|
if (e.target.tagName === 'INPUT' || e.target.tagName === 'SELECT') return;
|
|
if (e.key === 'ArrowLeft') { stepEvent(-1); e.preventDefault(); }
|
|
if (e.key === 'ArrowRight') { stepEvent(+1); e.preventDefault(); }
|
|
});
|
|
|
|
// 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(); });
|
|
}
|
|
// New controls are wired here, not with onclick= in the HTML (no inline JS).
|
|
document.getElementById('ch-on-btn').addEventListener('click', () => changeCallHome(true));
|
|
document.getElementById('ch-off-btn').addEventListener('click', () => changeCallHome(false));
|
|
applyControls();
|
|
|
|
// Reflect any persisted mic-unit preference in the header pill on load
|
|
_refreshMicUnitToggleLabel();
|
|
|
|
// We default to Database view → trigger initial history + units load
|
|
// (switchSection handles this when clicked, but we never click on first paint).
|
|
if (currentSection === 'db') {
|
|
if (!histLoaded) loadHistory();
|
|
if (!unitsLoaded) loadUnits();
|
|
}
|
|
|
|
// Press Enter in any live connect field to connect
|
|
['dev-host','dev-port'].forEach(id => {
|
|
document.getElementById(id)?.addEventListener('keydown', e => { if (e.key === 'Enter') connectUnit(); });
|
|
});
|