25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

1344 satır
45KB

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