Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f3f966f5b7 | ||
|
|
38c838d232 | ||
|
|
7eb734d86f | ||
|
|
b49599150c | ||
|
|
331db58705 | ||
|
|
62e20de69c | ||
|
|
480d24384b | ||
|
|
c2ff0f714a | ||
|
|
fe2affc72f | ||
|
|
be0326c862 | ||
|
|
8113557015 | ||
|
|
3def789742 | ||
|
|
92ea98bcfa |
@@ -57,9 +57,9 @@ import (
|
||||
"hamlog/internal/relaydev"
|
||||
"hamlog/internal/rigctld"
|
||||
"hamlog/internal/rotator/dcu1"
|
||||
"hamlog/internal/rotator/spid"
|
||||
"hamlog/internal/rotator/gs232"
|
||||
"hamlog/internal/rotator/pst"
|
||||
"hamlog/internal/rotator/spid"
|
||||
"hamlog/internal/rotgenius"
|
||||
"hamlog/internal/scp"
|
||||
"hamlog/internal/settings"
|
||||
@@ -14120,8 +14120,9 @@ func (a *App) ActivateProfile(id int64) error {
|
||||
|
||||
// reloadAfterProfileSwitch re-applies all settings-derived state for the newly
|
||||
// active profile: lookup providers, upload-service accounts, CAT connection,
|
||||
// and the QSO recorder (audio devices). The Winkeyer stays as-is (the operator
|
||||
// connects it explicitly). The frontend reloads its panels via profile:changed.
|
||||
// the station hardware, and the QSO recorder (audio devices). The Winkeyer
|
||||
// stays as-is (the operator connects it explicitly). The frontend reloads its
|
||||
// panels via profile:changed.
|
||||
func (a *App) reloadAfterProfileSwitch() {
|
||||
a.reloadLookupProviders()
|
||||
if a.extsvc != nil {
|
||||
@@ -14131,6 +14132,21 @@ func (a *App) reloadAfterProfileSwitch() {
|
||||
// runs from ActivateProfile, a click, and a rig that is slow to release would
|
||||
// otherwise freeze the switch.
|
||||
a.restartAsync("cat", a.reloadCAT)
|
||||
// Every device below is configured PER PROFILE, and none of them used to
|
||||
// follow the profile: they were built once at startup and again only when
|
||||
// Settings was saved. An operator with an SPE on COM9 for HF and another on
|
||||
// COM10 for 6 m — one amplifier per profile, which is the whole point of
|
||||
// having two — switched profile and stayed connected to the previous port,
|
||||
// then had to open Settings and press Save to get the right one. Save is not
|
||||
// a connect button; switching profile is what asks for this hardware.
|
||||
//
|
||||
// Unconditional, exactly as a save is: the alternative is comparing every
|
||||
// device's configuration between profiles, and a needless reconnect on a
|
||||
// profile switch costs a second, while a missed one costs the amplifier.
|
||||
a.restartAsync("amp", a.startAmps)
|
||||
a.restartAsync("antenna", a.startUltrabeam)
|
||||
a.restartAsync("antgenius", a.startAntGenius)
|
||||
a.restartAsync("tuner", a.startTunerGenius)
|
||||
a.startQSORecorderIfEnabled()
|
||||
}
|
||||
|
||||
@@ -14757,6 +14773,13 @@ func buildDeviceDriver(d StationDevice) relaydev.Device {
|
||||
case "usbrelay":
|
||||
// Host carries the COM port (e.g. "COM5"); CH340/LCUS "A0" serial protocol.
|
||||
return relaydev.NewSerialRelay(d.Host, deviceRelayCount(d))
|
||||
case "httpgen":
|
||||
// The whole board lives in its URLs — Host is not used at all, which is
|
||||
// why it may be left empty. Leaving this case out is what made the
|
||||
// generic board fall through to the WebSwitch driver below: it answered
|
||||
// the WebSwitch's own address, never sent one configured URL, and
|
||||
// reported itself offline so every relay button stayed greyed out.
|
||||
return relaydev.NewHTTPGeneric(d.OnURLs, d.OffURLs, d.OnPat, d.OffPat, d.User, d.Pass, deviceRelayCount(d), d.Labels)
|
||||
default:
|
||||
return relaydev.NewWebswitch(d.Host)
|
||||
}
|
||||
@@ -14765,7 +14788,20 @@ func buildDeviceDriver(d StationDevice) relaydev.Device {
|
||||
// deviceKey is the config signature that, when unchanged, lets us reuse a device's
|
||||
// open driver (and its OS handle) instead of rebuilding it every poll.
|
||||
func deviceKey(d StationDevice) string {
|
||||
return fmt.Sprintf("%s|%s|%s|%s|%d", d.Type, d.Host, d.User, d.Pass, deviceRelayCount(d))
|
||||
k := fmt.Sprintf("%s|%s|%s|%s|%d", d.Type, d.Host, d.User, d.Pass, deviceRelayCount(d))
|
||||
if d.Type == "httpgen" {
|
||||
// The generic board's entire configuration is its URLs, and none of it is
|
||||
// in the signature above. Correcting a typo in one of them would have
|
||||
// handed back the cached driver still holding the wrong address, so the
|
||||
// fix appeared to do nothing until OpsLog was restarted.
|
||||
k += "|" + d.OnPat + "|" + d.OffPat +
|
||||
"|" + strings.Join(d.OnURLs, "\x1f") + "|" + strings.Join(d.OffURLs, "\x1f") +
|
||||
// The labels are part of the wire format here: {value} sends them.
|
||||
// Renaming a relay re-addresses it, and the cached driver would keep
|
||||
// commanding the old name.
|
||||
"|" + strings.Join(d.Labels, "\x1f")
|
||||
}
|
||||
return k
|
||||
}
|
||||
|
||||
// driverFor returns the cached, still-open driver for a device, building it once
|
||||
@@ -15864,13 +15900,24 @@ func (a *App) restartMotorFollow(s UltrabeamSettings) {
|
||||
close(a.ubFollowStop)
|
||||
a.ubFollowStop = nil
|
||||
}
|
||||
if !s.Follow || a.motorAnt == nil {
|
||||
applog.Printf("ultrabeam: follow loop stopped")
|
||||
// Say WHICH of the two reasons it is. "follow loop stopped" covered both, and
|
||||
// at startup — where nothing was running to stop — it read as a fault. An
|
||||
// operator whose antenna sat at 21050 while the rig worked 21074 sent a log
|
||||
// that said the antenna had started, answered every poll, and had its follow
|
||||
// loop "stopped": three lines that together looked like a link going dead,
|
||||
// when tracking was simply switched off and the antenna was waiting to be
|
||||
// tuned by hand.
|
||||
if a.motorAnt == nil {
|
||||
applog.Printf("antenna: tracking not started — no antenna connected")
|
||||
return
|
||||
}
|
||||
if !s.Follow {
|
||||
applog.Printf("antenna: %s connected, but TRACKING IS OFF in Settings — it will not follow the rig, and only moves when you tune it by hand", s.Type)
|
||||
return
|
||||
}
|
||||
stop := make(chan struct{})
|
||||
a.ubFollowStop = stop
|
||||
applog.Printf("ultrabeam: follow loop restarting — covered bands %v, mode %s, step %d kHz", s.Bands, normMotorTrackMode(s.TrackMode), s.StepKHz)
|
||||
applog.Printf("antenna: %s tracking the rig — covered bands %v, mode %s, step %d kHz", s.Type, s.Bands, normMotorTrackMode(s.TrackMode), s.StepKHz)
|
||||
go a.ultrabeamFollowLoop(a.motorAnt, s.TrackMode, s.StepKHz, s.Bands, stop)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,36 @@
|
||||
[
|
||||
{
|
||||
"version": "0.25.5",
|
||||
"date": "",
|
||||
"en": [
|
||||
"DX cluster: when spots arrive and every one is filtered out, the panel says so, names the filters doing it and offers to clear them — it used to say “waiting for spots” beside a counter reading 76 live.",
|
||||
"DX cluster: the log times the connection and the first spot, so a slow first launch can be told apart from a quiet node.",
|
||||
"Generic HTTP relay: its URLs were never actually sent — fixed. {value} sends the relay's label, {relay-1} counts from zero, no host needed.",
|
||||
"Switching profile now reconnects the amplifier, antenna, Antenna Genius and tuner — they stayed on the previous profile's ports until you saved Settings.",
|
||||
"SteppIR: one missed reply used to wedge the link — the antenna stopped responding, with nothing at all in the log. It now recovers on its own.",
|
||||
"The log now says when a motorized antenna is connected but tracking is off, instead of a line that read like a fault.",
|
||||
"DXHunter spot clicks tune the rig again: the frequency it sends is read in whatever unit it uses, not always as MHz."
|
||||
],
|
||||
"fr": [
|
||||
"Cluster DX : quand des spots arrivent et que tout est filtré, le panneau le dit, nomme les filtres responsables et propose de les effacer — il affichait « en attente de spots » à côté d’un compteur à 76 en direct.",
|
||||
"Cluster DX : le journal chronomètre la connexion et le premier spot, pour distinguer un premier lancement lent d’un nœud silencieux.",
|
||||
"Relais HTTP générique : ses URL n’étaient jamais envoyées — corrigé. {value} envoie le libellé du relais, {relay-1} compte de zéro, hôte inutile.",
|
||||
"Changer de profil reconnecte l’ampli, l’antenne, l’Antenna Genius et le tuner — ils restaient sur les ports du profil précédent jusqu’à un Enregistrer.",
|
||||
"SteppIR : une seule réponse manquée bloquait la liaison — l’antenne ne répondait plus, sans rien dans le journal. Elle se rétablit maintenant seule.",
|
||||
"Le journal indique désormais qu’une antenne motorisée est connectée mais que le suivi est désactivé, au lieu d’une ligne qui ressemblait à une panne.",
|
||||
"Les clics de spot DXHunter accordent à nouveau le rig : la fréquence envoyée est lue dans son unité réelle, plus toujours en MHz."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.25.4",
|
||||
"date": "",
|
||||
"en": [
|
||||
"WinKeyer: the opening probe goes out as one write, matching a capture of a client that talks to the same K3NG keyer, and the handshake bytes are always logged so a keyer that stays silent can be diagnosed."
|
||||
],
|
||||
"fr": [
|
||||
"WinKeyer : la sonde d’ouverture part en un seul envoi, calquée sur la capture d’un client qui dialogue avec le même manipulateur K3NG, et les octets de la poignée de main sont toujours journalisés pour diagnostiquer un manipulateur muet."
|
||||
]
|
||||
},
|
||||
{
|
||||
"version": "0.25.3",
|
||||
"date": "",
|
||||
|
||||
+64
-2
@@ -1539,6 +1539,41 @@ export default function App() {
|
||||
// Hide spots already worked (exact call worked, or this band+mode slot done).
|
||||
const [clusterHideWorked, setClusterHideWorked] = useState(() => lsBool('opslog.clusterHideWorked', false));
|
||||
|
||||
// Everything currently narrowing the spot list, in words. Shown when spots
|
||||
// arrived and none survived — the operator needs to know WHICH filter to
|
||||
// loosen, and the two locks are the least memorable because they follow the
|
||||
// rig rather than a click.
|
||||
const clusterActiveFilterSummary = useMemo(() => {
|
||||
const on: string[] = [];
|
||||
if (clusterLockBand) on.push(t('clg2.fBandLock'));
|
||||
else if (clusterBands.size > 0) on.push(t('clg2.fBands', { list: [...clusterBands].join(', ') }));
|
||||
if (clusterLockMode) on.push(t('clg2.fModeLock'));
|
||||
else if (clusterModeFilter.size > 0) on.push(t('clg2.fModes', { list: [...clusterModeFilter].join(', ') }));
|
||||
if (clusterStatusFilter.size > 0) on.push(t('clg2.fStatus'));
|
||||
if (clusterHideWorked) on.push(t('clg2.fHideWorked'));
|
||||
if (clusterLotwOnly) on.push(t('clg2.fLotwOnly'));
|
||||
if (clusterSpotterConts.size > 0) on.push(t('clg2.fSpotterCont'));
|
||||
if (clusterFilterSource) on.push(t('clg2.fSource'));
|
||||
if (clusterSearch.trim()) on.push(t('clg2.fSearch', { q: clusterSearch.trim() }));
|
||||
return on.join(' · ');
|
||||
}, [t, clusterLockBand, clusterBands, clusterLockMode, clusterModeFilter, clusterStatusFilter,
|
||||
clusterHideWorked, clusterLotwOnly, clusterSpotterConts, clusterFilterSource, clusterSearch]);
|
||||
|
||||
// Undo every one of them at once. A list of ten switches spread down a panel
|
||||
// is not something to walk back by hand when the answer is "show me anything".
|
||||
const clearClusterFilters = useCallback(() => {
|
||||
setClusterLockBand(false);
|
||||
setClusterBands(new Set());
|
||||
setClusterLockMode(false);
|
||||
setClusterModeFilter(new Set());
|
||||
setClusterStatusFilter(new Set());
|
||||
setClusterHideWorked(false);
|
||||
setClusterLotwOnly(false);
|
||||
setClusterSpotterConts(new Set());
|
||||
setClusterFilterSource('');
|
||||
setClusterSearch('');
|
||||
}, []);
|
||||
|
||||
// Persist every cluster filter selection whenever it changes, so it is still
|
||||
// set after a close/reopen.
|
||||
useEffect(() => {
|
||||
@@ -6738,14 +6773,41 @@ export default function App() {
|
||||
// pane). All the filter state lives in the right-side panel.
|
||||
const rendered = clusterRenderedRows;
|
||||
if (rendered.length === 0) {
|
||||
const connected = clusterServerStatuses.some((s) => s.state === 'connected');
|
||||
// Spots HAVE arrived and the filters ate every one of them.
|
||||
//
|
||||
// This used to say "Waiting for spots…" regardless, which is a
|
||||
// lie the moment the counter beside it reads 76 live: an
|
||||
// operator reads the two together and goes looking for a
|
||||
// connection fault instead of at the filter panel. The band and
|
||||
// mode locks are the usual culprits and the least visible —
|
||||
// they follow the rig, so nobody remembers switching them on.
|
||||
if (connected && spots.length > 0) {
|
||||
return (
|
||||
<div className="flex-1 flex flex-col items-center justify-center text-muted-foreground gap-2 py-12 px-6 text-center">
|
||||
<SlidersHorizontal className="size-10 opacity-30" />
|
||||
<div className="text-sm font-semibold text-foreground/70">
|
||||
{t('clg2.allFiltered', { n: spots.length })}
|
||||
</div>
|
||||
{clusterActiveFilterSummary && (
|
||||
<div className="text-xs max-w-md leading-relaxed">
|
||||
{t('clg2.activeFilters')} <span className="font-medium text-foreground/80">{clusterActiveFilterSummary}</span>
|
||||
</div>
|
||||
)}
|
||||
<Button size="sm" variant="outline" className="mt-1" onClick={clearClusterFilters}>
|
||||
{t('clg2.clearAllFilters')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="flex-1 flex flex-col items-center justify-center text-muted-foreground gap-2 py-12">
|
||||
<Hash className="size-10 opacity-30" />
|
||||
<div className="text-sm font-semibold text-foreground/70">
|
||||
{clusterServerStatuses.some((s) => s.state === 'connected') ? 'Waiting for spots…' : 'No active connection'}
|
||||
{connected ? 'Waiting for spots…' : 'No active connection'}
|
||||
</div>
|
||||
<div className="text-xs">
|
||||
{clusterServerStatuses.some((s) => s.state === 'connected')
|
||||
{connected
|
||||
? 'Spots will appear as the cluster sends them.'
|
||||
: 'Use Connect all (or configure a cluster in Settings → DX Cluster).'}
|
||||
</div>
|
||||
|
||||
@@ -527,16 +527,25 @@ export function StationControlPanel({ centerLat, centerLon, bearing }: RotatorPr
|
||||
const deviceCard = (dev: Device) => {
|
||||
const st = status[dev.id];
|
||||
const relays = st?.relays ?? dev.labels.map((label, i) => ({ number: i + 1, label, on: false }));
|
||||
// The generic HTTP board has no address of its own and nothing to poll: its
|
||||
// relays can each live on a different box, and no status endpoint is read
|
||||
// back. So no host under the name, no online dot, and the buttons are never
|
||||
// greyed out waiting for a connection that is never made.
|
||||
const fireAndForget = dev.type === 'httpgen';
|
||||
return (
|
||||
<div className="rounded-xl border border-border bg-card shadow-sm overflow-hidden h-full">
|
||||
<div className="flex items-center gap-2 px-3 py-2 border-b border-border/60 bg-muted/30">
|
||||
<PlugZap className="size-4 text-primary" />
|
||||
<div className="min-w-0">
|
||||
<div className="text-sm font-semibold truncate">{dev.name || TYPE_LABEL[dev.type]}</div>
|
||||
<div className="text-[10px] text-muted-foreground font-mono truncate">{TYPE_LABEL[dev.type]} · {dev.host}</div>
|
||||
<div className="text-[10px] text-muted-foreground font-mono truncate">
|
||||
{TYPE_LABEL[dev.type]}{fireAndForget || !dev.host ? '' : ` · ${dev.host}`}
|
||||
</div>
|
||||
</div>
|
||||
{fireAndForget ? <span className="ml-auto" /> : (
|
||||
<span className={cn('ml-auto size-2 rounded-full shrink-0', st?.connected ? 'bg-success' : 'bg-muted-foreground/40')}
|
||||
title={st?.connected ? t('station.online') : (st?.error || t('station.offline'))} />
|
||||
)}
|
||||
<button className="text-muted-foreground hover:text-foreground" title={t('station.edit')}
|
||||
onClick={() => setEditing({ ...dev, labels: [...dev.labels] })}><Pencil className="size-3.5" /></button>
|
||||
<button className="text-muted-foreground hover:text-destructive" title={t('station.delete')}
|
||||
@@ -549,7 +558,7 @@ export function StationControlPanel({ centerLat, centerLon, bearing }: RotatorPr
|
||||
const key = `${dev.id}:${r.number}`;
|
||||
const label = r.label || `${t('station.relay')} ${r.number}`;
|
||||
return (
|
||||
<button key={r.number} type="button" disabled={!st?.connected}
|
||||
<button key={r.number} type="button" disabled={!fireAndForget && !st?.connected}
|
||||
title={label}
|
||||
onClick={() => toggle(dev, r.number, !r.on)}
|
||||
className={cn('w-[150px] flex items-center gap-1.5 rounded-md border px-2 py-1 text-left transition-colors disabled:opacity-40',
|
||||
@@ -687,6 +696,13 @@ function DeviceEditor({ device, onChange, onSave, onCancel, t }: {
|
||||
const isDenkovi = device.type === 'denkovi';
|
||||
const isUsbRelay = device.type === 'usbrelay';
|
||||
const isHTTPGen = device.type === 'httpgen';
|
||||
// {value} sends a relay's label, so a URL using it on an unnamed relay would
|
||||
// go out with an empty parameter. Warn while it is being typed rather than at
|
||||
// the moment an antenna fails to switch.
|
||||
const valueNeedsLabels = isHTTPGen
|
||||
&& [...(device.on_urls ?? []), ...(device.off_urls ?? []), device.on_pattern ?? '', device.off_pattern ?? '']
|
||||
.some((s) => (s ?? '').includes('{value}'))
|
||||
&& device.labels.some((l) => !l.trim());
|
||||
// COM ports for the generic USB-serial relay picker.
|
||||
const [serialPorts, setSerialPorts] = useState<string[]>([]);
|
||||
useEffect(() => {
|
||||
@@ -795,7 +811,12 @@ function DeviceEditor({ device, onChange, onSave, onCancel, t }: {
|
||||
</div>
|
||||
<p className="text-[10px] text-muted-foreground">{t('station.usbRelayHint')}</p>
|
||||
</div>
|
||||
) : (
|
||||
) : isHTTPGen ? null : (
|
||||
/* No Host for the generic board: its driver never reads one. Each URL
|
||||
below carries its own address, and they need not even share it — one
|
||||
relay can sit on a different box from the next. A field that changes
|
||||
nothing is worse than no field: it reads as the thing to fill in first,
|
||||
and then the URLs look like they should be relative to it. */
|
||||
<div className={cn('grid gap-3', (isKM || isDingtian) ? 'grid-cols-3' : 'grid-cols-1')}>
|
||||
<div className={cn('space-y-1', (isKM || isDingtian) ? '' : 'max-w-xs')}>
|
||||
<Label>{t('station.host')}</Label>
|
||||
@@ -886,6 +907,10 @@ function DeviceEditor({ device, onChange, onSave, onCancel, t }: {
|
||||
|
||||
<div className="space-y-1">
|
||||
<Label>{t('station.labels')}</Label>
|
||||
{/* {value} sends the label, so an unnamed relay would go out as "?on=".
|
||||
Said here, beside the empty box, rather than when the antenna fails
|
||||
to switch and the log is the only place that explains why. */}
|
||||
{valueNeedsLabels && <p className="text-[10px] text-warning">{t('station.valueNeedsLabels')}</p>}
|
||||
<div className="grid grid-cols-4 gap-2">
|
||||
{device.labels.map((lab, i) => (
|
||||
<Input key={i} value={lab} placeholder={`${t('station.relay')} ${i + 1}`} className="h-8 text-xs"
|
||||
@@ -901,12 +926,20 @@ function DeviceEditor({ device, onChange, onSave, onCancel, t }: {
|
||||
</span>
|
||||
)}
|
||||
<div className="ml-auto flex gap-2">
|
||||
{/* No connection test for the generic board, and no host required to
|
||||
save it. There is nothing to test: it has no address of its own and
|
||||
no status to read — its URLs are fired and forgotten. A button that
|
||||
can only ever say "OK, 4 relays" tests nothing, and a Save greyed
|
||||
out for a missing host made a perfectly complete configuration —
|
||||
four full URLs — impossible to store. */}
|
||||
{!isHTTPGen && (
|
||||
<Button size="sm" variant="outline" onClick={testDevice} disabled={testing || !device.host.trim()}>
|
||||
{testing ? <Loader2 className="size-3.5 mr-1 animate-spin" /> : <PlugZap className="size-3.5 mr-1" />}
|
||||
{t('station.test')}
|
||||
</Button>
|
||||
)}
|
||||
<Button size="sm" variant="ghost" onClick={onCancel}><X className="size-3.5 mr-1" />{t('station.cancel')}</Button>
|
||||
<Button size="sm" onClick={onSave} disabled={!device.host.trim()}><Check className="size-3.5 mr-1" />{t('station.save')}</Button>
|
||||
<Button size="sm" onClick={onSave} disabled={!isHTTPGen && !device.host.trim()}><Check className="size-3.5 mr-1" />{t('station.save')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,6 +1,6 @@
|
||||
// Single source of truth for the app version shown in the UI (header + About).
|
||||
// Bump this on a release (the release script updates it alongside telemetry.go).
|
||||
export const APP_VERSION = '0.25.3';
|
||||
export const APP_VERSION = '0.25.5';
|
||||
|
||||
// Author / credits, shown in Help -> About.
|
||||
export const APP_AUTHOR = 'F4BPO';
|
||||
|
||||
@@ -369,10 +369,21 @@ func (s *session) runOnce() (time.Time, error) {
|
||||
// failure surfaces as an error on Read — which is the only thing that ends
|
||||
// a session below.
|
||||
d := net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}
|
||||
// TIMED, and reported. An operator sees "connected" and no spots for a
|
||||
// minute on the first launch, then an instant connection when the program is
|
||||
// restarted — which is the signature of a slow name resolution rather than a
|
||||
// slow cluster (the OS caches the answer, so the second run skips it). The
|
||||
// only way to tell that from a node that simply had nothing to say is to
|
||||
// know how long the dial itself took.
|
||||
dialStart := time.Now()
|
||||
conn, err := d.Dial("tcp", addr)
|
||||
if err != nil {
|
||||
applog.Printf("cluster[%s] dial %s failed after %s: %v", s.cfg.Name, addr, time.Since(dialStart).Round(time.Millisecond), err)
|
||||
return time.Time{}, fmt.Errorf("dial %s: %w", addr, err)
|
||||
}
|
||||
applog.Printf("cluster[%s] connected to %s in %s", s.cfg.Name, addr, time.Since(dialStart).Round(time.Millisecond))
|
||||
linkUpAt := time.Now()
|
||||
firstSpotLogged := false
|
||||
s.mu.Lock()
|
||||
s.conn = conn
|
||||
s.mu.Unlock()
|
||||
@@ -556,6 +567,13 @@ func (s *session) runOnce() (time.Time, error) {
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if s.onSpot != nil {
|
||||
if !firstSpotLogged {
|
||||
firstSpotLogged = true
|
||||
// The gap between the socket opening and the first spot is the
|
||||
// other half of the answer: a long dial is the network, a quick
|
||||
// dial and a long silence is the node (or the login) instead.
|
||||
applog.Printf("cluster[%s] first spot %s after connecting", s.cfg.Name, time.Since(linkUpAt).Round(time.Millisecond))
|
||||
}
|
||||
s.onSpot(spot)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
package udp
|
||||
|
||||
import "testing"
|
||||
|
||||
// A remote-call <FREQ> arrives in whatever unit the sender happens to use, and
|
||||
// the same sender uses more than one. Every form has to land on the same dial
|
||||
// frequency, because the alternative is a rig sent to the wrong band.
|
||||
func TestRemoteTuneUnits(t *testing.T) {
|
||||
const m20 = 14_074_000
|
||||
for _, c := range []struct {
|
||||
in string
|
||||
want int64
|
||||
why string
|
||||
}{
|
||||
{"14.074", m20, "MHz, the documented DXHunter form"},
|
||||
{"10.136", 10_136_000, "MHz, 30 m"},
|
||||
{"14074", m20, "kHz"},
|
||||
{"14074.0", m20, "kHz with a decimal point"},
|
||||
{"1407400", m20, "tens of Hz — what N1MM RadioInfo publishes, echoed back"},
|
||||
{"2107400", 21_074_000, "the value from the field log that failed every time"},
|
||||
{"14074000", m20, "Hz"},
|
||||
{"7000000", 7_000_000, "Hz on 40 m, not tens of Hz on 4 m"},
|
||||
{"0", 0, "no frequency"},
|
||||
{"999999999999", 0, "nothing plausible — tune nothing rather than guess"},
|
||||
{"abc", 0, "not a number"},
|
||||
} {
|
||||
if got := remoteTuneHz(c.in); got != c.want {
|
||||
t.Errorf("remoteTuneHz(%q) = %d, want %d (%s)", c.in, got, c.want, c.why)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,38 @@ import (
|
||||
"hamlog/internal/applog"
|
||||
)
|
||||
|
||||
// remoteTuneHz turns a <FREQ> value from a remote-call packet into Hz.
|
||||
//
|
||||
// The field has NO agreed unit, and the same sender uses two of them. DXHunter
|
||||
// documents "<FREQ>10.136" — MHz — but a log from a working station showed it
|
||||
// echoing "<FREQ>2107400" straight back: the frequency OpsLog had just
|
||||
// published to it in the N1MM RadioInfo broadcast, whose <Freq> is in units of
|
||||
// 10 Hz. Read as MHz, that asked the rig for 2 107 400 MHz, and every tune
|
||||
// request failed with "out of the 11-digit CAT range" from the first second
|
||||
// after launch.
|
||||
//
|
||||
// So the unit is inferred: try each one and keep the first that lands on an
|
||||
// amateur band. Anything a station is asked to tune to is, by definition, in
|
||||
// one. Hz is tried before 10 Hz because the one overlap between them — a 40 m
|
||||
// frequency in Hz reads as a 4 m one in tens of Hz — is far more likely to be
|
||||
// 40 m. Nothing plausible means nothing is tuned: a wrong band is worse than a
|
||||
// request that visibly did nothing.
|
||||
func remoteTuneHz(s string) int64 {
|
||||
v, err := strconv.ParseFloat(s, 64)
|
||||
if err != nil || v <= 0 {
|
||||
return 0
|
||||
}
|
||||
for _, hz := range []int64{int64(v * 1e6), int64(v * 1e3), int64(v), int64(v * 10)} {
|
||||
if bandFromHz(hz) != "" {
|
||||
return hz
|
||||
}
|
||||
}
|
||||
// Refusing in silence is how the previous version's failure looked from the
|
||||
// outside: a spot clicked in another program, and nothing happening here.
|
||||
applog.Printf("udp: remote_call <FREQ>%s is not a frequency in any amateur band in MHz, kHz or Hz — not tuning\n", s)
|
||||
return 0
|
||||
}
|
||||
|
||||
// remoteFreqRe / remoteModeRe pull the optional tune request out of a
|
||||
// ServiceRemoteCall packet: "<FREQ>10.136" (MHz) and "<MODE>FT8". Both accept
|
||||
// an optional closing tag for proper-XML senders.
|
||||
@@ -397,9 +429,7 @@ func (s *Server) handle(pkt []byte, remote *net.UDPAddr) {
|
||||
// otherwise leave their values as stray tokens and corrupt the
|
||||
// "last token = callsign" heuristic.
|
||||
if m := remoteFreqRe.FindStringSubmatch(text); m != nil {
|
||||
if mhz, err := strconv.ParseFloat(m[1], 64); err == nil && mhz > 0 {
|
||||
ev.TuneFreqHz = int64(mhz * 1e6)
|
||||
}
|
||||
ev.TuneFreqHz = remoteTuneHz(m[1])
|
||||
text = strings.Replace(text, m[0], " ", 1)
|
||||
}
|
||||
if m := remoteModeRe.FindStringSubmatch(text); m != nil {
|
||||
|
||||
+117
-17
@@ -3,6 +3,8 @@ package relaydev
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -20,13 +22,28 @@ import (
|
||||
//
|
||||
// - one URL pair with {relay} in it, used for every relay:
|
||||
// http://192.168.1.9/relay?n={relay}&state=on
|
||||
// - or one pair per relay, when the box has no pattern to speak of:
|
||||
// - one pair per relay, when the box has no pattern to speak of:
|
||||
// relay 1 → http://192.168.1.9/FF0101 , relay 2 → .../FF0201
|
||||
//
|
||||
// The second is the reason this driver exists. A hand-made switch often has
|
||||
// URLs with nothing in common between channels, and a template with {relay}
|
||||
// cannot express that.
|
||||
//
|
||||
// TWO SUBSTITUTIONS are available in either form:
|
||||
//
|
||||
// {relay} the relay number, 1-based. {relay-1} for a board that counts its
|
||||
// channels from zero — otherwise the whole pattern has to be given
|
||||
// up for eight hand-typed URLs over one missing offset.
|
||||
// {value} that relay's LABEL, the name given to it in Relay labels. A switch
|
||||
// addressed by antenna name rather than by channel number
|
||||
// (…/relay?on=Ant1) is then one pattern instead of eight URLs, and
|
||||
// renaming the antenna re-addresses it — the name the operator reads
|
||||
// on the button and the name on the wire cannot drift apart because
|
||||
// they are the same string.
|
||||
//
|
||||
// The label is percent-encoded, so a name with a space or an accent goes out as
|
||||
// a valid URL rather than a request the board rejects without saying why.
|
||||
//
|
||||
// STATE IS REMEMBERED, NOT READ. Most of these boxes have no status endpoint,
|
||||
// or answer with a web page nobody can parse reliably. Status therefore returns
|
||||
// what we last commanded — see the method for what that costs.
|
||||
@@ -35,6 +52,7 @@ type httpGen struct {
|
||||
offURLs []string
|
||||
onPat string // pattern with {relay}, used when the per-relay URL is empty
|
||||
offPat string
|
||||
labels []string // index 0 = relay 1; what {value} resolves to
|
||||
user string
|
||||
pass string
|
||||
count int
|
||||
@@ -45,8 +63,8 @@ type httpGen struct {
|
||||
|
||||
// NewHTTPGeneric builds the driver. onURLs/offURLs are per relay (index 0 =
|
||||
// relay 1) and may be short or hold empty entries; onPat/offPat are the
|
||||
// fallback patterns.
|
||||
func NewHTTPGeneric(onURLs, offURLs []string, onPat, offPat, user, pass string, count int) Device {
|
||||
// fallback patterns; labels are the relay names {value} substitutes.
|
||||
func NewHTTPGeneric(onURLs, offURLs []string, onPat, offPat, user, pass string, count int, labels []string) Device {
|
||||
if count <= 0 {
|
||||
count = len(onURLs)
|
||||
}
|
||||
@@ -55,7 +73,7 @@ func NewHTTPGeneric(onURLs, offURLs []string, onPat, offPat, user, pass string,
|
||||
}
|
||||
return &httpGen{
|
||||
onURLs: onURLs, offURLs: offURLs,
|
||||
onPat: onPat, offPat: offPat,
|
||||
onPat: onPat, offPat: offPat, labels: labels,
|
||||
user: user, pass: pass, count: count,
|
||||
state: make([]bool, count),
|
||||
}
|
||||
@@ -64,38 +82,120 @@ func NewHTTPGeneric(onURLs, offURLs []string, onPat, offPat, user, pass string,
|
||||
func (h *httpGen) Count() int { return h.count }
|
||||
func (h *httpGen) Close() error { return nil } // stateless HTTP, nothing to release
|
||||
|
||||
// urlFor picks the per-relay URL, falling back to the pattern.
|
||||
func (h *httpGen) urlFor(relay int, on bool) string {
|
||||
list, pat := h.offURLs, h.offPat
|
||||
// patFor returns the pattern for a direction, trimmed.
|
||||
func (h *httpGen) patFor(on bool) string {
|
||||
if on {
|
||||
list, pat = h.onURLs, h.onPat
|
||||
return strings.TrimSpace(h.onPat)
|
||||
}
|
||||
return strings.TrimSpace(h.offPat)
|
||||
}
|
||||
|
||||
// entryFor returns what was typed in the per-relay box for a direction.
|
||||
func (h *httpGen) entryFor(relay int, on bool) string {
|
||||
list := h.offURLs
|
||||
if on {
|
||||
list = h.onURLs
|
||||
}
|
||||
if i := relay - 1; i >= 0 && i < len(list) {
|
||||
if u := strings.TrimSpace(list[i]); u != "" {
|
||||
return u
|
||||
return strings.TrimSpace(list[i])
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// labelFor returns the relay's name, as typed in Relay labels.
|
||||
func (h *httpGen) labelFor(relay int) string {
|
||||
if i := relay - 1; i >= 0 && i < len(h.labels) {
|
||||
return strings.TrimSpace(h.labels[i])
|
||||
}
|
||||
if pat = strings.TrimSpace(pat); pat == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
// urlFor builds the request for one relay in one direction: the per-relay URL
|
||||
// if there is one, the pattern otherwise, with both substitutions applied.
|
||||
func (h *httpGen) urlFor(relay int, on bool) string {
|
||||
u := h.entryFor(relay, on)
|
||||
if u == "" {
|
||||
u = h.patFor(on)
|
||||
}
|
||||
if u == "" {
|
||||
return ""
|
||||
}
|
||||
return strings.ReplaceAll(pat, "{relay}", strconv.Itoa(relay))
|
||||
return expand(u, relay, h.labelFor(relay))
|
||||
}
|
||||
|
||||
// escapeValue percent-encodes a relay label for use anywhere in a URL.
|
||||
//
|
||||
// url.QueryEscape alone is wrong: it writes a space as "+", which is a space
|
||||
// only in a query string and a literal plus sign in a path. Encoding it as %20
|
||||
// instead is correct in both, and {value} may land in either.
|
||||
func escapeValue(s string) string {
|
||||
return strings.ReplaceAll(url.QueryEscape(s), "+", "%20")
|
||||
}
|
||||
|
||||
// withScheme supplies http:// when none was typed, and leaves https:// alone.
|
||||
//
|
||||
// The same rule the named boards get from relayBase, and it has to be here too:
|
||||
// this driver takes whole URLs rather than a host, and a line typed as
|
||||
// "192.168.1.9/Set0/1" would otherwise fail with "unsupported protocol scheme"
|
||||
// — an error about a scheme, for a field where nobody knew one was expected.
|
||||
// An https:// board (a reverse proxy fronting the shack, most often) is passed
|
||||
// through untouched and needs no other handling: it is the same HTTP client.
|
||||
func withScheme(u string) string {
|
||||
if u == "" {
|
||||
return ""
|
||||
}
|
||||
if l := strings.ToLower(u); strings.HasPrefix(l, "http://") || strings.HasPrefix(l, "https://") {
|
||||
return u
|
||||
}
|
||||
return "http://" + u
|
||||
}
|
||||
|
||||
// relayToken matches {relay} and its offset forms, {relay-1} / {relay+2}.
|
||||
var relayToken = regexp.MustCompile(`\{relay([+-]\d+)?\}`)
|
||||
|
||||
// expand substitutes {value} with the relay's label and {relay} with its
|
||||
// number, honouring an offset. A board that numbers its channels from zero is
|
||||
// written {relay-1}; without that the whole pattern has to be abandoned for
|
||||
// four hand-typed URLs.
|
||||
func expand(s string, relay int, label string) string {
|
||||
s = strings.ReplaceAll(s, "{value}", escapeValue(label))
|
||||
return relayToken.ReplaceAllStringFunc(s, func(m string) string {
|
||||
n := relay
|
||||
if i := strings.IndexAny(m, "+-"); i >= 0 {
|
||||
if off, err := strconv.Atoi(m[i : len(m)-1]); err == nil {
|
||||
n += off
|
||||
}
|
||||
}
|
||||
return strconv.Itoa(n)
|
||||
})
|
||||
}
|
||||
|
||||
func (h *httpGen) Set(ctx context.Context, relay int, on bool) error {
|
||||
if relay < 1 || relay > h.count {
|
||||
return fmt.Errorf("relay %d out of range 1..%d", relay, h.count)
|
||||
}
|
||||
u := h.urlFor(relay, on)
|
||||
if u == "" {
|
||||
// Naming the direction matters: an operator who filled the ON URLs and
|
||||
// left OFF empty gets a switch that latches, and "no URL configured"
|
||||
// alone would not say which half is missing.
|
||||
// Naming the direction matters: an operator who filled the ON URLs and left
|
||||
// OFF empty gets a switch that latches, and "no URL configured" alone would
|
||||
// not say which half is missing.
|
||||
dir := "OFF"
|
||||
if on {
|
||||
dir = "ON"
|
||||
}
|
||||
tmpl := h.entryFor(relay, on)
|
||||
if tmpl == "" {
|
||||
tmpl = h.patFor(on)
|
||||
}
|
||||
if tmpl == "" {
|
||||
return fmt.Errorf("no %s URL configured for relay %d", dir, relay)
|
||||
}
|
||||
// {value} with no label would send "?on=" — an empty parameter to an antenna
|
||||
// switch, which most boards answer with a cheerful 200 and no movement. Say
|
||||
// what is missing instead of firing it.
|
||||
if strings.Contains(tmpl, "{value}") && h.labelFor(relay) == "" {
|
||||
return fmt.Errorf("the %s URL for relay %d uses {value}, but relay %d has no label to put there", dir, relay, relay)
|
||||
}
|
||||
u := h.urlFor(relay, on)
|
||||
u = withScheme(u)
|
||||
if _, err := get(ctx, u, h.user, h.pass); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ func TestHTTPGenericPattern(t *testing.T) {
|
||||
|
||||
d := NewHTTPGeneric(nil, nil,
|
||||
srv.URL+"/relay?n={relay}&state=on",
|
||||
srv.URL+"/relay?n={relay}&state=off", "", "", 4)
|
||||
srv.URL+"/relay?n={relay}&state=off", "", "", 4, nil)
|
||||
if err := d.Set(context.Background(), 2, true); err != nil {
|
||||
t.Fatalf("Set on: %v", err)
|
||||
}
|
||||
@@ -53,7 +53,7 @@ func TestHTTPGenericPerRelayURLsWinOverThePattern(t *testing.T) {
|
||||
d := NewHTTPGeneric(
|
||||
[]string{srv.URL + "/FF0101", "", srv.URL + "/weird/on"},
|
||||
[]string{srv.URL + "/FF0100", "", ""},
|
||||
srv.URL+"/pattern/on/{relay}", srv.URL+"/pattern/off/{relay}", "", "", 3)
|
||||
srv.URL+"/pattern/on/{relay}", srv.URL+"/pattern/off/{relay}", "", "", 3, nil)
|
||||
|
||||
_ = d.Set(context.Background(), 1, true) // its own URL
|
||||
_ = d.Set(context.Background(), 2, true) // empty → falls back to the pattern
|
||||
@@ -66,10 +66,90 @@ func TestHTTPGenericPerRelayURLsWinOverThePattern(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// {value} is the relay's LABEL: a switch addressed by antenna name rather than
|
||||
// by channel number is one pattern instead of eight URLs.
|
||||
func TestHTTPGenericValueIsTheRelayLabel(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var got []string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
got = append(got, r.URL.String())
|
||||
mu.Unlock()
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
d := NewHTTPGeneric(
|
||||
[]string{srv.URL + "/relay?on={value}"}, // per-relay URL
|
||||
nil,
|
||||
"", srv.URL+"/relay?off={value}", // and the pattern, for the other direction
|
||||
"", "", 3, []string{"Ant1", "Beam 20m", ""})
|
||||
_ = d.Set(context.Background(), 1, true)
|
||||
_ = d.Set(context.Background(), 2, false)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
// The space in "Beam 20m" must go out as %20 — a "+" would be a literal plus
|
||||
// in a path, and this substitution can land in either half of a URL.
|
||||
want := []string{"/relay?on=Ant1", "/relay?off=Beam%2020m"}
|
||||
if strings.Join(got, " ") != strings.Join(want, " ") {
|
||||
t.Errorf("requested %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// {relay-1} for a board whose channels are numbered from zero.
|
||||
func TestHTTPGenericRelayOffset(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
var got []string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
mu.Lock()
|
||||
got = append(got, r.URL.Path)
|
||||
mu.Unlock()
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
d := NewHTTPGeneric(nil, nil,
|
||||
srv.URL+"/set0/{relay-1}/1", srv.URL+"/set0/{relay-1}/0", "", "", 4, nil)
|
||||
_ = d.Set(context.Background(), 1, true)
|
||||
_ = d.Set(context.Background(), 4, false)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
want := []string{"/set0/0/1", "/set0/3/0"}
|
||||
if strings.Join(got, " ") != strings.Join(want, " ") {
|
||||
t.Errorf("requested %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// A URL that uses {value} on an unlabelled relay would go out as "?on=" — an
|
||||
// empty parameter, which most boards answer with a cheerful 200 and no
|
||||
// movement. It must be refused, and the message must say the label is what is
|
||||
// missing.
|
||||
func TestHTTPGenericRefusesValueWithoutALabel(t *testing.T) {
|
||||
d := NewHTTPGeneric(nil, nil, "http://x/relay?on={value}", "", "", "", 2, []string{"", ""})
|
||||
err := d.Set(context.Background(), 1, true)
|
||||
if err == nil || !strings.Contains(err.Error(), "label") {
|
||||
t.Errorf("err = %v, want it to name the missing label", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A URL typed without a scheme must still be sent — the named boards take a
|
||||
// bare host and add http:// themselves, and this one has to behave the same.
|
||||
// https:// is left exactly as typed.
|
||||
func TestHTTPGenericSuppliesTheScheme(t *testing.T) {
|
||||
for _, c := range []struct{ in, want string }{
|
||||
{"192.168.1.9/Set0/1", "http://192.168.1.9/Set0/1"},
|
||||
{"http://192.168.1.9/x", "http://192.168.1.9/x"},
|
||||
{"https://relay.example.com/x", "https://relay.example.com/x"},
|
||||
{"HTTPS://relay.example.com/x", "HTTPS://relay.example.com/x"},
|
||||
} {
|
||||
if got := withScheme(c.in); got != c.want {
|
||||
t.Errorf("withScheme(%q) = %q, want %q", c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A switch with the ON URLs filled and OFF left empty latches. The error has to
|
||||
// name the direction, or the operator cannot tell which half is missing.
|
||||
func TestHTTPGenericNamesTheMissingDirection(t *testing.T) {
|
||||
d := NewHTTPGeneric([]string{"http://x/on"}, nil, "", "", "", "", 1)
|
||||
d := NewHTTPGeneric([]string{"http://x/on"}, nil, "", "", "", "", 1, nil)
|
||||
err := d.Set(context.Background(), 1, false)
|
||||
if err == nil || !strings.Contains(err.Error(), "OFF") {
|
||||
t.Errorf("err = %v, want it to name the OFF direction", err)
|
||||
@@ -80,7 +160,7 @@ func TestHTTPGenericNamesTheMissingDirection(t *testing.T) {
|
||||
func TestHTTPGenericRemembersWhatItCommanded(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
|
||||
defer srv.Close()
|
||||
d := NewHTTPGeneric(nil, nil, srv.URL+"/on/{relay}", srv.URL+"/off/{relay}", "", "", 3)
|
||||
d := NewHTTPGeneric(nil, nil, srv.URL+"/on/{relay}", srv.URL+"/off/{relay}", "", "", 3, nil)
|
||||
_ = d.Set(context.Background(), 2, true)
|
||||
st, err := d.Status(context.Background())
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package steppir
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// silentPort is a serial port that has stopped answering: every read times out.
|
||||
// On Windows that is reported as (0, nil) — a timeout is not an error on this
|
||||
// transport — which is precisely what io.ReadFull cannot survive.
|
||||
type silentPort struct{ reads int }
|
||||
|
||||
func (p *silentPort) Read(b []byte) (int, error) {
|
||||
p.reads++
|
||||
time.Sleep(5 * time.Millisecond) // stand in for the port's read timeout
|
||||
return 0, nil
|
||||
}
|
||||
func (p *silentPort) Write(b []byte) (int, error) { return len(b), nil }
|
||||
func (p *silentPort) Close() error { return nil }
|
||||
|
||||
// A controller that goes quiet must make the read FAIL, not hang. Hanging held
|
||||
// the io mutex, so the poll loop never reported a fault and every operator
|
||||
// command blocked behind it: the antenna stopped responding and the log had
|
||||
// nothing in it.
|
||||
func TestReadFrameGivesUpOnASilentController(t *testing.T) {
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- readFrame(&silentPort{}, make([]byte, 11), 100*time.Millisecond)
|
||||
}()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err == nil {
|
||||
t.Fatal("a silent controller was reported as a good frame")
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("readFrame never returned — the driver is wedged exactly as it was in the field")
|
||||
}
|
||||
}
|
||||
|
||||
// dribblePort delivers the frame a few bytes at a time, with empty reads in
|
||||
// between — a slow 4800-baud link, which must still assemble one frame.
|
||||
type dribblePort struct {
|
||||
data []byte
|
||||
step int
|
||||
idle int // empty reads before each chunk
|
||||
n int
|
||||
}
|
||||
|
||||
func (p *dribblePort) Read(b []byte) (int, error) {
|
||||
if p.n < p.idle {
|
||||
p.n++
|
||||
return 0, nil
|
||||
}
|
||||
p.n = 0
|
||||
if len(p.data) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
k := p.step
|
||||
if k > len(p.data) {
|
||||
k = len(p.data)
|
||||
}
|
||||
if k > len(b) {
|
||||
k = len(b)
|
||||
}
|
||||
copy(b, p.data[:k])
|
||||
p.data = p.data[k:]
|
||||
return k, nil
|
||||
}
|
||||
func (p *dribblePort) Write(b []byte) (int, error) { return len(b), nil }
|
||||
func (p *dribblePort) Close() error { return nil }
|
||||
|
||||
func TestReadFrameAssemblesASlowFrame(t *testing.T) {
|
||||
want := []byte{'@', 'A', 0x00, 0x20, 0x1E, 0xA8, 0x00, 0x05, 0x30, 0x37, 0x0D}
|
||||
p := &dribblePort{data: append([]byte(nil), want...), step: 3, idle: 2}
|
||||
buf := make([]byte, 11)
|
||||
if err := readFrame(p, buf, time.Second); err != nil {
|
||||
t.Fatalf("readFrame: %v", err)
|
||||
}
|
||||
for i := range want {
|
||||
if buf[i] != want[i] {
|
||||
t.Fatalf("read % X, want % X", buf, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A truncated frame is a failure, not a frame. The controller sending 5 bytes
|
||||
// and stopping used to spin forever on the missing 6.
|
||||
func TestReadFrameRejectsATruncatedFrame(t *testing.T) {
|
||||
p := &dribblePort{data: []byte{'@', 'A', 0x00, 0x20, 0x1E}, step: 5}
|
||||
err := readFrame(p, make([]byte, 11), 100*time.Millisecond)
|
||||
if err == nil {
|
||||
t.Fatal("a 5-byte frame was accepted as 11")
|
||||
}
|
||||
}
|
||||
|
||||
// A real error still comes straight back.
|
||||
func TestReadFrameReturnsPortErrors(t *testing.T) {
|
||||
want := errors.New("port closed")
|
||||
p := errPort{err: want}
|
||||
if err := readFrame(p, make([]byte, 11), time.Second); !errors.Is(err, want) {
|
||||
t.Fatalf("err = %v, want %v", err, want)
|
||||
}
|
||||
}
|
||||
|
||||
type errPort struct{ err error }
|
||||
|
||||
func (p errPort) Read([]byte) (int, error) { return 0, p.err }
|
||||
func (p errPort) Write(b []byte) (int, error) { return len(b), nil }
|
||||
func (p errPort) Close() error { return nil }
|
||||
|
||||
var _ io.ReadWriteCloser = errPort{}
|
||||
@@ -419,6 +419,45 @@ func drain(conn io.ReadWriteCloser) int {
|
||||
return total
|
||||
}
|
||||
|
||||
// frameTimeout bounds the wait for one 11-byte status reply. At 4800 baud the
|
||||
// frame itself takes ~23 ms; three seconds is a controller that is not going to
|
||||
// answer this query.
|
||||
const frameTimeout = 3 * time.Second
|
||||
|
||||
// readFrame reads exactly len(buf) bytes, or gives up.
|
||||
//
|
||||
// io.ReadFull CANNOT be used on a serial port, and using it here is what made an
|
||||
// antenna "stop responding after a while" with nothing whatsoever in the log.
|
||||
//
|
||||
// On Windows a serial read that times out returns (0, nil) — a timeout is not an
|
||||
// error on this transport. io.ReadFull loops while err == nil, so a controller
|
||||
// that goes quiet, or sends a truncated frame, spins it forever. It holds ioMu
|
||||
// the whole time, and that is the part the operator sees: the poll goroutine
|
||||
// never returns to report a fault, so the last status stays on screen and the
|
||||
// link still looks connected — while every command blocks on the same mutex.
|
||||
// The trace line used to sit AFTER that lock, so even the attempt went unlogged.
|
||||
// One dropped reply on a 4800-baud link wedged the driver until OpsLog restarted.
|
||||
//
|
||||
// Giving up returns an error, which the poll loop already knows how to handle:
|
||||
// it says so in the log and reconnects.
|
||||
func readFrame(conn io.ReadWriteCloser, buf []byte, d time.Duration) error {
|
||||
deadline := time.Now().Add(d)
|
||||
for n := 0; n < len(buf); {
|
||||
m, err := conn.Read(buf[n:])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n += m
|
||||
if n >= len(buf) {
|
||||
return nil
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return fmt.Errorf("timed out after %s with %d of %d bytes", d, n, len(buf))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) queryStatus() (*Status, error) {
|
||||
c.connMu.Lock()
|
||||
conn := c.conn
|
||||
@@ -438,7 +477,7 @@ func (c *Client) queryStatus() (*Status, error) {
|
||||
return nil, fmt.Errorf("write status cmd: %w", err)
|
||||
}
|
||||
buf := make([]byte, 11)
|
||||
if _, err := io.ReadFull(conn, buf); err != nil {
|
||||
if err := readFrame(conn, buf, frameTimeout); err != nil {
|
||||
return nil, fmt.Errorf("read status: %w", err)
|
||||
}
|
||||
// Reject anything that isn't a framed reply rather than decoding garbage into
|
||||
@@ -523,9 +562,14 @@ func (c *Client) writeCmd(pkt []byte) error {
|
||||
if conn == nil {
|
||||
return fmt.Errorf("steppir: not connected")
|
||||
}
|
||||
// Traced BEFORE taking the lock, not after. A command waits here for the poll
|
||||
// in flight, and when that wait was unbounded the log showed no sign the
|
||||
// operator had asked for anything at all — the one fact that would have named
|
||||
// the fault. The line now means "asked for"; a failure to write is reported
|
||||
// by the caller.
|
||||
log.Printf("steppir: → % X", pkt)
|
||||
c.ioMu.Lock()
|
||||
defer c.ioMu.Unlock()
|
||||
log.Printf("steppir: → % X", pkt)
|
||||
setDeadline(conn, 3*time.Second)
|
||||
if _, err := conn.Write(pkt); err != nil {
|
||||
c.closeConn()
|
||||
|
||||
@@ -95,18 +95,25 @@ func hostOpenOnce(p serial.Port, boot time.Duration) (int, error) {
|
||||
time.Sleep(boot)
|
||||
drain(p)
|
||||
|
||||
// Resync the command parser before asking it anything.
|
||||
if _, err := p.Write([]byte{cmdNull, cmdNull, cmdNull}); err != nil {
|
||||
return 0, fmt.Errorf("resync: %w", err)
|
||||
}
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
drain(p)
|
||||
|
||||
// Is anything actually there?
|
||||
if _, err := p.Write([]byte{cmdAdmin, adminEcho, echoProbe}); err != nil {
|
||||
// The resync nulls and the echo probe go out as ONE write.
|
||||
//
|
||||
// Copied byte for byte from a Logger32 capture against the K3NG keyer that
|
||||
// would not answer OpsLog: "Sent: 13 13 13 00 04 55 / Rcvd: 55". Same keyer,
|
||||
// same port, same six bytes — the only difference was that we sent them as
|
||||
// two writes with a pause and a buffer purge in between, and Logger32 sends
|
||||
// them as one. On a keyer that reboots when the port opens, that pause is a
|
||||
// window for it to come up mid-sequence and swallow half of it.
|
||||
//
|
||||
// There is nothing to wait for between the two halves anyway: a null produces
|
||||
// no reply, so the pause was only ever giving the keyer a chance to change
|
||||
// its mind.
|
||||
probe := []byte{cmdNull, cmdNull, cmdNull, cmdAdmin, adminEcho, echoProbe}
|
||||
traceHandshake("TX", probe, 0, false)
|
||||
if _, err := p.Write(probe); err != nil {
|
||||
return 0, fmt.Errorf("echo test: %w", err)
|
||||
}
|
||||
b, ok := readByte(p, echoTimeout)
|
||||
traceHandshake("RX", nil, b, ok)
|
||||
if !ok {
|
||||
return 0, errNoKeyer
|
||||
}
|
||||
@@ -116,16 +123,37 @@ func hostOpenOnce(p serial.Port, boot time.Duration) (int, error) {
|
||||
return 0, fmt.Errorf("echo test: expected 0x%02X, got 0x%02X — is this the keyer's port?", echoProbe, b)
|
||||
}
|
||||
|
||||
if _, err := p.Write([]byte{cmdAdmin, adminOpen}); err != nil {
|
||||
open := []byte{cmdAdmin, adminOpen}
|
||||
traceHandshake("TX", open, 0, false)
|
||||
if _, err := p.Write(open); err != nil {
|
||||
return 0, fmt.Errorf("host open: %w", err)
|
||||
}
|
||||
ver, ok := readByte(p, openTimeout)
|
||||
traceHandshake("RX", nil, ver, ok)
|
||||
if !ok {
|
||||
return 0, errors.New("host open: the keyer echoed but did not return its firmware version")
|
||||
}
|
||||
return int(ver), nil
|
||||
}
|
||||
|
||||
// traceHandshake puts the opening exchange in the log, ALWAYS — unlike the
|
||||
// running trace beside it, which is behind the diagnostic option.
|
||||
//
|
||||
// A failure that says only "no WinKeyer answered" cannot be told apart from a
|
||||
// wrong port, a wrong baud rate, a keyer still rebooting, or another program
|
||||
// holding the line. The bytes can. It is four lines per connect, and only when
|
||||
// the connect is attempted.
|
||||
func traceHandshake(dir string, b []byte, got byte, ok bool) {
|
||||
switch {
|
||||
case dir == "TX":
|
||||
applog.Printf("winkeyer: handshake TX % 02X", b)
|
||||
case ok:
|
||||
applog.Printf("winkeyer: handshake RX %02X", got)
|
||||
default:
|
||||
applog.Printf("winkeyer: handshake RX — nothing came back")
|
||||
}
|
||||
}
|
||||
|
||||
// readByte waits up to d for one byte. The serial read timeout is per-call and
|
||||
// can return 0 bytes without an error, so this loops until the deadline rather
|
||||
// than trusting a single Read.
|
||||
|
||||
@@ -102,6 +102,8 @@ func TestHostOpenFollowsK1ELSequence(t *testing.T) {
|
||||
if ver != 23 {
|
||||
t.Errorf("version = %d, want 23", ver)
|
||||
}
|
||||
// One write for the six probe bytes, then Host Open — the order and the
|
||||
// grouping of a Logger32 capture against a real K3NG.
|
||||
want := []byte{
|
||||
cmdNull, cmdNull, cmdNull,
|
||||
cmdAdmin, adminEcho, echoProbe,
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Every setting in OpsLog is per profile, station hardware included. A device
|
||||
// started at boot and never again therefore stays on the PREVIOUS profile's
|
||||
// port until Settings is opened and saved — which is how an operator running an
|
||||
// SPE on COM9 for HF and another on COM10 for 6 m, one per profile, found the
|
||||
// amplifier still on the old port after switching. Save is not a connect
|
||||
// button.
|
||||
//
|
||||
// This test keeps startup and reloadAfterProfileSwitch in lockstep: anything
|
||||
// started at boot must either be re-applied on a profile switch or be listed
|
||||
// below with the reason it must not be. Adding a device makes the choice
|
||||
// explicit instead of leaving the fifth one to be found by a user.
|
||||
func TestProfileSwitchReappliesEveryStartupDevice(t *testing.T) {
|
||||
src, err := os.ReadFile("app.go")
|
||||
if err != nil {
|
||||
t.Fatalf("read app.go: %v", err)
|
||||
}
|
||||
|
||||
// Started at boot but deliberately NOT re-run on a profile switch:
|
||||
notPerProfile := map[string]string{
|
||||
"startAllEnabledClusters": "the cluster panel reconnects itself; its servers are a global list",
|
||||
"startGridCache": "a shared on-disk grid cache, not a profile's",
|
||||
"startBandOpenFeed": "PSK Reporter, keyed on the operator grid it re-reads itself",
|
||||
}
|
||||
|
||||
startup := body(t, string(src), "func (a *App) startup(ctx context.Context) {")
|
||||
reload := body(t, string(src), "func (a *App) reloadAfterProfileSwitch() {")
|
||||
|
||||
call := regexp.MustCompile(`a\.(start[A-Z][A-Za-z]*)\b`)
|
||||
seen := map[string]bool{}
|
||||
for _, m := range call.FindAllStringSubmatch(startup, -1) {
|
||||
name := m[1]
|
||||
if seen[name] || notPerProfile[name] != "" {
|
||||
continue
|
||||
}
|
||||
seen[name] = true
|
||||
if !strings.Contains(reload, "a."+name) {
|
||||
t.Errorf("%s runs at startup but not on a profile switch — the device stays on the previous profile's settings.\n"+
|
||||
"Add it to reloadAfterProfileSwitch, or to notPerProfile here with the reason it must not follow the profile.", name)
|
||||
}
|
||||
}
|
||||
if len(seen) == 0 {
|
||||
t.Fatal("no startup device starters found — this test has stopped checking anything")
|
||||
}
|
||||
}
|
||||
|
||||
// body returns the source of the function opening with the given signature,
|
||||
// up to the closing brace in column 0.
|
||||
func body(t *testing.T, src, signature string) string {
|
||||
t.Helper()
|
||||
i := strings.Index(src, signature)
|
||||
if i < 0 {
|
||||
t.Fatalf("%q not found in app.go", signature)
|
||||
}
|
||||
rest := src[i+len(signature):]
|
||||
if j := strings.Index(rest, "\n}"); j >= 0 {
|
||||
return rest[:j]
|
||||
}
|
||||
return rest
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The generic HTTP board must actually be built from its URLs.
|
||||
//
|
||||
// It was not: buildDeviceDriver had no case for it, so it fell through to the
|
||||
// WebSwitch driver. The board was configured, saved, listed — and every command
|
||||
// went to a WebSwitch address that did not exist, which also left the device
|
||||
// reported as offline and every relay button on the panel greyed out. Nothing in
|
||||
// the UI said so; the URLs were simply never sent.
|
||||
func TestGenericHTTPBoardSendsItsConfiguredURL(t *testing.T) {
|
||||
hit := make(chan string, 4)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hit <- r.URL.Path
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
// Host deliberately empty — this board's whole address is in the URLs.
|
||||
d := StationDevice{
|
||||
Type: "httpgen",
|
||||
Channels: 2,
|
||||
OnURLs: []string{srv.URL + "/relay1/on", srv.URL + "/relay2/on"},
|
||||
OffURLs: []string{srv.URL + "/relay1/off", srv.URL + "/relay2/off"},
|
||||
}
|
||||
if err := buildDeviceDriver(d).Set(context.Background(), 2, true); err != nil {
|
||||
t.Fatalf("Set: %v", err)
|
||||
}
|
||||
select {
|
||||
case got := <-hit:
|
||||
if got != "/relay2/on" {
|
||||
t.Errorf("board was asked for %q, want /relay2/on", got)
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("the configured URL was never requested — the board is not using its own driver")
|
||||
}
|
||||
}
|
||||
|
||||
// Editing a URL must rebuild the driver. The cached one is keyed by the device's
|
||||
// configuration, and the URLs used not to be part of that key: correcting a typo
|
||||
// handed back the driver still holding the old address, so the fix looked like it
|
||||
// had done nothing until OpsLog was restarted.
|
||||
func TestGenericHTTPBoardKeyCoversItsURLs(t *testing.T) {
|
||||
a := StationDevice{Type: "httpgen", Channels: 2, OnURLs: []string{"http://box/a"}}
|
||||
b := StationDevice{Type: "httpgen", Channels: 2, OnURLs: []string{"http://box/b"}}
|
||||
if deviceKey(a) == deviceKey(b) {
|
||||
t.Error("two boards with different URLs share a cache key — an edited URL would not take effect")
|
||||
}
|
||||
c := a
|
||||
c.OnPat = "http://box/{relay}"
|
||||
if deviceKey(a) == deviceKey(c) {
|
||||
t.Error("changing the ON pattern left the cache key unchanged")
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -21,7 +21,7 @@ import (
|
||||
|
||||
const (
|
||||
// appVersion is stamped on every heartbeat (and could feed the About box).
|
||||
appVersion = "0.25.3"
|
||||
appVersion = "0.25.5"
|
||||
|
||||
// posthogHost is the PostHog ingestion endpoint. EU cloud by default; change
|
||||
// to https://us.i.posthog.com for a US project.
|
||||
|
||||
Reference in New Issue
Block a user