Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

1372 wiersze
46KB

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