Wideband autonomous SDR analysis engine forked from sdr-visual-suite
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1519 строки
52KB

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