Compare commits

..
10 Commits
Author SHA1 Message Date
rouggy f3f966f5b7 chore: release v0.25.5 2026-08-16 01:04:54 +02:00
rouggy 38c838d232 chore(changelog): move today's work from the shipped 0.25.4 to 0.25.5
v0.25.4 was already released — tag v0.25.4 at 8113557, fourteen hours ago —
carrying exactly one entry, the WinKeyer probe. Everything since (cluster empty
state and timing, the generic HTTP relay, hardware following the profile, the
SteppIR read that never returned, the DXHunter tune unit) was written into that
block and would have been announced to operators as something they already have.

The 0.25.4 block is now byte-identical to the one that shipped, and the seven
later entries are under 0.25.5.
2026-08-16 00:46:15 +02:00
rouggy 7eb734d86f chore(changelog): open 0.25.5
0.25.4 is going out with eight entries. The version constants are left alone —
the release script is the one source that bumps them, and touching them here
would make its "release commit already exists" check misfire.
2026-08-16 00:35:30 +02:00
rouggy b49599150c fix(steppir): a silent controller wedged the driver for good
io.ReadFull cannot be used on a serial port, and it was.

On Windows a serial read that times out returns (0, nil) — on this transport a
timeout is not an error. io.ReadFull loops while err == nil, so a controller
that goes quiet for one poll, or answers with a truncated frame, spins it
forever. It holds ioMu throughout, and that is the whole failure the operator
sees:

  - the poll goroutine never returns, so nothing is ever logged about a fault
    and the cached status keeps the antenna looking connected;
  - every command blocks on the same mutex, and the trace line sat AFTER the
    lock, so even the attempt left no trace.

One dropped reply on a 4800-baud link therefore stopped the antenna responding
until OpsLog was restarted, with a log that showed the antenna starting, a few
status frames, and then nothing — which is exactly how it was reported.

Reads are now bounded: three seconds for an 11-byte frame that takes 23 ms on
the wire. Giving up returns an error, and the poll loop already knows what to do
with one — say so and reconnect. The command trace moved ahead of the lock, so
what the operator asked for is in the log even when the answer is not.

The SPE driver reads through a bufio.Reader, whose ErrNoProgress guard already
covers this; the ADIF parser reads a file. This was the only exposed one.
2026-08-16 00:33:32 +02:00
rouggy 331db58705 fix(antenna,udp): name the reason tracking is off; infer the remote-tune unit
The SteppIR report was not a SteppIR fault. In the log the antenna starts,
answers every poll, and sits at 21050 kHz while the rig works 21074 — and the
status line only prints when the frame CHANGES, so a link that is alive and
parked looks identical to one that died. The one line that explained it said
"ultrabeam: follow loop stopped", which covers two quite different situations
and, at startup where nothing was running, reads as a fault. Tracking was simply
switched off. It now says which of the two it is, names the antenna type, and
states the consequence — that the antenna will not follow the rig.

Same log, a second and unrelated fault: every launch failed a tune request from
DXHunter with "frequency 2107400000000 out of the 11-digit CAT range".
<FREQ> was read as MHz, but DXHunter had echoed back the value OpsLog itself
published in the N1MM RadioInfo broadcast, whose <Freq> is in tens of Hz. Both
units come from the same peer, so the unit is now inferred: try MHz, kHz, Hz,
tens of Hz, and keep the first that lands on an amateur band — anything a
station is asked to tune to is in one. Hz before tens of Hz because their only
overlap, 40 m against 4 m, is far more likely to be 40 m. Nothing plausible
tunes nothing and says so, rather than sending the rig to a wrong band.
2026-08-16 00:27:53 +02:00
rouggy 62e20de69c fix(profiles): station hardware must follow the active profile
Every setting is per profile, amplifiers included — that is the whole point of
one profile per station. But the amplifier clients were built once at startup
and again only when Settings was saved, so switching profile left them on the
previous profile's port. An operator with an SPE on COM9 for HF and another on
COM10 for 6 m had to open Settings and press Save after every switch. Save is
not a connect button; switching profile is what asks for that hardware.

The amplifier is what was reported, but it was never alone: the motorized
antenna, the Antenna Genius and the Tuner Genius are configured the same way and
were started in the same two places. All four now restart on a profile switch,
asynchronously, exactly as a save does.

Rotators were already correct — their client is built per command rather than
held open, so they read the active profile every time.

Unconditional, like a save: comparing each device's configuration across
profiles to skip a reconnect would trade a second of downtime for the chance of
missing one. A test now keeps the two lists in lockstep — anything started at
boot must be re-applied on a profile switch or be named, with its reason, as
something that must not be.
2026-08-16 00:18:11 +02:00
rouggy 480d24384b fix(relays): {value} is the relay's label, not a per-relay value
It was built the other way round on a misreading of two screenshots: the pattern
held {value} and the per-relay boxes held numbers to drop into it. The ask was
simpler and better — {value} is the name typed in Relay labels, so a switch
addressed by antenna name is one pattern instead of eight URLs:

  http://10.10.10.100/relay?on={value}   relay 1 named Ant1  →  ?on=Ant1

Renaming the antenna re-addresses it, and the name on the button and the name on
the wire cannot drift apart because they are the same string. It works in the
per-relay URLs and in the patterns alike, so the per-relay boxes go back to
holding URLs and nothing about them changes meaning any more.

The label is percent-encoded with %20 rather than "+" for a space: "+" is a
space only in a query string and a literal plus in a path, and this can land in
either half of a URL.

{value} on a relay with no label would send "?on=", an empty parameter that most
boards answer with a cheerful 200 and no movement. The driver refuses it and
names the label as what is missing; the editor warns while it is being typed,
beside the empty box rather than after an antenna fails to switch. The labels
also join the driver's cache key — they are part of the wire format now.
2026-08-16 00:09:18 +02:00
rouggy c2ff0f714a revert(cluster): keep the filter selections across restarts
They were made session-only on a misreading: the ask was about the FIRST launch
of a fresh install, not every launch. Restored as they were — restored on
reopen, and travelling with a copied data/ folder.

A first-ever launch already starts with nothing filtered: every selection
defaults to empty or off and there is no code that switches one on. The one
route by which a new installation can come up filtered is a copied data/ folder,
which carries the previous machine's selections by design.

The filtered-out message and the clear-every-filter button stay: they are what
makes a filter that IS set visible, whenever it was set.
2026-08-15 23:58:40 +02:00
rouggy fe2affc72f fix(relays): the generic HTTP board never sent its URLs; cluster filters start off
buildDeviceDriver had no case for "httpgen", so the generic board fell through
to the WebSwitch driver: it polled an address it had never been given, reported
itself offline, greyed out every relay button, and sent none of the configured
URLs. Nothing in the interface said so — the board was configured, saved and
listed, and simply did nothing. deviceKey did not cover the URLs either, so once
that is fixed, correcting a typo in one would still have handed back the cached
driver holding the old address until a restart.

Two shapes of home-made switch could not be described at all:

  - a bit-mask board whose four URLs differ by one character
    (/Set0/1, /Set0/2, /Set0/4, /Set0/8) — {value} in the pattern now takes the
    number from the per-relay box, keeping the address in one place;
  - a board numbering its channels from zero — {relay-1}, since giving up the
    pattern for eight hand-typed URLs was the only alternative.

The pattern decides what the per-relay boxes hold, and the grid says which as
soon as {value} is typed: guessing per box ("does this look like a URL?") would
change meaning on a typo, which is not a thing to do to something wired to an
antenna. A URL typed without a scheme gets http:// like the named boards get
from relayBase; https:// is passed through untouched.

Host and the connection test are gone for this type. It has no address of its
own — its relays may each live on a different box — and no status to read, so a
test could only ever answer "OK, 4 relays". Save was greyed out without a host,
which made a complete configuration of four full URLs impossible to store.

Cluster filters no longer persist across launches. A band lock set weeks earlier
is invisible to whoever set it: the counter reads 76 spots live, the grid is
empty, and the search goes to the cluster instead. Nobody loses work by
re-ticking a chip. Grouping and the panel state still persist — they change how
spots look, never whether they appear.
2026-08-15 23:53:32 +02:00
rouggy be0326c862 fix(cluster): stop saying "waiting for spots" when 76 have arrived
An operator sent two screenshots: 76 LIVE in the counter, and the panel beside
it reading "Waiting for spots… Spots will appear as the cluster sends them."
Both his band and mode were locked to the rig — 20 m, SSB — so the filters were
doing exactly their job and the empty state was describing a different problem
entirely. He went looking for a connection fault.

It now says how many arrived, names every filter currently narrowing the list,
and offers one button to clear them all. The band and mode locks are named
first: they follow the rig rather than a click, so they are the two nobody
remembers switching on.

Also times the connection. He reports the first launch taking a while to
produce spots and a restart connecting instantly, which is the signature of a
slow name resolution rather than a slow node — the OS caches the answer, so the
second run skips it. The log now carries the dial duration and the delay to the
first spot, which separates that from a node that simply had nothing to say.
Hypothesis, not conclusion: the next log settles it.
2026-08-15 23:35:56 +02:00
16 changed files with 766 additions and 54 deletions
+54 -7
View File
@@ -57,9 +57,9 @@ import (
"hamlog/internal/relaydev" "hamlog/internal/relaydev"
"hamlog/internal/rigctld" "hamlog/internal/rigctld"
"hamlog/internal/rotator/dcu1" "hamlog/internal/rotator/dcu1"
"hamlog/internal/rotator/spid"
"hamlog/internal/rotator/gs232" "hamlog/internal/rotator/gs232"
"hamlog/internal/rotator/pst" "hamlog/internal/rotator/pst"
"hamlog/internal/rotator/spid"
"hamlog/internal/rotgenius" "hamlog/internal/rotgenius"
"hamlog/internal/scp" "hamlog/internal/scp"
"hamlog/internal/settings" "hamlog/internal/settings"
@@ -14120,8 +14120,9 @@ func (a *App) ActivateProfile(id int64) error {
// reloadAfterProfileSwitch re-applies all settings-derived state for the newly // reloadAfterProfileSwitch re-applies all settings-derived state for the newly
// active profile: lookup providers, upload-service accounts, CAT connection, // active profile: lookup providers, upload-service accounts, CAT connection,
// and the QSO recorder (audio devices). The Winkeyer stays as-is (the operator // the station hardware, and the QSO recorder (audio devices). The Winkeyer
// connects it explicitly). The frontend reloads its panels via profile:changed. // stays as-is (the operator connects it explicitly). The frontend reloads its
// panels via profile:changed.
func (a *App) reloadAfterProfileSwitch() { func (a *App) reloadAfterProfileSwitch() {
a.reloadLookupProviders() a.reloadLookupProviders()
if a.extsvc != nil { 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 // runs from ActivateProfile, a click, and a rig that is slow to release would
// otherwise freeze the switch. // otherwise freeze the switch.
a.restartAsync("cat", a.reloadCAT) 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() a.startQSORecorderIfEnabled()
} }
@@ -14757,6 +14773,13 @@ func buildDeviceDriver(d StationDevice) relaydev.Device {
case "usbrelay": case "usbrelay":
// Host carries the COM port (e.g. "COM5"); CH340/LCUS "A0" serial protocol. // Host carries the COM port (e.g. "COM5"); CH340/LCUS "A0" serial protocol.
return relaydev.NewSerialRelay(d.Host, deviceRelayCount(d)) 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: default:
return relaydev.NewWebswitch(d.Host) 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 // 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. // open driver (and its OS handle) instead of rebuilding it every poll.
func deviceKey(d StationDevice) string { 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 // 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) close(a.ubFollowStop)
a.ubFollowStop = nil a.ubFollowStop = nil
} }
if !s.Follow || a.motorAnt == nil { // Say WHICH of the two reasons it is. "follow loop stopped" covered both, and
applog.Printf("ultrabeam: follow loop stopped") // 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 return
} }
stop := make(chan struct{}) stop := make(chan struct{})
a.ubFollowStop = stop 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) go a.ultrabeamFollowLoop(a.motorAnt, s.TrackMode, s.StepKHz, s.Bands, stop)
} }
+22
View File
@@ -1,4 +1,26 @@
[ [
{
"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é dun compteur à 76 en direct.",
"Cluster DX : le journal chronomètre la connexion et le premier spot, pour distinguer un premier lancement lent dun 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 lampli, lantenne, lAntenna 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 — lantenne ne répondait plus, sans rien dans le journal. Elle se rétablit maintenant seule.",
"Le journal indique désormais quune antenne motorisée est connectée mais que le suivi est désactivé, au lieu dune 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", "version": "0.25.4",
"date": "", "date": "",
+64 -2
View File
@@ -1539,6 +1539,41 @@ export default function App() {
// Hide spots already worked (exact call worked, or this band+mode slot done). // Hide spots already worked (exact call worked, or this band+mode slot done).
const [clusterHideWorked, setClusterHideWorked] = useState(() => lsBool('opslog.clusterHideWorked', false)); 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 // Persist every cluster filter selection whenever it changes, so it is still
// set after a close/reopen. // set after a close/reopen.
useEffect(() => { useEffect(() => {
@@ -6738,14 +6773,41 @@ export default function App() {
// pane). All the filter state lives in the right-side panel. // pane). All the filter state lives in the right-side panel.
const rendered = clusterRenderedRows; const rendered = clusterRenderedRows;
if (rendered.length === 0) { 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 ( return (
<div className="flex-1 flex flex-col items-center justify-center text-muted-foreground gap-2 py-12"> <div className="flex-1 flex flex-col items-center justify-center text-muted-foreground gap-2 py-12">
<Hash className="size-10 opacity-30" /> <Hash className="size-10 opacity-30" />
<div className="text-sm font-semibold text-foreground/70"> <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>
<div className="text-xs"> <div className="text-xs">
{clusterServerStatuses.some((s) => s.state === 'connected') {connected
? 'Spots will appear as the cluster sends them.' ? 'Spots will appear as the cluster sends them.'
: 'Use Connect all (or configure a cluster in Settings → DX Cluster).'} : 'Use Connect all (or configure a cluster in Settings → DX Cluster).'}
</div> </div>
+43 -10
View File
@@ -527,16 +527,25 @@ export function StationControlPanel({ centerLat, centerLon, bearing }: RotatorPr
const deviceCard = (dev: Device) => { const deviceCard = (dev: Device) => {
const st = status[dev.id]; const st = status[dev.id];
const relays = st?.relays ?? dev.labels.map((label, i) => ({ number: i + 1, label, on: false })); 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 ( return (
<div className="rounded-xl border border-border bg-card shadow-sm overflow-hidden h-full"> <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"> <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" /> <PlugZap className="size-4 text-primary" />
<div className="min-w-0"> <div className="min-w-0">
<div className="text-sm font-semibold truncate">{dev.name || TYPE_LABEL[dev.type]}</div> <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> </div>
<span className={cn('ml-auto size-2 rounded-full shrink-0', st?.connected ? 'bg-success' : 'bg-muted-foreground/40')} {fireAndForget ? <span className="ml-auto" /> : (
title={st?.connected ? t('station.online') : (st?.error || t('station.offline'))} /> <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')} <button className="text-muted-foreground hover:text-foreground" title={t('station.edit')}
onClick={() => setEditing({ ...dev, labels: [...dev.labels] })}><Pencil className="size-3.5" /></button> onClick={() => setEditing({ ...dev, labels: [...dev.labels] })}><Pencil className="size-3.5" /></button>
<button className="text-muted-foreground hover:text-destructive" title={t('station.delete')} <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 key = `${dev.id}:${r.number}`;
const label = r.label || `${t('station.relay')} ${r.number}`; const label = r.label || `${t('station.relay')} ${r.number}`;
return ( return (
<button key={r.number} type="button" disabled={!st?.connected} <button key={r.number} type="button" disabled={!fireAndForget && !st?.connected}
title={label} title={label}
onClick={() => toggle(dev, r.number, !r.on)} 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', 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 isDenkovi = device.type === 'denkovi';
const isUsbRelay = device.type === 'usbrelay'; const isUsbRelay = device.type === 'usbrelay';
const isHTTPGen = device.type === 'httpgen'; 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. // COM ports for the generic USB-serial relay picker.
const [serialPorts, setSerialPorts] = useState<string[]>([]); const [serialPorts, setSerialPorts] = useState<string[]>([]);
useEffect(() => { useEffect(() => {
@@ -795,7 +811,12 @@ function DeviceEditor({ device, onChange, onSave, onCancel, t }: {
</div> </div>
<p className="text-[10px] text-muted-foreground">{t('station.usbRelayHint')}</p> <p className="text-[10px] text-muted-foreground">{t('station.usbRelayHint')}</p>
</div> </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('grid gap-3', (isKM || isDingtian) ? 'grid-cols-3' : 'grid-cols-1')}>
<div className={cn('space-y-1', (isKM || isDingtian) ? '' : 'max-w-xs')}> <div className={cn('space-y-1', (isKM || isDingtian) ? '' : 'max-w-xs')}>
<Label>{t('station.host')}</Label> <Label>{t('station.host')}</Label>
@@ -886,6 +907,10 @@ function DeviceEditor({ device, onChange, onSave, onCancel, t }: {
<div className="space-y-1"> <div className="space-y-1">
<Label>{t('station.labels')}</Label> <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"> <div className="grid grid-cols-4 gap-2">
{device.labels.map((lab, i) => ( {device.labels.map((lab, i) => (
<Input key={i} value={lab} placeholder={`${t('station.relay')} ${i + 1}`} className="h-8 text-xs" <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> </span>
)} )}
<div className="ml-auto flex gap-2"> <div className="ml-auto flex gap-2">
<Button size="sm" variant="outline" onClick={testDevice} disabled={testing || !device.host.trim()}> {/* No connection test for the generic board, and no host required to
{testing ? <Loader2 className="size-3.5 mr-1 animate-spin" /> : <PlugZap className="size-3.5 mr-1" />} save it. There is nothing to test: it has no address of its own and
{t('station.test')} no status to read — its URLs are fired and forgotten. A button that
</Button> 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" 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> </div>
</div> </div>
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1,6 +1,6 @@
// Single source of truth for the app version shown in the UI (header + About). // 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). // Bump this on a release (the release script updates it alongside telemetry.go).
export const APP_VERSION = '0.25.4'; export const APP_VERSION = '0.25.5';
// Author / credits, shown in Help -> About. // Author / credits, shown in Help -> About.
export const APP_AUTHOR = 'F4BPO'; export const APP_AUTHOR = 'F4BPO';
+18
View File
@@ -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 // failure surfaces as an error on Read — which is the only thing that ends
// a session below. // a session below.
d := net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second} 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) conn, err := d.Dial("tcp", addr)
if err != nil { 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) 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.mu.Lock()
s.conn = conn s.conn = conn
s.mu.Unlock() s.mu.Unlock()
@@ -556,6 +567,13 @@ func (s *session) runOnce() (time.Time, error) {
} }
s.mu.Unlock() s.mu.Unlock()
if s.onSpot != nil { 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) 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)
}
}
}
+33 -3
View File
@@ -17,6 +17,38 @@ import (
"hamlog/internal/applog" "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 // remoteFreqRe / remoteModeRe pull the optional tune request out of a
// ServiceRemoteCall packet: "<FREQ>10.136" (MHz) and "<MODE>FT8". Both accept // ServiceRemoteCall packet: "<FREQ>10.136" (MHz) and "<MODE>FT8". Both accept
// an optional closing tag for proper-XML senders. // 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 // otherwise leave their values as stray tokens and corrupt the
// "last token = callsign" heuristic. // "last token = callsign" heuristic.
if m := remoteFreqRe.FindStringSubmatch(text); m != nil { if m := remoteFreqRe.FindStringSubmatch(text); m != nil {
if mhz, err := strconv.ParseFloat(m[1], 64); err == nil && mhz > 0 { ev.TuneFreqHz = remoteTuneHz(m[1])
ev.TuneFreqHz = int64(mhz * 1e6)
}
text = strings.Replace(text, m[0], " ", 1) text = strings.Replace(text, m[0], " ", 1)
} }
if m := remoteModeRe.FindStringSubmatch(text); m != nil { if m := remoteModeRe.FindStringSubmatch(text); m != nil {
+122 -22
View File
@@ -3,6 +3,8 @@ package relaydev
import ( import (
"context" "context"
"fmt" "fmt"
"net/url"
"regexp"
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
@@ -20,13 +22,28 @@ import (
// //
// - one URL pair with {relay} in it, used for every relay: // - one URL pair with {relay} in it, used for every relay:
// http://192.168.1.9/relay?n={relay}&state=on // 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 // 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 // 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} // URLs with nothing in common between channels, and a template with {relay}
// cannot express that. // 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, // 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 // or answer with a web page nobody can parse reliably. Status therefore returns
// what we last commanded — see the method for what that costs. // what we last commanded — see the method for what that costs.
@@ -35,6 +52,7 @@ type httpGen struct {
offURLs []string offURLs []string
onPat string // pattern with {relay}, used when the per-relay URL is empty onPat string // pattern with {relay}, used when the per-relay URL is empty
offPat string offPat string
labels []string // index 0 = relay 1; what {value} resolves to
user string user string
pass string pass string
count int count int
@@ -45,8 +63,8 @@ type httpGen struct {
// NewHTTPGeneric builds the driver. onURLs/offURLs are per relay (index 0 = // 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 // relay 1) and may be short or hold empty entries; onPat/offPat are the
// fallback patterns. // fallback patterns; labels are the relay names {value} substitutes.
func NewHTTPGeneric(onURLs, offURLs []string, onPat, offPat, user, pass string, count int) Device { func NewHTTPGeneric(onURLs, offURLs []string, onPat, offPat, user, pass string, count int, labels []string) Device {
if count <= 0 { if count <= 0 {
count = len(onURLs) count = len(onURLs)
} }
@@ -55,7 +73,7 @@ func NewHTTPGeneric(onURLs, offURLs []string, onPat, offPat, user, pass string,
} }
return &httpGen{ return &httpGen{
onURLs: onURLs, offURLs: offURLs, onURLs: onURLs, offURLs: offURLs,
onPat: onPat, offPat: offPat, onPat: onPat, offPat: offPat, labels: labels,
user: user, pass: pass, count: count, user: user, pass: pass, count: count,
state: make([]bool, 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) Count() int { return h.count }
func (h *httpGen) Close() error { return nil } // stateless HTTP, nothing to release func (h *httpGen) Close() error { return nil } // stateless HTTP, nothing to release
// urlFor picks the per-relay URL, falling back to the pattern. // patFor returns the pattern for a direction, trimmed.
func (h *httpGen) urlFor(relay int, on bool) string { func (h *httpGen) patFor(on bool) string {
list, pat := h.offURLs, h.offPat
if on { 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 i := relay - 1; i >= 0 && i < len(list) {
if u := strings.TrimSpace(list[i]); u != "" { return strings.TrimSpace(list[i])
return u
}
} }
if pat = strings.TrimSpace(pat); pat == "" { 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])
}
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 ""
} }
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 { func (h *httpGen) Set(ctx context.Context, relay int, on bool) error {
if relay < 1 || relay > h.count { if relay < 1 || relay > h.count {
return fmt.Errorf("relay %d out of range 1..%d", relay, h.count) return fmt.Errorf("relay %d out of range 1..%d", relay, h.count)
} }
u := h.urlFor(relay, on) // Naming the direction matters: an operator who filled the ON URLs and left
if u == "" { // OFF empty gets a switch that latches, and "no URL configured" alone would
// Naming the direction matters: an operator who filled the ON URLs and // not say which half is missing.
// left OFF empty gets a switch that latches, and "no URL configured" dir := "OFF"
// alone would not say which half is missing. if on {
dir := "OFF" dir = "ON"
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) 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 { if _, err := get(ctx, u, h.user, h.pass); err != nil {
return err return err
} }
+84 -4
View File
@@ -22,7 +22,7 @@ func TestHTTPGenericPattern(t *testing.T) {
d := NewHTTPGeneric(nil, nil, d := NewHTTPGeneric(nil, nil,
srv.URL+"/relay?n={relay}&state=on", 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 { if err := d.Set(context.Background(), 2, true); err != nil {
t.Fatalf("Set on: %v", err) t.Fatalf("Set on: %v", err)
} }
@@ -53,7 +53,7 @@ func TestHTTPGenericPerRelayURLsWinOverThePattern(t *testing.T) {
d := NewHTTPGeneric( d := NewHTTPGeneric(
[]string{srv.URL + "/FF0101", "", srv.URL + "/weird/on"}, []string{srv.URL + "/FF0101", "", srv.URL + "/weird/on"},
[]string{srv.URL + "/FF0100", "", ""}, []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(), 1, true) // its own URL
_ = d.Set(context.Background(), 2, true) // empty → falls back to the pattern _ = 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 // 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. // name the direction, or the operator cannot tell which half is missing.
func TestHTTPGenericNamesTheMissingDirection(t *testing.T) { 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) err := d.Set(context.Background(), 1, false)
if err == nil || !strings.Contains(err.Error(), "OFF") { if err == nil || !strings.Contains(err.Error(), "OFF") {
t.Errorf("err = %v, want it to name the OFF direction", err) 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) { func TestHTTPGenericRemembersWhatItCommanded(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
defer srv.Close() 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) _ = d.Set(context.Background(), 2, true)
st, err := d.Status(context.Background()) st, err := d.Status(context.Background())
if err != nil { if err != nil {
+113
View File
@@ -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{}
+46 -2
View File
@@ -419,6 +419,45 @@ func drain(conn io.ReadWriteCloser) int {
return total 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) { func (c *Client) queryStatus() (*Status, error) {
c.connMu.Lock() c.connMu.Lock()
conn := c.conn conn := c.conn
@@ -438,7 +477,7 @@ func (c *Client) queryStatus() (*Status, error) {
return nil, fmt.Errorf("write status cmd: %w", err) return nil, fmt.Errorf("write status cmd: %w", err)
} }
buf := make([]byte, 11) 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) return nil, fmt.Errorf("read status: %w", err)
} }
// Reject anything that isn't a framed reply rather than decoding garbage into // 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 { if conn == nil {
return fmt.Errorf("steppir: not connected") 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() c.ioMu.Lock()
defer c.ioMu.Unlock() defer c.ioMu.Unlock()
log.Printf("steppir: → % X", pkt)
setDeadline(conn, 3*time.Second) setDeadline(conn, 3*time.Second)
if _, err := conn.Write(pkt); err != nil { if _, err := conn.Write(pkt); err != nil {
c.closeConn() c.closeConn()
+68
View File
@@ -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
}
+60
View File
@@ -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
View File
@@ -21,7 +21,7 @@ import (
const ( const (
// appVersion is stamped on every heartbeat (and could feed the About box). // appVersion is stamped on every heartbeat (and could feed the About box).
appVersion = "0.25.4" appVersion = "0.25.5"
// posthogHost is the PostHog ingestion endpoint. EU cloud by default; change // posthogHost is the PostHog ingestion endpoint. EU cloud by default; change
// to https://us.i.posthog.com for a US project. // to https://us.i.posthog.com for a US project.