maybe wsjtx integration

pull/49/head
accius 2 days ago
parent 0ea34e82c7
commit 82585acb3e

@ -77,6 +77,17 @@ SHOW_SATELLITES=true
# Show DX paths on map (true/false)
SHOW_DX_PATHS=true
# ===========================================
# WSJT-X / JTDX UDP INTEGRATION
# ===========================================
# Enable WSJT-X UDP listener (true/false)
# Listens for decoded FT8/FT4/JT65/WSPR messages from WSJT-X, JTDX, etc.
WSJTX_ENABLED=true
# UDP port to listen on (must match WSJT-X Settings > Reporting > UDP Server port)
WSJTX_UDP_PORT=2237
# ===========================================
# DX CLUSTER SETTINGS
# ===========================================

@ -22,6 +22,7 @@ const compression = require('compression');
const path = require('path');
const fetch = require('node-fetch');
const net = require('net');
const dgram = require('dgram');
const fs = require('fs');
// Auto-create .env from .env.example on first run
@ -3620,6 +3621,519 @@ app.get('/api/config', (req, res) => {
});
});
// ============================================
// WSJT-X UDP LISTENER
// ============================================
// Receives decoded messages from WSJT-X, JTDX, etc.
// Configure WSJT-X: Settings > Reporting > UDP Server > address/port
// Protocol: QDataStream binary format per NetworkMessage.hpp
const WSJTX_UDP_PORT = parseInt(process.env.WSJTX_UDP_PORT || '2237');
const WSJTX_ENABLED = process.env.WSJTX_ENABLED !== 'false'; // enabled by default
const WSJTX_MAX_DECODES = 200; // max decodes to keep in memory
const WSJTX_MAX_AGE = 30 * 60 * 1000; // 30 minutes
// WSJT-X protocol magic number
const WSJTX_MAGIC = 0xADBCCBDA;
// Message types
const WSJTX_MSG = {
HEARTBEAT: 0,
STATUS: 1,
DECODE: 2,
CLEAR: 3,
REPLY: 4,
QSO_LOGGED: 5,
CLOSE: 6,
REPLAY: 7,
HALT_TX: 8,
FREE_TEXT: 9,
WSPR_DECODE: 10,
LOCATION: 11,
LOGGED_ADIF: 12,
HIGHLIGHT_CALLSIGN: 13,
SWITCH_CONFIG: 14,
CONFIGURE: 15,
};
// In-memory store
const wsjtxState = {
clients: {}, // clientId -> { status, lastSeen }
decodes: [], // decoded messages (ring buffer)
qsos: [], // logged QSOs
wspr: [], // WSPR decodes
};
/**
* QDataStream binary reader for WSJT-X protocol
* Reads big-endian Qt-serialized data types
*/
class WSJTXReader {
constructor(buffer) {
this.buf = buffer;
this.offset = 0;
}
remaining() { return this.buf.length - this.offset; }
readUInt8() {
if (this.remaining() < 1) return null;
const v = this.buf.readUInt8(this.offset);
this.offset += 1;
return v;
}
readInt32() {
if (this.remaining() < 4) return null;
const v = this.buf.readInt32BE(this.offset);
this.offset += 4;
return v;
}
readUInt32() {
if (this.remaining() < 4) return null;
const v = this.buf.readUInt32BE(this.offset);
this.offset += 4;
return v;
}
readUInt64() {
if (this.remaining() < 8) return null;
// JavaScript can't do 64-bit ints natively, use BigInt or approximate
const high = this.buf.readUInt32BE(this.offset);
const low = this.buf.readUInt32BE(this.offset + 4);
this.offset += 8;
return high * 0x100000000 + low;
}
readBool() {
const v = this.readUInt8();
return v === null ? null : v !== 0;
}
readDouble() {
if (this.remaining() < 8) return null;
const v = this.buf.readDoubleBE(this.offset);
this.offset += 8;
return v;
}
// Qt utf8 string: uint32 length + bytes (0xFFFFFFFF = null)
readUtf8() {
const len = this.readUInt32();
if (len === null || len === 0xFFFFFFFF) return null;
if (len === 0) return '';
if (this.remaining() < len) return null;
const str = this.buf.toString('utf8', this.offset, this.offset + len);
this.offset += len;
return str;
}
// QTime: uint32 milliseconds since midnight
readQTime() {
const ms = this.readUInt32();
if (ms === null) return null;
const h = Math.floor(ms / 3600000);
const m = Math.floor((ms % 3600000) / 60000);
const s = Math.floor((ms % 60000) / 1000);
return { ms, hours: h, minutes: m, seconds: s,
formatted: `${String(h).padStart(2,'0')}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}` };
}
// QDateTime: QDate (int64 julian day) + QTime (uint32 ms) + timespec
readQDateTime() {
const julianDay = this.readUInt64();
const time = this.readQTime();
const timeSpec = this.readUInt8();
if (timeSpec === 2) this.readInt32(); // UTC offset
return { julianDay, time, timeSpec };
}
}
/**
* Parse a WSJT-X UDP datagram
*/
function parseWSJTXMessage(buffer) {
const reader = new WSJTXReader(buffer);
// Header
const magic = reader.readUInt32();
if (magic !== WSJTX_MAGIC) return null;
const schema = reader.readUInt32();
const type = reader.readUInt32();
const id = reader.readUtf8();
if (type === null || id === null) return null;
const msg = { type, id, schema, timestamp: Date.now() };
try {
switch (type) {
case WSJTX_MSG.HEARTBEAT: {
msg.maxSchema = reader.readUInt32();
msg.version = reader.readUtf8();
msg.revision = reader.readUtf8();
break;
}
case WSJTX_MSG.STATUS: {
msg.dialFrequency = reader.readUInt64();
msg.mode = reader.readUtf8();
msg.dxCall = reader.readUtf8();
msg.report = reader.readUtf8();
msg.txMode = reader.readUtf8();
msg.txEnabled = reader.readBool();
msg.transmitting = reader.readBool();
msg.decoding = reader.readBool();
msg.rxDF = reader.readUInt32();
msg.txDF = reader.readUInt32();
msg.deCall = reader.readUtf8();
msg.deGrid = reader.readUtf8();
msg.dxGrid = reader.readUtf8();
msg.txWatchdog = reader.readBool();
msg.subMode = reader.readUtf8();
msg.fastMode = reader.readBool();
msg.specialOp = reader.readUInt8();
msg.freqTolerance = reader.readUInt32();
msg.trPeriod = reader.readUInt32();
msg.configName = reader.readUtf8();
msg.txMessage = reader.readUtf8();
break;
}
case WSJTX_MSG.DECODE: {
msg.isNew = reader.readBool();
msg.time = reader.readQTime();
msg.snr = reader.readInt32();
msg.deltaTime = reader.readDouble();
msg.deltaFreq = reader.readUInt32();
msg.mode = reader.readUtf8();
msg.message = reader.readUtf8();
msg.lowConfidence = reader.readBool();
msg.offAir = reader.readBool();
break;
}
case WSJTX_MSG.CLEAR: {
msg.window = reader.readUInt8();
break;
}
case WSJTX_MSG.QSO_LOGGED: {
msg.dateTimeOff = reader.readQDateTime();
msg.dxCall = reader.readUtf8();
msg.dxGrid = reader.readUtf8();
msg.txFrequency = reader.readUInt64();
msg.mode = reader.readUtf8();
msg.reportSent = reader.readUtf8();
msg.reportRecv = reader.readUtf8();
msg.txPower = reader.readUtf8();
msg.comments = reader.readUtf8();
msg.name = reader.readUtf8();
msg.dateTimeOn = reader.readQDateTime();
msg.operatorCall = reader.readUtf8();
msg.myCall = reader.readUtf8();
msg.myGrid = reader.readUtf8();
msg.exchangeSent = reader.readUtf8();
msg.exchangeRecv = reader.readUtf8();
msg.adifPropMode = reader.readUtf8();
break;
}
case WSJTX_MSG.WSPR_DECODE: {
msg.isNew = reader.readBool();
msg.time = reader.readQTime();
msg.snr = reader.readInt32();
msg.deltaTime = reader.readDouble();
msg.frequency = reader.readUInt64();
msg.drift = reader.readInt32();
msg.callsign = reader.readUtf8();
msg.grid = reader.readUtf8();
msg.power = reader.readInt32();
msg.offAir = reader.readBool();
break;
}
case WSJTX_MSG.LOGGED_ADIF: {
msg.adif = reader.readUtf8();
break;
}
case WSJTX_MSG.CLOSE:
break;
default:
// Unknown message type - ignore per protocol spec
return null;
}
} catch (e) {
// Malformed packet - ignore
return null;
}
return msg;
}
/**
* Parse decoded message text to extract callsigns and grid
* FT8/FT4 messages follow a standard format
*/
function parseDecodeMessage(text) {
if (!text) return {};
const result = {};
// CQ message: "CQ DX K1ABC FN42" or "CQ K1ABC FN42"
const cqMatch = text.match(/^CQ\s+(?:(\S+)\s+)?([A-Z0-9/]+)\s+([A-Z]{2}\d{2}[a-z]{0,2})?/i);
if (cqMatch) {
result.type = 'CQ';
result.modifier = cqMatch[1] && !cqMatch[1].match(/^[A-Z0-9/]{3,}$/) ? cqMatch[1] : null;
result.caller = cqMatch[2] || cqMatch[1];
result.grid = cqMatch[3] || null;
return result;
}
// Standard QSO exchange: "K1ABC W2DEF +05" or "K1ABC W2DEF R-12" or "K1ABC W2DEF RR73"
const qsoMatch = text.match(/^([A-Z0-9/]+)\s+([A-Z0-9/]+)\s+(.*)/i);
if (qsoMatch) {
result.type = 'QSO';
result.dxCall = qsoMatch[1];
result.deCall = qsoMatch[2];
result.exchange = qsoMatch[3].trim();
// Check for grid in exchange
const gridMatch = result.exchange.match(/^([A-Z]{2}\d{2}[a-z]{0,2})$/i);
if (gridMatch) result.grid = gridMatch[1];
return result;
}
return result;
}
/**
* Convert frequency in Hz to band name
*/
function freqToBand(freqHz) {
const mhz = freqHz / 1000000;
if (mhz >= 1.8 && mhz < 2.0) return '160m';
if (mhz >= 3.5 && mhz < 4.0) return '80m';
if (mhz >= 5.3 && mhz < 5.4) return '60m';
if (mhz >= 7.0 && mhz < 7.3) return '40m';
if (mhz >= 10.1 && mhz < 10.15) return '30m';
if (mhz >= 14.0 && mhz < 14.35) return '20m';
if (mhz >= 18.068 && mhz < 18.168) return '17m';
if (mhz >= 21.0 && mhz < 21.45) return '15m';
if (mhz >= 24.89 && mhz < 24.99) return '12m';
if (mhz >= 28.0 && mhz < 29.7) return '10m';
if (mhz >= 50.0 && mhz < 54.0) return '6m';
if (mhz >= 144.0 && mhz < 148.0) return '2m';
if (mhz >= 420.0 && mhz < 450.0) return '70cm';
return `${mhz.toFixed(3)} MHz`;
}
/**
* Handle incoming WSJT-X messages
*/
function handleWSJTXMessage(msg) {
if (!msg) return;
switch (msg.type) {
case WSJTX_MSG.HEARTBEAT: {
wsjtxState.clients[msg.id] = {
...(wsjtxState.clients[msg.id] || {}),
version: msg.version,
lastSeen: msg.timestamp
};
break;
}
case WSJTX_MSG.STATUS: {
wsjtxState.clients[msg.id] = {
...(wsjtxState.clients[msg.id] || {}),
lastSeen: msg.timestamp,
dialFrequency: msg.dialFrequency,
mode: msg.mode,
dxCall: msg.dxCall,
deCall: msg.deCall,
deGrid: msg.deGrid,
txEnabled: msg.txEnabled,
transmitting: msg.transmitting,
decoding: msg.decoding,
subMode: msg.subMode,
band: msg.dialFrequency ? freqToBand(msg.dialFrequency) : null,
configName: msg.configName,
txMessage: msg.txMessage,
};
break;
}
case WSJTX_MSG.DECODE: {
const clientStatus = wsjtxState.clients[msg.id] || {};
const parsed = parseDecodeMessage(msg.message);
const decode = {
id: `${msg.id}-${msg.timestamp}-${msg.deltaFreq}`,
clientId: msg.id,
isNew: msg.isNew,
time: msg.time?.formatted || '',
timeMs: msg.time?.ms || 0,
snr: msg.snr,
dt: msg.deltaTime ? msg.deltaTime.toFixed(1) : '0.0',
freq: msg.deltaFreq,
mode: msg.mode || clientStatus.mode || '',
message: msg.message,
lowConfidence: msg.lowConfidence,
offAir: msg.offAir,
dialFrequency: clientStatus.dialFrequency || 0,
band: clientStatus.band || '',
...parsed,
timestamp: msg.timestamp,
};
// Resolve grid to lat/lon for map plotting
if (parsed.grid) {
const coords = gridToLatLon(parsed.grid);
if (coords) {
decode.lat = coords.latitude;
decode.lon = coords.longitude;
}
}
// Only keep new decodes (not replays)
if (msg.isNew) {
wsjtxState.decodes.push(decode);
// Trim old decodes
const cutoff = Date.now() - WSJTX_MAX_AGE;
while (wsjtxState.decodes.length > WSJTX_MAX_DECODES ||
(wsjtxState.decodes.length > 0 && wsjtxState.decodes[0].timestamp < cutoff)) {
wsjtxState.decodes.shift();
}
}
break;
}
case WSJTX_MSG.CLEAR: {
// WSJT-X cleared its band activity - optionally clear our decodes for this client
wsjtxState.decodes = wsjtxState.decodes.filter(d => d.clientId !== msg.id);
break;
}
case WSJTX_MSG.QSO_LOGGED: {
const clientStatus = wsjtxState.clients[msg.id] || {};
const qso = {
clientId: msg.id,
dxCall: msg.dxCall,
dxGrid: msg.dxGrid,
frequency: msg.txFrequency,
band: msg.txFrequency ? freqToBand(msg.txFrequency) : '',
mode: msg.mode,
reportSent: msg.reportSent,
reportRecv: msg.reportRecv,
myCall: msg.myCall || clientStatus.deCall,
myGrid: msg.myGrid || clientStatus.deGrid,
timestamp: msg.timestamp,
};
// Resolve grid to lat/lon
if (msg.dxGrid) {
const coords = gridToLatLon(msg.dxGrid);
if (coords) { qso.lat = coords.latitude; qso.lon = coords.longitude; }
}
wsjtxState.qsos.push(qso);
// Keep last 50 QSOs
if (wsjtxState.qsos.length > 50) wsjtxState.qsos.shift();
break;
}
case WSJTX_MSG.WSPR_DECODE: {
const wsprDecode = {
clientId: msg.id,
isNew: msg.isNew,
time: msg.time?.formatted || '',
snr: msg.snr,
dt: msg.deltaTime ? msg.deltaTime.toFixed(1) : '0.0',
frequency: msg.frequency,
drift: msg.drift,
callsign: msg.callsign,
grid: msg.grid,
power: msg.power,
timestamp: msg.timestamp,
};
if (msg.isNew) {
wsjtxState.wspr.push(wsprDecode);
if (wsjtxState.wspr.length > 100) wsjtxState.wspr.shift();
}
break;
}
case WSJTX_MSG.CLOSE: {
delete wsjtxState.clients[msg.id];
break;
}
}
}
// Start UDP listener
let wsjtxSocket = null;
if (WSJTX_ENABLED) {
try {
wsjtxSocket = dgram.createSocket('udp4');
wsjtxSocket.on('message', (buf, rinfo) => {
const msg = parseWSJTXMessage(buf);
if (msg) handleWSJTXMessage(msg);
});
wsjtxSocket.on('error', (err) => {
logErrorOnce('WSJT-X UDP', err.message);
});
wsjtxSocket.on('listening', () => {
const addr = wsjtxSocket.address();
console.log(`[WSJT-X] UDP listener on ${addr.address}:${addr.port}`);
});
wsjtxSocket.bind(WSJTX_UDP_PORT, '0.0.0.0');
} catch (e) {
console.error(`[WSJT-X] Failed to start UDP listener: ${e.message}`);
}
}
// API endpoint: get WSJT-X data
app.get('/api/wsjtx', (req, res) => {
const clients = {};
for (const [id, client] of Object.entries(wsjtxState.clients)) {
// Only include clients seen in last 5 minutes
if (Date.now() - client.lastSeen < 5 * 60 * 1000) {
clients[id] = client;
}
}
res.json({
enabled: WSJTX_ENABLED,
port: WSJTX_UDP_PORT,
clients,
decodes: wsjtxState.decodes.slice(-100), // last 100
qsos: wsjtxState.qsos.slice(-20), // last 20
wspr: wsjtxState.wspr.slice(-50), // last 50
stats: {
totalDecodes: wsjtxState.decodes.length,
totalQsos: wsjtxState.qsos.length,
totalWspr: wsjtxState.wspr.length,
activeClients: Object.keys(clients).length,
}
});
});
// API endpoint: get just decodes (lightweight polling)
app.get('/api/wsjtx/decodes', (req, res) => {
const since = parseInt(req.query.since) || 0;
const decodes = since
? wsjtxState.decodes.filter(d => d.timestamp > since)
: wsjtxState.decodes.slice(-100);
res.json({ decodes, timestamp: Date.now() });
});
// ============================================
// CATCH-ALL FOR SPA
// ============================================
@ -3663,6 +4177,9 @@ app.listen(PORT, '0.0.0.0', () => {
console.log(` 🔗 Network access: http://<your-ip>:${PORT}`);
}
console.log(' 📡 API proxy enabled for NOAA, POTA, SOTA, DX Cluster');
if (WSJTX_ENABLED) {
console.log(` 🔊 WSJT-X UDP listener on port ${WSJTX_UDP_PORT}`);
}
console.log(' 🖥️ Open your browser to start using OpenHamClock');
console.log('');
if (CONFIG.callsign !== 'N0CALL') {

@ -34,7 +34,8 @@ import {
useDXpeditions,
useSatellites,
useSolarIndices,
usePSKReporter
usePSKReporter,
useWSJTX
} from './hooks';
// Utils
@ -104,9 +105,9 @@ const App = () => {
const [mapLayers, setMapLayers] = useState(() => {
try {
const stored = localStorage.getItem('openhamclock_mapLayers');
const defaults = { showDXPaths: true, showDXLabels: true, showPOTA: true, showSatellites: false, showPSKReporter: true };
const defaults = { showDXPaths: true, showDXLabels: true, showPOTA: true, showSatellites: false, showPSKReporter: true, showWSJTX: true };
return stored ? { ...defaults, ...JSON.parse(stored) } : defaults;
} catch (e) { return { showDXPaths: true, showDXLabels: true, showPOTA: true, showSatellites: false, showPSKReporter: true }; }
} catch (e) { return { showDXPaths: true, showDXLabels: true, showPOTA: true, showSatellites: false, showPSKReporter: true, showWSJTX: true }; }
});
useEffect(() => {
@ -122,6 +123,7 @@ const App = () => {
const togglePOTA = useCallback(() => setMapLayers(prev => ({ ...prev, showPOTA: !prev.showPOTA })), []);
const toggleSatellites = useCallback(() => setMapLayers(prev => ({ ...prev, showSatellites: !prev.showSatellites })), []);
const togglePSKReporter = useCallback(() => setMapLayers(prev => ({ ...prev, showPSKReporter: !prev.showPSKReporter })), []);
const toggleWSJTX = useCallback(() => setMapLayers(prev => ({ ...prev, showWSJTX: !prev.showWSJTX })), []);
// 12/24 hour format
const [use12Hour, setUse12Hour] = useState(() => {
@ -208,6 +210,7 @@ const App = () => {
const satellites = useSatellites(config.location);
const localWeather = useLocalWeather(config.location);
const pskReporter = usePSKReporter(config.callsign, { minutes: 15, enabled: config.callsign !== 'N0CALL' });
const wsjtx = useWSJTX();
// Filter PSKReporter spots for map display
const filteredPskSpots = useMemo(() => {
@ -228,6 +231,11 @@ const App = () => {
});
}, [pskReporter.txReports, pskReporter.rxReports, pskFilters]);
// Filter WSJT-X decodes for map display (only those with lat/lon from grid)
const wsjtxMapSpots = useMemo(() => {
return wsjtx.decodes.filter(d => d.lat && d.lon && d.type === 'CQ');
}, [wsjtx.decodes]);
// Computed values
const deGrid = useMemo(() => calculateGridSquare(config.location.lat, config.location.lon), [config.location]);
const dxGrid = useMemo(() => calculateGridSquare(dxLocation.lat, dxLocation.lon), [dxLocation]);
@ -503,6 +511,8 @@ const App = () => {
showPOTA={mapLayers.showPOTA}
showSatellites={mapLayers.showSatellites}
showPSKReporter={mapLayers.showPSKReporter}
wsjtxSpots={wsjtxMapSpots}
showWSJTX={mapLayers.showWSJTX}
onToggleSatellites={toggleSatellites}
hoveredSpot={hoveredSpot}
/>
@ -641,6 +651,8 @@ const App = () => {
showPOTA={mapLayers.showPOTA}
showSatellites={mapLayers.showSatellites}
showPSKReporter={mapLayers.showPSKReporter}
wsjtxSpots={wsjtxMapSpots}
showWSJTX={mapLayers.showWSJTX}
onToggleSatellites={toggleSatellites}
hoveredSpot={hoveredSpot}
/>
@ -677,7 +689,7 @@ const App = () => {
/>
</div>
{/* PSKReporter - digital mode spots */}
{/* PSKReporter + WSJT-X - digital mode spots */}
<div style={{ flex: '1 1 auto', minHeight: '140px', overflow: 'hidden' }}>
<PSKReporterPanel
callsign={config.callsign}
@ -690,6 +702,15 @@ const App = () => {
setDxLocation({ lat: report.lat, lon: report.lon, call: report.receiver || report.sender });
}
}}
wsjtxDecodes={wsjtx.decodes}
wsjtxClients={wsjtx.clients}
wsjtxQsos={wsjtx.qsos}
wsjtxStats={wsjtx.stats}
wsjtxLoading={wsjtx.loading}
wsjtxEnabled={wsjtx.enabled}
wsjtxPort={wsjtx.port}
showWSJTXOnMap={mapLayers.showWSJTX}
onToggleWSJTXMap={toggleWSJTX}
/>
</div>

@ -1,7 +1,7 @@
/**
* PSKReporter Panel
* Shows where your digital mode signals are being received
* Uses MQTT WebSocket for real-time data
* Toggles between PSKReporter (internet) and WSJT-X (local UDP) views
*/
import React, { useState, useMemo } from 'react';
import { usePSKReporter } from '../hooks/usePSKReporter.js';
@ -13,9 +13,23 @@ const PSKReporterPanel = ({
showOnMap,
onToggleMap,
filters = {},
onOpenFilters
onOpenFilters,
// WSJT-X props
wsjtxDecodes = [],
wsjtxClients = {},
wsjtxQsos = [],
wsjtxStats = {},
wsjtxLoading,
wsjtxEnabled,
wsjtxPort,
showWSJTXOnMap,
onToggleWSJTXMap
}) => {
const [activeTab, setActiveTab] = useState('tx'); // Default to 'tx' (Being Heard)
const [panelMode, setPanelMode] = useState('psk'); // 'psk' | 'wsjtx'
const [activeTab, setActiveTab] = useState('tx'); // PSK: tx | rx
const [wsjtxTab, setWsjtxTab] = useState('decodes'); // WSJT-X: decodes | qsos
const [bandFilter, setBandFilter] = useState('all');
const [showCQ, setShowCQ] = useState(false);
const {
txReports,
@ -32,23 +46,17 @@ const PSKReporterPanel = ({
enabled: callsign && callsign !== 'N0CALL'
});
// Filter reports by band, grid, and mode
// PSK filter logic
const filterReports = (reports) => {
return reports.filter(r => {
// Band filter
if (filters?.bands?.length && !filters.bands.includes(r.band)) return false;
// Grid filter (prefix match)
if (filters?.grids?.length) {
const grid = activeTab === 'tx' ? r.receiverGrid : r.senderGrid;
if (!grid) return false;
const gridPrefix = grid.substring(0, 2).toUpperCase();
if (!filters.grids.includes(gridPrefix)) return false;
}
// Mode filter
if (filters?.modes?.length && !filters.modes.includes(r.mode)) return false;
return true;
});
};
@ -57,7 +65,6 @@ const PSKReporterPanel = ({
const filteredRx = useMemo(() => filterReports(rxReports), [rxReports, filters, activeTab]);
const filteredReports = activeTab === 'tx' ? filteredTx : filteredRx;
// Count active filters
const getActiveFilterCount = () => {
let count = 0;
if (filters?.bands?.length) count++;
@ -67,46 +74,66 @@ const PSKReporterPanel = ({
};
const filterCount = getActiveFilterCount();
// Get band color from frequency
const getFreqColor = (freqMHz) => {
if (!freqMHz) return 'var(--text-muted)';
const freq = parseFloat(freqMHz);
return getBandColor(freq);
return getBandColor(parseFloat(freqMHz));
};
// Format age
const formatAge = (minutes) => {
if (minutes < 1) return 'now';
if (minutes < 60) return `${minutes}m`;
return `${Math.floor(minutes/60)}h`;
};
// Get status indicator
const getStatusIndicator = () => {
if (connected) {
return <span style={{ color: '#4ade80', fontSize: '10px' }}> LIVE</span>;
}
if (source === 'connecting' || source === 'reconnecting') {
return <span style={{ color: '#fbbf24', fontSize: '10px' }}> {source}</span>;
}
if (error) {
return <span style={{ color: '#ef4444', fontSize: '10px' }}> offline</span>;
}
if (connected) return <span style={{ color: '#4ade80', fontSize: '10px' }}> LIVE</span>;
if (source === 'connecting' || source === 'reconnecting') return <span style={{ color: '#fbbf24', fontSize: '10px' }}> {source}</span>;
if (error) return <span style={{ color: '#ef4444', fontSize: '10px' }}> offline</span>;
return null;
};
if (!callsign || callsign === 'N0CALL') {
return (
<div className="panel" style={{ padding: '10px' }}>
<div style={{ fontSize: '12px', color: 'var(--accent-primary)', fontWeight: '700', marginBottom: '6px' }}>
📡 PSKReporter
</div>
<div style={{ color: 'var(--text-muted)', textAlign: 'center', padding: '10px', fontSize: '11px' }}>
Set callsign in Settings
</div>
</div>
);
}
// WSJT-X helpers
const activeClients = Object.entries(wsjtxClients);
const primaryClient = activeClients.length > 0 ? activeClients[0][1] : null;
const wsjtxBands = useMemo(() => {
const bands = new Set(wsjtxDecodes.map(d => d.band).filter(Boolean));
return ['all', ...Array.from(bands).sort((a, b) => (parseInt(b) || 999) - (parseInt(a) || 999))];
}, [wsjtxDecodes]);
const filteredDecodes = useMemo(() => {
let filtered = [...wsjtxDecodes];
if (bandFilter !== 'all') filtered = filtered.filter(d => d.band === bandFilter);
if (showCQ) filtered = filtered.filter(d => d.type === 'CQ');
return filtered.reverse();
}, [wsjtxDecodes, bandFilter, showCQ]);
const getSnrColor = (snr) => {
if (snr === null || snr === undefined) return 'var(--text-muted)';
if (snr >= 0) return '#4ade80';
if (snr >= -10) return '#fbbf24';
if (snr >= -18) return '#fb923c';
return '#ef4444';
};
const getMsgColor = (decode) => {
if (decode.type === 'CQ') return '#60a5fa';
if (decode.exchange === 'RR73' || decode.exchange === '73' || decode.exchange === 'RRR') return '#4ade80';
if (decode.exchange?.startsWith('R')) return '#fbbf24';
return 'var(--text-primary)';
};
// Mode switch button style
const modeBtn = (mode, color) => ({
padding: '2px 8px',
background: panelMode === mode ? `${color}22` : 'transparent',
border: `1px solid ${panelMode === mode ? color : 'var(--border-color)'}`,
color: panelMode === mode ? color : 'var(--text-muted)',
borderRadius: '3px',
fontSize: '10px',
cursor: 'pointer',
fontWeight: panelMode === mode ? '700' : '400',
});
return (
<div className="panel" style={{
@ -116,114 +143,119 @@ const PSKReporterPanel = ({
height: '100%',
overflow: 'hidden'
}}>
{/* Header */}
{/* Mode switcher header */}
<div style={{
fontSize: '12px',
color: 'var(--accent-primary)',
fontWeight: '700',
marginBottom: '6px',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
alignItems: 'center'
marginBottom: '4px',
flexShrink: 0
}}>
<span>📡 PSKReporter {getStatusIndicator()}</span>
<div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
<div style={{ display: 'flex', gap: '3px' }}>
<button onClick={() => setPanelMode('psk')} style={modeBtn('psk', 'var(--accent-primary)')}>
📡 PSKReporter
</button>
<button onClick={() => setPanelMode('wsjtx')} style={modeBtn('wsjtx', '#a78bfa')}>
🔊 WSJT-X
</button>
</div>
{/* Controls row - differs per mode */}
<div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>
{panelMode === 'psk' && (
<>
<span style={{ fontSize: '9px', color: 'var(--text-muted)' }}>
{filteredReports.length}/{activeTab === 'tx' ? txCount : rxCount}
</span>
<button
onClick={onOpenFilters}
style={{
{getStatusIndicator()}
<button onClick={onOpenFilters} style={{
background: filterCount > 0 ? 'rgba(255, 170, 0, 0.3)' : 'rgba(100, 100, 100, 0.3)',
border: `1px solid ${filterCount > 0 ? '#ffaa00' : '#666'}`,
color: filterCount > 0 ? '#ffaa00' : '#888',
padding: '2px 8px',
borderRadius: '4px',
fontSize: '10px',
fontFamily: 'JetBrains Mono',
cursor: 'pointer'
}}
>
🔍 Filters
</button>
<button
onClick={refresh}
disabled={loading}
title={connected ? 'Reconnect' : 'Connect'}
style={{
background: 'rgba(100, 100, 100, 0.3)',
border: '1px solid #666',
color: '#888',
padding: '2px 6px',
borderRadius: '4px',
fontSize: '10px',
cursor: loading ? 'not-allowed' : 'pointer',
opacity: loading ? 0.5 : 1
}}
>
🔄
</button>
padding: '2px 6px', borderRadius: '4px', fontSize: '10px', cursor: 'pointer'
}}>🔍</button>
<button onClick={refresh} disabled={loading} style={{
background: 'rgba(100, 100, 100, 0.3)', border: '1px solid #666',
color: '#888', padding: '2px 6px', borderRadius: '4px', fontSize: '10px',
cursor: loading ? 'not-allowed' : 'pointer', opacity: loading ? 0.5 : 1
}}>🔄</button>
{onToggleMap && (
<button
onClick={onToggleMap}
style={{
<button onClick={onToggleMap} style={{
background: showOnMap ? 'rgba(68, 136, 255, 0.3)' : 'rgba(100, 100, 100, 0.3)',
border: `1px solid ${showOnMap ? '#4488ff' : '#666'}`,
color: showOnMap ? '#4488ff' : '#888',
padding: '2px 8px',
borderRadius: '4px',
fontSize: '10px',
fontFamily: 'JetBrains Mono',
cursor: 'pointer'
}}
>
🗺 {showOnMap ? 'ON' : 'OFF'}
</button>
padding: '2px 6px', borderRadius: '4px', fontSize: '10px', cursor: 'pointer'
}}>🗺 {showOnMap ? 'ON' : 'OFF'}</button>
)}
</>
)}
{panelMode === 'wsjtx' && (
<>
{primaryClient && (
<span style={{ fontSize: '10px', color: 'var(--text-muted)' }}>
{primaryClient.mode || ''} {primaryClient.band || ''}
{primaryClient.transmitting && <span style={{ color: '#ef4444', marginLeft: '3px' }}>TX</span>}
{primaryClient.decoding && <span style={{ color: '#4ade80', marginLeft: '3px' }}>RX</span>}
</span>
)}
<select value={bandFilter} onChange={(e) => setBandFilter(e.target.value)} style={{
background: 'var(--bg-tertiary)', color: 'var(--text-primary)',
border: '1px solid var(--border-color)', borderRadius: '3px',
fontSize: '10px', padding: '1px 2px', cursor: 'pointer'
}}>
{wsjtxBands.map(b => <option key={b} value={b}>{b === 'all' ? 'All' : b}</option>)}
</select>
<button onClick={() => setShowCQ(!showCQ)} style={{
background: showCQ ? '#60a5fa33' : 'transparent',
color: showCQ ? '#60a5fa' : 'var(--text-muted)',
border: `1px solid ${showCQ ? '#60a5fa55' : 'var(--border-color)'}`,
borderRadius: '3px', fontSize: '10px', padding: '1px 4px', cursor: 'pointer'
}}>CQ</button>
{onToggleWSJTXMap && (
<button onClick={onToggleWSJTXMap} style={{
background: showWSJTXOnMap ? 'rgba(167, 139, 250, 0.3)' : 'rgba(100, 100, 100, 0.3)',
border: `1px solid ${showWSJTXOnMap ? '#a78bfa' : '#666'}`,
color: showWSJTXOnMap ? '#a78bfa' : '#888',
padding: '2px 6px', borderRadius: '4px', fontSize: '10px', cursor: 'pointer'
}}>🗺 {showWSJTXOnMap ? 'ON' : 'OFF'}</button>
)}
</>
)}
</div>
</div>
{/* Tabs */}
<div style={{
display: 'flex',
gap: '4px',
marginBottom: '6px'
}}>
<button
onClick={() => setActiveTab('tx')}
style={{
flex: 1,
padding: '4px 6px',
{/* === PSKReporter View === */}
{panelMode === 'psk' && (
<>
{(!callsign || callsign === 'N0CALL') ? (
<div style={{ color: 'var(--text-muted)', textAlign: 'center', padding: '10px', fontSize: '11px' }}>
Set callsign in Settings
</div>
) : (
<>
{/* PSK Tabs */}
<div style={{ display: 'flex', gap: '4px', marginBottom: '6px', flexShrink: 0 }}>
<button onClick={() => setActiveTab('tx')} style={{
flex: 1, padding: '4px 6px',
background: activeTab === 'tx' ? 'rgba(74, 222, 128, 0.2)' : 'rgba(100, 100, 100, 0.2)',
border: `1px solid ${activeTab === 'tx' ? '#4ade80' : '#555'}`,
borderRadius: '3px',
color: activeTab === 'tx' ? '#4ade80' : '#888',
cursor: 'pointer',
fontSize: '10px',
fontFamily: 'JetBrains Mono'
}}
>
📤 Being Heard ({filterCount > 0 ? `${filteredTx.length}` : txCount})
borderRadius: '3px', color: activeTab === 'tx' ? '#4ade80' : '#888',
cursor: 'pointer', fontSize: '10px', fontFamily: 'JetBrains Mono'
}}>
📤 Being Heard ({filterCount > 0 ? filteredTx.length : txCount})
</button>
<button
onClick={() => setActiveTab('rx')}
style={{
flex: 1,
padding: '4px 6px',
<button onClick={() => setActiveTab('rx')} style={{
flex: 1, padding: '4px 6px',
background: activeTab === 'rx' ? 'rgba(96, 165, 250, 0.2)' : 'rgba(100, 100, 100, 0.2)',
border: `1px solid ${activeTab === 'rx' ? '#60a5fa' : '#555'}`,
borderRadius: '3px',
color: activeTab === 'rx' ? '#60a5fa' : '#888',
cursor: 'pointer',
fontSize: '10px',
fontFamily: 'JetBrains Mono'
}}
>
📥 Hearing ({filterCount > 0 ? `${filteredRx.length}` : rxCount})
borderRadius: '3px', color: activeTab === 'rx' ? '#60a5fa' : '#888',
cursor: 'pointer', fontSize: '10px', fontFamily: 'JetBrains Mono'
}}>
📥 Hearing ({filterCount > 0 ? filteredRx.length : rxCount})
</button>
</div>
{/* Reports list */}
{/* PSK Reports list */}
{error && !connected ? (
<div style={{ textAlign: 'center', padding: '10px', color: 'var(--text-muted)', fontSize: '11px' }}>
Connection failed - click 🔄 to retry
@ -246,12 +278,7 @@ const PSKReporterPanel = ({
: 'No stations heard yet'}
</div>
) : (
<div style={{
flex: 1,
overflow: 'auto',
fontSize: '12px',
fontFamily: 'JetBrains Mono, monospace'
}}>
<div style={{ flex: 1, overflow: 'auto', fontSize: '12px', fontFamily: 'JetBrains Mono, monospace' }}>
{filteredReports.slice(0, 20).map((report, i) => {
const freqMHz = report.freqMHz || (report.freq ? (report.freq / 1000000).toFixed(3) : '?');
const color = getFreqColor(freqMHz);
@ -263,58 +290,171 @@ const PSKReporterPanel = ({
key={`${displayCall}-${report.freq}-${i}`}
onClick={() => onShowOnMap && report.lat && report.lon && onShowOnMap(report)}
style={{
display: 'grid',
gridTemplateColumns: '55px 1fr auto',
gap: '6px',
padding: '4px 6px',
borderRadius: '3px',
marginBottom: '2px',
display: 'grid', gridTemplateColumns: '55px 1fr auto',
gap: '6px', padding: '4px 6px', borderRadius: '3px', marginBottom: '2px',
background: i % 2 === 0 ? 'rgba(255,255,255,0.03)' : 'transparent',
cursor: report.lat && report.lon ? 'pointer' : 'default',
transition: 'background 0.15s',
borderLeft: '2px solid transparent'
transition: 'background 0.15s', borderLeft: '2px solid transparent'
}}
onMouseEnter={(e) => e.currentTarget.style.background = 'rgba(68, 136, 255, 0.15)'}
onMouseLeave={(e) => e.currentTarget.style.background = i % 2 === 0 ? 'rgba(255,255,255,0.03)' : 'transparent'}
>
<div style={{ color, fontWeight: '600', fontSize: '11px' }}>
{freqMHz}
</div>
<div style={{
color: 'var(--text-primary)',
fontWeight: '600',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
fontSize: '11px'
}}>
<div style={{ color, fontWeight: '600', fontSize: '11px' }}>{freqMHz}</div>
<div style={{ color: 'var(--text-primary)', fontWeight: '600', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontSize: '11px' }}>
{displayCall}
{grid && <span style={{ color: 'var(--text-muted)', fontWeight: '400', marginLeft: '4px', fontSize: '9px' }}>{grid}</span>}
</div>
<div style={{
display: 'flex',
alignItems: 'center',
gap: '4px',
fontSize: '10px'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '10px' }}>
<span style={{ color: 'var(--text-muted)' }}>{report.mode}</span>
{report.snr !== null && report.snr !== undefined && (
<span style={{
color: report.snr >= 0 ? '#4ade80' : report.snr >= -10 ? '#fbbf24' : '#f97316',
fontWeight: '600'
}}>
<span style={{ color: report.snr >= 0 ? '#4ade80' : report.snr >= -10 ? '#fbbf24' : '#f97316', fontWeight: '600' }}>
{report.snr > 0 ? '+' : ''}{report.snr}
</span>
)}
<span style={{ color: 'var(--text-muted)', fontSize: '9px' }}>
{formatAge(report.age)}
</span>
<span style={{ color: 'var(--text-muted)', fontSize: '9px' }}>{formatAge(report.age)}</span>
</div>
</div>
);
})}
</div>
)}
</>
)}
</>
)}
{/* === WSJT-X View === */}
{panelMode === 'wsjtx' && (
<>
{/* WSJT-X Tabs */}
<div style={{ display: 'flex', gap: '2px', marginBottom: '4px', flexShrink: 0 }}>
{[
{ key: 'decodes', label: `Decodes (${wsjtxDecodes.length})` },
{ key: 'qsos', label: `QSOs (${wsjtxQsos.length})` },
].map(tab => (
<button
key={tab.key}
onClick={() => setWsjtxTab(tab.key)}
style={{
flex: 1,
background: wsjtxTab === tab.key ? 'var(--bg-tertiary)' : 'transparent',
color: wsjtxTab === tab.key ? '#a78bfa' : 'var(--text-muted)',
border: 'none',
borderBottom: wsjtxTab === tab.key ? '2px solid #a78bfa' : '2px solid transparent',
fontSize: '10px', padding: '3px 6px', cursor: 'pointer',
borderRadius: '3px 3px 0 0',
}}
>
{tab.label}
</button>
))}
</div>
{/* No WSJT-X connected */}
{!wsjtxLoading && activeClients.length === 0 && wsjtxDecodes.length === 0 ? (
<div style={{
flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
flexDirection: 'column', gap: '6px', color: 'var(--text-muted)',
fontSize: '11px', textAlign: 'center', padding: '8px'
}}>
<div>Waiting for WSJT-X...</div>
<div style={{ fontSize: '10px', opacity: 0.7 }}>
Settings Reporting UDP Server
<br />
Address: {'{server IP}'} &nbsp; Port: {wsjtxPort || 2237}
</div>
</div>
) : (
<>
{/* Decodes / QSOs content */}
<div style={{
flex: 1, overflowY: 'auto', overflowX: 'hidden',
fontSize: '11px', fontFamily: "'JetBrains Mono', 'Fira Code', monospace",
}}>
{wsjtxTab === 'decodes' && (
<>
{filteredDecodes.length === 0 ? (
<div style={{ color: 'var(--text-muted)', textAlign: 'center', padding: '20px', fontSize: '11px' }}>
{wsjtxDecodes.length > 0 ? 'No decodes match filter' : 'Listening for decodes...'}
</div>
) : (
filteredDecodes.map((d, i) => (
<div
key={d.id || i}
style={{
display: 'flex', gap: '6px', padding: '2px 0',
borderBottom: '1px solid var(--border-color)',
alignItems: 'baseline',
opacity: d.lowConfidence ? 0.6 : 1,
}}
>
<span style={{ color: 'var(--text-muted)', minWidth: '48px', fontSize: '10px' }}>{d.time}</span>
<span style={{ color: getSnrColor(d.snr), minWidth: '28px', textAlign: 'right', fontSize: '10px' }}>
{d.snr != null ? (d.snr >= 0 ? `+${d.snr}` : d.snr) : ''}
</span>
<span style={{ color: 'var(--text-muted)', minWidth: '28px', textAlign: 'right', fontSize: '10px' }}>{d.dt}</span>
<span style={{
color: d.band ? getBandColor(d.dialFrequency / 1000000) : 'var(--text-muted)',
minWidth: '36px', textAlign: 'right', fontSize: '10px'
}}>{d.freq}</span>
<span style={{
color: getMsgColor(d), flex: 1, whiteSpace: 'nowrap',
overflow: 'hidden', textOverflow: 'ellipsis',
}}>{d.message}</span>
</div>
))
)}
</>
)}
{wsjtxTab === 'qsos' && (
<>
{wsjtxQsos.length === 0 ? (
<div style={{ color: 'var(--text-muted)', textAlign: 'center', padding: '20px', fontSize: '11px' }}>
No QSOs logged yet
</div>
) : (
[...wsjtxQsos].reverse().map((q, i) => (
<div key={i} style={{
display: 'flex', gap: '6px', padding: '3px 0',
borderBottom: '1px solid var(--border-color)', alignItems: 'baseline',
}}>
<span style={{ color: q.band ? getBandColor(q.frequency / 1000000) : 'var(--accent-green)', fontWeight: '600', minWidth: '70px' }}>
{q.dxCall}
</span>
<span style={{ color: 'var(--text-muted)', minWidth: '40px', fontSize: '10px' }}>{q.band}</span>
<span style={{ color: 'var(--text-muted)', minWidth: '30px', fontSize: '10px' }}>{q.mode}</span>
<span style={{ color: 'var(--text-muted)', fontSize: '10px' }}>{q.reportSent}/{q.reportRecv}</span>
{q.dxGrid && <span style={{ color: '#a78bfa', fontSize: '10px' }}>{q.dxGrid}</span>}
</div>
))
)}
</>
)}
</div>
{/* WSJT-X status bar */}
{activeClients.length > 0 && (
<div style={{
fontSize: '9px', color: 'var(--text-muted)',
borderTop: '1px solid var(--border-color)',
paddingTop: '3px', marginTop: '3px',
display: 'flex', justifyContent: 'space-between', flexShrink: 0
}}>
<span>
{activeClients.map(([id, c]) => `${id}${c.version ? ` v${c.version}` : ''}`).join(', ')}
</span>
{primaryClient?.dialFrequency && (
<span style={{ color: '#a78bfa' }}>
{(primaryClient.dialFrequency / 1000000).toFixed(6)} MHz
</span>
)}
</div>
)}
</>
)}
</>
)}
</div>
);
};

@ -27,12 +27,14 @@ export const WorldMap = ({
dxFilters,
satellites,
pskReporterSpots,
wsjtxSpots,
showDXPaths,
showDXLabels,
onToggleDXLabels,
showPOTA,
showSatellites,
showPSKReporter,
showWSJTX,
onToggleSatellites,
hoveredSpot
}) => {
@ -52,6 +54,7 @@ export const WorldMap = ({
const satMarkersRef = useRef([]);
const satTracksRef = useRef([]);
const pskMarkersRef = useRef([]);
const wsjtxMarkersRef = useRef([]);
const countriesLayerRef = useRef(null);
// Plugin system refs and state
@ -647,6 +650,87 @@ export const WorldMap = ({
}
}, [pskReporterSpots, showPSKReporter, deLocation]);
// Update WSJT-X markers (CQ callers with grid locators)
useEffect(() => {
if (!mapInstanceRef.current) return;
const map = mapInstanceRef.current;
wsjtxMarkersRef.current.forEach(m => map.removeLayer(m));
wsjtxMarkersRef.current = [];
const hasValidDE = deLocation &&
typeof deLocation.lat === 'number' && !isNaN(deLocation.lat) &&
typeof deLocation.lon === 'number' && !isNaN(deLocation.lon);
if (showWSJTX && wsjtxSpots && wsjtxSpots.length > 0 && hasValidDE) {
// Deduplicate by callsign - keep most recent
const seen = new Map();
wsjtxSpots.forEach(spot => {
const call = spot.caller || spot.dxCall || '';
if (call && (!seen.has(call) || spot.timestamp > seen.get(call).timestamp)) {
seen.set(call, spot);
}
});
seen.forEach((spot, call) => {
let spotLat = parseFloat(spot.lat);
let spotLon = parseFloat(spot.lon);
if (!isNaN(spotLat) && !isNaN(spotLon)) {
const freqMHz = spot.dialFrequency ? (spot.dialFrequency / 1000000) : 0;
const bandColor = freqMHz ? getBandColor(freqMHz) : '#a78bfa';
try {
// Draw line from DE to CQ caller
const points = getGreatCirclePoints(
deLocation.lat, deLocation.lon,
spotLat, spotLon,
50
);
if (points && Array.isArray(points) && points.length > 1 &&
points.every(p => Array.isArray(p) && !isNaN(p[0]) && !isNaN(p[1]))) {
const line = L.polyline(points, {
color: '#a78bfa',
weight: 1.5,
opacity: 0.4,
dashArray: '2, 6'
}).addTo(map);
wsjtxMarkersRef.current.push(line);
const endPoint = points[points.length - 1];
spotLat = endPoint[0];
spotLon = endPoint[1];
}
// Diamond-shaped marker to distinguish from PSK circles
const diamond = L.marker([spotLat, spotLon], {
icon: L.divIcon({
className: '',
html: `<div style="
width: 8px; height: 8px;
background: ${bandColor};
border: 1px solid #fff;
transform: rotate(45deg);
opacity: 0.9;
"></div>`,
iconSize: [8, 8],
iconAnchor: [4, 4]
})
}).bindPopup(`
<b>${call}</b> CQ<br>
${spot.grid || ''} ${spot.band || ''}<br>
${spot.mode || ''} SNR: ${spot.snr != null ? (spot.snr >= 0 ? '+' : '') + spot.snr : '?'} dB
`).addTo(map);
wsjtxMarkersRef.current.push(diamond);
} catch (err) {
// skip bad spots
}
}
});
}
}, [wsjtxSpots, showWSJTX, deLocation]);
return (
<div style={{ position: 'relative', height: '100%', minHeight: '200px' }}>
<div ref={mapRef} style={{ height: '100%', width: '100%', borderRadius: '8px', background: mapStyle === 'countries' ? '#4a90d9' : undefined }} />

@ -16,3 +16,4 @@ export { useDXpeditions } from './useDXpeditions.js';
export { useSatellites } from './useSatellites.js';
export { useSolarIndices } from './useSolarIndices.js';
export { usePSKReporter } from './usePSKReporter.js';
export { useWSJTX } from './useWSJTX.js';

@ -0,0 +1,104 @@
/**
* useWSJTX Hook
* Polls the server for WSJT-X UDP data (decoded messages, status, QSOs)
*
* WSJT-X sends decoded FT8/FT4/JT65/WSPR messages over UDP.
* The server listens on the configured port and this hook fetches the results.
*/
import { useState, useEffect, useCallback, useRef } from 'react';
const POLL_INTERVAL = 2000; // Poll every 2 seconds for near-real-time feel
const API_URL = '/api/wsjtx';
const DECODES_URL = '/api/wsjtx/decodes';
export function useWSJTX(enabled = true) {
const [data, setData] = useState({
clients: {},
decodes: [],
qsos: [],
wspr: [],
stats: { totalDecodes: 0, totalQsos: 0, totalWspr: 0, activeClients: 0 },
enabled: false,
port: 2237,
});
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const lastTimestamp = useRef(0);
const fullFetchCounter = useRef(0);
// Lightweight poll - just new decodes since last check
const pollDecodes = useCallback(async () => {
if (!enabled) return;
try {
const url = lastTimestamp.current
? `${DECODES_URL}?since=${lastTimestamp.current}`
: DECODES_URL;
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const json = await res.json();
if (json.decodes?.length > 0) {
setData(prev => {
// Merge new decodes, dedup by id, keep last 200
const existing = new Set(prev.decodes.map(d => d.id));
const newDecodes = json.decodes.filter(d => !existing.has(d.id));
if (newDecodes.length === 0) return prev;
const merged = [...prev.decodes, ...newDecodes].slice(-200);
return { ...prev, decodes: merged, stats: { ...prev.stats, totalDecodes: merged.length } };
});
}
lastTimestamp.current = json.timestamp || Date.now();
setError(null);
} catch (e) {
// Silent fail for lightweight polls
}
}, [enabled]);
// Full fetch - get everything including status, QSOs, clients
const fetchFull = useCallback(async () => {
if (!enabled) return;
try {
const res = await fetch(API_URL);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const json = await res.json();
setData(json);
lastTimestamp.current = Date.now();
setLoading(false);
setError(null);
} catch (e) {
setError(e.message);
setLoading(false);
}
}, [enabled]);
// Initial full fetch
useEffect(() => {
if (enabled) fetchFull();
}, [enabled, fetchFull]);
// Polling - mostly lightweight, full refresh every 15s
useEffect(() => {
if (!enabled) return;
const interval = setInterval(() => {
fullFetchCounter.current++;
if (fullFetchCounter.current >= 8) { // Every ~16 seconds
fullFetchCounter.current = 0;
fetchFull();
} else {
pollDecodes();
}
}, POLL_INTERVAL);
return () => clearInterval(interval);
}, [enabled, fetchFull, pollDecodes]);
return {
...data,
loading,
error,
refresh: fetchFull,
};
}
Loading…
Cancel
Save

Powered by TurnKey Linux.