選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

1314 行
42KB

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