You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1505 line
51KB

  1. const qs = (id) => document.getElementById(id);
  2. const navCanvas = qs('navCanvas');
  3. const spectrumCanvas = qs('spectrum');
  4. const waterfallCanvas = qs('waterfall');
  5. const occupancyCanvas = qs('occupancy');
  6. const timelineCanvas = qs('timeline');
  7. const detailSpectrogram = qs('detailSpectrogram');
  8. const wsBadge = qs('wsBadge');
  9. const metaLine = qs('metaLine');
  10. const heroSubtitle = qs('heroSubtitle');
  11. const configStatusEl = qs('configStatus');
  12. const timelineRangeEl = qs('timelineRange');
  13. const metricCenter = qs('metricCenter');
  14. const metricSpan = qs('metricSpan');
  15. const metricRes = qs('metricRes');
  16. const metricSignals = qs('metricSignals');
  17. const metricGpu = qs('metricGpu');
  18. const metricSource = qs('metricSource');
  19. const centerInput = qs('centerInput');
  20. const spanInput = qs('spanInput');
  21. const sampleRateSelect = qs('sampleRateSelect');
  22. const bwSelect = qs('bwSelect');
  23. const fftSelect = qs('fftSelect');
  24. const gainRange = qs('gainRange');
  25. const gainInput = qs('gainInput');
  26. const thresholdRange = qs('thresholdRange');
  27. const thresholdInput = qs('thresholdInput');
  28. const cfarToggle = qs('cfarToggle');
  29. const cfarGuardInput = qs('cfarGuardInput');
  30. const cfarTrainInput = qs('cfarTrainInput');
  31. const cfarRankInput = qs('cfarRankInput');
  32. const cfarScaleInput = qs('cfarScaleInput');
  33. const minDurationInput = qs('minDurationInput');
  34. const holdInput = qs('holdInput');
  35. const emaAlphaInput = qs('emaAlphaInput');
  36. const hysteresisInput = qs('hysteresisInput');
  37. const stableFramesInput = qs('stableFramesInput');
  38. const gapToleranceInput = qs('gapToleranceInput');
  39. const agcToggle = qs('agcToggle');
  40. const dcToggle = qs('dcToggle');
  41. const iqToggle = qs('iqToggle');
  42. const avgSelect = qs('avgSelect');
  43. const maxHoldToggle = qs('maxHoldToggle');
  44. const gpuToggle = qs('gpuToggle');
  45. const recEnableToggle = qs('recEnableToggle');
  46. const recIQToggle = qs('recIQToggle');
  47. const recAudioToggle = qs('recAudioToggle');
  48. const recDemodToggle = qs('recDemodToggle');
  49. const recDecodeToggle = qs('recDecodeToggle');
  50. const recMinSNR = qs('recMinSNR');
  51. const recMaxDisk = qs('recMaxDisk');
  52. const recClassFilter = qs('recClassFilter');
  53. const signalList = qs('signalList');
  54. const eventList = qs('eventList');
  55. const recordingList = qs('recordingList');
  56. const signalCountBadge = qs('signalCountBadge');
  57. const eventCountBadge = qs('eventCountBadge');
  58. const recordingCountBadge = qs('recordingCountBadge');
  59. const healthBuffer = qs('healthBuffer');
  60. const healthDropped = qs('healthDropped');
  61. const healthResets = qs('healthResets');
  62. const healthAge = qs('healthAge');
  63. const healthGpu = qs('healthGpu');
  64. const healthFps = qs('healthFps');
  65. const drawerEl = qs('eventDrawer');
  66. const drawerCloseBtn = qs('drawerClose');
  67. const detailSubtitle = qs('detailSubtitle');
  68. const detailCenterEl = qs('detailCenter');
  69. const detailBwEl = qs('detailBw');
  70. const detailStartEl = qs('detailStart');
  71. const detailEndEl = qs('detailEnd');
  72. const detailSnrEl = qs('detailSnr');
  73. const detailDurEl = qs('detailDur');
  74. const detailClassEl = qs('detailClass');
  75. const jumpToEventBtn = qs('jumpToEventBtn');
  76. const exportEventBtn = qs('exportEventBtn');
  77. const liveListenEventBtn = qs('liveListenEventBtn');
  78. const decodeEventBtn = qs('decodeEventBtn');
  79. const decodeModeSelect = qs('decodeMode');
  80. const recordingMetaEl = qs('recordingMeta');
  81. const decodeResultEl = qs('decodeResult');
  82. const classifierScoresEl = qs('classifierScores');
  83. const recordingMetaLink = qs('recordingMetaLink');
  84. const recordingIQLink = qs('recordingIQLink');
  85. const recordingAudioLink = qs('recordingAudioLink');
  86. const followBtn = qs('followBtn');
  87. const fitBtn = qs('fitBtn');
  88. const resetMaxBtn = qs('resetMaxBtn');
  89. const timelineFollowBtn = qs('timelineFollowBtn');
  90. const timelineFreezeBtn = qs('timelineFreezeBtn');
  91. const modeButtons = Array.from(document.querySelectorAll('.mode-btn'));
  92. const railTabs = Array.from(document.querySelectorAll('.rail-tab'));
  93. const tabPanels = Array.from(document.querySelectorAll('.tab-panel'));
  94. const presetButtons = Array.from(document.querySelectorAll('.preset-btn'));
  95. const liveListenBtn = qs('liveListenBtn');
  96. const listenSecondsInput = qs('listenSeconds');
  97. const listenModeSelect = qs('listenMode');
  98. let latest = null;
  99. let currentConfig = null;
  100. let liveAudio = null;
  101. let stats = { buffer_samples: 0, dropped: 0, resets: 0, last_sample_ago_ms: -1 };
  102. let gpuInfo = { available: false, active: false, error: '' };
  103. let zoom = 1;
  104. let pan = 0;
  105. let followLive = true;
  106. let maxHold = false;
  107. let avgAlpha = 0;
  108. let avgSpectrum = null;
  109. let maxSpectrum = null;
  110. let lastFFTSize = null;
  111. let processedSpectrum = null;
  112. let processedSpectrumSource = null;
  113. let processingDirty = true;
  114. let pendingConfigUpdate = null;
  115. let pendingSettingsUpdate = null;
  116. let configTimer = null;
  117. let settingsTimer = null;
  118. let isSyncingConfig = false;
  119. let isDraggingSpectrum = false;
  120. let dragStartX = 0;
  121. let dragStartPan = 0;
  122. let navDrag = false;
  123. let timelineFrozen = false;
  124. let renderFrames = 0;
  125. let renderFps = 0;
  126. let lastFpsTs = performance.now();
  127. let wsReconnectTimer = null;
  128. let eventsFetchInFlight = false;
  129. const events = [];
  130. const eventsById = new Map();
  131. let lastEventEndMs = 0;
  132. let selectedEventId = null;
  133. let timelineRects = [];
  134. let liveSignalRects = [];
  135. let recordings = [];
  136. let recordingsFetchInFlight = false;
  137. const GAIN_MAX = 60;
  138. const timelineWindowMs = 5 * 60 * 1000;
  139. function setConfigStatus(text) {
  140. configStatusEl.textContent = text;
  141. }
  142. function setWsBadge(text, kind = 'neutral') {
  143. wsBadge.textContent = text;
  144. wsBadge.style.borderColor = kind === 'ok'
  145. ? 'rgba(124, 251, 131, 0.35)'
  146. : kind === 'bad'
  147. ? 'rgba(255, 107, 129, 0.35)'
  148. : 'rgba(112, 150, 207, 0.18)';
  149. }
  150. function toMHz(hz) { return hz / 1e6; }
  151. function fromMHz(mhz) { return mhz * 1e6; }
  152. function fmtMHz(hz, digits = 3) { return `${(hz / 1e6).toFixed(digits)} MHz`; }
  153. function fmtKHz(hz, digits = 2) { return `${(hz / 1e3).toFixed(digits)} kHz`; }
  154. function fmtHz(hz) {
  155. if (hz >= 1e6) return `${(hz / 1e6).toFixed(3)} MHz`;
  156. if (hz >= 1e3) return `${(hz / 1e3).toFixed(2)} kHz`;
  157. return `${hz.toFixed(0)} Hz`;
  158. }
  159. function fmtMs(ms) {
  160. if (ms < 1000) return `${Math.max(0, Math.round(ms))} ms`;
  161. return `${(ms / 1000).toFixed(2)} s`;
  162. }
  163. function colorMap(v) {
  164. const x = Math.max(0, Math.min(1, v));
  165. const r = Math.floor(255 * Math.pow(x, 0.55));
  166. const g = Math.floor(255 * Math.pow(x, 1.08));
  167. const b = Math.floor(220 * Math.pow(1 - x, 1.15));
  168. return [r, g, b];
  169. }
  170. function snrColor(snr) {
  171. const norm = Math.max(0, Math.min(1, (snr + 5) / 35));
  172. const [r, g, b] = colorMap(norm);
  173. return `rgb(${r}, ${g}, ${b})`;
  174. }
  175. function binForFreq(freq, centerHz, sampleRate, n) {
  176. return Math.floor((freq - (centerHz - sampleRate / 2)) / (sampleRate / n));
  177. }
  178. function maxInBinRange(spectrum, b0, b1) {
  179. const n = spectrum.length;
  180. let start = Math.max(0, Math.min(n - 1, b0));
  181. let end = Math.max(0, Math.min(n - 1, b1));
  182. if (end < start) [start, end] = [end, start];
  183. let max = -1e9;
  184. for (let i = start; i <= end; i++) {
  185. if (spectrum[i] > max) max = spectrum[i];
  186. }
  187. return max;
  188. }
  189. function markSpectrumDirty() {
  190. processingDirty = true;
  191. }
  192. function processSpectrum(spectrum) {
  193. if (!spectrum) return spectrum;
  194. let base = spectrum;
  195. if (avgAlpha > 0) {
  196. if (!avgSpectrum || avgSpectrum.length !== spectrum.length) {
  197. avgSpectrum = spectrum.slice();
  198. } else {
  199. for (let i = 0; i < spectrum.length; i++) {
  200. avgSpectrum[i] = avgAlpha * spectrum[i] + (1 - avgAlpha) * avgSpectrum[i];
  201. }
  202. }
  203. base = avgSpectrum;
  204. }
  205. if (maxHold) {
  206. if (!maxSpectrum || maxSpectrum.length !== base.length) {
  207. maxSpectrum = base.slice();
  208. } else {
  209. for (let i = 0; i < base.length; i++) {
  210. if (base[i] > maxSpectrum[i]) maxSpectrum[i] = base[i];
  211. }
  212. }
  213. base = maxSpectrum;
  214. }
  215. return base;
  216. }
  217. function resetProcessingCaches() {
  218. avgSpectrum = null;
  219. maxSpectrum = null;
  220. processedSpectrum = null;
  221. processedSpectrumSource = null;
  222. processingDirty = true;
  223. }
  224. function getProcessedSpectrum() {
  225. if (!latest?.spectrum_db) return null;
  226. if (!processingDirty && processedSpectrumSource === latest.spectrum_db) return processedSpectrum;
  227. processedSpectrum = processSpectrum(latest.spectrum_db);
  228. processedSpectrumSource = latest.spectrum_db;
  229. processingDirty = false;
  230. return processedSpectrum;
  231. }
  232. function resizeCanvas(canvas) {
  233. if (!canvas) return;
  234. const rect = canvas.getBoundingClientRect();
  235. const dpr = window.devicePixelRatio || 1;
  236. const width = Math.max(1, Math.floor(rect.width * dpr));
  237. const height = Math.max(1, Math.floor(rect.height * dpr));
  238. if (canvas.width !== width || canvas.height !== height) {
  239. canvas.width = width;
  240. canvas.height = height;
  241. }
  242. }
  243. function resizeAll() {
  244. [navCanvas, spectrumCanvas, waterfallCanvas, occupancyCanvas, timelineCanvas, detailSpectrogram].forEach(resizeCanvas);
  245. }
  246. window.addEventListener('resize', resizeAll);
  247. resizeAll();
  248. function setSelectValueOrNearest(selectEl, numericValue) {
  249. if (!selectEl) return;
  250. const options = Array.from(selectEl.options || []);
  251. const exact = options.find(o => Number.parseFloat(o.value) === numericValue);
  252. if (exact) {
  253. selectEl.value = exact.value;
  254. return;
  255. }
  256. let best = options[0];
  257. let bestDist = Infinity;
  258. for (const opt of options) {
  259. const dist = Math.abs(Number.parseFloat(opt.value) - numericValue);
  260. if (dist < bestDist) {
  261. best = opt;
  262. bestDist = dist;
  263. }
  264. }
  265. if (best) selectEl.value = best.value;
  266. }
  267. function applyConfigToUI(cfg) {
  268. if (!cfg) return;
  269. isSyncingConfig = true;
  270. centerInput.value = toMHz(cfg.center_hz).toFixed(6);
  271. setSelectValueOrNearest(sampleRateSelect, cfg.sample_rate / 1e6);
  272. setSelectValueOrNearest(bwSelect, cfg.tuner_bw_khz || 1536);
  273. setSelectValueOrNearest(fftSelect, cfg.fft_size);
  274. if (lastFFTSize !== cfg.fft_size) {
  275. resetProcessingCaches();
  276. lastFFTSize = cfg.fft_size;
  277. }
  278. const uiGain = Math.max(0, Math.min(GAIN_MAX, GAIN_MAX - cfg.gain_db));
  279. gainRange.value = uiGain;
  280. gainInput.value = uiGain;
  281. thresholdRange.value = cfg.detector.threshold_db;
  282. thresholdInput.value = cfg.detector.threshold_db;
  283. if (cfarToggle) cfarToggle.checked = !!cfg.detector.cfar_enabled;
  284. if (cfarGuardInput) cfarGuardInput.value = cfg.detector.cfar_guard_cells ?? 2;
  285. if (cfarTrainInput) cfarTrainInput.value = cfg.detector.cfar_train_cells ?? 16;
  286. if (cfarRankInput) cfarRankInput.value = cfg.detector.cfar_rank ?? 24;
  287. if (cfarScaleInput) cfarScaleInput.value = cfg.detector.cfar_scale_db ?? 6;
  288. if (minDurationInput) minDurationInput.value = cfg.detector.min_duration_ms;
  289. if (holdInput) holdInput.value = cfg.detector.hold_ms;
  290. if (emaAlphaInput) emaAlphaInput.value = cfg.detector.ema_alpha ?? 0.2;
  291. if (hysteresisInput) hysteresisInput.value = cfg.detector.hysteresis_db ?? 3;
  292. if (stableFramesInput) stableFramesInput.value = cfg.detector.min_stable_frames ?? 3;
  293. if (gapToleranceInput) gapToleranceInput.value = cfg.detector.gap_tolerance_ms ?? cfg.detector.hold_ms;
  294. agcToggle.checked = !!cfg.agc;
  295. dcToggle.checked = !!cfg.dc_block;
  296. iqToggle.checked = !!cfg.iq_balance;
  297. gpuToggle.checked = !!cfg.use_gpu_fft;
  298. maxHoldToggle.checked = maxHold;
  299. if (cfg.recorder) {
  300. if (recEnableToggle) recEnableToggle.checked = !!cfg.recorder.enabled;
  301. if (recIQToggle) recIQToggle.checked = !!cfg.recorder.record_iq;
  302. if (recAudioToggle) recAudioToggle.checked = !!cfg.recorder.record_audio;
  303. if (recDemodToggle) recDemodToggle.checked = !!cfg.recorder.auto_demod;
  304. if (recDecodeToggle) recDecodeToggle.checked = !!cfg.recorder.auto_decode;
  305. if (recMinSNR) recMinSNR.value = cfg.recorder.min_snr_db ?? 10;
  306. if (recMaxDisk) recMaxDisk.value = cfg.recorder.max_disk_mb ?? 0;
  307. if (recClassFilter) recClassFilter.value = (cfg.recorder.class_filter || []).join(', ');
  308. }
  309. spanInput.value = (cfg.sample_rate / zoom / 1e6).toFixed(3);
  310. isSyncingConfig = false;
  311. }
  312. async function loadConfig() {
  313. try {
  314. const res = await fetch('/api/config');
  315. if (!res.ok) throw new Error('config');
  316. currentConfig = await res.json();
  317. applyConfigToUI(currentConfig);
  318. setConfigStatus('Config synced');
  319. } catch {
  320. setConfigStatus('Config offline');
  321. }
  322. }
  323. async function loadSignals() {
  324. try {
  325. const res = await fetch('/api/signals');
  326. if (!res.ok) return;
  327. const sigs = await res.json();
  328. if (Array.isArray(sigs)) {
  329. latest = latest || {};
  330. latest.signals = sigs;
  331. renderLists();
  332. }
  333. } catch {}
  334. }
  335. async function loadDecoders() {
  336. if (!decodeModeSelect) return;
  337. try {
  338. const res = await fetch('/api/decoders');
  339. if (!res.ok) return;
  340. const list = await res.json();
  341. if (!Array.isArray(list)) return;
  342. const current = decodeModeSelect.value;
  343. decodeModeSelect.innerHTML = '';
  344. list.forEach((mode) => {
  345. const opt = document.createElement('option');
  346. opt.value = mode;
  347. opt.textContent = mode;
  348. decodeModeSelect.appendChild(opt);
  349. });
  350. if (current) decodeModeSelect.value = current;
  351. } catch {}
  352. }
  353. async function loadStats() {
  354. try {
  355. const res = await fetch('/api/stats');
  356. if (!res.ok) return;
  357. stats = await res.json();
  358. } catch {}
  359. }
  360. async function loadGPU() {
  361. try {
  362. const res = await fetch('/api/gpu');
  363. if (!res.ok) return;
  364. gpuInfo = await res.json();
  365. } catch {}
  366. }
  367. function queueConfigUpdate(partial) {
  368. if (isSyncingConfig) return;
  369. pendingConfigUpdate = { ...(pendingConfigUpdate || {}), ...partial };
  370. setConfigStatus('Applying…');
  371. clearTimeout(configTimer);
  372. configTimer = setTimeout(sendConfigUpdate, 180);
  373. }
  374. function queueSettingsUpdate(partial) {
  375. if (isSyncingConfig) return;
  376. pendingSettingsUpdate = { ...(pendingSettingsUpdate || {}), ...partial };
  377. setConfigStatus('Applying…');
  378. clearTimeout(settingsTimer);
  379. settingsTimer = setTimeout(sendSettingsUpdate, 120);
  380. }
  381. async function sendConfigUpdate() {
  382. if (!pendingConfigUpdate) return;
  383. const payload = pendingConfigUpdate;
  384. pendingConfigUpdate = null;
  385. try {
  386. const res = await fetch('/api/config', {
  387. method: 'POST',
  388. headers: { 'Content-Type': 'application/json' },
  389. body: JSON.stringify(payload),
  390. });
  391. if (!res.ok) throw new Error('apply');
  392. currentConfig = await res.json();
  393. applyConfigToUI(currentConfig);
  394. setConfigStatus('Config applied');
  395. } catch {
  396. setConfigStatus('Config apply failed');
  397. }
  398. }
  399. async function sendSettingsUpdate() {
  400. if (!pendingSettingsUpdate) return;
  401. const payload = pendingSettingsUpdate;
  402. pendingSettingsUpdate = null;
  403. try {
  404. const res = await fetch('/api/sdr/settings', {
  405. method: 'POST',
  406. headers: { 'Content-Type': 'application/json' },
  407. body: JSON.stringify(payload),
  408. });
  409. if (!res.ok) throw new Error('apply');
  410. currentConfig = await res.json();
  411. applyConfigToUI(currentConfig);
  412. setConfigStatus('Settings applied');
  413. } catch {
  414. setConfigStatus('Settings apply failed');
  415. }
  416. }
  417. function updateHeroMetrics() {
  418. if (!latest) return;
  419. const span = latest.sample_rate / zoom;
  420. const binHz = latest.sample_rate / Math.max(1, latest.spectrum_db?.length || latest.fft_size || 1);
  421. metricCenter.textContent = fmtMHz(latest.center_hz, 6);
  422. metricSpan.textContent = fmtHz(span);
  423. metricRes.textContent = `${binHz.toFixed(1)} Hz/bin`;
  424. metricSignals.textContent = String(latest.signals?.length || 0);
  425. metricGpu.textContent = gpuInfo.active ? 'ON' : (gpuInfo.available ? 'OFF' : 'N/A');
  426. metricSource.textContent = stats.last_sample_ago_ms >= 0 ? `${stats.last_sample_ago_ms} ms` : 'n/a';
  427. const gpuText = gpuInfo.active ? 'GPU active' : (gpuInfo.available ? 'GPU ready' : 'GPU n/a');
  428. metaLine.textContent = `${fmtMHz(latest.center_hz, 3)} · ${fmtHz(span)} span · ${gpuText}`;
  429. heroSubtitle.textContent = `${latest.signals?.length || 0} live signals · ${events.length} recent events tracked`;
  430. healthBuffer.textContent = String(stats.buffer_samples ?? '-');
  431. healthDropped.textContent = String(stats.dropped ?? '-');
  432. healthResets.textContent = String(stats.resets ?? '-');
  433. healthAge.textContent = stats.last_sample_ago_ms >= 0 ? `${stats.last_sample_ago_ms} ms` : 'n/a';
  434. healthGpu.textContent = gpuInfo.error ? `${gpuInfo.active ? 'ON' : 'OFF'} · ${gpuInfo.error}` : (gpuInfo.active ? 'ON' : (gpuInfo.available ? 'Ready' : 'N/A'));
  435. healthFps.textContent = `${renderFps.toFixed(0)} fps`;
  436. }
  437. function renderBandNavigator() {
  438. if (!latest) return;
  439. const ctx = navCanvas.getContext('2d');
  440. const w = navCanvas.width;
  441. const h = navCanvas.height;
  442. ctx.clearRect(0, 0, w, h);
  443. const display = getProcessedSpectrum();
  444. if (!display) return;
  445. const minDb = -120;
  446. const maxDb = 0;
  447. ctx.fillStyle = '#071018';
  448. ctx.fillRect(0, 0, w, h);
  449. ctx.strokeStyle = 'rgba(102, 169, 255, 0.25)';
  450. ctx.lineWidth = 1;
  451. ctx.beginPath();
  452. for (let x = 0; x < w; x++) {
  453. const idx = Math.min(display.length - 1, Math.floor((x / w) * display.length));
  454. const v = display[idx];
  455. const y = h - ((v - minDb) / (maxDb - minDb)) * (h - 10) - 5;
  456. if (x === 0) ctx.moveTo(x, y);
  457. else ctx.lineTo(x, y);
  458. }
  459. ctx.stroke();
  460. const span = latest.sample_rate / zoom;
  461. const fullStart = latest.center_hz - latest.sample_rate / 2;
  462. const viewStart = latest.center_hz - span / 2 + pan * span;
  463. const viewEnd = latest.center_hz + span / 2 + pan * span;
  464. const x1 = ((viewStart - fullStart) / latest.sample_rate) * w;
  465. const x2 = ((viewEnd - fullStart) / latest.sample_rate) * w;
  466. ctx.fillStyle = 'rgba(102, 240, 209, 0.10)';
  467. ctx.strokeStyle = 'rgba(102, 240, 209, 0.85)';
  468. ctx.lineWidth = 2;
  469. ctx.fillRect(x1, 4, Math.max(2, x2 - x1), h - 8);
  470. ctx.strokeRect(x1, 4, Math.max(2, x2 - x1), h - 8);
  471. }
  472. function drawSpectrumGrid(ctx, w, h, startHz, endHz) {
  473. ctx.strokeStyle = 'rgba(86, 109, 148, 0.18)';
  474. ctx.lineWidth = 1;
  475. for (let i = 1; i < 6; i++) {
  476. const y = (h / 6) * i;
  477. ctx.beginPath();
  478. ctx.moveTo(0, y);
  479. ctx.lineTo(w, y);
  480. ctx.stroke();
  481. }
  482. for (let i = 1; i < 8; i++) {
  483. const x = (w / 8) * i;
  484. ctx.beginPath();
  485. ctx.moveTo(x, 0);
  486. ctx.lineTo(x, h);
  487. ctx.stroke();
  488. const hz = startHz + (i / 8) * (endHz - startHz);
  489. ctx.fillStyle = 'rgba(173, 192, 220, 0.72)';
  490. ctx.font = `${Math.max(11, Math.floor(h / 26))}px Inter, sans-serif`;
  491. ctx.fillText((hz / 1e6).toFixed(3), x + 4, h - 8);
  492. }
  493. }
  494. function drawCfarEdgeOverlay(ctx, w, h, startHz, endHz) {
  495. if (!latest || !currentConfig?.detector?.cfar_enabled) return;
  496. const guard = currentConfig.detector.cfar_guard_cells ?? 0;
  497. const train = currentConfig.detector.cfar_train_cells ?? 0;
  498. const bins = guard + train;
  499. if (bins <= 0) return;
  500. const fftSize = latest.fft_size || latest.spectrum_db?.length;
  501. if (!fftSize || fftSize <= 0) return;
  502. const binHz = latest.sample_rate / fftSize;
  503. const edgeHz = bins * binHz;
  504. const bandStart = latest.center_hz - latest.sample_rate / 2;
  505. const bandEnd = latest.center_hz + latest.sample_rate / 2;
  506. const leftEdgeEnd = bandStart + edgeHz;
  507. const rightEdgeStart = bandEnd - edgeHz;
  508. ctx.fillStyle = 'rgba(255, 204, 102, 0.08)';
  509. ctx.strokeStyle = 'rgba(255, 204, 102, 0.18)';
  510. ctx.lineWidth = 1;
  511. const leftStart = Math.max(startHz, bandStart);
  512. const leftEnd = Math.min(endHz, leftEdgeEnd);
  513. if (leftEnd > leftStart) {
  514. const x1 = ((leftStart - startHz) / (endHz - startHz)) * w;
  515. const x2 = ((leftEnd - startHz) / (endHz - startHz)) * w;
  516. ctx.fillRect(x1, 0, Math.max(2, x2 - x1), h);
  517. ctx.strokeRect(x1, 0, Math.max(2, x2 - x1), h);
  518. }
  519. const rightStart = Math.max(startHz, rightEdgeStart);
  520. const rightEnd = Math.min(endHz, bandEnd);
  521. if (rightEnd > rightStart) {
  522. const x1 = ((rightStart - startHz) / (endHz - startHz)) * w;
  523. const x2 = ((rightEnd - startHz) / (endHz - startHz)) * w;
  524. ctx.fillRect(x1, 0, Math.max(2, x2 - x1), h);
  525. ctx.strokeRect(x1, 0, Math.max(2, x2 - x1), h);
  526. }
  527. }
  528. function renderSpectrum() {
  529. if (!latest) return;
  530. const ctx = spectrumCanvas.getContext('2d');
  531. const w = spectrumCanvas.width;
  532. const h = spectrumCanvas.height;
  533. ctx.clearRect(0, 0, w, h);
  534. const display = getProcessedSpectrum();
  535. if (!display) return;
  536. const n = display.length;
  537. const span = latest.sample_rate / zoom;
  538. const startHz = latest.center_hz - span / 2 + pan * span;
  539. const endHz = latest.center_hz + span / 2 + pan * span;
  540. spanInput.value = (span / 1e6).toFixed(3);
  541. drawSpectrumGrid(ctx, w, h, startHz, endHz);
  542. drawCfarEdgeOverlay(ctx, w, h, startHz, endHz);
  543. const minDb = -120;
  544. const maxDb = 0;
  545. const fill = ctx.createLinearGradient(0, 0, 0, h);
  546. fill.addColorStop(0, 'rgba(102, 240, 209, 0.20)');
  547. fill.addColorStop(1, 'rgba(102, 240, 209, 0.02)');
  548. ctx.beginPath();
  549. for (let x = 0; x < w; x++) {
  550. const f1 = startHz + (x / w) * (endHz - startHz);
  551. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  552. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  553. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  554. const v = maxInBinRange(display, b0, b1);
  555. const y = h - ((v - minDb) / (maxDb - minDb)) * (h - 18) - 6;
  556. if (x === 0) ctx.moveTo(x, y);
  557. else ctx.lineTo(x, y);
  558. }
  559. ctx.lineTo(w, h);
  560. ctx.lineTo(0, h);
  561. ctx.closePath();
  562. ctx.fillStyle = fill;
  563. ctx.fill();
  564. ctx.strokeStyle = '#66f0d1';
  565. ctx.lineWidth = 2;
  566. ctx.beginPath();
  567. liveSignalRects = [];
  568. for (let x = 0; x < w; x++) {
  569. const f1 = startHz + (x / w) * (endHz - startHz);
  570. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  571. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  572. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  573. const v = maxInBinRange(display, b0, b1);
  574. const y = h - ((v - minDb) / (maxDb - minDb)) * (h - 18) - 6;
  575. if (x === 0) ctx.moveTo(x, y);
  576. else ctx.lineTo(x, y);
  577. }
  578. ctx.stroke();
  579. if (Array.isArray(latest.signals)) {
  580. latest.signals.forEach((s, index) => {
  581. const left = s.center_hz - s.bw_hz / 2;
  582. const right = s.center_hz + s.bw_hz / 2;
  583. if (right < startHz || left > endHz) return;
  584. const x1 = ((left - startHz) / (endHz - startHz)) * w;
  585. const x2 = ((right - startHz) / (endHz - startHz)) * w;
  586. const boxW = Math.max(2, x2 - x1);
  587. const color = snrColor(s.snr_db || 0);
  588. ctx.fillStyle = color.replace('rgb', 'rgba').replace(')', ', 0.14)');
  589. ctx.strokeStyle = color;
  590. ctx.lineWidth = 1.5;
  591. ctx.fillRect(x1, 10, boxW, h - 28);
  592. ctx.strokeRect(x1, 10, boxW, h - 28);
  593. ctx.fillStyle = color;
  594. ctx.font = '12px Inter, sans-serif';
  595. const label = `${(s.center_hz / 1e6).toFixed(4)} MHz`;
  596. ctx.fillText(label, Math.max(4, x1 + 4), 24 + (index % 3) * 16);
  597. liveSignalRects.push({
  598. x: x1,
  599. y: 10,
  600. w: boxW,
  601. h: h - 28,
  602. signal: s,
  603. });
  604. });
  605. }
  606. }
  607. function renderWaterfall() {
  608. if (!latest) return;
  609. const ctx = waterfallCanvas.getContext('2d');
  610. const w = waterfallCanvas.width;
  611. const h = waterfallCanvas.height;
  612. const prev = ctx.getImageData(0, 0, w, h - 1);
  613. ctx.putImageData(prev, 0, 1);
  614. const display = getProcessedSpectrum();
  615. if (!display) return;
  616. const n = display.length;
  617. const span = latest.sample_rate / zoom;
  618. const startHz = latest.center_hz - span / 2 + pan * span;
  619. const endHz = latest.center_hz + span / 2 + pan * span;
  620. const minDb = -120;
  621. const maxDb = 0;
  622. const row = ctx.createImageData(w, 1);
  623. for (let x = 0; x < w; x++) {
  624. const f1 = startHz + (x / w) * (endHz - startHz);
  625. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  626. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  627. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  628. const v = maxInBinRange(display, b0, b1);
  629. const norm = Math.max(0, Math.min(1, (v - minDb) / (maxDb - minDb)));
  630. const [r, g, b] = colorMap(norm);
  631. row.data[x * 4] = r;
  632. row.data[x * 4 + 1] = g;
  633. row.data[x * 4 + 2] = b;
  634. row.data[x * 4 + 3] = 255;
  635. }
  636. ctx.putImageData(row, 0, 0);
  637. drawCfarEdgeOverlay(ctx, w, h, startHz, endHz);
  638. }
  639. function renderOccupancy() {
  640. const ctx = occupancyCanvas.getContext('2d');
  641. const w = occupancyCanvas.width;
  642. const h = occupancyCanvas.height;
  643. ctx.clearRect(0, 0, w, h);
  644. ctx.fillStyle = '#071018';
  645. ctx.fillRect(0, 0, w, h);
  646. if (!latest || events.length === 0) return;
  647. const bins = new Array(Math.max(32, Math.min(160, Math.floor(w / 8)))).fill(0);
  648. const bandStart = latest.center_hz - latest.sample_rate / 2;
  649. const bandEnd = latest.center_hz + latest.sample_rate / 2;
  650. const now = Date.now();
  651. const windowStart = now - timelineWindowMs;
  652. for (const ev of events) {
  653. if (ev.end_ms < windowStart || ev.start_ms > now) continue;
  654. const left = ev.center_hz - ev.bandwidth_hz / 2;
  655. const right = ev.center_hz + ev.bandwidth_hz / 2;
  656. const normL = Math.max(0, Math.min(1, (left - bandStart) / (bandEnd - bandStart)));
  657. const normR = Math.max(0, Math.min(1, (right - bandStart) / (bandEnd - bandStart)));
  658. let b0 = Math.floor(normL * bins.length);
  659. let b1 = Math.floor(normR * bins.length);
  660. if (b1 < b0) [b0, b1] = [b1, b0];
  661. for (let i = Math.max(0, b0); i <= Math.min(bins.length - 1, b1); i++) {
  662. bins[i] += Math.max(0.3, (ev.snr_db || 0) / 12 + 1);
  663. }
  664. }
  665. const maxBin = Math.max(1, ...bins);
  666. bins.forEach((v, i) => {
  667. const norm = v / maxBin;
  668. const [r, g, b] = colorMap(norm);
  669. ctx.fillStyle = `rgb(${r}, ${g}, ${b})`;
  670. const x = (i / bins.length) * w;
  671. const bw = Math.ceil(w / bins.length) + 1;
  672. ctx.fillRect(x, 0, bw, h);
  673. });
  674. }
  675. function renderTimeline() {
  676. const ctx = timelineCanvas.getContext('2d');
  677. const w = timelineCanvas.width;
  678. const h = timelineCanvas.height;
  679. ctx.clearRect(0, 0, w, h);
  680. ctx.fillStyle = '#071018';
  681. ctx.fillRect(0, 0, w, h);
  682. if (events.length === 0) {
  683. timelineRangeEl.textContent = 'No events yet';
  684. return;
  685. }
  686. const endMs = Date.now();
  687. const startMs = endMs - timelineWindowMs;
  688. timelineRangeEl.textContent = `${new Date(startMs).toLocaleTimeString()} - ${new Date(endMs).toLocaleTimeString()}`;
  689. let minHz = Infinity;
  690. let maxHz = -Infinity;
  691. if (latest) {
  692. minHz = latest.center_hz - latest.sample_rate / 2;
  693. maxHz = latest.center_hz + latest.sample_rate / 2;
  694. } else {
  695. for (const ev of events) {
  696. minHz = Math.min(minHz, ev.center_hz - ev.bandwidth_hz / 2);
  697. maxHz = Math.max(maxHz, ev.center_hz + ev.bandwidth_hz / 2);
  698. }
  699. }
  700. if (!isFinite(minHz) || !isFinite(maxHz) || minHz === maxHz) {
  701. minHz = 0;
  702. maxHz = 1;
  703. }
  704. ctx.strokeStyle = 'rgba(86, 109, 148, 0.18)';
  705. ctx.lineWidth = 1;
  706. for (let i = 1; i < 6; i++) {
  707. const y = (h / 6) * i;
  708. ctx.beginPath();
  709. ctx.moveTo(0, y);
  710. ctx.lineTo(w, y);
  711. ctx.stroke();
  712. }
  713. for (let i = 1; i < 8; i++) {
  714. const x = (w / 8) * i;
  715. ctx.beginPath();
  716. ctx.moveTo(x, 0);
  717. ctx.lineTo(x, h);
  718. ctx.stroke();
  719. }
  720. timelineRects = [];
  721. for (const ev of events) {
  722. if (ev.end_ms < startMs || ev.start_ms > endMs) continue;
  723. const x1 = ((Math.max(ev.start_ms, startMs) - startMs) / (endMs - startMs)) * w;
  724. const x2 = ((Math.min(ev.end_ms, endMs) - startMs) / (endMs - startMs)) * w;
  725. const topHz = ev.center_hz + ev.bandwidth_hz / 2;
  726. const bottomHz = ev.center_hz - ev.bandwidth_hz / 2;
  727. const y1 = ((maxHz - topHz) / (maxHz - minHz)) * h;
  728. const y2 = ((maxHz - bottomHz) / (maxHz - minHz)) * h;
  729. const rect = { x: x1, y: y1, w: Math.max(2, x2 - x1), h: Math.max(3, y2 - y1), id: ev.id };
  730. timelineRects.push(rect);
  731. ctx.fillStyle = snrColor(ev.snr_db || 0).replace('rgb', 'rgba').replace(')', ', 0.85)');
  732. ctx.fillRect(rect.x, rect.y, rect.w, rect.h);
  733. }
  734. if (selectedEventId) {
  735. const hit = timelineRects.find(r => r.id === selectedEventId);
  736. if (hit) {
  737. ctx.strokeStyle = '#ffffff';
  738. ctx.lineWidth = 2;
  739. ctx.strokeRect(hit.x - 1, hit.y - 1, hit.w + 2, hit.h + 2);
  740. }
  741. }
  742. }
  743. function renderDetailSpectrogram() {
  744. const ev = eventsById.get(selectedEventId);
  745. const ctx = detailSpectrogram.getContext('2d');
  746. const w = detailSpectrogram.width;
  747. const h = detailSpectrogram.height;
  748. ctx.clearRect(0, 0, w, h);
  749. ctx.fillStyle = '#071018';
  750. ctx.fillRect(0, 0, w, h);
  751. if (!latest || !ev) return;
  752. const display = getProcessedSpectrum();
  753. if (!display) return;
  754. const n = display.length;
  755. const localSpan = Math.min(latest.sample_rate, Math.max(ev.bandwidth_hz * 4, latest.sample_rate / 10));
  756. const startHz = ev.center_hz - localSpan / 2;
  757. const endHz = ev.center_hz + localSpan / 2;
  758. const minDb = -120;
  759. const maxDb = 0;
  760. const row = ctx.createImageData(w, 1);
  761. for (let x = 0; x < w; x++) {
  762. const f1 = startHz + (x / w) * (endHz - startHz);
  763. const f2 = startHz + ((x + 1) / w) * (endHz - startHz);
  764. const b0 = binForFreq(f1, latest.center_hz, latest.sample_rate, n);
  765. const b1 = binForFreq(f2, latest.center_hz, latest.sample_rate, n);
  766. const v = maxInBinRange(display, b0, b1);
  767. const norm = Math.max(0, Math.min(1, (v - minDb) / (maxDb - minDb)));
  768. const [r, g, b] = colorMap(norm);
  769. row.data[x * 4] = r;
  770. row.data[x * 4 + 1] = g;
  771. row.data[x * 4 + 2] = b;
  772. row.data[x * 4 + 3] = 255;
  773. }
  774. for (let y = 0; y < h; y++) ctx.putImageData(row, 0, y);
  775. const centerX = w / 2;
  776. ctx.strokeStyle = 'rgba(255,255,255,0.65)';
  777. ctx.lineWidth = 1;
  778. ctx.beginPath();
  779. ctx.moveTo(centerX, 0);
  780. ctx.lineTo(centerX, h);
  781. ctx.stroke();
  782. }
  783. function renderLists() {
  784. const signals = Array.isArray(latest?.signals) ? [...latest.signals] : [];
  785. signals.sort((a, b) => (b.snr_db || 0) - (a.snr_db || 0));
  786. signalCountBadge.textContent = `${signals.length} live`;
  787. metricSignals.textContent = String(signals.length);
  788. if (signals.length === 0) {
  789. signalList.innerHTML = '<div class="empty-state">No live signals yet.</div>';
  790. } else {
  791. signalList.innerHTML = signals.slice(0, 24).map((s) => `
  792. <button class="list-item signal-item" type="button" data-center="${s.center_hz}" data-bw="${s.bw_hz || 0}" data-class="${s.class?.mod_type || ''}">
  793. <div class="item-top">
  794. <span class="item-title">${fmtMHz(s.center_hz, 6)}</span>
  795. <span class="item-badge" style="color:${snrColor(s.snr_db || 0)}">${(s.snr_db || 0).toFixed(1)} dB</span>
  796. </div>
  797. <div class="item-bottom">
  798. <span class="item-meta">BW ${fmtKHz(s.bw_hz || 0)}</span>
  799. <span class="item-meta">${s.class?.mod_type || 'live carrier'}</span>
  800. </div>
  801. </button>
  802. `).join('');
  803. }
  804. const recent = [...events].sort((a, b) => b.end_ms - a.end_ms);
  805. eventCountBadge.textContent = `${recent.length} stored`;
  806. if (recent.length === 0) {
  807. eventList.innerHTML = '<div class="empty-state">No events yet.</div>';
  808. } else {
  809. eventList.innerHTML = recent.slice(0, 40).map((ev) => `
  810. <button class="list-item event-item ${selectedEventId === ev.id ? 'active' : ''}" type="button" data-event-id="${ev.id}">
  811. <div class="item-top">
  812. <span class="item-title">${fmtMHz(ev.center_hz, 6)}</span>
  813. <span class="item-badge" style="color:${snrColor(ev.snr_db || 0)}">${(ev.snr_db || 0).toFixed(1)} dB</span>
  814. </div>
  815. <div class="item-bottom">
  816. <span class="item-meta">${fmtKHz(ev.bandwidth_hz || 0)} · ${fmtMs(ev.duration_ms || 0)}</span>
  817. <span class="item-meta">${new Date(ev.end_ms).toLocaleTimeString()}</span>
  818. </div>
  819. </button>
  820. `).join('');
  821. }
  822. if (recordingList && recordingCountBadge) {
  823. recordingCountBadge.textContent = `${recordings.length}`;
  824. if (recordings.length === 0) {
  825. recordingList.innerHTML = '<div class="empty-state">No recordings yet.</div>';
  826. } else {
  827. recordingList.innerHTML = recordings.slice(0, 50).map((rec) => `
  828. <button class="list-item recording-item" type="button" data-id="${rec.id}">
  829. <div class="item-top">
  830. <span class="item-title">${new Date(rec.start).toLocaleString()}</span>
  831. <span class="item-badge">${fmtMHz(rec.center_hz || 0, 6)}</span>
  832. </div>
  833. <div class="item-bottom">
  834. <span class="item-meta">${rec.id}</span>
  835. <span class="item-meta">recording</span>
  836. </div>
  837. </button>
  838. `).join('');
  839. }
  840. }
  841. }
  842. function normalizeEvent(ev) {
  843. const startMs = new Date(ev.start).getTime();
  844. const endMs = new Date(ev.end).getTime();
  845. return {
  846. ...ev,
  847. start_ms: startMs,
  848. end_ms: endMs,
  849. duration_ms: Math.max(0, endMs - startMs),
  850. };
  851. }
  852. function upsertEvents(list, replace = false) {
  853. if (replace) {
  854. events.length = 0;
  855. eventsById.clear();
  856. }
  857. for (const raw of list) {
  858. if (!raw || !raw.id || eventsById.has(raw.id)) continue;
  859. const ev = normalizeEvent(raw);
  860. eventsById.set(ev.id, ev);
  861. events.push(ev);
  862. }
  863. events.sort((a, b) => a.end_ms - b.end_ms);
  864. const maxEvents = 1500;
  865. if (events.length > maxEvents) {
  866. const drop = events.length - maxEvents;
  867. for (let i = 0; i < drop; i++) eventsById.delete(events[i].id);
  868. events.splice(0, drop);
  869. }
  870. if (events.length > 0) lastEventEndMs = events[events.length - 1].end_ms;
  871. renderLists();
  872. }
  873. async function fetchEvents(initial) {
  874. if (eventsFetchInFlight || timelineFrozen) return;
  875. eventsFetchInFlight = true;
  876. try {
  877. let url = '/api/events?limit=1000';
  878. if (!initial && lastEventEndMs > 0) url = `/api/events?since=${lastEventEndMs - 1}`;
  879. const res = await fetch(url);
  880. if (!res.ok) return;
  881. const data = await res.json();
  882. if (Array.isArray(data)) upsertEvents(data, initial);
  883. } finally {
  884. eventsFetchInFlight = false;
  885. }
  886. }
  887. async function fetchRecordings() {
  888. if (recordingsFetchInFlight || !recordingList) return;
  889. recordingsFetchInFlight = true;
  890. try {
  891. const res = await fetch('/api/recordings');
  892. if (!res.ok) return;
  893. const data = await res.json();
  894. if (Array.isArray(data)) {
  895. recordings = data;
  896. renderLists();
  897. }
  898. } finally {
  899. recordingsFetchInFlight = false;
  900. }
  901. }
  902. function openDrawer(ev) {
  903. if (!ev) return;
  904. selectedEventId = ev.id;
  905. detailSubtitle.textContent = `Event ${ev.id}`;
  906. detailCenterEl.textContent = fmtMHz(ev.center_hz, 6);
  907. detailBwEl.textContent = fmtKHz(ev.bandwidth_hz || 0);
  908. detailStartEl.textContent = new Date(ev.start_ms).toLocaleString();
  909. detailEndEl.textContent = new Date(ev.end_ms).toLocaleString();
  910. detailSnrEl.textContent = `${(ev.snr_db || 0).toFixed(1)} dB`;
  911. detailDurEl.textContent = fmtMs(ev.duration_ms || 0);
  912. detailClassEl.textContent = ev.class?.mod_type || '-';
  913. if (classifierScoresEl) {
  914. const scores = ev.class?.scores;
  915. if (scores && typeof scores === 'object') {
  916. const rows = Object.entries(scores)
  917. .sort((a, b) => b[1] - a[1])
  918. .slice(0, 6)
  919. .map(([k, v]) => `${k}:${v.toFixed(2)}`)
  920. .join(' · ');
  921. classifierScoresEl.textContent = rows ? `Classifier scores: ${rows}` : 'Classifier scores: -';
  922. } else {
  923. classifierScoresEl.textContent = 'Classifier scores: -';
  924. }
  925. }
  926. if (recordingMetaEl) {
  927. recordingMetaEl.textContent = 'Recording: -';
  928. }
  929. if (recordingMetaLink) {
  930. recordingMetaLink.href = '#';
  931. recordingIQLink.href = '#';
  932. recordingAudioLink.href = '#';
  933. }
  934. drawerEl.classList.add('open');
  935. drawerEl.setAttribute('aria-hidden', 'false');
  936. renderDetailSpectrogram();
  937. renderLists();
  938. }
  939. function closeDrawer() {
  940. drawerEl.classList.remove('open');
  941. drawerEl.setAttribute('aria-hidden', 'true');
  942. selectedEventId = null;
  943. renderLists();
  944. }
  945. function fitView() {
  946. zoom = 1;
  947. pan = 0;
  948. followLive = true;
  949. }
  950. function tuneToFrequency(centerHz) {
  951. if (!Number.isFinite(centerHz)) return;
  952. followLive = true;
  953. centerInput.value = (centerHz / 1e6).toFixed(6);
  954. queueConfigUpdate({ center_hz: centerHz });
  955. }
  956. function connect() {
  957. clearTimeout(wsReconnectTimer);
  958. const proto = location.protocol === 'https:' ? 'wss' : 'ws';
  959. const ws = new WebSocket(`${proto}://${location.host}/ws`);
  960. setWsBadge('Connecting', 'neutral');
  961. ws.onopen = () => setWsBadge('Live', 'ok');
  962. ws.onmessage = (ev) => {
  963. latest = JSON.parse(ev.data);
  964. markSpectrumDirty();
  965. if (followLive) pan = 0;
  966. updateHeroMetrics();
  967. renderLists();
  968. };
  969. ws.onclose = () => {
  970. setWsBadge('Retrying', 'bad');
  971. wsReconnectTimer = setTimeout(connect, 1000);
  972. };
  973. ws.onerror = () => ws.close();
  974. }
  975. function renderLoop() {
  976. renderFrames += 1;
  977. const now = performance.now();
  978. if (now - lastFpsTs >= 1000) {
  979. renderFps = (renderFrames * 1000) / (now - lastFpsTs);
  980. renderFrames = 0;
  981. lastFpsTs = now;
  982. }
  983. if (latest) {
  984. renderBandNavigator();
  985. renderSpectrum();
  986. renderWaterfall();
  987. renderOccupancy();
  988. renderTimeline();
  989. if (drawerEl.classList.contains('open')) renderDetailSpectrogram();
  990. }
  991. updateHeroMetrics();
  992. requestAnimationFrame(renderLoop);
  993. }
  994. function handleSpectrumClick(ev) {
  995. const rect = spectrumCanvas.getBoundingClientRect();
  996. const x = (ev.clientX - rect.left) * (spectrumCanvas.width / rect.width);
  997. const y = (ev.clientY - rect.top) * (spectrumCanvas.height / rect.height);
  998. for (let i = liveSignalRects.length - 1; i >= 0; i--) {
  999. const r = liveSignalRects[i];
  1000. if (x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h) {
  1001. tuneToFrequency(r.signal.center_hz);
  1002. return;
  1003. }
  1004. }
  1005. if (!latest) return;
  1006. const span = latest.sample_rate / zoom;
  1007. const startHz = latest.center_hz - span / 2 + pan * span;
  1008. const clickedHz = startHz + (x / spectrumCanvas.width) * span;
  1009. tuneToFrequency(clickedHz);
  1010. }
  1011. function handleNavPosition(ev) {
  1012. if (!latest) return;
  1013. const rect = navCanvas.getBoundingClientRect();
  1014. const x = Math.max(0, Math.min(rect.width, ev.clientX - rect.left));
  1015. const norm = x / rect.width;
  1016. const fullStart = latest.center_hz - latest.sample_rate / 2;
  1017. const newViewCenter = fullStart + norm * latest.sample_rate;
  1018. const span = latest.sample_rate / zoom;
  1019. const desiredPan = (newViewCenter - latest.center_hz) / span;
  1020. pan = Math.max(-0.5, Math.min(0.5, desiredPan));
  1021. followLive = false;
  1022. }
  1023. function exportSelectedEvent() {
  1024. const ev = eventsById.get(selectedEventId);
  1025. if (!ev) return;
  1026. const blob = new Blob([JSON.stringify(ev, null, 2)], { type: 'application/json' });
  1027. const a = document.createElement('a');
  1028. a.href = URL.createObjectURL(blob);
  1029. a.download = `event-${ev.id}.json`;
  1030. a.click();
  1031. URL.revokeObjectURL(a.href);
  1032. }
  1033. spectrumCanvas.addEventListener('wheel', (ev) => {
  1034. ev.preventDefault();
  1035. const direction = Math.sign(ev.deltaY);
  1036. zoom = Math.max(0.25, Math.min(24, zoom * (direction > 0 ? 1.12 : 0.89)));
  1037. followLive = false;
  1038. });
  1039. spectrumCanvas.addEventListener('mousedown', (ev) => {
  1040. isDraggingSpectrum = true;
  1041. dragStartX = ev.clientX;
  1042. dragStartPan = pan;
  1043. });
  1044. window.addEventListener('mouseup', () => {
  1045. isDraggingSpectrum = false;
  1046. navDrag = false;
  1047. });
  1048. window.addEventListener('mousemove', (ev) => {
  1049. if (isDraggingSpectrum) {
  1050. const dx = ev.clientX - dragStartX;
  1051. pan = Math.max(-0.5, Math.min(0.5, dragStartPan - dx / spectrumCanvas.clientWidth));
  1052. followLive = false;
  1053. }
  1054. if (navDrag) handleNavPosition(ev);
  1055. });
  1056. spectrumCanvas.addEventListener('dblclick', fitView);
  1057. spectrumCanvas.addEventListener('click', handleSpectrumClick);
  1058. navCanvas.addEventListener('mousedown', (ev) => {
  1059. navDrag = true;
  1060. handleNavPosition(ev);
  1061. });
  1062. navCanvas.addEventListener('click', handleNavPosition);
  1063. centerInput.addEventListener('change', () => {
  1064. const mhz = parseFloat(centerInput.value);
  1065. if (Number.isFinite(mhz)) tuneToFrequency(fromMHz(mhz));
  1066. });
  1067. spanInput.addEventListener('change', () => {
  1068. const mhz = parseFloat(spanInput.value);
  1069. if (!Number.isFinite(mhz) || mhz <= 0) return;
  1070. const baseRate = currentConfig?.sample_rate || latest?.sample_rate;
  1071. if (!baseRate) return;
  1072. zoom = Math.max(0.25, Math.min(24, baseRate / fromMHz(mhz)));
  1073. followLive = false;
  1074. });
  1075. sampleRateSelect.addEventListener('change', () => {
  1076. const mhz = parseFloat(sampleRateSelect.value);
  1077. if (Number.isFinite(mhz)) queueConfigUpdate({ sample_rate: Math.round(fromMHz(mhz)) });
  1078. });
  1079. bwSelect.addEventListener('change', () => {
  1080. const bw = parseInt(bwSelect.value, 10);
  1081. if (Number.isFinite(bw)) queueConfigUpdate({ tuner_bw_khz: bw });
  1082. });
  1083. fftSelect.addEventListener('change', () => {
  1084. const size = parseInt(fftSelect.value, 10);
  1085. if (Number.isFinite(size)) queueConfigUpdate({ fft_size: size });
  1086. });
  1087. gainRange.addEventListener('input', () => {
  1088. gainInput.value = gainRange.value;
  1089. const uiVal = parseFloat(gainRange.value);
  1090. if (Number.isFinite(uiVal)) queueConfigUpdate({ gain_db: Math.max(0, Math.min(GAIN_MAX, GAIN_MAX - uiVal)) });
  1091. });
  1092. gainInput.addEventListener('change', () => {
  1093. const uiVal = parseFloat(gainInput.value);
  1094. if (Number.isFinite(uiVal)) {
  1095. gainRange.value = uiVal;
  1096. queueConfigUpdate({ gain_db: Math.max(0, Math.min(GAIN_MAX, GAIN_MAX - uiVal)) });
  1097. }
  1098. });
  1099. thresholdRange.addEventListener('input', () => {
  1100. thresholdInput.value = thresholdRange.value;
  1101. queueConfigUpdate({ detector: { threshold_db: parseFloat(thresholdRange.value) } });
  1102. });
  1103. thresholdInput.addEventListener('change', () => {
  1104. const v = parseFloat(thresholdInput.value);
  1105. if (Number.isFinite(v)) {
  1106. thresholdRange.value = v;
  1107. queueConfigUpdate({ detector: { threshold_db: v } });
  1108. }
  1109. });
  1110. if (cfarToggle) cfarToggle.addEventListener('change', () => queueConfigUpdate({ detector: { cfar_enabled: cfarToggle.checked } }));
  1111. if (cfarGuardInput) cfarGuardInput.addEventListener('change', () => {
  1112. const v = parseInt(cfarGuardInput.value, 10);
  1113. if (Number.isFinite(v)) queueConfigUpdate({ detector: { cfar_guard_cells: v } });
  1114. });
  1115. if (cfarTrainInput) cfarTrainInput.addEventListener('change', () => {
  1116. const v = parseInt(cfarTrainInput.value, 10);
  1117. if (Number.isFinite(v)) queueConfigUpdate({ detector: { cfar_train_cells: v } });
  1118. });
  1119. if (cfarRankInput) cfarRankInput.addEventListener('change', () => {
  1120. const v = parseInt(cfarRankInput.value, 10);
  1121. if (Number.isFinite(v)) queueConfigUpdate({ detector: { cfar_rank: v } });
  1122. });
  1123. if (cfarScaleInput) cfarScaleInput.addEventListener('change', () => {
  1124. const v = parseFloat(cfarScaleInput.value);
  1125. if (Number.isFinite(v)) queueConfigUpdate({ detector: { cfar_scale_db: v } });
  1126. });
  1127. if (minDurationInput) minDurationInput.addEventListener('change', () => {
  1128. const v = parseInt(minDurationInput.value, 10);
  1129. if (Number.isFinite(v)) queueConfigUpdate({ detector: { min_duration_ms: v } });
  1130. });
  1131. if (holdInput) holdInput.addEventListener('change', () => {
  1132. const v = parseInt(holdInput.value, 10);
  1133. if (Number.isFinite(v)) queueConfigUpdate({ detector: { hold_ms: v } });
  1134. });
  1135. if (emaAlphaInput) emaAlphaInput.addEventListener('change', () => {
  1136. const v = parseFloat(emaAlphaInput.value);
  1137. if (Number.isFinite(v)) queueConfigUpdate({ detector: { ema_alpha: v } });
  1138. });
  1139. if (hysteresisInput) hysteresisInput.addEventListener('change', () => {
  1140. const v = parseFloat(hysteresisInput.value);
  1141. if (Number.isFinite(v)) queueConfigUpdate({ detector: { hysteresis_db: v } });
  1142. });
  1143. if (stableFramesInput) stableFramesInput.addEventListener('change', () => {
  1144. const v = parseInt(stableFramesInput.value, 10);
  1145. if (Number.isFinite(v)) queueConfigUpdate({ detector: { min_stable_frames: v } });
  1146. });
  1147. if (gapToleranceInput) gapToleranceInput.addEventListener('change', () => {
  1148. const v = parseInt(gapToleranceInput.value, 10);
  1149. if (Number.isFinite(v)) queueConfigUpdate({ detector: { gap_tolerance_ms: v } });
  1150. });
  1151. agcToggle.addEventListener('change', () => queueSettingsUpdate({ agc: agcToggle.checked }));
  1152. dcToggle.addEventListener('change', () => queueSettingsUpdate({ dc_block: dcToggle.checked }));
  1153. iqToggle.addEventListener('change', () => queueSettingsUpdate({ iq_balance: iqToggle.checked }));
  1154. gpuToggle.addEventListener('change', () => queueConfigUpdate({ use_gpu_fft: gpuToggle.checked }));
  1155. if (recEnableToggle) recEnableToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { enabled: recEnableToggle.checked } }));
  1156. if (recIQToggle) recIQToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { record_iq: recIQToggle.checked } }));
  1157. if (recAudioToggle) recAudioToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { record_audio: recAudioToggle.checked } }));
  1158. if (recDemodToggle) recDemodToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { auto_demod: recDemodToggle.checked } }));
  1159. if (recDecodeToggle) recDecodeToggle.addEventListener('change', () => queueConfigUpdate({ recorder: { auto_decode: recDecodeToggle.checked } }));
  1160. if (recMinSNR) recMinSNR.addEventListener('change', () => queueConfigUpdate({ recorder: { min_snr_db: parseFloat(recMinSNR.value) } }));
  1161. if (recMaxDisk) recMaxDisk.addEventListener('change', () => queueConfigUpdate({ recorder: { max_disk_mb: parseInt(recMaxDisk.value || '0', 10) } }));
  1162. if (recClassFilter) recClassFilter.addEventListener('change', () => {
  1163. const list = (recClassFilter.value || '')
  1164. .split(',')
  1165. .map(s => s.trim())
  1166. .filter(Boolean);
  1167. queueConfigUpdate({ recorder: { class_filter: list } });
  1168. });
  1169. avgSelect.addEventListener('change', () => {
  1170. avgAlpha = parseFloat(avgSelect.value) || 0;
  1171. resetProcessingCaches();
  1172. });
  1173. maxHoldToggle.addEventListener('change', () => {
  1174. maxHold = maxHoldToggle.checked;
  1175. maxSpectrum = null;
  1176. markSpectrumDirty();
  1177. });
  1178. resetMaxBtn.addEventListener('click', () => {
  1179. maxSpectrum = null;
  1180. markSpectrumDirty();
  1181. });
  1182. followBtn.addEventListener('click', () => { followLive = true; pan = 0; });
  1183. fitBtn.addEventListener('click', fitView);
  1184. timelineFollowBtn.addEventListener('click', () => { timelineFrozen = false; });
  1185. timelineFreezeBtn.addEventListener('click', () => {
  1186. timelineFrozen = !timelineFrozen;
  1187. timelineFreezeBtn.textContent = timelineFrozen ? 'Frozen' : 'Freeze';
  1188. });
  1189. presetButtons.forEach((btn) => {
  1190. btn.addEventListener('click', () => {
  1191. const mhz = parseFloat(btn.dataset.center);
  1192. if (Number.isFinite(mhz)) tuneToFrequency(fromMHz(mhz));
  1193. });
  1194. });
  1195. railTabs.forEach((tab) => {
  1196. tab.addEventListener('click', () => {
  1197. railTabs.forEach(t => t.classList.toggle('active', t === tab));
  1198. tabPanels.forEach(panel => panel.classList.toggle('active', panel.dataset.panel === tab.dataset.tab));
  1199. });
  1200. });
  1201. modeButtons.forEach((btn) => {
  1202. btn.addEventListener('click', () => {
  1203. modeButtons.forEach(b => b.classList.toggle('active', b === btn));
  1204. document.body.classList.remove('mode-live', 'mode-hunt', 'mode-review', 'mode-lab');
  1205. document.body.classList.add(`mode-${btn.dataset.mode}`);
  1206. });
  1207. });
  1208. document.body.classList.add('mode-live');
  1209. drawerCloseBtn.addEventListener('click', closeDrawer);
  1210. exportEventBtn.addEventListener('click', exportSelectedEvent);
  1211. if (liveListenEventBtn) {
  1212. liveListenEventBtn.addEventListener('click', () => {
  1213. const ev = eventsById.get(selectedEventId);
  1214. if (!ev) return;
  1215. const freq = ev.center_hz;
  1216. const bw = ev.bandwidth_hz || 12000;
  1217. const mode = (listenModeSelect?.value || ev.class?.mod_type || 'NFM');
  1218. const sec = parseInt(listenSecondsInput?.value || '2', 10);
  1219. const url = `/api/demod?freq=${freq}&bw=${bw}&mode=${mode}&sec=${sec}`;
  1220. const audio = new Audio(url);
  1221. audio.play();
  1222. });
  1223. }
  1224. if (decodeEventBtn) {
  1225. decodeEventBtn.addEventListener('click', async () => {
  1226. const ev = eventsById.get(selectedEventId);
  1227. if (!ev) return;
  1228. if (!recordingMetaEl) return;
  1229. const rec = recordings.find(r => r.event_id === ev.id) || recordings.find(r => r.center_hz === ev.center_hz);
  1230. if (!rec) {
  1231. decodeResultEl.textContent = 'Decode: no recording';
  1232. return;
  1233. }
  1234. const mode = decodeModeSelect?.value || ev.class?.mod_type || 'FT8';
  1235. const res = await fetch(`/api/recordings/${rec.id}/decode?mode=${mode}`);
  1236. if (!res.ok) {
  1237. decodeResultEl.textContent = 'Decode: failed';
  1238. return;
  1239. }
  1240. const data = await res.json();
  1241. decodeResultEl.textContent = `Decode: ${String(data.stdout || '').slice(0, 80)}`;
  1242. });
  1243. }
  1244. jumpToEventBtn.addEventListener('click', () => {
  1245. const ev = eventsById.get(selectedEventId);
  1246. if (!ev) return;
  1247. tuneToFrequency(ev.center_hz);
  1248. });
  1249. timelineCanvas.addEventListener('click', (ev) => {
  1250. const rect = timelineCanvas.getBoundingClientRect();
  1251. const x = (ev.clientX - rect.left) * (timelineCanvas.width / rect.width);
  1252. const y = (ev.clientY - rect.top) * (timelineCanvas.height / rect.height);
  1253. for (let i = timelineRects.length - 1; i >= 0; i--) {
  1254. const r = timelineRects[i];
  1255. if (x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h) {
  1256. openDrawer(eventsById.get(r.id));
  1257. return;
  1258. }
  1259. }
  1260. });
  1261. signalList.addEventListener('click', (ev) => {
  1262. const target = ev.target.closest('.signal-item');
  1263. if (!target) return;
  1264. const center = parseFloat(target.dataset.center);
  1265. if (Number.isFinite(center)) tuneToFrequency(center);
  1266. });
  1267. if (liveListenBtn) {
  1268. liveListenBtn.addEventListener('click', async () => {
  1269. const first = signalList.querySelector('.signal-item');
  1270. if (!first) return;
  1271. const freq = parseFloat(first.dataset.center);
  1272. const bw = parseFloat(first.dataset.bw || '12000');
  1273. const mode = (listenModeSelect?.value || first.dataset.class || 'NFM');
  1274. const sec = parseInt(listenSecondsInput?.value || '2', 10);
  1275. const url = `/api/demod?freq=${freq}&bw=${bw}&mode=${mode}&sec=${sec}`;
  1276. if (liveAudio) {
  1277. liveAudio.pause();
  1278. }
  1279. liveAudio = new Audio(url);
  1280. liveAudio.play().catch(() => {});
  1281. });
  1282. }
  1283. eventList.addEventListener('click', (ev) => {
  1284. const target = ev.target.closest('.event-item');
  1285. if (!target) return;
  1286. const id = target.dataset.eventId;
  1287. openDrawer(eventsById.get(id));
  1288. });
  1289. if (recordingList) {
  1290. recordingList.addEventListener('click', async (ev) => {
  1291. const target = ev.target.closest('.recording-item');
  1292. if (!target) return;
  1293. const id = target.dataset.id;
  1294. const audio = new Audio(`/api/recordings/${id}/audio`);
  1295. audio.play();
  1296. if (recordingMetaEl) recordingMetaEl.textContent = `Recording: ${id}`;
  1297. if (recordingMetaLink) {
  1298. recordingMetaLink.href = `/api/recordings/${id}`;
  1299. recordingIQLink.href = `/api/recordings/${id}/iq`;
  1300. recordingAudioLink.href = `/api/recordings/${id}/audio`;
  1301. }
  1302. try {
  1303. const res = await fetch(`/api/recordings/${id}`);
  1304. if (!res.ok) return;
  1305. const meta = await res.json();
  1306. if (decodeResultEl) {
  1307. const rds = meta.rds_ps ? `RDS: ${meta.rds_ps}` : '';
  1308. decodeResultEl.textContent = `Decode: ${rds}`;
  1309. }
  1310. if (classifierScoresEl) {
  1311. const scores = meta.classification?.scores;
  1312. if (scores && typeof scores === 'object') {
  1313. const rows = Object.entries(scores)
  1314. .sort((a, b) => b[1] - a[1])
  1315. .slice(0, 6)
  1316. .map(([k, v]) => `${k}:${v.toFixed(2)}`)
  1317. .join(' · ');
  1318. classifierScoresEl.textContent = rows ? `Classifier scores: ${rows}` : 'Classifier scores: -';
  1319. } else {
  1320. classifierScoresEl.textContent = 'Classifier scores: -';
  1321. }
  1322. }
  1323. } catch {}
  1324. });
  1325. }
  1326. window.addEventListener('keydown', (ev) => {
  1327. if (ev.target && ['INPUT', 'SELECT', 'TEXTAREA'].includes(ev.target.tagName)) return;
  1328. if (ev.key === ' ') {
  1329. ev.preventDefault();
  1330. followLive = true;
  1331. pan = 0;
  1332. } else if (ev.key.toLowerCase() === 'f') {
  1333. fitView();
  1334. } else if (ev.key.toLowerCase() === 'm') {
  1335. maxHold = !maxHold;
  1336. maxHoldToggle.checked = maxHold;
  1337. if (!maxHold) maxSpectrum = null;
  1338. markSpectrumDirty();
  1339. } else if (ev.key.toLowerCase() === 'g') {
  1340. gpuToggle.checked = !gpuToggle.checked;
  1341. queueConfigUpdate({ use_gpu_fft: gpuToggle.checked });
  1342. } else if (ev.key === '[') {
  1343. zoom = Math.max(0.25, zoom * 0.88);
  1344. } else if (ev.key === ']') {
  1345. zoom = Math.min(24, zoom * 1.12);
  1346. } else if (ev.key === 'ArrowLeft') {
  1347. pan = Math.max(-0.5, pan - 0.04);
  1348. followLive = false;
  1349. } else if (ev.key === 'ArrowRight') {
  1350. pan = Math.min(0.5, pan + 0.04);
  1351. followLive = false;
  1352. }
  1353. });
  1354. loadConfig();
  1355. loadStats();
  1356. loadGPU();
  1357. fetchEvents(true);
  1358. fetchRecordings();
  1359. loadDecoders();
  1360. connect();
  1361. requestAnimationFrame(renderLoop);
  1362. setInterval(loadStats, 1000);
  1363. setInterval(loadGPU, 1000);
  1364. setInterval(() => fetchEvents(false), 2000);
  1365. setInterval(fetchRecordings, 5000);
  1366. setInterval(loadSignals, 1500);
  1367. setInterval(loadDecoders, 10000);