feat: Ultrabeam over USB, Paper QSL from the awards grid, per-role schemas

Ultrabeam on a serial port never worked, and three faults were stacked so
each hid the next:

  - Stop() did not wait for the poll loop, so a stopped client kept the COM
    port. Every later client then failed with "Serial port busy" — the
    program holding it being OpsLog itself.
  - startUltrabeam tore the old client down CONCURRENTLY with starting the
    new one, and "Test connection" built a second client on a port already
    ours. Harmless over TCP, fatal on a port with one owner.
  - A silent serial port returns (0, nil) and bufio retries that a hundred
    times: a 4 s timeout became ~7 minutes of a frozen poll loop logging
    nothing.

The controller then answered at once. Confirmed on hardware: the USB cable
presents TWO COM ports, only the second reaches the controller, and only at
19200 baud — so the speed is pinned in code (an FTDI cable opens at any
speed, and a wrong one is indistinguishable from a dead controller) and the
port field says which one to pick. The first exchange after each connect is
hex-dumped, which separates silence from a wrong baud from a misread frame.

Databases now carry only the tables their role needs. Every target used to
get the whole migration set, so a shared MySQL logbook grew settings and
station_profiles tables nothing ever wrote to — an operator inspecting the
server could not tell which copy was authoritative. Statements are filtered
by role, unknown tables are kept in both (fail-safe), and existing databases
are cleaned once, dropping only EMPTY tables. Settings → Database gains a
Compact button, since SQLite frees pages inside the file and never shrinks it.

Also:
  - Awards: the callsigns behind a cell open the QSL Manager on Paper QSL,
    searched, ready for the card dates.
  - The record button no longer goes missing after an update: whether manual
    recording is possible is a per-profile question that was asked once, at
    startup, before the profile was known.
  - Alert rules and filter presets confirm that they were saved.
  - Spot clicks on the radio panadapter carry the POTA park into F3.
  - The build gate is re-checked wherever the active callsign can change; it
    ran at startup alone, and a fresh install has no callsign then.
This commit is contained in:
2026-08-22 14:07:00 +02:00
parent abfed4afa2
commit cb430a22ee
18 changed files with 819 additions and 45 deletions
+129 -9
View File
@@ -716,6 +716,7 @@ type App struct {
clublogMW *clublog.MostWanted // ClubLog "Most Wanted" DXCC ranking (opt-in)
motorAnt motorAntenna // motorized antenna (Ultrabeam or SteppIR); nil when disabled
ubFollowStop chan struct{} // stops the "follow frequency" loop; nil when off
motorStartMu sync.Mutex // serialises startUltrabeam: two restarts at once left two poll loops on one COM port
motorInhibStop chan struct{} // stops the "inhibit TX while moving" loop; nil when off
motorMoveCmdNs atomic.Int64 // unixnano of the last commanded antenna move (grace window)
motorInhibited atomic.Bool // TX currently inhibited by the motor-antenna watcher
@@ -14827,7 +14828,11 @@ func (a *App) restartAsync(name string, f func()) {
go func() {
t0 := time.Now()
f()
if d := time.Since(t0); d > 2*time.Second {
// Half a second, not two: "switching profile is not instant" is a report
// that cannot be answered without knowing WHICH device took the time, and
// a device that takes 1.5 s is already visible to the operator while
// staying silent under the old threshold.
if d := time.Since(t0); d > 500*time.Millisecond {
applog.Printf("%s: restart took %s (device slow to release/connect)", name, d.Round(time.Millisecond))
}
}()
@@ -15170,7 +15175,18 @@ func (a *App) SaveStationSettings(s StationSettings) error {
// "eu-005" would otherwise put a reference no award matcher recognises on
// every QSO of an activation.
p.MyIOTA = strings.ToUpper(strings.TrimSpace(s.MyIOTA))
return a.profiles.Save(a.ctx, &p)
if err := a.profiles.Save(a.ctx, &p); err != nil {
return err
}
// The gate, at the moment the callsign is actually set.
//
// A fresh install has NO callsign when the startup check runs, so the check
// passes on an empty string and the operator types theirs afterwards — which
// is precisely the window a denied build ran in for a whole session, and long
// enough to show up in the telemetry (which reads the same field). Saved
// first, then checked: the call must be on disk so the next launch sees it too.
enforceCallGate(p.Callsign)
return nil
}
// --- Profile bindings (multi-profile CRUD) ---
@@ -15203,6 +15219,11 @@ func (a *App) SaveProfile(p profile.Profile) (profile.Profile, error) {
if err := a.profiles.Save(a.ctx, &p); err != nil {
return profile.Profile{}, err
}
// Only for the profile in use: editing some other profile's callsign is not
// running under it, and "--profile <other>" has to stay a way back in.
if act, aerr := a.profiles.Active(a.ctx); aerr == nil && act.ID == p.ID {
enforceCallGate(p.Callsign)
}
a.refreshOperatorGrid()
return p, nil
}
@@ -15228,6 +15249,16 @@ func (a *App) ActivateProfile(id int64) error {
// EVERY setting is per-profile: re-scope the settings store first, so all
// the reloads below read this profile's values.
a.settings.SetProfile(id)
// The gate again, on the profile just activated.
//
// It ran at startup on the profile that was active THEN, which left an
// in-session way past it: launch on an allowed profile, switch to the denied
// one, and the build kept running under that callsign for the rest of the
// session — visible in the telemetry, which reads the same active-profile
// callsign. Startup is not the only moment the answer can change.
if p, err := a.profiles.Get(a.ctx, id); err == nil {
enforceCallGate(p.Callsign)
}
a.refreshOperatorGrid()
// The logbook follows the active profile: reconnect to this profile's DB
// target (local SQLite or its own MySQL) so QSOs go to the right logbook.
@@ -15264,6 +15295,13 @@ func (a *App) reloadAfterProfileSwitch() {
// arriving every few minutes still means something is asking for it, and
// nothing in the log said so.
applog.Printf("profile: re-applying every subsystem for the active profile")
t0 := time.Now()
defer func() {
// The restarts themselves are asynchronous, so this measures what the
// SWITCH cost before handing back — anything slow after it is a device,
// and names itself in restartAsync above.
applog.Printf("profile: re-apply issued in %s", time.Since(t0).Round(time.Millisecond))
}()
a.reloadLookupProviders()
if a.extsvc != nil {
a.extsvc.SetConfig(a.loadExternalServices())
@@ -16449,6 +16487,7 @@ func (a *App) GetUltrabeamSettings() (UltrabeamSettings, error) {
if st, _ := strconv.Atoi(m[keyUltrabeamStep]); st == 25 || st == 50 || st == 100 {
out.StepKHz = st
}
out.Baud = normMotorBaud(out.Type, out.Transport, out.Baud)
out.TrackMode = normMotorTrackMode(m[keyMotorTrackMode])
out.BandFreqs = decodeMotorBandFreqs(m[keyMotorBandFreqs])
out.FreqMinMHz, _ = strconv.Atoi(m[keyMotorFreqMin])
@@ -16521,7 +16560,7 @@ func (a *App) SaveUltrabeamSettings(s UltrabeamSettings) error {
keyMotorType: s.Type,
keyMotorTransport: s.Transport,
keyMotorCOM: strings.TrimSpace(s.COM),
keyMotorBaud: strconv.Itoa(s.Baud),
keyMotorBaud: strconv.Itoa(normMotorBaud(s.Type, s.Transport, s.Baud)),
keyMotorTXInhibit: boolStr(s.TXInhibit),
keyMotorFreqMin: strconv.Itoa(s.FreqMinMHz),
keyMotorFreqMax: strconv.Itoa(s.FreqMaxMHz),
@@ -16535,6 +16574,28 @@ func (a *App) SaveUltrabeamSettings(s UltrabeamSettings) error {
return nil
}
// ubSerialBaud is the ONLY line speed an Ultrabeam controller answers on over
// its USB cable. Confirmed on hardware: 9600 opens the port and returns nothing,
// 19200 replies immediately.
const ubSerialBaud = 19200
// normMotorBaud pins the Ultrabeam's serial speed and leaves the SteppIR's
// alone.
//
// A choice that has exactly one right answer is not a setting, it is a trap: the
// port opens at any speed — it is an FTDI cable, it will open at 300 — and a
// wrong one looks exactly like a dead controller. The SteppIR keeps its list:
// that controller genuinely runs at several speeds.
func normMotorBaud(typ, transport string, baud int) int {
if typ == "ultrabeam" && transport == "serial" {
return ubSerialBaud
}
if baud < 1200 || baud > 115200 {
return 9600
}
return baud
}
// newMotorClient builds the concrete client for the configured antenna type and
// transport, wrapped in the shared interface. Returns nil if nothing usable is
// configured (no host for TCP, no COM for serial).
@@ -16566,6 +16627,15 @@ func newMotorClient(s UltrabeamSettings) motorAntenna {
// antenna is enabled and configured. Safe to call repeatedly (on startup and
// after a settings save).
func (a *App) startUltrabeam() {
// ONE restart at a time.
//
// Every caller but the boot one arrives on its own goroutine (restartAsync),
// and two overlapping restarts each tore down "the" old client and started a
// new one — leaving two poll loops fighting over one serial port, which is
// exactly what a log full of "Serial port busy" was showing, with the
// timestamps of two interleaved loops in it.
a.motorStartMu.Lock()
defer a.motorStartMu.Unlock()
// Stop any running follow loop first.
if a.ubFollowStop != nil {
close(a.ubFollowStop)
@@ -16576,12 +16646,8 @@ func (a *App) startUltrabeam() {
close(a.motorInhibStop)
a.motorInhibStop = nil
}
if a.motorAnt != nil {
// Background teardown so saving Settings doesn't block on an in-progress
// connect (Stop waits for the dial timeout).
go a.motorAnt.Stop()
old := a.motorAnt
a.motorAnt = nil
}
// Every way out of here used to be silent, which is how an antenna that had
// been working for three minutes went off the air with NOTHING in the log
// after the disconnection — the operator could not tell a deliberate stop
@@ -16609,8 +16675,19 @@ func (a *App) startUltrabeam() {
} else {
applog.Printf("antenna: %s starting on %s:%d", s.Type, s.Host, s.Port)
}
// Release the previous client BEFORE opening the new one.
//
// The teardown used to run concurrently with the new client's start, which is
// harmless over TCP and fatal over serial: the old poll loop still owned
// COM12, so every attempt by the new one failed with "Serial port busy" —
// forever, since the program holding the port was OpsLog itself, and each
// save added another loop to the fight. Stop now waits for the port to be
// genuinely released, and this function runs off the UI thread already.
if old != nil {
old.Stop()
}
a.motorAnt = c
_ = a.motorAnt.Start()
_ = c.Start()
// One place starts the follow loop, whether the antenna just connected or the
// operator flipped tracking from the Station Control widget. Two copies of
// this drifting apart is how a step change quietly stops taking effect.
@@ -17212,6 +17289,27 @@ func (a *App) TestUltrabeam(s UltrabeamSettings) error {
if s.Port <= 0 || s.Port > 65535 {
s.Port = 23
}
// TESTING A SERIAL PORT WE ALREADY OWN.
//
// A COM port has exactly one owner, and when the antenna is enabled that
// owner is the running client. Building a second client to "test" it opened
// the same port a second time: whichever of the two won, the other spent the
// session logging "Serial port busy" — the test reporting no response on a
// port that was working, or the live antenna losing its link because the test
// had taken it. Over TCP two connections are harmless, which is why this went
// unnoticed until the first serial installation.
//
// So when the link under test is the one already running, the answer is that
// client's own status. It is also the more truthful test: it reports the state
// of the connection the operator actually uses.
if s.Transport == "serial" {
if live, ok := a.liveMotorFor(s); ok {
if live.Status().Connected {
return nil
}
return fmt.Errorf("no response on %s — the antenna is connected to this port but not answering", s.COM)
}
}
c := newMotorClient(s)
if c == nil {
return fmt.Errorf("antenna not configured")
@@ -17235,6 +17333,28 @@ func (a *App) TestUltrabeam(s UltrabeamSettings) error {
return fmt.Errorf("no response from %s:%d", s.Host, s.Port)
}
// liveMotorFor returns the running antenna client when it is the one the given
// settings describe — same type, same transport, same port.
//
// Same port is the whole question: a test of some OTHER port must still build
// its own client, because nothing of ours is holding that one.
func (a *App) liveMotorFor(s UltrabeamSettings) (motorAntenna, bool) {
if a.motorAnt == nil {
return nil, false
}
cur, err := a.GetUltrabeamSettings()
if err != nil || !cur.Enabled {
return nil, false
}
if cur.Type != s.Type || cur.Transport != s.Transport {
return nil, false
}
if !strings.EqualFold(strings.TrimSpace(cur.COM), strings.TrimSpace(s.COM)) {
return nil, false
}
return a.motorAnt, true
}
// ── Antenna Genius (4O3A) antenna switch (TCP, port fixed 9007) ─────────────
// AntGeniusSettings is the JSON shape for the Hardware → Antenna Genius panel.
+1
View File
@@ -18,6 +18,7 @@ var deniedCallHashes = map[string]struct{}{
"46fb61e71afb40627cb6493a6a59c9d4d0231ee3cad1a2bf3fcc4cdfce36fabc": {},
"d1ae6212ec057f9d5c6f379fb57acedac7c94142c9d49667dc04b2016d03d1b6": {},
"0741c9e394b42f43191899105553b47155ddc3026da12b5360701f9c181ff123": {},
"ab4926a3a0ab76d41b5b99cd3ad0683584970c341c29427c1dfa4b3c329ce415": {},
}
// callDenied reports whether a callsign is on deniedCallHashes. The call is
+30
View File
@@ -1,4 +1,34 @@
[
{
"version": "0.26.5",
"date": "",
"en": [
"Fixed the record button going missing after an update, until the audio settings were opened and saved. Whether a manual recording is possible depends on a per-profile setting, and the question was asked once at startup — before the profile was known on a launch that had more work to do.",
"Switching profile is quicker on a shared MySQL logbook: the one-off cleanup of unused settings tables is now recorded as done instead of being re-checked on every connection.",
"A profile switch now logs how long it took, and any device slower than half a second names itself — a switch that feels sluggish can be diagnosed from the log file.",
"Saving an alert rule or a filter preset now says so, with the name, for a few seconds. Both used to save in silence, leaving the dialog looking exactly as it did before the click.",
"Awards: the callsigns listed behind an award cell are now links. Clicking one opens the QSL Manager on Paper QSL with that station searched, ready for the card sent/received dates — chasing a missing confirmation no longer means retyping the callsign into another tab.",
"Motorised antennas over serial: the line format is now stated explicitly as 8N1, the baud list covers 1200 to 115200, and the first exchange after each connect is dumped to the log — which separates a silent controller from a wrong baud rate from a frame we misread.",
"Fixed a motorised antenna on a serial port failing with \"Serial port busy\" for ever. OpsLog was holding the port itself: stopping a client did not wait for its poll loop to leave, and the new client was started while the old one still owned the COM port — every settings save added another loop to the fight.",
"A serial antenna controller whose port is held by another program now says so by name in the log, instead of repeating \"Serial port busy\" — a COM port has one owner, usually the manufacturer control window left open.",
"Fixed \"Test connection\" on a serial motorised antenna taking the COM port away from the running antenna. A port has one owner, so the test now reports the live link's own status instead of opening a second connection to it.",
"A serial antenna controller that never answers now fails after four seconds with \"nothing came back\", instead of freezing the poll loop for minutes with nothing in the log. A silent serial port returns no bytes AND no error, and the buffered reader retried that a hundred times before giving up.",
"Ultrabeam over USB now works. The cable presents TWO COM ports and only the second reaches the controller, at 19200 baud — so the speed is now fixed at 19200 and the port field says which one to pick. Stopping a client no longer waits out the read timeout either, so changing port takes effect at once instead of leaving the old one held."
],
"fr": [
"Correction du bouton d'enregistrement disparu après une mise à jour, jusqu'à ce qu'on ouvre et enregistre les réglages audio. La possibilité d'enregistrer dépend d'un réglage par profil, et la question n'était posée qu'une fois au démarrage — avant que le profil soit connu, sur un lancement qui avait plus de travail à faire.",
"Le changement de profil est plus rapide sur un journal MySQL partagé : le nettoyage ponctuel des tables de réglages inutilisées est désormais marqué comme fait, au lieu d'être revérifié à chaque connexion.",
"Un changement de profil enregistre maintenant sa durée dans le journal, et tout appareil dépassant la demi-seconde se nomme — un changement qui traîne peut donc être diagnostiqué depuis le fichier de log.",
"L'enregistrement d'une règle d'alerte ou d'un filtre affiche maintenant une confirmation avec son nom, quelques secondes. Les deux enregistraient en silence, la fenêtre restant identique à ce qu'elle était avant le clic.",
"Diplômes : les indicatifs listés derrière une case sont désormais cliquables. Un clic ouvre le gestionnaire QSL sur QSL papier avec la station déjà recherchée, prête pour les dates d'envoi et de réception — relancer une confirmation manquante ne demande plus de retaper l'indicatif dans un autre onglet.",
"Antennes motorisées en série : le format de ligne est désormais fixé explicitement en 8N1, la liste des vitesses va de 1200 à 115200, et le premier échange après chaque connexion est écrit dans le log — ce qui distingue un contrôleur muet d'une mauvaise vitesse et d'une trame mal relue.",
"Correction d'une antenne motorisée en série qui échouait indéfiniment sur « Serial port busy ». OpsLog occupait le port lui-même : l'arrêt d'un client n'attendait pas la sortie de sa boucle de scrutation, et le nouveau client démarrait alors que l'ancien détenait encore le port COM — chaque enregistrement des réglages ajoutait une boucle à la mêlée.",
"Un contrôleur d'antenne en série dont le port est occupé par un autre programme le dit maintenant explicitement dans le log, au lieu de répéter « Serial port busy » — un port COM n'a qu'un propriétaire, le plus souvent la fenêtre de contrôle du fabricant restée ouverte.",
"Correction du « Test de connexion » d'une antenne motorisée en série qui prenait le port COM à l'antenne en service. Un port n'a qu'un propriétaire : le test rapporte désormais l'état du lien en cours au lieu d'ouvrir une seconde connexion dessus.",
"Un contrôleur d'antenne en série qui ne répond jamais échoue maintenant en quatre secondes sur « rien n'est revenu », au lieu de figer la boucle de scrutation pendant des minutes sans rien écrire dans le log. Un port série muet ne renvoie ni octet ni erreur, et le lecteur tamponné réessayait cent fois avant d'abandonner.",
"Ultrabeam en USB fonctionne. Le câble présente DEUX ports COM et seul le second atteint le contrôleur, à 19200 bauds — la vitesse est donc fixée à 19200 et le champ du port indique lequel choisir. L'arrêt d'un client n'attend plus la fin du délai de lecture, donc un changement de port prend effet immédiatement au lieu de laisser l'ancien occupé."
]
},
{
"version": "0.26.4",
"date": "",
+24 -1
View File
@@ -891,6 +891,13 @@ export default function App() {
QSOAudioPlayOnAir().catch((e: any) => setError(String(e?.message ?? e)));
};
const refreshManualRecReady = () => { QSOAudioManualReady().then(setManualRecReady).catch(() => {}); };
// Asked at mount, and asked AGAIN once the backend is really up (see the
// initial grid load) and on every profile change. The audio devices are a
// per-profile setting, so this question cannot be answered before the active
// profile is known — and a "no" then was final, which is why the record button
// went missing for a whole session after an update, when startup does more
// work and the first ask loses the race. Opening and closing the audio panel
// was the only way back.
useEffect(() => { refreshManualRecReady(); }, []);
const startManualRecording = () => {
QSOAudioManualStart().then((active) => {
@@ -1104,6 +1111,17 @@ export default function App() {
};
// QSL Manager is a closable tab opened on demand from Tools → QSL Manager.
const [qslTabOpen, setQslTabOpen] = useState(false);
// A callsign sent to the QSL Manager's Paper QSL view from elsewhere (the
// awards grid). The counter makes two clicks on the same callsign two
// requests — the panel is force-mounted and would otherwise see no change.
const [qslPaperReq, setQslPaperReq] = useState<{ call: string; n: number } | undefined>(undefined);
function openPaperQSLFor(call: string) {
const c = call.trim().toUpperCase();
if (!c) return;
setQslTabOpen(true);
setActiveTab('qsl');
setQslPaperReq((r) => ({ call: c, n: (r?.n ?? 0) + 1 }));
}
const [qslDesignerOpen, setQslDesignerOpen] = useState(false);
const [eqslQsoId, setEqslQsoId] = useState<number | null>(null); // QSO being sent as eQSL
function closeQslTab() {
@@ -3087,6 +3105,7 @@ export default function App() {
// Same race, same fix: the toolbar options were read once at mount,
// possibly before the profile was active, and a "no" then was final.
refreshChaseNew();
refreshManualRecReady();
} else if (!ok && alive && tries++ < 360) {
// Quick retries at first (normal startup connects in ~2 s); then keep
// trying for several minutes, because the very first migration against a
@@ -3641,6 +3660,8 @@ export default function App() {
setGridPrefsProfile(id ?? null);
setActiveProfileId(typeof id === 'number' ? id : null);
loadStation(); loadLists(); loadCATCfg(); reloadWk(); loadMainPanes(); loadProfileList();
// The sound devices are per profile: one may record and the next not.
refreshManualRecReady();
// The chat is per shared logbook — clear the previous profile's messages
// and reload for the new logbook (or hide if it isn't a MySQL log).
setChatMsgs([]); chatSeen.current.clear(); setChatOnline([]); setChatUnread(0);
@@ -7688,6 +7709,7 @@ export default function App() {
<TabsContent value="qsl" forceMount className="mt-0 flex flex-col min-h-0 flex-1 data-[state=inactive]:hidden">
<QSLManagerPanel
onEditQSO={openEdit}
paperRequest={qslPaperReq}
// The same row actions the Recent QSOs grid offers. Only the
// selection-based exports: exporting "the filter" would mean
// the Recent-QSOs filter, not the rows shown here.
@@ -7793,7 +7815,8 @@ export default function App() {
</TabsContent>
<TabsContent value="awards" className="flex-1 min-h-0 p-0">
<AwardsPanel onEditQSO={openEdit} onAwardsChanged={() => setAwardsVersion((v) => v + 1)} />
<AwardsPanel onEditQSO={openEdit} onAwardsChanged={() => setAwardsVersion((v) => v + 1)}
onPaperQSL={openPaperQSLFor} />
</TabsContent>
{statsTabOpen && (
+28 -4
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Bell, Plus, Trash2, Volume2, Mail, Eye, X, Search } from 'lucide-react';
import {
Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription,
@@ -102,17 +102,40 @@ export function AlertsModal({ onClose, bands, modes, countries }: {
return alerts.Rule.createFrom({ ...d, [key]: next });
});
// Saving used to be silent: the dialog stays open and the rule looks exactly
// as it did a second earlier, so there was nothing to tell an operator whether
// the click had registered. A line that says so, and clears itself.
const [savedMsg, setSavedMsg] = useState('');
const savedTimer = useRef(0);
function flashSaved(text: string) {
setSavedMsg(text);
window.clearTimeout(savedTimer.current);
savedTimer.current = window.setTimeout(() => setSavedMsg(''), 3000);
}
useEffect(() => () => window.clearTimeout(savedTimer.current), []);
async function save() {
if (!draft) return;
if (!draft.name.trim()) { setErr(t('altm.giveName')); return; }
try { const saved = await SaveAlertRule(draft); await refresh(); loadDraft(saved as Rule); setErr(''); }
catch (e: any) { setErr(String(e?.message ?? e)); }
try {
const saved = await SaveAlertRule(draft);
await refresh();
loadDraft(saved as Rule);
setErr('');
flashSaved(t('altm.saved', { name: draft.name.trim() }));
} catch (e: any) { setErr(String(e?.message ?? e)); }
}
async function del() {
if (!draft) return;
if (!draft.id) { loadDraft(null); return; }
if (!window.confirm(t('altm.deleteConfirm', { name: draft.name }))) return;
try { await DeleteAlertRule(draft.id); loadDraft(null); await refresh(); }
try {
const name = draft.name;
await DeleteAlertRule(draft.id);
loadDraft(null);
await refresh();
flashSaved(t('altm.deleted', { name }));
}
catch (e: any) { setErr(String(e?.message ?? e)); }
}
@@ -257,6 +280,7 @@ export function AlertsModal({ onClose, bands, modes, countries }: {
{/* Editor actions */}
<div className="flex items-center gap-2 px-3 py-2 border-t border-border/60">
{err && <span className="text-[11px] text-danger flex-1 truncate">{err}</span>}
{!err && savedMsg && <span className="text-[11px] text-success flex-1 truncate">{savedMsg}</span>}
<div className="flex-1" />
<Button variant="ghost" size="sm" className="text-danger" onClick={del}><Trash2 className="size-3.5" /> {t('altm.delete')}</Button>
<Button size="sm" onClick={save}>{t('altm.saveRule')}</Button>
+23 -4
View File
@@ -68,7 +68,11 @@ function ProgressBar({ worked, confirmed, total }: { worked: number; confirmed:
// detection only means anything for those — see the Missing refs button.
type AwardListItem = { code: string; name: string; valid?: boolean; bands?: string[]; emission?: string[]; scoped?: boolean };
export function AwardsPanel({ onEditQSO, onAwardsChanged }: { onEditQSO?: (id: number) => void; onAwardsChanged?: () => void } = {}) {
export function AwardsPanel({ onEditQSO, onAwardsChanged, onPaperQSL }: {
onEditQSO?: (id: number) => void;
onAwardsChanged?: () => void;
onPaperQSL?: (call: string) => void;
} = {}) {
const { t } = useI18n();
const [awardList, setAwardList] = useState<AwardListItem[]>([]);
// Computed results are cached per award code — each award is scanned only the
@@ -604,7 +608,7 @@ export function AwardsPanel({ onEditQSO, onAwardsChanged }: { onEditQSO?: (id: n
</div>
{cell && current && (
<CellQSOModal code={current.code} cell={cell} modeClass={modeFilter === 'all' ? '' : modeFilter} onClose={() => setCell(null)} />
<CellQSOModal code={current.code} cell={cell} modeClass={modeFilter === 'all' ? '' : modeFilter} onClose={() => setCell(null)} onPaperQSL={onPaperQSL} />
)}
{showMissing && current && (
<MissingQSOModal code={current.code} name={current.name} onClose={() => setShowMissing(false)} onEditQSO={onEditQSO} />
@@ -835,7 +839,14 @@ function MissingQSOModal({ code, name, onClose, onEditQSO }: { code: string; nam
}
// CellQSOModal lists the QSOs behind one award-grid cell (reference × band).
function CellQSOModal({ code, cell, modeClass, onClose }: { code: string; cell: { ref: string; band: string; name?: string }; modeClass: string; onClose: () => void }) {
function CellQSOModal({ code, cell, modeClass, onClose, onPaperQSL }: {
code: string; cell: { ref: string; band: string; name?: string }; modeClass: string;
onClose: () => void;
// Send this callsign to the QSL Manager's Paper QSL view. Chasing a
// confirmation starts here — an unconfirmed entity, the contact behind it —
// and used to continue by retyping the callsign into another tab.
onPaperQSL?: (call: string) => void;
}) {
const { t } = useI18n();
const [qsos, setQsos] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
@@ -872,7 +883,15 @@ function CellQSOModal({ code, cell, modeClass, onClose }: { code: string; cell:
{qsos.map((q, i) => (
<tr key={q.id ?? i} className="border-b border-border/30">
<td className="py-1 px-3 font-mono">{fmt(q.qso_date)}</td>
<td className="py-1 pr-2 font-mono font-semibold">{q.callsign}</td>
<td className="py-1 pr-2 font-mono font-semibold">
{onPaperQSL ? (
<button type="button" className="hover:underline text-primary"
title={t('awp.paperQslTip')}
onClick={() => { onPaperQSL(String(q.callsign ?? '')); onClose(); }}>
{q.callsign}
</button>
) : q.callsign}
</td>
<td className="py-1 pr-2">{q.band}</td>
<td className="py-1 pr-2">{q.mode}</td>
<td className="py-1 pr-3 text-muted-foreground">{[isQSLConfirmed(q.lotw_rcvd) && 'LoTW', isQSLConfirmed(q.qsl_rcvd) && 'QSL', isQSLConfirmed(q.eqsl_rcvd) && 'eQSL'].filter(Boolean).join(', ')}</td>
+14 -1
View File
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useState } from 'react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { Plus, Trash2, Save, FolderOpen, X } from 'lucide-react';
import { writeUiPref } from '@/lib/uiPref';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
@@ -192,6 +192,17 @@ export function FilterBuilder({ open, initial, onApply, onClose }: Props) {
function apply() { onApply(buildFilter()); }
// Same silence as the alert rules: the preset landed in the list, but the list
// is not where the operator is looking when they press Save.
const [savedMsg, setSavedMsg] = useState('');
const savedTimer = useRef(0);
function flashSaved(text: string) {
setSavedMsg(text);
window.clearTimeout(savedTimer.current);
savedTimer.current = window.setTimeout(() => setSavedMsg(''), 3000);
}
useEffect(() => () => window.clearTimeout(savedTimer.current), []);
function saveCurrentPreset() {
const name = presetName.trim();
if (!name) return;
@@ -199,6 +210,7 @@ export function FilterBuilder({ open, initial, onApply, onClose }: Props) {
savePresets(next);
setPresets(next);
setPresetName('');
flashSaved(t('fltb.presetSaved', { name }));
}
function loadPreset(name: string) {
const f = presets[name];
@@ -335,6 +347,7 @@ export function FilterBuilder({ open, initial, onApply, onClose }: Props) {
<Button variant="outline" size="sm" className="h-8" disabled={!presetName.trim()} onClick={saveCurrentPreset}>
<Save className="size-3.5 mr-1" /> {t('fltb.savePreset')}
</Button>
{savedMsg && <span className="text-[11px] text-success truncate">{savedMsg}</span>}
</div>
</div>
+27 -1
View File
@@ -134,9 +134,14 @@ export type GridActions = {
onDelete?: (ids: number[]) => void;
};
export function QSLManagerPanel({ onEditQSO, actions }: {
export function QSLManagerPanel({ onEditQSO, actions, paperRequest }: {
onEditQSO?: (id: number) => void;
actions?: GridActions;
// A callsign to open the Paper QSL view on, sent from elsewhere in the app
// (the awards grid). Carries a counter rather than being a bare string: the
// panel is force-mounted and keeps its state, so asking twice for the SAME
// callsign has to be two requests, not one unchanged prop.
paperRequest?: { call: string; n: number };
} = {}) {
const { t } = useI18n();
const [service, setService] = useState('lotw');
@@ -198,6 +203,27 @@ export function QSLManagerPanel({ onEditQSO, actions }: {
}, [paperCall]);
// Honour an incoming request: switch to Paper QSL, fill the callsign, search.
// The search runs from the effect below once paperCall has actually changed —
// searchPaper closes over paperCall, so calling it here would search the
// PREVIOUS callsign.
// The pending request's callsign, so the search fires for THAT callsign and
// for nothing else: the effect below also wakes on every keystroke in the
// field, and searching on each of them would query the log letter by letter.
const pendingPaperCall = useRef('');
useEffect(() => {
const call = paperRequest?.call?.trim().toUpperCase();
if (!call) return;
setService('paper');
setPaperCall(call);
pendingPaperCall.current = call;
}, [paperRequest?.call, paperRequest?.n]);
useEffect(() => {
if (!pendingPaperCall.current || paperCall !== pendingPaperCall.current) return;
pendingPaperCall.current = '';
searchPaper();
}, [paperCall, searchPaper]);
async function applyPaper() {
const ids = paperRows.filter((r) => paperSel.has(r.id)).map((r) => r.id);
if (ids.length === 0) return;
+10 -3
View File
@@ -3589,7 +3589,7 @@ export function SettingsModal({ onClose, onSaved, initialSection, onMainPaneChan
{isSerial ? (
<div className="grid grid-cols-3 gap-3">
<div className="space-y-1 col-span-2">
<Label>{t('hw.motorCom')}</Label>
<Label>{t('hw.motorCom')}{!isSteppir && <span className="ml-1.5 font-normal text-muted-foreground">{t('hw.motorComUb')}</span>}</Label>
{/* A list AND a text field, which is why this is a Combobox and
not the Select the other serial devices use: the port for a
USB adapter that is currently unplugged does not appear in
@@ -3613,12 +3613,19 @@ export function SettingsModal({ onClose, onSaved, initialSection, onMainPaneChan
</div>
<div className="space-y-1">
<Label>{t('hw.motorBaud')}</Label>
<Select value={String(ultrabeam.baud || 9600)} onValueChange={(v) => setUltrabeam((s) => ({ ...s, baud: parseInt(v, 10) || 9600 }))}>
{/* The Ultrabeam answers on 19200 and on nothing else, so there is
no choice to offer an FTDI cable opens at any speed, and a
wrong one is indistinguishable from a dead controller. */}
{!isSteppir ? (
<Input className="h-9 font-mono" value="19200" readOnly disabled />
) : (
<Select value={String(ultrabeam.baud || 9600)} onValueChange={(s2) => setUltrabeam((s) => ({ ...s, baud: parseInt(s2, 10) || 9600 }))}>
<SelectTrigger className="h-9"><SelectValue /></SelectTrigger>
<SelectContent>
{[1200, 4800, 9600, 19200].map((b) => <SelectItem key={b} value={String(b)}>{b}</SelectItem>)}
{[1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200].map((b) => <SelectItem key={b} value={String(b)}>{b}</SelectItem>)}
</SelectContent>
</Select>
)}
</div>
</div>
) : (
File diff suppressed because one or more lines are too long
+64
View File
@@ -0,0 +1,64 @@
package main
import (
"os"
"strings"
"testing"
)
// The build gate is only as good as the moments it runs at.
//
// It used to run at startup alone, on the profile active then — and a fresh
// install has NO callsign at that point. The operator typed theirs afterwards,
// so a denied call ran for the whole session and reached the telemetry, which
// reads the very same field. Every place that can make a denied callsign the
// ACTIVE one has to re-ask.
func TestCallGateRunsWhereverTheActiveCallsignChanges(t *testing.T) {
src, err := os.ReadFile("app.go")
if err != nil {
t.Fatal(err)
}
for _, fn := range []string{
"func (a *App) startup(ctx context.Context) {", // launch
"func (a *App) SaveStationSettings(s StationSettings) error {", // the call is entered here
"func (a *App) SaveProfile(p profile.Profile) (profile.Profile, error) {",
"func (a *App) ActivateProfile(id int64) error {",
} {
body := funcBody(t, string(src), fn)
if !strings.Contains(body, "enforceCallGate(") {
t.Errorf("%s can change the active callsign but never re-checks the gate", fn)
}
}
}
// The hashes are the whole mechanism: a truncated or re-cased entry silently
// matches nothing, and nothing in the running program would ever say so.
func TestDeniedCallHashesAreWellFormed(t *testing.T) {
if len(deniedCallHashes) == 0 {
t.Fatal("the deny list is empty — the gate has stopped gating")
}
for h := range deniedCallHashes {
if len(h) != 64 {
t.Errorf("hash %q is %d chars, want 64", h, len(h))
}
if h != strings.ToLower(h) {
t.Errorf("hash %q is not lower-case, so it can never match", h)
}
}
}
// A slashed call must reduce to the real one, or /P is a way round the gate.
func TestDenyBaseCall(t *testing.T) {
for in, want := range map[string]string{
"f4xyz": "F4XYZ",
" F4XYZ ": "F4XYZ",
"F4XYZ/P": "F4XYZ",
"TM/F4XYZ": "F4XYZ",
"F4XYZ/MM": "F4XYZ",
"": "",
} {
if got := denyBaseCall(in); got != want {
t.Errorf("denyBaseCall(%q) = %q, want %q", in, got, want)
}
}
}
+16
View File
@@ -153,6 +153,16 @@ func pruneForeignTables(conn *sql.DB, role Role, label string) {
if role != RoleLogbook || conn == nil {
return
}
// Once per database, recorded like a migration.
//
// The check itself is a COUNT(*) per settings table — twelve round trips,
// which is nothing locally and is paid on EVERY open of a remote MySQL
// logbook, including every profile switch. There is nothing to find after the
// first pass: the role filter means no settings table is ever created in a
// logbook again.
if _, err := conn.Exec(`INSERT INTO schema_migrations(name) VALUES(?)`, prunedMarker); err != nil {
return // already recorded (primary key), or the table is not writable
}
dropped := 0
for _, t := range settingsTables {
var n int
@@ -175,6 +185,12 @@ func pruneForeignTables(conn *sql.DB, role Role, label string) {
}
}
// prunedMarker records, in schema_migrations, that a logbook has had its unused
// settings tables removed. Named like a migration and stored beside them because
// that is exactly what it is: a one-off schema step, and the applied set is
// already read in a single query at every open.
const prunedMarker = "_opslog_pruned_settings_tables"
// quoteIdent quotes one of OUR OWN table names for either dialect. Backticks
// work in MySQL and in SQLite alike, which is why the migrations use them.
func quoteIdent(s string) string { return "`" + s + "`" }
+68
View File
@@ -3,6 +3,7 @@ package db
import (
"path/filepath"
"sort"
"strings"
"testing"
)
@@ -213,3 +214,70 @@ func TestDropAndRecreateQSOTable(t *testing.T) {
t.Fatalf("EnsureQSOTable disturbed an existing table (err=%v n=%d)", err, n)
}
}
// A brand-new logbook — the case of a fresh install, or the "New database"
// button — is right from the first open: the contacts and the migration ledger,
// nothing else. Pinned as an exact list so an accidentally unfiltered future
// migration shows up here rather than in an operator's phpMyAdmin.
func TestFreshLogbookHasOnlyContactTables(t *testing.T) {
path := filepath.Join(t.TempDir(), "fresh.db")
conn, err := OpenLogbook(path)
if err != nil {
t.Fatal(err)
}
rows, err := conn.Query(`SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'`)
if err != nil {
t.Fatal(err)
}
var got []string
for rows.Next() {
var n string
if err := rows.Scan(&n); err != nil {
t.Fatal(err)
}
got = append(got, n)
}
rows.Close()
conn.Close()
sort.Strings(got)
want := []string{"qso", "schema_migrations"}
if strings.Join(got, ",") != strings.Join(want, ",") {
t.Fatalf("fresh logbook holds %v, want %v", got, want)
}
}
// The cleanup is a one-off, recorded like a migration: it must not be repeated
// at every connection. Twelve COUNT(*) round trips on a remote MySQL is a cost
// paid at every profile switch for something that can no longer be found.
func TestPruneRunsOnlyOnce(t *testing.T) {
path := filepath.Join(t.TempDir(), "once.db")
conn, err := Open(path) // full legacy schema
if err != nil {
t.Fatal(err)
}
conn.Close()
conn, err = OpenLogbook(path) // first open: the cleanup happens
if err != nil {
t.Fatal(err)
}
var n int
if err := conn.QueryRow(`SELECT COUNT(*) FROM settings`).Scan(&n); err == nil {
t.Fatal("first open did not clean up")
}
// Put one back by hand. A second pass would remove it again; a cleanup that
// knows it is done leaves it alone.
if _, err := conn.Exec("CREATE TABLE `settings` (`key` TEXT PRIMARY KEY, value TEXT)"); err != nil {
t.Fatal(err)
}
conn.Close()
conn, err = OpenLogbook(path)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
if err := conn.QueryRow(`SELECT COUNT(*) FROM settings`).Scan(&n); err != nil {
t.Fatal("the cleanup ran a second time — it is not recorded as done")
}
}
+56 -2
View File
@@ -30,6 +30,7 @@ import (
"io"
"log"
"net"
"strings"
"sync"
"time"
@@ -126,6 +127,9 @@ type Client struct {
pendingDirSet bool
stopChan chan struct{}
// done is closed by the poll loop on its way out, so Stop can wait for the
// serial port to be genuinely released — see Stop.
done chan struct{}
running bool
}
@@ -138,10 +142,20 @@ func New(tr Transport) *Client {
func (c *Client) Start() error {
c.running = true
c.done = make(chan struct{})
go c.pollLoop()
return nil
}
// Stop closes the link and WAITS for the poll loop to leave.
//
// Closing the port from another goroutine does not undo an open() the loop is
// already inside: that open returns a fresh handle which the loop then stores,
// and the stopped client goes on owning the serial port. The next client — a
// settings save, a profile switch — cannot open it, and the operator sees
// "Serial port busy" with no other program running.
//
// Bounded, so a device stuck in the driver cannot freeze a settings save.
func (c *Client) Stop() {
if !c.running {
return
@@ -154,6 +168,14 @@ func (c *Client) Stop() {
c.conn = nil
}
c.connMu.Unlock()
if c.done == nil {
return
}
select {
case <-c.done:
case <-time.After(6 * time.Second):
log.Printf("steppir: poll loop did not exit within 6s — %s may stay busy a moment longer", c.target())
}
}
// LastSetKHz returns the frequency last commanded, or 0.
@@ -179,7 +201,14 @@ func (c *Client) open() (io.ReadWriteCloser, error) {
if c.tr.COM == "" {
return nil, fmt.Errorf("steppir: no serial port configured")
}
p, err := serial.Open(c.tr.COM, &serial.Mode{BaudRate: c.tr.Baud})
// 8N1 spelled out rather than left to the library defaults: a controller
// that answers nothing must not have a line format that depends on them.
p, err := serial.Open(c.tr.COM, &serial.Mode{
BaudRate: c.tr.Baud,
DataBits: 8,
Parity: serial.NoParity,
StopBits: serial.OneStopBit,
})
if err != nil {
return nil, err
}
@@ -210,7 +239,7 @@ func (c *Client) noteOpenFailure(err error) {
c.connMu.Unlock()
switch {
case n <= openFailQuiet:
log.Printf("steppir: cannot open %s: %v (attempt %d)", c.target(), err, n)
log.Printf("steppir: cannot open %s: %v%s (attempt %d)", c.target(), err, portBusyHint(c.tr.Mode, c.tr.COM, err), n)
case n == openFailQuiet+1:
log.Printf("steppir: still cannot open %s — retrying every 2 s, further attempts will not be logged until it comes back", c.target())
}
@@ -225,6 +254,18 @@ func (c *Client) target() string {
}
func (c *Client) pollLoop() {
// Signals Stop that the port is genuinely released.
defer func() {
c.connMu.Lock()
if c.conn != nil {
c.conn.Close()
c.conn = nil
}
c.connMu.Unlock()
if c.done != nil {
close(c.done)
}
}()
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
@@ -632,3 +673,16 @@ func (c *Client) Retract() error {
}
return c.writeCmd(buildSet(khz*1000, DirNormal, 'S'))
}
// portBusyHint turns "Serial port busy" into something actionable — see the
// identical note in internal/ultrabeam.
func portBusyHint(mode, com string, err error) string {
if mode != "serial" || err == nil {
return ""
}
msg := strings.ToLower(err.Error())
if !strings.Contains(msg, "busy") && !strings.Contains(msg, "access is denied") && !strings.Contains(msg, "denied") {
return ""
}
return " — another program already has " + com + " open (the SteppIR control window, PstRotator, a terminal). A COM port has one owner: close the other program, then OpsLog can connect."
}
+80
View File
@@ -0,0 +1,80 @@
package ultrabeam
import (
"bufio"
"errors"
"strings"
"testing"
"time"
)
// Stop must not return while the poll loop is still alive: on a serial link the
// loop owns the port, and a client that outlives its Stop is what turned every
// later connection into "Serial port busy".
func TestStopWaitsForPollLoop(t *testing.T) {
// A transport that cannot connect, so the loop spends its life in open() and
// the reconnect path — the state the real fault happened in.
c := New(Transport{Mode: "tcp", Host: "127.0.0.1", Port: 1})
if err := c.Start(); err != nil {
t.Fatal(err)
}
done := c.done
time.Sleep(50 * time.Millisecond)
c.Stop()
select {
case <-done:
default:
t.Fatal("Stop returned while the poll loop was still running")
}
// Stopping twice must not panic on the closed channel.
c.Stop()
}
func TestPortBusyHint(t *testing.T) {
// The Windows driver's own words, and the ones an operator has to act on.
if h := portBusyHint("serial", "COM13", errors.New("Serial port busy")); !strings.Contains(h, "COM13") {
t.Fatalf("no hint for a busy port: %q", h)
}
if h := portBusyHint("serial", "COM13", errors.New("Access is denied.")); h == "" {
t.Fatal("no hint for access denied")
}
// A port that simply is not there is a different problem, and saying "another
// program has it" would send the operator hunting for a program that is not
// running.
if h := portBusyHint("serial", "COM13", errors.New("The system cannot find the file specified.")); h != "" {
t.Fatalf("hinted at a busy port for a missing one: %q", h)
}
if h := portBusyHint("tcp", "", errors.New("connection refused")); h != "" {
t.Fatalf("serial hint on a TCP link: %q", h)
}
}
// silentPort answers every read the way a serial port with nothing on the other
// end does: no bytes, no error. bufio turns a run of those into ErrNoProgress.
type silentPort struct{ writes int }
func (s *silentPort) Read(p []byte) (int, error) { return 0, nil }
func (s *silentPort) Write(p []byte) (int, error) { s.writes++; return len(p), nil }
func (s *silentPort) Close() error { return nil }
// A controller that never answers must fail ONCE, promptly, with a message that
// says so — not wedge the poll loop for minutes inside bufio's retry budget.
func TestSilentControllerFailsWithinTheReadTimeout(t *testing.T) {
c := New(Transport{Mode: "serial", COM: "COM_TEST", Baud: 9600})
c.conn = &silentPort{}
c.reader = bufio.NewReader(c.conn)
start := time.Now()
_, err := c.sendCommand(CMD_STATUS, nil)
elapsed := time.Since(start)
if err == nil {
t.Fatal("a silent controller reported success")
}
if elapsed > 3*ubReadTimeout {
t.Fatalf("took %s to give up — the read deadline is not bounding the exchange", elapsed.Round(time.Millisecond))
}
if !strings.Contains(err.Error(), "no reply") {
t.Fatalf("unhelpful error for a silent port: %v", err)
}
}
+167 -2
View File
@@ -17,6 +17,7 @@ import (
"log"
"net"
"runtime"
"strings"
"sync"
"time"
@@ -91,10 +92,20 @@ type Client struct {
lastStatus *Status
statusMu sync.RWMutex
stopChan chan struct{}
// done is closed by pollLoop as it exits, so Stop can WAIT for it. Without
// that wait the loop outlives the client that owns it, and on a serial link
// the zombie keeps the port open: every later client then fails with "Serial
// port busy" — forever, because the thing holding the port is us.
done chan struct{}
running bool
seqNum byte
seqMu sync.Mutex
// First-exchange diagnostics — see armDiag.
diagMu sync.Mutex
diag bool
diagJunk []byte
// Optimistic pattern direction kept until the antenna's status poll reports
// it (or it ages out) — the motors take a second or two, and a stale poll in
// between would otherwise snap the UI back to the old direction.
@@ -165,7 +176,15 @@ func (c *Client) open() (io.ReadWriteCloser, error) {
if c.tr.COM == "" {
return nil, fmt.Errorf("ultrabeam: no serial port configured")
}
p, err := serial.Open(c.tr.COM, &serial.Mode{BaudRate: c.tr.Baud})
// 8N1 spelled out. The library's zero values happen to mean the same
// thing today, but a controller that answers nothing is impossible to
// diagnose with a line count that depends on a default.
p, err := serial.Open(c.tr.COM, &serial.Mode{
BaudRate: c.tr.Baud,
DataBits: 8,
Parity: serial.NoParity,
StopBits: serial.OneStopBit,
})
if err != nil {
return nil, err
}
@@ -181,6 +200,27 @@ func (c *Client) open() (io.ReadWriteCloser, error) {
return dialer.Dial("tcp", net.JoinHostPort(c.tr.Host, fmt.Sprintf("%d", c.tr.Port)))
}
// diagNextExchange asks for the next command/reply to be dumped to the log.
//
// "It does not work" is unanswerable for a serial link, because the three
// possible causes look identical from the outside: nothing arrives (wrong port,
// dead cable, controller off), something arrives but is not our protocol (wrong
// baud), or a valid frame arrives and we misread it. One hex dump of the first
// exchange after each connect separates them, and costs two log lines per
// connection.
func (c *Client) armDiag() {
c.diagMu.Lock()
c.diag = true
c.diagJunk = c.diagJunk[:0]
c.diagMu.Unlock()
}
func (c *Client) diagOn() bool {
c.diagMu.Lock()
defer c.diagMu.Unlock()
return c.diag
}
// target names what the client is talking to, for the log.
func (c *Client) target() string {
if c.tr.Mode == "serial" {
@@ -219,10 +259,22 @@ func transientRead(err error) bool {
func (c *Client) Start() error {
c.running = true
c.done = make(chan struct{})
go c.pollLoop()
return nil
}
// Stop closes the link and WAITS for the poll loop to leave.
//
// The wait is the point. Closing the port from another goroutine does not undo
// an open() the loop is already inside: that open returns a fresh handle, the
// loop stores it, and the client that was told to stop goes on owning the serial
// port. The next client — a settings save, a profile switch — then cannot open
// it, and the operator sees "Serial port busy" with no other program running.
//
// Bounded, because a serial open can sit in the driver for a while and a stuck
// device must not freeze a settings save. If the deadline passes, the loop is
// still on its way out and the log says so.
func (c *Client) Stop() {
if !c.running {
return
@@ -236,9 +288,30 @@ func (c *Client) Stop() {
c.conn = nil
}
c.connMu.Unlock()
if c.done == nil {
return
}
select {
case <-c.done:
case <-time.After(6 * time.Second):
log.Printf("Ultrabeam: poll loop did not exit within 6s — %s may stay busy a moment longer", c.target())
}
}
func (c *Client) pollLoop() {
// Signals Stop that the port is genuinely released.
defer func() {
c.connMu.Lock()
if c.conn != nil {
c.conn.Close()
c.conn = nil
}
c.connMu.Unlock()
if c.done != nil {
close(c.done)
}
}()
ticker := time.NewTicker(2 * time.Second) // Increased from 500ms to 2s
defer ticker.Stop()
@@ -256,7 +329,7 @@ func (c *Client) pollLoop() {
log.Printf("Ultrabeam: Not connected, attempting connection to %s...", c.target())
conn, err := c.open()
if err != nil {
log.Printf("Ultrabeam: Connection failed: %v", err)
log.Printf("Ultrabeam: Connection failed: %v%s", err, portBusyHint(c.tr.Mode, c.tr.COM, err))
c.connMu.Unlock()
// Mark as disconnected
@@ -266,9 +339,25 @@ func (c *Client) pollLoop() {
continue
}
c.conn = conn
// Stopped while open() was running? Let go of the port at once.
// Stop cannot interrupt an open already in flight, so without this
// the fresh handle is stored by a client that has been told to die,
// and it keeps the port — which is precisely the "Serial port busy"
// the next client then reports, forever.
select {
case <-c.stopChan:
conn.Close()
c.conn = nil // already closed; keep the deferred cleanup from closing it twice
c.connMu.Unlock()
return
default:
}
c.reader = bufio.NewReader(c.conn)
pollFails = 0
log.Printf("Ultrabeam: Connected to %s", c.target())
// Dump the first exchange on this link. A connection that opens and
// then says nothing is the whole of what a serial user can see.
c.armDiag()
}
c.connMu.Unlock()
@@ -502,6 +591,10 @@ func (c *Client) sendCommand(cmd byte, data []byte) ([]byte, error) {
seq := c.getNextSeq()
packet := c.buildPacket(seq, cmd, data)
diag := c.diagOn()
if diag {
log.Printf("Ultrabeam: first exchange on %s — sending %d bytes: % X", c.target(), len(packet), packet)
}
if _, err := c.conn.Write(packet); err != nil {
return nil, fmt.Errorf("failed to write: %w", err)
}
@@ -509,6 +602,20 @@ func (c *Client) sendCommand(cmd byte, data []byte) ([]byte, error) {
// Read the reply with a timeout generous enough for a remote link.
c.setReadTimeout(ubReadTimeout)
buffer, err := c.readPacket()
if diag {
c.diagMu.Lock()
junk := append([]byte(nil), c.diagJunk...)
c.diag = false
c.diagMu.Unlock()
switch {
case err != nil && len(junk) == 0:
log.Printf("Ultrabeam: first exchange — NOTHING came back (%v). The controller is not answering on this port. Note that the USB cable presents TWO COM ports and only the SECOND one reaches the controller (at 19200 baud on the units seen so far); also check the cable and that the controller is on.", err)
case err != nil:
log.Printf("Ultrabeam: first exchange — %d bytes came back but no frame started (% X): %v. Bytes with no frame usually mean the wrong baud rate.", len(junk), junk, err)
default:
log.Printf("Ultrabeam: first exchange — reply %d bytes: % X (%d discarded before the frame: % X)", len(buffer), buffer, len(junk), junk)
}
}
if err != nil {
return nil, err
}
@@ -561,13 +668,53 @@ func (c *Client) drainStale() {
// so a raw ETX only ever appears as the real terminator. Caller holds connMu and
// has set a read deadline.
func (c *Client) readPacket() ([]byte, error) {
// A DEADLINE for the whole frame, not a timeout per read.
//
// A silent serial port does not error: it returns (0, nil) on every read once
// its timeout expires, and bufio retries that a hundred times before giving up
// with ErrNoProgress. With a 4-second port timeout that is over six minutes of
// a poll loop frozen mid-exchange, logging nothing — which is exactly how a
// controller that never answered looked like a program that had hung. Short
// port timeouts, checked against a deadline here, turn it into one clear
// "nothing came back" after four seconds.
deadline := time.Now().Add(ubReadTimeout)
c.setReadTimeout(250 * time.Millisecond)
defer c.setReadTimeout(ubReadTimeout)
var buffer []byte
for {
// A stop must not have to wait out the deadline. Without this, tearing the
// client down mid-exchange took up to four seconds — long enough for the
// replacement client to find the port still held, and for Stop to give up
// waiting and say so.
select {
case <-c.stopChan:
return nil, fmt.Errorf("stopped")
default:
}
if time.Now().After(deadline) {
if len(buffer) == 0 {
return nil, fmt.Errorf("no reply within %s", ubReadTimeout)
}
return nil, fmt.Errorf("incomplete frame within %s (% X)", ubReadTimeout, buffer)
}
b, err := c.reader.ReadByte()
if err != nil {
// A quiet port between bytes is normal — go.bug.st returns (0, nil) on
// its timeout, which bufio eventually reports as ErrNoProgress. Only the
// deadline above decides that the exchange has failed.
if transientRead(err) {
continue
}
return nil, fmt.Errorf("failed to read: %w", err)
}
if len(buffer) == 0 && b != STX {
// Kept, briefly, for the first exchange after a connect: what gets
// discarded here IS the diagnosis when the link is misconfigured.
c.diagMu.Lock()
if c.diag && len(c.diagJunk) < 32 {
c.diagJunk = append(c.diagJunk, b)
}
c.diagMu.Unlock()
continue // resync to the start of a frame
}
buffer = append(buffer, b)
@@ -725,3 +872,21 @@ func (c *Client) ModifyElement(elementNum int, lengthMm int) error {
_, err := c.sendCommand(CMD_MODIFY_ELEM, data)
return err
}
// portBusyHint turns "Serial port busy" into something actionable.
//
// A COM port has exactly one owner. The message the driver gives back says the
// port is busy and stops there, which reads like a fault in OpsLog — and the
// program actually holding it is usually the antenna manufacturer's own control
// window, sitting open on the same desktop. Naming that is the difference
// between a bug report and a five-second fix.
func portBusyHint(mode, com string, err error) string {
if mode != "serial" || err == nil {
return ""
}
msg := strings.ToLower(err.Error())
if !strings.Contains(msg, "busy") && !strings.Contains(msg, "access is denied") && !strings.Contains(msg, "denied") {
return ""
}
return " — another program already has " + com + " open (the UltraBeam Controller window, PstRotator, a terminal). A COM port has one owner: close the other program, then OpsLog can connect."
}
+27
View File
@@ -76,3 +76,30 @@ func TestMotorTuneKHzForBandFallsBack(t *testing.T) {
}
}
}
// The Ultrabeam's USB link answers on 19200 and on nothing else — confirmed on
// hardware, where 9600 opened the port and returned not one byte. A speed with a
// single right answer must not be storable as anything else, whatever an older
// config or a hand-edited setting says.
func TestNormMotorBaud(t *testing.T) {
for _, tc := range []struct {
typ, transport string
in, want int
}{
{"ultrabeam", "serial", 9600, 19200},
{"ultrabeam", "serial", 0, 19200},
{"ultrabeam", "serial", 115200, 19200},
// Over TCP the speed is the adapter's business, not ours.
{"ultrabeam", "tcp", 9600, 9600},
// The SteppIR controller really does run at several speeds.
{"steppir", "serial", 4800, 4800},
{"steppir", "serial", 19200, 19200},
// Nonsense falls back rather than reaching the driver.
{"steppir", "serial", 0, 9600},
{"steppir", "serial", 999999, 9600},
} {
if got := normMotorBaud(tc.typ, tc.transport, tc.in); got != tc.want {
t.Errorf("normMotorBaud(%q, %q, %d) = %d, want %d", tc.typ, tc.transport, tc.in, got, tc.want)
}
}
}
+38 -1
View File
@@ -1,6 +1,10 @@
package main
import "testing"
import (
"os"
"strings"
"testing"
)
// The tracking mode decides how often a motorized antenna's elements run, so a
// value that fails to parse must not silently become the most aggressive
@@ -46,3 +50,36 @@ func TestBandForHzDrivesBandTracking(t *testing.T) {
t.Errorf("30 m and 20 m both read %q — band mode would never re-tune between them", a)
}
}
// A "Test connection" on a serial port must not open a port OpsLog already
// holds: a COM port has one owner, and the owner is the running antenna client.
// Building a second client made the two fight — one of them logging "Serial port
// busy" for the rest of the session.
func TestTestUltrabeamReusesTheLiveSerialClient(t *testing.T) {
src, err := os.ReadFile("app.go")
if err != nil {
t.Fatal(err)
}
body := funcBody(t, string(src), "func (a *App) TestUltrabeam(s UltrabeamSettings) error {")
if !strings.Contains(body, "a.liveMotorFor(s)") {
t.Error("TestUltrabeam builds a client without first checking whether the live one already owns that port")
}
// The check has to come BEFORE the second client is created, or it is no check.
if i, j := strings.Index(body, "a.liveMotorFor(s)"), strings.Index(body, "newMotorClient(s)"); i < 0 || j < 0 || i > j {
t.Error("the live-client check must precede newMotorClient")
}
}
// funcBody returns the source of a function, up to the closing brace in column 0.
func funcBody(t *testing.T, src, signature string) string {
t.Helper()
i := strings.Index(src, signature)
if i < 0 {
t.Fatalf("function not found: %s", signature)
}
rest := src[i:]
if j := strings.Index(rest, "\n}\n"); j >= 0 {
return rest[:j]
}
return rest
}