Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

1329 řádky
44KB

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