forked from accius/openhamclock
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseContestQsos.js
More file actions
204 lines (176 loc) · 6.33 KB
/
useContestQsos.js
File metadata and controls
204 lines (176 loc) · 6.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import { useEffect, useRef, useState } from 'react';
import { esc } from '../../utils/escapeHtml.js';
import { getBandColor, getBandFromFreq } from '../../utils/callsign.js';
import { getGreatCirclePoints, replicatePath, replicatePoint } from '../../utils/geo.js';
export const metadata = {
id: 'contest_qsos',
name: 'Contest QSOs',
description: 'Recent QSOs from contest loggers (N1MM/DXLog)',
icon: 'QSO',
category: 'amateur',
defaultEnabled: false,
defaultOpacity: 0.7,
version: '1.0.0',
};
const normalizeBandKey = (band) => {
if (band == null) return null;
const raw = String(band).trim().toLowerCase();
if (!raw || raw === 'other') return null;
if (raw.endsWith('cm') || raw.endsWith('m')) return raw;
if (/^\d+(\.\d+)?$/.test(raw)) return `${raw}m`;
return raw;
};
const bandFromAnyFrequency = (freq) => {
if (freq == null || freq === '') return null;
const n = parseFloat(freq);
if (!Number.isFinite(n) || n <= 0) return null;
return normalizeBandKey(getBandFromFreq(n));
};
const findLatestLocatedQso = (qsos) => {
for (let i = qsos.length - 1; i >= 0; i -= 1) {
const qso = qsos[i];
const lat = parseFloat(qso?.lat);
const lon = parseFloat(qso?.lon);
if (Number.isFinite(lat) && Number.isFinite(lon)) {
return { qso, lat, lon };
}
}
return null;
};
export function useLayer({ enabled = false, opacity = 0.7, map = null, onDXChange, mapBandFilter }) {
const [qsos, setQsos] = useState([]);
const [deLocation, setDeLocation] = useState(null);
const markersRef = useRef([]);
const linesRef = useRef([]);
const pollRef = useRef(null);
const configLoadedRef = useRef(false);
const lastHandledTargetKeyRef = useRef(null);
useEffect(() => {
if (!enabled || configLoadedRef.current) return;
const loadConfig = async () => {
try {
const res = await fetch('/api/config');
if (!res.ok) return;
const data = await res.json();
if (Number.isFinite(data.latitude) && Number.isFinite(data.longitude)) {
setDeLocation({ lat: data.latitude, lon: data.longitude, callsign: data.callsign || '' });
configLoadedRef.current = true;
}
} catch (e) {
// ignore
}
};
loadConfig();
}, [enabled]);
useEffect(() => {
if (!enabled) return;
const fetchQsos = async () => {
try {
const res = await fetch('/api/contest/qsos?limit=200');
if (!res.ok) return;
const data = await res.json();
setQsos(Array.isArray(data.qsos) ? data.qsos : []);
} catch (e) {
// ignore
}
};
fetchQsos();
pollRef.current = setInterval(fetchQsos, 5000);
return () => {
if (pollRef.current) {
clearInterval(pollRef.current);
pollRef.current = null;
}
};
}, [enabled]);
useEffect(() => {
if (!enabled) {
lastHandledTargetKeyRef.current = null;
}
}, [enabled]);
useEffect(() => {
if (!enabled || typeof onDXChange !== 'function') return;
const latestLocated = findLatestLocatedQso(qsos);
if (!latestLocated) return;
const { qso: latestLocatedQso, lat, lon } = latestLocated;
const targetKey =
latestLocatedQso.id ||
`${latestLocatedQso.timestamp || ''}:${latestLocatedQso.dxCall || ''}:${lat.toFixed(4)}:${lon.toFixed(4)}`;
if (lastHandledTargetKeyRef.current === targetKey) return;
// Remember handled QSOs even while DX is locked so unlocking later
// does not retroactively replay an older contest contact.
lastHandledTargetKeyRef.current = targetKey;
onDXChange({ lat, lon });
}, [enabled, qsos, onDXChange]);
useEffect(() => {
if (!map || typeof L === 'undefined') return;
linesRef.current.forEach((line) => {
try {
map.removeLayer(line);
} catch (e) {}
});
markersRef.current.forEach((marker) => {
try {
map.removeLayer(marker);
} catch (e) {}
});
linesRef.current = [];
markersRef.current = [];
if (!enabled || qsos.length === 0) return;
const selectedMapBands = Array.isArray(mapBandFilter)
? new Set(mapBandFilter.map((b) => normalizeBandKey(b)).filter(Boolean))
: new Set();
const hasMapBandFilter = selectedMapBands.size > 0;
const recent = qsos.slice(-120);
const de = deLocation;
recent.forEach((qso) => {
const lat = parseFloat(qso.lat);
const lon = parseFloat(qso.lon);
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return;
const freqMHz = qso.freqMHz || qso.bandMHz || qso.band;
const band = normalizeBandKey(qso.band) || bandFromAnyFrequency(freqMHz || qso.freq_khz);
if (hasMapBandFilter && (!band || !selectedMapBands.has(band))) return;
const bandColor = freqMHz ? getBandColor(parseFloat(freqMHz)) : '#22c55e';
const lineOpacity = Math.max(0.15, Math.min(0.7, opacity * 0.35));
const markerOpacity = Math.max(0.2, Math.min(0.9, opacity));
if (de && Number.isFinite(de.lat) && Number.isFinite(de.lon)) {
const points = getGreatCirclePoints(de.lat, de.lon, lat, lon, 50);
if (Array.isArray(points) && points.length > 1) {
replicatePath(points).forEach((copy) => {
const line = L.polyline(copy, {
color: bandColor,
weight: 1.5,
opacity: lineOpacity,
dashArray: '2, 6',
}).addTo(map);
linesRef.current.push(line);
});
}
}
const bandLabel = qso.bandMHz ? `${qso.bandMHz} MHz` : qso.band || '';
const timeLabel = qso.time || (qso.timestamp ? new Date(qso.timestamp).toLocaleTimeString() : '');
const sourceLabel = qso.source ? qso.source.toUpperCase() : '';
replicatePoint(lat, lon).forEach(([rLat, rLon]) => {
const marker = L.circleMarker([rLat, rLon], {
radius: 5,
fillColor: bandColor,
color: '#fff',
weight: 1,
opacity: 0.9,
fillOpacity: markerOpacity,
})
.bindPopup(
`
<b>${esc(qso.dxCall || '')}</b><br>
${esc(qso.mode || '')} ${esc(bandLabel)}<br>
${timeLabel ? `${esc(timeLabel)}<br>` : ''}
${esc(sourceLabel)}
`,
)
.addTo(map);
markersRef.current.push(marker);
});
});
}, [qsos, enabled, opacity, map, deLocation, mapBandFilter]);
return { layer: markersRef.current };
}