Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

1477 rindas
50KB

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