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

1277 строки
41KB

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