您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1311 行
43KB

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