Compare commits

...
226 Commits
Author SHA1 Message Date
rouggy 1f667e4a4b chore: release v0.27.4 2026-08-30 22:24:05 +02:00
rouggy d5f7e290ab chore(changelog): the FTx menu, the FT Map and the map fixes enter the 0.27.4 block 2026-08-30 22:23:30 +02:00
rouggy f2ba798764 fix(maps): zooming stays centred on the grid and decode maps
The hard maxBounds added for the single-world look fought the zoom: with
the world smaller than the window the clamp dragged every zoom step into
a corner. The noWrap tiles already guarantee one world on their own, so
the bounds go — on both maps.
2026-08-30 22:18:27 +02:00
rouggy d7ee87f22d feat(ftx): the digital corner gets its own menu, and the watchlist learns to line up
An FTx menu between View and Tools gathers FT Decodes, FT Map and the
Grid squares map — three views of the same UDP feed that were buried in
Tools. And the watchlist spot rows swap the elastic country column for
fixed widths, so band, mode and frequency read as columns instead of
starting wherever each country name happened to end.
2026-08-30 22:14:40 +02:00
rouggy 2587e6bcfe style(ftmap): one world, themed ground — here and on every map
The FT map wrapped the planet into a row of copies and showed Leaflet's
hard-coded grey beyond it. noWrap tiles inside hard bounds now, like the
grid-square map already did — and the container background override moves to
style.css so EVERY map's surround follows the theme's card surface instead
of #ddd (the grid map's per-div fix was losing to leaflet.css specificity).
2026-08-30 22:05:25 +02:00
rouggy 755392e0fa feat(ftmap): the live decode feed as a world map — feature branch
A new FT Map tab (Tools menu, beside FT decodes): every station decoded in
the last half hour drawn as a great-circle arc from the operator's own
square, coloured by band the way PSK Reporter taught everyone to read it,
fading with age, one arc per call (its freshest sighting), a tooltip with
call/grid/SNR, the MainMap basemap picker and a legend of only the bands on
screen.

Performance was the open question and it is answered structurally: the panel
mounts only while its tab is ACTIVE (zero cost otherwise), the map renders
canvas (one element, not one node per arc), arcs are capped at 300, and
redraws follow the decode list — every period, not every frame.
2026-08-30 21:54:00 +02:00
rouggy a9fb428a0a fix(chase): band/mode/slot needs finally dim — 'worked' is not ''
spotEntityStatus says 'worked' when every grain is in the log; the
unconfirmed check compared its all-ledger verdict against the empty string,
so no band/mode/slot need ever dimmed however many unconfirmed QSOs stood
behind it — only the entity-level NEW, tested by map presence, behaved. The
check now runs for exactly the four needy statuses and asks for 'worked'.
2026-08-30 21:43:47 +02:00
rouggy bbb485b9cf fix(chase): the unconfirmed entity badge is visible
Dimming the filled chip to a transparent background left its light
foreground text on nothing — an invisible badge in the row. Unconfirmed now
renders in the category's own hue, dashed border and text, like the extras
beside it.
2026-08-30 21:40:26 +02:00
rouggy 3a94a69be3 style(chase): no question marks — the dashed dimmed chip says it alone 2026-08-30 21:38:14 +02:00
rouggy e4028f4bcd fix(chase): switching the rules invalidates every resolved verdict
The frontend caches statuses and only asks about unknown keys, so flipping
the chase mode left half the screen judged under the old rules until a
restart — which read as the mode not working. The backend now broadcasts an
invalidation and the panels re-ask as rows repaint. The entity badges also
say their name with a question mark, dashed, when the need is only a missing
QSL — the 50% opacity was invisible on a filled chip.
2026-08-30 21:37:31 +02:00
rouggy 7c10517bf5 fix(chase): each unconfirmed badge keeps its own name; the block moves up
The unconf label was hard-coded to GRID? for every category — a prefix
worked-but-unconfirmed showed as a second grid badge beside the real one,
which read as impossible. Each badge now says its own name plus a question
mark. And the global Chase block moves above the Chase POTA/SOTA/grid
checkboxes, where its operator expected the master switch.
2026-08-30 21:28:52 +02:00
rouggy cd4e5b1117 i18n: the global chase block's labels, dropped by the failed batch edit 2026-08-30 21:23:17 +02:00
rouggy a13ac7d917 test: the bulk-edit guard learns the integer My-station fields
my_dxcc/my_cq_zone/my_itu_zone go through BulkSetIntField, not the string
column map — the guard flagged them as unwritable ever since they were
added, which is the drift it exists to catch, one package over.
2026-08-30 21:03:03 +02:00
rouggy 4e28098a4e feat(chase): the global hunt — new, or new plus unconfirmed, every category
The gap between worked and confirmed becomes visible everywhere. A Chase
setting on the DX Cluster page picks the mode; in new-plus-unconfirmed the
verdicts for DXCC/band/mode/slot, prefix, county and state are judged against
CONFIRMED-only ledgers built from the operator's chosen sources (LoTW, card,
eQSL, QRZ.com — HRDLog has no confirmation field in ADIF to offer), and a
need that exists only because a QSL never arrived is flagged Unconf: the
cluster and decode badges render it dimmed, the convention the grid hunt
introduced. The grid's own Chase selector folds into the global one; its
square-matching scope stays where it was, being grid-specific. One snapshot
key change rebuilds the cache when any of it flips.
2026-08-30 21:02:34 +02:00
rouggy 52e98a71f4 feat(decodes): NEW STATE — badge and filter
The WAS gap made visible: a worked-states set joins the cluster status cache
(distinct states over the three US entities), the status entries carry a
NewState flag wherever the state resolves (log county first, ULS licence
second), and the decode panel gains the badge in its status column plus the
filter chip alongside NEW/BAND/MODE/GRID. Colour from the shared marker
palette, so the cluster can adopt it later without a second hue.
2026-08-30 20:44:58 +02:00
rouggy 81ff6a9b0e style(decodes): a gap between the state badge and its name 2026-08-30 20:38:50 +02:00
rouggy be52a23868 feat(decodes): a State column — badge plus full name
Between the locator and the country, per its operator: the two-letter badge
anchors the eye and the spelled-out name answers it — 'SD' alone is a quiz
for a European. The status-cell badge from the first pass moves here.
2026-08-30 20:36:45 +02:00
rouggy fc1561804c style(decodes): the US state is a proper badge
Bigger and boxed, per its operator — the plain grey text vanished into the
column it was meant to anchor.
2026-08-30 20:34:02 +02:00
rouggy 1288b3f998 feat(decodes): the two-letter US state in the status column
Plain text, not a badge — it is a fact, not an action — placed first so a
WAS chaser can scan the column edge. Shown whenever the status cache knows
the state (log county data or the licence address).
2026-08-30 20:31:05 +02:00
rouggy e00488fad8 chore: release v0.27.3 2026-08-30 20:19:39 +02:00
rouggy 12c61dc35a feat(dvk): delete a message — recording and label together
A deleted message is a free slot, per its operator; keeping the label made it
look half-deleted.
2026-08-30 20:15:45 +02:00
rouggy 0c0e8b06ba feat(dvk): twelve slots; perf: Settings pauses the heavy streams
The voice keyer grows to F1-F12 — the UI was already data-driven, so the
count constant, the F-key range and the labels are the whole change.

And the preferences stop stuttering on a busy station: every spot batch,
decode batch and CAT snapshot re-rendered the entire App tree behind the
dialog — cluster grid, decodes panel, thousands of nodes — and the pointer
janked over the very panel the operator was trying to use. While Settings is
open the flushes park their batches in the pending refs (bounded) and CAT
repaints at most every two seconds; closing the dialog drains everything.
2026-08-30 20:09:44 +02:00
rouggy 1bd3896ca7 feat(decodes): arrival order within a period, not strongest-first
The panel now mirrors the decoder's own window line for line — the operator
compares the two side by side, and the SNR sort scrambled that
correspondence. The report is still right there in its column.
2026-08-30 19:26:52 +02:00
rouggy 7e6c0b4f7e fix(kpa): stop switching the KPA500 off, and answer its operator instantly
Three faults, one report. The slow poll asks ^TP — the KPA1500's ATU, which
a KPA500 (no ATU) never answers — and ask() dropped the whole connection on
any read timeout: a two-second stall and a reconnect every slow cycle, which
is why buttons lagged and the status read wrong. Worse, every serial reopen
toggled DTR/RTS — and those lines are the KPA500's POWER SWITCH (that is how
the Elecraft utility turns it on), so the amplifier obediently switched off
twenty seconds after its operator pressed nothing but Standby.

Silence is no longer a dead link (write errors still are), ^TP is never asked
again after one silence, the control lines are asserted once and held, and
the baud field becomes a list of the rates these amplifiers actually speak.
2026-08-30 19:14:35 +02:00
rouggy 2cde1a2c27 chore: release v0.27.2 2026-08-30 16:06:51 +02:00
rouggy 53100eb6c8 debug(rigctld): always trace a client's first six commands
A connect that lasts 50 ms leaves nothing to say which answer the client
disliked — WSJT-X refusing to attach to the shared CAT was undiagnosable
without the full wire trace. The handshake is now always logged; steady-state
polling stays behind the trace switch.
2026-08-30 15:55:58 +02:00
rouggy 3b555219d2 style(i18n): trim the FR follow-mode hint, and fix its double-escaped accents 2026-08-30 15:38:14 +02:00
rouggy ba35d4094c style(i18n): trim the follow-mode hint to its first sentence 2026-08-30 15:36:33 +02:00
rouggy 9bd6d988aa feat(udp): spot clicks switch the decoder's mode
Configure (message 15), mode field only, every other field sent as
no-change: an FT4 spot clicked while WSJT-X sits in FT8 lands the operator
ready to decode instead of staring at gibberish. Sent to every instance
heard this session — one already in the right mode treats it as a no-op —
and only for modes the decoder actually speaks (FT8/FT4/JT65/JT9/MSK144/
Q65/FST4); CW and SSB are none of its business. Toggle in the Connections
panel, on by default.
2026-08-30 15:33:07 +02:00
rouggy daabbc63c7 fix(map): Zoom DX clamps its frame to Mercator's edge
The great-circle arc to a polar entity (Franz Josef Land) peaks near 88°N;
fitting the raw arc points framed a band of tile-less white above 85°, where
Web Mercator ends. The camera's bounds are clamped to ±85° — the line still
draws to wherever it goes, only the framing stays where there is a map.
2026-08-30 15:30:30 +02:00
rouggy 997bc81d5e fix(udp): edge-detect the decoder's DX Call stream
WSJT-X restates the same DX Call in every Status packet, and a spot clicked
in OpsLog put that call into the last-UDP memory (deliberately, for another
case) — so the guard let the decoder's next restatement straight through and
the entry snapped back to old news. The decoder's stream now only counts when
its value CHANGES; a clear over there resets the edge so re-selecting the
same station still lands. Explicit picks (N1MM, remote, spot relays) are
untouched.
2026-08-30 15:29:07 +02:00
rouggy 3c59507bc3 feat(udp): Highlight Callsign and Replay — the decoder becomes log-aware
Message 13 paints callsigns in WSJT-X/JTDX's own Band Activity window with
verdicts from the same cluster status cache that colours the spot grid:
watchlist pink, new DXCC green, new band for its entity orange. Deduplicated
per instance+call+verdict, one datagram each; a verdict that lapses (the
operator worked them) clears that call, and turning the option off clears
everything via the protocol's CLEARALL!. Off by default, switch in the
Connections panel.

Message 7 asks a program heard for the first time this session to replay the
decodes already on its screen, so the FT decodes panel starts full instead of
empty until the next period. Replayed lines arrive marked not-new and are
shown but never auto-answered — the auto-caller now checks, on top of its
30-second freshness gate.
2026-08-30 15:25:58 +02:00
rouggy 721c43d569 style(settings): the Connections panel drops its two explainer paragraphs
Same cleanup as the General and DX Cluster panels: the section speaks for
itself, and the per-service hints remain where the choice is made.
2026-08-30 15:09:08 +02:00
rouggy 25eda98612 style(watchlist): a pass toward DXHunter's look
The operator preferred the original's aesthetics. Adopted: the signature pink
callsign (a fixed identity colour, like the cluster palette), counters as
coloured pills, a quieter card surface with a hover, a stronger needed bar on
spot rows, and the lightning bolt back on the DXpedition badge. Everything
else stays on theme tokens.
2026-08-30 13:35:37 +02:00
rouggy 0b909a4d63 fix(elecraft): the K3 power meter converts to real watts
The operator measured the whole table: 10 W showed 83, 12 W showed 100, 13 W
showed 8 — the bargraph is relative to a meter RANGE that flips at 12 W
(0-12 QRP, 0-120 above). A bar percentage was never watts; with the PC
setting choosing the range, it converts, and the console prints the watts
beside the bar.
2026-08-30 13:31:34 +02:00
rouggy 37298afd77 fix(qso): every by-ids statement is chunked — 168k QSOs is a selection too
One placeholder per id in a single IN (…) hits SQLite's bound-variable cap:
bulk field set died at 168 000 QSOs with 'too many SQL variables' (10 000
passed). One chunker now serves bulk set (text/int/extra/frequency), the
delete, the post-upload markers and the export-selection iterator — the last
collecting and sorting once at the end so its chronological contract holds
across chunks. 500 ids a statement keeps every backend far from any limit.
2026-08-30 13:13:22 +02:00
rouggy 5a77fdf68f chore: release v0.27.1 2026-08-30 12:01:03 +02:00
rouggy 31c898ad7f revert(icom): drop Wake-on-LAN — the deck does not honour it
Tried on the real IC-7760: the magic packet wakes nothing; Icom's own
mechanism is the network-standby session plus the CI-V power-on, which
OpsLog already does. The MAC store and the WOL sender go, and the changelog
entry with them. The CI-V pump now says once per session that the client
pings are armed — invisible pings read as absent pings.
2026-08-30 11:59:25 +02:00
rouggy 88c9756edf fix(icom): the client pings too — the dropouts' likely root cause
wfview sends a ping (0x07, 0x15 bytes, its own seq and a monotonic
timestamp) every 500 ms on every stream, and so does RS-BA1. OpsLog only
ever REPLIED to the rig's pings — and the loaner IC-7760 stopped serving
CI-V data about a minute into nearly every session while the transport
stayed alive: the rig had concluded nobody was listening. Scope, TX audio
and idle numbering were each eliminated in turn before wfview's source
settled it. Pings now go out on control, CI-V and audio alike.
2026-08-30 11:42:48 +02:00
rouggy 7b15b534cd fix(wb): latest lookup wins the worked-before panel
Two lookups race when a second callsign is typed before the first answered,
and the slow one landed last: the grid showed the previous call's QSOs under
the new call's name — LU5AVM's contact filed under LW8ETV, screenshot in
hand. A request token now discards any response that is not the newest.
2026-08-30 11:26:47 +02:00
rouggy 8e7ecc3d51 feat(icom): Wake-on-LAN for a deck that sleeps with its server
A 7760 switched fully off takes its LAN server down, and no session means no
console and no ON button — the one thing remote operation cannot tolerate.
The rig's MAC is learned from every login and persisted; when a dial finds
nobody home, the magic packet goes out to it before the next attempt. The
rig wakes into standby, the session opens, and the ON button does the rest.
2026-08-30 11:17:55 +02:00
rouggy 7f9019c7bc fix(omnirig): a Yaesu in split tunes both VFOs to the spot
The generic Freq write lands on the TX VFO when split is engaged: an FT-2000
moved B and left A — the receiver — behind, so a spot click QSYed the
transmitter and nothing audible changed; without split the same write moved A.
With split on (and the operator on MAIN), FreqA and FreqB are both written,
so the radio arrives on the spot whole, split left as the operator had it.
2026-08-30 11:12:08 +02:00
rouggy a1a3bad682 fix(cluster): the FT8/FT4 watering holes exist on every band
The inference tables knew FT8 on some bands and nothing on others: a 10.136
spot with a bare comment read as generic DATA — which is what every
skimmerless spot of a DXpedition's 30 m FT8 slot did. The standard FT8/FT4
windows are added on 30 m, 60 m, 80 m (FT4), 17 m (FT4) and 12 m, in BOTH
tables (backend band plan and frontend spot.ts), ahead of the wide segments
they sit inside — order is the mechanism there.
2026-08-30 03:14:21 +02:00
rouggy 1b746f2452 fix(icom): CI-V idles carry real sequence numbers
Every idle went out with seq 0, seven a second, interleaved with
properly-numbered data — where RS-BA1 and wfview draw idle sequence numbers
from the same counter as everything else. A rig that follows the sequence
tolerates the zeros for a minute or so and then stops serving CI-V data on
the stream: the shape of every dropout the loaner IC-7760 has shown, with the
scope and the TX path both since eliminated as causes. Idles now take the
next tracked seq and sit in the retransmit buffer like any other packet.
2026-08-30 03:08:59 +02:00
rouggy 3db49e1213 debug(icom): say whether the split mode-align was accepted
The 0x26 01 copy was fire-and-forget, and a real 7760's sub VFO kept
yesterday's mode with nothing to show why — refused, or sent with a stale
mode byte. The mode is read first when unknown, and both outcomes are
logged.
2026-08-30 03:02:06 +02:00
rouggy 605c934d33 style(icom): the shared LED meters, and the sideband named
The console's thin home-made bars were the one holdout — every other panel
(Flex, Elecraft, the amps, the tuner) draws the same MeterBar. And the mode
badge said SSB, which on any band leaves the operator guessing which
sideband the rig is on: the panel now shows USB or LSB (the log keeps ADIF's
SSB).
2026-08-30 03:00:58 +02:00
rouggy dad762a0f1 fix(dvk): repair the auto-CQ trace mangled by the previous commit
Shell quoting ate the template literals; the traced loop now compiles.
2026-08-30 02:52:04 +02:00
rouggy 97567d15dd debug(dvk): trace the auto-CQ loop into the app log
It keeps 'not repeating' on a network rig and every guess at which guard was
tripping proved wrong. Each round now logs play / playing-flag / end / gap,
and every exit names its reason.
2026-08-30 02:51:05 +02:00
rouggy fc080f3719 fix(icom): kill the leftover waveform in both command forms, and say so
The blind kill at connect still left a real 7760 streaming — the selector
byte differs by model, and the result was discarded so a quiet failure looked
like a cure. Both forms go out now (a NAK costs one frame) and the outcomes
are logged. The power table also gains its third measured anchor: a real
200 W reads full deflection, so raw 213 is 200 W — not the printed face's
250.
2026-08-30 02:43:43 +02:00
rouggy ce9ea10d68 fix(dvk): a transiently blank mode no longer kills the auto-CQ loop
Over the network the rig's mode read fails now and then and the CAT push
blanks the mode for a poll or two; the auto-CQ loop treated that blank as
'not a phone mode' and stopped after the first call. Only a KNOWN non-phone
mode stops the loop now.
2026-08-30 02:42:20 +02:00
rouggy dc94aa94b6 fix(icom): needle inertia for the TX meters, and room for three digits
The CI-V meters are point samples: between two SSB syllables a poll lands on
0 W and a perfect SWR, so a 150 W transmission read 0-10 W most of the time
and the SWR sat at 1.0. Power now decays like a needle and SWR holds its peak
then snaps to the live value — the same meterPeak the Yaesu and Kenwood
consoles already use. The readout column also widens so '180 W' stays on one
line.
2026-08-30 02:40:07 +02:00
rouggy db7ac771b1 feat(icom): the ATU can be taken out of line
TUNE (1C 01 02) started a cycle; nothing sent the 0 that puts the tuner back
through. An ATU chip beside SPLIT now toggles it, and the tuner state is read
on the slow front-panel beat so the radio's own TUNER button stays in sync.
2026-08-30 02:36:46 +02:00
rouggy 19134ea23c revert(icom): drop the PTT+split strip — MOX and SPLIT already live below
Added on a report that they were missing; they were below the fold, not
absent. The useful parts stay: the MOX button routes the PC microphone on a
network station, split aligns the TX VFO's mode, and SetIcomSplitOffset
remains available for a future use.
2026-08-30 02:34:47 +02:00
rouggy b12011fab7 fix(icom): send the leftover-waveform kill blind, at connect
The first attempt sent it only after CI-V answered — but the waveform flood
is what stops CI-V answering, so a rig wedged streaming never received its
cure. It now goes out at the end of Connect, before anything waits on a
reply: an unanswered set costs one frame, and the rig acts on what it decodes
whether or not we hear the acknowledgement.
2026-08-30 02:33:19 +02:00
rouggy d62cd10478 fix(icom): switch off a leftover waveform stream at first contact
The 0x27 output flag lives in the RADIO and survives our sessions: a scope
enabled by an older build (or another program) kept flooding every new
session with 700-byte frames — and on the IC-7760 that flood is what kills
the CI-V link. One 'waveform output off' as soon as the rig answers, once per
session; the front-panel display is deliberately untouched.
2026-08-30 02:28:41 +02:00
rouggy 7de7cb96c3 fix(icom): one sequence space for everything sent on the audio stream
The voice keyer and the live microphone each numbered their packets from 1.
A message played after a talk session re-used sequence numbers the rig had
already seen and was discarded wholesale: the PTT keyed for the full length
of the message and none of it was modulated. PlayTX now feeds the same framer
and counters as the microphone.
2026-08-30 02:25:37 +02:00
rouggy dbc97ad61b feat(icom): remove the console's spectrum scope
Every Icom streams its waveform differently: the IC-7851 controls a scope it
never streams, and a real IC-7760 stops answering CI-V altogether a few
frames in — taking CAT and the audio down with it, which is this week's whole
dropout saga. Chasing a per-model frame layout for a decoration is not worth
a console that drops the link; the radio's own scope is better anyway. The
backend scope plumbing stays (harmless while nothing enables it); the UI and
its enable path go.
2026-08-30 02:23:31 +02:00
rouggy 7966b01900 fix(icom): the console PTT carries the microphone on a network station
Keying alone is right on USB, where the operator talks into the radio's own
mic; over the LAN it transmitted silence. The console button now goes through
one binding that picks the road: network To-radio → the same key-and-stream
path as the Talk button, USB → key and nothing more.
2026-08-30 02:20:40 +02:00
rouggy f98e95fe9e feat(icom): PTT and offset split at the operator's hand
The MOX and SPLIT controls lived at the bottom of the Transmit card, below
the fold on most layouts — a console whose PTT needs scrolling is not a
console. A strip under the mode row now carries the PTT and Split as
OFF/+1k/+5k/+10k, DXpedition style, on a new SetIcomSplitOffset that takes
the chosen TX offset (0 keeps the old CW/SSB convention). The mode-alignment
from the previous fix rides along on every engage.
2026-08-30 02:15:16 +02:00
rouggy 392b93f089 fix(audio): the Listen button works with the network stream as the source
Its enable condition predated the network audio: with From-radio empty — the
normal network setup — the button was greyed out, and an operator who had
stopped listening had no way to start again from this panel. The stale 'later'
hints on both buttons said the network paths did not exist; they do.
2026-08-30 02:04:51 +02:00
rouggy 9c459c754f fix(icom): standby is not a fault — the quiet recovery needs prior CI-V
A radio in standby is silent on CI-V by design; only the transport chats.
The quiet-recovery added for the mid-session deafness treated that silence
as the fault it usually is and tore the session down every 15 s — taking the
console and its ON button with it, so a radio that was off when OpsLog
started could never be turned on. The recovery now arms only once the
session has heard at least one CI-V payload.
2026-08-30 01:55:35 +02:00
rouggy ec967e29cf fix(icom): the audio stream no longer depends on the speakers
The sink — decode + recorder feed — was built only on the success path of
starting the monitor, so speakers-off (the remembered preference) or an
output device that failed to open silently disabled the WHOLE stream: the
session connected audio=false, and a ticked RX-audio checkbox did nothing.
The sink now exists whenever the stream is on; only the monitor obeys the
speaker choice.
2026-08-30 01:53:06 +02:00
rouggy 58e36667a7 fix(audio): starting the monitor restarts a running one instead of refusing
'Monitor already running' surfaced as the speakers checkbox unticking itself
the instant it was ticked, whenever the UI's idea of the state and the real
monitor had drifted apart. Stop-then-start makes the button mean what it
says.
2026-08-30 01:44:11 +02:00
rouggy 77aba73096 fix(icom): a disconnected radio says so, not 'use the USB sound card'
The TX-audio entry points type-assert the transport; a nil port failed the
assertion and produced the sound-card message, sending an operator whose
radio was simply off — or on a new DHCP address — hunting through audio
devices.
2026-08-30 01:36:37 +02:00
rouggy da8f60a7b3 fix(icom): the SUB dial is always shown, and split aligns the TX mode
The unselected VFO was read only when split was on, so a dual-receiver rig's
second dial sat blank on the console. It is now read on the same slow beat
regardless. And engaging split copies the main's mode (and data flag) onto
the TX VFO with 0x26 01 — a split whose TX VFO still speaks yesterday's mode
transmits FM into a CW pileup; rigs that predate 0x26 NAK it harmlessly.
2026-08-29 21:53:16 +02:00
rouggy e8b5444fc2 feat(icom): live microphone over the network — the last remote brick
The talk button learns the network road the voice keyer already took: when
To-radio is the radio itself, the microphone is captured and re-framed into
the rig's 320-sample packets, the capture callback serving as the clock — the
mic delivers in real time, so no ring and no pacer. Counters and the frame
remainder live on the audio stream, so a talk session spans calls. PTT keys
before and releases after, through the same code as the USB path.

With this, a network Icom is a complete remote station over three UDP ports:
RX audio to the headset, live voice and recorded messages back, CW through
the rig's keyer, CAT for everything else.
2026-08-29 21:51:37 +02:00
rouggy 08bc401681 fix(audio): the network monitor needs no From-radio device
AudioStartMonitor refused before reaching the network branch when From-radio
was empty — which is the NORMAL network setup, so the new speakers checkbox
un-ticked itself the instant it was ticked. The capture-device requirement now
applies only to the USB path that actually captures.
2026-08-29 21:45:18 +02:00
rouggy 7ac342e2d4 feat(icom): the speaker choice appears beside the RX-audio option too
Same remembered preference as the console's speaker button, surfaced where
the stream itself is enabled — tick RX audio and decide in the same breath
whether it reaches the speakers. Applied immediately, no save needed.
2026-08-29 20:02:28 +02:00
rouggy b244575937 feat(icom): a speaker toggle on the console itself
Muting the network RX audio took a trip through Settings → Audio → Stop
listening — two panels away from the console the operator is actually using.
A speaker button now sits beside ON/OFF (network only, like them): one click
to listen or mute, the recorder and the voice keyer unaffected, the choice
remembered across reconnects and launches.
2026-08-29 19:49:09 +02:00
rouggy c878742e50 feat(icom): listening to the network audio is a remembered choice
The RX stream and the speakers were welded together: every reconnect and
every launch restarted the monitor, so an operator sitting in the room with
the radio could not have the stream (which the recorder and the voice keyer
need) without also hearing it twice. Stop listening now persists, the Listen
button turns it back on, and reconnects respect the choice.
2026-08-29 19:42:18 +02:00
rouggy 13434ca36c feat(icom): phase 5 — the voice keyer plays to the radio over the LAN
The audio session opens its TX side alongside RX (txenable in the conninfo,
16 kHz both ways), the stream gains a paced sender — 320 samples every 20 ms,
the frame mirroring what the rig itself sends on this socket, IDs swapped —
and the network Icom takes the same NetworkPlayer slot a TCI radio does: pick
'Radio (network audio)' as the To-radio device and the voice keyer needs no
cable and no virtual sound card. PTT brackets the message through the same
code as every other audio path.
2026-08-29 19:34:05 +02:00
rouggy 6345710de5 fix(icom): wait out the rig's session cleanup before redialling
The capture shows the spiral: a session goes deaf on CI-V (28 unanswered
commands, transport alive), the fast-fail rebuilds it, the new session answers
for one second — one state read got through — and is then strangled when the
rig purges the half-open old one. Twenty seconds a lap, no audio throughout,
and only the third or fourth session survives. When the previous session died
less than 90 s after connecting, the redial now pauses 20 s so the purge
happens BEFORE the new session, not on top of it. A long-lived session still
reconnects immediately.
2026-08-29 19:21:55 +02:00
rouggy 0cab1c1e6b debug(icom): count the questions asked during a CI-V silence
The operator's counter-hypothesis deserves an answer: RS-BA1 shows no such
dropouts, so are we sure the rig stops answering — or do we stop asking? The
quiet log now carries the number of CI-V commands sent since the last answer.
Zero would convict our own poll loop; a healthy count convicts the rig.
2026-08-29 18:43:46 +02:00
rouggy 1c71495446 fix(icom): give up on the quiet CI-V stream after 15 s, not 30
The capture settled it: the 7760 keeps the transport chatting (pings answered,
no socket error, no loss) while CI-V data simply stops, the in-place reopen is
ignored, and only a fresh session brings it back. So: one reopen attempt at
10 s — kept, it is free and the log will say if a firmware ever honours it —
and at 15 s the link is failed deliberately so the manager rebuilds it,
halving the outage. Also: the recovered-acknowledgement now sits on the DATA
packet, not on any packet — pings were toggling the detector, 160 reopens in
thirty seconds all logged as recoveries that never happened.
2026-08-29 18:35:41 +02:00
rouggy 2c0158b75c fix(icom): re-open the CI-V flow when the rig goes quiet mid-session
The IC-7760 recurrently stops answering CI-V a few minutes into a network
session while the transport keeps chatting — pings answered, session alive,
commands unanswered — and the only recovery was the 30 s watchdog's full
teardown. At 10 s of CI-V silence the pump now says 'open' again on the
existing stream, which is all it should take if the rig quietly closed the
data flow; the watchdog remains as the backstop. The send counters gain a
mutex since the pump now transmits too.
2026-08-29 16:56:06 +02:00
rouggy a2b019b280 debug(icom): the quiet detector watches CI-V DATA, not transport chatter
The first detector counted any packet and never fired: pings and idles keep
flowing while the rig stops answering CI-V commands — which is what the 7760's
recurring silence turns out to be. Now it fires on 10 s without a CI-V payload
and reports the ages of the transport, the last scope frame and the last
socket error, so the next occurrence says exactly what the rig was still
sending.
2026-08-29 16:54:37 +02:00
rouggy 1fba7d2d57 fix(icom): create the audio manager before the CAT link comes up
reloadCAT builds the network audio sink gated on audioMgr, and startup created
the manager AFTER the first reloadCAT: every fresh launch connected with audio
silently off however the option was set, and the operator had to
untick/save/retick it to hear anything. The manager is idle-until-used, so
creating it earlier costs nothing.
2026-08-29 16:47:42 +02:00
rouggy 490941f506 fix(icom): only forward-moving audio packets reach the sink
Every audio packet was delivered as if it were the next 20 ms, duplicates and
late retransmits included. The monitor's capped ring quietly threw the surplus
away, so the speakers sounded fine — but the recorder keeps every sample it is
given, and the file came out longer than the QSO, slowed and stuttering, each
lost-then-resent packet heard twice. trackRxSeq now says whether a packet
advances the stream, and only those are handed on.
2026-08-29 16:43:41 +02:00
rouggy 6bf759b6ae fix(cw): Icom CI-V CW works over the network backend too
The CI-V keyer is the same 0x17 command on the same IcomController whatever
carries the link; only the warnings and enable checks insisted on the USB
backend, telling a network operator their working keyer would fail.
2026-08-29 16:39:43 +02:00
rouggy 43e5088e96 fix(icom): the live radio names MY_RIG, and a manual take records it too
Two halves of the same station confusion. The entry form pre-filled MY_RIG
from the per-band default on every band change, so the log-time priority (the
radio that is keying beats the radio that was planned) never ran — the field
was no longer empty by the time the backend looked. The form now asks the
active radio first, through a new ActiveRadioMyRig binding.

And the manual record button started its capture from the From-radio sound
card unconditionally, where the automatic recorder already knew a network
Icom's audio is pushed from the 50003 stream: a manual take on the IC-7760
was a faithful recording of the Flex's DAX. Same source rule for both, and
the button is offered with no sound card at all when the network stream is
the source.
2026-08-29 16:35:25 +02:00
rouggy 582fa561b2 fix(rec): a fresh take starts its clock at zero, not at the last take's total
Two effects, wrong order: the ticking effect ran before the reset effect on a
new take, so its closure captured the PREVIOUS take's elapsed as its starting
point — the counter showed 0 for one second and then jumped back to thirty
minutes. Effects run in declaration order; the reset now comes first.
2026-08-29 16:31:38 +02:00
rouggy 7f328d4eb5 debug(icom): say what the CI-V stream was doing when it goes quiet
A real IC-7760 keeps going silent on the CI-V stream two-three minutes into a
session while the control link stays alive. At 10 s of silence the pump now
logs the last real socket error and the retransmit backlog, and notes when the
stream resumes — the 30 s watchdog that follows cannot tell a dead socket from
a rig that stopped talking, and the next occurrence should.
2026-08-29 16:07:42 +02:00
rouggy b2eb6a4b1e fix(icom): the 7760 power meter interpolates between MEASURED anchors
A known 50 W read raw ~89 where the two-segment curve said 62: the face is
not linear in watts below half scale. Watts now interpolate through the
measured points (50 W, 100 W, full-scale 250 W); refining the curve is adding
a row to the table.
2026-08-29 16:06:05 +02:00
rouggy c2db4c5f7e chore(icom): stop blaming a hijacker for every silent CI-V stream
The 30 s watchdog message asserted another program had taken the session; a
real IC-7760 went silent once with nothing else on the network, and the
message sent its operator hunting software that was not installed. State both
causes.
2026-08-29 16:04:06 +02:00
rouggy b246c4d10a fix(icom): power in watts on the 7760, and Listening restarts clean
The power meter applies Icom's own meter calibration (raw 143 = half
deflection, 213 = full scale) anchored against the real radio: a measured
100 W sits at half deflection of the 7760's 250 W face — the linear guess
showed it as 140. The RF power slider says watts on a 200 W rig instead of a
percentage the operator has to convert.

And the Listening button, pressed while a network Icom is connected, restarts
the monitor render-only: it used to open a USB capture from the From-radio
device as well, and that second producer interleaved with the network pushes
chopped the audio to pieces.
2026-08-29 16:02:15 +02:00
rouggy 6d4a110949 fix(cat): the settings panel opens on the radio that is actually active
The loader looked for an 'active' flag the radio list has never carried, so
reopening the panel always landed on the first entry — Radio 1's name over
whichever radio's settings were live, and every field edit (MY_RIG included)
silently rewriting the wrong entry. The backend is the only one who knows
which radio is on the air; ask it.
2026-08-29 15:52:37 +02:00
rouggy ffbbff80d6 feat(icom): a DATA button, native PSK, real watts — and the audio codec
The console gains a DATA mode button (USB-D, what FT8 and friends ride on);
the PSK button now maps to the rigs' native PSK mode (0x12) instead of erroring
as an unknown mode — rigs without one NAK it, exactly as RS-BA1's button does
there. The power meter shows real watts on the IC-7760, whose meter face runs
to 250 W where a 100 W rig's percentage was the watts. The clickable S-meter
gets a pointer cursor so it looks like what it is.

Network audio: rxcodec 0x04 — the experiments on the real 7760 settle the
codec table (0x10 = 16-bit stereo, 0x02 = 8-bit mono, both heard as garble),
and 0x04 is the 16-bit mono the playback path actually plays.
2026-08-29 15:48:26 +02:00
rouggy bd2edf6624 fix(icom): verify the data flag after a mode set, and correct it with 0x26
The IC-7760 acknowledges the 1A 06 data-mode command and stays in USB-D
anyway, which left the operator unable to get back to plain USB from the
console at all. After every mode set the flag is read back; on a mismatch it
is said again with 0x26 — mode, data flag and filter in one frame, the form
the newer rigs actually honour. Only on a mismatch, so rigs that predate 0x26
never see the command.
2026-08-29 15:36:55 +02:00
rouggy 6321948415 fix(icom): fold the 7760's stereo RX stream down to the mono it plays as
The rig keeps sending two-channel LPCM after rxcodec asks for one — 1280-byte
payloads, 320 stereo frames per 20 ms tick, right channel all zeros in the
capture. Played as mono that interleaving is half-speed metallic garble. A
stereo-sized packet is folded to its left channel; a 640-byte mono packet from
a rig that honours the request passes through untouched.
2026-08-29 15:34:18 +02:00
rouggy 89e239d83f fix(icom): decode the network RX audio as what the rig actually sends
The first real radio on the 50003 stream (an IC-7760) settles the two guesses
the experimental audio path shipped with. The payload starts at 0x18 — the
packet carries a big-endian payload length at 0x14 (0x500 on every packet) —
not at 0x16, which swallowed two header bytes into the PCM and laid a 50 Hz
click track under everything. And rxcodec 0x10 asks for TWO-channel LPCM,
which the mono playback path rendered as double-speed garble; 0x02 asks for
the one channel the monitor plays.
2026-08-29 15:32:44 +02:00
rouggy 0e48ad7bb2 fix(icom): the IC-7760's attenuator is the stepped 6/12/18 dB kind
Confirmed on a real one. It was falling into the single-20 dB default, whose
one button the rig NAKs.
2026-08-29 15:29:14 +02:00
rouggy ad82c21dbc debug(icom): log the raw packets seen during a control handshake
A rig that answers something unrecognised (a newer model, another firmware)
and a rig that answers nothing are different faults; a silent timeout hides
which. Capped at a dozen packets so a working handshake cannot flood the log.
Prompted by the first IC-7760 network attempt — which turned out to be aimed
at the console's IP, where nothing listens; the remote server lives on the RF
deck.
2026-08-29 15:12:12 +02:00
rouggy 6f126802cd feat(icom): the IC-7760 joins the model list
CI-V default address B2h, per the radio's own menu. Both places that know a
model: the settings dropdown and civ.ModelName.
2026-08-29 15:02:23 +02:00
rouggy 704b614c38 fix(elecraft): calibrate the S-meter, and stop the SWR spike lingering
The S-unit mapping was provisional, waiting for a real radio. One arrived:
side by side with a K3's own display, raw 5 reads S7 and raw 9 reads S9+20,
so S9 sits near raw 6.5 — not 9 — and each raw step above it is worth ~8 dB.
The old scale showed everything two S-units low.

The SWR meter borrowed the power meter's needle inertia — hold the peak, then
close a quarter of the gap per poll. The K3 throws a brief SWR spike as an FT8
frame ends, and that decay turned one bad sample into twelve seconds of red on
the next transmission. SWR now holds the peak for the same 1.5 s and then
snaps back to the live reading: it is a warning light, not a needle.
2026-08-29 13:52:40 +02:00
rouggy 6eb6f1b339 chore: release v0.27.0 2026-08-29 02:56:48 +02:00
rouggy dbd2fff121 chore(changelog): the watchlist block becomes 0.27.0
A new tab, a new file format carried over from another program, and a ClubLog
integration are a minor version, not a patch.
2026-08-29 02:56:28 +02:00
rouggy dc6da67cbf chore(changelog): the watchlist headlines 0.26.24
The block's one genuinely new feature opens it — with the ClubLog enrichment,
which had not made it into the entry yet — instead of sitting seventh between
an Elecraft button row and a bulk-edit field.
2026-08-29 02:55:16 +02:00
rouggy ea6fb1c29c fix(flex): send the spot-click zoom after the tune, not alongside it
Double-clicking a cluster spot tuned the slice and zoomed the panadapter in
the same breath. On a cross-band jump SmartSDR moves the panadapter itself to
follow the slice, and that follow lands after — and overrides — a zoom sent in
the same instant, so the width the operator configured never appeared. A spot
clicked ON the panadapter never hit this, because the radio had already tuned
before our zoom arrived; the two paths now behave the same. The Chase new
panel's pick is sequenced identically.
2026-08-29 02:45:07 +02:00
rouggy 29267a865c fix(flex): the Chase new panel's spot click zooms the panadapter too
Every other spot click — cluster grid, band map, watchlist, alert list — goes
through handleSpotClick, which applies the operator's per-mode panadapter
width after the tune. The Chase new panel had its own pick handler that tuned
and stopped there; it now makes the same view change, after the tune for the
same reason.
2026-08-29 02:37:13 +02:00
rouggy e93d2d36a8 feat(watchlist): the ClubLog expedition enrichment — phase 2 lands
clublog.org/watch.php, per entry: the DXpedition flag, OQRS, LiveStream, the
log's QSO total and the last-24h rate — the fields the schema has carried since
phase 1. Refreshed on DXHunter's own cadence (hourly for expeditions,
six-hourly for the rest), two at a time with a breath between requests: the
application API key is shared by every install, so a hundred-entry list must
read as a trickle at ClubLog's end. Nothing to configure — OpsLog's own key,
already used for cty and Most Wanted, serves.

A starred pattern is asked about by its base (ClubLog has no log for VK9*).
The card gains the 24h rate beside the QSO total and the Live link to the
expedition's stream.
2026-08-29 01:49:13 +02:00
rouggy 107c6fccf6 fix(watchlist): remove on a single click, like the bell and trophy beside it
The two-click arm goes: removing an entry is cheap to undo (type it again), so
it does not earn a confirmation its neighbours do not have. The bin reddens on
hover and the green line confirms the removal.
2026-08-29 01:36:06 +02:00
rouggy 9350af9589 fix(watchlist): remove actually removes on the second click
The two-click arm compared against the STATE variable, which each click's
handler captured at render time — a quick double-click read the pre-arm value
twice, so both clicks merely armed: the bin turned red and nothing was ever
deleted. The arm lives in a ref now, compared synchronously, and the window
grows to three seconds.
2026-08-29 01:34:09 +02:00
rouggy a9a6579a9a feat(watchlist): confirm an add, and both messages clear themselves
A green line under the toolbar says what was added (and as what — the contest
variant names the per-UTC-day rule); the already-exists error keeps its red
line. Both fade after four seconds: a stale 'added' from ten minutes ago reads
as a fresh one.
2026-08-29 01:30:10 +02:00
rouggy 7795e13432 fix(watchlist): open the store before the logbook connect
It was created after the (possibly remote) logbook connect, so a 10-30 s MySQL
dial left the tab saying 'Watchlist: 0' until the next refresh tick — twenty
seconds of an empty list for a JSON file that reads in a millisecond. It now
opens right after the data dir is known; only the auto-contest pattern waits
for the settings store.
2026-08-29 01:28:50 +02:00
rouggy c9e98d5fdd feat(watchlist): exact match by default, * for a family
The prefix matching ported from DXHunter swallowed too much: a three-letter
special-event entry N8W lit up NEEDED for N8WCR, a different station entirely.
The implicit becomes explicit — a bare entry matches exactly that call, a
trailing star makes it a family: VK9* catches every VK9…, RI0SP* the
expedition's portable forms. A star anywhere else (or alone) is refused at Add
rather than silently matching nothing. Same rule in the backend Match and the
tab's own matcher, pinned by test.
2026-08-29 01:25:34 +02:00
rouggy 72253f99fa style(watchlist): the toolbar is two atomic groups — no more orphan chip
Add-controls left, filters right, justify-between: when the pane narrows, the
whole filter group drops below as a block instead of shedding its last chip.
Shorter chip labels (Active / Needed) and a slimmer search keep both groups on
one line at the tab's normal width.
2026-08-29 01:16:53 +02:00
rouggy f0d3bed8a2 style(stats): room for a long entity beside its badges
The F1 panel widens 560 → 600 px, the header row drops its outer padding and
wide gaps, and the country badge tightens — so 'Central African Republic' and
the NEW SLOT chip share one line instead of the chip dropping alone underneath.
2026-08-29 01:11:02 +02:00
rouggy 30c9acf0d2 style(watchlist): counters on their own centred line, sane placeholders
The counters are the tab's headline and now sit alone, centred, above the
toolbar; everything one interacts with lives on the second row. The inputs stop
shouting their placeholders — the uppercase belonged to the VALUE (callsigns),
not the hint text — and the auto-contest field says what it is.
2026-08-29 01:08:39 +02:00
rouggy e3175ef6a3 fix(watchlist): never draw a spot before its verdict
A new spot rendered as Needed the instant it arrived and was withdrawn half a
second later when the worked answer landed — the list twitched on every burst.
Unsettled spots are now invisible everywhere (card lines, counters, the
Active/Needed-only filters) until their verdict is in: nobody needs a spot
150 ms early, they need it settled. The answer map is merged rather than
replaced, so a settled line can never fall back to unknown, and the query
debounce drops to 150 ms since there is nothing on screen waiting for it.
2026-08-29 01:06:01 +02:00
rouggy 441eb295c6 feat(watchlist): header counters, mode filter — and the alert checks worked FIRST
DXHunter's header row, ported: Watchlist / Active / Needed counts up front and
the All-Modes select beside the other filters (DIGI matches the digital class,
SSB folds USB/LSB). Counters, card lists and the Active/Needed-only filters all
read the same mode-filtered view, so the numbers add up to what is on screen.

And the notify alert now asks the SAME worked-slot question the tab asks —
before making a sound. It used to fire on the raw spot while the tab's verdict
arrived on a debounce, so the bell rang for a slot that showed Worked a moment
later. Judged in the backend at emit time: exact slot for named modes, digital
class for generic DATA, today-only for contest entries.
2026-08-29 01:03:37 +02:00
rouggy cb2f8aba72 fix(watchlist): the auto-contest FIELD — the backend shipped without its UI
The wiring script died on an app.go anchor mid-run: the backend half was
committed, the frontend half (the pattern field, the changed-event refresh, the
i18n keys) never ran. Replayed; the field sits after Add.
2026-08-29 00:58:46 +02:00
rouggy 7b9cda93bc style(watchlist): drop the lone '!' on needed lines
A needed line already says so twice — the amber left border and the Needed!
badge — and the exclamation mark was noise. The green tick stays on worked
lines.
2026-08-29 00:52:38 +02:00
rouggy 8f64e3fee3 feat(watchlist): the auto-contest pattern — DXHunter's contest_prefix
A field in the tab's toolbar (e.g. WWA): while non-empty, any spotted callsign
CONTAINING it joins the watchlist as a contest entry by itself — a
special-event fleet (HB9WWA, DL0WWA, F4WWA/P…) is collected as it appears
instead of typed in one by one, and each is judged per UTC day like any contest
entry. Contains, not prefix, because the event string sits anywhere in those
calls.

Global setting, cached in an atomic so the spot pipeline never touches the
settings store per spot. Emptying the field stops the collecting but keeps what
was collected — DXHunter deletes non-matching contest entries on a pattern
change, and a setting that silently empties an operator's list is the one
behaviour of the original this port refuses.

The tab also refreshes on backend auto-adds (event) and on a slow tick, so
last-seen and the counters stay honest while it sits open.
2026-08-29 00:50:14 +02:00
rouggy c4de5f2ea0 style(watchlist): a wider column, and the country stops truncating first
max-w-4xl left 'Central African R…' cut mid-name: the column grows to 5xl and
the country cell flexes with the row (capped at 14rem) instead of a hard 8rem.
2026-08-29 00:46:34 +02:00
rouggy 9172f504e5 fix(watchlist): judge generic DATA spots at digital-class grain; tidy the toolbar wrap
7.0589 falls in the band plan's generic [7.04-7.1] DATA segment — an F/H
DXpedition off the standard dials — and 'DATA' is in nobody's log, so the spot
read NEW MODE / Needed while the FT8 contact sat right there. A generic mode
cannot be matched exactly; it is now judged at digital-class grain — worked if
ANY digital mode of that call is logged on that band — against a second
class-folded slot set built beside the exact one (shared when the grouping
option already folds them). DXHunter answers this with a finer frequency table,
which fails on exactly these off-dial expeditions; the class rule cannot.

The toolbar also wraps as a whole with tighter gaps instead of dropping its
last filter chip onto a lone second line.
2026-08-29 00:43:30 +02:00
rouggy 7322e2ab66 feat(watchlist): dockable in the Main tab; sticky filters; Needed-only hides worked lines
The watchlist joins the Main-tab pane list (Settings → Main view), rendered in
a card like the other docked panels.

The three filters persist across tab switches — the component unmounts on every
switch, and filters that reset each time are filters nobody trusts.

Needed-only now hides the worked SPOT LINES as well as the all-worked cards,
which is DXHunter's own Not-Worked behaviour and the reported complaint: a
filter that says needed and still lists five green Worked rows answers a
different question than the one asked.

The add-row checkbox is relabelled 'as contest' — it marks the entry being
ADDED, and read as a filter beside the All/DX/Contest buttons it looked
redundant.
2026-08-29 00:39:07 +02:00
rouggy 29d79fb5d1 fix(watchlist): read the cluster's slot index, and cap the card width
The first version asked the alerts' worked-index — keyed by RAW mode (FT8) —
with a CLASS name (DIGI). Nothing ever matched, and a DXpedition worked on five
bands showed every slot as Needed.

The verdict now reads the cluster's own WorkedCallSlotKeys set, built in the
cached status maps (now unconditionally — it used to exist only when a display
option wanted it). Same index, same mode normalisation as the grid, so the
watchlist can never contradict the cluster about the same spot. The contest
today-set is normalised through the same function.

And the cards column is capped at a reading width instead of stretching
callsign-to-badge lines across the whole window.
2026-08-29 00:33:52 +02:00
rouggy f6b70184a7 chore(qso): drop the redundant SlotsSince free function 2026-08-29 00:26:32 +02:00
rouggy e4abcda94f feat(watchlist): the DXHunter watchlist as an OpsLog tab
The concept, transplanted: a list of callsigns or prefixes being hunted,
matched against the live spot stream, one card per entry with the spots
underneath and the two questions that matter answered on every line — is this
slot still needed, and what is it worth (the cluster's own NEW badges, read
from the same status index).

The file is DXHunter's own watchlist.json, field for field, ClubLog block
included though phase 2 will fill it — a file that round-trips unchanged is the
whole of 'same format', and a test pins it with a real DXHunter entry. Global
(dataDir), not per profile.

CONTEST is per entry, not the global mode DXHunter has: a contest entry is
judged against the current UTC day — the boundary lives in the query's date
bound, so midnight needs no timer and resets nothing. Normal entries read the
same in-memory worked index the alerts use. Prefix matching is why RI0SP
catches RI0SP/MM, pinned by test.

Notify goes through the existing alert:fired event — the frontend already
toasts and sounds it — throttled to one alert per entry per two minutes,
because a DXpedition lights every skimmer on the planet.

Tab wired like NET Control: opt-in from Tools, persisted, closable. Single
click fills the callsign, double click works the spot — the cluster's own
gesture, kept.
2026-08-29 00:25:40 +02:00
rouggy 284ee4ba7c feat(bulk): My DXCC / My CQ zone / My ITU zone
The My-station group covered nineteen fields and not the three numeric ones.
They take their own integer path rather than the generic text setter: the
columns are nullable integers, and while SQLite would coerce '14' quietly, a
shared MySQL logbook would not — and empty must become NULL, never ''. Bounds
checked (DXCC <1000, CQ 1-40, ITU 1-90) so a slip cannot stamp zone 400 across
a thousand rows.
2026-08-29 00:13:47 +02:00
rouggy 10ef984962 feat(k3): align RIT/XIT and the power step with the other consoles
'None of the consoles look alike' is the complaint ShiftRow exists to answer,
and the Elecraft panel was still driving its offset with a row of nudge buttons.
It now uses the shared control — ±, wheel, typed value — plus the same
Ctrl+←/→ 10 Hz clarifier the Icom and TCI panels have. The K3 keeps ONE offset
for RIT and XIT, so both rows show it, exactly like the Icom's.

The backend gains the absolute setter the shared control speaks
(SetKenwoodRITOffset, funnelled through the same RO write as the nudge), and
the power slider moves in 1 W steps — nobody asks a K3 for 'between 10 and 15
watts' in fives.

Also per review: the chase switches are labelled 'Chase POTA' / 'Chase SOTA',
matching 'Chase new grids' beside them.
2026-08-28 23:56:49 +02:00
rouggy bd8719ce99 feat(cluster): chase switches for POTA and SOTA
An operator who does not chase parks does not want NEW POTA shouting from every
activator spot. Two switches (Settings → DX Cluster, on by default): off, the
marker is withdrawn at the display layer — applySpotDisplay, the same chokepoint
the grid, the band map and the filter read through — so the badge, the colour,
the filter chip and the reference column all go quiet together, and a new-band +
new-POTA spot reads NEW BAND alone. The facts keep being computed; only the
telling stops, so ticking the box back on needs no rescan.
2026-08-28 23:48:22 +02:00
rouggy 5e38319379 style(settings): trim the DX Cluster panel's explanations
Per review: the digital-grouping sentence on the same-slot option, the
spot-lifetime explanation, the ring-buffer paragraph on the spots-kept field,
and the free-public-nodes line all go.
2026-08-28 23:44:01 +02:00
rouggy 7e7ad50f60 feat(k3): a mode row on the Elecraft console — CW/USB/LSB/DATA/DATA-RTTY
The report: switching the K3 to a data mode 'does not work for FT8 — the K3
does not go into DATA'. The mode digit is only half the answer on that radio:
MD6 keeps whatever DT submode the previous session left, and with FSK D still
armed the rig keys FT8 with no rear-audio modulation.

The panel buttons say the whole thing: DATA is MD6+DT0 (DATA A, the soundcard
path), DATA RTTY is MD6+DT2 (FSK D). The DT submode is also read on the
settings beat — Elecraft only, a plain Kenwood would '?;' it — so the active
DATA button follows what the rig is actually in, front-panel changes included.
A dedicated SetKenwoodPanelMode rather than the logger's SetMode: a panel
button is the operator saying exactly what the rig should do, not an ADIF mode
to be mapped through preferences.
2026-08-28 23:35:25 +02:00
rouggy 0f4e31853b fix(cluster): slot colour apart from POTA, chips match badges, NEW CALL filter works
Three from review. Aqua for NEW SLOT sat right next to the POTA green — it is
now the sky cyan the panadapter palette has shipped for new-slot all along.
The NEW COUNTY chip was green while its badge is violet, and NEW SLOT's chip
was still caution yellow: chips now carry the badge's own colour (color-mix for
the muted border/背景), because a filter that does not look like what it selects
has to be learned twice.

And the NEW CALL chip matched only the DISPLAYED status, which is manufactured
by the slot-highlight option — with that option off the chip matched nothing
and read as broken. It now filters on the fact itself (worked_slot false), so
it works either way.
2026-08-28 23:29:08 +02:00
rouggy c222468021 style(cluster): give NEW SLOT its own colour
The whole new-* family shared the warning amber while the NEW PFX marker sits in
caution yellow — two different facts, two near-identical colours in one cell.
NEW SLOT now takes aqua (chart-2), the same story the panadapter palette already
tells: its default for new-slot has been cyan all along.
2026-08-28 23:24:06 +02:00
rouggy 2fb4a4d0ce fix(spot): in split, pre-fill the RX frequency — where the station is
The Send-spot dialog took catState.freq_hz, which is the TX frequency. Working
a DXpedition split, that is where WE transmit: the spot went out five up from
the DX, pointing the whole cluster at the pile-up instead of the station. The
RX frequency is where we listen — where the DX is — and is what a spot names.
2026-08-28 23:21:17 +02:00
rouggy e4828482c4 fix(tci): send the sensor subscription in both cases
Two rounds of fixes and the SunSDR's meters are still silent. The one remaining
difference from the protocol document is the case: its examples read
TX_SENSORS_ENABLE:true,200; and ours went out lower-case. Every other command
works lower-case, but nothing proves this newer path does — a case-insensitive
server ignores the duplicate, a sensitive one finally hears it.
2026-08-28 22:54:44 +02:00
rouggy 8acfda4e42 fix(tci): resubscribe to the meters at 'ready', and log what comes back
The report from a real SunSDR: transmit power and SWR still empty after the
sensors fix. The subscription went out once, at connect — while ExpertSDR3 is
still streaming its initial state dump, exactly where a unidirectional control
command can be ignored. It is now renewed every time the server says 'ready'.

The sensor messages also join the logged-on-arrival set, capped like the rest:
the next log will say whether TX_SENSORS ever arrives, which is the question —
a radio that never sends it (AetherSDR may not) and a frame that arrived and
was dropped leave the same blank meters and need opposite fixes.
2026-08-28 22:51:25 +02:00
rouggy db24c38e63 chore: release v0.26.23 2026-08-28 22:45:55 +02:00
rouggy 06868e9ed1 style(settings): three more explanations off the General panel
The SCP paragraph, the digital-grouping parenthetical and the IARU region hint
all move into tooltips on their own controls.
2026-08-28 22:20:31 +02:00
rouggy 3ed643e072 style(settings): tidy the General panel
Per review: the panel-wide 'saved instantly' hint goes; the date-format picker
loses its embedded sample line (kept as the buttons' tooltip) so the row is one
line tall; the IARU region moves up under the date format, before the themes;
and the parentheticals after Distances-in-miles, Check-updates and the
telemetry opt-out go. The telemetry and ClubLog explanations survive as
tooltips — an opt-out about data leaving the machine, and an option changing
how entities resolve, should still say what they do somewhere.
2026-08-28 22:15:53 +02:00
rouggy f0f9898f7c feat(bandmap): draw the band plan of the operator's IARU region
The band maps carried one hard-coded table — Region 1's — so a US operator's
40 m stopped at 7200 with stations spotted at 7250 hanging past the top of the
map, and the SSB wash started 25 kHz early. The region is a station-level fact
stated once (Settings → General, portable pref); lib/bandplan owns the three
tables and publishes changes to the open maps the way the distance unit reaches
the grids.

The tables stay deliberately coarse: a band map's wash is context, not a
regulatory chart, so only the differences an operator notices are split out —
Region 2's 80 m to 4000 and 40 m to 7300 (phone from 7125), Region 3's 80 m to
3900, the wider VHF/UHF allocations. National fine print does not belong in a
background tint.
2026-08-28 21:55:37 +02:00
rouggy 73cae855ed chore(labels): park the label designer and printing on feature/labels
The feature needs more rounds than the next release can wait for, so main goes
back to before it: the packages, bindings, migration, UI and i18n all move to
the feature/labels branch, which holds every commit. The 0.26.23 block keeps
only the Station column.

The 0031 migration may already have run on a machine that launched a dev build;
the two label tables it created are inert and the recorded migration row is
harmless — the runner only applies filenames it has, so re-adding the migration
when the branch merges will skip cleanly there and apply everywhere else.
2026-08-28 21:35:50 +02:00
rouggy de3a115ca6 chore(changelog): move the post-release entries into a 0.26.23 block
The Station column, the Label Designer and the label printing all landed after
v0.26.22 was tagged; the .22 block is byte-identical to the tag again.
2026-08-28 21:31:09 +02:00
rouggy 1d7633484b fix(labels): the manager's address, not the DX's — and one PDF, just opened
Three corrections from the first real session. Routed via a manager, the box
was prefilled with the DX's own address — the one thing that must not go on
that envelope. It now starts empty and the QRZ fetch fills in the MANAGER's;
switching the routing recomputes the box unless the operator has typed in it,
because a hand-checked address is not the app's to replace.

A fetch that came back with no street was overwriting a reviewed address with a
bare country — the cty.dat fallback dressed as an answer. It now refuses to
touch the box and says nothing was found. And the prefill no longer stacks the
same town three times (address + QTH + country all carrying it).

The output is ONE PDF for the whole session, each page at its own label size,
written to the temp dir and opened straight in the viewer — no save dialog: the
file is a print run, not a document to keep.
2026-08-28 20:07:36 +02:00
rouggy 5ee0ade54b feat(labels): print the labels — queue, address review, PDF, log update
The printing session in three steps. The worklist is the paper queue (ADIF
qsl_sent R/Q), grouped by callsign since several QSOs of one station share a
card. Each recipient is reviewed before anything prints: routing first — via
manager when qsl_via says so, direct when an address is known, bureau otherwise
— then the address itself, editable and fetchable from QRZ (the MANAGER's
address when routing says via). What is printed is the reviewed text verbatim,
not a re-resolution that could differ from what was checked.

One PDF per label kind, never one file for all: a roll printer holds one stock
at a time, and a file mixing 29 mm addresses with 62 mm QSO labels could not be
printed at all. Pages are rasterised by the designer's own renderer at the
stock's dpi and carried into the PDF untouched — internal/pdf is a hand-written
image-page writer (DeviceGray + flate: monochrome, lossless, no cgo) because
that is the entire need.

Bureau stations get no address label (no envelope); return labels are printed
one per envelope. Finishing offers the log update: QSL_SENT=Y, the chosen date,
via B or D per routing — through the same BulkUpdateQSL the paper view uses.
2026-08-28 19:58:37 +02:00
rouggy e637f0814d style(labels): fit the preview to the pane
A fixed 720 px cap cut a 98 mm label off at the RST column and wasted half the
window; the scale now follows the centre pane's measured size, with a floor so
small stock never renders unreadably.
2026-08-28 19:46:54 +02:00
rouggy 1a169fdb4f feat(labels): the Label Designer — QSO and address labels for paper QSL
The designer's data model lives in internal/labels: STOCKS are the physical
roll in the printer (geometry in mm, margins, dpi — seeded with the common
Brother DK sizes, the QL family being what prompted the feature), TEMPLATES are
one design each, of two kinds: the QSO label glued on the card, whose repeating
table carries several contacts of the same station, and the address label for
the envelope, whose lines collapse when a variable is empty.

Everything is measured in millimetres — labels are sold in mm, and an operator
lining a design up against a physical sticker thinks in mm; pixels exist only in
the renderer, at the stock's dpi. The canvas renderer is shared between the
editor's preview and the future print path, so there is no second
implementation for the preview to disagree with.

The preview is fed with the log's latest contacts rather than lorem ipsum: real
data shows a too-narrow column immediately.

Printing (PDF, one page per label at exact size) is the next module; nothing
here prints yet.
2026-08-28 19:41:15 +02:00
rouggy 3dc31697cd feat(lotw): name the station callsign on each downloaded confirmation
With 'All my callsigns' the report spans F4BPO, F4BPO/P and TM2Q at once, and a
list mixing them says nothing about which one a confirmation belongs to — which
is the question that option creates.

The column appears only when the rows actually carry a station: the other
services return one, and an empty column for them would be noise.
2026-08-28 17:43:05 +02:00
rouggy 242a68080a chore: release v0.26.22 2026-08-28 17:33:35 +02:00
rouggy 8c7e1c1a3d fix(cluster): group duplicates by call AND band AND mode
The grouping keyed on the callsign alone, so every spot of a station outside the
first one's band and mode was dropped from the list. RI1FJL spotted on 17m CW,
20m, 30m, 12m and 15m FT8 showed as a single row: four slots gone from the one
view an operator uses to find them.

A duplicate is the dozen skimmers that all heard the same CQ — same station,
same band, same mode. The same station on another band is the opposite of a
duplicate; it is what the chaser is scanning for.
2026-08-28 16:25:06 +02:00
rouggy 47ddbed665 fix(tci): send the spot colour as an unsigned ARGB integer
Expert Electronics' own document gives the command whole:

    SPOT:RN6LHF,CW,7100000,16711680,ANY_TEXT;

16711680 is 0x00FF0000 — positive. This backend sent the same field as a SIGNED
32-bit value, from a third-party example: with the alpha byte set to FF for
opacity, 0xFFFFA500 becomes -22336, and a spot whose colour ExpertSDR cannot
read is dropped without a reply or an error.

Reported on ExpertSDR3 1.3, which speaks TCI 2.x — the protocol version was
never the problem, and my first reading of that report was wrong.

The first three spots are now logged verbatim: an ignored spot leaves no trace
whatsoever, so that line is the only evidence of what went out.
2026-08-28 16:23:32 +02:00
rouggy fd7ae77a61 fix(tci): subscribe to the radio's meters; fix the new-spot count; explain an SMTP refusal
TCI meters: the S-meter came only from RX_SMETER and the transmit meters from
TX_POWER / TX_SWR — commands ExpertSDR3 does not send. The protocol's answer is
a subscription (RX_SENSORS_ENABLE / TX_SENSORS_ENABLE, §4.4 of the TCI PDF),
after which the radio pushes RX_CHANNEL_SENSORS and TX_SENSORS. Nobody had
asked, so the console's meters sat empty in RX and in TX while everything else
worked.

Cluster: the held-spot counter looked for the row it froze on. A station spotted
again REPLACES its row, so that row vanishes in the ordinary course of things
and the count fell through to 'everything is new' — 4, 5, then 500. Counted by
timestamp now, which survives both the replacement and the ring buffer.

SMTP: '535 5.7.139 basic authentication is disabled' is a policy, not a typo.
The message now says so, and says what actually helps, without claiming a policy
when the server simply rejected the password.
2026-08-28 15:29:44 +02:00
rouggy 3e794f57e0 perf(cluster): widen the spot batching window with the rate of the feed
Every flush commits state the whole window re-renders on, and the window was a
flat 50 ms — twenty full renders a second under an RBN firehose. That is paid
everywhere else in the interface, and it is what a dropdown highlighting its
entries a beat behind the mouse actually is.

The window now follows the rate: 50 ms on a quiet cluster, where a spot should
appear the moment it arrives; 200 ms past five a second; 500 ms past twenty,
where half a second's delay on a line already scrolling past is invisible.
2026-08-28 15:06:08 +02:00
rouggy 30f74583ff style(cluster): one header row in the docked pane
The pane drew its own title bar above the grid's toolbar, so the cluster spent
two lines on headers where Recent QSOs beside it spent one — in a pane often
only a few spots tall. The grid's toolbar now takes what the caller wants on its
left, and the pane passes its title, live count and Filters button there.
Reported by VK4DX.
2026-08-28 13:15:41 +02:00
rouggy f7b9aa2181 fix(lotw): show TQSL's account of a refused upload, not just the error
UploadLoTW returns both a terse error ('no QSOs processed') and a Message
carrying TQSL's own lines — '17 QSO records were already uploaded', 'N QSO
records are out of date range'. The caller took the error whenever there was
one, which is precisely the half that explains nothing: the operator saw a red
line naming a condition with three unrelated causes and no way to tell which.
2026-08-28 13:10:09 +02:00
rouggy 766b0f95a4 feat(tci): key CW through the radio's own macro keyer
The sixth CW engine, and the one the TCI backend was left without. A SunSDR
keys from the WebSocket that already carries the CAT: no WinKeyer, no second
serial port, nothing to wire.

    CW_MACROS:0,<text>;     send
    CW_MACROS_SPEED:<wpm>;  speed
    CW_MACROS_STOP;         abort

Confirmed against the TCI command table in ars-ka0s/eesdr-tci — the source that
settled SPOT. CW_MACROS rather than TCI 2.0's CW_MSG: it exists from 1.6, and
OpsLog resolves its own variables, so the before/after callsign fields have
nothing to carry.

Commas and semicolons are stripped before sending. They are the protocol's own
separators: a comma would become another argument, a semicolon would end the
command with the message half keyed and the rest parsed as a command.

Only the MACRO speed is set, not the paddle keyer's — an operator who set their
paddle to 28 wpm did not ask for it to change because a macro went out at 25.
And there is no backspace: TCI can stop a message but cannot un-type one, so the
type-ahead correction the Flex engine offers is absent rather than faked.
2026-08-28 13:01:55 +02:00
rouggy 8bc4ed68d4 fix(window): place the window in absolute desktop coordinates
Wails saves and restores in two different coordinate systems. WindowGetPosition
returns GetWindowRect — absolute. WindowSetPosition is winc's ControlBase.SetPos,
which adds the CURRENT monitor's work-area origin:

    w32.SetWindowPos(hwnd, HWND_TOP, int(info.RcWork.Left)+x, ...)

On the primary monitor that origin is 0 and nothing shows. With a monitor to the
LEFT it compounds: a station with its left screen at x=-3840 saved -3844,
reopened there, had -3840 added, and stored -7684 — then -11524, one screen
further out at every launch, until the window was off the desktop entirely.

So the placement is done here, with SetWindowPos and no offset, falling back to
the toolkit when the handle cannot be found. Compact mode had the same pairing
and is fixed with it.
2026-08-28 12:48:03 +02:00
rouggy d534825e92 fix(tci): pick the sideband from the frequency just commanded
Clicking a spot sets the frequency, then the mode 150 ms later, and SetMode
chose USB or LSB from t.freqA — the frequency the radio had ECHOED. From 7 MHz
onto a 14 MHz spot that echo has often not landed, so the sideband was computed
for the band being left: LSB on 20 m. Clicking the same spot again, the echo
having arrived, gave USB. Reported from a SunSDR as 'the frequency is right, the
mode is wrong until I click twice'.

SetFrequency now records what was asked for and SetMode prefers it until the
radio's own echo confirms the move.

The server's 'protocol:' announcement is also kept instead of being filed under
unhandled: it names the ExpertSDR and its TCI version, and panorama spots need
TCI 1.5 — older servers accept the spot commands and silently drop them, which
is indistinguishable from a broken logger. Now it says so.
2026-08-28 12:42:05 +02:00
rouggy 08d6492df1 fix(bandmap): say WHOSE 'Worked' it is — the entity's, not the callsign's
The status comes from spotEntityStatus: it means the country has been worked on
this band and mode. The label said 'Worked (this band + mode already in log)',
which reads as 'I have had this station' — so a spot the cluster called NEW PFX
looked like a contradiction, when the two were answering different questions
about different subjects.

The callsign-level fact has its own marker and its own words ('Callsign already
worked'), so the two are now told apart by reading them.
2026-08-28 12:22:23 +02:00
rouggy a156b6ad10 fix(bandmap): the two tooltip labels the previous commit left out
Without them t() was handed undefined for a new prefix or grid, so the tooltip
would have shown an empty segment — the opposite of naming the fact.
2026-08-28 12:17:59 +02:00
rouggy 3bb92f79b2 fix(bandmap): name the new prefix and new grid in the tooltip
The strip deliberately shows three markers of five — the pill is 22 px and a
fourth segment makes it a colour code nobody reads. But the tooltip has room and
was filtering them out too, so the same spot read NEW PFX in the cluster and
'Worked (this band + mode already in log)' on the map. Both were true: the
entity is worked on that slot and the WPX prefix never has been. Neither view
said so.
2026-08-28 12:17:09 +02:00
rouggy 65cae0d822 perf(lotw): stop asking for the QSL details by default
A tester compared LogHX's two download options on the same account: two minutes
for the confirmations, twenty for the confirmations with QSO details. OpsLog was
always sending qso_qsldetail=yes — LogHX's slow option — which is the whole of
the wait people were reporting.

Marking a confirmation needs call, date, band and mode; the detail adds the QSL
date and the station's grid, state and county. Now a choice, off by default, and
forced on when the download is also ADDING the QSOs it cannot find — the one
case where those fields have no other source.
2026-08-28 08:54:42 +02:00
rouggy b24f880d62 chore: release v0.26.21 2026-08-28 08:48:14 +02:00
rouggy ef71ddb648 docs(changelog): open 0.26.21 with the entries written after the release
Miles and the LoTW download progress landed after v0.26.20 was tagged, so they
belonged to the next block: an entry appended to a shipped one never reaches the
operators who installed it, and misstates what that version contained. The .20
block is byte-identical to the tag again.
2026-08-28 08:47:00 +02:00
rouggy 0143a84cee fix(lotw): stop the heartbeat when the report starts arriving
Deferred, it stopped at the end of the function — so 'still waiting for LoTW to
build the report' kept printing between the megabyte lines, saying the opposite
of what was happening.
2026-08-28 08:43:06 +02:00
rouggy 82721110ed fix(lotw): count out the wait before the first byte
The progress lines only start once bytes arrive, and on a large account nothing
arrives for minutes — LoTW builds the entire report before sending any of it.
That silence WAS the complaint: the window still just said 'working'.

A heartbeat every fifteen seconds until the headers land, then the HTTP status,
then the megabytes — the first at 256 KB rather than 1 MB, so the very first
sign that it is moving comes early.
2026-08-28 08:38:34 +02:00
rouggy aec363b152 fix(lotw): show the download moving, retry a busy server, fail a dead one
Three reports of the same shape: a 503 for anything wider than a few days
before, and since the timeout was raised, a window that sits at 'working'
forever. Both are the same missing thing — nothing said what the transfer was
doing.

The body is now read in chunks and every megabyte is reported. A 503/502/504 is
retried twice, 20 s then 40 s, each attempt announced: LoTW answers 'busy' to a
wide report often enough that other loggers simply ask again. And the deadline
is no longer on the whole exchange, which either cut off a healthy slow download
or hid a dead one for twenty minutes — it is ten minutes to START answering
(LoTW builds the whole report first) and two minutes of silence once it has,
which is the difference between slow and dead.
2026-08-28 08:29:26 +02:00
rouggy 9a21c936b1 feat(units): show distances in miles
Everything is computed in kilometres and converted once at display time, in
lib/units — storing miles anywhere would give the same number two sources of
truth and a rounding error that grows with every hop.

The grids capture the unit inside their column definitions, header and formatter
both, so a change is published to them the way the date format already is;
without that a toggle would only appear after a language change or a restart.
The preference is portable, like the other display ones.
2026-08-28 08:25:02 +02:00
rouggy d8f0fd7b4f chore: release v0.26.20 2026-08-27 23:47:14 +02:00
rouggy 4a942a04c3 docs(changelog): name the SOTA cluster server in the SOTA entry 2026-08-27 23:27:26 +02:00
rouggy ecae68ca79 merge: matrix call mark, Icom scope, KPA chip, SOTA column, awards slots, LoTW download fixes 2026-08-27 23:24:34 +02:00
rouggy 9270b227b0 fix(lotw): send a date even for 'all', and give the report time to arrive
Without qso_qslsince LoTW does not answer 'every confirmation' — it answers
with a few recent ones, as a 200 and a valid ADIF. 'All' therefore downloaded a
nearly empty report and said 'matched 1 of 1' on an account holding twelve
thousand. It now asks from 1945-11-15, older than any QSO LoTW accepts.

And the request had two minutes: LoTW spends several of them building a full
account before the first byte, so asking for everything ended in 'context
deadline exceeded while reading body' — a network-shaped message for a
too-short deadline. Twenty minutes, and the read cap raised past the 18 MB such
a report actually weighs.
2026-08-27 23:15:54 +02:00
rouggy cff590fe8a fix(lotw): keep another station's confirmations out, and show a suspect report
Unscoped, the report carries every station on the account — including the calls
belonging to another profile's logbook. Those match nothing here, and with 'add
the ones not found' ticked they would pour a second log into this one. The
station callsigns this logbook actually holds are now the filter: a portable
worked here is kept, an expedition call never used here is skipped and counted.

A near-empty report is also the failure that reads as success — 'matched 1 of 1'
where the account holds twelve thousand. Under 4 KB, what LoTW answered is shown
verbatim instead.
2026-08-27 23:12:44 +02:00
rouggy 4366083152 feat(lotw): let the download cover every callsign on the account
The download passes qso_owncall so one profile does not pull another's
confirmations. That scope also hides them: a QSO made as F4BPO/P is confirmed at
LoTW and can never come back to an F4BPO profile, so it stays unconfirmed here
for good while the ARRL counts it — found while reconciling a DXCC account
against the panel, where it was the whole of the CW gap (Jersey, worked as
F4BPO/P).

Off by default: the scope is right for anyone whose profiles are separate
stations.
2026-08-27 22:43:46 +02:00
rouggy 8865af35fd feat(qsl): a QRZ button beside the paper-QSL search 2026-08-27 21:53:59 +02:00
rouggy bfad51268b style(awards): fade the confirmed cells while chasing the ones to confirm
The filter keeps a REFERENCE for its unconfirmed slots, so its confirmed ones
come along — and green on grey means the answer is the quietest thing in the
row. Faded to a quarter under that filter only, not hidden: which band is
already done is part of deciding which one to chase.
2026-08-27 21:45:46 +02:00
rouggy 0e77e8d61f feat(awards): find the slots worked but not confirmed
The Challenge line says 1832 worked against 1554 confirmed and stops there —
278 band-slots waiting for a card with nothing pointing at them. Every existing
filter works per REFERENCE, so an entity confirmed on 20 m answers 'confirmed'
and its unconfirmed 15 m contact stays invisible.

The new filter keeps the references holding at least one such slot, and the
count beside the reference total is the gap itself, recomputed over whatever the
other filters left on screen and over the bands actually displayed — so it
always adds up to the columns in front of the operator.
2026-08-27 21:38:25 +02:00
rouggy 08d316b1e0 feat(cluster): a SOTA column, and a spot click that credits the summit
The SOTA feeds put the summit in the spot's own text, so there is nothing to
poll: a regex on the comment gives the reference, and clicking the spot writes
SOTA@<ref> into the award references the way a park already wrote POTA@<ref>.

The regex is narrow on purpose — association/region-NNN, anchored — because
POTA (US-4475), WWFF (DLFF-0001) and portable callsigns (DL/SP9DPM/P) share
that field and none of them is a summit. Pinned by a table test.

Off by default: the reference is only there on the summit feeds, and an empty
column for every operator who does not chase them is worse than a checkbox.
2026-08-27 21:33:17 +02:00
rouggy b8796369ba fix(amp): the KPA was missing from the status-bar chip
The chip read a.spe ?? a.acom ?? a.pgxl, so a KPA fell through to the
not-connected fallback: red on a working amplifier, and a click that opened the
settings instead of switching to STANDBY. Reported from a KPA500 whose panel
showed band, SWR and temperature at the same time.

The card's offline text also borrowed the Acom's string, so a KPA that dropped
its link announced itself as an Acom.
2026-08-27 18:55:55 +02:00
rouggy fa1c41388d fix(icom): say when a radio has no scope stream instead of drawing nothing
The CI-V trace settles it: the IC-7851 answers 27 10 01 with FB and 27 14 00
with its mode, but refuses 27 11 in BOTH shapes — it controls its scope over
CI-V and never streams it. Its last firmware is from 2016, older than the
waveform stream itself; Hamlib's caps claim otherwise, the radio is the
authority.

Rejected both ways is a permanent answer, so it is remembered and reported:
the panadapter says the radio does not send its scope, which is the one thing a
black rectangle could not say.
2026-08-27 16:30:39 +02:00
rouggy d2cfad490a revert(icom): keep 0x27 0x11 as the scope data switch, log what the retry got
Hamlib documents the spectrum scope on the IC-785x, so a rejected 0x27 0x11 is
not proof the command is missing — and taking 0x27 0x10 for the data switch
would have blanked that operator's own scope screen when OpsLog disabled it.

Both shapes were refused within 96 ms, so neither was a timeout, and guessing
the next subcommand is how the last two rounds went. The retry now logs the
second attempt's own error and the failure points at the CI-V trace.
2026-08-27 16:25:29 +02:00
rouggy 69d78ba8c0 fix(icom): fall back to 0x27 0x10 when a rig has no 0x27 0x11
The IC-7851 rejects 0x27 0x11 in BOTH shapes: on that radio 0x27 0x10 is the
waveform-output switch itself, not a display switch. Rejected both ways, take
0x10 as the output command and switch it off on disable too — there it stops a
stream rather than blanking the operator's own scope screen.

A mode/span/edge answer also settles the selector question directly: three bytes
or more means the rig wants the main/sub form. Worth reading, because a
wrong-shaped SET is answered with silence on this firmware, and a timeout is
something the rejection retry cannot act on — which is why the fixed/centre
sets were timing out.
2026-08-27 16:18:55 +02:00
rouggy 9cf1984fb2 fix(icom): ask the radio which shape its scope commands take
The IC-7851 rejects "27 11 01" and wants "27 11 00 01" — the main/sub selector
its two scopes need. The shape was picked from a list of CI-V addresses, so an
address not on it got the wrong one and the scope stayed blank with a rejection
in the log and nothing on screen.

A rejection is an unambiguous answer, so a rejected 0x27 set is now re-sent in
the other shape and the winner remembered. A TIMEOUT deliberately is not
retried: several firmwares never ack a 0x27 set, and treating silence as a
wrong guess would flip a rig that was already working.
2026-08-27 16:14:53 +02:00
rouggy ee8fd32bf7 fix(matrix): dot the portable variants too
The header counts QSOs with the callsign through callMatch — RI1FJL/1 and
ZA/RI1FJL included — while the grid's own per-callsign columns matched the bare
string. A cell could hold one of the QSOs the header had counted and show
nothing.
2026-08-27 15:57:41 +02:00
rouggy f357dad629 feat(appearance): give the worked-with-this-call dot its own two colours
The dot is drawn over all five cell backgrounds, so it cannot borrow one of
their colours; it defaults to the theme foreground with a background ring and
now takes two overrides of its own, worked and confirmed, alongside the rest of
the matrix palette.
2026-08-27 15:29:01 +02:00
rouggy b3547364d4 style(matrix): move the worked-with-this-call dot in from the corner 2026-08-27 09:01:31 +02:00
rouggy 965ed4c792 feat(matrix): mark the slots already worked with the callsign in hand
The worked-before cell answered one question with two facts fused into it.
bandStatusCode takes the highest of them, so a confirmed entity outranks a
worked callsign — right for awards, wrong while chasing: a slot worked with the
DXpedition this morning reads "entity confirmed" and says nothing about it.

BandStatus now carries the callsign's own answer alongside the entity's, and the
cell draws a dot for it. The dot is deliberately identical everywhere — same
shape, same colour, over all five backgrounds — so it is read as one thing
rather than as five variants of the colour underneath it.
2026-08-27 08:55:37 +02:00
rouggy 32dbfbd04e chore(changelog): open 0.26.20 with the per-radio MY_RIG 2026-08-27 01:09:09 +02:00
rouggy a930a4f02d merge: MY_RIG follows the connected radio
Operating conditions describe a plan; a logged QSO asks which radio was
keying. With one rig those were the same answer, with several they are
not — so each saved radio carries its own MY_RIG, ahead of the per-band
station and doing nothing at all when left empty.
2026-08-27 01:08:19 +02:00
rouggy f98a831195 feat(cat): MY_RIG follows the radio that is connected
With one rig, MY_RIG belonged in Operating conditions and nowhere else.
With several, that becomes the wrong place: operating conditions describe
a PLAN — 'on 20 m I use the beam and the 7300' — while the question a
logged QSO asks is which radio was keying.

So each saved radio carries its own MY_RIG, consulted BEFORE the per-band
station. When the two disagree — a second rig borrowed for one evening on
20 m — the one that is transmitting is the true answer.

Left empty it changes nothing at all: the old chain (band default, then
the profile's rig) answers exactly as it did, which is what every
single-radio station will keep doing without touching a setting.
2026-08-27 01:03:27 +02:00
rouggy 9d21af9f7c chore: release v0.26.19 2026-08-27 00:55:38 +02:00
rouggy 0680181016 chore: drop a stray temp file committed by accident
theirs.tmp was scratch from comparing the GitHub readme against ours. It
had no business in the repository and none in a release.
2026-08-27 00:47:37 +02:00
rouggy afd0714301 chore(changelog): open 0.26.19 with the multi-radio switch 2026-08-27 00:47:28 +02:00
rouggy 8855eaf05a merge: several radios, switched from the status bar
The answer to 'I have two rigs' was 'make two profiles', which moves the
whole station — logbook included — to change which radio is connected.
Radios are a list now, like amplifiers, and the CAT chip switches between
them while everything else stays put.

The active radio still lives in the settings keys the rest of OpsLog
reads, so the consoles, the CAT sharing and the band-follow needed no
change at all.
2026-08-27 00:46:18 +02:00
rouggy 2594697e00 fix(cat): the chip says what YOU called the radio
It showed what the radio calls itself over CAT — 'Kenwood (911)' for a K3,
a bare 'CAT' for a Flex that reports nothing useful. That is the answer to
a question nobody asks once the rig has a name in the list, and it made
the two radios look alike in the one place they have to be told apart.

The name the operator typed comes first now, on the chip and in the menu,
and falls back to the radio's own identity when they typed none. The model
identity is still in the tooltip, where it answers 'what is actually
connected' without taking the place of 'which of my rigs is this'.
2026-08-27 00:42:26 +02:00
rouggy cf5efea3e4 fix(cat): the chip opens the radio menu with one radio too
It only became a menu from two radios, on the reasoning that a single
radio has nothing to switch to. That hides the feature from precisely the
operator who has not made a second radio yet — the click lands on a
settings dialog they did not ask for, which is what happened on the first
try. With one radio the menu now shows that radio and 'Add a radio…'.

Right-click still goes straight to the CAT settings.
2026-08-27 00:32:00 +02:00
rouggy 4689505fb9 feat(cat): several radios, switched from the status bar
The answer to 'I have two rigs' was 'make two profiles', which is a heavy
instrument for a light question: a profile carries the whole station —
logbook, callsign, awards, cluster, macros — so switching one to change
which radio is connected takes all of that with it, including a change of
logbook when the profiles point at different databases.

Radios are a list now, the way amplifiers already are. The CAT chip in the
status bar opens it, one click connects the chosen rig, and nothing else
about the station moves.

The storage keeps the ACTIVE radio in the same settings keys everything
already reads (cat.backend, cat.icom_port, …), and switching writes the
chosen entry into them and reloads the link. So the consoles, the CAT
sharing, the band-follow and every panel see exactly what they saw before
and needed no change at all — the list is a second store beside the
configuration, not a replacement for it.

Details that matter more than they look:
  - An operator who has run one rig for a year opens the list and finds it
    there, because a missing list reads as the CURRENT settings rather
    than as nothing. It is written on the first save, not on the first
    read.
  - Editing the CAT panel updates the active entry, or an edit made before
    switching away would be lost on the way back.
  - A new radio starts as a COPY of the current one: a second rig is
    usually the same shape with one port changed, and an empty form is a
    form to fill in twice.
  - Switching saves the panel first, so edits to the radio being left
    behind are kept.
  - The chip only becomes a menu with more than one radio; with one it
    opens the CAT settings exactly as it always did.
2026-08-27 00:22:19 +02:00
rouggy 23f425f95f docs(readme): restore it, and bring it up to date
THE README WAS GONE. A commit of mine last night replaced OpsLog's readme
with the text of the TCI protocol specification — 322 lines of ours for 77
of Expert Electronics' — and nobody noticed because nothing builds from
it. Restored from the commit before, then updated.

What it was missing, all of it shipped since: the Kenwood/Elecraft and
Yaesu CAT backends and their consoles, the SunSDR console, TCI audio in
both directions, CAT sharing over Hamlib rigctl or TCI, the Elecraft
KPA500/KPA1500 and the Tuner Genius XL, Cloudlog and HAMLOG uploads, the
RDA district work, the DXCC Challenge, the editable satellite list, four
main-view panes instead of two, and Esri basemaps in place of Carto.

Also a section on importing a log, which had none — including the rule
that matters most to somebody moving years of contacts across: a deleted
DXCC entity keeps the number the file gives it, because cty.dat only knows
where a callsign is today.
2026-08-26 23:38:35 +02:00
rouggy 2fd9845b37 chore: release v0.26.18 2026-08-26 22:17:07 +02:00
rouggy e851bd97e0 chore(changelog): fold the console's fixes into its own entry
It has not shipped yet, so an operator reading about the SunSDR console
should meet what it does — not a list of repairs to a thing they have
never run.
2026-08-26 22:10:01 +02:00
rouggy b487ca1145 merge: the SunSDR console, working this time
Everything here came from one operator with the radio in front of him, and
most of it was mine to fix. The drive commands need the transceiver index
('drive:0,15;', not 'drive:15;') or the radio ignores them without a word.
The console now holds a click the radio does not echo, so a working button
stops looking dead — and lets go the moment the radio contradicts it, so a
REFUSED setting still tells the truth. Filters per mode, APF only in CW,
levels on wide rows with typed values, the RIT control shared with the
Icom console, the transmit meters, and a TUNE that can be switched off
again.

Two findings worth keeping: this radio re-asserts sql_enable eighty
milliseconds after being told to turn the squelch off, and it never
answers TX_POWER or TX_SWR — both are its own doing, and both are visible
in the log rather than argued about.
2026-08-26 22:07:24 +02:00
rouggy 27b342a5e7 chore(tci): cap the diagnostic logging per message type
The transmit meters are asked for four times a second while keyed, so
logging every arrival would fill an evening's log — and a diagnostic that
fills a log is one that gets switched off instead of read. Twenty of each
is enough to tell an answer from a silence, which is all it is for.
2026-08-26 22:07:11 +02:00
rouggy c1cd76bbcf fix(import): a deleted DXCC entity is not re-stamped from cty.dat
Reported with a Logger32 export: the record said <DXCC:3>151 and OpsLog
stored 54.

cty.dat answers one question — where is this callsign TODAY — and that is
the wrong question for a log. R1MVI was Malyj Vysotskij Island, entity
151, until the ARRL deleted it in 2012; the same call resolves to European
Russia today. Forcing the lookup onto a 2004 contact therefore destroys a
credit that can NEVER be worked again, because the place no longer counts.

So the ADIF's number wins whenever it names a deleted entity, and nothing
is corrected on those records at all — the country name and the zones of a
deleted entity are equally beyond what a present-day prefix table knows.
The list is the ADIF specification's own enumeration, sixty-odd entities
that only change when the ARRL deletes another one.

The guard sits in the forced path, so it also covers the grid's 'Update
from cty.dat' on a selection — the other way an operator could have lost
the same credits, one right-click at a time.
2026-08-26 21:59:53 +02:00
rouggy 4a28b51ade fix(awards): stale statistics, and the Challenge said out loud
Two things from one screenshot, and the second is arithmetic rather than a
bug.

Editing an award refreshed the grid and not the statistics matrix, so
changing which confirmations count left the table showing the old rule's
numbers with nothing to mark them stale. That is how a setting comes to
look as though it does nothing.

And OpsLog's 3229 against LoTW's 3004: the Challenge counts confirmed
band-slots on ten bands, and 60 m is not one of them. 3229 less the 224 in
the 60 m column is 3005. So the number was right and the QUESTION was
different — the panel now answers the Challenge one too, under the table
where the comparison is made.

The two totals also say what they are on hover. 'Total' and 'Général' side
by side tell nobody which counts entities and which counts band-slots, and
3309 read as entities is an impossible number — which is exactly how it
was read.
2026-08-26 21:45:11 +02:00
rouggy 130c4e72e0 chore(tci): log the transmit meters as they arrive, or fail to
The log shows 'tx_power;' going out four times a second during a tune and
nothing coming back — but that proves less than it looks: a reply that
arrived and failed to parse leaves exactly the same trace as one that
never came. Both are now visible.
2026-08-26 21:28:09 +02:00
rouggy 980c54a616 fix(tci): TUNE can be switched off again, and the meters watch it
Two faults with one cause: this radio does not echo 'tune:0,true'.

So the panel never knew a tune was running. The button stayed on TUNE and
every further press sent another START — there was no way to stop it from
here at all. The state is recorded when the command is sent now; whatever
the radio says afterwards still wins, it simply never says anything.

And the transmit meters were asked for only while t.tx, which a tune
carrier does not set: the radio reports tuning as its own state, not as a
transmission. So power and SWR sat at zero for the whole tune — the exact
carrier an operator holds a tune for in order to watch an SWR on. They now
follow PTT or TUNE, and the S-meter reads '—' under our own carrier
either way.
2026-08-26 21:25:06 +02:00
rouggy 1201b44908 feat(tci): the transmit meters, and no temperature invented
TX_POWER and TX_SWR are read-only commands the radio answers when asked,
so they are asked for on each poll of a KEYED radio and not at all
otherwise: a receiving station pays nothing for meters nobody is watching.
Both appear next to the S-meter only while transmitting, because showing
them the rest of the time would show the last thing that happened as if it
were now.

An SWR of 0 draws as '—' rather than as 1.0. A perfect match on an antenna
nobody has measured is the one reading an operator should never be handed.

There is no temperature. The protocol's command list has TX_POWER and
TX_SWR and nothing thermal at all — so rather than leave the question
hanging, it is written down where the next person will look for it. A
temperature invented from something else, on a transmitter, is exactly the
kind of number somebody would trust.
2026-08-26 21:14:58 +02:00
rouggy 9c7983b13e fix(alerts): one band plan, not two that disagree
A spot at 10131.5 showed as DATA in the cluster list and raised an alert
announcing SSB. Two tables answered the same question: the frontend knew
10.130-10.150 is the 30 m data segment, while the alert engine knew a CW
range that stopped at 10.130 and ended with a bare 'return SSB' for
everything else.

That fall-through was the fault. A band plan that answers 'SSB' for
anything it does not recognise is not a band plan, it is a default wearing
one — and it fed the alert text, the FlexRadio spot colours and the mode
the radio is told to switch to.

The Go table is now transcribed from the frontend's, segment for segment,
and returns nothing where it knows nothing. The order matters and is now
load-bearing — the FT8 and FT4 watering holes are listed BEFORE the wide
data blocks they sit inside — so there is a test that fails if anybody
sorts the table by frequency and quietly turns every FT8 hole into DATA.

WPM counts as CW while we are here: nothing else is reported in words per
minute, and RBN puts it on every line.
2026-08-26 21:09:52 +02:00
rouggy 01d0b8f22b fix(tci): the squelch is the radio's refusal, not our bug — and the panel now shows it
The log settles it, and it was not mute. Mute works: '→ mute:0,true;' and
the radio answers 'mute:0,true'. What happens is that the squelch REFUSES
to go off — we send 'sql_enable:0,false;', the radio echoes false, and
eighty milliseconds later announces 'sql_enable:0,true' again. Six times
in the log, always the same shape. The SQL lamp coming back on right after
a MUTE click is that revert landing, not the mute doing it.

So the optimistic hold is fixed rather than the phantom. It was a fixed
1.2 s, which is wrong in both directions: too short for a setting the
radio never echoes at all (AGC), and too long for one it refuses, where it
showed the operator a lie for a second. The requested value now stands
while the radio says nothing about that setting, and the instant the radio
reports any change for it, its word replaces ours. A refusal is therefore
visible immediately, and an unechoed setting still sticks.

Also from the same session: filters per MODE — the narrow end in CW, the
voice widths in SSB, a middle set for the digital modes — because 250 Hz
in SSB and 2.8 kHz in CW are buttons nobody presses. And APF is shown only
in CW: it rings a single tone out of the noise, which is a CW tool and
nothing else.
2026-08-26 21:04:00 +02:00
rouggy dad71e9e4f fix(tci): a filter button does what it says, and mute is put under a log
250 now means 0-250. It meant 575-825: the width was right and it was
centred on the CW note, on the reasoning that a CW filter should contain
the note. That reasoning may be right for a radio and it is still wrong
here, because it is not what the button says — and a button that does not
do what it says is worse than one that does something simple. The two
edges are editable underneath for anything else, which is what TCI takes
anyway.

And MUTE still lights the squelch on a real radio. Nothing in this code
can do that — the button sends mute and only mute, and the two are
separate state — so the radio's own announcements are logged as they
arrive. What it says after the command will settle whether this is our
reading or its doing; no more reasoning from here will.
2026-08-26 20:59:31 +02:00
rouggy fbe01bf19d fix(tci): wide level rows, honest filter labels, and mute read both ways
Three things reported from the radio, all of them mine.

THE LEVELS. Two half-width sliders side by side left each of them a couple
of centimetres long, which is not enough to set 15% with. One level per
row now, full width, with the value typed in or stepped with ± — and in
the radio's own units, so the volume is dB and the squelch a dBm
threshold, matching what ExpertSDR3's own window shows.

THE FILTERS. The button said 250 and the radio was set to 300-550: 250 Hz
wide, but sitting where no CW note is. The edges are computed from the
width now, and a narrow filter is CENTRED ON THE CW NOTE — a 250 Hz filter
from 100 to 350 would put the note outside its own passband. A button also
lights on the WIDTH the radio reports rather than on an exact pair of
edges, so moving one edge on the radio no longer darkens every button.

MUTE. Read from one shape only, while this radio reports the other
('mute:0,false'), so the button showed the opposite of the truth. Both are
accepted now.

None of this should have reached main before somebody had a radio in front
of it.
2026-08-26 20:54:28 +02:00
rouggy fc79be7c05 fix(tci): the drive commands need the TRX index, and the console holds its own clicks
Two faults, reported from a real SunSDR.

DRIVE AND TUNE DRIVE DID NOTHING, and neither did MUTE. Those commands
carry the transceiver index — 'drive:0,15;', not 'drive:15;' — and sent
without it the radio ignores them silently: no error, no answer, the power
unchanged. The rule was in the radio's own reports all along, which is
where it should have been read from: it announces 'drive:0,85' and
'mute:0,false' at connect, while 'mic_level:100' and 'volume:-12' come
with no index at all. Sending the shape the radio speaks in is the whole
rule, and it is now written down next to the two exceptions.

AGC LOOKED STUCK ON SLOW. The panel showed only what the radio reported
back, on the principle that the radio is the truth — but ExpertSDR3 does
not echo every setting it accepts, so a working button sat unlit. Changes
are shown at once and held for a moment now; whatever the radio announces
afterwards still wins, so a clamped or refused setting stays honest
without every working one looking broken.

Also from the same report, and fair: the consoles did not resemble each
other. The Icom panel's RIT control is now a shared component both use —
chip, signed offset, ± keys, wheel, and TYPING a value straight in, which
is the thing a row of ±10/±100 buttons cannot do. Ctrl+←/→ shifts the RIT
here as it does there. And LONG is gone from the AGC row: the protocol
takes it, but it is a hang time nobody reaches for between overs.
2026-08-26 19:15:48 +02:00
rouggy 4c2638a7e5 chore(changelog): the SunSDR console, in 0.26.18 2026-08-26 19:06:47 +02:00
rouggy a501366cbf merge: the SunSDR control console, and the audio device fixes with it
TCI pushes everything about the radio unasked, so the console is mostly a
place to put what was already arriving and being logged once as unhandled.
Drive, tune drive, mic gain, TUNE, volume, mute, squelch, NB/NR/ANF/APF,
AGC, passband, RIT and XIT, VFO lock, and an S-meter in real dBm.

Merged with two corrections to the audio page the console's own work
turned up: the radio was being offered as a recording microphone, and the
RX monitor was enabled for a source it cannot play.
2026-08-26 19:04:13 +02:00
rouggy afde919e5b fix(audio): the radio is offered only where it can actually be
Adding it to the device lists put it in all four dropdowns, and an
operator picked it as their RECORDING MIC — which would have recorded the
station they were listening to instead of their own voice, on every voice
message and every QSO recording. It is not a microphone, and it is not a
pair of speakers either: the audio going the other way is transmit audio.
So it is listed for 'From radio' and 'To radio', and taken out of the mic
and the listening dropdowns.

And the RX monitor is disabled when the radio IS the source, with a line
saying why: the TCI stream is pushed into the QSO recorder, and nothing
plays it to the speakers. The button was there, enabled, doing nothing
audible — which is worse than a button that says it cannot.
2026-08-26 19:04:02 +02:00
rouggy 98c49f6bbc feat(tci): a control console for the SunSDR
TCI already carries the frequency, the mode, the meters and now the audio.
It also carries everything else about the radio — and OpsLog was logging
most of it once as '(unhandled once)' and throwing it away. The console is
mostly a place to put what was already arriving.

That makes it the cheapest panel here, and it is worth saying why. A K3
console costs a command and a reply for every value it shows, which is why
it reads its settings in a rotation and its meters only while on screen.
TCI PUSHES: the radio announces its drive, its filters, its noise blanker
and the rest on connect, and again whenever any of them changes —
including when the operator changes them in ExpertSDR3's own window, which
this panel therefore follows without asking anything.

What it drives: drive and tune drive, mic gain, TUNE, volume, mute,
squelch and its threshold, NB, NR, ANF, APF, AGC speed, the passband, RIT
and XIT with their offsets, and the VFO lock. The S-meter is a real dBm
reading, so its S units are arithmetic rather than the calibration guess a
K3's meter needs.

Setters never update the cached state. The radio answers with the new
value, and taking its word is what keeps the panel honest when a setting
is refused, clamped, or changed at the radio a second later — the one
exception being a slider mid-drag, held for 900 ms so it is not dragged
back by its own echo.

Capped width and centred, like the other consoles. Also offered as a
docked pane — and the Elecraft console is offered there too now: App has
always had that pane, Settings simply never listed it.
2026-08-26 18:31:44 +02:00
rouggy 8b9c835ca1 fix(antenna): the COM port picks from the list again
Reported on an Ultrabeam over USB: the port could not be chosen from the
dropdown, and the panel would not scroll.

That field was a Combobox — a list you can also type into — chosen so the
port of an adapter currently UNPLUGGED could still be configured. It is
now the same Select every other serial device in OpsLog uses, the one that
demonstrably works. The case it was built for is kept differently: a
configured port that is no longer detected is added to the list, so it
stays selected and visible instead of vanishing when the adapter is out.

Also hardened the Test button's guard, which called .trim() straight on
the port and the host. A settings object without them — an older build, a
save that landed short — throws there DURING RENDER, and a panel that
throws while rendering is exactly a panel with a dead dropdown that will
not scroll. Whether or not that is what this operator hit, it is a way to
produce both symptoms at once and it costs nothing to remove.
2026-08-26 18:21:41 +02:00
rouggy 37b436f543 fix(maps): Carto now stamps its key-free tiles, so Light and Topo move to Esri
Reported with a screenshot: the map came up with API KEY REQUIRED written
twice across the middle of it, on the Light and Voyager views only. Those
are exactly the two Carto basemaps.

Nothing here could have caught it. The tiles still answer 200 with a real
image — the watermark is IN the image — so the map looks like it is
working and simply says otherwise in large grey letters.

Both views move to Esri, which is already behind Street and Satellite. That
is the point: a second key-free provider is a second chance to be cut off,
and this is now the third time a tile source has changed its terms under
us. Light is Esri's light canvas with its own label layer, and Voyager
becomes the topographic map, labelled Topo — the stored key stays
'voyager' so nobody who chose it is quietly moved somewhere else.

The canvas runs out of tiles at zoom 16 where the others go to 19, so
maxNativeZoom is set per basemap: Leaflet upscales the last real tile
instead of asking for a level that does not exist, which is the difference
between a slightly soft map and a blank grey square.
2026-08-26 18:16:45 +02:00
rouggy 656af9dae4 docs(changelog): say the Elecraft support has never met an amplifier
Written into the entry itself rather than added as a line of its own:
somebody reading about the feature should learn it there, not two entries
further down.
2026-08-26 18:12:08 +02:00
rouggy eff412a9a9 chore(changelog): the Elecraft amplifiers, in 0.26.18 2026-08-26 18:11:09 +02:00
rouggy ff7227af5b merge: Elecraft KPA500 and KPA1500 amplifiers
A fourth amplifier brand alongside the SPE, the Acom and the PowerGenius,
sharing the same multi-amplifier support: the linking, the fan-out and the
polling all work on it unchanged.

The protocol is the Elecraft one — a caret, letters, a semicolon — decoded
from the KPA1500 Programming Reference, with the document's own examples
kept as the test. ^WS gives forward power and SWR in one exchange, ^VI
gives volts in tenths and amps whole, and ^FL is HEX: read as decimal, the
'antenna not connected' fault matches nothing at all.

Three things this amplifier does that the others do not, each handled
where it shows: a KPA500 has no network side, the amplifier answers while
its main supplies are off, and going to OPERATE clears the current fault.

Nothing here has met real hardware yet.
2026-08-26 18:09:39 +02:00
rouggy 3013a2ba08 feat(kpa): the band-follow is asked for, not assumed
Telling somebody's amplifier where to be is a write to their station, and
it now has a switch — the SAME switch an Acom uses. 'Keep the amplifier on
the radio's band' is one idea to an operator; that it needs a second
serial port and a rig emulator on one amplifier and a single ^BN on
another is our business, not a reason for two checkboxes.

On by default for a KPA, because an amplifier left on the wrong band is
the worse outcome of the two, and the operator who has wired it straight
to the radio turns it off once. The hint says exactly that case, since it
is the only one where a second voice telling the amplifier where to be is
unwelcome.
2026-08-26 18:07:35 +02:00
rouggy de95a437bb fix(kpa): its own card, and no band-follow it does not need
Two things the wiring got wrong, both visible on screen.

A KPA fell through to the PowerGenius branch of the amplifier card and was
drawn as one — titled 'POWERGENIUSXL · ELECRAFT KPA1500', with a
PowerGenius's meters and none of its own. It has a card now: OPERATE, ON
and OFF, band, power, SWR, temperature, supply, and the fault across the
end. The OPERATE button carries a tooltip saying it also clears the fault,
because that is the button an operator already has under the cursor when
they need it.

And the band-follow option was offered on it. That option exists because
an Acom POLLS a transceiver and has no command to be given a band, so
following it needs a second serial port and a rig emulator answering those
polls. The KPA has ^BN — OpsLog simply tells it, on the link it is already
using, and only when the band CHANGES. The option is gone from the KPA and
the telling is automatic.

Also: Acom rather than ACOM everywhere it is read, which is how the
company writes it. Identifiers, package names and log lines are left
alone — renaming those is churn with no reader.
2026-08-26 18:00:46 +02:00
rouggy 85872f8379 feat(kpa): the Elecraft amplifiers in the Settings, the card and the widget
Wired into the multi-amplifier support that already carries the SPE, the
ACOM and the PowerGenius: a fourth brand rather than a fourth mechanism.
The linking, the fan-out and the poll all work on it unchanged.

Three things the KPA does differently, and each is handled where it shows
rather than explained in a hint:

  - A KPA500 has no network side at all. Choosing it puts the entry on
    serial, and a configuration still asking for TCP is refused with a
    line saying so instead of retrying an address that cannot answer.
  - The amplifier answers ^ON while its main supplies are OFF — a sleeping
    microcontroller stays awake for exactly that — so power-on stays
    available over the network, unlike the SPE and ACOM which need their
    serial control lines.
  - Going to OPERATE clears the current fault, everything except
    temperature. The widget says so under the fault, because the button
    that fixes it is the one already on screen.

Defaults that leave a working configuration when the model is changed:
38400 baud, TCP port 1500, and a full-scale power mark of 500 or 1500 W
by model — a KPA500 read against a 1500 W scale looks idle at full
output.
2026-08-26 17:50:30 +02:00
rouggy 55a643d9a4 feat(kpa): the Elecraft KPA500 / KPA1500 protocol, decoded and pinned
One package for both amplifiers: they share the Elecraft command set — a
caret, letters, a semicolon, case-insensitive in and upper case out — the
same family as the K3/K4 panel. What differs is the transport and which
commands exist, not the grammar.

Everything here comes from the KPA1500 Programming Reference, and the
document's own examples ARE the test:

  ^WS1204 014;  1204 W and SWR 1.4:1 — power and SWR in one exchange
  ^VI513 061;   51.3 V and 61 A — volts in tenths, amps whole
  ^FL91;        HEX, and 0x91 is 'antenna not connected?'

That last one is why the parsing is pinned rather than eyeballed: read as
decimal, 90 and 91 become 144 and 145 and match nothing, so an amplifier
shut down by high reflected power would report a fault OpsLog could not
name. SWR in tenths is confirmed by the reference too — 'expressed in
tenths, 123 is 12.3:1' — where it had only been inferred from Hamlib.

The client is question-and-answer under one lock, never two questions in
flight: the reference states there is no flow control and that commands
are paced by waiting for the reply. Fast cycle four times a second for
power, SWR and the fault; the rest once a second.

Faults are named in the operator's terms — 'the ATU found no match', not
'fault 92' — and an unknown code from a newer firmware still says
something rather than nothing.

Not wired to the app yet, and two commands are deliberately absent: ^TX
makes the amplifier transmit from software, and ^ON0 cuts the main
supplies with Wake-on-LAN as the way back. Neither belongs on a poll loop
or behind a button that can be pressed by accident.
2026-08-26 17:43:32 +02:00
rouggy 949b92d7e7 chore(changelog): the band-matrix columns belong to 0.26.18
v0.26.17 was tagged with its three entries before that work landed.
2026-08-26 12:29:08 +02:00
rouggy 37e9e288ba fix(awards): band columns follow the contacts, not the permission
The columns took the award's declared band list when it had one, so every
band the award PERMITS got a column whether or not anything had ever been
worked on it. DDFM permits 6m and 70cm; a station that has never worked a
French department on either was shown two empty columns, which reads as a
gap in the log rather than as a band nobody tried.

They now follow the bands this operator actually has contacts on for the
award. The declared list is the fallback for an award with nothing worked
yet — there, saying what the award is played on is the only honest answer
available — and the classic HF set is the fallback for an award that
declares nothing either.

Together with taking the order from the full band list, this is what puts
23cm on DDFM: the column appears because there are contacts on it.
2026-08-26 11:57:02 +02:00
rouggy 2b8ebd73cb fix(awards): the band matrix stops pretending 70cm is the top band
The columns were the intersection of the award's bands with a fixed list
that ended at 70cm, so a band the award genuinely covers could not appear
whatever it said. DDFM is worked well into the microwaves and had no 23cm
column, and nothing anywhere would have produced one.

The intersection is now taken against every band in frequency order, the
same list internal/award already sorts its own band counts by. The classic
HF-plus-2m-and-70cm set stays as the fallback for an award with no band
list and no contacts yet — the full list would be twenty-nine columns of
mostly nothing.
2026-08-26 11:51:15 +02:00
rouggy f9f8380ece chore: release v0.26.17 2026-08-26 11:44:40 +02:00
rouggy 10e1504531 fix(cat-share): answer get_freq with the listening VFO, not the transmit one
Reported from a station running an IC-7850 over USB: with split engaged,
turning VFO B moved VFO A slightly. OpsLog writes nothing to that radio on
its own — but it shares it, and what it was sharing was wrong.

Hamlib's 'f' means the VFO IN USE. RigState follows ADIF, where FreqHz is
where we TRANSMIT, and the two are the same number until split is
engaged — so the adapter handed FreqHz over unchanged and every client
asking for the dial was given VFO B. A client that reads the dial and
writes it back, which is what WSJT-X and its like do, then wrote VFO B's
frequency into VFO A. Hence a shift the size of the split offset, and
hence 'it did not do this before': it only happens with split on.

get_split_freq ('i') already answers the transmit frequency and is
untouched. The one-line rule is lifted into shareRXFreq with a test that
includes this case, the simplex case, and a backend that reports split
without ever filling in the receive frequency — which would otherwise
answer a client with 0 Hz.
2026-08-26 11:41:15 +02:00
rouggy 2e3464104d fix(awards): the RDA arbitration writes CNTY, and settled rows leave the list
Two faults, and the first was a design mistake of mine.

The choice was written only as the award override, to keep the imported
CNTY as a record of what HAMLOG said. But CNTY is what the comparison
READS, so the contact went on disagreeing for ever: settle a hundred
rows, run the comparison again, get the same hundred back. The reasoning
was about preserving evidence; the effect was a button with no visible
consequence anywhere, which is indistinguishable from one that does
nothing. This is the operator's own log, and correcting a field in it is
the point of the exercise. The district now lands in CNTY as well as in
the award reference.

And the settled rows stayed on screen, which made the same button look
broken a second time. They are dropped as they are applied — locally,
rather than by re-running the comparison, which reads the whole log and
would be seconds of silence on a remote database to be told what is
already known. The agree/disagree counters follow.
2026-08-26 11:08:15 +02:00
rouggy dc8f9c5099 fix(stats): confirmed outranks worked in the band/mode matrix
Reported by VK4DX with the case that names itself: YB confirmed on 20m
digital, painted blue, because one unconfirmed YB station had also been
worked on that slot.

The ladder ran call_c > call_w > dxcc_c > dxcc_w, so a callsign worked and
not confirmed beat an entity CONFIRMED on the same band and mode. The grid
answers 'what do I still need here', and a confirmed entity needs nothing
whoever was worked afterwards — so the order is now call_c > dxcc_c >
call_w > dxcc_w.

Two things made it easy to get wrong, and both are fixed rather than
merely corrected. The code was a run of assignments where the later test
silently overwrote the earlier, so 'call worked' erased 'entity
confirmed'; it now takes the maximum. And the rule lived inside a scan
loop where nothing could reach it, so it is lifted into bandStatusCode
with a table test — including this exact case, and one that fails if
anybody reorders the constants.
2026-08-26 10:53:36 +02:00
rouggy 08905a1680 chore(changelog): the RDA arbitration belongs to 0.26.17
v0.26.16 was tagged with its one TCI entry before this was written.
2026-08-26 10:48:54 +02:00
rouggy fd939797dd feat(awards): settle each RDA disagreement on its own row
The comparison could show two hundred contacts where the log and the
database name different districts, and leave the operator with nothing to
do about any of them but open each QSO and edit it by hand.

Now each row carries the two values as buttons: click the district you
keep, then apply. There are shortcuts for keeping one source everywhere,
and applying is a separate act — clicking through two hundred rows with
each one written as it is clicked would make a slip permanent before the
reading was finished.

The choice is written as the contact's AWARD REFERENCE, not over the
imported CNTY, and that distinction is the point. CNTY is what the
downloaded log said; overwriting it would destroy the evidence the
comparison runs on, and the next comparison would agree with itself and
prove nothing. The override is the operator's decision, it is what the
award engine counts, and it beats both sources. So the log keeps saying
what it said, the database keeps saying what it says, and the contact
counts for the district that was chosen.

The buttons show the districts themselves rather than a tick box: someone
arbitrating between RO-19 and KO-05 should be picking a value they can
read, not remembering which source a checked box stood for.
2026-08-26 10:22:23 +02:00
97 changed files with 10413 additions and 1159 deletions
+398 -61
View File
@@ -1,77 +1,414 @@
# Transceiver Control Interface # OpsLog
## Introduction <a href="https://discord.gg/tmVPdQ5A8" target="_blank">
<img src="https://img.shields.io/badge/Discord-Join%20the%20server-5865F2?logo=discord&logoColor=white" alt="Join our Discord" />
</a>
TCI (Transceiver Control Interface) is a network interface for control, data transfer and A modern, fast ham-radio logger for Windows — single-strip entry, real-time CAT
synchronization between transceiver/receiver, contest loggers, digital mode software, skimmers for **OmniRig**, native **FlexRadio/SmartSDR**, native **Icom CI-V** (USB **and**
and other software, as well as external power amplifiers, bandpass filter units, antenna switches, remote-over-internet, replacing RS-BA1) and **TCI** (SunSDR / Expert Electronics),
radio controllers and other devices. DX cluster with spot alerts, awards tracking, maps, contest logging, QSL
management and a QSL-card designer. Built with **Wails v2** (Go backend +
React/TypeScript frontend), **pure Go** (no CGO): SQLite for configuration,
optional **shared MySQL** for the logbook so several operators can run one log.
Fully themeable and bilingual (English / French).
TCI was created as a modern alternative to the outdated COM port and audio cable Developed by **F4BPO**.
interfaces, it uses a full duplex web socket protocol that runs on top of a TCP connection and
serves for server-client communications, providing cross-platform connectivity. Transceiver works
as a server, all other software and devices as clients. The server and clients can be inside the
same computer (program-server, hardware log, etc.-clients) and/or in separate physical devices
connected through the local network (classical transceiver, power amplifier, antenna switch, FFT
unit, etc.).
The TCI interface contains basic transceiver control commands (analog of CAT system), ---
receives CW macros from clients and broadcasts them, outputs transceiver IQ stream to clients,
receives spots from skimmers and Internet clusters, receives/outputs audio signal to work in
digital modes.
The TCI uses an extensible architecture and can be supplemented with new functions and ## Building / developing
commands, while keeping the old ones operational. Thus, the TCI interface can be extended and
supplemented to meet the specific needs of any software manufacturer and/or device
manufacturer (receivers, transceivers, power amplifiers, switches, etc.). The presence of a device
identifier allows the manufacturers of transceivers and receivers to switch to the TCI interface
while maintaining the device model designation. The extensibility of the TCI interface allows you
to create an individual set of commands and functions for each device model, while maintaining
the basic command set inherent to all transceivers.
Our company advocates universal unification of data exchange between devices and - **Dev:** `wails dev` (Vite hot-reload; Go methods reachable at http://localhost:34115).
software by creating the TCI interface for this purpose. Modern transceivers and software must - **Build:** `wails build` (use the project's wails v2.11 — `~/go/bin/wails.exe`).
communicate using one protocol - the TCI protocol. - **Regenerate Go↔TS bindings** after changing exported `App` methods:
`wails generate module`.
- **Release:** `.vscode/release.ps1` (Ctrl+Shift+P → *Tasks: Run Task*
*Release OpsLog*) — bumps the version, pushes source to Gitea, builds the exe
and publishes it to Gitea + GitHub releases.
## Interface description ---
Any command represents an ASCII string that contains a command name and a list of ## Logging
arguments corresponding to this command. There are reserved characters that cannot be
included in the command name and command arguments.
List of reserved characters: «:», «,», «;». - **Single-strip entry:** callsign, RST tx/rx, name/QTH/grid, band/mode,
TX/RX frequency (split), start/end time, comment/note. The contacted entity's
**flag** is shown large next to the RST fields.
- **Callsign lookup** (QRZ.com / HamQTH) with photo, auto-fill of name/QTH/grid
and the QRZ.com tab.
- **Offline DXCC** resolution from `cty.dat` (country, CQ/ITU zones, continent),
with `/MM` `/AM` `/B` (beacon) and call-area (`/8`, `/W6`) handling, plus
ClubLog DXpedition date overrides.
- **Editable lists** for bands, modes (with their default RST) and **satellites**
— the satellite name on the entry form is offered as a dropdown, because
SAT_NAME is compared character for character by the awards and by LoTW.
- **Recent QSOs**, **Worked-before** matrix (per band/mode slot), bulk re-resolve
from cty/QRZ/ClubLog, bulk send to QSL services. A live **selection count**, a
**Select all / Unselect all** toggle, and a row limit that keeps the full log
fast **but is lifted while a filter is active** (every match is shown, not just
the first page).
- **Advanced QSO filter builder** (field / operator / value, AND / OR, saved
presets) with filtered- and selected-row **ADIF export**.
- **Find duplicates** (Tools) — groups QSOs by same call + band + mode (optionally
same day / minute) and lets you pick which to delete.
- **ADIF 3.1.7 compliant** import/export: a full field dictionary, 30 promoted
columns, a generic "extra fields" editor and standard/all export modes.
- **Profiles:** every setting is per-profile; each profile can point its logbook
at the local SQLite file or a **shared MySQL** database (multi-operator).
Command structure: ## Maps & antenna
1. Name of the command;
2. Separating character between command name and arguments «:»;
3. Separating character between arguments «,»;
4. End of the command character «;».
If a command has no arguments, an end of command symbol is placed after the command - **Main view = two configurable panes** (per profile, Settings → General →
name. If the command is invalid, it is ignored. The case of letters does not matter. *Main view*): great-circle map, locator (street) map, the cluster grid, the
worked-before grid, recent QSOs, the **FT decodes**, or any of the radio
consoles — **FlexRadio**, **Icom**, **Yaesu**, **Elecraft K3/K4**, **SunSDR
(TCI)** — and the **Net control** panel. Up to four panes, in columns or a
quadrant.
- **Great-circle map** with short/long-path distance & azimuth, selectable
basemaps (Light / Topo / Street / Satellite — Esri tiles, key-free and
labelled) and the **antenna beam lobe(s)** drawn from the rotor azimuth.
- **Rotor compass** (azimuthal-equidistant, click-to-turn) driven by
**PstRotator** (UDP), a **4O3A Rotator Genius** (native TCP) or a **microHAM
ARCO** controlled natively — no PstRotator needed — over the **LAN** or **USB**
using its Yaesu GS-232A protocol.
- **Ultrabeam** support (Normal / 180° reverse / Bidirectional): the radiating
direction is shown in green and the **mechanical boom** in grey, on both the
compass and the map, so you never lose track of where the antenna points.
The ExpertSDR3 program acts as a server, which can have several client connections at ## DX Cluster
the same time, they will be synchronized with each other by the server. When connecting to the
ExpertSDR3, the client receives the current status of the ExpertSDR3, first sending initialization
commands, then parameters to set the status, such as frequency, modulation, etc.
When a parameter change occurs in the ExpertSDR3 (server) program, the server notifies - Multiple cluster servers with auto-reconnect, a master for commands.
all connected clients, i.e., clients do not need to poll the server constantly, any change of state - **Filter sidebar** (callsign search, hide-worked, group duplicates, band /
will be sent in time to all clients. If the client sends a new state, the server will set it to itself, as mode / status / source) shared by the Cluster tab and the Main-view cluster
well as send it to all clients, that is, the server acts as a synchronizer. All clients connected to the pane, with a show/hide toggle.
server will be automatically synchronized. This way of work allows to minimize network load, - Per-spot **status** (new / new-band / new-slot / worked), click-to-tune the
reducing traffic. rig, and a multi-band **Band Map** (panadapter-style strips). Optionally, all
**digital modes count as one** (DXCC-style) for the new/new-slot colouring and
the worked-before matrix badges (Settings → General).
- **POTA** spots are tagged with their park reference (via `api.pota.app`).
- **Spot alerts:** rules on call / country / band / mode /
spotter, with sound, visual and e-mail notification (Tools → *Alert
management*).
The TCI protocol implements the transmission of receiver IQ stream to clients, which is ## CAT control
necessary for the work of special skimmer software, they automatically find the station and
decode it throughout the band, and it also allows you to record radio signals in the file.
TCI is also used to transmit audio signals of the receiver to clients and to receive audio Six native backends (Settings → CAT), each with auto-reconnect and a fast,
signals from clients, i.e., the client can transmit audio signals to ExpertSDR3 for radio non-blocking connect so a powered-off radio never freezes the app. The settings
transmission. The audio stream exchange is designed to work with digital modes, where encoding ask two questions rather than one — **which radio**, then **how it is
and decoding is performed by third-party software, as well as in voice modes, where audio macros connected** — and only offer the links that radio actually has:
can be broadcasted, which is very much in demand in contest loggers.
When working in contests, it is important to record all on the air operation, for this purpose - **OmniRig** (Rig 1/2, hot-swap) — works with any OmniRig-supported rig.
the audio stream from the line-output is sent to all clients. The resulting audio stream can be - **FlexRadio (SmartSDR)** over the radio's TCP API — real-time slice freq /
recorded to a file or played back with a PC sound card. mode / split, UDP discovery, and **panadapter spots** (cluster spots pushed to
the Flex display; a click fills the call and **tunes the rig to the right
frequency AND mode**).
- **Icom CI-V** — native, over the radio's **USB** port *or* over the internet
via the radio's **built-in LAN server** (see *Remote Icom* below). No RS-BA1 or
Remote Utility needed.
- **Kenwood / Elecraft** — native ASCII CAT over USB or an RS232-to-Ethernet
bridge, for the K3 / K4 and the Kenwood dialect they share.
- **Yaesu** — native ASCII CAT (FA/FB/MD/VS…), which replaces OmniRig for an
FTDX and gives the Yaesu console below.
- **TCI** (WebSocket) — SunSDR / ExpertSDR3 and any TCI-compatible server:
freq / mode / PTT / split, panorama spots, **audio in both directions** and a
full console. See *TCI audio* below.
**CAT sharing:** OpsLog can hand the radio on to other programs while it holds
the port — a **Hamlib NET rigctl** server (WSJT-X, JTDX, MSHV, fldigi…) or a
**TCI** server. One or the other, on a port you choose.
Mode is taken from the radio; the digital sub-mode (FT4 vs FT8) is inferred from
the frequency. **Per-band Flex RX/TX antennas** can be configured and are applied
automatically on band change.
### FlexRadio control tab (SmartSDR-style)
Shown only when the CAT backend is a FlexRadio:
- **Transmit:** RF power, tune power, TUNE, MOX, speech processor (NOR/DX/DX+),
VOX (+ level + delay), monitor (+ level), mic gain.
- **Receive (active slice):** RX/TX **antenna** selectors and a **DAX** toggle
(TX audio through DAX, for WSJT-X & co), AGC mode/threshold, audio level,
NB / WNB / NR / ANF, and — on **SmartSDR v4** radios (8000 / Aurora series) —
the extra DSP tools **NRL, NRS, NRF** (with level) plus **RNN** (AI noise
reduction) and **ANFT** (FFT auto-notch), shown automatically when the radio
supports them. **RIT / XIT** with wheel / ± tuning.
- **Antenna tuner (ATU):** tune / bypass / memories.
- **Amplifier:** the amp card follows whichever amplifier is configured, with a
dropdown to pick it when **several amplifiers** are set up (e.g. two SPEs run
in parallel). See *Amplifiers & switches* below.
- **Live meters** over the UDP VITA-49 stream: S-meter (S-units), forward power
(W), SWR, ALC, PA temperature, voltage, plus the amplifier's meters.
### Elecraft K3 / K4 control tab
Shown for the Elecraft and Kenwood backends: power, AF/RF gain, mic gain,
squelch, preamp/attenuator, NB/NR/AGC, filter widths (200 Hz to 4.0 kHz, the
K3 maximum and the one FT8 wants), antenna selection, MOX and the ATU
(tap to tune, hold for in/out), RIT/XIT with ±10 / ±100 steps, key speed, and
live S / power / SWR meters. The SWR is read from the radio's own `SW;`.
### Yaesu control tab
Shown for the Yaesu backend: power, mic gain, AGC, NB/NR, preamp/attenuator,
filter width, RIT/XIT and the meters — the same shape as the others, driven by
the FTDX's own CAT set.
### SunSDR console (TCI)
Shown for the TCI backend. Drive and tune drive, mic gain, TUNE, power and SWR
while transmitting, volume, mute, squelch and its threshold, NB / NR / ANF,
APF in CW, AGC speed, filter widths **offered per mode**, RIT and XIT, and the
VFO lock. Levels can be dragged, scrolled, stepped or typed. The S-meter reads
real dBm, so its S-units are arithmetic rather than a calibration guess.
It costs nothing to keep open: TCI **pushes** every setting as it changes —
including changes made in the radio's own window, which the console follows
without asking anything.
### Icom control tab
Shown when the CAT backend is Icom (USB or network). A full RS-BA1-style console:
- **Twin VFO readout** (MAIN / SUB) with the big tabular frequency, mode badge,
band and RIT/ΔTX offset, and a **mode-button row** (SSB / CW / RTTY / PSK /
AM / FM).
- **Spectrum scope + waterfall** (panadapter): ON/OFF, CTR/FIX, double-click to
tune, and **◀ ⊙ ▶** buttons to centre the scope on the current frequency
(±50 kHz) and pan left/right.
- **Live meters** always visible: S-meter (click → fill RST), power in watts, SWR.
- **Receive DSP:** AF / RF gain, squelch, AGC, preamp, attenuator, filter
(FIL1/2/3), NB, NR, ANF and — **on CW only** — the **APF** (audio peak filter).
- **Passband / notch:** Twin PBT (inner / outer), manual notch + position.
- **Transmit:** RF power, MOX, TUNE, **split with an automatic offset**
(+5 kHz on SSB, +1 kHz on CW), and monitor. On **voice modes only**: mic gain,
speech compressor, VOX (+ gain + anti-VOX). Controls that don't apply to the
current mode are hidden automatically.
- **Bands & antenna:** one-touch band buttons and ANT1/ANT2 selection.
- **Clarifiers:** RIT and ΔTX with wheel / ± tuning (Ctrl+←/→ nudges RIT).
- **Power ON / OFF** buttons (manual by design — the app never wakes the rig on
connect).
- **CW keying** can run through the radio's own keyer (see *Keyers* below).
### Remote Icom (over the internet, no RS-BA1)
OpsLog speaks the IC-7610's built-in network protocol directly — it **replaces
both the Icom Remote Utility and RS-BA1**. Enter the radio's IP, the Network
User1 name/password and the CI-V address, and the whole Icom console works over
the LAN/internet: login + token (auto-renewed), CI-V tunnel, receive-side
retransmit for a rock-solid link even with the panadapter streaming, and manual
power ON/OFF. (Audio is out of scope — use the radio in USB + a voice link such
as Mumble.)
## Keyers & audio
- **CW keyer** with macros and F-key macros. The keyer engine is selectable:
**WinKeyer** (K1EL WK1/2/3 over a COM port), **FlexRadio CWX** (the radio's
built-in keyer over the SmartSDR API — type-ahead and backspace, no WinKeyer or
SmartCAT needed), **Icom** (the radio's own keyer over CI-V — no extra hardware,
works over the remote link too) or **TCI**.
- **Digital Voice Keyer** (DVK): record F1F6 voice messages and transmit them.
- **QSO audio recording:** continuous rolling capture; on *Log QSO* the contact
is saved to a per-QSO WAV (`CALL_YYYYMMDD_HHMMSS.wav`); mixes RX + mic.
### TCI audio — no virtual cable
A SunSDR carries its audio on the same WebSocket as its commands, so OpsLog can
take it directly. Pick **Radio (TCI network audio)** as the *From radio* or
*To radio* device and the QSO recorder and the voice keyer work with no virtual
audio cable, no second sound card and nothing to set in the Windows mixer.
Transmit needs no setting up in ExpertSDR3 either: the audio source is named on
each key-down, so it works in SSB as well as the digital modes, and the
microphone stays the source for every transmission that is not a voice message.
## Amplifiers & switches
- **Amplifiers** — configure **one or several** amps (Settings → Amplifier is a
list; e.g. two SPEs run in parallel for more power). Each amp's control card
appears on the FlexRadio tab and in **Station Control**, with a dropdown to
choose which one it shows; the bottom status bar carries **one clickable chip
per amp** (green = OPERATE, orange = STANDBY, red = offline). Supported:
- **PowerGenius XL** (4O3A) over direct TCP — operate/standby, fan-mode
selector and fault display.
- **SPE Expert** (1.3K-FA / 1.5K-FA / 2K-FA) over **USB** (virtual COM) or the
**network** (RS232-to-Ethernet bridge) — operate/standby, ON/OFF,
Low / Mid / High output level, an output-power bar and live status (band,
SWR, PA current, temperature, warnings/alarms).
- **Acom** (500S / 600S / 700S / 1200S / 2020S) over **USB** or the **network**
(RS232-to-Ethernet bridge) — operate/standby/off and live telemetry (forward
& reflected power, SWR, PA temperature, band, fan, faults). Power-ON works
over a serial cable that wires the DTR/RTS lines.
- **Elecraft KPA500 / KPA1500** over **USB** (serial) or — on the KPA1500 —
over the **network**. Operate/standby, on/off, forward power, SWR,
temperature, supply voltage and current, the band, and faults named in plain
words rather than as a code. The amplifier follows the radio's band by
itself, on the link already open — it has a band command of its own, so no
second serial port is involved.
An amplifier that takes its band from a transceiver instead (Acom, SPE) can be
followed a second way: OpsLog answers its frequency polls as a Kenwood rig on
a **second COM port**, independent of the control link.
- **Antenna Genius** (4O3A) antenna switch over TCP/GSCP — a docked A/B
antenna-switch widget, and an option to write the **selected antenna into
MY_ANTENNA** under the name the switch itself carries.
- **Tuner Genius XL** (4O3A) over TCP — SWR and power, TUNE / BYPASS / OPERATE.
- **Station Control** panel (dockable, drag-to-reorder widgets): the **rotator**,
**Ultrabeam** element control and **relay boards** — WebSwitch 1216H, KMTronic,
**Denkovi** USB (FT245 D2XX bit-bang, 4 or 8 relays) and generic USB-serial
(CH340 / LCUS, A0 protocol) — for station power, antennas and accessories.
- **Relay auto-control** (Settings): switch Station-Control relays automatically
from the rig frequency / band (like PstRotator) — per relay, a frequency window
or a set of bands.
## QSL & awards
- **Awards engine:** built-in + custom award definitions (shared **globally**
across profiles) — DXCC, WAS / WAZ / WAC, WPX, IOTA / POTA / SOTA / WWFF,
**DDFM**, worked/confirmed/validated by band & mode, OR rules and manual
reference assignment, live reference detection on call entry, **reference-list
import** for totals/names, and a **Rescan** that re-pulls the logbook (picks up
fresh LoTW/QRZ confirmations).
- **Award statistics** by band and by mode class, with the **DXCC Challenge**
worked out where it can be compared to LoTW's own figure — it counts confirmed
band-slots on ten bands, and 60 m is not one of them, which is the whole of the
usual discrepancy. The band columns follow the bands you actually have contacts
on, up to and beyond 23 cm.
- **Russian districts (RDA):** an offline district database that knows where a
callsign was **on the day of the contact**, a bulk fill for existing QSOs, and
a comparison against the district an imported log carries — each disagreement
settled on its own row, with the choice written into the contact.
- **QSL services:** ClubLog (batched ADIF upload), LoTW, QRZ.com, eQSL,
**Cloudlog / Wavelog** and **HAMLOG.online** — upload and **confirmation
download** (which auto-refreshes the award stats).
- **QSL Card Designer** (see below).
- **E-mail eQSL:** right-click a QSO → *Send eQSL by e-mail* via the configured
SMTP account. (Outlook/Hotmail disable basic-auth SMTP — use Gmail with an app
password, or a Microsoft app password.)
## Contest logging
- **Contest tab:** pick a contest (built-in ADIF `CONTEST_ID` list) and an
exchange (running serial or a fixed exchange). OpsLog auto-fills `CONTEST_ID`
and the sent/received serials (`STX` / `SRX`), enforces a window start/end,
flags dupes and keeps a live scoreboard.
## Statistics
- **Logbook statistics dashboard:** headline tiles (QSOs, unique callsigns, DXCC
entities, continents, % confirmed) plus charts — QSOs **by mode**, a per-band
**CW / phone / data** split, **activity over time** (rolling day / 7-day /
30-day / 12-month views), by operator and by continent. Date-range, per-operator
and per-contest filters, and a **Table** view that mirrors every chart.
## Multi-operator live status (special events)
For a multi-op special-event call on a shared MySQL logbook (e.g. **TM74TFR**),
publishing is **automatic** — no setting to turn on. Each OpsLog instance
heartbeats its current activity (operator call, band, frequency, mode) into a
`live_status` table every ~15 s, and drops back to *off air* automatically 5 min
after the last logged QSO. A small PHP renderer
([`docs/livestatus/tm74-status.php`](docs/livestatus/tm74-status.php)) on your
own web server reads that table and produces a live page/image you can embed on
the station's **QRZ.com** bio (`<img src="…/tm74-status.php?img=1">`). OpsLog
only writes to the DB — it is not a web server.
## Net control
- **Directed-net logging** (Tools → Net): a global roster (`nets.json`) plus an
in-memory active session — check stations in, then log them individually or the
whole net at once (**Log everyone**) using the CAT frequency. **Drag & drop**
between the two lists (roster → on-air starts a QSO, on-air → roster logs it),
and after each log the next on-air station is selected automatically so you can
chain contacts.
## Appearance & language
- **Themes:** four complete themes (Warm light, Warm dark, Graphite dark, High
contrast) plus **Auto** (follows the OS light/dark preference), selectable in
Settings → General. Every panel and every AG-Grid table follows the theme.
- **Bilingual:** full **English / French** UI, with a first-run flag chooser and
a switcher in Settings → General.
## Security
- **Secret vault:** opt-in passphrase encryption of the stored passwords
(AES-GCM + PBKDF2). Encrypted values are portable; a single unlock prompt at
launch decrypts them for the session.
## Integrations (outbound)
- **UDP emitters:** push the current frequency to **PstRotator**, radio info in
**N1MM `RadioInfo`** format, or an **ADIF record on each logged QSO** — so
external tools (rotator control, digital apps, other loggers) stay in sync.
- **CAT sharing:** a **Hamlib NET rigctl** or **TCI** server, so WSJT-X, JTDX,
MSHV, fldigi and the rest still reach the radio while OpsLog holds the port.
- **WSJT-X / JTDX / MSHV** decodes over UDP: the heard stations feed the band
map, the alerts and — on a FlexRadio — the panadapter.
## Other
- **Autostart:** launch external programs (WSJT-X, JTAlert, rotator control…) at
OpsLog startup, skipping any already running.
- **Backup:** optional database + ADIF backup at shutdown.
- **Update check** at startup and every 5 minutes (and on opening Help → About),
with a toast (toggleable), plus a **What's new** dialog that shows the changelog
(English / French) on the first launch after an update — reopenable any time
from the Help menu.
- **Anonymous usage telemetry** (a once-a-day heartbeat: random install ID +
version + OS — no callsign or QSO data; opt-out in Preferences).
---
## QSL Card Designer
Tools → *QSL Card Designer…* turns a few photos into a polished eQSL card:
1. Pick 16 photos (jpeg/png). OpsLog analyzes them offline (detail/luminance
grid) and proposes **3 designs** — callsign in the calmest zone of the best
photo, operator name, CQ/ITU zones + locator line, country flag, the other
photos as bordered inserts, and a per-QSO confirmation box.
2. Pick a proposal and fine-tune it: click an element to select, drag to move,
change font / style preset (gel gold, gel silver, classic white outline,
script, flat) and per-preset knobs in the right panel.
3. Save the template (photos are copied into `data/qsl/templates/<id>/`, so the
originals can move). One template can be the default per profile.
Sending: right-click a QSO → *Send eQSL by e-mail*. The card is rendered with
that QSO's data, rasterized to a ≤ 800 KB JPEG, archived in `data/qsl/outbox/`
and sent through the configured SMTP account to the address found by the
QRZ/HamQTH lookup. On success the QSO is stamped `EQSL_SENT=Y` (ADIF). The
e-mail subject/body templates live in the designer
(`{CALL} {DATE} {BAND} {MODE} {MYCALL}` variables).
Fonts: Archivo Black, Lilita One, Baloo 2, Oswald, Great Vibes, Allura (all
OFL, embedded — licenses in `internal/qslcard/assets/fonts/`); Cooper Black is
offered when MS Office installed it. Flags: flag-icons (MIT), embedded for the
commonly-worked DXCC entities.
---
## Importing a log
- **ADIF import** with duplicate handling (skip / update / import anyway) and an
optional field mapping for exports that use their own names.
- Optionally recompute country / continent / DXCC / zones from **cty.dat** and
the **ClubLog date-ranged exceptions** — which know that a callsign belonged to
a different entity on an older date.
- **Deleted DXCC entities are left alone.** cty.dat only knows where a callsign
is *today*: R1MVI resolves to European Russia now, but a 2004 contact was Malyj
Vysotskij — an entity the ARRL deleted in 2012 and which can never be worked
again. Where a record names one of the sixty-odd deleted entities, its own
number is kept.
## Data & storage
- **Config** (settings, profiles, rigs/antennas, cluster nodes, lookup cache,
award lists, QSL templates) always lives in the local SQLite file under
`data/` — instant even when the logbook is on a far-away MySQL.
- **Logbook** (QSOs) lives where the active profile points it: the local SQLite
file or a per-profile shared **MySQL** database.
---
*A French version of this document is available in [README.fr.md](README.fr.md).*
+715 -106
View File
File diff suppressed because it is too large Load Diff
+49
View File
@@ -0,0 +1,49 @@
package main
// The voice keyer, through an Icom's network link — the Icom face of what
// app_tci_dvk.go does for a SunSDR: selecting the radio as the "To radio"
// output hands messages to the 50003 audio session instead of a sound card.
// The same PTT before and after, the same gain, the same files.
import (
"fmt"
"hamlog/internal/applog"
"hamlog/internal/audio"
"hamlog/internal/cat"
)
// icomTXPlayer hands one message to the radio. Fetched on the CAT goroutine,
// played off it — a ten-second message must not freeze frequency, mode and
// PTT handling for ten seconds (see tciTXPlayer, which set the pattern).
func (a *App) icomTXPlayer(pcm []byte, rate, ch, bits int, stop <-chan struct{}) error {
if a.cat == nil {
return fmt.Errorf("CAT not initialized")
}
type txPlayer interface {
PlayTXAudio(pcm []byte, rate, ch, bits int, stop <-chan struct{}) error
}
var player txPlayer
err := a.cat.IcomDo(func(ic cat.IcomController) error {
p, ok := ic.(txPlayer)
if !ok {
return fmt.Errorf("this radio cannot take transmit audio over its CAT link")
}
player = p
return nil
})
if err != nil {
return err
}
return player.PlayTXAudio(pcm, rate, ch, bits, stop)
}
// installIcomTXPlayer offers the network Icom as an audio output, or withdraws
// it. Withdrawing matters as much as offering — see installTCITXPlayer.
func (a *App) installIcomTXPlayer(on bool) {
if !on {
return // the reloadCAT preamble already cleared the network player
}
audio.SetNetworkPlayer(a.icomTXPlayer)
applog.Printf("icom net: the radio is available as an audio output — the voice keyer can play to it without a cable")
}
+11
View File
@@ -24,6 +24,17 @@ func (a *App) GetKenwoodState() cat.KenwoodTXState {
return st return st
} }
// SetKenwoodPanelMode sets the operating mode from the panel's mode row —
// CW / USB / LSB / DATA (soundcard, DT0) / RTTY (FSK D, DT2).
func (a *App) SetKenwoodPanelMode(mode string) error {
return a.kenwoodPanelDo(func(k cat.KenwoodPanelController) error { return k.SetKenwoodPanelMode(mode) })
}
// SetKenwoodRITOffset sets the RIT/XIT offset to an absolute value in Hz.
func (a *App) SetKenwoodRITOffset(hz int) error {
return a.kenwoodPanelDo(func(k cat.KenwoodPanelController) error { return k.SetKenwoodRITOffset(hz) })
}
func (a *App) SetKenwoodPower(w int) error { func (a *App) SetKenwoodPower(w int) error {
return a.kenwoodPanelDo(func(k cat.KenwoodPanelController) error { return k.SetKenwoodPower(w) }) return a.kenwoodPanelDo(func(k cat.KenwoodPanelController) error { return k.SetKenwoodPower(w) })
} }
+246
View File
@@ -0,0 +1,246 @@
package main
// Several radios, and the one that is on the air.
//
// Until now the answer to "I have two rigs" was "make two profiles", which is a
// heavy instrument for a light question: a profile carries the whole station —
// logbook, callsign, awards, cluster, macros — and switching one to change
// which radio is connected takes all of that with it, including a logbook
// change if the profiles point at different databases.
//
// So radios are a LIST, the way amplifiers already are, and switching is one
// click on the CAT chip in the status bar. Nothing else about the station
// moves.
//
// The storage deliberately keeps the ACTIVE radio in the settings keys the rest
// of OpsLog already reads (cat.backend, cat.icom_port, …). Switching writes the
// chosen entry into those keys and reloads the link, so every consumer — the
// consoles, the CAT sharing, the band-follow, the panels — sees exactly what it
// saw before and needed no change at all. The list is a second store beside it,
// not a replacement for it.
import (
"encoding/json"
"fmt"
"strings"
"time"
"hamlog/internal/applog"
)
const (
// keyRadiosList holds the saved radios as JSON.
keyRadiosList = "cat.radios.json"
// keyRadioActive is the id of the one currently connected.
keyRadioActive = "cat.radios.active"
)
// RadioConfig is one saved radio: a name and the CAT settings that reach it.
type RadioConfig struct {
ID string `json:"id"`
Name string `json:"name"`
// Settings is the whole CAT configuration for this radio — the same shape
// the CAT panel has always edited, so a saved radio is exactly "what the
// settings said the day it was saved".
Settings CATSettings `json:"settings"`
// MyRig is what goes into MY_RIG on a QSO made with this radio.
//
// It belongs here rather than in Operating conditions once there is more
// than one rig: the operating conditions describe a PLAN — "on 20 m I use
// the beam and the 7300" — while this is the fact of which radio is keying.
// Left empty, nothing changes: the old chain (band default, then the
// profile's rig) answers exactly as it did.
MyRig string `json:"my_rig"`
}
// radioLabel is what the status bar shows when the operator never named one.
func radioLabel(c RadioConfig, i int) string {
if n := strings.TrimSpace(c.Name); n != "" {
return n
}
if b := strings.TrimSpace(c.Settings.Backend); b != "" {
return strings.ToUpper(b)
}
return fmt.Sprintf("Radio %d", i+1)
}
// GetRadios returns the saved radios.
//
// When nothing was ever saved, the CURRENT settings are presented as the single
// entry — so an operator who has been running one rig for a year opens the list
// and finds it there, rather than an empty box suggesting their configuration
// has been lost. It is persisted on the next save, not here: reading a list
// should not write one.
func (a *App) GetRadios() ([]RadioConfig, error) {
if a.settings == nil {
return nil, fmt.Errorf("db not initialized")
}
raw := a.settingOr(keyRadiosList, "")
if strings.TrimSpace(raw) != "" {
var list []RadioConfig
if err := json.Unmarshal([]byte(raw), &list); err == nil && len(list) > 0 {
return list, nil
}
}
cur, err := a.GetCATSettings()
if err != nil {
return nil, err
}
return []RadioConfig{{ID: "radio-1", Name: "", Settings: cur}}, nil
}
// SaveRadios stores the list, giving an id to anything new.
func (a *App) SaveRadios(list []RadioConfig) error {
if a.settings == nil {
return fmt.Errorf("db not initialized")
}
for i := range list {
if strings.TrimSpace(list[i].ID) == "" {
list[i].ID = fmt.Sprintf("radio-%d-%d", time.Now().Unix(), i)
}
}
b, err := json.Marshal(list)
if err != nil {
return err
}
return a.settings.Set(a.ctx, keyRadiosList, string(b))
}
// ActiveRadioID is the id of the radio currently on the air, or the first one
// when nothing was ever chosen.
func (a *App) ActiveRadioID() string {
id := strings.TrimSpace(a.settingOr(keyRadioActive, ""))
list, err := a.GetRadios()
if err != nil || len(list) == 0 {
return id
}
for _, r := range list {
if r.ID == id {
return id
}
}
// The stored id names a radio that has since been deleted. The first one is
// a better answer than an empty selection: the CAT link is up, and it is up
// on SOMETHING.
return list[0].ID
}
// RadioListEntry is what the status-bar menu needs: enough to draw a row.
//
// Name is what the OPERATOR typed, empty when they typed nothing; Label is what
// to draw when there is no better idea. The two are separate because the caller
// has a better idea than we do: the status bar knows what the radio calls
// itself over CAT, and "FTDX10" beats "Radio 2" — but only where the operator
// has not given it a name of their own, which beats both.
type RadioListEntry struct {
ID string `json:"id"`
Name string `json:"name"`
Label string `json:"label"`
Backend string `json:"backend"`
Active bool `json:"active"`
}
// ListRadios is the status bar's view of the list.
func (a *App) ListRadios() []RadioListEntry {
list, err := a.GetRadios()
if err != nil {
return nil
}
active := a.ActiveRadioID()
out := make([]RadioListEntry, 0, len(list))
for i, r := range list {
out = append(out, RadioListEntry{
ID: r.ID, Name: strings.TrimSpace(r.Name), Label: radioLabel(r, i),
Backend: r.Settings.Backend, Active: r.ID == active,
})
}
return out
}
// SetActiveRadio connects the given radio and leaves the rest of the station
// alone.
//
// The chosen entry's settings become THE CAT settings — SaveCATSettings writes
// them and restarts the link — so switching rigs is the same operation as
// editing the CAT panel and pressing Save, which is a path that already works
// everywhere it needs to.
func (a *App) SetActiveRadio(id string) error {
list, err := a.GetRadios()
if err != nil {
return err
}
id = strings.TrimSpace(id)
for i, r := range list {
if r.ID != id {
continue
}
// Persisted BEFORE the link is rebuilt: reloadCAT can take a moment on a
// radio that is switched off, and an operator who closes OpsLog during
// that moment should still come back to the rig they chose.
a.setSetting(keyRadioActive, id)
// The list is written back as well when it was only ever implicit, so
// the first switch is also what makes the list real.
if strings.TrimSpace(a.settingOr(keyRadiosList, "")) == "" {
_ = a.SaveRadios(list)
}
applog.Printf("cat: switching to %q (%s)", radioLabel(r, i), r.Settings.Backend)
return a.SaveCATSettings(r.Settings)
}
return fmt.Errorf("no radio with id %q", id)
}
// syncActiveRadio writes the settings just saved into the active entry of the
// list, so the list and the live configuration never disagree.
//
// Only when a list actually exists: an operator with one radio who has never
// opened the list has nothing to keep in step, and writing one here would
// create a list as a side effect of saving the CAT panel.
func (a *App) syncActiveRadio(s CATSettings) {
if a.settings == nil || strings.TrimSpace(a.settingOr(keyRadiosList, "")) == "" {
return
}
list, err := a.GetRadios()
if err != nil {
return
}
id := a.ActiveRadioID()
for i := range list {
if list[i].ID == id {
list[i].Settings = s
_ = a.SaveRadios(list)
return
}
}
}
// activeRadioMyRig is the MY_RIG of the radio currently connected, or "".
//
// Consulted BEFORE the per-band default, and deliberately: the band default is
// what the operator planned to use on that band, this is which radio is
// actually on the air. When they disagree — a second rig borrowed for one
// evening on 20 m — the one that is transmitting is the true answer.
func (a *App) activeRadioMyRig() string {
if a.settings == nil || strings.TrimSpace(a.settingOr(keyRadiosList, "")) == "" {
return "" // no list was ever made: nothing to say, nothing changes
}
list, err := a.GetRadios()
if err != nil {
return ""
}
id := a.ActiveRadioID()
for _, r := range list {
if r.ID == id {
return strings.TrimSpace(r.MyRig)
}
}
return ""
}
// ActiveRadioMyRig exposes the connected radio's MY_RIG to the frontend, which
// pre-fills the entry form's My-station fields on every band change. Without
// this the per-band default landed in the field FIRST, and the log-time
// priority (the radio that is keying beats the radio that was planned) never
// ran — the field was no longer empty by the time the backend looked.
func (a *App) ActiveRadioMyRig() string {
return a.activeRadioMyRig()
}
+118
View File
@@ -0,0 +1,118 @@
package main
// The TCI control console — bindings.
//
// Thin on purpose: the state is a snapshot the radio pushed and the setters are
// one command each. Everything interesting is in internal/cat/tci_panel.go.
import (
"fmt"
"hamlog/internal/cat"
)
// GetTCIPanel returns the console state. Connected=false when the active CAT
// backend is not a TCI radio, so the frontend has one thing to look at rather
// than an error to distinguish from a disconnected radio.
func (a *App) GetTCIPanel() cat.TCIPanelState {
if a.cat == nil {
return cat.TCIPanelState{}
}
st, _ := a.cat.TCIPanelState()
return st
}
// tciDo is the shape every setter below takes.
func (a *App) tciDo(fn func(cat.TCIPanelController) error) error {
if a.cat == nil {
return fmt.Errorf("CAT not initialized")
}
return a.cat.TCIPanelDo(fn)
}
// SetTCIDrive sets the transmit drive (0-100).
func (a *App) SetTCIDrive(v int) error {
return a.tciDo(func(t cat.TCIPanelController) error { return t.SetDrive(v) })
}
// SetTCITuneDrive sets the drive TUNE uses (0-100).
func (a *App) SetTCITuneDrive(v int) error {
return a.tciDo(func(t cat.TCIPanelController) error { return t.SetTuneDrive(v) })
}
// SetTCIMicLevel sets the microphone gain (0-100).
func (a *App) SetTCIMicLevel(v int) error {
return a.tciDo(func(t cat.TCIPanelController) error { return t.SetMicLevel(v) })
}
// SetTCIVolume sets the receive volume in dB (0 down to -60).
func (a *App) SetTCIVolume(db int) error {
return a.tciDo(func(t cat.TCIPanelController) error { return t.SetVolume(db) })
}
// SetTCIMute mutes or unmutes the receiver.
func (a *App) SetTCIMute(on bool) error {
return a.tciDo(func(t cat.TCIPanelController) error { return t.SetMute(on) })
}
// SetTCIAGC picks the AGC speed: off, long, slow, med, fast.
func (a *App) SetTCIAGC(mode string) error {
return a.tciDo(func(t cat.TCIPanelController) error { return t.SetAGC(mode) })
}
// SetTCISquelch turns the squelch on or off.
func (a *App) SetTCISquelch(on bool) error {
return a.tciDo(func(t cat.TCIPanelController) error { return t.SetSquelch(on) })
}
// SetTCISquelchLevel sets the squelch threshold in dBm.
func (a *App) SetTCISquelchLevel(v int) error {
return a.tciDo(func(t cat.TCIPanelController) error { return t.SetSquelchLevel(v) })
}
// SetTCINB, SetTCINR, SetTCIANF and SetTCIAPF switch the receive processing.
func (a *App) SetTCINB(on bool) error {
return a.tciDo(func(t cat.TCIPanelController) error { return t.SetNB(on) })
}
func (a *App) SetTCINR(on bool) error {
return a.tciDo(func(t cat.TCIPanelController) error { return t.SetNR(on) })
}
func (a *App) SetTCIANF(on bool) error {
return a.tciDo(func(t cat.TCIPanelController) error { return t.SetANF(on) })
}
func (a *App) SetTCIAPF(on bool) error {
return a.tciDo(func(t cat.TCIPanelController) error { return t.SetAPF(on) })
}
// SetTCIFilter sets the passband edges in Hz.
func (a *App) SetTCIFilter(lo, hi int) error {
return a.tciDo(func(t cat.TCIPanelController) error { return t.SetFilter(lo, hi) })
}
// SetTCIRIT / SetTCIXIT switch the offsets on; the Offset calls move them.
func (a *App) SetTCIRIT(on bool) error {
return a.tciDo(func(t cat.TCIPanelController) error { return t.SetRIT(on) })
}
func (a *App) SetTCIXIT(on bool) error {
return a.tciDo(func(t cat.TCIPanelController) error { return t.SetXIT(on) })
}
func (a *App) SetTCIRITOffset(hz int) error {
return a.tciDo(func(t cat.TCIPanelController) error { return t.SetRITOffset(hz) })
}
func (a *App) SetTCIXITOffset(hz int) error {
return a.tciDo(func(t cat.TCIPanelController) error { return t.SetXITOffset(hz) })
}
// SetTCILock locks the radio's VFO knob.
func (a *App) SetTCILock(on bool) error {
return a.tciDo(func(t cat.TCIPanelController) error { return t.SetLock(on) })
}
// SetTCITune starts or stops the tune carrier.
//
// IT TRANSMITS, and at tune_drive rather than at drive — which is why the panel
// shows those two numbers next to the button rather than hiding one of them in
// a menu.
func (a *App) SetTCITune(on bool) error {
return a.tciDo(func(t cat.TCIPanelController) error { return t.SetTune(on) })
}
+293
View File
@@ -0,0 +1,293 @@
package main
// Watchlist bindings — the DXHunter watchlist concept as an OpsLog tab.
// The store lives in internal/watchlist (global watchlist.json, DXHunter's own
// schema); this file is the Wails boundary plus the two places the list meets
// the rest of the app: the spot stream (MarkSeen + alert) and the logbook (the
// worked-today answer contest entries are judged by).
import (
"context"
"fmt"
"net/http"
"strings"
"time"
"hamlog/internal/applog"
"hamlog/internal/qso"
"hamlog/internal/watchlist"
wruntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// The auto-contest pattern, DXHunter's contest_prefix: while non-empty, any
// spotted callsign CONTAINING it is added to the watchlist as a contest entry
// by itself — a special-event fleet (HB9WWA, DL0WWA, F4WWA…) is collected as
// it appears instead of typed in one by one. Held in an atomic so the spot
// pipeline never touches the settings store per spot.
func (a *App) GetWatchlistContestPattern() string {
if v := a.watchPattern.Load(); v != nil {
return v.(string)
}
return ""
}
// SetWatchlistContestPattern stores the pattern (global, like the list itself).
// Emptying it stops the auto-add; entries already collected stay — deleting an
// operator's list because a setting changed is DXHunter behaviour this port
// deliberately drops.
func (a *App) SetWatchlistContestPattern(p string) {
p = strings.ToUpper(strings.TrimSpace(p))
a.watchPattern.Store(p)
a.setSettingGlobal(keyWatchlistContestPattern, p)
}
// WatchlistEntries returns the list for the tab.
func (a *App) WatchlistEntries() []watchlist.Entry {
if a.watchlist == nil {
return nil
}
return a.watchlist.Entries()
}
// WatchlistAdd adds a callsign or prefix; contest entries are judged per UTC day.
func (a *App) WatchlistAdd(callsign string, contest bool) error {
if a.watchlist == nil {
return fmt.Errorf("watchlist not initialized")
}
return a.watchlist.Add(callsign, contest)
}
// WatchlistRemove deletes an entry.
func (a *App) WatchlistRemove(callsign string) error {
if a.watchlist == nil {
return fmt.Errorf("watchlist not initialized")
}
return a.watchlist.Remove(callsign)
}
// WatchlistSetNotify arms the existing alert path (sound + toast) for an entry.
func (a *App) WatchlistSetNotify(callsign string, on bool) error {
if a.watchlist == nil {
return fmt.Errorf("watchlist not initialized")
}
return a.watchlist.SetNotify(callsign, on)
}
// WatchlistSetContest flips the per-entry contest rule.
func (a *App) WatchlistSetContest(callsign string, on bool) error {
if a.watchlist == nil {
return fmt.Errorf("watchlist not initialized")
}
return a.watchlist.SetContest(callsign, on)
}
// WatchlistSlotQuery asks whether one spot's slot is worked — against the whole
// log for a normal entry, against TODAY (UTC) for a contest one.
type WatchlistSlotQuery struct {
Call string `json:"call"`
Band string `json:"band"`
Mode string `json:"mode"`
Contest bool `json:"contest"`
}
// WatchlistWorkedSlots answers a batch of slot questions for the tab.
//
// Normal entries read the CLUSTER's own slot set — the same cached
// WorkedCallSlotKeys index that colours the grid — so the watchlist can never
// contradict the cluster about the same spot. That index normalises the mode
// exactly as the operator configured (digital grouping on → FT4 counts as FT8's
// class; off → exact mode), and the first version of this ignored that: it
// asked the alerts' raw-mode index with a CLASS name, matched nothing, and
// showed a fully-worked DXpedition as all Needed.
//
// Contest entries read TODAY's contacts instead — the midnight-UTC reset is
// the query's date bound, nothing stored, nothing to reset — normalised through
// the same function so the two answers use one grammar.
func (a *App) WatchlistWorkedSlots(queries []WatchlistSlotQuery) []bool {
out := make([]bool, len(queries))
if a.qso == nil || len(queries) == 0 {
return out
}
idx := a.clusterStatusMaps()
norm := func(m string) string {
m = strings.ToUpper(strings.TrimSpace(m))
if idx.normMode != nil {
m = idx.normMode(m)
}
return m
}
slotKey := func(call, band, mode string) string {
up := strings.ToUpper(strings.TrimSpace(call))
b := strings.ToLower(strings.TrimSpace(band))
if m := norm(mode); m != "" {
return up + "|" + b + "|" + m
}
return up + "|" + b
}
// A spot whose mode the band plan could only call "DATA" (an F/H DXpedition
// off the standard dials, a comment with no mode) cannot be matched exactly:
// "DATA" is in nobody's log. Such a spot is judged at digital-CLASS grain —
// worked if ANY digital mode of that call is logged on that band. Claiming
// NEW MODE because the label differs from FT8 was the reported bug.
generic := func(m string) bool {
switch strings.ToUpper(strings.TrimSpace(m)) {
case "", "DATA", "DIG", "DIGI", "DIGITAL":
return true
}
return false
}
digKey := func(call, band string) string {
return strings.ToUpper(strings.TrimSpace(call)) + "|" + strings.ToLower(strings.TrimSpace(band)) + "|DIG"
}
needToday := false
for _, q := range queries {
if q.Contest {
needToday = true
break
}
}
today := map[string]bool{}
if needToday {
midnight := time.Now().UTC().Truncate(24 * time.Hour)
rows, err := a.qso.SlotsSince(a.ctx, midnight)
if err == nil {
for _, r := range rows {
today[slotKey(r.Callsign, r.Band, r.Mode)] = true
today[digKey(r.Callsign, r.Band)] = qso.ModeClass(r.Mode) == "DIG" || today[digKey(r.Callsign, r.Band)]
}
}
}
for i, q := range queries {
if q.Contest {
if generic(q.Mode) {
out[i] = today[digKey(q.Call, q.Band)]
} else {
out[i] = today[slotKey(q.Call, q.Band, q.Mode)]
}
} else if generic(q.Mode) {
if idx.workedCallSlotsDig != nil {
_, out[i] = idx.workedCallSlotsDig[digKey(q.Call, q.Band)]
}
} else if idx.workedCallSlots != nil {
_, out[i] = idx.workedCallSlots[slotKey(q.Call, q.Band, q.Mode)]
}
}
return out
}
// watchSpot runs one live spot through the watchlist: last-seen bookkeeping and
// the alert, through the SAME event the alert rules fire — the frontend already
// knows how to toast and sound it, and a second notification path would be a
// second thing to misconfigure.
func (a *App) watchSpot(dxCall, band, mode, country, comment string, freqHz int64) {
if a.watchlist == nil {
return
}
entry, notify, ok := a.watchlist.MarkSeen(dxCall)
if !ok {
// Not watched yet — the auto-contest pattern may claim it. Contains, not
// prefix: the event string sits anywhere in these calls (HB9WWA, F4WWA/P).
if p := a.GetWatchlistContestPattern(); p != "" &&
strings.Contains(strings.ToUpper(dxCall), p) {
if err := a.watchlist.Add(dxCall, true); err == nil {
applog.Printf("watchlist: auto-added %s (contest pattern %q)", dxCall, p)
entry, notify, ok = a.watchlist.MarkSeen(dxCall)
if a.ctx != nil {
wruntime.EventsEmit(a.ctx, "watchlist:changed")
}
}
}
}
if !ok || !notify || a.ctx == nil {
return
}
// Already worked? Then nothing to announce. Judged HERE, before the sound —
// the report was an alert ringing for a slot the tab showed as Worked a
// moment later, because the frontend's verdict arrives on a debounce while
// the alert used to fire on the raw spot. Same verdict as the tab: exact
// slot for named modes, digital class for a generic DATA spot, today-only
// for a contest entry.
if e, found := a.watchlist.Get(entry); found {
if a.WatchlistWorkedSlots([]WatchlistSlotQuery{{Call: dxCall, Band: band, Mode: mode, Contest: e.IsContest}})[0] {
return
}
}
// Throttled per entry: a DXpedition lights up every skimmer on the planet,
// and forty alerts a minute for one station is a alarm nobody keeps on.
a.watchAlertMu.Lock()
last := a.watchAlertAt[entry]
now := time.Now()
if now.Sub(last) < 2*time.Minute {
a.watchAlertMu.Unlock()
return
}
a.watchAlertAt[entry] = now
a.watchAlertMu.Unlock()
wruntime.EventsEmit(a.ctx, "alert:fired", map[string]any{
"rule": "Watchlist " + entry,
"call": strings.ToUpper(strings.TrimSpace(dxCall)),
"band": band,
"mode": mode,
"freq_hz": freqHz,
"country": country,
"comment": comment,
"sound": true,
"visual": true,
})
}
// startWatchlistClubLog begins the expedition enrichment: every entry's
// ClubLog block (expedition flag, OQRS, LiveStream, QSO totals and 24 h rate)
// is refreshed on a rolling schedule — hourly for expeditions, six-hourly for
// the rest, DXHunter's own cadence. OpsLog's application API key is used, so
// there is nothing to configure.
//
// Two at a time with a breath between requests: the key is shared by every
// OpsLog install, and a hundred-entry watchlist must read as a trickle at
// ClubLog's end, not a burst.
func (a *App) startWatchlistClubLog() {
if a.watchlist == nil {
return
}
go func() {
client := &http.Client{Timeout: 30 * time.Second}
// Let the app finish starting before the first network pass.
time.Sleep(15 * time.Second)
for {
stale := a.watchlist.StaleEntries(1*time.Hour, 6*time.Hour)
changed := false
for _, call := range stale {
// The pattern's BASE is what ClubLog knows: VK9* has no log.
base := strings.TrimSuffix(call, "*")
if base == "" {
continue
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
d, err := watchlist.FetchWatch(ctx, client, clublogAppAPIKey, base)
cancel()
if err != nil {
applog.Printf("watchlist clublog: %s: %v", base, err)
continue
}
if a.watchlist.ApplyClubLog(call, d) {
changed = true
if d.IsExpedition {
applog.Printf("watchlist clublog: %s is a DXpedition (%d QSOs, %d/24h, OQRS=%v)",
base, func() int {
if d.ClubLogInfo != nil {
return d.ClubLogInfo.TotalQSOs
}
return 0
}(), d.QSOs24h(), d.HasOQRS)
}
}
time.Sleep(400 * time.Millisecond)
}
if changed && a.ctx != nil {
wruntime.EventsEmit(a.ctx, "watchlist:changed")
}
time.Sleep(10 * time.Minute)
}
}()
}
+155
View File
@@ -0,0 +1,155 @@
package main
// Log-aware colours in WSJT-X / JTDX's own Band Activity window (message 13),
// the way JTAlert paints them: a decode of a watchlist member, a new DXCC or a
// new band for its entity is highlighted where the operator is actually
// looking. The verdicts come from the same cluster status cache that colours
// the spot grid, so the two windows can never disagree.
import (
"strings"
"hamlog/internal/applog"
"hamlog/internal/dxcc"
udp "hamlog/internal/integrations/udp"
)
const (
keyWsjtHighlight = "udp.wsjt.highlight"
keyWsjtFollowMode = "udp.wsjt.followmode" // spot clicks switch the decoder's mode
)
// wsjtModes are the modes a Configure message can meaningfully ask for — the
// decoder's own vocabulary. Anything else (CW, SSB, RTTY) is none of its
// business and is not sent.
var wsjtModes = map[string]bool{
"FT8": true, "FT4": true, "JT65": true, "JT9": true,
"MSK144": true, "Q65": true, "FST4": true, "JS8": false, // JS8Call speaks another protocol
}
// GetWsjtFollowMode reports whether spot clicks retune the decoder's mode.
func (a *App) GetWsjtFollowMode() bool {
return a.settingOr(keyWsjtFollowMode, "1") == "1"
}
// SetWsjtFollowMode flips it.
func (a *App) SetWsjtFollowMode(on bool) {
v := "0"
if on {
v = "1"
}
a.setSetting(keyWsjtFollowMode, v)
}
// ConfigureDecoderMode asks the connected decoders to switch mode — called by
// the frontend after a spot click has tuned the radio. A no-op for modes the
// decoder does not speak, and when the option is off or nothing is connected.
func (a *App) ConfigureDecoderMode(mode string) {
mode = strings.ToUpper(strings.TrimSpace(mode))
if a.udp == nil || !wsjtModes[mode] || !a.GetWsjtFollowMode() {
return
}
a.udp.SendConfigureMode(mode)
}
// The palette. Fixed colours, not theme tokens — they are painted into another
// application's window, which has no idea what theme OpsLog wears.
var (
hlWatchlist = udp.RGB{R: 244, G: 114, B: 182} // the watchlist pink
hlNewDXCC = udp.RGB{R: 22, G: 130, B: 60} // green
hlNewBand = udp.RGB{R: 226, G: 122, B: 24} // orange
hlWhite = udp.RGB{R: 255, G: 255, B: 255}
hlBlack = udp.RGB{R: 20, G: 20, B: 20}
)
// GetWsjtHighlight reports whether decode highlighting is on.
func (a *App) GetWsjtHighlight() bool {
return a.settingOr(keyWsjtHighlight, "0") == "1"
}
// SetWsjtHighlight turns decode highlighting on or off. Turning it OFF also
// clears every instruction OpsLog installed in the running applications — a
// disabled option that leaves stale colours behind looks broken, not disabled.
func (a *App) SetWsjtHighlight(on bool) {
v := "0"
if on {
v = "1"
}
a.setSetting(keyWsjtHighlight, v)
a.wsjtHighlightOn.Store(on)
if !on && a.udp != nil {
for _, inst := range a.udp.Instances() {
_ = a.udp.SendClearHighlights(inst)
}
a.wsjtHLMu.Lock()
a.wsjtHLSent = map[string]string{}
a.wsjtHLMu.Unlock()
applog.Printf("wsjt highlight: off — cleared in every instance")
}
}
// maybeHighlightDecode paints one decoded callsign in the instance that heard
// it, when the option is on and the verdict is worth a colour. De-duplicated
// per instance+call+verdict: a station CQing all evening is decoded four times
// a minute, and the instruction only needs to be said once.
func (a *App) maybeHighlightDecode(instance, call, band string) {
if !a.wsjtHighlightOn.Load() || a.udp == nil || call == "" || instance == "" {
return
}
bg, fg, verdict := a.decodeHighlightVerdict(call, band)
key := instance + "|" + strings.ToUpper(call) + "|" + band
a.wsjtHLMu.Lock()
if a.wsjtHLSent == nil {
a.wsjtHLSent = map[string]string{}
}
if len(a.wsjtHLSent) > 4000 { // bounded; a long session just re-says a few
a.wsjtHLSent = map[string]string{}
}
prev, had := a.wsjtHLSent[key]
if had && prev == verdict {
a.wsjtHLMu.Unlock()
return
}
a.wsjtHLSent[key] = verdict
a.wsjtHLMu.Unlock()
if verdict == "" {
// Was highlighted under an earlier verdict and no longer deserves it
// (the operator just worked them): clear that one callsign.
if had && prev != "" {
_ = a.udp.SendHighlight(instance, call, nil, nil, false)
}
return
}
_ = a.udp.SendHighlight(instance, call, bg, fg, false)
}
// decodeHighlightVerdict ranks a callsign: watchlist beats new-DXCC beats
// new-band; anything else is "no colour". The empty verdict doubles as the
// clear signal in maybeHighlightDecode.
func (a *App) decodeHighlightVerdict(call, band string) (bg, fg *udp.RGB, verdict string) {
if a.watchlist != nil {
if _, ok := a.watchlist.Match(call); ok {
c := hlWatchlist
f := hlBlack
return &c, &f, "watchlist"
}
}
c := a.clusterStatusMaps()
if a.dxcc != nil {
if m, ok := a.dxcc.Lookup(call); ok && m.Entity != nil {
num := dxcc.EntityDXCC(m.Entity.Name)
ent := c.entities[num]
if ent == nil {
bgc, fgc := hlNewDXCC, hlWhite
return &bgc, &fgc, "new-dxcc"
}
if band != "" {
if _, workedBand := ent.Bands[strings.ToLower(band)]; !workedBand {
bgc, fgc := hlNewBand, hlBlack
return &bgc, &fgc, "new-band"
}
}
}
}
return nil, nil, ""
}
+7
View File
@@ -174,6 +174,11 @@ type MatrixColors struct {
EntityWorked string `json:"entity_worked"` EntityWorked string `json:"entity_worked"`
NotWorked string `json:"not_worked"` NotWorked string `json:"not_worked"`
CurrentEntry string `json:"current_entry"` CurrentEntry string `json:"current_entry"`
// The dot marking a slot already worked with the callsign in hand. It is a
// mark rather than a background, so it needs its own two colours: it is
// drawn on top of all five of the above and must stay legible over each.
MarkWorked string `json:"mark_worked"`
MarkConfirmed string `json:"mark_confirmed"`
} }
// normMatrixColors keeps only plain hex values. Anything else becomes "" — i.e. // normMatrixColors keeps only plain hex values. Anything else becomes "" — i.e.
@@ -196,6 +201,8 @@ func normMatrixColors(c MatrixColors) MatrixColors {
EntityWorked: clean(c.EntityWorked), EntityWorked: clean(c.EntityWorked),
NotWorked: clean(c.NotWorked), NotWorked: clean(c.NotWorked),
CurrentEntry: clean(c.CurrentEntry), CurrentEntry: clean(c.CurrentEntry),
MarkWorked: clean(c.MarkWorked),
MarkConfirmed: clean(c.MarkConfirmed),
} }
} }
+6
View File
@@ -33,6 +33,12 @@ func TestBulkEditFieldsAreWritable(t *testing.T) {
id := m[1] id := m[1]
// Handled before the column map: freq takes a numeric path (freq_hz + // Handled before the column map: freq takes a numeric path (freq_hz +
// band together) and the extras live in extras_json. // band together) and the extras live in extras_json.
// The integer My-station fields take their own numeric path
// (BulkSetIntField + bulkEditableIntCols in the repo), added after this
// guard was written — which is exactly the drift it exists to catch.
if id == "my_dxcc" || id == "my_cq_zone" || id == "my_itu_zone" {
continue
}
if id == "freq" || qso.IsBulkEditableExtra(id) { if id == "freq" || qso.IsBulkEditableExtra(id) {
continue continue
} }
+66
View File
@@ -0,0 +1,66 @@
package main
import (
"testing"
"hamlog/internal/cat"
)
// What a rigctl client is told when it asks "what frequency is the radio on".
//
// Hamlib's "f" means the VFO IN USE — where the operator is listening. RigState
// follows ADIF, where FreqHz is where we TRANSMIT, and the two are the same
// number until split is engaged. They were handed over unchanged, so with split
// on every client asking for the dial was given VFO B.
//
// Reported from a station running an IC-7850 over USB: turning VFO B moved
// VFO A. OpsLog was writing nothing to that radio — a client read the dial, was
// handed the transmit VFO, and wrote it back as the dial.
func TestShareRXFreqAnswersTheListeningVFO(t *testing.T) {
const rx, tx = 14195000, 14200500
cases := []struct {
name string
st cat.RigState
want int64
}{
{
name: "simplex — the one frequency there is",
st: cat.RigState{FreqHz: rx},
want: rx,
},
{
name: "split — the RX VFO, not the TX one",
st: cat.RigState{Split: true, FreqHz: tx, RxFreqHz: rx},
want: rx,
},
{
// A backend that reports split without ever filling RxFreqHz would
// otherwise be answered with 0, and a client told the radio is on
// 0 Hz does something worse than nothing with it.
name: "split claimed but no RX frequency known",
st: cat.RigState{Split: true, FreqHz: tx},
want: tx,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := shareRXFreq(c.st); got != c.want {
t.Errorf("shareRXFreq(%+v) = %d, want %d", c.st, got, c.want)
}
})
}
}
// And the pair, stated together: the two questions must not return the same
// answer while split is on, or the distinction has been lost somewhere.
func TestShareSplitReportsTheOtherVFO(t *testing.T) {
st := cat.RigState{Split: true, FreqHz: 14200500, RxFreqHz: 14195000}
rxAnswer := shareRXFreq(st)
txAnswer := st.FreqHz // what Split() hands back for "i" / get_split_freq
if rxAnswer == txAnswer {
t.Fatalf("get_freq and get_split_freq both answered %d — a client cannot tell the VFOs apart", rxAnswer)
}
if rxAnswer != st.RxFreqHz || txAnswer != st.FreqHz {
t.Errorf("got rx=%d tx=%d, want rx=%d tx=%d", rxAnswer, txAnswer, st.RxFreqHz, st.FreqHz)
}
}
+308
View File
@@ -1,4 +1,312 @@
[ [
{
"version": "0.27.4",
"date": "",
"en": [
"FT decodes: a State column between the locator and the country — the two-letter badge plus the full name — for the WAS chasers.",
"FT decodes: a NEW STATE badge and filter — a US state never worked lights up in the status column, and the filter chip shows only those. The WAS chase is complete.",
"The hunt goes global: a “Chase” setting (DX Cluster page) decides for EVERY category — DXCC, band, mode, slot, prefix, county, state, grid — whether “worked but never confirmed” still counts as something to chase, judged against the confirmation sources you pick (LoTW, QSL card, eQSL, QRZ.com). Such needs show as dimmed badges: a QSL to chase, not a QSO to make. The grids own Chase selector folds into it.",
"New FTx menu gathering FT Decodes, the new FT Map and the Grid squares map.",
"FT Map: a world map of the live FTx decodes — great-circle arcs from your QTH to every station heard in the last 30 minutes, coloured by band, with the PSK-Reporter palette and a basemap picker.",
"Maps: one single world (no more side-by-side copies), the surround follows the theme colour, and zooming stays centred — on the FT Map and the Grid squares map.",
"Watchlist: fixed columns in the spot rows, so band, mode and frequency line up instead of drifting with the country name."
],
"fr": [
"FT decodes : une colonne État entre le locator et le pays — le badge deux lettres plus le nom complet — pour les chasseurs de WAS.",
"FT decodes : un badge et un filtre NOUVEL ÉTAT — un état US jamais contacté sallume dans la colonne statut, et la puce de filtre ne montre que ceux-là. La chasse WAS est complète.",
"La chasse devient globale : un réglage « Chasse » (page DX Cluster) décide pour TOUTES les catégories — DXCC, bande, mode, slot, préfixe, comté, état, grille — si « contacté mais jamais confirmé » reste à chasser, jugé selon les sources de confirmation choisies (LoTW, carte QSL, eQSL, QRZ.com). Ces besoins saffichent en badges atténués : une QSL à chasser, pas un QSO à faire. Le sélecteur Chasse des grilles fusionne dedans.",
"Nouveau menu FTx regroupant FT Decodes, la nouvelle FT Map et la carte Grid squares.",
"FT Map : une carte du monde des décodages FTx en direct — arcs orthodromiques depuis votre QTH vers chaque station entendue dans les 30 dernières minutes, colorés par bande, avec la palette PSK Reporter et un choix de fond de carte.",
"Cartes : un seul monde (fini les copies côte à côte), le pourtour suit la couleur du thème et le zoom reste centré — sur la FT Map et la carte Grid squares.",
"Watchlist : colonnes fixes dans les lignes de spots — bande, mode et fréquence s'alignent au lieu de dériver avec le nom du pays."
]
},
{
"version": "0.27.3",
"date": "",
"en": [
"KPA500: the amplifier no longer switches itself off and commands respond instantly. A command this model does not know (the KPA1500s ATU poll) was tearing the link down every cycle, and each reconnect toggled the serial control lines — which are the KPA500s power switch. The lines are now held steady, silence is not treated as a dead link, and the baud is picked from a list.",
"FT decodes: within a period, decodes are listed in arrival order — mirroring the decoders own window — instead of strongest-first.",
"Voice keyer: twelve message slots (F1F12) instead of six.",
"Preferences open smoothly on a busy station: while the dialog is open, cluster spots, FT decodes and CAT snapshots queue quietly instead of repainting the whole window behind it — everything catches up the moment it closes.",
"Voice keyer: a delete button per message — removes the recording and clears the label."
],
"fr": [
"KPA500 : lampli ne s’éteint plus tout seul et les commandes répondent instantanément. Une commande inconnue de ce modèle (le poll ATU du KPA1500) détruisait le lien à chaque cycle, et chaque reconnexion basculait les lignes de contrôle série — qui sont linterrupteur du KPA500. Les lignes sont désormais tenues stables, le silence nest plus traité comme un lien mort, et le baud se choisit dans une liste.",
"FT decodes : dans une période, les décodages sont listés dans lordre darrivée — comme la fenêtre du décodeur — au lieu du plus fort dabord.",
"Manipulateur vocal : douze messages (F1F12) au lieu de six.",
"Les Préférences restent fluides sur une station chargée : dialogue ouvert, les spots cluster, les décodages FT et les instantanés CAT patientent en file au lieu de repeindre toute la fenêtre derrière — tout se rattrape à la fermeture.",
"Manipulateur vocal : un bouton supprimer par message — efface lenregistrement et le libellé."
]
},
{
"version": "0.27.2",
"date": "",
"en": [
"Bulk operations work on any size of selection — setting a field, fixing frequencies, deleting, marking uploads and exporting the selection all failed with “too many SQL variables” past a few tens of thousands of QSOs. Statements are now issued in slices.",
"Elecraft console: the power meter reads in real watts. The K3s bargraph is relative to a range that flips at 12 W — calibrated against a real radios full table, the PC setting picks the range and the bar converts to watts.",
"Watchlist: a visual pass toward DXHunters look — pink callsigns, counter pills, quieter cards with a hover, the ⚡ back on the DXpedition badge.",
"WSJT-X / JTDX: OpsLog can highlight decodes in the decoders own Band Activity window from your log — watchlist members pink, new DXCC green, new band orange (option in Settings → Connections). And a freshly-started decoder is asked to replay its on-screen decodes, so the FT decodes panel starts full.",
"WSJT-X / JTDX / MSHV: only a CHANGED DX Call updates the entry — the decoder re-broadcasts the same call endlessly, and it kept overwriting a spot clicked in OpsLog.",
"Map: Zoom DX toward a polar entity no longer frames a band of blank white above the top of the world — the camera stays within the maps ±85°, the path still draws.",
"WSJT-X / JTDX / MSHV: clicking a spot in a digital mode the decoder speaks (FT8, FT4, JT65…) switches the decoders mode too — option in Settings → Connections, on by default."
],
"fr": [
"Les opérations groupées fonctionnent quelle que soit la taille de la sélection — définir un champ, corriger des fréquences, supprimer, marquer les uploads et exporter la sélection échouaient avec « too many SQL variables » au-delà de quelques dizaines de milliers de QSO. Les requêtes sont désormais émises par tranches.",
"Console Elecraft : le wattmètre lit en vrais watts. Le bargraph du K3 est relatif à une gamme qui bascule à 12 W — calibré sur la table complète dune vraie radio, le réglage PC choisit la gamme et la barre se convertit en watts.",
"Watchlist : une passe visuelle vers le look DXHunter — indicatifs roses, compteurs en pastilles, cartes plus feutrées avec survol, le ⚡ de retour sur le badge DXpedition.",
"WSJT-X / JTDX : OpsLog peut surligner les décodages dans la fenêtre Band Activity du décodeur selon votre log — watchlist en rose, nouveau DXCC en vert, nouvelle bande en orange (option dans Réglages → Connections). Et un décodeur fraîchement détecté rejoue ses décodages à l’écran, donc le panneau FT decodes démarre plein.",
"WSJT-X / JTDX / MSHV : seul un DX Call qui CHANGE met à jour la saisie — le décodeur rediffuse le même call sans fin, et il écrasait un spot cliqué dans OpsLog.",
"Carte : Zoom DX vers une entité polaire ne cadre plus une bande blanche au-dessus du haut du monde — la caméra reste dans les ±85° de la carte, le trajet se dessine toujours.",
"WSJT-X / JTDX / MSHV : cliquer un spot dans un mode numérique que le décodeur parle (FT8, FT4, JT65…) change aussi le mode du décodeur — option dans Réglages → Connections, activée par défaut."
]
},
{
"version": "0.27.1",
"date": "",
"en": [
"Elecraft console: the S-meter is calibrated against a real K3 — S9 and the +dB readings now match the radios own display (they read about two S-units low).",
"Elecraft console: an SWR spike (the K3s own blip at the end of an FT8 frame) no longer fades over twelve seconds — the peak shows briefly, then the meter returns straight to the live reading.",
"Icom: the IC-7760 joins the model list (CI-V address B2h).",
"Icom console: the IC-7760 gets its real attenuator steps — 6/12/18 dB.",
"Icom network audio: the RX stream is decoded correctly — mono is requested and the payload offset was confirmed on a real IC-7760, curing the garbled, clicking audio.",
"Icom: switching back from a data mode (USB-D1) to plain USB now sticks — if the rig ignores the data-flag command, it is repeated with the modern one-frame form (0x26). Seen on the IC-7760.",
"Icom console: a DATA mode button (USB-D, what FT8 wants), the PSK button drives the rigs that have a native PSK mode, and the power meter reads in real watts on the IC-7760s 250 W scale.",
"Icom network audio: the right codec is requested (16-bit mono LPCM), settled by experiment on a real IC-7760.",
"CAT settings: reopening the panel now shows the radio that is actually selected — it always showed the first one, with the fields (MY_RIG included) silently editing the wrong entry.",
"IC-7760: the power meter is calibrated against the radio (100 W reads 100 W on the 250 W face) and the RF power setting reads in watts, not a percentage.",
"Icom network audio: toggling Listening off and on no longer chops the sound — the monitor restarts as network-fed instead of also opening a USB capture.",
"QSO recorder: starting a fresh manual take resets the counter for good — it used to flash 0 and jump back to the previous takes elapsed time.",
"MY_RIG follows the radio actually connected: the entry form now asks the active radio first, before the per-band default — an IC-7760 on the air no longer logs as the Flex the band plan names.",
"QSO recorder: a manual take on a network Icom records the network RX stream, not the “From radio” sound card (which captured another radios DAX on a mixed station).",
"Icom network audio: duplicate and late-retransmitted packets no longer reach the recorder — recordings came out longer than the QSO, slowed and stuttering, while the speakers played fine.",
"Icom network audio: it now starts with the app — launching OpsLog connected with audio silently off, and the option had to be unticked and re-saved to hear anything.",
"Icom network: when the rig goes quiet on CI-V while the session stays up (seen on the IC-7760), the CI-V flow is re-opened on the spot — recovery in seconds instead of the 35-second full reconnect.",
"Icom network: after a session dies young, the redial waits 20 s so the rig can purge the old session first — stops the reconnect-die-reconnect spiral seen on the IC-7760, where each fresh session answered for a second and was then strangled by the previous ones cleanup.",
"Icom network audio, phase 5: the radio can now TAKE audio — with RX audio enabled, pick “Radio (network audio)” as the To-radio device and the voice keyer plays straight to the rig over the LAN, no cable, no virtual sound card. First tested on the IC-7760.",
"Icom network audio: listening is now a remembered choice — Stop listening keeps the speakers off across reconnects and restarts, while the stream stays open for the QSO recorder and the voice keyer.",
"Icom console: a speaker button beside ON/OFF toggles listening to the network RX audio right from the console — no more trip through Settings → Audio; recordings and the voice keyer keep working either way, and the choice is remembered.",
"CAT settings: a “Play it through the speakers” checkbox sits under the Icom RX-audio option — the same remembered switch as the consoles speaker button, applied immediately.",
"Icom network audio: “Talk to radio” now works over the LAN too — live microphone straight to the rig, PTT included. With RX audio and a headset, OpsLog is a complete remote station: hear, talk, key CW and log over one network link.",
"Icom console: the SUB display shows the sub receivers frequency at all times (it was blank until split), and engaging split copies the mode to the TX VFO so it matches the main.",
"Icom network audio: the stream now opens regardless of the speaker choice — speakers-off (or a failed output device) was silently disabling the whole stream: no audio session, no recordings, no voice keyer, despite the RX-audio option being ticked.",
"Icom network: a radio in standby keeps its session and the consoles ON button — the quiet-CI-V recovery was tearing the session down every 15 s, so a radio that was off when OpsLog started could never be powered on.",
"Icom console: the MOX button carries your microphone on a network station, and engaging split aligns the TX VFOs mode with the main.",
"Icom console: the spectrum scope is removed. Every model streams its waveform differently — and on the IC-7760 enabling it killed the whole CI-V link, audio included. The radios own scope does it better.",
"Icom: any leftover waveform stream is switched off at connect — the scope flag lives in the radio and survived sessions, and its flood is what was killing the IC-7760s CI-V link.",
"Icom console: an ATU chip beside SPLIT engages or DISENGAGES the internal tuner — TUNE started a cycle but could never take the tuner back out of line.",
"Icom console: the TX meters get needle inertia — power holds its peak instead of flickering to 0 W between syllables, SWR shows the real peak then returns to the live value — and the wattage readout no longer wraps at three digits.",
"Icom console: the meters use the same LED bars as the Flex and Elecraft consoles, and the mode badge says USB or LSB instead of an ambiguous SSB.",
"Cluster: spots on the standard FT8/FT4 frequencies of every band now read FT8/FT4 when the comment names no mode — 30 m, 60 m, 80 m FT4, 17 m FT4 and 12 m were falling into the generic DATA bucket.",
"OmniRig (Yaesu): with split engaged, tuning to a spot moves BOTH VFOs — on an FT-2000 the write landed on the TX VFO only, so the transmitter QSYed and the receiver stayed behind.",
"Worked before: a slow lookup can no longer overwrite a newer one — typing a second callsign quickly could leave the previous calls QSOs displayed under the new calls name.",
"Icom network: OpsLog now sends its own pings every 500 ms on all three streams, as RS-BA1 and wfview do — a client that only ever replied was judged absent by the rig, which stopped serving CI-V data about a minute into every session: the recurring sound/CAT dropouts."
],
"fr": [
"Console Elecraft : le S-mètre est calibré sur un vrai K3 — S9 et les +dB correspondent désormais à laffichage de la radio (il lisait environ deux points S trop bas).",
"Console Elecraft : un pic de ROS (le sursaut du K3 en fin de trame FT8) ne sestompe plus pendant douze secondes — le pic saffiche brièvement, puis le ros-mètre revient directement à la valeur réelle.",
"Icom : lIC-7760 rejoint la liste des modèles (adresse CI-V B2h).",
"Console Icom : lIC-7760 reçoit ses vrais crans datténuateur — 6/12/18 dB.",
"Audio réseau Icom : le flux RX est décodé correctement — le mono est demandé et loffset du payload a été confirmé sur un vrai IC-7760, ce qui guérit le son inaudible et les clics.",
"Icom : revenir dun mode data (USB-D1) au USB simple tient désormais — si la radio ignore la commande du drapeau data, elle est répétée sous la forme moderne en une trame (0x26). Constaté sur lIC-7760.",
"Console Icom : un bouton de mode DATA (USB-D, celui de FT8), le bouton PSK pilote les radios qui ont un vrai mode PSK, et le wattmètre lit en watts réels sur l’échelle 250 W de lIC-7760.",
"Audio réseau Icom : le bon codec est demandé (LPCM mono 16 bits), déterminé par lexpérience sur un vrai IC-7760.",
"Réglages CAT : rouvrir le panneau montre désormais la radio réellement sélectionnée — il montrait toujours la première, et les champs (MY_RIG compris) modifiaient silencieusement la mauvaise entrée.",
"IC-7760 : le wattmètre est calibré sur la radio (100 W affiche 100 W sur l’échelle 250 W) et le réglage RF power se lit en watts, plus en pourcentage.",
"Audio réseau Icom : couper puis relancer Listening ne hache plus le son — le moniteur redémarre alimenté par le réseau au lieu douvrir en plus une capture USB.",
"Enregistreur de QSO : démarrer une nouvelle prise manuelle remet le compteur à zéro pour de bon — il affichait 0 puis resautait au temps de la prise précédente.",
"MY_RIG suit la radio réellement connectée : le formulaire interroge dabord la radio active, avant le défaut par bande — un IC-7760 à lantenne ne se logue plus comme le Flex prévu par le plan de bande.",
"Enregistreur de QSO : une prise manuelle sur un Icom réseau enregistre le flux RX réseau, pas la carte son « From Radio » (qui capturait le DAX dune autre radio sur une station mixte).",
"Audio réseau Icom : les paquets dupliqués ou retransmis en retard natteignent plus lenregistreur — les enregistrements sortaient plus longs que le QSO, ralentis et hachés, alors que les haut-parleurs jouaient bien.",
"Audio réseau Icom : il démarre maintenant avec lapplication — au lancement, la connexion se faisait audio coupé, et il fallait décocher/recocher loption pour entendre quelque chose.",
"Réseau Icom : quand la radio se tait sur le CI-V alors que la session tient (constaté sur lIC-7760), le flux CI-V est rouvert immédiatement — récupération en quelques secondes au lieu des 35 secondes de reconnexion complète.",
"Réseau Icom : après une session morte jeune, la renumérotation attend 20 s pour que la radio purge dabord lancienne session — stoppe la spirale reconnexion-mort-reconnexion vue sur lIC-7760, où chaque session neuve répondait une seconde avant d’être étranglée par le nettoyage de la précédente.",
"Audio réseau Icom, phase 5 : la radio peut maintenant RECEVOIR de laudio — avec le RX audio activé, choisissez « Radio (network audio) » comme périphérique To Radio et le voice keyer joue directement vers la radio par le LAN, sans câble ni carte son virtuelle. Premier test sur lIC-7760.",
"Audio réseau Icom : l’écoute est désormais un choix mémorisé — Stop listening garde les enceintes coupées à travers reconnexions et redémarrages, tandis que le flux reste ouvert pour lenregistreur de QSO et le voice keyer.",
"Console Icom : un bouton haut-parleur à côté de ON/OFF bascule l’écoute du RX audio réseau depuis la console — fini laller-retour dans Réglages → Audio ; enregistrements et voice keyer continuent de fonctionner, et le choix est mémorisé.",
"Réglages CAT : une case « Écouter dans les enceintes » sous loption RX audio Icom — le même interrupteur mémorisé que le bouton haut-parleur de la console, appliqué immédiatement.",
"Audio réseau Icom : « Talk to radio » fonctionne aussi par le LAN — micro en direct vers la radio, PTT compris. Avec le RX audio et un casque, OpsLog devient une station remote complète : écouter, parler, manipuler la CW et loguer sur un seul lien réseau.",
"Console Icom : laffichage SUB montre la fréquence du sub receiver en permanence (il restait vide hors split), et activer le split copie le mode sur le VFO TX pour quil suive le main.",
"Audio réseau Icom : le flux souvre désormais indépendamment du choix d’écoute — enceintes coupées (ou périphérique de sortie en échec) désactivait silencieusement tout le flux : pas de session audio, ni enregistrements, ni voice keyer, malgré la case RX audio cochée.",
"Réseau Icom : une radio en veille garde sa session et le bouton ON de la console — la récupération du CI-V muet détruisait la session toutes les 15 s, donc une radio éteinte au lancement dOpsLog ne pouvait jamais être allumée.",
"Console Icom : le bouton MOX emporte votre micro sur une station réseau, et activer le split aligne le mode du VFO TX sur le main.",
"Console Icom : le scope spectral est retiré. Chaque modèle streame sa forme donde différemment — et sur lIC-7760 son activation tuait tout le lien CI-V, audio compris. Le scope de la radio fait ça mieux.",
"Icom : tout flux waveform résiduel est coupé à la connexion — le drapeau scope vit dans la radio et survivait aux sessions, et son flot est ce qui tuait le lien CI-V de lIC-7760.",
"Console Icom : une puce ATU à côté de SPLIT engage ou DÉSENGAGE le tuner interne — TUNE lançait un cycle mais ne pouvait jamais remettre le tuner hors ligne.",
"Console Icom : les mètres TX gagnent une inertie daiguille — la puissance tient sa crête au lieu de retomber à 0 W entre les syllabes, le ROS montre la vraie crête puis revient à la valeur vive — et laffichage en watts ne passe plus à la ligne à trois chiffres.",
"Console Icom : les mètres utilisent les mêmes barres LED que les consoles Flex et Elecraft, et le badge de mode dit USB ou LSB au lieu dun SSB ambigu.",
"Cluster : les spots sur les fréquences standard FT8/FT4 de chaque bande lisent désormais FT8/FT4 quand le commentaire ne nomme pas de mode — 30 m, 60 m, FT4 80 m, FT4 17 m et 12 m tombaient dans le bloc DATA générique.",
"OmniRig (Yaesu) : avec le split actif, se rendre sur un spot déplace LES DEUX VFO — sur un FT-2000 l’écriture natteignait que le VFO TX, donc l’émetteur QSYait et le récepteur restait derrière.",
"Déjà contacté : une recherche lente ne peut plus écraser une plus récente — taper un second indicatif rapidement pouvait laisser les QSO du call précédent affichés sous le nom du nouveau.",
"Réseau Icom : OpsLog envoie désormais ses propres pings toutes les 500 ms sur les trois flux, comme RS-BA1 et wfview — un client qui ne faisait que répondre était jugé absent par la radio, qui cessait de servir le CI-V au bout dune minute : les coupures récurrentes de son/CAT."
]
},
{
"version": "0.27.0",
"date": "",
"en": [
"⭐ NEW — Watchlist (Tools): the DXHunter watchlist as an OpsLog tab — callsigns you are hunting (exact, or a family with a trailing * — VK9* catches every VK9), the live cluster spots under each with the NEW badges and a Needed/Worked verdict per slot, an ON AIR badge, per-entry alerts through the normal alert path, and CONTEST entries judged per UTC day (at midnight everything is workable again).Each entry is enriched from ClubLog automatically: DXpedition badge, OQRS, LiveStream link, QSO total and 24-hour rate — nothing to configure. Reads and writes DXHunters own watchlist.json format — drop your existing file into the data folder to carry it over.",
"TCI (SunSDR): the meter subscription is renewed when the radio announces it is ready — sent only at connect, it could fall inside the initial state dump and be ignored, which left the transmit power and SWR empty. The log now also records the subscription and the first sensor frames, so a report can tell “the radio never sends them” from “they arrived and were dropped”.",
"Sending a spot while in split now pre-fills the RX frequency — where the station actually is — instead of the TX frequency, which spotted the pile-up five up from the DX.",
"Cluster: NEW SLOT gets its own colour — the sky cyan the panadapter palette already uses for it, clearly apart from POTA green and the yellows. The NEW SLOT and NEW COUNTY filter chips now wear the same colours as the badges they select, and the NEW CALL filter works even when the slot-highlight display option is off.",
"Elecraft console: a mode row — CW, USB, LSB, DATA and DATA RTTY. The two DATA buttons set the K3s submode as well (DATA A for FT8/FT4, FSK D for RTTY): switching to DATA by mode alone kept whatever submode the last session left, which is how a K3 “in DATA” keys FT8 with no audio.",
"DX Cluster settings: “I chase POTA” and “I chase SOTA”, on by default. Unticked, the NEW POTA badge, colour and filter disappear — a new-band + new-POTA spot reads NEW BAND alone — and the reference columns stay empty.",
"Elecraft console: RIT and XIT use the same control as the Icom and TCI consoles — ± buttons, mouse wheel, typed value, Ctrl+←/→ — and the power slider moves in 1 W steps instead of 5.",
"Bulk edit: My DXCC, My CQ zone and My ITU zone join the My-station fields — numbers checked against their real ranges, empty clears.",
"Clicking a spot in the Chase new panel now applies the FlexRadio panadapter width/zoom, like every other spot click.",
"FlexRadio: the panadapter width/zoom now applies reliably when double-clicking a cluster spot — the zoom is sent after the tune settles, so SmartSDRs own pan-follow on a band change no longer overrides it."
],
"fr": [
"⭐ NOUVEAU — Watchlist (Outils) : la watchlist de DXHunter en onglet OpsLog — indicatifs chassés (exacts, ou une famille avec une * finale — VK9* attrape tous les VK9), les spots cluster en direct sous chaque entrée avec les badges NOUVEAU et un verdict Manquant/Contacté par créneau, un badge ON AIR, des alertes par entrée via le circuit d'alerte normal, et des entrées CONTEST jugées par jour UTC (à minuit tout redevient à faire).Chaque entrée est enrichie automatiquement depuis ClubLog : badge DXpedition, OQRS, lien LiveStream, total de QSO et rythme sur 24 h — rien à configurer. Lit et écrit le format watchlist.json de DXHunter — déposez votre fichier existant dans le dossier data pour le récupérer.",
"TCI (SunSDR) : l'abonnement aux mesures est renouvelé quand la radio annonce qu'elle est prête — envoyé seulement à la connexion, il pouvait tomber pendant l'envoi initial de l'état et être ignoré, laissant la puissance et le ROS vides en émission. Le journal enregistre aussi l'abonnement et les premières trames de mesure, pour distinguer « la radio ne les envoie jamais » de « elles arrivaient et étaient perdues ».",
"Envoyer un spot en split préremplit désormais la fréquence RX — là où la station se trouve réellement — au lieu de la fréquence TX, qui spottait le pile-up cinq au-dessus du DX.",
"Cluster : NOUVEAU SLOT reçoit sa propre couleur — le cyan ciel que la palette du panadapter lui donne déjà, bien distinct du vert POTA et des jaunes. Les puces de filtre NOUVEAU SLOT et NOUVEAU COMTÉ portent désormais les couleurs des badges qu'elles sélectionnent, et le filtre NOUVEAU CALL fonctionne même quand l'option de surlignage par slot est désactivée.",
"Console Elecraft : une rangée de modes — CW, USB, LSB, DATA et DATA RTTY. Les deux boutons DATA règlent aussi le sous-mode du K3 (DATA A pour FT8/FT4, FSK D pour le RTTY) : passer en DATA par le seul mode gardait le sous-mode de la session précédente, et un K3 « en DATA » manipulait le FT8 sans audio.",
"Réglages DX Cluster : « Je chasse le POTA » et « Je chasse le SOTA », cochés par défaut. Décochés, le badge, la couleur et le filtre NOUVEAU POTA disparaissent — un spot nouvelle bande + nouveau POTA affiche seulement NOUVELLE BANDE — et les colonnes de références restent vides.",
"Console Elecraft : le RIT et le XIT utilisent la même commande que les consoles Icom et TCI — boutons ±, molette, valeur tapée, Ctrl+←/→ — et le curseur de puissance avance par pas de 1 W au lieu de 5.",
"Édition groupée : My DXCC, My CQ zone et My ITU zone rejoignent les champs Ma station — valeurs vérifiées contre leurs bornes réelles, vide efface.",
"Cliquer un spot dans le panneau Chase new applique désormais la largeur/zoom du panadapter FlexRadio, comme tout autre clic de spot.",
"FlexRadio : la largeur/zoom du panadapter sapplique désormais de façon fiable au double-clic sur un spot du cluster — le zoom est envoyé après le tune, pour que le suivi du panadapter de SmartSDR lors dun changement de bande ne l’écrase plus."
]
},
{
"version": "0.26.23",
"date": "",
"en": [
"LoTW: the downloaded confirmations list gains a Station column, so a list spanning several callsigns says which one each confirmation belongs to. Shown only when the report actually carries more than the one station.",
"The band maps follow your IARU region (Settings → General): Region 2s 40 m runs to 7300 kHz with phone from 7125 and its 80 m to 4000, Region 3s 80 m to 3900 — the band edges and the CW/digital/phone shading all adjust."
],
"fr": [
"LoTW : la liste des confirmations téléchargées gagne une colonne Station, pour savoir à quel indicatif appartient chaque confirmation quand le téléchargement en couvre plusieurs. Affichée seulement si le rapport en contient effectivement.",
"Les cartes de bande suivent votre région IARU (Réglages → Général) : le 40 m de la Région 2 va jusqu'à 7300 kHz avec la phonie dès 7125 et son 80 m jusqu'à 4000, le 80 m de la Région 3 jusqu'à 3900 — les limites de bande et les zones CW/numérique/phonie s'ajustent."
]
},
{
"version": "0.26.22",
"date": "",
"en": [
"LoTW download: the QSL details (QSL date, grid, state, county) are now optional and off by default — LoTW takes about ten times longer to build that report, twenty minutes against two on the same account, and marking a confirmation needs none of it. Still asked for automatically when adding the QSOs not found in the log.",
"Band map: the tooltip now also names a new prefix or a new grid square. They stay off the 22-pixel colour strip, but leaving them out of the text made the two panels look as though they disagreed — the cluster said NEW PFX about a spot the map called Worked, and both were right. The maps “Worked” also says whose: it is the ENTITY that was worked on that band and mode, not the callsign, which is what made the two readings look contradictory.",
"TCI (SunSDR): clicking a cluster spot no longer needs a second click to get the mode right — the sideband was chosen from the frequency the radio had last reported instead of the one just asked for. The log also names the ExpertSDR version now, and says so when it is older than the 1.5 that panorama spots need.",
"Two screens: OpsLog no longer walks off the desktop. On a monitor placed left of the primary one, the saved position was being added to that monitors own origin at every launch, so the window moved one screen further out each time until it was invisible.",
"CW over TCI: a SunSDR can now be keyed through its own macro keyer — pick TCI as the keyer engine (Settings → CW Keyer) and macros, auto-call and the speed control all work over the link already open, with no WinKeyer and no second serial port. NOT TESTED on the air yet.",
"LoTW upload: a refusal now shows TQSLs own explanation — which contacts were already uploaded, which fell outside the certificates dates — instead of the bare “no QSOs processed”, and names the two settings that cause it.",
"Main tab: the docked cluster now has ONE header row — its title, live count and Filters button sit with Clear filters and Columns, as Recent QSOs beside it already did. The pane is titled DX Cluster.",
"A busy cluster no longer makes the rest of the interface sluggish: incoming spots are grouped into fewer, larger updates as the feed gets faster (up to half a second), instead of redrawing the window twenty times a second. A quiet cluster still shows each spot as it lands.",
"SunSDR console: the meters work. The S-meter, transmit power and SWR are pushed by the radio only to a client that subscribes, and OpsLog never did — it was reading commands ExpertSDR3 does not send.",
"Cluster: the “N new spots” counter no longer jumps to the whole buffer. It was looking for the row it had frozen on, and a station spotted again replaces its row — so the count fell through to “everything is new”.",
"E-mail: a refused SMTP login now says what to do about it — Microsoft 365 and outlook.com have switched off password-based SMTP, and an app password does not bring it back.",
"TCI panorama spots: the colour was sent as a negative number and ExpertSDR dropped every spot in silence. It now goes out as the unsigned ARGB integer the protocol document uses, and the first few spots are written to the log verbatim.",
"Cluster: “Group duplicates” was hiding the same station on OTHER bands and modes — a DXpedition spotted on five bands showed as one line and four slots disappeared. A duplicate is now what it should always have been: the same station on the same band and mode."
],
"fr": [
"Téléchargement LoTW : les détails QSL (date du QSL, locator, état, comté) deviennent optionnels et désactivés par défaut — LoTW met environ dix fois plus longtemps à construire ce rapport, vingt minutes contre deux sur le même compte, et marquer une confirmation n'en a pas besoin. Toujours demandés automatiquement quand on ajoute les QSO absents du log.",
"Carte des bandes : l'infobulle indique aussi un nouveau préfixe ou un nouveau locator. Ils restent hors de la bande de couleur de 22 pixels, mais les omettre du texte donnait l'impression que les deux panneaux se contredisaient — le cluster annonçait NOUVEAU PFX pour un spot que la carte disait contacté, et les deux avaient raison. Le « Contacté » de la carte dit aussi de qui il parle : c'est l'ENTITÉ qui a été contactée sur cette bande et ce mode, pas l'indicatif — d'où l'impression de contradiction.",
"TCI (SunSDR) : cliquer un spot du cluster ne demande plus un second clic pour obtenir le bon mode — la bande latérale était choisie d'après la fréquence encore annoncée par la radio au lieu de celle qu'on venait de demander. Le journal indique aussi la version d'ExpertSDR, et signale si elle est antérieure à la 1.5 qu'exigent les spots sur le panorama.",
"Deux écrans : OpsLog ne s'échappe plus du bureau. Sur un écran placé à gauche de l'écran principal, la position enregistrée était ajoutée à l'origine de cet écran à chaque lancement, si bien que la fenêtre s'éloignait d'un écran à chaque fois jusqu'à devenir invisible.",
"CW en TCI : un SunSDR peut désormais être manipulé par son propre keyer à macros — choisissez TCI comme moteur (Réglages → Manipulateur CW) et les macros, l'appel automatique et le réglage de vitesse passent par la liaison déjà ouverte, sans WinKeyer ni second port série. PAS ENCORE TESTÉ sur l'air.",
"Envoi LoTW : un refus affiche désormais l'explication de TQSL — quels contacts étaient déjà envoyés, lesquels tombaient hors des dates du certificat — au lieu du seul « no QSOs processed », et nomme les deux réglages qui en sont la cause.",
"Onglet Main : le cluster ancré n'a plus qu'UNE ligne d'en-tête — son titre, le compteur live et le bouton Filtres rejoignent Effacer les filtres et Colonnes, comme le faisait déjà la liste des QSO récents à côté. Le panneau s'intitule DX Cluster.",
"Un cluster chargé ne ralentit plus le reste de l'interface : les spots entrants sont regroupés en mises à jour moins nombreuses à mesure que le flux s'accélère (jusqu'à une demi-seconde), au lieu de redessiner la fenêtre vingt fois par seconde. Sur un cluster calme, chaque spot s'affiche toujours dès son arrivée.",
"Console SunSDR : les mesures fonctionnent. Le S-mètre, la puissance et le ROS ne sont envoyés qu'à un client qui s'abonne, ce qu'OpsLog ne faisait pas — il lisait des commandes qu'ExpertSDR3 n'envoie pas.",
"Cluster : le compteur « N nouveaux spots » ne saute plus à la taille du tampon. Il cherchait la ligne sur laquelle il s'était figé, or une station re-spottée remplace sa ligne — le compte basculait donc sur « tout est nouveau ».",
"E-mail : un refus d'authentification SMTP explique désormais quoi faire — Microsoft 365 et outlook.com ont désactivé le SMTP par mot de passe, et un mot de passe d'application ne le rétablit pas.",
"Spots sur le panorama TCI : la couleur partait en nombre négatif et ExpertSDR écartait chaque spot en silence. Elle est désormais envoyée en entier ARGB non signé, comme dans la documentation du protocole, et les premiers spots sont écrits tels quels dans le journal.",
"Cluster : « Grouper les doublons » masquait la même station sur les AUTRES bandes et modes — une expédition spottée sur cinq bandes n'affichait qu'une ligne et quatre créneaux disparaissaient. Un doublon est désormais ce qu'il aurait toujours dû être : la même station sur la même bande et le même mode."
]
},
{
"version": "0.26.21",
"date": "",
"en": [
"Distances can be shown in miles (Settings → General): the cluster and Recent QSOs columns, the map path box, the rotator buttons and the band-opening list all follow, and the column headers name the unit.",
"LoTW download: the report is now counted in megabytes as it arrives, LoTWs \"busy\" answer (HTTP 503) is retried twice instead of failing, and a transfer that stops moving for two minutes says so rather than showing \"working\" indefinitely."
],
"fr": [
"Les distances peuvent s'afficher en miles (Réglages → Général) : les colonnes du cluster et des QSO récents, l'encart du tracé sur la carte, les boutons du rotor et la liste des ouvertures suivent, et l'unité est indiquée dans les en-têtes de colonne.",
"Téléchargement LoTW : le rapport est compté en mégaoctets au fur et à mesure, la réponse « occupé » de LoTW (HTTP 503) est retentée deux fois au lieu d'échouer, et un transfert qui n'avance plus pendant deux minutes le dit au lieu d'afficher « en cours » indéfiniment."
]
},
{
"version": "0.26.20",
"date": "",
"en": [
"Each radio carries its own MY_RIG (Settings → CAT), written on every QSO made with it — ahead of the per-band station in Operating conditions, which says what you planned to use rather than which radio is keying. Left empty, nothing changes.",
"Worked-before matrix: a dot in the corner of a cell now means the callsign you are working has already been worked on that slot, whatever colour the entity status gave the cell. Its two colours (worked / confirmed with this callsign) are in Appearance with the other matrix colours.",
"Icom spectrum scope: the command shape (with or without the main/sub selector) is now worked out from the radios own answers instead of a list of models. A radio that has scope control but no waveform stream over CI-V — the IC-7851 — says so in the panel rather than showing a black rectangle.",
"Elecraft KPA: the status-bar chip now shows the amplifier as connected and switches it between OPERATE and STANDBY like the other brands, and an offline KPA no longer calls itself an Acom.",
"Cluster: a SOTA column, read from the summit reference the SOTA feeds put in the spot comment. Clicking the spot fills the QSOs SOTA award reference, as a POTA spot already did. Turn the column on in Columns. Add cluster.sota.org.uk:7300 as a server to receive the summit spots.",
"Awards: a \"Slots to confirm\" filter and a running count beside the reference total, so the gap between worked and confirmed band-slots — the Challenge difference — can be seen reference by reference instead of only as two numbers.",
"QSL Manager: a QRZ button next to the Paper QSL search, opening the callsign on QRZ.com.",
"LoTW: an \"All my callsigns\" option beside the download. The download is scoped to the profiles own callsign, so a QSO made as a portable or contest call was confirmed at LoTW and never marked here. Confirmations made under a callsign this logbook has never used are skipped, and a suspiciously small report now shows what LoTW actually answered.",
"LoTW download: \"All\" really means all — without a date LoTW answered with a handful of recent confirmations, which looked like a successful download of an empty account. A full account also has time to arrive: the two-minute limit that ended in \"context deadline exceeded\" is now twenty."
],
"fr": [
"Chaque radio porte son propre MY_RIG (Réglages → CAT), inscrit sur chaque QSO fait avec elle — avant la station par bande des Conditions de trafic, qui dit ce qui était prévu et non quelle radio émet. Laissé vide, rien ne change.",
"Matrice des contacts : un point dans le coin d'une case indique que l'indicatif en cours a déjà été contacté sur ce créneau, quelle que soit la couleur donnée par le statut de l'entité. Ses deux couleurs (contacté / confirmé avec cet indicatif) se règlent dans Apparence avec les autres couleurs de la matrice.",
"Scope Icom : la forme des commandes (avec ou sans le sélecteur main/sub) est déduite des réponses de la radio au lieu d'une liste de modèles. Une radio qui pilote son scope mais ne l'envoie pas en CI-V — l'IC-7851 — l'indique dans le panneau au lieu d'afficher un rectangle noir.",
"Elecraft KPA : la pastille de la barre d'état montre enfin l'amplificateur comme connecté et bascule OPERATE / STANDBY comme les autres marques, et un KPA hors ligne ne s'annonce plus comme un Acom.",
"Cluster : une colonne SOTA, lue dans la référence de sommet que les flux SOTA mettent dans le commentaire du spot. Cliquer le spot remplit la référence SOTA du QSO, comme le faisait déjà un spot POTA. Colonne à activer dans Colonnes. Ajoutez le serveur cluster.sota.org.uk:7300 pour recevoir les spots de sommets.",
"Awards : un filtre « Slots à confirmer » et un compteur à côté du total de références, pour voir l'écart entre créneaux contactés et confirmés — la différence du Challenge — référence par référence et non plus seulement en deux chiffres.",
"Gestionnaire QSL : un bouton QRZ à côté de la recherche QSL papier, qui ouvre l'indicatif sur QRZ.com.",
"LoTW : une option « Tous mes indicatifs » à côté du téléchargement. Celui-ci est limité à l'indicatif du profil, si bien qu'un QSO fait sous un indicatif portable ou de contest était confirmé chez LoTW sans jamais être marqué ici. Les confirmations faites sous un indicatif que ce carnet n'a jamais utilisé sont ignorées, et un rapport anormalement petit affiche désormais ce que LoTW a réellement répondu.",
"Téléchargement LoTW : « Tout » veut enfin dire tout — sans date, LoTW ne renvoyait qu'une poignée de confirmations récentes, ce qui ressemblait à un téléchargement réussi d'un compte vide. Un compte complet a aussi le temps d'arriver : la limite de deux minutes, qui finissait en « context deadline exceeded », passe à vingt."
]
},
{
"version": "0.26.19",
"date": "",
"en": [
"Several radios, and one click to change which one is connected. Settings → CAT holds a list — name them, add one (it starts as a copy of the current one), remove one — and the CAT button in the status bar switches between them. The logbook, the callsign and everything else about the station stay exactly as they are, which is what making a profile per radio could not do."
],
"fr": [
"Plusieurs radios, et un clic pour changer celle qui est connectée. Réglages → CAT contient une liste — les nommer, en ajouter une (elle part d'une copie de la courante), en retirer une — et le bouton CAT de la barre d'état passe de l'une à l'autre. Le carnet, l'indicatif et tout le reste de la station ne bougent pas, ce qu'un profil par radio ne permettait pas."
]
},
{
"version": "0.26.18",
"date": "",
"en": [
"Awards: the band matrix shows the bands you have contacts on — no more, and no longer capped at 70cm. It used to list every band the award permits, so DDFM stood there with empty 6m and 70cm columns, and it could not show 23cm at all whatever the award said.",
"Elecraft KPA500 and KPA1500 amplifiers, over serial or — on the KPA1500 — over the network. Operate/standby, on/off, power, SWR, temperature, supply voltage and current, the band, and faults named in plain words rather than as a code. They join the SPE, the Acom and the PowerGenius, so linking several amplifiers works on them too. NEW, AND NOT YET TESTED ON A REAL AMPLIFIER: it is written from Elecraft's programming reference, so please report what it does.",
"The Elecraft amplifiers follow the radio's band by themselves, on the link already open — they have a band command of their own, so no second serial port is involved. It can be turned off for an amplifier wired straight to the radio.",
"The Light and Voyager maps came up stamped 'API KEY REQUIRED' across the middle. Carto now watermarks its key-free tiles, so both views move to Esri, the provider already behind Street and Satellite. Light looks the same; Voyager is now a topographic map and is named Topo — anyone who had it selected keeps it.",
"Ultrabeam / SteppIR over USB: the COM port can be picked from the list again. It used a field you could also type into, and the list could not be selected from at all.",
"A control console for SunSDR / ExpertSDR3, as a tab and as a docked pane: drive and tune drive, mic gain, TUNE, power and SWR while transmitting, volume, mute, squelch, NB, NR, ANF, APF in CW, AGC, filters chosen per mode, RIT and XIT, the VFO lock, and an S-meter reading real dBm. Levels can be dragged, scrolled, stepped or typed. It follows the radio's own window — TCI announces every change, whoever made it.",
"The Elecraft console can be docked as a main-view pane. It always could; the setting simply never listed it.",
"Spot alerts name the right mode. A 30 m FT8 spot raised an alert saying SSB while the cluster list beside it said DATA: the alert engine had its own, coarser band plan, which called everything above 10.130 phone. Both now read the same table, and a frequency the plan does not cover is left unnamed rather than guessed at.",
"Awards: editing an award now refreshes its statistics as well as its grid. Changing which confirmations count — LoTW only, LoTW plus cards — left the whole matrix showing the previous rule's numbers, with nothing to say they were stale.",
"The DXCC statistics show the Challenge, and say what the two totals mean. The Challenge counts confirmed band-slots on ten bands and 60 m is not one of them — which is the whole of the gap against LoTW's figure. The Total column is entities, the last column is band-slots, and both now say so when hovered.",
"Deleted DXCC entities survive an import. A QSO carrying an entity the ARRL has since deleted — Malyj Vysotskij, Czechoslovakia, the German DR and the rest — was being re-stamped from cty.dat, which only knows where a callsign is TODAY: a 2004 R1MVI came back as European Russia and the credit was gone, for a place that can never be worked again. The number in the file is now left alone for those entities."
],
"fr": [
"Diplômes : la matrice des bandes affiche les bandes sur lesquelles on a des contacts — pas davantage, et sans s'arrêter au 70cm. Elle listait toutes les bandes autorisées par le diplôme, si bien que le DDFM restait avec des colonnes 6m et 70cm vides, et ne pouvait pas afficher le 23cm quoi que dise le diplôme.",
"Amplificateurs Elecraft KPA500 et KPA1500, en série ou — pour le KPA1500 — par le réseau. Operate/standby, marche/arrêt, puissance, ROS, température, tension et courant d'alimentation, la bande, et les défauts nommés en clair plutôt qu'en code. Ils rejoignent le SPE, l'Acom et le PowerGenius, donc le couplage de plusieurs amplificateurs fonctionne aussi avec eux. NOUVEAU, ET PAS ENCORE TESTÉ SUR UN VRAI AMPLIFICATEUR : c'est écrit d'après la documentation de programmation d'Elecraft, donc merci de signaler ce que ça donne.",
"Les amplificateurs Elecraft suivent tout seuls la bande de la radio, sur la liaison déjà ouverte — ils ont leur propre commande de bande, donc aucun second port série n'intervient. Désactivable pour un amplificateur câblé directement à la radio.",
"Les cartes Light et Voyager s'affichaient barrées d'un « API KEY REQUIRED ». Carto marque désormais ses tuiles sans clé, donc les deux vues passent chez Esri, le fournisseur déjà derrière Street et Satellite. Light garde son allure ; Voyager devient une carte topographique et s'appelle Topo — ceux qui l'avaient choisie la conservent.",
"Ultrabeam / SteppIR en USB : le port COM se choisit à nouveau dans la liste. Le champ était de ceux où l'on peut aussi taper, et la liste ne se laissait pas sélectionner.",
"Une console de contrôle pour SunSDR / ExpertSDR3, en onglet et en volet ancré : puissance et puissance d'accord, gain micro, ACCORD, puissance et ROS pendant l'émission, volume, muet, squelch, NB, NR, ANF, APF en CW, AGC, filtres proposés selon le mode, RIT et XIT, verrouillage du VFO, et un S-mètre en vrais dBm. Les niveaux se règlent à la souris, à la molette, par pas ou en tapant la valeur. Elle suit la fenêtre de la radio — TCI annonce chaque changement, quel qu'en soit l'auteur.",
"La console Elecraft peut être ancrée comme volet de la vue principale. Elle le pouvait depuis toujours ; le réglage ne la proposait tout simplement pas.",
"Les alertes de spot nomment le bon mode. Un spot FT8 sur 30 m déclenchait une alerte annonçant SSB alors que la liste du cluster juste à côté affichait DATA : le moteur d'alertes avait son propre plan de bandes, plus grossier, qui appelait « phonie » tout ce qui dépassait 10,130. Les deux lisent désormais la même table, et une fréquence hors plan reste sans mode plutôt que devinée.",
"Diplômes : modifier un diplôme actualise désormais ses statistiques et pas seulement sa grille. Changer les confirmations qui comptent — LoTW seul, LoTW plus cartes — laissait toute la matrice afficher les chiffres de la règle précédente, sans rien pour dire qu'ils étaient périmés.",
"Les statistiques DXCC affichent le Challenge et disent ce que sont les deux totaux. Le Challenge compte les créneaux bande confirmés sur dix bandes, dont le 60 m ne fait pas partie — c'est là tout l'écart avec le chiffre de LoTW. La colonne Total, ce sont les entités ; la dernière, les créneaux bande ; les deux le disent au survol.",
"Les entités DXCC supprimées survivent à un import. Un QSO portant une entité depuis supprimée par l'ARRL — Malyj Vysotskij, la Tchécoslovaquie, la RDA et les autres — était réécrit d'après cty.dat, qui ne sait que où se trouve un indicatif AUJOURD'HUI : un R1MVI de 2004 revenait en Russie d'Europe et le crédit disparaissait, pour un endroit qu'on ne pourra plus jamais contacter. Le numéro du fichier est désormais conservé pour ces entités."
]
},
{
"version": "0.26.17",
"date": "",
"en": [
"Awards, RDA district comparison: each disagreement can now be settled on its own row. Click the district you keep — the log's or the database's — and apply. It is written into the contact's CNTY and its award reference, and the settled rows leave the list.",
"The band/mode matrix: a confirmed slot now shows as confirmed. A callsign worked and not confirmed was outranking an entity CONFIRMED on the same band and mode, so a slot that needs nothing was painted as if it still did.",
"CAT sharing: a program connected to OpsLog's rigctl server is told the frequency it is LISTENING on. With split engaged it was given the transmit VFO instead, so a client that reads the dial and writes it back — WSJT-X and its like — could move VFO A when VFO B was turned."
],
"fr": [
"Diplômes, comparaison des districts RDA : chaque divergence se règle désormais sur sa propre ligne. Cliquer le district qu'on garde — celui du log ou celui de la base — puis appliquer. Il est écrit dans le CNTY du contact et dans sa référence de diplôme, et les lignes réglées quittent la liste.",
"Matrice bandes/modes : une case confirmée s'affiche enfin comme confirmée. Un indicatif travaillé et non confirmé l'emportait sur une entité CONFIRMÉE sur la même bande et le même mode, si bien qu'une case qui ne demandait plus rien était peinte comme s'il manquait encore quelque chose.",
"Partage CAT : un programme connecté au serveur rigctl d'OpsLog reçoit la fréquence sur laquelle on ÉCOUTE. En split, c'était le VFO d'émission qui lui était donné, si bien qu'un client qui lit le VFO et le réécrit — WSJT-X et consorts — pouvait déplacer le VFO A quand on tournait le VFO B."
]
},
{ {
"version": "0.26.16", "version": "0.26.16",
"date": "", "date": "",
+441 -73
View File
File diff suppressed because it is too large Load Diff
+50 -2
View File
@@ -47,7 +47,7 @@ function powerLevelLabel(pl?: string): string {
} }
} }
type Amp = { id: string; name: string; type?: string; spe?: any; acom?: any; pgxl?: any }; type Amp = { id: string; name: string; type?: string; spe?: any; acom?: any; kpa?: any; pgxl?: any };
export function AmpCard({ amp, flex, t }: { amp: Amp; flex: any; t: (k: string, v?: any) => string }) { export function AmpCard({ amp, flex, t }: { amp: Amp; flex: any; t: (k: string, v?: any) => string }) {
// Peak-hold so the jittery VITA-49 meters read steadily (own ref per card). // Peak-hold so the jittery VITA-49 meters read steadily (own ref per card).
@@ -64,6 +64,7 @@ export function AmpCard({ amp, flex, t }: { amp: Amp; flex: any; t: (k: string,
const isSPE = !!amp.spe; const isSPE = !!amp.spe;
const isACOM = !!amp.acom; const isACOM = !!amp.acom;
const isKPA = !!amp.kpa;
if (isSPE) { if (isSPE) {
const spe = amp.spe; const spe = amp.spe;
@@ -127,7 +128,7 @@ export function AmpCard({ amp, flex, t }: { amp: Amp; flex: any; t: (k: string,
if (isACOM) { if (isACOM) {
const acom = amp.acom; const acom = amp.acom;
return ( return (
<Card icon={Flame} ckey="amplifier" title={`${t('flxp.amplifier')} · ${amp.name || `ACOM${acom.model ? ' ' + acom.model : ''}`}`} accent="#ea580c"> <Card icon={Flame} ckey="amplifier" title={`${t('flxp.amplifier')} · ${amp.name || `Acom${acom.model ? ' ' + acom.model : ''}`}`} accent="#ea580c">
<div className="flex items-center gap-3 flex-wrap"> <div className="flex items-center gap-3 flex-wrap">
<button type="button" disabled={!acom.connected} <button type="button" disabled={!acom.connected}
onClick={() => AmpOperate(amp.id, !acom.operate).catch(() => {})} onClick={() => AmpOperate(amp.id, !acom.operate).catch(() => {})}
@@ -168,6 +169,53 @@ export function AmpCard({ amp, flex, t }: { amp: Amp; flex: any; t: (k: string,
); );
} }
if (isKPA) {
const kpa = amp.kpa;
return (
<Card icon={Flame} ckey="amplifier" title={`${t('flxp.amplifier')} · ${amp.name || kpa.model || 'Elecraft'}`} accent="#ea580c">
<div className="flex items-center gap-3 flex-wrap">
<button type="button" disabled={!kpa.connected}
onClick={() => AmpOperate(amp.id, !kpa.operate).catch(() => {})}
title={kpa.fault_text ? t('flxp.kpaClearsFault') : undefined}
className={cn('px-4 py-2 rounded-lg text-sm font-extrabold tracking-wide border-2 transition-all disabled:opacity-30',
kpa.operate ? 'bg-warning text-warning-foreground border-warning shadow-[0_0_14px] shadow-warning/50' : 'bg-card text-warning border-warning hover:bg-warning-muted')}>
{kpa.operate ? 'OPERATE' : 'STANDBY'}
</button>
{/* The amplifier answers while its main supplies are off — a sleeping
microcontroller stays awake for exactly that — so ON is offered
over the network as well, unlike the SPE and Acom. */}
<div className="inline-flex rounded-lg overflow-hidden border-2 border-success/70">
<button type="button" disabled={!kpa.connected}
onClick={() => AmpPower(amp.id, true).catch(() => {})}
className="px-3 py-2 text-sm font-bold bg-card text-success hover:bg-success/15 disabled:opacity-30">ON</button>
<button type="button" disabled={!kpa.connected}
onClick={() => AmpPower(amp.id, false).catch(() => {})}
className="px-3 py-2 text-sm font-bold bg-card text-danger border-l-2 border-success/70 hover:bg-danger/15 disabled:opacity-30">OFF</button>
</div>
<span className={cn('inline-flex items-center gap-1.5 text-sm', kpa.connected ? 'text-muted-foreground' : 'text-danger')}>
<span className={cn('size-2 rounded-full', kpa.connected ? 'bg-success' : 'bg-danger')} />
{kpa.connected ? (kpa.tuning ? t('flxp.kpaTuning') : (kpa.power_on ? 'ON' : 'OFF')) : t('flxp.kpaOffline')}
</span>
{kpa.connected && (
<span className="text-sm font-mono text-muted-foreground tabular-nums">
{kpa.band ? `${kpa.band} · ` : ''}{kpa.fwd_w}W · SWR {Number(kpa.swr ?? 0).toFixed(1)} · {kpa.temp_c}°C · {kpa.volt_v}V {kpa.cur_a}A
</span>
)}
<div className="flex-1" />
{kpa.fault_text && (
<span className="px-2 py-1 rounded bg-danger-muted text-danger-muted-foreground text-xs font-bold"> {kpa.fault_text}</span>
)}
</div>
{kpa.connected && (
<MeterBar label={t('flxp.outputPower')} value={Number(kpa.fwd_w) || 0} unit="W"
lo={0} hi={String(kpa.model).includes('500') ? 500 : 1500}
display={`${Number(kpa.fwd_w) || 0} W`}
segColor={(f) => (f > 0.9 ? '#dc2626' : f > 0.75 ? '#f59e0b' : '#ea580c')} />
)}
</Card>
);
}
// PowerGenius XL — OPERATE + meters ride on the Flex; fan mode on the GSCP link. // PowerGenius XL — OPERATE + meters ride on the Flex; fan mode on the GSCP link.
const pg = amp.pgxl || {}; const pg = amp.pgxl || {};
const viaFlex = !!flex?.amp_available; const viaFlex = !!flex?.amp_available;
+27 -9
View File
@@ -15,7 +15,7 @@ import { AmpOperate, AmpPower, AmpPowerLevel, AmpFanMode, FlexAmpOperate } from
// With several amplifiers configured the caller passes a selection ("all" or an // With several amplifiers configured the caller passes a selection ("all" or an
// amp id) chosen from the toolbar icon's dropdown. // amp id) chosen from the toolbar icon's dropdown.
type Amp = { id: string; name: string; type?: string; spe?: any; acom?: any; pgxl?: any }; type Amp = { id: string; name: string; type?: string; spe?: any; acom?: any; kpa?: any; pgxl?: any };
// Full-scale watts for the output bar, from the model string. // Full-scale watts for the output bar, from the model string.
function maxW(model?: string, fallback = 1300): number { function maxW(model?: string, fallback = 1300): number {
@@ -92,27 +92,39 @@ function OperateButton({ operate, disabled, onClick, t }: {
function AmpBlock({ amp, flex, showName, t }: { function AmpBlock({ amp, flex, showName, t }: {
amp: Amp; flex: any; showName: boolean; t: (k: string, v?: any) => string; amp: Amp; flex: any; showName: boolean; t: (k: string, v?: any) => string;
}) { }) {
const spe = amp.spe, acom = amp.acom; const spe = amp.spe, acom = amp.acom, kpaAmp = amp.kpa;
const hold = usePeakHold(); const hold = usePeakHold();
if (spe || acom) { // One block for the three amplifiers OpsLog drives over its own link. They
const s = spe || acom; // report the same handful of things under different names, so the differences
// are named here rather than spread through the markup.
if (spe || acom || kpaAmp) {
const s = spe || acom || kpaAmp;
// The amp reports zero watts on receive, so its TX flag clears the meter as // The amp reports zero watts on receive, so its TX flag clears the meter as
// soon as the operator lets go — and the radio's own flag, when we have one, // soon as the operator lets go — and the radio's own flag, when we have one,
// gets there first (the amp is polled on its own slower cycle). // gets there first (the amp is polled on its own slower cycle).
const txing = typeof flex?.transmitting === 'boolean' ? flex.transmitting : s.tx !== false; const txing = typeof flex?.transmitting === 'boolean' ? flex.transmitting : s.tx !== false;
const w = hold('w', Number(spe ? s.output_w : s.fwd_w) || 0, txing); const w = hold('w', Number(spe ? s.output_w : s.fwd_w) || 0, txing);
const swr = Number(spe ? s.swr_ant : s.swr) || 0; const swr = Number(spe ? s.swr_ant : s.swr) || 0;
const hi = spe ? maxW(s.model) : (Number(s.max_w) || 800); // The full-scale mark. A KPA500 reading against a 1500 W scale would look
// idle at full output, so the model decides it.
const hi = spe ? maxW(s.model)
: kpaAmp ? (String(s.model).includes('500') ? 500 : 1500)
: (Number(s.max_w) || 800);
// Power ON drives the remote-on control lines, so it stays available while // Power ON drives the remote-on control lines, so it stays available while
// the amplifier is off and reporting nothing — but only over a serial link. // the amplifier is off and reporting nothing — but only over a serial link.
const canPowerOn = spe ? (s.connected || s.transport === 'serial') : (s.port_open && s.transport === 'serial'); // A KPA answers ^ON while its main supplies are off — the sleeping
// microcontroller stays awake for exactly that — so power-on is available
// whenever the link itself is up, over serial and over the network alike.
const canPowerOn = spe ? (s.connected || s.transport === 'serial')
: kpaAmp ? !!s.connected
: (s.port_open && s.transport === 'serial');
return ( return (
<div className="h-full flex flex-col gap-1.5"> <div className="h-full flex flex-col gap-1.5">
{showName && ( {showName && (
<div className="flex items-center gap-1.5"> <div className="flex items-center gap-1.5">
<span className={cn('size-1.5 rounded-full shrink-0', s.connected ? 'bg-success shadow-[0_0_6px_rgba(16,185,129,0.8)]' : 'bg-danger')} /> <span className={cn('size-1.5 rounded-full shrink-0', s.connected ? 'bg-success shadow-[0_0_6px_rgba(16,185,129,0.8)]' : 'bg-danger')} />
<span className="text-[10px] font-bold uppercase tracking-wider truncate">{amp.name || (spe ? 'SPE' : 'ACOM')}</span> <span className="text-[10px] font-bold uppercase tracking-wider truncate">{amp.name || (spe ? 'SPE' : kpaAmp ? (s.model || 'KPA') : 'Acom')}</span>
{s.connected && s.band && <span className="ml-auto text-[9px] text-muted-foreground shrink-0">{s.band}</span>} {s.connected && s.band && <span className="ml-auto text-[9px] text-muted-foreground shrink-0">{s.band}</span>}
</div> </div>
)} )}
@@ -155,11 +167,17 @@ function AmpBlock({ amp, flex, showName, t }: {
) : ( ) : (
<div className="text-[10px] text-center text-muted-foreground italic py-1">{t('ampw.offline')}</div> <div className="text-[10px] text-center text-muted-foreground italic py-1">{t('ampw.offline')}</div>
)} )}
{(s.warnings || s.alarms || s.err_text) && ( {(s.warnings || s.alarms || s.err_text || s.fault_text) && (
<div className="rounded-md border border-danger-border bg-danger-muted text-danger-muted-foreground text-[9px] px-1.5 py-0.5 text-center break-words"> <div className="rounded-md border border-danger-border bg-danger-muted text-danger-muted-foreground text-[9px] px-1.5 py-0.5 text-center break-words">
{s.err_text || `${s.warnings || ''} ${s.alarms || ''}`.trim()} {s.fault_text || s.err_text || `${s.warnings || ''} ${s.alarms || ''}`.trim()}
</div> </div>
)} )}
{/* Said where the fault is read, because it is the way out of it: on a
KPA, going to OPERATE clears the current fault — everything except
temperature, which clears by cooling. */}
{kpaAmp && s.fault_text && (
<div className="text-[9px] text-center text-muted-foreground">{t('ampw.kpaClear')}</div>
)}
<PowerMeter label={t('flxp.outputPower')} watts={s.connected ? w : 0} maxWatts={hi} /> <PowerMeter label={t('flxp.outputPower')} watts={s.connected ? w : 0} maxWatts={hi} />
</div> </div>
); );
@@ -127,6 +127,12 @@ function MatrixColorsSection() {
<span className="inline-block w-7 h-5 rounded bg-mx-dx-work" /> <span className="inline-block w-7 h-5 rounded bg-mx-dx-work" />
<span className="inline-block w-7 h-5 rounded bg-mx-none" /> <span className="inline-block w-7 h-5 rounded bg-mx-none" />
<span className="inline-block w-7 h-5 rounded bg-mx-none ring-2 ring-mx-cur ring-inset" /> <span className="inline-block w-7 h-5 rounded bg-mx-none ring-2 ring-mx-cur ring-inset" />
<span className="relative inline-block w-7 h-5 rounded bg-mx-dx-conf">
<span className="absolute top-[4px] right-[4px] size-[5px] rounded-full bg-mx-mark-work ring-1 ring-background" />
</span>
<span className="relative inline-block w-7 h-5 rounded bg-mx-dx-conf">
<span className="absolute top-[4px] right-[4px] size-[5px] rounded-full bg-mx-mark-conf ring-1 ring-background" />
</span>
</div> </div>
<button type="button" onClick={reset} <button type="button" onClick={reset}
+119 -19
View File
@@ -29,7 +29,32 @@ type AwardResult = {
type AwardStatRow = { label: string; cells: number[]; total: number; grand_total: number }; type AwardStatRow = { label: string; cells: number[]; total: number; grand_total: number };
type AwardStats = { code: string; bands: string[]; rows: AwardStatRow[] }; type AwardStats = { code: string; bands: string[]; rows: AwardStatRow[] };
// Fixed band columns for the matrix view (Log4OM-style). // Every band the matrix can show, in the order they belong in.
//
// The columns are the intersection of this with what the award covers, so a
// band missing HERE cannot appear at all whatever the award says — which is how
// DDFM, a French award worked well into the microwaves, ended at 70cm with no
// 23cm column and no way to ask for one.
//
// Mirrors bandOrder in internal/award — the same list in frequency order. The
// two are kept apart because they answer different questions (that one sorts an
// award's own band counts, this one lays out columns), but a band added to one
// belongs in the other.
// The DXCC Challenge counts one point per CONFIRMED entity per band, over ten
// bands — and 60 m is NOT one of them. That is the whole of the gap an operator
// notices between OpsLog and LoTW: 3229 here against 3004 there, and 224 of the
// difference is the 60 m column.
//
// Worked out from the confirmed row rather than asked of the backend, because
// that row IS the answer: the Challenge is its sum over these ten bands.
const CHALLENGE_BANDS = ['160m', '80m', '40m', '30m', '20m', '17m', '15m', '12m', '10m', '6m'];
const ALL_BANDS = ['2190m','630m','160m','80m','60m','40m','30m','20m','17m','15m','12m','10m',
'6m','4m','2m','1.25m','70cm','33cm','23cm','13cm','9cm','6cm','3cm','1.25cm','6mm','4mm','2.5mm','2mm','1mm'];
// What to show when there is nothing to narrow it down: an award with no band
// list and no contacts yet. The classic set — the whole of ALL_BANDS would be
// twenty-nine columns of mostly nothing.
const GRID_BANDS = ['160m','80m','60m','40m','30m','20m','17m','15m','12m','10m','6m','2m','70cm']; const GRID_BANDS = ['160m','80m','60m','40m','30m','20m','17m','15m','12m','10m','6m','2m','70cm'];
// Per-band status for a reference, highest first. // Per-band status for a reference, highest first.
@@ -40,6 +65,19 @@ function cellStatus(r: AwardRef, band: string): CellStatus {
if (r.bands?.includes(band)) return 'worked'; if (r.bands?.includes(band)) return 'worked';
return 'none'; return 'none';
} }
// slotsToConfirm counts the band-slots worked with this reference and not yet
// confirmed on any of them — the QSLs still outstanding, one per cell showing W.
//
// It is the difference the Challenge line makes visible in the aggregate (1832
// worked against 1554 confirmed) without saying WHERE it is. Counted over the
// bands actually on screen, so it always adds up to the columns in front of the
// operator rather than to a band set they filtered out.
function slotsToConfirm(r: AwardRef, bands: string[]): number {
let n = 0;
for (const b of bands) if (cellStatus(r, b) === 'worked') n++;
return n;
}
const CELL_STYLE: Record<CellStatus, string> = { const CELL_STYLE: Record<CellStatus, string> = {
validated: 'bg-success text-success-foreground', validated: 'bg-success text-success-foreground',
confirmed: 'bg-warning text-warning-foreground', confirmed: 'bg-warning text-warning-foreground',
@@ -87,7 +125,7 @@ export function AwardsPanel({ onEditQSO, onAwardsChanged, onPaperQSL }: {
const [refSearch, setRefSearch] = useState(''); const [refSearch, setRefSearch] = useState('');
const [editing, setEditing] = useState(false); const [editing, setEditing] = useState(false);
const [view, setView] = useState<'grid' | 'list' | 'stats'>('grid'); const [view, setView] = useState<'grid' | 'list' | 'stats'>('grid');
const [refFilter, setRefFilter] = useState<'all' | 'worked' | 'notworked' | 'worked_notconf'>('all'); const [refFilter, setRefFilter] = useState<'all' | 'worked' | 'notworked' | 'worked_notconf' | 'slots_notconf'>('all');
// Mode filter, stacked ON TOP of the status one. "Worked on CW but not // Mode filter, stacked ON TOP of the status one. "Worked on CW but not
// confirmed" is two questions at once, and answering only one of them is what // confirmed" is two questions at once, and answering only one of them is what
// sends an operator to a spreadsheet. // sends an operator to a spreadsheet.
@@ -180,26 +218,46 @@ export function AwardsPanel({ onEditQSO, onAwardsChanged, onPaperQSL }: {
useEffect(() => { if (selected) compute(selected); /* eslint-disable-next-line react-hooks/exhaustive-deps */ }, [modeFilter]); useEffect(() => { if (selected) compute(selected); /* eslint-disable-next-line react-hooks/exhaustive-deps */ }, [modeFilter]);
// Bands relevant to the selected award, used by BOTH the grid and the stats // Bands relevant to the selected award, used by BOTH the grid and the stats
// matrix so neither is padded with bands the award doesn't use. Rule: the // matrix so neither is padded with bands nothing was worked on. Rule: the
// award's explicit valid_bands if it has any (e.g. WAPC = 40/20/15/10m); else // bands this operator HAS contacts on for this award; failing that, the
// the bands the operator actually has contacts on (so DXCC, which has no band // award's own list of permitted bands. Empty set = no basis at all → callers
// restriction, shows 160m6m instead of empty VHF/UHF columns). Empty set = // fall back to the classic columns.
// no basis yet → callers fall back to all bands.
const awardBands = useMemo(() => { const awardBands = useMemo(() => {
const vb = (awardList.find((a) => a.code === selected)?.bands ?? []).map((b) => b.toLowerCase()); // The bands with CONTACTS on them come first, whatever the award declares.
if (vb.length > 0) return new Set(vb); //
const worked = (current?.bands ?? []) // It used to take the declared list when there was one, which put up a
// column for every band the award permits — DDFM allows 6m and 70cm, so
// both stood there empty on a station that has never worked a French
// department on either. An always-blank column reads as a gap in the log
// rather than as a band the operator never tried.
const worked = new Set((current?.bands ?? [])
.filter((b) => (b.worked ?? 0) > 0) .filter((b) => (b.worked ?? 0) > 0)
.map((b) => String(b.band).toLowerCase()); .map((b) => String(b.band).toLowerCase()));
return new Set(worked); if (worked.size > 0) return worked;
// Nothing worked yet: the award's own list is the honest answer — it says
// what this award is played on, which is the only thing there is to show.
return new Set((awardList.find((a) => a.code === selected)?.bands ?? []).map((b) => b.toLowerCase()));
}, [awardList, selected, current]); }, [awardList, selected, current]);
const gridBands = useMemo(() => { const gridBands = useMemo(() => {
if (awardBands.size === 0) return GRID_BANDS; if (awardBands.size === 0) return GRID_BANDS;
const filtered = GRID_BANDS.filter((b) => awardBands.has(b)); // Filtered from ALL_BANDS, so a band the award covers gets its column even
// when it is one the classic set never listed.
const filtered = ALL_BANDS.filter((b) => awardBands.has(b));
return filtered.length ? filtered : GRID_BANDS; return filtered.length ? filtered : GRID_BANDS;
}, [awardBands]); }, [awardBands]);
const challenge = useMemo(() => {
if (!stats || selected.toUpperCase() !== 'DXCC') return null;
const row = stats.rows.find((r) => r.label === 'CONFIRMED');
if (!row) return null;
let total = 0;
stats.bands.forEach((b, i) => {
if (CHALLENGE_BANDS.includes(String(b).toLowerCase())) total += Number(row.cells[i]) || 0;
});
return total;
}, [stats, selected]);
// Stats rows to show: drop the mode-category rows (CW / DIGITAL / PHONE) the // Stats rows to show: drop the mode-category rows (CW / DIGITAL / PHONE) the
// award doesn't cover. The "ALL" rows (no suffix) always show; a category row // award doesn't cover. The "ALL" rows (no suffix) always show; a category row
// shows only when the award has no emission restriction or lists that emission. // shows only when the award has no emission restriction or lists that emission.
@@ -259,6 +317,10 @@ export function AwardsPanel({ onEditQSO, onAwardsChanged, onPaperQSL }: {
if (refFilter === 'worked' && !r.worked) return false; if (refFilter === 'worked' && !r.worked) return false;
if (refFilter === 'notworked' && r.worked) return false; if (refFilter === 'notworked' && r.worked) return false;
if (refFilter === 'worked_notconf' && !(r.worked && !r.confirmed)) return false; if (refFilter === 'worked_notconf' && !(r.worked && !r.confirmed)) return false;
// Worked-not-confirmed by SLOT, not by reference: an entity confirmed on
// 20 m still has a 15 m contact waiting for its card, and every filter
// above answers "no" for it because the entity itself is confirmed.
if (refFilter === 'slots_notconf' && slotsToConfirm(r, gridBands) === 0) return false;
if (modeFilter !== 'all' && refFilter !== 'notworked') { if (modeFilter !== 'all' && refFilter !== 'notworked') {
// A reference never worked has no mode, so "not worked" plus a mode is // A reference never worked has no mode, so "not worked" plus a mode is
// a contradiction: the mode filter stands aside rather than emptying // a contradiction: the mode filter stands aside rather than emptying
@@ -294,7 +356,14 @@ export function AwardsPanel({ onEditQSO, onAwardsChanged, onPaperQSL }: {
} }
return a.ref.localeCompare(b.ref, undefined, { numeric: true }) * dir; return a.ref.localeCompare(b.ref, undefined, { numeric: true }) * dir;
}); });
}, [current, refSearch, refFilter, modeFilter, refSort, refSortDir]); }, [current, refSearch, refFilter, modeFilter, refSort, refSortDir, gridBands]);
// The gap itself, over whatever the other filters left on screen: the number
// of cells an operator would have to turn green to close it.
const slotGap = useMemo(
() => filteredRefs.reduce((n, r) => n + slotsToConfirm(r, gridBands), 0),
[filteredRefs, gridBands],
);
// The group column earns its width only when the list actually carries one // The group column earns its width only when the list actually carries one
// (DXCC prefixes, POTA locations); most custom lists have none. For DXCC the // (DXCC prefixes, POTA locations); most custom lists have none. For DXCC the
@@ -319,7 +388,13 @@ export function AwardsPanel({ onEditQSO, onAwardsChanged, onPaperQSL }: {
{t('awp.rescan')} {t('awp.rescan')}
</Button> </Button>
</div> </div>
<AwardEditor open={editing} onClose={() => setEditing(false)} onSaved={() => { setByCode({}); loadList(); onAwardsChanged?.(); }} /> {/* setRescanTick as well as setByCode. The grid was refreshed on save
and the statistics matrix was not, so changing which confirmations
count — LoTW only, LoTW plus cards — left the whole table showing
the previous rule's numbers with nothing to say they were stale.
That is how a setting comes to look as though it does nothing. */}
<AwardEditor open={editing} onClose={() => setEditing(false)}
onSaved={() => { setByCode({}); setRescanTick((t) => t + 1); loadList(); onAwardsChanged?.(); }} />
{/* Quick selector — scales when there are many awards. */} {/* Quick selector — scales when there are many awards. */}
{awardList.length > 0 && ( {awardList.length > 0 && (
<div className="px-2 py-2 border-b border-border/40"> <div className="px-2 py-2 border-b border-border/40">
@@ -417,7 +492,7 @@ export function AwardsPanel({ onEditQSO, onAwardsChanged, onPaperQSL }: {
<Input className="h-8 w-56 pl-7 text-sm" placeholder={t('awp.filterReferences')} value={refSearch} onChange={(e) => setRefSearch(e.target.value)} /> <Input className="h-8 w-56 pl-7 text-sm" placeholder={t('awp.filterReferences')} value={refSearch} onChange={(e) => setRefSearch(e.target.value)} />
</div> </div>
<div className="flex items-center rounded-md border border-border overflow-hidden text-sm"> <div className="flex items-center rounded-md border border-border overflow-hidden text-sm">
{([['all', t('awp.filterAll')], ['worked', t('awp.filterWkd')], ['notworked', t('awp.filterNotWkd')], ['worked_notconf', t('awp.filterWkdNotCfmd')]] as const).map(([k, label]) => ( {([['all', t('awp.filterAll')], ['worked', t('awp.filterWkd')], ['notworked', t('awp.filterNotWkd')], ['worked_notconf', t('awp.filterWkdNotCfmd')], ['slots_notconf', t('awp.filterSlotsNotCfmd')]] as const).map(([k, label]) => (
<button key={k} onClick={() => setRefFilter(k)} <button key={k} onClick={() => setRefFilter(k)}
className={cn('px-2 py-1', refFilter === k ? 'bg-accent font-medium' : 'hover:bg-accent/50 text-muted-foreground')}> className={cn('px-2 py-1', refFilter === k ? 'bg-accent font-medium' : 'hover:bg-accent/50 text-muted-foreground')}>
{label} {label}
@@ -433,6 +508,11 @@ export function AwardsPanel({ onEditQSO, onAwardsChanged, onPaperQSL }: {
))} ))}
</div> </div>
<span className="text-xs text-muted-foreground">{filteredRefs.length} {t('awp.refs')}</span> <span className="text-xs text-muted-foreground">{filteredRefs.length} {t('awp.refs')}</span>
{slotGap > 0 && (
<span className="text-xs text-muted-foreground" title={t('awp.slotGapTip')}>
· <span className="font-semibold text-foreground">{slotGap}</span> {t('awp.slotGap')}
</span>
)}
{/* Only for an award scoped to a DXCC entity. "In this award's {/* Only for an award scoped to a DXCC entity. "In this award's
scope but with no reference" needs a scope to be in: on a scope but with no reference" needs a scope to be in: on a
worldwide reference award — POTA, SOTA, IOTA, WWFF — every worldwide reference award — POTA, SOTA, IOTA, WWFF — every
@@ -473,8 +553,8 @@ export function AwardsPanel({ onEditQSO, onAwardsChanged, onPaperQSL }: {
<tr className="bg-card"> <tr className="bg-card">
<th className="sticky left-0 z-20 bg-card text-left py-1.5 pr-3 font-medium border-b border-border">{t('awp.statistic')}</th> <th className="sticky left-0 z-20 bg-card text-left py-1.5 pr-3 font-medium border-b border-border">{t('awp.statistic')}</th>
{statsBandIdx.map((i) => <th key={stats.bands[i]} className="py-1.5 px-1 font-mono font-medium border-b border-border text-center w-11">{stats.bands[i]}</th>)} {statsBandIdx.map((i) => <th key={stats.bands[i]} className="py-1.5 px-1 font-mono font-medium border-b border-border text-center w-11">{stats.bands[i]}</th>)}
<th className="py-1.5 px-2 font-medium border-b border-border text-center">{t('awp.total')}</th> <th className="py-1.5 px-2 font-medium border-b border-border text-center" title={t('awp.totalHint')}>{t('awp.total')}</th>
<th className="py-1.5 px-2 font-medium border-b border-border text-center">{t('awp.grand')}</th> <th className="py-1.5 px-2 font-medium border-b border-border text-center" title={t('awp.grandHint')}>{t('awp.grand')}</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -493,6 +573,19 @@ export function AwardsPanel({ onEditQSO, onAwardsChanged, onPaperQSL }: {
); );
})} })}
</tbody> </tbody>
{challenge !== null && (
<tfoot>
<tr>
<td className="sticky left-0 bg-card py-1.5 pr-3 font-semibold whitespace-nowrap" title={t('awp.challengeHint')}>
{t('awp.challenge')}
</td>
<td colSpan={statsBandIdx.length} className="py-1.5 text-[11px] text-muted-foreground">
{t('awp.challengeBands')}
</td>
<td className="text-center py-1.5 px-2 font-mono font-bold text-success" colSpan={2}>{challenge}</td>
</tr>
</tfoot>
)}
</table> </table>
)} )}
</div> </div>
@@ -540,7 +633,14 @@ export function AwardsPanel({ onEditQSO, onAwardsChanged, onPaperQSL }: {
<td key={b} className="border-b border-l border-border/30 p-0 text-center"> <td key={b} className="border-b border-l border-border/30 p-0 text-center">
{s === 'none' ? <span className="block w-11 h-7" /> : ( {s === 'none' ? <span className="block w-11 h-7" /> : (
<button <button
className={cn('block w-11 h-7 text-[11px] font-bold', CELL_STYLE[s], 'hover:brightness-110')} className={cn('block w-11 h-7 text-[11px] font-bold', CELL_STYLE[s], 'hover:brightness-110',
// Chasing the slots still to confirm, the
// confirmed ones are context, not the answer:
// a row is kept for its W cells and its V
// cells would otherwise be the loudest thing
// on it. Faded rather than hidden — which
// band is already done is worth seeing.
refFilter === 'slots_notconf' && s !== 'worked' && 'opacity-25')}
title={t('awp.cellTitle', { ref: r.ref, band: b })} title={t('awp.cellTitle', { ref: r.ref, band: b })}
onClick={() => setCell({ ref: r.ref, band: b, name: r.name })} onClick={() => setCell({ ref: r.ref, band: b, name: r.name })}
>{CELL_LABEL[s]}</button> >{CELL_LABEL[s]}</button>
+34 -56
View File
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Minus, Plus, Crosshair, X, PanelLeft, PanelRight } from 'lucide-react'; import { Minus, Plus, Crosshair, X, PanelLeft, PanelRight } from 'lucide-react';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { useI18n } from '@/lib/i18n'; import { useI18n } from '@/lib/i18n';
import { bandRange, bandSegments, subscribeIaruRegion, type SegMode } from '@/lib/bandplan';
import { spotStatusKey, inferSpotMode, spotModeCategory } from '@/lib/spot'; import { spotStatusKey, inferSpotMode, spotModeCategory } from '@/lib/spot';
import { SPOT_MARKERS, activeMarkers } from '@/lib/spotMarkers'; import { SPOT_MARKERS, activeMarkers } from '@/lib/spotMarkers';
import { applySpotDisplay, readSpotDisplayOptions } from '@/lib/spotDisplay'; import { applySpotDisplay, readSpotDisplayOptions } from '@/lib/spotDisplay';
@@ -76,6 +77,13 @@ const BMP_MARKER_LABEL: Record<string, string> = {
new_pota: 'bmp.legendNewPota', new_pota: 'bmp.legendNewPota',
new_county: 'bmp.legendNewCounty', new_county: 'bmp.legendNewCounty',
worked_call: 'bmp.legendWorkedCall', worked_call: 'bmp.legendWorkedCall',
// Not on the strip — the pill is 22 px and a fourth segment turns it into a
// colour code nobody reads — but the TOOLTIP has room, and leaving them out of
// it made the two panels contradict each other: the cluster said NEW PFX about
// a spot the map called "Worked". Both were true (the entity is worked on this
// slot, the WPX prefix never has been) and neither view said so.
new_pfx: 'clg2.newPfx',
new_grid: 'clg2.newGrid',
}; };
interface Props { interface Props {
@@ -107,59 +115,26 @@ interface Props {
keyNav?: boolean; keyNav?: boolean;
} }
const BAND_RANGES: Record<string, [number, number]> = { // Band edges and mode segments come from lib/bandplan, which knows the
'160m': [1800, 2000], // operator's IARU region (Settings → General): a Region 2 operator's 40 m runs
'80m': [3500, 3800], // to 7300 with phone from 7125, and drawing Region 1's plan under their spots
'60m': [5350, 5450], // cut the top 100 kHz of the band off the map.
'40m': [7000, 7200], //
'30m': [10100, 10150], // Sub-band shading colours: these are IDENTITIES (which mode the segment is
'20m': [14000, 14350], // for), not states, so they take categorical hues — never the status tokens.
'17m': [18068, 18168], // All three are drawn from the cool end of the categorical order and laid down
'15m': [21000, 21450], // at low opacity, so the band plan stays background context while the warm
'12m': [24890, 24990], // spot pills keep the foreground. Checked with the palette validator in both
'10m': [28000, 29700], // themes (violet failed the dark protan step; magenta clears every check).
'6m': [50000, 50500], const SEG_COLOR: Record<SegMode, string> = {
'4m': [70000, 70500], cw: 'var(--chart-7)', // magenta
'2m': [144000, 146000], digi: 'var(--chart-1)', // blue
'70cm': [430000, 440000], phone: 'var(--chart-2)', // aqua
}; };
// Sub-band shading: CW / digital / phone.
//
// These are IDENTITIES (which mode the segment is for), not states, so they take
// categorical hues — never the status tokens. They used to use success / info /
// warning, which collided head-on with the spot pills drawn ON TOP of them: amber
// is "new band" in this very component's legend, so the whole SSB portion read as
// a giant "new band" wash. Status colours are reserved for status.
//
// All three are drawn from the COOL end of the categorical order and laid down at
// low opacity, so the band plan stays background context while the warm spot pills
// keep the foreground to themselves.
// Checked with the palette validator in BOTH themes. Violet was the first pick
// for CW and failed on the dark steps — violet and blue land 1.9 ΔE apart for a
// protan reader there, i.e. the same colour. Magenta clears every check on both
// surfaces (worst adjacent pair 13.0 light / 15.9 dark).
const SEG_CW = 'var(--chart-7)'; // magenta
const SEG_DIGI = 'var(--chart-1)'; // blue
const SEG_PHONE = 'var(--chart-2)'; // aqua
// A band-plan wash is CONTEXT, not data: it must stay under the spot pills that // A band-plan wash is CONTEXT, not data: it must stay under the spot pills that
// are read on top of it. // are read on top of it.
const SEG_OPACITY = 0.13; const SEG_OPACITY = 0.13;
const SEGMENT_COLORS: Record<string, [number, number, string][]> = {
'160m': [[1800, 1838, SEG_CW], [1838, 1840, SEG_DIGI], [1840, 2000, SEG_PHONE]],
'80m': [[3500, 3580, SEG_CW], [3580, 3600, SEG_DIGI], [3600, 3800, SEG_PHONE]],
'60m': [[5350, 5450, SEG_PHONE]],
'40m': [[7000, 7040, SEG_CW], [7040, 7100, SEG_DIGI], [7100, 7200, SEG_PHONE]],
'30m': [[10100, 10130, SEG_CW], [10130, 10150, SEG_DIGI]],
'20m': [[14000, 14070, SEG_CW], [14070, 14100, SEG_DIGI], [14100, 14350, SEG_PHONE]],
'17m': [[18068, 18095, SEG_CW], [18095, 18110, SEG_DIGI], [18110, 18168, SEG_PHONE]],
'15m': [[21000, 21070, SEG_CW], [21070, 21150, SEG_DIGI], [21150, 21450, SEG_PHONE]],
'12m': [[24890, 24915, SEG_CW], [24915, 24940, SEG_DIGI], [24940, 24990, SEG_PHONE]],
'10m': [[28000, 28070, SEG_CW], [28070, 28300, SEG_DIGI], [28300, 29700, SEG_PHONE]],
'6m': [[50000, 50100, SEG_CW], [50100, 50500, SEG_PHONE]],
};
// Small coloured dot + label used in the band-map legend strip. // Small coloured dot + label used in the band-map legend strip.
function LegendDot({ cls, colour, label }: { cls?: string; colour?: string; label: string }) { function LegendDot({ cls, colour, label }: { cls?: string; colour?: string; label: string }) {
return ( return (
@@ -297,13 +272,16 @@ export function BandMap({ band, spots, spotStatus: spotStatusRaw, currentFreqHz,
// nothing until the next poll happened to hand over a fresh object. // nothing until the next poll happened to hand over a fresh object.
const dispOpts = readSpotDisplayOptions(); const dispOpts = readSpotDisplayOptions();
const spotStatus = useMemo(() => { const spotStatus = useMemo(() => {
if (!dispOpts.muteWorked && !dispOpts.slotHighlight) return spotStatusRaw; if (!dispOpts.muteWorked && !dispOpts.slotHighlight && dispOpts.chasePota) return spotStatusRaw;
const out: Record<string, SpotStatusEntry> = {}; const out: Record<string, SpotStatusEntry> = {};
for (const k of Object.keys(spotStatusRaw)) out[k] = applySpotDisplay(spotStatusRaw[k], dispOpts) as SpotStatusEntry; for (const k of Object.keys(spotStatusRaw)) out[k] = applySpotDisplay(spotStatusRaw[k], dispOpts) as SpotStatusEntry;
return out; return out;
}, [spotStatusRaw, dispOpts.muteWorked, dispOpts.slotHighlight]); }, [spotStatusRaw, dispOpts.muteWorked, dispOpts.slotHighlight, dispOpts.chasePota]);
const range = BAND_RANGES[band]; // Re-render when the operator changes their IARU region in Settings.
const segments = SEGMENT_COLORS[band] ?? []; const [, setRegionTick] = useState(0);
useEffect(() => subscribeIaruRegion(() => setRegionTick((n) => n + 1)), []);
const range = bandRange(band);
const segments = bandSegments(band).map(([a, b, m]) => [a, b, SEG_COLOR[m]] as [number, number, string]);
const [zoomIdx, setZoomIdx] = useState(() => readZoom(band)); const [zoomIdx, setZoomIdx] = useState(() => readZoom(band));
// The docked map follows the rig, so a band change must bring up THAT band's // The docked map follows the rig, so a band change must bring up THAT band's
// remembered zoom. // remembered zoom.
@@ -737,7 +715,7 @@ export function BandMap({ band, spots, spotStatus: spotStatusRaw, currentFreqHz,
'hover:translate-x-0.5 hover:shadow', 'hover:translate-x-0.5 hover:shadow',
style.pill, style.pill,
)} )}
title={`${p.spot.dx_call}${entry?.country ? ' · ' + entry.country : ''} · ${p.spot.freq_khz.toFixed(1)} kHz · ${statusLabel(st, t)}${markersFor(entry).map((m) => ' · ' + t(BMP_MARKER_LABEL[m.key])).join('')}${p.spot.comment ? ' · ' + p.spot.comment : ''}${p.spot.spotter ? ' · de ' + p.spot.spotter : ''}`} title={`${p.spot.dx_call}${entry?.country ? ' · ' + entry.country : ''} · ${p.spot.freq_khz.toFixed(1)} kHz · ${statusLabel(st, t)}${activeMarkers(entry).map((m) => ' · ' + t(BMP_MARKER_LABEL[m.key])).join('')}${p.spot.comment ? ' · ' + p.spot.comment : ''}${p.spot.spotter ? ' · de ' + p.spot.spotter : ''}`}
> >
{/* Left accent strip. With no extra marker it repeats the status {/* Left accent strip. With no extra marker it repeats the status
colour, exactly as before; otherwise it splits into one colour, exactly as before; otherwise it splits into one
@@ -787,9 +765,9 @@ export function BandMap({ band, spots, spotStatus: spotStatusRaw, currentFreqHz,
))} ))}
{/* Sub-band shading, so the wash behind the pills is never colour-alone. */} {/* Sub-band shading, so the wash behind the pills is never colour-alone. */}
<span className="mx-0.5 opacity-40">|</span> <span className="mx-0.5 opacity-40">|</span>
<LegendDot colour={SEG_CW} label={t("bmp.legendCW")} /> <LegendDot colour={SEG_COLOR.cw} label={t("bmp.legendCW")} />
<LegendDot colour={SEG_DIGI} label={t("bmp.legendData")} /> <LegendDot colour={SEG_COLOR.digi} label={t("bmp.legendData")} />
<LegendDot colour={SEG_PHONE} label={t("bmp.legendPhone")} /> <LegendDot colour={SEG_COLOR.phone} label={t("bmp.legendPhone")} />
</div> </div>
<div className="px-3 py-1 text-[9px] text-muted-foreground bg-muted/30 border-t border-border font-mono text-center shrink-0"> <div className="px-3 py-1 text-[9px] text-muted-foreground bg-muted/30 border-t border-border font-mono text-center shrink-0">
{t('bmp.footerHint')} {t('bmp.footerHint')}
+52 -11
View File
@@ -81,23 +81,44 @@ const STATUS_CLASSES: Record<string, string> = {
// i18n keys the Appearance panel's colour pickers use, so the two can never // i18n keys the Appearance panel's colour pickers use, so the two can never
// disagree about which green is which. swatch = the background class (or a // disagree about which green is which. swatch = the background class (or a
// special ring marker for the current-entry cell). // special ring marker for the current-entry cell).
const LEGEND: { swatch: string; ring?: boolean; label: string }[] = [ const LEGEND: { swatch: string; ring?: boolean; mark?: string; label: string }[] = [
{ swatch: 'bg-mx-call-conf', label: 'mx.callConf' }, { swatch: 'bg-mx-call-conf', label: 'mx.callConf' },
{ swatch: 'bg-mx-call-work', label: 'mx.callWork' }, { swatch: 'bg-mx-call-work', label: 'mx.callWork' },
{ swatch: 'bg-mx-dx-conf', label: 'mx.dxConf' }, { swatch: 'bg-mx-dx-conf', label: 'mx.dxConf' },
{ swatch: 'bg-mx-dx-work', label: 'mx.dxWork' }, { swatch: 'bg-mx-dx-work', label: 'mx.dxWork' },
{ swatch: 'bg-mx-none', label: 'mx.none' }, { swatch: 'bg-mx-none', label: 'mx.none' },
{ swatch: 'bg-mx-none', ring: true, label: 'mx.current' }, { swatch: 'bg-mx-none', ring: true, label: 'mx.current' },
{ swatch: 'bg-mx-none', mark: 'w', label: 'mx.markWork' },
{ swatch: 'bg-mx-none', mark: 'c', label: 'mx.markConf' },
]; ];
function cellTitle(t: (k: string) => string, band: string, cls: string, status: string, current: boolean): string { // CallMark — "this callsign has already been worked on this slot".
//
// Drawn the same way on every cell, whatever colour the entity status gave it:
// the operator learns one shape and reads it without first working out what the
// background means. Only the fill changes, and only with the callsign's own
// state (worked / confirmed) — never with the entity's. The ring is the theme
// background, which is what keeps the dot legible over all five cell colours.
function CallMark({ state = 'w' }: { state?: string }) {
return (
<span
className={cn(
'pointer-events-none absolute top-[4px] right-[4px] size-[5px] rounded-full ring-1 ring-background',
state === 'c' ? 'bg-mx-mark-conf' : 'bg-mx-mark-work',
)}
/>
);
}
function cellTitle(t: (k: string) => string, band: string, cls: string, status: string, current: boolean, call = ''): string {
const desc = const desc =
status === 'call_c' ? t('mx.tipCallConf') : status === 'call_c' ? t('mx.tipCallConf') :
status === 'call_w' ? t('mx.tipCallWork') : status === 'call_w' ? t('mx.tipCallWork') :
status === 'dxcc_c' ? t('mx.tipDxConf') : status === 'dxcc_c' ? t('mx.tipDxConf') :
status === 'dxcc_w' ? t('mx.tipDxWork') : status === 'dxcc_w' ? t('mx.tipDxWork') :
t('mx.tipNone'); t('mx.tipNone');
return `${band} ${cls}: ${desc}${current ? ' — ' + t('mx.current') : ''}`; const mine = call === 'c' ? t('mx.tipThisCallConf') : call === 'w' ? t('mx.tipThisCall') : '';
return `${band} ${cls}: ${desc}${mine ? ' — ' + mine : ''}${current ? ' — ' + t('mx.current') : ''}`;
} }
export function BandSlotGrid({ wb, busy, currentBand, currentMode, bands, hasCall = true, lat, lon, forCall, onEditQso }: Props) { export function BandSlotGrid({ wb, busy, currentBand, currentMode, bands, hasCall = true, lat, lon, forCall, onEditQso }: Props) {
@@ -126,6 +147,16 @@ export function BandSlotGrid({ wb, busy, currentBand, currentMode, bands, hasCal
return m; return m;
}, [wb]); }, [wb]);
// Worked-with-this-callsign, per cell — carried separately by the backend
// because collapsing it into the status is what hid it.
const callMap = useMemo(() => {
const m = new Map<string, string>();
for (const s of wb?.band_status ?? []) {
if ((s as any).call) m.set(`${s.band}|${s.class}`, (s as any).call);
}
return m;
}, [wb]);
// "Newness" of the current band+mode entry, for the award/DX-chase badges. // "Newness" of the current band+mode entry, for the award/DX-chase badges.
// Derived straight from the entity's real band_status (all bands it was // Derived straight from the entity's real band_status (all bands it was
// worked on — not just the operator's configured column list). // worked on — not just the operator's configured column list).
@@ -211,11 +242,11 @@ export function BandSlotGrid({ wb, busy, currentBand, currentMode, bands, hasCal
return ( return (
<section <section
className={cn( className={cn(
'flex items-center gap-4 px-3 py-2 flex-wrap shrink-0', 'flex items-center gap-2 px-2 py-2 flex-wrap shrink-0',
newOne && 'bg-gradient-to-br from-warning-muted to-warning-muted rounded-lg', newOne && 'bg-gradient-to-br from-warning-muted to-warning-muted rounded-lg',
)} )}
> >
<div className="flex items-center gap-2 min-w-[220px] flex-1"> <div className="flex items-center gap-2 min-w-0 flex-1">
{newOne ? ( {newOne ? (
<> <>
<Badge className="bg-warning text-warning-foreground gap-1 px-3 py-1 text-[11px]"> <Badge className="bg-warning text-warning-foreground gap-1 px-3 py-1 text-[11px]">
@@ -238,7 +269,7 @@ export function BandSlotGrid({ wb, busy, currentBand, currentMode, bands, hasCal
{forCall} {forCall}
</Badge> </Badge>
)} )}
<Badge className="bg-primary text-primary-foreground px-3 py-1 text-xs normal-case font-semibold tracking-normal"> <Badge className="bg-primary text-primary-foreground px-2 py-0.5 text-xs normal-case font-semibold tracking-normal leading-tight">
{dxccName || `DXCC #${dxcc}`} {dxccName || `DXCC #${dxcc}`}
</Badge> </Badge>
{mwBadge} {mwBadge}
@@ -308,21 +339,29 @@ export function BandSlotGrid({ wb, busy, currentBand, currentMode, bands, hasCal
</th> </th>
{cols.map((b) => { {cols.map((b) => {
const st = statusMap.get(`${b.tag}|${cls}`) ?? ''; const st = statusMap.get(`${b.tag}|${cls}`) ?? '';
// The same cell's other answer: worked with THIS callsign
// here. The status above is the entity's, and a confirmed
// entity outranks a worked call — so chasing a DXpedition,
// the cell could say "confirmed" about a contact made years
// ago and nothing about the one made this morning.
const mine = callMap.get(`${b.tag}|${cls}`) ?? '';
const isCurrent = hasCall && b.tag === currentBand && classCurrent; const isCurrent = hasCall && b.tag === currentBand && classCurrent;
return ( return (
<td <td
key={b.tag} key={b.tag}
title={cellTitle(t, b.tag, cls, st, isCurrent) + (st ? ' — ' + t('mx.tipClick') : '')} title={cellTitle(t, b.tag, cls, st, isCurrent, mine) + (st ? ' — ' + t('mx.tipClick') : '')}
onClick={st ? () => setSlot({ band: b.tag, cls }) : undefined} onClick={st ? () => setSlot({ band: b.tag, cls }) : undefined}
className={cn( className={cn(
'w-[28px] h-[24px] rounded transition-colors p-0', 'relative w-[28px] h-[24px] rounded transition-colors p-0',
st ? STATUS_CLASSES[st] : 'bg-mx-none', st ? STATUS_CLASSES[st] : 'bg-mx-none',
// Only a filled cell has anything to show — an empty one // Only a filled cell has anything to show — an empty one
// stays inert rather than opening a "no QSOs" dialog. // stays inert rather than opening a "no QSOs" dialog.
st && 'cursor-pointer hover:brightness-110', st && 'cursor-pointer hover:brightness-110',
isCurrent && 'ring-2 ring-mx-cur ring-inset', isCurrent && 'ring-2 ring-mx-cur ring-inset',
)} )}
/> >
{mine ? <CallMark state={mine} /> : null}
</td>
); );
})} })}
</tr> </tr>
@@ -337,11 +376,13 @@ export function BandSlotGrid({ wb, busy, currentBand, currentMode, bands, hasCal
<span key={l.label} className="flex items-center gap-1.5 text-[10px] text-muted-foreground"> <span key={l.label} className="flex items-center gap-1.5 text-[10px] text-muted-foreground">
<span <span
className={cn( className={cn(
'inline-block size-3 rounded shrink-0', 'relative inline-block size-3 rounded shrink-0',
l.swatch, l.swatch,
l.ring && 'ring-2 ring-mx-cur ring-inset', l.ring && 'ring-2 ring-mx-cur ring-inset',
)} )}
/> >
{l.mark ? <CallMark state={l.mark} /> : null}
</span>
{t(l.label)} {t(l.label)}
</span> </span>
))} ))}
@@ -60,6 +60,9 @@ const FIELDS: FieldDef[] = [
// No promoted column: written into extras_json (see qso.bulkEditableExtras). // No promoted column: written into extras_json (see qso.bulkEditableExtras).
{ id: 'owner_callsign', label: 'bulk.fOwnerCallsign', group: 'My station', kind: 'text', upper: true }, { id: 'owner_callsign', label: 'bulk.fOwnerCallsign', group: 'My station', kind: 'text', upper: true },
{ id: 'my_grid', label: 'bulk.fMyGrid', group: 'My station', kind: 'text', upper: true }, { id: 'my_grid', label: 'bulk.fMyGrid', group: 'My station', kind: 'text', upper: true },
{ id: 'my_dxcc', label: 'bulk.fMyDxcc', group: 'My station', kind: 'text' },
{ id: 'my_cq_zone', label: 'bulk.fMyCqZone', group: 'My station', kind: 'text' },
{ id: 'my_itu_zone', label: 'bulk.fMyItuZone', group: 'My station', kind: 'text' },
{ id: 'my_antenna', label: 'bulk.fMyAntenna', group: 'My station', kind: 'text' }, { id: 'my_antenna', label: 'bulk.fMyAntenna', group: 'My station', kind: 'text' },
{ id: 'my_rig', label: 'bulk.fMyRig', group: 'My station', kind: 'text' }, { id: 'my_rig', label: 'bulk.fMyRig', group: 'My station', kind: 'text' },
{ id: 'my_street', label: 'bulk.fMyStreet', group: 'My station', kind: 'text' }, { id: 'my_street', label: 'bulk.fMyStreet', group: 'My station', kind: 'text' },
+2 -1
View File
@@ -10,6 +10,7 @@
// new is being decoded on FT8/FT4/JS8 near here — not that the band is dead. // new is being decoded on FT8/FT4/JS8 near here — not that the band is dead.
import { useEffect, useMemo, useState } from 'react'; import { useEffect, useMemo, useState } from 'react';
import { Radar, Loader2, X } from 'lucide-react'; import { Radar, Loader2, X } from 'lucide-react';
import { formatDistance } from '@/lib/units';
import { useI18n } from '@/lib/i18n'; import { useI18n } from '@/lib/i18n';
import { markerColour } from '@/lib/spotMarkers'; import { markerColour } from '@/lib/spotMarkers';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
@@ -186,7 +187,7 @@ export function ChaseNewPanel({ onPick, onClose }: Props) {
title={[ title={[
s.country, s.country,
s.grid, s.grid,
s.dist_km ? `${s.dist_km} km` : '', s.dist_km ? formatDistance(s.dist_km) : '',
s.freq_hz ? `${(s.freq_hz / 1000).toFixed(1)} kHz` : '', s.freq_hz ? `${(s.freq_hz / 1000).toFixed(1)} kHz` : '',
].filter(Boolean).join(' · ')} ].filter(Boolean).join(' · ')}
> >
+71 -19
View File
@@ -13,8 +13,9 @@ import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox'; import { Checkbox } from '@/components/ui/checkbox';
import { cleanSpotter, inferSpotMode, spotStatusKey } from '@/lib/spot'; import { cleanSpotter, inferSpotMode, spotStatusKey } from '@/lib/spot';
import { markerColour } from '@/lib/spotMarkers'; import { markerColour } from '@/lib/spotMarkers';
import { applySpotDisplay, readSpotDisplayOptions } from '@/lib/spotDisplay'; import { applySpotDisplay, chasePota, chaseSota, readSpotDisplayOptions } from '@/lib/spotDisplay';
import { loadLocal, loadRemote, saveState, seedLocal, whenGridPrefsReady } from '@/lib/gridPrefs'; import { loadLocal, loadRemote, saveState, seedLocal, whenGridPrefsReady } from '@/lib/gridPrefs';
import { distanceUnit, distanceValue, subscribeDistanceUnit } from '@/lib/units';
import { useI18n } from '@/lib/i18n'; import { useI18n } from '@/lib/i18n';
type TFn = (key: string, vars?: Record<string, string | number>) => string; type TFn = (key: string, vars?: Record<string, string | number>) => string;
@@ -45,6 +46,7 @@ export type ClusterSpot = {
raw: string; raw: string;
repeats?: number; repeats?: number;
pota_ref?: string; pota_ref?: string;
sota_ref?: string;
pota_name?: string; pota_name?: string;
}; };
@@ -63,6 +65,9 @@ export type SpotStatusEntry = {
state?: string; state?: string;
new_pota?: boolean; new_pota?: boolean;
new_pfx?: boolean; new_pfx?: boolean;
unconf_status?: boolean;
unconf_pfx?: boolean;
unconf_cty?: boolean;
pfx?: string; pfx?: string;
// lotw: the DX uploads to LoTW, per ARRL user list. Inert until downloaded. // lotw: the DX uploads to LoTW, per ARRL user list. Inert until downloaded.
lotw?: boolean; lotw?: boolean;
@@ -82,6 +87,11 @@ type Props = {
// stray click while looking took the operator off the station they were // stray click while looking took the operator off the station they were
// working. Looking and going are now two different gestures. // working. Looking and going are now two different gestures.
onSpotSelect?: (s: ClusterSpot) => void; onSpotSelect?: (s: ClusterSpot) => void;
// Anything the caller wants on the LEFT of the toolbar — the pane's title, its
// live count, its Filters button. Docked in a pane, the title used to sit on a
// row of its own above this one, so the cluster ate two lines of a short pane
// where Recent QSOs beside it ate one. Reported by VK4DX.
headerLeft?: React.ReactNode;
}; };
const COL_STATE_KEY = 'hamlog.clusterColState.v1'; const COL_STATE_KEY = 'hamlog.clusterColState.v1';
@@ -141,6 +151,12 @@ function statusFor(p: any): SpotStatusEntry | undefined {
// filled pfx → new prefix filled POTA → new park filled county → new county // filled pfx → new prefix filled POTA → new park filled county → new county
// blue call → already worked (not a novelty, so text only) // blue call → already worked (not a novelty, so text only)
const NEW = 'var(--warning)'; // yellow: something here is new const NEW = 'var(--warning)'; // yellow: something here is new
// NEW SLOT gets its own hue. It shared the amber NEW family while the NEW PFX
// marker sits in caution yellow — two different facts, two near-identical
// colours in the same cell. Sky cyan, the exact colour the panadapter palette
// ships for new-slot (#5AC8FA), so the two views tell one story — and clearly
// apart from the POTA green the first attempt (aqua) sat next to.
const NEWSLOT = '#5AC8FA';
const WKD = 'var(--info)'; // blue: this callsign is already in the log const WKD = 'var(--info)'; // blue: this callsign is already in the log
// FILLING the cell that carries the fact, rather than only tinting its text. // FILLING the cell that carries the fact, rather than only tinting its text.
@@ -183,9 +199,10 @@ function statusColor(s: SpotStatusEntry | undefined): string | null {
case 'new-band-mode': case 'new-band-mode':
case 'new-band': case 'new-band':
case 'new-mode': case 'new-mode':
case 'new-slot':
case 'new-call': case 'new-call':
return NEW; return NEW;
case 'new-slot':
return NEWSLOT;
default: default:
return s?.worked_call ? WKD : null; return s?.worked_call ? WKD : null;
} }
@@ -290,13 +307,15 @@ const makeColCatalog = (t: TFn): ColEntry[] => [
: s?.status === 'new-slot' ? t('clg2.newSlot') : s?.status === 'new-slot' ? t('clg2.newSlot')
: s?.status === 'new-call' ? t('clg2.newCall') : s?.status === 'new-call' ? t('clg2.newCall')
: t('clg2.wkdCall'); : t('clg2.wkdCall');
parts.push({ text: label, color: main }); // Dimmed when the need is only a missing confirmation — the grid's
// own convention, now spoken by every category.
parts.push(s?.unconf_status ? { text: label, color: main, dim: true } : { text: label, color: main });
} }
// Colours from lib/spotMarkers — shared with the band map so a marker is // Colours from lib/spotMarkers — shared with the band map so a marker is
// never one colour here and another there. // never one colour here and another there.
if (s?.new_county) parts.push({ text: t('clg2.newCounty'), color: markerColour('new_county') }); if (s?.new_county) parts.push({ text: t('clg2.newCounty'), color: markerColour('new_county'), dim: !!s?.unconf_cty });
if (s?.new_pota) parts.push({ text: t('clg2.newPota'), color: markerColour('new_pota') }); if (s?.new_pota) parts.push({ text: t('clg2.newPota'), color: markerColour('new_pota') });
if (s?.new_pfx) parts.push({ text: t('clg2.newPfx'), color: markerColour('new_pfx') }); if (s?.new_pfx) parts.push({ text: t('clg2.newPfx'), color: markerColour('new_pfx'), dim: !!s?.unconf_pfx });
// Worked-but-unconfirmed is a QSL to chase, not a QSO to make. Same hue // Worked-but-unconfirmed is a QSL to chase, not a QSO to make. Same hue
// held back, so it reads as "less" of the same thing rather than a // held back, so it reads as "less" of the same thing rather than a
// different fact — and the label says which. // different fact — and the label says which.
@@ -329,13 +348,26 @@ const makeColCatalog = (t: TFn): ColEntry[] => [
}, },
{ {
group: 'Spot', label: t('clg2.c.pota'), colId: 'pota', group: 'Spot', label: t('clg2.c.pota'), colId: 'pota',
headerName: t('clg2.c.pota'), field: 'pota_ref' as any, width: 92, cellClass: 'font-mono', headerName: t('clg2.c.pota'), width: 92, cellClass: 'font-mono',
// Through a valueGetter so the chase switch empties the column live.
valueGetter: (p: any) => (chasePota() ? p.data?.pota_ref ?? '' : ''),
defaultVisible: true, defaultVisible: true,
cellStyle: (p: any) => (statusFor(p)?.new_pota cellStyle: (p: any) => (statusFor(p)?.new_pota
? fillStyle(markerColour('new_pota')) ? fillStyle(markerColour('new_pota'))
: { color: 'var(--success)' }) as any, : { color: 'var(--success)' }) as any,
tooltipValueGetter: (p: any) => (p.data?.pota_name ? t('clg2.tipPota', { name: p.data.pota_name }) : undefined), tooltipValueGetter: (p: any) => (p.data?.pota_name ? t('clg2.tipPota', { name: p.data.pota_name }) : undefined),
}, },
{
// SOTA sits next to POTA and reads the same way. The reference comes from the
// spot's comment, so it is present on the SOTA feeds and empty elsewhere —
// which is why the column is off by default rather than an empty column for
// everyone who does not watch summits.
group: 'Spot', label: t('clg2.c.sota'), colId: 'sota',
headerName: t('clg2.c.sota'), width: 100, cellClass: 'font-mono',
valueGetter: (p: any) => (chaseSota() ? p.data?.sota_ref ?? '' : ''),
defaultVisible: false,
cellStyle: () => ({ color: 'var(--success)' }) as any,
},
{ {
group: 'Spot', label: t('clg2.c.freq'), colId: 'freq', group: 'Spot', label: t('clg2.c.freq'), colId: 'freq',
headerName: t('clg2.c.freq'), field: 'freq_khz' as any, width: 95, type: 'rightAligned', cellClass: 'font-mono', headerName: t('clg2.c.freq'), field: 'freq_khz' as any, width: 95, type: 'rightAligned', cellClass: 'font-mono',
@@ -432,8 +464,13 @@ const makeColCatalog = (t: TFn): ColEntry[] => [
}, },
{ {
group: 'Geo', label: t('clg2.c.distance_km'), colId: 'distance_km', group: 'Geo', label: t('clg2.c.distance_km'), colId: 'distance_km',
headerName: t('clg2.h.distance_km'), field: 'distance_km' as any, width: 80, type: 'rightAligned', cellClass: 'font-mono', // The header carries the unit, so the cells stay bare numbers and the
valueFormatter: (p) => p.value ? String(p.value) : '', // column still sorts on the km the backend sent — converting the VALUE
// would sort miles as if they were kilometres either way, but it would
// also round twice.
headerName: t('clg2.h.distance_km') + ' (' + distanceUnit() + ')',
field: 'distance_km' as any, width: 90, type: 'rightAligned', cellClass: 'font-mono',
valueFormatter: (p) => p.value ? String(distanceValue(p.value)) : '',
comparator: (a, b) => (a ?? 0) - (b ?? 0), comparator: (a, b) => (a ?? 0) - (b ?? 0),
}, },
{ {
@@ -506,13 +543,15 @@ const GROUP_ORDER = ['Spot', 'Geo'];
const CLG_GRP_KEYS: Record<string, string> = { Spot: 'clg2.grpSpot', Geo: 'clg2.grpGeo' }; const CLG_GRP_KEYS: Record<string, string> = { Spot: 'clg2.grpSpot', Geo: 'clg2.grpGeo' };
const groupLabel = (t: TFn, g: string): string => t(CLG_GRP_KEYS[g] ?? g); const groupLabel = (t: TFn, g: string): string => t(CLG_GRP_KEYS[g] ?? g);
export function ClusterGrid({ rows, spotStatus, onSpotClick, onSpotSelect }: Props) { export function ClusterGrid({ rows, spotStatus, onSpotClick, onSpotSelect, headerLeft }: Props) {
const { t } = useI18n(); const { t } = useI18n();
const gridRef = useRef<any>(null); const gridRef = useRef<any>(null);
const [pickerOpen, setPickerOpen] = useState(false); const [pickerOpen, setPickerOpen] = useState(false);
// Localized column catalog — rebuilt when the language changes. // Localized column catalog — rebuilt when the language changes.
const COL_CATALOG = useMemo(() => makeColCatalog(t), [t]); const [distUnit, setDistUnit] = useState(distanceUnit);
useEffect(() => subscribeDistanceUnit(() => setDistUnit(distanceUnit())), []);
const COL_CATALOG = useMemo(() => makeColCatalog(t), [t, distUnit]);
// A rebuild makes AG Grid re-apply every colDef hide/width DEFAULT and fire the // A rebuild makes AG Grid re-apply every colDef hide/width DEFAULT and fire the
// matching column events. Without this guard those events were persisted, so a // matching column events. Without this guard those events were persisted, so a
@@ -603,16 +642,27 @@ export function ClusterGrid({ rows, spotStatus, onSpotClick, onSpotSelect }: Pro
const [held, setHeld] = useState<ClusterSpot[] | null>(null); const [held, setHeld] = useState<ClusterSpot[] | null>(null);
const shown = held ?? rows; const shown = held ?? rows;
// How many arrived since the freeze. Counted by finding the frozen top row in // How many arrived since the freeze — counted by TIME, not by finding the
// the live list rather than by comparing lengths: the list is a ring buffer, // frozen top row again.
// so once it is full the length stops growing and a length comparison would //
// report nothing new for the rest of the evening. // Looking for that row was wrong in the ordinary case: a station spotted again
const spotID = (r: ClusterSpot) => `${(r as any).received_at}-${r.dx_call}-${(r as any).source_id}`; // REPLACES its row (that is the de-dupe), so the row we froze on disappears
// from the live list the moment somebody re-spots it — and the count fell
// through to "everything is new", jumping from 4 to the buffer cap. Reported
// as "it shows 4, 5 new spots and then 500 all at once".
//
// A timestamp survives both the replacement and the ring buffer, which was the
// reason the length was not used either.
const spotTime = (r: ClusterSpot) => Date.parse(String((r as any).received_at ?? '')) || 0;
const waiting = useMemo(() => { const waiting = useMemo(() => {
if (!held || held.length === 0) return 0; if (!held || held.length === 0) return 0;
const top = spotID(held[0]); const since = spotTime(held[0]);
const i = rows.findIndex((r) => spotID(r) === top); if (!since) return 0; // no usable timestamp — say nothing rather than a number
return i < 0 ? rows.length : i; // fell out of the buffer: everything is new let n = 0;
for (const r of rows) {
if (spotTime(r) > since) n++;
}
return n;
}, [held, rows]); }, [held, rows]);
const onBodyScroll = (e: { top: number }) => { const onBodyScroll = (e: { top: number }) => {
@@ -670,7 +720,9 @@ export function ClusterGrid({ rows, spotStatus, onSpotClick, onSpotSelect }: Pro
return ( return (
<> <>
<div className="flex items-center justify-end gap-2 px-2.5 py-1 border-b border-border/60 bg-muted/20"> <div className="flex items-center gap-2 px-2.5 py-1 border-b border-border/60 bg-muted/20">
{headerLeft}
<div className="flex-1" />
<Button variant="ghost" size="sm" className="h-7 text-[11px]" onClick={() => gridRef.current?.api?.setFilterModel(null)} <Button variant="ghost" size="sm" className="h-7 text-[11px]" onClick={() => gridRef.current?.api?.setFilterModel(null)}
title={t('clg2.clearFiltersTitle')}> title={t('clg2.clearFiltersTitle')}>
<FilterX className="size-3.5" /> {t('clg2.clearFilters')} <FilterX className="size-3.5" /> {t('clg2.clearFilters')}
+63 -17
View File
@@ -72,8 +72,14 @@ type StatusEntry = {
new_pota?: boolean; new_pota?: boolean;
new_pfx?: boolean; new_pfx?: boolean;
new_grid?: boolean; new_grid?: boolean;
new_state?: boolean;
unconf_status?: boolean;
unconf_pfx?: boolean;
unconf_cty?: boolean;
unconf_state?: boolean;
// "new" = never worked, "unconf" = worked and awaiting a confirmation. // "new" = never worked, "unconf" = worked and awaiting a confirmation.
grid_state?: string; grid_state?: string;
state?: string;
grid?: string; grid?: string;
lotw?: boolean; lotw?: boolean;
}; };
@@ -112,7 +118,7 @@ interface Props {
// //
// All off means no filtering at all: this is a decode LOG first, and a panel // All off means no filtering at all: this is a decode LOG first, and a panel
// that starts by hiding most of the band would be lying about what is on it. // that starts by hiding most of the band would be lying about what is on it.
type NewCat = 'dxcc' | 'band' | 'mode' | 'slot' | 'pfx' | 'grid' | 'pota' | 'cty'; type NewCat = 'dxcc' | 'band' | 'mode' | 'slot' | 'pfx' | 'grid' | 'pota' | 'cty' | 'state';
const NEW_CATS: { key: NewCat; label: string; colour: string }[] = [ const NEW_CATS: { key: NewCat; label: string; colour: string }[] = [
{ key: 'dxcc', label: 'dec.stNew', colour: 'var(--success)' }, { key: 'dxcc', label: 'dec.stNew', colour: 'var(--success)' },
@@ -123,6 +129,7 @@ const NEW_CATS: { key: NewCat; label: string; colour: string }[] = [
{ key: 'grid', label: 'dec.bgGrid', colour: markerColour('new_grid') }, { key: 'grid', label: 'dec.bgGrid', colour: markerColour('new_grid') },
{ key: 'pfx', label: 'dec.bgPfx', colour: markerColour('new_pfx') }, { key: 'pfx', label: 'dec.bgPfx', colour: markerColour('new_pfx') },
{ key: 'cty', label: 'dec.bgCounty', colour: markerColour('new_county') }, { key: 'cty', label: 'dec.bgCounty', colour: markerColour('new_county') },
{ key: 'state', label: 'dec.bgState', colour: markerColour('new_state') },
]; ];
// catsOf lists everything a decode is new for. A station can be several at once // catsOf lists everything a decode is new for. A station can be several at once
@@ -143,6 +150,7 @@ function catsOf(e: StatusEntry | undefined): Set<NewCat> {
if (e.new_grid) out.add('grid'); if (e.new_grid) out.add('grid');
if (e.new_pfx) out.add('pfx'); if (e.new_pfx) out.add('pfx');
if (e.new_county) out.add('cty'); if (e.new_county) out.add('cty');
if (e.new_state) out.add('state');
return out; return out;
} }
@@ -227,7 +235,7 @@ const CELL_LAST = 'flex items-center min-w-0 px-2 gap-1 overflow-hidden';
// One declaration per column, in display order: the header, the widths and the // One declaration per column, in display order: the header, the widths and the
// resize handles all read from this, so a column cannot be resized in the header // resize handles all read from this, so a column cannot be resized in the header
// and stay the old width in the body. // and stay the old width in the body.
type ColKey = 'time' | 'snr' | 'dt' | 'freq' | 'band' | 'mode' | 'msg' | 'grid' | 'country' | 'status'; type ColKey = 'time' | 'snr' | 'dt' | 'freq' | 'band' | 'mode' | 'msg' | 'grid' | 'state' | 'country' | 'status';
const COLS: { key: ColKey; tkey: string; def: number; min: number }[] = [ const COLS: { key: ColKey; tkey: string; def: number; min: number }[] = [
{ key: 'time', tkey: 'dec.colTime', def: 64, min: 44 }, { key: 'time', tkey: 'dec.colTime', def: 64, min: 44 },
{ key: 'snr', tkey: 'dec.colSnr', def: 50, min: 36 }, { key: 'snr', tkey: 'dec.colSnr', def: 50, min: 36 },
@@ -241,9 +249,26 @@ const COLS: { key: ColKey; tkey: string; def: number; min: number }[] = [
// The grid was carried and shown nowhere: it drives the NEW GRID badge, and // The grid was carried and shown nowhere: it drives the NEW GRID badge, and
// an operator chasing squares could see the verdict but never the square. // an operator chasing squares could see the verdict but never the square.
{ key: 'grid', tkey: 'dec.colGrid', def: 62, min: 46 }, { key: 'grid', tkey: 'dec.colGrid', def: 62, min: 46 },
// For the WAS chasers: the badge carries the two letters, the name spells
// them out — "SD" alone is a quiz for a European.
{ key: 'state', tkey: 'dec.colState', def: 120, min: 56 },
{ key: 'country', tkey: 'dec.colCountry', def: 140, min: 70 }, { key: 'country', tkey: 'dec.colCountry', def: 140, min: 70 },
{ key: 'status', tkey: 'dec.colStatus', def: 186, min: 80 }, { key: 'status', tkey: 'dec.colStatus', def: 186, min: 80 },
]; ];
const US_STATES: Record<string, string> = {
AL: 'Alabama', AK: 'Alaska', AZ: 'Arizona', AR: 'Arkansas', CA: 'California',
CO: 'Colorado', CT: 'Connecticut', DE: 'Delaware', FL: 'Florida', GA: 'Georgia',
HI: 'Hawaii', ID: 'Idaho', IL: 'Illinois', IN: 'Indiana', IA: 'Iowa',
KS: 'Kansas', KY: 'Kentucky', LA: 'Louisiana', ME: 'Maine', MD: 'Maryland',
MA: 'Massachusetts', MI: 'Michigan', MN: 'Minnesota', MS: 'Mississippi',
MO: 'Missouri', MT: 'Montana', NE: 'Nebraska', NV: 'Nevada', NH: 'New Hampshire',
NJ: 'New Jersey', NM: 'New Mexico', NY: 'New York', NC: 'North Carolina',
ND: 'North Dakota', OH: 'Ohio', OK: 'Oklahoma', OR: 'Oregon', PA: 'Pennsylvania',
RI: 'Rhode Island', SC: 'South Carolina', SD: 'South Dakota', TN: 'Tennessee',
TX: 'Texas', UT: 'Utah', VT: 'Vermont', VA: 'Virginia', WA: 'Washington',
WV: 'West Virginia', WI: 'Wisconsin', WY: 'Wyoming', DC: 'District of Columbia',
};
const COL_MAX = 600; const COL_MAX = 600;
const COLW_KEY = 'opslog.decodeColWidths'; const COLW_KEY = 'opslog.decodeColWidths';
@@ -308,12 +333,15 @@ function ColResizer({ onResize, onReset }: { onResize: (dx: number) => void; onR
// //
// Colours match the cluster list and the band map — the same fact must not be // Colours match the cluster list and the band map — the same fact must not be
// amber in one panel and green in the next. // amber in one panel and green in the next.
const ENTITY_BADGE: Record<string, { label: string; cls: string }> = { const ENTITY_BADGE: Record<string, { label: string; cls: string; colour: string }> = {
'new': { label: 'dec.stNew', cls: 'bg-success text-success-foreground' }, // colour is the category's own hue, for the UNCONFIRMED rendering: the
'new-band': { label: 'dec.stBand', cls: 'bg-warning text-warning-foreground' }, // filled cls puts light text on a filled chip, and dimming that to a
'new-mode': { label: 'dec.stMode', cls: 'bg-info text-info-foreground' }, // transparent background left light-on-nothing — an invisible badge.
'new-slot': { label: 'dec.stSlot', cls: 'bg-caution text-caution-foreground' }, 'new': { label: 'dec.stNew', cls: 'bg-success text-success-foreground', colour: 'var(--success)' },
'new-call': { label: 'dec.stCall', cls: 'bg-muted text-muted-foreground' }, 'new-band': { label: 'dec.stBand', cls: 'bg-warning text-warning-foreground', colour: 'var(--warning)' },
'new-mode': { label: 'dec.stMode', cls: 'bg-info text-info-foreground', colour: 'var(--info)' },
'new-slot': { label: 'dec.stSlot', cls: 'bg-caution text-caution-foreground', colour: 'var(--caution)' },
'new-call': { label: 'dec.stCall', cls: 'bg-muted text-muted-foreground', colour: 'var(--muted-foreground)' },
}; };
// entityBadgesFor turns a status into the badges that describe it. // entityBadgesFor turns a status into the badges that describe it.
@@ -324,7 +352,7 @@ const ENTITY_BADGE: Record<string, { label: string; cls: string }> = {
// passed the BAND and MODE filters and then showed no reason for being there, // passed the BAND and MODE filters and then showed no reason for being there,
// which is precisely what was reported. catsOf has always split the status into // which is precisely what was reported. catsOf has always split the status into
// its two categories; this is the same split, on the screen. // its two categories; this is the same split, on the screen.
function entityBadgesFor(status: string): { label: string; cls: string }[] { function entityBadgesFor(status: string): { label: string; cls: string; colour: string }[] {
if (status === 'new-band-mode') { if (status === 'new-band-mode') {
return [ENTITY_BADGE['new-band'], ENTITY_BADGE['new-mode']]; return [ENTITY_BADGE['new-band'], ENTITY_BADGE['new-mode']];
} }
@@ -343,6 +371,7 @@ function entityBadgesFor(status: string): { label: string; cls: string }[] {
const EXTRA_BADGES: { key: keyof StatusEntry; marker: SpotMarkerKey; label: string }[] = [ const EXTRA_BADGES: { key: keyof StatusEntry; marker: SpotMarkerKey; label: string }[] = [
{ key: 'new_pota', marker: 'new_pota', label: 'dec.bgPota' }, { key: 'new_pota', marker: 'new_pota', label: 'dec.bgPota' },
{ key: 'new_grid', marker: 'new_grid', label: 'dec.bgGrid' }, { key: 'new_grid', marker: 'new_grid', label: 'dec.bgGrid' },
{ key: 'new_state', marker: 'new_state', label: 'dec.bgState' },
{ key: 'new_pfx', marker: 'new_pfx', label: 'dec.bgPfx' }, { key: 'new_pfx', marker: 'new_pfx', label: 'dec.bgPfx' },
{ key: 'new_county', marker: 'new_county', label: 'dec.bgCounty' }, { key: 'new_county', marker: 'new_county', label: 'dec.bgCounty' },
]; ];
@@ -498,10 +527,11 @@ function buildPeriods(filtered: Decode[], txMsgs: TxMsg[]) {
// the same way it was grouped. // the same way it was grouped.
tr: trSeconds(g.decodes[0]?.mode ?? g.tx[0]?.mode, g.decodes[0]?.tr_period), tr: trSeconds(g.decodes[0]?.mode ?? g.tx[0]?.mode, g.decodes[0]?.tr_period),
tx: g.tx, tx: g.tx,
// Strongest first inside a period: the eye should land on what is // ARRIVAL order inside a period, per the operator: it mirrors the
// workable, and time within a slot means nothing — they were all // decoder's own window line for line, which makes the two screens
// transmitting simultaneously. // comparable at a glance — the strongest-first sort scrambled that
decodes: g.decodes.sort((x, y) => y.snr - x.snr), // correspondence, and SNR is right there in its column anyway.
decodes: g.decodes,
})); }));
} }
@@ -1096,6 +1126,15 @@ export function DecodesPanel({ decodes, txMsgs, txState, txStates, spotStatus, o
<span className="truncate">{d.grid || e?.grid || ''}</span> <span className="truncate">{d.grid || e?.grid || ''}</span>
</span> </span>
<span className={cn(CELL, 'gap-1.5')}>
{e?.state && (
<>
<span className="rounded px-1.5 py-px text-[11px] font-bold bg-info/15 text-info border border-info/40 shrink-0">{e.state}</span>
<span className="text-[11px] text-muted-foreground truncate">{US_STATES[e.state.toUpperCase()] ?? ''}</span>
</>
)}
</span>
<span className={cn(CELL, 'text-[11px] text-muted-foreground')}> <span className={cn(CELL, 'text-[11px] text-muted-foreground')}>
<span className="truncate">{e?.country ?? ''}</span> <span className="truncate">{e?.country ?? ''}</span>
</span> </span>
@@ -1113,7 +1152,11 @@ export function DecodesPanel({ decodes, txMsgs, txState, txStates, spotStatus, o
</span> </span>
)} )}
{entities.map((b) => ( {entities.map((b) => (
<span key={b.label} className={cn('rounded px-1 py-px text-[10px] font-bold uppercase tracking-wide shrink-0', b.cls)}> <span key={b.label}
title={e?.unconf_status ? t('dec.unconfTip') : undefined}
className={cn('rounded px-1 py-px text-[10px] font-bold uppercase tracking-wide shrink-0',
e?.unconf_status ? 'border bg-transparent' : b.cls)}
style={e?.unconf_status ? { color: b.colour, borderColor: b.colour, borderStyle: 'dashed', opacity: 0.6 } : undefined}>
{t(b.label)} {t(b.label)}
</span> </span>
))} ))}
@@ -1123,16 +1166,19 @@ export function DecodesPanel({ decodes, txMsgs, txState, txStates, spotStatus, o
// Same hue, held back — the badge reads as "less" of the // Same hue, held back — the badge reads as "less" of the
// same thing, and its label says which. One badge for both // same thing, and its label says which. One badge for both
// is what made a station worked an hour ago read as new. // is what made a station worked an hour ago read as new.
const unconf = b.key === 'new_grid' && e?.grid_state === 'unconf'; const unconf = (b.key === 'new_grid' && e?.grid_state === 'unconf')
|| (b.key === 'new_state' && !!e?.unconf_state)
|| (b.key === 'new_county' && !!e?.unconf_cty)
|| (b.key === 'new_pfx' && !!e?.unconf_pfx);
const c = markerColour(b.marker); const c = markerColour(b.marker);
return ( return (
<span key={b.key as string} <span key={b.key as string}
title={unconf ? t('dec.bgGridUnconfTip') : undefined} title={unconf ? t('dec.unconfTip') : undefined}
className="rounded border px-1 py-px text-[10px] font-semibold uppercase tracking-wide bg-transparent shrink-0" className="rounded border px-1 py-px text-[10px] font-semibold uppercase tracking-wide bg-transparent shrink-0"
style={unconf style={unconf
? { borderColor: c, color: c, opacity: 0.45, borderStyle: 'dashed' } ? { borderColor: c, color: c, opacity: 0.45, borderStyle: 'dashed' }
: { borderColor: c, color: c }}> : { borderColor: c, color: c }}>
{unconf ? t('dec.bgGridUnconf') : t(b.label)} {t(b.label)}
</span> </span>
); );
})} })}
+1 -1
View File
@@ -19,7 +19,7 @@ type Props = {
phoneOk: boolean; // false when the rig is on a non-phone mode → DVK TX blocked phoneOk: boolean; // false when the rig is on a non-phone mode → DVK TX blocked
}; };
// Operating panel for the Digital Voice Keyer — transmits the recorded F1F6 // Operating panel for the Digital Voice Keyer — transmits the recorded F1F12
// voice messages to the rig ("To Radio"). Mirrors the WinKeyer panel's slot in // voice messages to the rig ("To Radio"). Mirrors the WinKeyer panel's slot in
// the reserved area. Recording/labeling lives in Settings → Audio. // the reserved area. Recording/labeling lives in Settings → Audio.
export function DvkPanel({ messages, status, onPlay, onStop, onClose, autoCq, autoCqSecs, onToggleAutoCq, onSetAutoCqSecs, phoneOk }: Props) { export function DvkPanel({ messages, status, onPlay, onStop, onClose, autoCq, autoCqSecs, onToggleAutoCq, onSetAutoCqSecs, phoneOk }: Props) {
+81 -31
View File
@@ -4,20 +4,21 @@ import {
GetKenwoodState, RefreshKenwood, SetKenwoodPower, SetKenwoodAFGain, SetKenwoodTX, TuneKenwoodATU, GetKenwoodState, RefreshKenwood, SetKenwoodPower, SetKenwoodAFGain, SetKenwoodTX, TuneKenwoodATU,
SetKenwoodRFGain, SetKenwoodMicGain, SetKenwoodSquelch, SetKenwoodPreamp, SetKenwoodAtt, SetKenwoodRFGain, SetKenwoodMicGain, SetKenwoodSquelch, SetKenwoodPreamp, SetKenwoodAtt,
SetKenwoodNB, SetKenwoodNR, SetKenwoodAGC, SetKenwoodFilter, SetKenwoodAntenna, SetKenwoodNB, SetKenwoodNR, SetKenwoodAGC, SetKenwoodFilter, SetKenwoodAntenna,
SetKenwoodRIT, SetKenwoodXIT, ClearKenwoodRIT, SetKenwoodKeySpeed, ToggleKenwoodATU, NudgeKenwoodRIT, SetKenwoodRIT, SetKenwoodXIT, ClearKenwoodRIT, SetKenwoodKeySpeed, ToggleKenwoodATU, SetKenwoodRITOffset, SetKenwoodPanelMode,
GetCATState, GetCATState,
} from '../../wailsjs/go/main/App'; } from '../../wailsjs/go/main/App';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { useI18n } from '@/lib/i18n'; import { useI18n } from '@/lib/i18n';
import { sMeterRST } from '@/lib/rst'; import { sMeterRST } from '@/lib/rst';
import { ShiftRow } from '@/components/ShiftRow';
import { MeterBar } from '@/components/MeterBar'; import { MeterBar } from '@/components/MeterBar';
import { WheelRange } from '@/components/WheelRange'; import { WheelRange } from '@/components/WheelRange';
type KenwoodState = { type KenwoodState = {
available: boolean; model?: string; elecraft: boolean; mode?: string; available: boolean; model?: string; elecraft: boolean; mode?: string; data_sub?: string;
transmitting: boolean; split: boolean; split_tx_hz?: number; transmitting: boolean; split: boolean; split_tx_hz?: number;
s_meter: number; s_meter_raw: number; s_meter: number; s_meter_raw: number;
power_meter: number; swr: number; swr_raw: number; power_meter: number; power_w?: number; swr: number; swr_raw: number;
rf_power: number; af_gain: number; rf_gain: number; mic_gain: number; squelch: number; rf_power: number; af_gain: number; rf_gain: number; mic_gain: number; squelch: number;
preamp: boolean; att: boolean; nb: boolean; nr: boolean; agc?: string; preamp: boolean; att: boolean; nb: boolean; nr: boolean; agc?: string;
filter_hz: number; antenna: number; rit: boolean; xit: boolean; rit_offset: number; key_speed: number; filter_hz: number; antenna: number; rit: boolean; xit: boolean; rit_offset: number; key_speed: number;
@@ -41,18 +42,22 @@ const ZERO: KenwoodState = {
// nobody notices are missing. // nobody notices are missing.
const FILTERS = [200, 400, 700, 1000, 1800, 2400, 2800, 4000]; const FILTERS = [200, 400, 700, 1000, 1800, 2400, 2800, 4000];
// Raw S-meter → S units. The K3 answers 0-21 across S0…S9+60; S9 is taken at // Raw S-meter → S units, CALIBRATED against a real K3 beside its own display
// raw 9 and each step above it as 6 dB. PROVISIONAL, like the rest of the // (2026-08): raw 5 reads S7 on the radio, raw 9 reads S9+20. So S9 sits near
// scaling: the raw value is on screen and in the log, so a real radio settles // raw 6.5 — not 9, which showed everything two S-units low — and each raw step
// it rather than this comment. // above it is worth ~8 dB, shown in the 10 dB steps the K3's own meter uses.
const S9_RAW = 9; // A Kenwood answers 0-30 on the same command and keeps the simple 1-per-raw
const DB_PER_RAW = 6; // scale until someone calibrates one against a real radio too.
function sParts(rawV: number): { s: number; over: number; label: string } { const K3_S9_RAW = 6.5;
if (rawV >= S9_RAW) { const K3_DB_PER_RAW = 8;
const over = Math.max(0, Math.round((rawV - S9_RAW) * DB_PER_RAW)); function sParts(rawV: number, elecraft: boolean): { s: number; over: number; label: string } {
const s9raw = elecraft ? K3_S9_RAW : 9;
if (rawV >= s9raw) {
let over = Math.max(0, Math.round((rawV - s9raw) * (elecraft ? K3_DB_PER_RAW : 6)));
if (elecraft) over = Math.round(over / 10) * 10;
return { s: 9, over, label: over > 0 ? `S9+${over}` : 'S9' }; return { s: 9, over, label: over > 0 ? `S9+${over}` : 'S9' };
} }
const s = Math.max(0, Math.min(9, rawV)); const s = Math.max(0, Math.min(9, Math.round(rawV * (elecraft ? 9 / K3_S9_RAW : 1))));
return { s, over: 0, label: `S${s}` }; return { s, over: 0, label: `S${s}` };
} }
@@ -89,9 +94,34 @@ function Toggle({ label, on, off, onClick }: { label: string; on: boolean; off:
); );
} }
// isDataMode: what the rig reports for MD6 varies — "DATA", or the configured
// digital default (FT8…) — so the DATA family is "not one of the native modes".
function isDataMode(m?: string): boolean {
switch ((m ?? '').toUpperCase()) {
case '': case 'CW': case 'USB': case 'LSB': case 'SSB': case 'FM': case 'AM': case 'RTTY':
return false;
}
return true;
}
export function ElecraftPanel({ onReportRST }: { onReportRST?: (rst: string) => void }) { export function ElecraftPanel({ onReportRST }: { onReportRST?: (rst: string) => void }) {
const { t } = useI18n(); const { t } = useI18n();
const [st, setSt] = useState<KenwoodState>(ZERO); const [st, setSt] = useState<KenwoodState>(ZERO);
// Ctrl+Left/Right shifts the RIT by ±10 Hz while RIT is on — the same
// keyboard clarifier the Icom and TCI consoles have, for zero-beating a
// caller without touching the mouse.
const stRef = useRef(st); stRef.current = st;
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (!e.ctrlKey || (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight')) return;
const v = stRef.current;
if (!v.available || !v.rit) return;
e.preventDefault();
SetKenwoodRITOffset((v.rit_offset || 0) + (e.key === 'ArrowRight' ? 10 : -10)).catch(() => {});
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, []);
const [freqHz, setFreqHz] = useState(0); const [freqHz, setFreqHz] = useState(0);
const [err, setErr] = useState(''); const [err, setErr] = useState('');
// Optimistic overlay: a slider must follow the finger, not the poll. Dropped // Optimistic overlay: a slider must follow the finger, not the poll. Dropped
@@ -149,6 +179,28 @@ export function ElecraftPanel({ onReportRST }: { onReportRST?: (rst: string) =>
{freqHz > 0 ? (freqHz / 1e6).toFixed(6) : '—'} {freqHz > 0 ? (freqHz / 1e6).toFixed(6) : '—'}
</div> </div>
</div> </div>
{/* Mode row. The two DATA buttons are why it exists: MD6 alone keeps
whatever submode the last session left, and a K3 "in DATA" with FSK D
still armed keys FT8 with no audio. DATA sends MD6+DT0 (DATA A, the
soundcard path), RTTY sends MD6+DT2 (FSK D). The active DATA button
follows the rig's own DT answer. */}
<div className="inline-flex rounded-md border border-border overflow-hidden">
{([
['CW', 'CW', view.mode === 'CW'],
['USB', 'USB', view.mode === 'USB'],
['LSB', 'LSB', view.mode === 'LSB'],
['DATA', t('k3.modeData'), isDataMode(view.mode) && view.data_sub !== 'FSK D' && view.data_sub !== 'PSK D'],
['RTTY', t('k3.modeRtty'), (isDataMode(view.mode) && (view.data_sub === 'FSK D' || view.data_sub === 'PSK D')) || view.mode === 'RTTY'],
] as [string, string, boolean][]).map(([cmd, label, on]) => (
<button key={cmd} type="button" disabled={off}
title={cmd === 'DATA' ? t('k3.modeDataHint') : cmd === 'RTTY' ? t('k3.modeRttyHint') : label}
onClick={() => SetKenwoodPanelMode(cmd).catch((e: any) => setErr(String(e?.message ?? e)))}
className={cn('px-2.5 py-1.5 text-xs font-bold border-l border-border first:border-l-0',
on ? 'bg-primary text-primary-foreground' : 'bg-card text-muted-foreground hover:bg-muted')}>
{label}
</button>
))}
</div>
<button type="button" className="text-[11px] text-muted-foreground hover:text-foreground flex items-center gap-1" <button type="button" className="text-[11px] text-muted-foreground hover:text-foreground flex items-center gap-1"
onClick={() => RefreshKenwood().catch(() => {})} title={t('k3.refreshHint')}> onClick={() => RefreshKenwood().catch(() => {})} title={t('k3.refreshHint')}>
<SlidersHorizontal className="size-3.5" /> <SlidersHorizontal className="size-3.5" />
@@ -163,14 +215,15 @@ export function ElecraftPanel({ onReportRST }: { onReportRST?: (rst: string) =>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2"> <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
<MeterBar label="S-METER" value={view.transmitting ? 0 : view.s_meter} lo={0} hi={100} <MeterBar label="S-METER" value={view.transmitting ? 0 : view.s_meter} lo={0} hi={100}
accent="#16a34a" segColor={sSegColor} accent="#16a34a" segColor={sSegColor}
display={view.transmitting ? '—' : sParts(view.s_meter_raw).label} display={view.transmitting ? '—' : sParts(view.s_meter_raw, view.elecraft).label}
onClick={() => { onClick={() => {
if (view.transmitting || !onReportRST) return; if (view.transmitting || !onReportRST) return;
const sp = sParts(view.s_meter_raw); const sp = sParts(view.s_meter_raw, view.elecraft);
onReportRST(sMeterRST(sp.s, sp.over, view.mode)); onReportRST(sMeterRST(sp.s, sp.over, view.mode));
}} }}
title={t('k3.sMeterHint', { raw: String(view.s_meter_raw) })} /> title={t('k3.sMeterHint', { raw: String(view.s_meter_raw) })} />
<MeterBar label="PWR" value={view.transmitting ? view.power_meter : 0} lo={0} hi={100} accent="#0ea5e9" /> <MeterBar label="PWR" value={view.transmitting ? view.power_meter : 0} lo={0} hi={100} accent="#0ea5e9"
display={view.transmitting && view.elecraft ? `${view.power_w ?? 0} W` : undefined} />
{/* 0 means "not measured", and it must not render as a perfect 1.0: {/* 0 means "not measured", and it must not render as a perfect 1.0:
a match that looks ideal on an antenna nobody has measured is the one a match that looks ideal on an antenna nobody has measured is the one
reading that can cost a radio. */} reading that can cost a radio. */}
@@ -216,7 +269,7 @@ export function ElecraftPanel({ onReportRST }: { onReportRST?: (rst: string) =>
<div className="grid grid-cols-1 lg:grid-cols-2 gap-x-6 gap-y-2"> <div className="grid grid-cols-1 lg:grid-cols-2 gap-x-6 gap-y-2">
<label className="flex items-center gap-2 text-xs"> <label className="flex items-center gap-2 text-xs">
<span className="w-16 shrink-0 text-muted-foreground">{t('k3.power')}</span> <span className="w-16 shrink-0 text-muted-foreground">{t('k3.power')}</span>
<WheelRange min={0} max={110} step={5} disabled={off} <WheelRange min={0} max={110} step={1} disabled={off}
value={view.rf_power ?? 0} value={view.rf_power ?? 0}
onChange={(n) => put({ rf_power: n }, () => SetKenwoodPower(n))} /> onChange={(n) => put({ rf_power: n }, () => SetKenwoodPower(n))} />
<span className="w-12 text-right font-mono tabular-nums">{view.rf_power ?? 0} W</span> <span className="w-12 text-right font-mono tabular-nums">{view.rf_power ?? 0} W</span>
@@ -279,21 +332,18 @@ export function ElecraftPanel({ onReportRST }: { onReportRST?: (rst: string) =>
))} ))}
</div> </div>
{/* RIT / XIT. Clear zeroes both offsets at once the radio's own RC, {/* RIT / XIT the shared ShiftRow, exactly as the Icom and TCI consoles
and what an operator means by "clear it". */} drive theirs: ± / wheel / type, Ctrl+/ while RIT is on. The K3 has
ONE offset for both, so both rows show it, like the Icom's. */}
<div className="space-y-1.5">
<ShiftRow label="RIT" accent="#8b5cf6" on={view.rit} hz={view.rit_offset || 0} disabled={off}
onToggle={() => SetKenwoodRIT(!view.rit).catch(setErrMsg)}
onSet={(hz) => SetKenwoodRITOffset(hz).catch(setErrMsg)} />
<ShiftRow label="XIT" accent="#f59e0b" on={view.xit} hz={view.rit_offset || 0} disabled={off}
onToggle={() => SetKenwoodXIT(!view.xit).catch(setErrMsg)}
onSet={(hz) => SetKenwoodRITOffset(hz).catch(setErrMsg)} />
</div>
<div className="flex flex-wrap items-center gap-1.5"> <div className="flex flex-wrap items-center gap-1.5">
<Toggle label="RIT" on={view.rit} off={off} onClick={() => SetKenwoodRIT(!view.rit).catch(setErrMsg)} />
<Toggle label="XIT" on={view.xit} off={off} onClick={() => SetKenwoodXIT(!view.xit).catch(setErrMsg)} />
{/* The offset itself. A lit RIT button says the feature is on and
nothing about where it has put the receiver. */}
{[-100, -10, 10, 100].map((d) => (
<Toggle key={d} label={(d > 0 ? '+' : '') + d} on={false} off={off}
onClick={() => NudgeKenwoodRIT(d).catch(setErrMsg)} />
))}
<span className="text-[11px] font-mono tabular-nums text-muted-foreground w-16">
{view.rit_offset > 0 ? '+' : ''}{view.rit_offset || 0} Hz
</span>
<Toggle label={t('k3.clear')} on={false} off={off} onClick={() => ClearKenwoodRIT().catch(setErrMsg)} />
{/* Antenna only when the radio answered AN a K3 without the internal {/* Antenna only when the radio answered AN a K3 without the internal
ATU has one socket and no switch to offer. */} ATU has one socket and no switch to offer. */}
{view.antenna > 0 && (<> {view.antenna > 0 && (<>
+154
View File
@@ -0,0 +1,154 @@
import { useEffect, useRef, useState } from 'react';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { gridToLatLon, greatCirclePoints } from '@/lib/maidenhead';
import { BASEMAPS, type BasemapKey } from '@/components/MainMap';
import { cn } from '@/lib/utils';
import { useI18n } from '@/lib/i18n';
// FT Map — the live decode feed as geography: every station decoded in the
// last half hour, an arc from the operator's own square to theirs, coloured by
// band the way PSK Reporter taught everyone to read it. Wholly display: the
// decode list is the same one the FT decodes tab shows, and a station with no
// grid (never sent one in a CQ) simply cannot be placed and is not drawn.
//
// Performance is a design constraint, not an afterthought: the panel only
// exists while its tab is active (the parent unmounts it otherwise), the map
// renders with canvas (one <canvas>, not one DOM node per arc), the arcs are
// capped, and redraws happen when the DECODE LIST changes — every 15 s in FT8,
// not per frame.
export type FTMapDecode = {
call: string;
grid?: string;
band?: string;
snr: number;
at: string;
};
// The band palette every PSK Reporter user already knows, near enough.
const BAND_COLOURS: Record<string, string> = {
'160m': '#7f7f7f', '80m': '#e550e5', '60m': '#00008b', '40m': '#5555ff',
'30m': '#62d962', '20m': '#f2c40c', '17m': '#f2f261', '15m': '#cca166',
'12m': '#b22222', '10m': '#ff69b4', '6m': '#ff0000', '4m': '#cc0044',
'2m': '#ff1493', '70cm': '#999900',
};
const bandColour = (b?: string) => BAND_COLOURS[(b ?? '').toLowerCase()] || '#9ca3af';
const MAX_ARCS = 300;
const MAX_AGE_MS = 30 * 60_000;
export function FTMapPanel({ decodes, myGrid }: { decodes: FTMapDecode[]; myGrid: string }) {
const { t } = useI18n();
const divRef = useRef<HTMLDivElement>(null);
const mapRef = useRef<L.Map | null>(null);
const layerRef = useRef<L.LayerGroup | null>(null);
const baseRef = useRef<L.TileLayer | null>(null);
const labelsRef = useRef<L.TileLayer | null>(null);
const [basemap, setBasemap] = useState<BasemapKey>(() =>
(localStorage.getItem('opslog.ftmapBase') as BasemapKey) || 'satellite');
// The map itself, once.
useEffect(() => {
if (!divRef.current || mapRef.current) return;
// ONE world: noWrap tiles inside hard bounds, no side-by-side copies —
// and the space beyond the edge is the theme's own surface (style.css).
const m = L.map(divRef.current, {
zoomControl: true, attributionControl: true,
// No maxBounds: with the world smaller than the window the clamp
// dragged every zoom into a corner. noWrap tiles alone keep one world.
worldCopyJump: false, preferCanvas: true,
center: [25, 0], zoom: 2, minZoom: 2,
});
mapRef.current = m;
layerRef.current = L.layerGroup().addTo(m);
return () => { m.remove(); mapRef.current = null; layerRef.current = null; };
}, []);
// Basemap follows the picker.
useEffect(() => {
const m = mapRef.current;
if (!m) return;
baseRef.current?.remove(); labelsRef.current?.remove();
const bm = BASEMAPS[basemap];
const opts: L.TileLayerOptions = {
maxNativeZoom: bm.maxNativeZoom,
noWrap: true,
bounds: L.latLngBounds(L.latLng(-85.0511, -180), L.latLng(85.0511, 180)),
};
baseRef.current = L.tileLayer(bm.url, { ...opts, attribution: bm.attr, subdomains: bm.subdomains ?? 'abc' }).addTo(m);
if (bm.labelsUrl) labelsRef.current = L.tileLayer(bm.labelsUrl, opts).addTo(m);
localStorage.setItem('opslog.ftmapBase', basemap);
}, [basemap]);
// The arcs, redrawn when the decode list changes. Newest last so they paint
// on top; opacity falls with age so the map reads as "now" with a memory.
useEffect(() => {
const layer = layerRef.current;
if (!layer) return;
layer.clearLayers();
const from = gridToLatLon(myGrid);
if (!from) return;
const now = Date.now();
const placed = decodes
.filter((d) => d.grid && Date.parse(d.at) > now - MAX_AGE_MS)
.slice(-MAX_ARCS);
// One line per CALL (its freshest sighting): the same CQer decoded thirty
// times in ten minutes is one path on the air, not thirty strokes of it.
const byCall = new Map<string, FTMapDecode>();
for (const d of placed) byCall.set(d.call.toUpperCase(), d);
L.circleMarker([from.lat, from.lon], {
radius: 5, color: '#fff', weight: 2, fillColor: '#e11d48', fillOpacity: 1,
}).addTo(layer);
for (const d of byCall.values()) {
const to = gridToLatLon(d.grid!);
if (!to) continue;
const age = now - Date.parse(d.at);
const fade = Math.max(0.15, 1 - age / MAX_AGE_MS);
const colour = bandColour(d.band);
const pts = greatCirclePoints(from.lat, from.lon, to.lat, to.lon, 48);
L.polyline(pts as L.LatLngExpression[], {
color: colour, weight: 1.3, opacity: 0.65 * fade, smoothFactor: 0,
}).addTo(layer);
L.circleMarker([to.lat, to.lon], {
radius: 3, color: colour, weight: 1, fillColor: colour, fillOpacity: 0.9 * fade,
}).bindTooltip(`${d.call} · ${d.grid} · ${d.snr > 0 ? '+' : ''}${d.snr} dB`, { direction: 'top' })
.addTo(layer);
}
}, [decodes, myGrid]);
const bands = [...new Set(decodes.map((d) => (d.band ?? '').toLowerCase()).filter(Boolean))];
return (
<div className="relative h-full w-full min-h-0">
<div ref={divRef} className="absolute inset-0 rounded-lg overflow-hidden" />
{/* Basemap picker, MainMap's own vocabulary. */}
<div className="absolute top-2 left-12 z-[1000] flex gap-1 rounded-md bg-background/85 backdrop-blur px-1 py-1 border border-border">
{(Object.keys(BASEMAPS) as BasemapKey[]).map((k) => (
<button key={k} type="button" onClick={() => setBasemap(k)}
className={cn('px-2 py-0.5 rounded text-[11px]',
basemap === k ? 'bg-primary text-primary-foreground font-semibold' : 'text-muted-foreground hover:bg-muted')}>
{BASEMAPS[k].label}
</button>
))}
</div>
{/* Band legend — only the bands actually on screen. */}
{bands.length > 0 && (
<div className="absolute bottom-2 left-2 z-[1000] flex flex-wrap gap-x-2.5 gap-y-1 rounded-md bg-background/85 backdrop-blur px-2 py-1.5 border border-border">
{bands.map((b) => (
<span key={b} className="flex items-center gap-1 text-[11px] text-foreground">
<span className="inline-block w-3 h-[3px] rounded" style={{ background: bandColour(b) }} />
{b.toUpperCase()}
</span>
))}
</div>
)}
{!gridToLatLon(myGrid) && (
<div className="absolute inset-0 z-[1000] flex items-center justify-center pointer-events-none">
<span className="rounded-md bg-background/90 border border-border px-3 py-2 text-sm text-muted-foreground">
{t('ftmap.noGrid')}
</span>
</div>
)}
</div>
);
}
+1 -5
View File
@@ -128,15 +128,11 @@ export function GridSquareMap({ myGrid, className }: { myGrid?: string; classNam
// impossible on any window wider than it is tall: one step out was already // impossible on any window wider than it is tall: one step out was already
// too far in. // too far in.
minZoom: 0, minZoom: 0,
maxBoundsViscosity: 1, // don't let a drag slide the world off to one side
}).setView([20, 0], 2); }).setView([20, 0], 2);
// The whole world, once, whatever the window is shaped like — computed by // The whole world, once, whatever the window is shaped like — computed by
// Leaflet from the container rather than guessed with a zoom number. // Leaflet from the container rather than guessed with a zoom number.
m.fitWorld({ animate: false }); m.fitWorld({ animate: false });
// Latitude only: the poles are the edge of the projection and there is
// nothing beyond them, while leaving longitude free keeps a drag from
// fighting the operator near the date line.
m.setMaxBounds(L.latLngBounds(L.latLng(-85, -Infinity), L.latLng(85, Infinity)));
mapRef.current = m; mapRef.current = m;
layerRef.current = L.layerGroup().addTo(m); layerRef.current = L.layerGroup().addTo(m);
// Leaflet measures its container ONCE, when the map is created, and never // Leaflet measures its container ONCE, when the map is created, and never
+118 -337
View File
@@ -1,11 +1,12 @@
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { Radio, AudioLines, Mic, Activity, SlidersHorizontal, Antenna, Filter, Power } from 'lucide-react'; import { Radio, AudioLines, Mic, Activity, SlidersHorizontal, Antenna, Filter, Power, Volume2, VolumeX } from 'lucide-react';
import { import {
GetIcomState, IcomRefresh, GetIcomState, IcomRefresh,
IcomSetAFGain, IcomSetRFGain, IcomSetNB, IcomSetNBLevel, IcomSetNR, IcomSetNRLevel, IcomSetAFGain, IcomSetRFGain, IcomSetNB, IcomSetNBLevel, IcomSetNR, IcomSetNRLevel,
IcomSetANF, IcomSetAPF, IcomSetAGC, IcomSetPreamp, IcomSetAtt, IcomSetFilter, IcomSetANF, IcomSetAPF, IcomSetAGC, IcomSetPreamp, IcomSetAtt, IcomSetFilter,
IcomSetRFPower, IcomSetMicGain, IcomSetSplit, IcomTune, IcomSetPTT, AudioMonitorActive, AudioStartMonitor, AudioStopMonitor,
IcomSetScope, IcomScopeData, IcomSetScopeMode, IcomSetScopeEdges, GetCATState, SetCATFrequency, SetCATMode, IcomSetRFPower, IcomSetMicGain, IcomSetSplit, IcomTune, IcomSetATU, IcomConsolePTT,
GetCATState, SetCATFrequency, SetCATMode,
IcomSetRIT, IcomSetRITOn, IcomSetXITOn, IcomSetRIT, IcomSetRITOn, IcomSetXITOn,
IcomSetAntenna, IcomSetPBTInner, IcomSetPBTOuter, IcomSetManualNotch, IcomSetNotchPos, IcomSetAntenna, IcomSetPBTInner, IcomSetPBTOuter, IcomSetManualNotch, IcomSetNotchPos,
IcomSetSquelch, IcomSetComp, IcomSetCompLevel, IcomSetMonitor, IcomSetMonLevel, IcomSetSquelch, IcomSetComp, IcomSetCompLevel, IcomSetMonitor, IcomSetMonLevel,
@@ -14,10 +15,12 @@ import {
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { useI18n } from '@/lib/i18n'; import { useI18n } from '@/lib/i18n';
import { sMeterRST } from '@/lib/rst'; import { sMeterRST } from '@/lib/rst';
import { MeterBar } from '@/components/MeterBar';
import { ShiftRow } from '@/components/ShiftRow';
type IcomState = { type IcomState = {
available: boolean; model?: string; mode?: string; available: boolean; model?: string; mode?: string;
transmitting: boolean; split: boolean; transmitting: boolean; split: boolean; sub_hz?: number; atu_on?: boolean;
s_meter: number; power_meter: number; swr_meter: number; s_meter: number; power_meter: number; swr_meter: number;
rf_power: number; mic_gain: number; rf_power: number; mic_gain: number;
af_gain: number; rf_gain: number; af_gain: number; rf_gain: number;
@@ -77,17 +80,18 @@ function bandsFor(model?: string): Band[] {
// Mode buttons for the console (like RS-BA1's row). SetCATMode picks USB/LSB for // Mode buttons for the console (like RS-BA1's row). SetCATMode picks USB/LSB for
// SSB by frequency and the rig's data variant for digital modes. // SSB by frequency and the rig's data variant for digital modes.
const MODES = ['SSB', 'CW', 'RTTY', 'PSK', 'AM', 'FM']; const MODES = ['SSB', 'CW', 'RTTY', 'PSK', 'AM', 'FM', 'DATA'];
// Attenuator steps are MODEL-dependent even though the CI-V command (0x11) is the // Attenuator steps are MODEL-dependent even though the CI-V command (0x11) is the
// same: the value byte is the dB. The IC-7610 (and 7700/7800/7851) have a 6/12/18 // same: the value byte is the dB. The IC-7610 (and 7700/7800/7851) have a 6/12/18
// dB stepped attenuator; the IC-7300/705/7100 have a single 20 dB attenuator; the // dB stepped attenuator, and the IC-7760 the same (confirmed on a real one); the
// IC-7300/705/7100 have a single 20 dB attenuator; the
// IC-9700 a single 10 dB. Offering the wrong steps = a dead button (the rig NAKs // IC-9700 a single 10 dB. Offering the wrong steps = a dead button (the rig NAKs
// e.g. 6 dB on a 7300). Default to the common single 20 dB for unknown models. // e.g. 6 dB on a 7300). Default to the common single 20 dB for unknown models.
function attOptions(model?: string): { v: string; l: string }[] { function attOptions(model?: string): { v: string; l: string }[] {
const m = (model ?? '').toUpperCase(); const m = (model ?? '').toUpperCase();
const OFF = { v: '0', l: 'OFF' }; const OFF = { v: '0', l: 'OFF' };
if (/(7610|7700|7800|7850|7851)/.test(m)) { if (/(7610|7700|7760|7800|7850|7851)/.test(m)) {
return [OFF, { v: '6', l: '6dB' }, { v: '12', l: '12dB' }, { v: '18', l: '18dB' }]; return [OFF, { v: '6', l: '6dB' }, { v: '12', l: '12dB' }, { v: '18', l: '18dB' }];
} }
if (m.includes('9700')) return [OFF, { v: '10', l: '10dB' }]; if (m.includes('9700')) return [OFF, { v: '10', l: '10dB' }];
@@ -126,9 +130,38 @@ function fmtVFO(hz?: number): string {
} }
// modeMatches marks a mode button active, folding the rig's USB/LSB into SSB. // modeMatches marks a mode button active, folding the rig's USB/LSB into SSB.
// icomWatts turns the backend's 0-100 meter percentage back into watts on the
// IC-7760's own meter face. The backend value is linear in the RAW meter byte
// (0-255 → 0-100), but Icom's calibration is not: raw 143 is half deflection
// and raw 213 is full scale. On a real 7760 a measured 100 W sits at half
// deflection of the 250 W face — the linear ×2.5 first tried showed 140 W for
// it. Below half scale watts run 0→100, above it 100→250.
// The anchors are MEASURED on the real radio, not derived: a known 50 W read
// raw ≈89 and a known 100 W read raw 143 (Icom's documented half-deflection),
// with raw 213 = full scale = 250 W. The face is not linear in watts at the
// bottom — a two-segment guess showed 50 W as 62 — so watts interpolate
// between the measured anchors, and a new measurement just adds a row.
// Third measured anchor (2026-08-30): a real 200 W read full deflection —
// raw 213 is 200 W on this rig, not the 250 the printed face suggests.
const ICOM_7760_PO: [number, number][] = [[0, 0], [89, 50], [143, 100], [213, 200]];
function icomWatts(pct: number): { w: number; defl: number } {
const raw = Math.max(0, pct * 2.55);
const defl = raw <= 143 ? (raw / 143) * 50 : Math.min(100, 50 + ((raw - 143) / 70) * 50);
let w = 200;
for (let i = 1; i < ICOM_7760_PO.length; i++) {
const [r0, w0] = ICOM_7760_PO[i - 1], [r1, w1] = ICOM_7760_PO[i];
if (raw <= r1) { w = w0 + ((raw - r0) / (r1 - r0)) * (w1 - w0); break; }
}
return { w: Math.round(w), defl };
}
function modeMatches(btn: string, cur?: string): boolean { function modeMatches(btn: string, cur?: string): boolean {
if (!cur) return false; if (!cur) return false;
if (btn === 'SSB') return cur === 'SSB' || cur === 'USB' || cur === 'LSB'; if (btn === 'SSB') return cur === 'SSB' || cur === 'USB' || cur === 'LSB';
// The backend surfaces USB-D as the operator's digital default (FT8…), or as
// plain DATA — either way it is the DATA button that should light.
if (btn === 'DATA') return ['DATA', 'FT8', 'FT4', 'JS8', 'JT65', 'JT9', 'MFSK', 'OLIVIA'].includes(cur);
if (btn === 'PSK') return cur === 'PSK' || cur === 'PSK31';
return btn === cur; return btn === cur;
} }
@@ -239,51 +272,25 @@ function Meter({ label, value, accent, scale, onClick, title }: { label: string;
<div className="flex-1 h-2.5 rounded-full bg-muted/60 overflow-hidden"> <div className="flex-1 h-2.5 rounded-full bg-muted/60 overflow-hidden">
<div className="h-full rounded-full transition-[width] duration-150" style={{ width: `${v}%`, background: accent }} /> <div className="h-full rounded-full transition-[width] duration-150" style={{ width: `${v}%`, background: accent }} />
</div> </div>
<span className="w-10 text-right text-[11px] font-mono tabular-nums text-muted-foreground">{scale ?? v}</span> <span className="w-14 shrink-0 whitespace-nowrap text-right text-[11px] font-mono tabular-nums text-muted-foreground">{scale ?? v}</span>
</> </>
); );
if (onClick) { if (onClick) {
return <button type="button" onClick={onClick} title={title} className="flex items-center gap-2 w-full rounded hover:bg-muted/50 -mx-1 px-1 py-0.5">{body}</button>; return <button type="button" onClick={onClick} title={title} className="flex items-center gap-2 w-full rounded cursor-pointer hover:bg-muted/50 -mx-1 px-1 py-0.5">{body}</button>;
} }
return <div className="flex items-center gap-2">{body}</div>; return <div className="flex items-center gap-2">{body}</div>;
} }
// ShiftRow — a RIT / ΔTX offset control: on/off chip + a wheel-adjustable signed
// offset (±10 Hz per notch or per ± button) + a clear (0) button.
function ShiftRow({ label, on, hz, accent, onToggle, onDelta, onClear }: {
label: string; on: boolean; hz: number; accent: string;
onToggle: () => void; onDelta: (d: number) => void; onClear: () => void;
}) {
const ref = useRef<HTMLDivElement>(null);
const cb = useRef(onDelta); cb.current = onDelta;
useEffect(() => {
const el = ref.current;
if (!el) return;
const onWheel = (e: WheelEvent) => { e.preventDefault(); cb.current(e.deltaY < 0 ? 10 : -10); };
el.addEventListener('wheel', onWheel, { passive: false });
return () => el.removeEventListener('wheel', onWheel);
}, []);
return (
<div className="flex items-center gap-2">
<Chip on={on} onClick={onToggle} label={label} />
<div ref={ref} title="Wheel / ± to shift"
className={cn('flex-1 flex items-center justify-between rounded-md border px-1 py-0.5 select-none cursor-ns-resize',
on ? 'border-border bg-muted/40' : 'border-border/60 bg-muted/20 opacity-60')}>
<button type="button" onClick={() => onDelta(-10)} className="px-2 text-sm font-bold text-muted-foreground hover:text-foreground"></button>
<span className="text-sm font-mono font-bold tabular-nums" style={{ color: on ? accent : undefined }}>
{hz > 0 ? '+' : hz < 0 ? '' : ''}{Math.abs(hz)} Hz
</span>
<button type="button" onClick={() => onDelta(10)} className="px-2 text-sm font-bold text-muted-foreground hover:text-foreground">+</button>
</div>
<button type="button" onClick={onClear}
className="w-8 shrink-0 py-1 rounded-md text-[11px] font-bold border border-border bg-card text-muted-foreground hover:bg-muted">0</button>
</div>
);
}
// sParts turns the raw 0-100 S-meter into S-unit + dB-over-S9 (S9 ≈ 47% on the // sParts turns the raw 0-100 S-meter into S-unit + dB-over-S9 (S9 ≈ 47% on the
// CI-V 0-255 scale, +60 dB near full scale). Used for both the display label and // CI-V 0-255 scale, +60 dB near full scale). Used for both the display label and
// the RST-tx value on click. // the RST-tx value on click.
// Green to S9, amber through +20, red above — the Elecraft console's scale.
function sSegColor(frac: number) {
if (frac > 0.78) return '#dc2626';
if (frac > 0.55) return '#f59e0b';
return '#16a34a';
}
function sParts(v: number): { s: number; over: number; label: string } { function sParts(v: number): { s: number; over: number; label: string } {
if (v >= 47) { if (v >= 47) {
const over = Math.max(0, Math.round((v - 47) * 60 / 47)); const over = Math.max(0, Math.round((v - 47) * 60 / 47));
@@ -311,287 +318,31 @@ function wfColor(v: number): [number, number, number] {
return WF_STOPS[WF_STOPS.length - 1][1]; return WF_STOPS[WF_STOPS.length - 1][1];
} }
// ScopePanadapter — enables the rig's spectrum-scope stream and draws the // The spectrum scope is GONE, deliberately. Every Icom streams its waveform
// reassembled sweep as a modern SDR panadapter: a glowing filled spectrum trace // differently — the IC-7851 controls a scope it never streams, and a real
// on top and a scrolling colour waterfall below. Amplitudes are raw rig scale // IC-7760 stops answering CI-V altogether a few frames in, taking CAT and
// (~0-160), normalised to the tallest recent peak so the trace fills the height. // audio down with it — and chasing a per-model frame layout for a decoration
function ScopePanadapter() { // is not worth a console that drops the link. The radio has a better scope
const { t } = useI18n(); // on its own front panel.
const [on, setOn] = useState(false);
const [fixed, setFixed] = useState(true);
const canvasRef = useRef<HTMLCanvasElement>(null);
const wfRef = useRef<HTMLCanvasElement>(null); // waterfall
const peakRef = useRef(160); // running amplitude ceiling for auto-scale
const holdRef = useRef<number[]>([]); // per-bin peak-hold line
const spanRef = useRef({ low: 0, high: 0 }); // latest sweep edges, for click-to-tune
const vfoRef = useRef(0); // latest VFO frequency, for wheel-tune
const centerRef = useRef(0); // scope centre we last set (for pan ◀/▶)
const toggle = () => {
const next = !on;
setOn(next);
IcomSetScope(next).catch(() => {});
};
// Centre/pan the FIXED scope: set the edges to centre ±50 kHz (a 100 kHz
// window). "Centre" uses the live VFO; ◀/▶ shift the window by 50 kHz. This
// just writes the rig's fixed edges — simple and independent of the waveform
// decode.
const SCOPE_HALF = 50_000;
const applyEdges = (center: number) => {
if (center <= 0) return;
centerRef.current = center;
setFixed(true);
IcomSetScopeEdges(center - SCOPE_HALF, center + SCOPE_HALF).catch(() => {});
};
const centerOnVfo = async () => {
let c = vfoRef.current;
if (c <= 0) { try { const cs = await GetCATState(); c = cs?.freq_hz || 0; } catch {} }
applyEdges(c);
};
const pan = (dir: number) => applyEdges((centerRef.current || vfoRef.current) + dir * SCOPE_HALF);
const setMode = (nextFixed: boolean) => {
setFixed(nextFixed);
IcomSetScopeMode(nextFixed).catch(() => {});
};
// Stop the stream when the panel unmounts.
useEffect(() => () => { IcomSetScope(false).catch(() => {}); }, []);
useEffect(() => {
if (!on) return;
let raf = 0, lastSeq = -1, alive = true;
const tick = async () => {
if (!alive) return;
try {
const sw = await IcomScopeData();
if (sw && sw.seq !== lastSeq && sw.amp && sw.amp.length) {
lastSeq = sw.seq;
setFixed(sw.fixed);
spanRef.current = { low: sw.low_hz, high: sw.high_hz };
let vfo = 0;
try {
const cs = await GetCATState();
vfo = cs?.split && cs.freq_rx_hz ? cs.freq_rx_hz : (cs?.freq_hz || 0);
} catch {}
if (vfo > 0) vfoRef.current = vfo;
draw(sw.amp, sw.low_hz, sw.high_hz, vfoRef.current, sw.fixed);
}
} catch {}
if (alive) raf = window.setTimeout(() => { raf = requestAnimationFrame(tick); }, 40) as unknown as number;
};
raf = requestAnimationFrame(tick);
return () => { alive = false; cancelAnimationFrame(raf); window.clearTimeout(raf); };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [on]);
// Double-click tunes the rig to the clicked frequency.
const onDblClick = (e: React.MouseEvent<HTMLCanvasElement>) => {
const cv = canvasRef.current;
const { low, high } = spanRef.current;
if (!cv || !(low > 0 && high > low)) return;
const rect = cv.getBoundingClientRect();
const frac = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
const hz = Math.round((low + frac * (high - low)) / 100) * 100; // nearest 100 Hz
SetCATFrequency(hz).catch(() => {});
};
// Mouse-wheel over the scope QSYs ±100 Hz. Non-passive listener so we can
// preventDefault (else the page scrolls); optimistic vfoRef so quick spins
// accumulate before the poll reconciles.
useEffect(() => {
const el = canvasRef.current;
if (!el || !on) return;
const onWheel = (e: WheelEvent) => {
if (!vfoRef.current) return;
e.preventDefault();
const next = vfoRef.current + (e.deltaY < 0 ? 100 : -100);
vfoRef.current = next;
SetCATFrequency(next).catch(() => {});
};
el.addEventListener('wheel', onWheel, { passive: false });
return () => el.removeEventListener('wheel', onWheel);
}, [on]);
const draw = (amp: number[], lowHz: number, highHz: number, vfoHz: number, fixedMode: boolean) => {
const cv = canvasRef.current;
if (!cv) return;
const dpr = window.devicePixelRatio || 1;
const w = cv.clientWidth, h = cv.clientHeight;
if (cv.width !== w * dpr || cv.height !== h * dpr) { cv.width = w * dpr; cv.height = h * dpr; }
const ctx = cv.getContext('2d');
if (!ctx) return;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
// Auto-scale: track the peak, decaying slowly so the floor doesn't jump.
const peak = Math.max(...amp);
peakRef.current = Math.max(peak, peakRef.current * 0.95, 40);
const scale = peakRef.current;
const n = amp.length;
// Background — deep navy vertical gradient.
const bg = ctx.createLinearGradient(0, 0, 0, h);
bg.addColorStop(0, '#0b1220'); bg.addColorStop(1, '#05070e');
ctx.fillStyle = bg; ctx.fillRect(0, 0, w, h);
// Grid.
ctx.strokeStyle = 'rgba(120,150,200,0.08)';
ctx.lineWidth = 1;
for (let i = 1; i < 4; i++) { const y = (h * i) / 4; ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(w, y); ctx.stroke(); }
for (let i = 1; i < 8; i++) { const x = (w * i) / 8; ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke(); }
const xOf = (i: number) => (i / (n - 1)) * w;
const yOf = (v: number) => h - Math.min(1, v / scale) * h;
// Peak-hold line (slow decay) — a faint ghost of recent maxima.
const hold = holdRef.current;
if (hold.length !== n) hold.length = n, hold.fill(0);
for (let i = 0; i < n; i++) hold[i] = Math.max(amp[i], hold[i] * 0.92);
// Filled spectrum area.
ctx.beginPath();
ctx.moveTo(0, h);
for (let i = 0; i < n; i++) ctx.lineTo(xOf(i), yOf(amp[i]));
ctx.lineTo(w, h); ctx.closePath();
const grad = ctx.createLinearGradient(0, 0, 0, h);
grad.addColorStop(0, 'rgba(56,189,248,0.40)');
grad.addColorStop(1, 'rgba(56,189,248,0.02)');
ctx.fillStyle = grad; ctx.fill();
// Peak-hold trace (thin, faint).
ctx.beginPath();
for (let i = 0; i < n; i++) { const x = xOf(i), y = yOf(hold[i]); i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y); }
ctx.strokeStyle = 'rgba(148,197,255,0.35)'; ctx.lineWidth = 1; ctx.stroke();
// Live spectrum trace with a soft glow.
ctx.save();
ctx.shadowColor = 'rgba(56,189,248,0.7)'; ctx.shadowBlur = 6;
ctx.beginPath();
for (let i = 0; i < n; i++) { const x = xOf(i), y = yOf(amp[i]); i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y); }
ctx.strokeStyle = '#7dd3fc'; ctx.lineWidth = 1.5; ctx.lineJoin = 'round'; ctx.stroke();
ctx.restore();
// VFO marker: you should ALWAYS see where you are. Exact position when the VFO
// is inside the span; the centre in CTR mode; clamped to the nearest edge with
// a sideways arrow in FIX mode when the fixed scope doesn't cover the VFO (so
// you can tell which way to tune to get it back on-screen).
const haveVfo = vfoHz > 0 && lowHz > 0 && highHz > lowHz;
const inSpan = haveVfo && vfoHz >= lowHz && vfoHz <= highHz;
let markerX = -1;
let offEdge = 0; // -1 = VFO off the left edge, +1 = off the right
if (inSpan) markerX = ((vfoHz - lowHz) / (highHz - lowHz)) * w;
else if (!fixedMode) markerX = w / 2;
else if (haveVfo) { offEdge = vfoHz < lowHz ? -1 : 1; markerX = offEdge < 0 ? 1 : w - 1; }
if (markerX >= 0) {
const x = markerX;
ctx.fillStyle = 'rgba(244,63,94,0.10)'; ctx.fillRect(x - 5, 0, 10, h);
ctx.strokeStyle = 'rgba(244,63,94,0.9)'; ctx.lineWidth = 1.25;
ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, h); ctx.stroke();
ctx.fillStyle = 'rgba(244,63,94,0.95)';
if (offEdge === 0) {
ctx.beginPath(); ctx.moveTo(x - 4, 0); ctx.lineTo(x + 4, 0); ctx.lineTo(x, 6); ctx.closePath(); ctx.fill();
} else {
const yh = 8; ctx.beginPath(); ctx.moveTo(x, yh - 5); ctx.lineTo(x + offEdge * 7, yh); ctx.lineTo(x, yh + 5); ctx.closePath(); ctx.fill();
}
}
// Frequency scale. In fixed mode the rig reports usable edge frequencies, so
// we label low/centre/high from them. In centre mode the header frame's edge
// pair isn't a usable low..high range, but the scope is centred on the VFO —
// so we always label the centre with the live VFO frequency (which we fetch
// each sweep), and only add edge labels when the reported edges genuinely
// bracket the VFO. That guarantees you always see your frequency in CTR.
const mhz = (hz: number) => (hz / 1e6).toFixed(3);
ctx.font = '10px ui-monospace, monospace';
ctx.textBaseline = 'bottom';
ctx.shadowColor = 'rgba(0,0,0,0.8)'; ctx.shadowBlur = 3;
ctx.fillStyle = 'rgba(226,232,240,0.85)';
const label = (txt: string, x: number, align: CanvasTextAlign) => { ctx.textAlign = align; ctx.fillText(txt, x, h - 3); };
const validEdges = lowHz > 0 && highHz > lowHz;
if (fixedMode) {
if (validEdges) {
label(mhz(lowHz), 4, 'left');
label(mhz((lowHz + highHz) / 2), w / 2, 'center');
label(mhz(highHz), w - 4, 'right');
}
} else {
if (validEdges && vfoHz >= lowHz && vfoHz <= highHz) {
label(mhz(lowHz), 4, 'left');
label(mhz(highHz), w - 4, 'right');
}
if (vfoHz > 0) label(mhz(vfoHz), w / 2, 'center');
}
ctx.shadowBlur = 0;
drawWaterfall(amp, scale);
};
// drawWaterfall scrolls the history down one row and paints the newest sweep
// as a colour-mapped line at the top.
const drawWaterfall = (amp: number[], scale: number) => {
const cv = wfRef.current;
if (!cv) return;
const w = Math.max(1, cv.clientWidth), h = Math.max(1, cv.clientHeight);
if (cv.width !== w || cv.height !== h) { cv.width = w; cv.height = h; }
const ctx = cv.getContext('2d');
if (!ctx) return;
// Scroll everything down by one pixel row.
ctx.drawImage(cv, 0, 0, w, h - 1, 0, 1, w, h - 1);
// Paint the new top row.
const row = ctx.createImageData(w, 1);
const n = amp.length;
for (let x = 0; x < w; x++) {
const i = Math.min(n - 1, Math.round((x / (w - 1)) * (n - 1)));
const [r, g, b] = wfColor(amp[i] / scale);
const o = x * 4;
row.data[o] = r; row.data[o + 1] = g; row.data[o + 2] = b; row.data[o + 3] = 255;
}
ctx.putImageData(row, 0, 0);
};
// Collapsible card: when the scope is off, only the header band shows (the
// canvas is hidden entirely) so it doesn't waste vertical space. The CTR/FIX
// and ON/OFF controls live in the header itself.
return (
<div className="rounded-xl border border-border bg-card shadow-sm overflow-hidden">
<div className="flex items-center gap-2 px-3 py-2 border-b border-border/60 bg-muted/30">
<Activity className="size-4" style={{ color: '#38bdf8' }} />
<span className="text-xs font-bold uppercase tracking-wider text-foreground/80">{t('icmp.spectrum')}</span>
<div className="ml-auto flex items-center gap-2 shrink-0">
{on && (
<div className="inline-flex rounded-md border border-border overflow-hidden">
<button type="button" onClick={() => pan(-1)} title={t('icmp.scopePanDown')}
className="px-2 py-1 text-xs font-bold bg-card text-muted-foreground hover:bg-muted border-r border-border"></button>
<button type="button" onClick={centerOnVfo} title={t('icmp.scopeCenterVfo')}
className="px-2 py-1 text-[11px] font-bold bg-card text-muted-foreground hover:bg-muted border-r border-border"></button>
<button type="button" onClick={() => pan(1)} title={t('icmp.scopePanUp')}
className="px-2 py-1 text-xs font-bold bg-card text-muted-foreground hover:bg-muted"></button>
</div>
)}
{on && (
<Segmented value={fixed ? 'FIX' : 'CTR'} options={[{ v: 'CTR', l: 'CTR' }, { v: 'FIX', l: 'FIX' }]}
onChange={(v) => setMode(v === 'FIX')} />
)}
<Chip label={on ? 'ON' : 'OFF'} on={on} onClick={toggle} />
</div>
</div>
{on && (
<div className="p-3">
<div className="rounded-xl overflow-hidden ring-1 ring-info/20 shadow-lg shadow-sky-500/5 bg-[#05070e]">
<canvas ref={canvasRef} onDoubleClick={onDblClick}
className="w-full block cursor-crosshair" style={{ height: 140 }} />
<canvas ref={wfRef} className="w-full block" style={{ height: 96 }} />
</div>
</div>
)}
</div>
);
}
// IcomPanel — full control surface (RX DSP + TX) for an Icom on the CI-V backend.
// Unlike the Flex (which pushes state), the Icom is polled: meters/TX state are
// read every cache cycle; DSP set-controls are optimistic and reconcile on the
// next poll. Front-panel knob changes for DSP show after ↻ Refresh.
export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (rst: string) => void; isNetwork?: boolean } = {}) { export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (rst: string) => void; isNetwork?: boolean } = {}) {
// The speaker toggle lives HERE, next to ON/OFF, because that is where the
// operator is looking — burying "stop listening" behind Settings → Audio
// meant a trip through two panels to mute a radio sitting in the same room.
const [listening, setListening] = useState(false);
useEffect(() => {
if (!isNetwork) return;
let alive = true;
const ask = () => AudioMonitorActive().then((v) => { if (alive) setListening(!!v); }).catch(() => {});
ask();
const id = window.setInterval(ask, 2000);
return () => { alive = false; window.clearInterval(id); };
}, [isNetwork]);
const toggleListening = () => {
const next = !listening;
setListening(next);
(next ? AudioStartMonitor() : Promise.resolve(AudioStopMonitor())).catch(() => setListening(!next));
};
const { t } = useI18n(); const { t } = useI18n();
const [st, setSt] = useState<IcomState>(ZERO); const [st, setSt] = useState<IcomState>(ZERO);
const [cat, setCat] = useState<any>(null); // RigState (freq/mode/split) for the VFO display const [cat, setCat] = useState<any>(null); // RigState (freq/mode/split) for the VFO display
@@ -627,7 +378,9 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
const toggleMox = () => { const toggleMox = () => {
const next = !txRef.current; const next = !txRef.current;
txRef.current = next; txRef.current = next;
set({ transmitting: next }, () => IcomSetPTT(next)); // Through the console binding: on a network station the PC microphone
// rides with the PTT (silence otherwise); on USB it keys and nothing more.
set({ transmitting: next }, () => IcomConsolePTT(next));
}; };
const tune = async () => { const tune = async () => {
@@ -670,8 +423,13 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
// other is TX (freq_hz); otherwise there's a single VFO (freq_hz). // other is TX (freq_hz); otherwise there's a single VFO (freq_hz).
const split = !!cat?.split; const split = !!cat?.split;
const mainHz: number = split ? (cat?.freq_rx_hz || 0) : (cat?.freq_hz || 0); const mainHz: number = split ? (cat?.freq_rx_hz || 0) : (cat?.freq_hz || 0);
const subHz: number = split ? (cat?.freq_hz || 0) : 0; // The sub receiver's dial is worth seeing whether or not split is on —
const curMode: string = cat?.mode || st.mode || ''; // in split the CAT state's TX freq is the authority, otherwise the panel's
// own sub_hz read.
const subHz: number = split ? (cat?.freq_hz || 0) : (st.sub_hz || 0);
// The panel's own mode first: it carries the sideband (USB/LSB) where the
// CAT state folds both into ADIF's SSB.
const curMode: string = st.mode || cat?.mode || '';
// Mode-dependent controls: VOX / speech-comp / mic are voice-only (hidden on // Mode-dependent controls: VOX / speech-comp / mic are voice-only (hidden on
// CW and data); APF (audio peak filter) is CW-only. Fold USB/LSB into phone. // CW and data); APF (audio peak filter) is CW-only. Fold USB/LSB into phone.
const um = curMode.toUpperCase(); const um = curMode.toUpperCase();
@@ -700,6 +458,14 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
rig's LAN server stays alive in standby, so both work. */} rig's LAN server stays alive in standby, so both work. */}
{isNetwork && ( {isNetwork && (
<> <>
<button type="button" onClick={toggleListening}
title={listening ? t('icmp.speakerOffHint') : t('icmp.speakerOnHint')}
className={cn('inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs font-bold',
listening
? 'border-primary/60 bg-primary/10 text-primary hover:bg-primary/20'
: 'border-border bg-card text-muted-foreground hover:bg-muted')}>
{listening ? <Volume2 className="size-3.5" /> : <VolumeX className="size-3.5" />}
</button>
<button type="button" onClick={() => IcomSetPower(true).catch(() => {})} title={t('icmp.powerOnHint')} <button type="button" onClick={() => IcomSetPower(true).catch(() => {})} title={t('icmp.powerOnHint')}
className="inline-flex items-center gap-1 rounded-md border border-success/60 bg-success/10 px-2 py-1 text-xs font-bold text-success hover:bg-success/20"> className="inline-flex items-center gap-1 rounded-md border border-success/60 bg-success/10 px-2 py-1 text-xs font-bold text-success hover:bg-success/20">
<Power className="size-3.5" /> ON <Power className="size-3.5" /> ON
@@ -741,7 +507,7 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
</div> </div>
</div> </div>
{/* Mode selector row (RS-BA1's SSB/CW/RTTY/PSK/AM/FM). */} {/* Mode selector row (RS-BA1's SSB/CW/RTTY/PSK/AM/FM). */}
<div className="grid grid-cols-6 border-t border-border/60 divide-x divide-border/60"> <div className="grid grid-cols-7 border-t border-border/60 divide-x divide-border/60">
{MODES.map((m) => { {MODES.map((m) => {
const on = modeMatches(m, curMode); const on = modeMatches(m, curMode);
return ( return (
@@ -755,20 +521,28 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
</div> </div>
</div> </div>
{/* Live meters — always visible: S (RX, click → RST), Po in watts, SWR. */} {/* Live meters the SAME LED MeterBar every other console uses (Flex,
<div className="rounded-xl border border-border bg-card px-3 py-2.5 shadow-sm grid grid-cols-1 sm:grid-cols-3 gap-x-5 gap-y-2"> Elecraft, the amp cards): one instrument look across the app, per the
operator's "les consoles doivent se ressembler". S is clickable RST. */}
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
{(() => { const sp = sParts(st.s_meter); return ( {(() => { const sp = sParts(st.s_meter); return (
<Meter label="S" value={st.s_meter} accent="#22c55e" scale={sp.label} <MeterBar label="S-METER" value={st.transmitting ? 0 : st.s_meter} lo={0} hi={100}
accent="#16a34a" segColor={sSegColor}
display={st.transmitting ? '—' : sp.label}
title={onReportRST ? t('rst.clickToFill') : undefined} title={onReportRST ? t('rst.clickToFill') : undefined}
onClick={onReportRST ? () => onReportRST(sMeterRST(sp.s, sp.over, st.mode)) : undefined} /> onClick={onReportRST ? () => { if (!st.transmitting) onReportRST(sMeterRST(sp.s, sp.over, st.mode)); } : undefined} />
); })()} ); })()}
<Meter label="Po" value={st.power_meter} accent="#ef4444" scale={`${st.power_meter} W`} /> {(() => {
<Meter label="SWR" value={st.swr_meter} accent="#f59e0b" scale={st.swr_meter > 0 ? `${(1 + st.swr_meter / 33.3).toFixed(1)}` : '1.0'} /> if ((st.model ?? '').includes('7760')) {
const { w, defl } = icomWatts(st.power_meter);
return <MeterBar label="PWR" value={defl} lo={0} hi={100} accent="#0ea5e9" display={`${w} W`} />;
}
return <MeterBar label="PWR" value={st.power_meter} lo={0} hi={100} accent="#0ea5e9" display={`${st.power_meter} W`} />;
})()}
<MeterBar label="SWR" value={st.swr_meter > 0 ? 1 + st.swr_meter / 33.3 : 0} lo={1} hi={4} accent="#f59e0b"
display={st.swr_meter > 0 ? (1 + st.swr_meter / 33.3).toFixed(1) : '—'} />
</div> </div>
{/* Spectrum panadapter (full width). */}
<ScopePanadapter />
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3"> <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
{/* Band buttons + antenna selection. */} {/* Band buttons + antenna selection. */}
<Card icon={Antenna} title={t('icmp.bandsAntenna')} accent="#0891b2"> <Card icon={Antenna} title={t('icmp.bandsAntenna')} accent="#0891b2">
@@ -797,10 +571,10 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
<Card icon={SlidersHorizontal} title={t('icmp.clarifiers')} accent="#8b5cf6"> <Card icon={SlidersHorizontal} title={t('icmp.clarifiers')} accent="#8b5cf6">
<ShiftRow label="RIT" accent="#8b5cf6" on={st.rit_on} hz={st.rit_hz} <ShiftRow label="RIT" accent="#8b5cf6" on={st.rit_on} hz={st.rit_hz}
onToggle={() => set({ rit_on: !st.rit_on }, () => IcomSetRITOn(!st.rit_on))} onToggle={() => set({ rit_on: !st.rit_on }, () => IcomSetRITOn(!st.rit_on))}
onDelta={(d) => setRit(st.rit_hz + d)} onClear={() => setRit(0)} /> onSet={setRit} />
<ShiftRow label="ΔTX" accent="#f59e0b" on={st.xit_on} hz={st.rit_hz} <ShiftRow label="ΔTX" accent="#f59e0b" on={st.xit_on} hz={st.rit_hz}
onToggle={() => set({ xit_on: !st.xit_on }, () => IcomSetXITOn(!st.xit_on))} onToggle={() => set({ xit_on: !st.xit_on }, () => IcomSetXITOn(!st.xit_on))}
onDelta={(d) => setRit(st.rit_hz + d)} onClear={() => setRit(0)} /> onSet={setRit} />
<p className="text-[11px] text-muted-foreground">{t('icmp.ritHint')}</p> <p className="text-[11px] text-muted-foreground">{t('icmp.ritHint')}</p>
</Card> </Card>
@@ -808,7 +582,11 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
<Card icon={Mic} title={t('icmp.transmit')} accent="#ef4444"> <Card icon={Mic} title={t('icmp.transmit')} accent="#ef4444">
<Row label={t('icmp.power')}> <Row label={t('icmp.power')}>
<Slider value={st.rf_power} accent="#ef4444" onChange={(v) => set({ rf_power: v }, () => IcomSetRFPower(v))} /> <Slider value={st.rf_power} accent="#ef4444" onChange={(v) => set({ rf_power: v }, () => IcomSetRFPower(v))} />
<span className="w-8 text-right text-xs font-mono tabular-nums text-muted-foreground">{st.rf_power}</span> {/* PC is a percentage of the rig's rated power; on a 200 W rig the
operator thinks in watts, so say it in watts there. */}
<span className="w-12 text-right text-xs font-mono tabular-nums text-muted-foreground">
{(st.model ?? '').includes('7760') ? `${st.rf_power * 2} W` : st.rf_power}
</span>
</Row> </Row>
{isPhone && ( {isPhone && (
<Row label={t('icmp.mic')}> <Row label={t('icmp.mic')}>
@@ -823,6 +601,9 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
{tx ? 'TX ON' : 'MOX'} {tx ? 'TX ON' : 'MOX'}
</button> </button>
<Chip label="SPLIT" on={st.split} onClick={() => set({ split: !st.split }, () => IcomSetSplit(!st.split))} /> <Chip label="SPLIT" on={st.split} onClick={() => set({ split: !st.split }, () => IcomSetSplit(!st.split))} />
{/* Tuner IN/OUT TUNE below starts a cycle but could never take the
tuner back out of line. */}
<Chip label="ATU" on={!!st.atu_on} onClick={() => set({ atu_on: !st.atu_on } as any, () => IcomSetATU(!st.atu_on))} />
<button type="button" onClick={tune} disabled={tuning} <button type="button" onClick={tune} disabled={tuning}
className={cn('w-14 shrink-0 px-2 py-1.5 rounded-md text-[11px] font-bold border transition-colors', className={cn('w-14 shrink-0 px-2 py-1.5 rounded-md text-[11px] font-bold border transition-colors',
tuning ? 'bg-warning border-warning text-warning-foreground animate-pulse' : 'bg-card text-foreground border-border hover:bg-muted')}> tuning ? 'bg-warning border-warning text-warning-foreground animate-pulse' : 'bg-card text-foreground border-border hover:bg-muted')}>
+72
View File
@@ -0,0 +1,72 @@
import { useState } from 'react';
import { cn } from '@/lib/utils';
import { WheelRange } from '@/components/WheelRange';
// LevelRow — a named level with a slider, a value you can type into, and ±.
//
// Shared, like ShiftRow, and for the same complaint: the consoles each drew
// their levels their own way. This is the wide shape — one row per level, the
// slider taking the width it needs — rather than two half-width sliders side by
// side, which is what "c'est laid et elles sont toutes petites" was about.
//
// Four ways to move it, so nobody has to learn ours: drag, wheel over the
// track, ± for one step, or click the number and type. Typing matters for the
// levels TCI reports in real units — a squelch at -95 dBm is a value an
// operator knows, not a position to hunt for with a mouse.
export function LevelRow({
label, value, min = 0, max = 100, step = 1, unit = '', accent, disabled, onSet,
}: {
label: string;
value: number;
min?: number;
max?: number;
step?: number;
unit?: string;
accent?: string;
disabled?: boolean;
onSet: (v: number) => void;
}) {
const [editing, setEditing] = useState<string | null>(null);
const clamp = (v: number) => Math.max(min, Math.min(max, v));
const commit = (raw: string) => {
setEditing(null);
const v = parseInt(raw.replace(/[^0-9+-]/g, ''), 10);
if (!Number.isNaN(v)) onSet(clamp(v));
};
return (
<div className="flex items-center gap-3">
<span className="w-24 shrink-0 text-[11px] font-bold uppercase tracking-wider text-muted-foreground">
{label}
</span>
<WheelRange
min={min} max={max} step={step} value={value} disabled={disabled} accent={accent}
onChange={onSet}
className="h-2.5 flex-1 [&::-webkit-slider-thumb]:size-4"
/>
<div className={cn('flex items-center gap-0.5 shrink-0', disabled && 'opacity-40')}>
<button type="button" disabled={disabled} onClick={() => onSet(clamp(value - step))}
className="px-1.5 text-sm font-bold text-muted-foreground hover:text-foreground disabled:opacity-40"></button>
{editing !== null ? (
<input
autoFocus
value={editing}
onChange={(e) => setEditing(e.target.value)}
onBlur={(e) => commit(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') commit((e.target as HTMLInputElement).value);
else if (e.key === 'Escape') setEditing(null);
}}
className="w-14 rounded border border-border bg-background px-1 text-right text-xs font-mono tabular-nums outline-none"
/>
) : (
<button type="button" disabled={disabled} onClick={() => setEditing(String(value))}
className="w-14 text-right text-xs font-mono tabular-nums hover:text-primary disabled:cursor-default">
{value}{unit}
</button>
)}
<button type="button" disabled={disabled} onClick={() => onSet(clamp(value + step))}
className="px-1.5 text-sm font-bold text-muted-foreground hover:text-foreground disabled:opacity-40">+</button>
</div>
</div>
);
}
+52 -14
View File
@@ -4,6 +4,7 @@ import 'leaflet/dist/leaflet.css';
import { nightPolygon } from '../lib/greyline'; import { nightPolygon } from '../lib/greyline';
import { gridToLatLon, gridSquareBounds, greatCirclePoints, pathBetween, destinationPoint } from '@/lib/maidenhead'; import { gridToLatLon, gridSquareBounds, greatCirclePoints, pathBetween, destinationPoint } from '@/lib/maidenhead';
import { writeUiPref } from '@/lib/uiPref'; import { writeUiPref } from '@/lib/uiPref';
import { formatDistance } from '@/lib/units';
// Persisted free-pan view of the world map (when auto-zoom is off). // Persisted free-pan view of the world map (when auto-zoom is off).
function loadMapView(): { lat: number; lon: number; zoom: number } | null { function loadMapView(): { lat: number; lon: number; zoom: number } | null {
@@ -42,8 +43,18 @@ function unwrapLon(ring: [number, number][]): [number, number][] {
return out; return out;
} }
const CARTO_LIGHT = 'https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png'; // CARTO IS GONE, and it went the same way OpenStreetMap did.
const CARTO_ATTR = '&copy; OpenStreetMap &copy; CARTO'; //
// Their key-free basemaps now serve tiles stamped "API KEY REQUIRED" across
// the middle of the map — reported by an operator whose Light and Voyager views
// came up watermarked. They still answer 200 with a real image, which is why
// nothing here could detect it: the map looks like it is working and simply
// says otherwise in large grey letters.
//
// So both are replaced by Esri layers, the same provider already behind Street
// and Satellite. That is deliberate: a second key-free provider is a second
// chance to be cut off, and this one has already been serving the other two
// views for as long as OpsLog has had a map.
// NOT tile.openstreetmap.org. Those are OpenStreetMap's VOLUNTEER-run servers, // NOT tile.openstreetmap.org. Those are OpenStreetMap's VOLUNTEER-run servers,
// and their usage policy does not cover a desktop application handed to an // and their usage policy does not cover a desktop application handed to an
@@ -55,17 +66,33 @@ const CARTO_ATTR = '&copy; OpenStreetMap &copy; CARTO';
// still credits OpenStreetMap) and Esri. Anything added here later must be // still credits OpenStreetMap) and Esri. Anything added here later must be
// checked the same way — a free tile URL is not the same thing as a tile URL we // checked the same way — a free tile URL is not the same thing as a tile URL we
// are allowed to ship. // are allowed to ship.
const ESRI_STREET = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}'; const ESRI = 'https://server.arcgisonline.com/ArcGIS/rest/services';
const ESRI_STREET = ESRI + '/World_Street_Map/MapServer/tile/{z}/{y}/{x}';
const ESRI_STREET_ATTR = 'Tiles &copy; Esri — Source: Esri, HERE, Garmin, &copy; OpenStreetMap contributors'; const ESRI_STREET_ATTR = 'Tiles &copy; Esri — Source: Esri, HERE, Garmin, &copy; OpenStreetMap contributors';
// The plain background the old Carto "Light" was: a pale canvas that lets the
// paths and the spots carry the colour. Its names come on a separate
// transparent layer, the same arrangement the satellite view already uses.
const ESRI_LIGHT = ESRI + '/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}';
const ESRI_LIGHT_LABELS = ESRI + '/Canvas/World_Light_Gray_Reference/MapServer/tile/{z}/{y}/{x}';
const ESRI_LIGHT_ATTR = 'Tiles &copy; Esri — Esri, DeLorme, NAVTEQ';
// Selectable basemaps for the world (great-circle) map. All key-free and all // Selectable basemaps for the world (great-circle) map. All key-free and all
// LABELLED (country/continent names). `labelsUrl` adds a transparent place-name // LABELLED (country/continent names). `labelsUrl` adds a transparent place-name
// overlay on top of an imagery basemap (so satellite keeps its names too). // overlay on top of an imagery basemap (so satellite keeps its names too).
export type BasemapKey = 'light' | 'voyager' | 'street' | 'satellite'; export type BasemapKey = 'light' | 'voyager' | 'street' | 'satellite';
export const BASEMAPS: Record<BasemapKey, { label: string; url: string; attr: string; subdomains?: string; labelsUrl?: string }> = { // maxNativeZoom is where a layer RUNS OUT of tiles. Leaflet then upscales the
light: { label: 'Light', url: CARTO_LIGHT, attr: CARTO_ATTR, subdomains: 'abcd' }, // last real one instead of asking for a level that does not exist, which is the
voyager: { label: 'Voyager', url: 'https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png', // difference between a slightly soft map and a blank grey square: the light
attr: CARTO_ATTR, subdomains: 'abcd' }, // canvas stops at 16 where the imagery and the topo go on to 19.
export const BASEMAPS: Record<BasemapKey, { label: string; url: string; attr: string; subdomains?: string; labelsUrl?: string; maxNativeZoom?: number }> = {
light: { label: 'Light', url: ESRI_LIGHT, attr: ESRI_LIGHT_ATTR, labelsUrl: ESRI_LIGHT_LABELS, maxNativeZoom: 16 },
// The key is still "voyager" so that everyone who chose it keeps their view
// rather than being silently moved to another one. What it draws is Esri's
// topographic map: terrain under the labels, which is what made Voyager worth
// choosing over the plain canvas.
voyager: { label: 'Topo', url: ESRI + '/World_Topo_Map/MapServer/tile/{z}/{y}/{x}',
attr: 'Tiles &copy; Esri — Esri, HERE, Garmin, USGS, NGA, &copy; OpenStreetMap contributors' },
street: { label: 'Street', url: ESRI_STREET, attr: ESRI_STREET_ATTR }, street: { label: 'Street', url: ESRI_STREET, attr: ESRI_STREET_ATTR },
satellite: { label: 'Satellite', url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', satellite: { label: 'Satellite', url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
attr: 'Tiles &copy; Esri — Source: Esri, Maxar, Earthstar Geographics', attr: 'Tiles &copy; Esri — Source: Esri, Maxar, Earthstar Geographics',
@@ -100,7 +127,8 @@ export function addBasemap(
if (labels.current) { m.removeLayer(labels.current); labels.current = null; } if (labels.current) { m.removeLayer(labels.current); labels.current = null; }
const bm = BASEMAPS[key]; const bm = BASEMAPS[key];
const tileOpts: L.TileLayerOptions = { const tileOpts: L.TileLayerOptions = {
maxZoom: 19, updateWhenIdle: true, updateWhenZooming: false, keepBuffer: 1, maxZoom: 19, maxNativeZoom: bm.maxNativeZoom ?? 19,
updateWhenIdle: true, updateWhenZooming: false, keepBuffer: 1,
noWrap: !!opts?.noWrap, noWrap: !!opts?.noWrap,
...(opts?.bounds ? { bounds: opts.bounds } : {}), ...(opts?.bounds ? { bounds: opts.bounds } : {}),
}; };
@@ -342,8 +370,14 @@ export function WorldMap({ fromGrid, toGrid, fromLabel, toLabel, beamAzimuths, b
if (autoZoom) { if (autoZoom) {
if (from && to && arcPts) { if (from && to && arcPts) {
const bounds = L.latLngBounds([[from.lat, from.lon], [to.lat, to.lon]]); // Latitudes clamped to Mercator's edge (±85°): the arc to a polar
arcPts.forEach((p) => bounds.extend(p as L.LatLngExpression)); // entity (Franz Josef Land) peaks near 88°N, and fitting the raw
// points framed a band of tile-less white above the top of the world.
// The line itself still draws to wherever it goes — only the CAMERA
// stays where there is a map to show.
const clamp = (lat: number) => Math.max(-85, Math.min(85, lat));
const bounds = L.latLngBounds([[clamp(from.lat), from.lon], [clamp(to.lat), to.lon]]);
arcPts.forEach((p) => bounds.extend([clamp(p[0]), p[1]] as L.LatLngExpression));
wm.fitBounds(bounds, { padding: [30, 30], maxZoom: 6 }); wm.fitBounds(bounds, { padding: [30, 30], maxZoom: 6 });
} else if (to) { } else if (to) {
wm.setView([to.lat, to.lon], 3); wm.setView([to.lat, to.lon], 3);
@@ -419,8 +453,8 @@ export function WorldMap({ fromGrid, toGrid, fromLabel, toLabel, beamAzimuths, b
</button> </button>
{path && ( {path && (
<div className="absolute bottom-1 left-1 z-[500] rounded-md bg-card/90 backdrop-blur px-2 py-1 text-[11px] font-mono shadow border border-border pointer-events-none"> <div className="absolute bottom-1 left-1 z-[500] rounded-md bg-card/90 backdrop-blur px-2 py-1 text-[11px] font-mono shadow border border-border pointer-events-none">
<div><span className="text-muted-foreground">Dist</span> {Math.round(path.distanceShort).toLocaleString()} km <div><span className="text-muted-foreground">Dist</span> {formatDistance(path.distanceShort)}
<span className="text-muted-foreground"> · LP</span> {Math.round(path.distanceLong).toLocaleString()} km</div> <span className="text-muted-foreground"> · LP</span> {formatDistance(path.distanceLong)}</div>
<div><span className="text-muted-foreground">Az SP</span> {Math.round(path.bearingShort)}° <div><span className="text-muted-foreground">Az SP</span> {Math.round(path.bearingShort)}°
<span className="text-muted-foreground"> · LP</span> {Math.round(path.bearingLong)}°</div> <span className="text-muted-foreground"> · LP</span> {Math.round(path.bearingLong)}°</div>
</div> </div>
@@ -448,8 +482,12 @@ export function LocatorMap({ toGrid, toLabel }: LocatorProps) {
// single ring of buffer tiles. Requesting tiles as fast as the pointer // single ring of buffer tiles. Requesting tiles as fast as the pointer
// moves is what gets an app blocked, and the next provider is under no // moves is what gets an app blocked, and the next provider is under no
// more obligation to tolerate it than the last one was. // more obligation to tolerate it than the last one was.
L.tileLayer(CARTO_LIGHT, { L.tileLayer(ESRI_LIGHT, {
attribution: CARTO_ATTR, subdomains: 'abcd', maxZoom: 19, attribution: ESRI_LIGHT_ATTR, maxZoom: 19, maxNativeZoom: 16,
updateWhenIdle: true, updateWhenZooming: false, keepBuffer: 1,
}).addTo(m);
L.tileLayer(ESRI_LIGHT_LABELS, {
maxZoom: 19, maxNativeZoom: 16,
updateWhenIdle: true, updateWhenZooming: false, keepBuffer: 1, updateWhenIdle: true, updateWhenZooming: false, keepBuffer: 1,
}).addTo(m); }).addTo(m);
locatorOverlay.current = L.layerGroup().addTo(m); locatorOverlay.current = L.layerGroup().addTo(m);
+43 -2
View File
@@ -8,7 +8,7 @@ import {
Select, SelectTrigger, SelectValue, SelectContent, SelectItem, Select, SelectTrigger, SelectValue, SelectContent, SelectItem,
} from '@/components/ui/select'; } from '@/components/ui/select';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { FindQSOsForUpload, UploadQSOsManual, DownloadConfirmations, CancelConfirmations, ImportHamlogConfirmations, ExportHamlogUnmatched, OpenADIFFile, SaveADIFFile, SyncPOTAHunterLog, ListQSO, BulkUpdateQSL, UploadCallsign, GetSlotStats } from '../../wailsjs/go/main/App'; import { GetLoTWQSLDetail, SetLoTWQSLDetail, GetLoTWDownloadAllCalls, SetLoTWDownloadAllCalls, OpenExternalURL, FindQSOsForUpload, UploadQSOsManual, DownloadConfirmations, CancelConfirmations, ImportHamlogConfirmations, ExportHamlogUnmatched, OpenADIFFile, SaveADIFFile, SyncPOTAHunterLog, ListQSO, BulkUpdateQSL, UploadCallsign, GetSlotStats } from '../../wailsjs/go/main/App';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { RecentQSOsGrid } from '@/components/RecentQSOsGrid'; import { RecentQSOsGrid } from '@/components/RecentQSOsGrid';
import { EventsOn } from '../../wailsjs/runtime/runtime'; import { EventsOn } from '../../wailsjs/runtime/runtime';
@@ -31,7 +31,7 @@ const UPLOAD_COLS: ColDef<UploadRow>[] = [
]; ];
type Confirmation = { type Confirmation = {
callsign: string; qso_date: string; band: string; mode: string; country: string; callsign: string; station?: string; qso_date: string; band: string; mode: string; country: string;
new_dxcc: boolean; new_band: boolean; new_mode: boolean; new_slot: boolean; new_dxcc: boolean; new_band: boolean; new_mode: boolean; new_slot: boolean;
}; };
@@ -255,6 +255,15 @@ export function QSLManagerPanel({ onEditQSO, actions, paperRequest }: {
const [searching, setSearching] = useState(false); const [searching, setSearching] = useState(false);
const [error, setError] = useState(''); const [error, setError] = useState('');
const [addNotFound, setAddNotFound] = useState(false); const [addNotFound, setAddNotFound] = useState(false);
// LoTW only: pull the whole account rather than this profile's callsign.
const [lotwAllCalls, setLotwAllCalls] = useState(false);
// LoTW only: ask for the QSL dates and station details. Ten times slower to
// build, so it is a choice rather than the default it used to be.
const [lotwDetail, setLotwDetail] = useState(false);
useEffect(() => {
GetLoTWDownloadAllCalls().then((v: boolean) => setLotwAllCalls(!!v)).catch(() => {});
GetLoTWQSLDetail().then((v: boolean) => setLotwDetail(!!v)).catch(() => {});
}, []);
// Download date window: 'last' = incremental since last pull, 'date' = from a // Download date window: 'last' = incremental since last pull, 'date' = from a
// chosen date, 'all' = everything. // chosen date, 'all' = everything.
const [sinceMode, setSinceMode] = useState<'last' | 'date' | 'all'>('last'); const [sinceMode, setSinceMode] = useState<'last' | 'date' | 'all'>('last');
@@ -434,6 +443,18 @@ export function QSLManagerPanel({ onEditQSO, actions, paperRequest }: {
{paperBusy ? <Loader2 className="size-3.5 animate-spin" /> : <Search className="size-3.5" />} {paperBusy ? <Loader2 className="size-3.5 animate-spin" /> : <Search className="size-3.5" />}
{t('qslm.search')} {t('qslm.search')}
</Button> </Button>
{/* The station's QRZ page, one click away: writing a card means
reading the address, the manager and whether they even want
paper, and all three are on that page. */}
<Button size="sm" variant="outline" className="h-8" disabled={!paperCall.trim()}
title={t('qslm.qrzTitle')}
onClick={() => {
const c = paperCall.trim().toUpperCase();
if (c) OpenExternalURL(`https://www.qrz.com/db/${c}`).catch(() => {});
}}>
<ExternalLink className="size-3.5" />
QRZ
</Button>
<span className="text-[11px] text-muted-foreground self-center">{t('qslm.paperHint')}</span> <span className="text-[11px] text-muted-foreground self-center">{t('qslm.paperHint')}</span>
</> </>
) : ( ) : (
@@ -598,6 +619,10 @@ export function QSLManagerPanel({ onEditQSO, actions, paperRequest }: {
<thead className="sticky top-0 bg-card"> <thead className="sticky top-0 bg-card">
<tr className="text-left text-muted-foreground border-b border-border"> <tr className="text-left text-muted-foreground border-b border-border">
<th className="py-1.5 px-2">{t('qslm.thDateUtc')}</th><th className="py-1.5 px-2">{t('qslm.thCallsign')}</th> <th className="py-1.5 px-2">{t('qslm.thDateUtc')}</th><th className="py-1.5 px-2">{t('qslm.thCallsign')}</th>
{/* Which of the operator's callsigns the contact was made
under. Only worth a column when the list can hold more than
one see "All my callsigns" on the download. */}
{shownConfs.some((c) => c.station) && <th className="py-1.5 px-2">{t('qslm.thStation')}</th>}
<th className="py-1.5 px-2">{t('qslm.thBand')}</th><th className="py-1.5 px-2">{t('qslm.thMode')}</th> <th className="py-1.5 px-2">{t('qslm.thBand')}</th><th className="py-1.5 px-2">{t('qslm.thMode')}</th>
<th className="py-1.5 px-2">{t('qslm.thCountry')}</th><th className="py-1.5 px-2">{t('qslm.thNew')}</th> <th className="py-1.5 px-2">{t('qslm.thCountry')}</th><th className="py-1.5 px-2">{t('qslm.thNew')}</th>
</tr> </tr>
@@ -607,6 +632,9 @@ export function QSLManagerPanel({ onEditQSO, actions, paperRequest }: {
<tr key={i} className="border-b border-border/40"> <tr key={i} className="border-b border-border/40">
<td className="py-1 px-2 font-mono">{fmtDate(c.qso_date)}</td> <td className="py-1 px-2 font-mono">{fmtDate(c.qso_date)}</td>
<td className="py-1 px-2 font-mono font-bold">{c.callsign}</td> <td className="py-1 px-2 font-mono font-bold">{c.callsign}</td>
{shownConfs.some((x) => x.station) && (
<td className="py-1 px-2 font-mono text-muted-foreground">{c.station ?? ''}</td>
)}
<td className="py-1 px-2">{c.band}</td> <td className="py-1 px-2">{c.band}</td>
<td className="py-1 px-2">{c.mode}</td> <td className="py-1 px-2">{c.mode}</td>
<td className="py-1 px-2 text-muted-foreground">{c.country}</td> <td className="py-1 px-2 text-muted-foreground">{c.country}</td>
@@ -736,6 +764,19 @@ export function QSLManagerPanel({ onEditQSO, actions, paperRequest }: {
<Checkbox checked={addNotFound} onCheckedChange={(c) => setAddNotFound(!!c)} /> <Checkbox checked={addNotFound} onCheckedChange={(c) => setAddNotFound(!!c)} />
{t('qslm.addNotFound')} {t('qslm.addNotFound')}
</label> </label>
{service === 'lotw' && (
<label className="flex items-center gap-1.5 text-[11px] text-muted-foreground cursor-pointer" title={t('qslm.lotwDetailTitle')}>
<Checkbox checked={lotwDetail || addNotFound} disabled={addNotFound}
onCheckedChange={(c) => { setLotwDetail(!!c); SetLoTWQSLDetail(!!c); }} />
{t('qslm.lotwDetail')}
</label>
)}
{service === 'lotw' && (
<label className="flex items-center gap-1.5 text-[11px] text-muted-foreground cursor-pointer" title={t('qslm.lotwAllCallsTitle')}>
<Checkbox checked={lotwAllCalls} onCheckedChange={(c) => { setLotwAllCalls(!!c); SetLoTWDownloadAllCalls(!!c); }} />
{t('qslm.lotwAllCalls')}
</label>
)}
</>)} </>)}
</div> </div>
<Button size="sm" onClick={upload} disabled={selectedCount === 0 || busy}> <Button size="sm" onClick={upload} disabled={selectedCount === 0 || busy}>
+7 -3
View File
@@ -9,6 +9,7 @@ import { formatDateTimeUTC, formatDateOnly, getDateFormat, subscribeDateFormat }
import { AgGridReact } from 'ag-grid-react'; import { AgGridReact } from 'ag-grid-react';
import { Columns3, FilterX, ListChecks } from 'lucide-react'; import { Columns3, FilterX, ListChecks } from 'lucide-react';
import type { QSOForm } from '@/types'; import type { QSOForm } from '@/types';
import { distanceUnit, distanceValue, subscribeDistanceUnit } from '@/lib/units';
import { QSOContextMenu, type QSOMenuState } from './QSOContextMenu'; import { QSOContextMenu, type QSOMenuState } from './QSOContextMenu';
import { import {
Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription, Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription,
@@ -177,8 +178,9 @@ export const makeColCatalog = (t: TFn, myGrid?: string): ColEntry[] => [
{ group: 'Contacted', label: t('rqg.c.lon'), colId: 'lon', headerName: t('rqg.c.lon'), field: 'lon' as any, width: 90, type: 'rightAligned', cellClass: 'font-mono' }, { group: 'Contacted', label: t('rqg.c.lon'), colId: 'lon', headerName: t('rqg.c.lon'), field: 'lon' as any, width: 90, type: 'rightAligned', cellClass: 'font-mono' },
// Derived, not stored: computed from the two locations at display time, like // Derived, not stored: computed from the two locations at display time, like
// the cluster grid's own distance column. // the cluster grid's own distance column.
{ group: 'Contacted', label: t('rqg.c.distance_km'), colId: 'distance_km', headerName: t('rqg.h.distance_km'), width: 90, type: 'rightAligned', cellClass: 'font-mono', { group: 'Contacted', label: t('rqg.c.distance_km'), colId: 'distance_km',
valueGetter: (p) => qsoDistanceKm(p.data, myGrid), headerName: t('rqg.h.distance_km') + ' (' + distanceUnit() + ')', width: 95, type: 'rightAligned', cellClass: 'font-mono',
valueGetter: (p) => { const km = qsoDistanceKm(p.data, myGrid); return km ? distanceValue(km) : km; },
comparator: (a, b) => (a ?? 0) - (b ?? 0), defaultVisible: true }, comparator: (a, b) => (a ?? 0) - (b ?? 0), defaultVisible: true },
{ group: 'Contacted', label: t('rqg.c.email'), colId: 'email', headerName: t('rqg.c.email'), field: 'email' as any, width: 180 }, { group: 'Contacted', label: t('rqg.c.email'), colId: 'email', headerName: t('rqg.c.email'), field: 'email' as any, width: 180 },
{ group: 'Contacted', label: t('rqg.c.web'), colId: 'web', headerName: t('rqg.c.web'), field: 'web' as any, width: 180 }, { group: 'Contacted', label: t('rqg.c.web'), colId: 'web', headerName: t('rqg.c.web'), field: 'web' as any, width: 180 },
@@ -335,7 +337,9 @@ export function RecentQSOsGrid({ rows, myGrid, selectAllSignal, selectRowSignal,
// inside the column definitions, so nothing else would notice. // inside the column definitions, so nothing else would notice.
const [dateFmt, setDateFmt] = useState(getDateFormat); const [dateFmt, setDateFmt] = useState(getDateFormat);
useEffect(() => subscribeDateFormat(() => setDateFmt(getDateFormat())), []); useEffect(() => subscribeDateFormat(() => setDateFmt(getDateFormat())), []);
const COL_CATALOG = useMemo(() => makeColCatalog(t, myGrid), [t, myGrid, dateFmt]); const [distUnit, setDistUnit] = useState(distanceUnit);
useEffect(() => subscribeDistanceUnit(() => setDistUnit(distanceUnit())), []);
const COL_CATALOG = useMemo(() => makeColCatalog(t, myGrid), [t, myGrid, dateFmt, distUnit]);
// Right-click: if the clicked row isn't already part of the selection, // Right-click: if the clicked row isn't already part of the selection,
// select just it; then open the bulk-action menu on the whole selection. // select just it; then open the bulk-action menu on the whole selection.
+451 -77
View File
@@ -9,11 +9,13 @@ import {
import { import {
GetLookupSettings, SaveLookupSettings, ClearLookupCache, TestLookupProvider, GetLookupSettings, SaveLookupSettings, ClearLookupCache, TestLookupProvider,
GetListsSettings, SaveListsSettings, GetListsSettings, SaveListsSettings,
GetCATSettings, SaveCATSettings, DiscoverFlexRadios, GetCATSettings, SaveCATSettings, GetRadios, SaveRadios, SetActiveRadio, ActiveRadioID, DiscoverFlexRadios, DVKDelete,
GetChaseSettings, SaveChaseSettings,
GetAudioMonitorPref,
ListProfiles, GetActiveProfile, SaveProfile, DeleteProfile, ActivateProfile, DuplicateProfile, ListProfiles, GetActiveProfile, SaveProfile, DeleteProfile, ActivateProfile, DuplicateProfile,
GetRotators, SaveRotators, TestRotatorDevice, RotatorPark, RotatorStop, GetRotators, SaveRotators, TestRotatorDevice, RotatorPark, RotatorStop,
GetRotorPresets, SaveRotorPresets, ResetRotorPresets, GetRotorPresets, SaveRotorPresets, ResetRotorPresets,
GetUltrabeamSettings, SaveUltrabeamSettings, TestUltrabeam, CompactDatabase, CheckHamlogKey, CompareRDASources, GetUltrabeamSettings, SaveUltrabeamSettings, TestUltrabeam, CompactDatabase, CheckHamlogKey, CompareRDASources, ApplyRDAChoices,
GetAntGeniusSettings, SaveAntGeniusSettings, GetAntGeniusSettings, SaveAntGeniusSettings,
GetTunerGeniusSettings, SaveTunerGeniusSettings, GetTunerGeniusSettings, SaveTunerGeniusSettings,
GetPSUSettings, SavePSUSettings, GetPSUSettings, SavePSUSettings,
@@ -80,6 +82,8 @@ import {
} from '@/components/ui/select'; } from '@/components/ui/select';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
import { writeUiPref } from '@/lib/uiPref'; import { writeUiPref } from '@/lib/uiPref';
import { setUseMiles } from '@/lib/units';
import { iaruRegion, setIaruRegion, type IaruRegion } from '@/lib/bandplan';
import { getDateFormat, setDateFormat, type DateFormat } from '@/lib/dateFormat'; import { getDateFormat, setDateFormat, type DateFormat } from '@/lib/dateFormat';
import { useI18n, FlagGB, FlagFR, type Lang } from '@/lib/i18n'; import { useI18n, FlagGB, FlagFR, type Lang } from '@/lib/i18n';
import { useTheme, CONCRETE_THEMES, type ThemeChoice } from '@/lib/theme'; import { useTheme, CONCRETE_THEMES, type ThemeChoice } from '@/lib/theme';
@@ -175,6 +179,8 @@ interface Props {
flexAvailable?: boolean; // CAT backend is FlexRadio → offer it as a Main pane flexAvailable?: boolean; // CAT backend is FlexRadio → offer it as a Main pane
icomAvailable?: boolean; // CAT backend is Icom → offer the Icom console as a Main pane icomAvailable?: boolean; // CAT backend is Icom → offer the Icom console as a Main pane
yaesuAvailable?: boolean; // CAT backend is Yaesu → offer the Yaesu console as a Main pane yaesuAvailable?: boolean; // CAT backend is Yaesu → offer the Yaesu console as a Main pane
elecraftAvailable?: boolean; // CAT backend is Elecraft/Kenwood → the K3/K4 console
tciAvailable?: boolean; // CAT backend is TCI → the SunSDR console
// Opens a QSO in the editor. Settings is not where a log is edited — but the // Opens a QSO in the editor. Settings is not where a log is edited — but the
// RDA comparison lists contacts whose district is in dispute, and a list of // RDA comparison lists contacts whose district is in dispute, and a list of
// things to fix that cannot be acted on is a list to write down and look up // things to fix that cannot be acted on is a list to write down and look up
@@ -686,8 +692,7 @@ function TelemetryToggle() {
<label className="flex items-center gap-2 text-sm cursor-pointer"> <label className="flex items-center gap-2 text-sm cursor-pointer">
<Checkbox checked={on} disabled={!loaded} <Checkbox checked={on} disabled={!loaded}
onCheckedChange={(c) => { const v = !!c; setOn(v); SetTelemetryEnabled(v).catch(() => {}); }} /> onCheckedChange={(c) => { const v = !!c; setOn(v); SetTelemetryEnabled(v).catch(() => {}); }} />
{t('settings.telemetry')} <span title={t('settings.telemetryHint')}>{t('settings.telemetry')}</span>
<span className="text-xs text-muted-foreground">({t('settings.telemetryHint')})</span>
</label> </label>
); );
} }
@@ -905,9 +910,10 @@ function AmpStatusCard({ id }: { id: string }) {
const t = window.setInterval(tick, 1000); const t = window.setInterval(tick, 1000);
return () => { alive = false; window.clearInterval(t); }; return () => { alive = false; window.clearInterval(t); };
}, [id]); }, [id]);
const st: any = amp?.spe ?? amp?.acom ?? amp?.pgxl ?? { connected: false }; const st: any = amp?.spe ?? amp?.acom ?? amp?.kpa ?? amp?.pgxl ?? { connected: false };
const isSPE = !!amp?.spe; const isSPE = !!amp?.spe;
const isACOM = !!amp?.acom; const isACOM = !!amp?.acom;
const isKPA = !!amp?.kpa;
const operate = !!st.operate; const operate = !!st.operate;
return ( return (
<div className="rounded-md border border-border p-3 space-y-2 text-xs max-w-xl"> <div className="rounded-md border border-border p-3 space-y-2 text-xs max-w-xl">
@@ -948,7 +954,23 @@ function AmpStatusCard({ id }: { id: string }) {
{st.err_text && <div className="col-span-4 text-warning"> {st.err_text} ({st.err_code})</div>} {st.err_text && <div className="col-span-4 text-warning"> {st.err_text} ({st.err_code})</div>}
</div> </div>
)} )}
{st.connected && !isSPE && !isACOM && ( {st.connected && isKPA && (
<div className="grid grid-cols-4 gap-x-3 gap-y-1 font-mono text-[11px]">
<div>{st.power_on ? 'ON' : 'OFF'}</div>
<div>Band {st.band || '—'}</div>
<div>{st.fwd_w} W</div>
<div>SWR {Number(st.swr ?? 0).toFixed(1)}</div>
<div>{st.volt_v} V</div>
<div>{st.cur_a} A</div>
<div>{st.temp_c}°C</div>
<div>{st.tuning ? 'TUNING' : ''}</div>
{/* A fault has already put the amplifier in standby by itself, so it
is the one thing worth the width and OPERATE is the way out of
it, which the button above already is. */}
{st.fault_text && <div className="col-span-4 text-warning"> {st.fault_text}</div>}
</div>
)}
{st.connected && !isSPE && !isACOM && !isKPA && (
<div className="grid grid-cols-3 gap-x-3 gap-y-1 font-mono text-[11px]"> <div className="grid grid-cols-3 gap-x-3 gap-y-1 font-mono text-[11px]">
<div>{st.state || ''}</div> <div>{st.state || ''}</div>
<div>Fan {st.fan_mode || '—'}</div> <div>Fan {st.fan_mode || '—'}</div>
@@ -1066,9 +1088,9 @@ function RelayAutoPanel() {
// panes. The first two are the view; the third and fourth can be left empty, and // panes. The first two are the view; the third and fourth can be left empty, and
// an empty one is not drawn at all. Per-profile (stored via SetUIPref, which is // an empty one is not drawn at all. Per-profile (stored via SetUIPref, which is
// profile-prefixed). Self-contained so it owns its async-loaded state. // profile-prefixed). Self-contained so it owns its async-loaded state.
const MAIN_PANE_VALUES = ['map1', 'map2', 'cluster', 'worked', 'recent', 'netcontrol', 'decodes']; const MAIN_PANE_VALUES = ['map1', 'map2', 'cluster', 'worked', 'recent', 'netcontrol', 'decodes', 'watchlist'];
const PANE_NONE = 'none'; const PANE_NONE = 'none';
function MainViewPanes({ onChanged, flexAvailable, icomAvailable, yaesuAvailable }: { onChanged?: (side: 'left' | 'right' | 'p3' | 'p4' | 'layout', value: string) => void; flexAvailable?: boolean; icomAvailable?: boolean; yaesuAvailable?: boolean }) { function MainViewPanes({ onChanged, flexAvailable, icomAvailable, yaesuAvailable, elecraftAvailable, tciAvailable }: { onChanged?: (side: 'left' | 'right' | 'p3' | 'p4' | 'layout', value: string) => void; flexAvailable?: boolean; icomAvailable?: boolean; yaesuAvailable?: boolean; elecraftAvailable?: boolean; tciAvailable?: boolean }) {
const { t } = useI18n(); const { t } = useI18n();
const [panes, setPanes] = useState<Record<string, string>>({ left: 'map1', right: 'map2', p3: PANE_NONE, p4: PANE_NONE }); const [panes, setPanes] = useState<Record<string, string>>({ left: 'map1', right: 'map2', p3: PANE_NONE, p4: PANE_NONE });
const [layout, setLayout] = useState('quad'); const [layout, setLayout] = useState('quad');
@@ -1078,11 +1100,16 @@ function MainViewPanes({ onChanged, flexAvailable, icomAvailable, yaesuAvailable
...(flexAvailable ? ['flex'] : []), ...(flexAvailable ? ['flex'] : []),
...(icomAvailable ? ['icom'] : []), ...(icomAvailable ? ['icom'] : []),
...(yaesuAvailable ? ['yaesu'] : []), ...(yaesuAvailable ? ['yaesu'] : []),
// The Elecraft console could be docked from the start — App has always had
// the pane — but it was never offered here, so the only way to reach it was
// the tab. Listed with the others now.
...(elecraftAvailable ? ['elecraft'] : []),
...(tciAvailable ? ['tci'] : []),
].map((value) => ({ value, label: t(`settings.pane.${value}`) })) ].map((value) => ({ value, label: t(`settings.pane.${value}`) }))
.sort((a, b) => a.label.localeCompare(b.label)); .sort((a, b) => a.label.localeCompare(b.label));
const KEYS: Record<string, string> = { left: 'mainPaneLeft', right: 'mainPaneRight', p3: 'mainPane3', p4: 'mainPane4' }; const KEYS: Record<string, string> = { left: 'mainPaneLeft', right: 'mainPaneRight', p3: 'mainPane3', p4: 'mainPane4' };
useEffect(() => { useEffect(() => {
const valid = (v: string) => v === 'flex' || v === 'icom' || v === 'yaesu' || MAIN_PANE_VALUES.includes(v); const valid = (v: string) => v === 'flex' || v === 'icom' || v === 'yaesu' || v === 'elecraft' || v === 'tci' || MAIN_PANE_VALUES.includes(v);
Promise.all([ Promise.all([
...Object.values(KEYS).map((k) => GetUIPref(k).catch(() => '')), ...Object.values(KEYS).map((k) => GetUIPref(k).catch(() => '')),
GetUIPref('mainPaneLayout').catch(() => ''), GetUIPref('mainPaneLayout').catch(() => ''),
@@ -1478,6 +1505,7 @@ const ICOM_MODELS: { name: string; addr: number }[] = [
{ name: 'IC-7600', addr: 0x7A }, { name: 'IC-7600', addr: 0x7A },
{ name: 'IC-7610', addr: 0x98 }, { name: 'IC-7610', addr: 0x98 },
{ name: 'IC-7700', addr: 0x74 }, { name: 'IC-7700', addr: 0x74 },
{ name: 'IC-7760', addr: 0xB2 },
{ name: 'IC-7800', addr: 0x6A }, { name: 'IC-7800', addr: 0x6A },
{ name: 'IC-7851', addr: 0x8E }, { name: 'IC-7851', addr: 0x8E },
{ name: 'IC-9100', addr: 0x7C }, { name: 'IC-9100', addr: 0x7C },
@@ -1536,7 +1564,7 @@ function brandOfBackend(backend: string, kenwoodLink?: string): { brand: string;
// memo() cuts that off. It only works if the props hold still, which is why // memo() cuts that off. It only works if the props hold still, which is why
// App passes callbacks that do not change identity on every render — see the // App passes callbacks that do not change identity on every render — see the
// useCallback wrappers there. // useCallback wrappers there.
function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged, flexAvailable, icomAvailable, yaesuAvailable, onEditQSO }: Props) { function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged, flexAvailable, icomAvailable, yaesuAvailable, elecraftAvailable, tciAvailable, onEditQSO }: Props) {
const { t } = useI18n(); const { t } = useI18n();
const [selected, setSelected] = useState<SectionId>((initialSection as SectionId) || 'station'); const [selected, setSelected] = useState<SectionId>((initialSection as SectionId) || 'station');
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
@@ -1572,6 +1600,12 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
// exotic or experimental bands not listed). // exotic or experimental bands not listed).
const [bandDraft, setBandDraft] = useState(''); const [bandDraft, setBandDraft] = useState('');
const [modeDraft, setModeDraft] = useState(''); const [modeDraft, setModeDraft] = useState('');
// The saved radios. The CAT panel edits ONE of them — whichever is on the air
// — and the list is what makes switching possible without touching profiles.
const [radios, setRadios] = useState<any[]>([]);
const [listenPref, setListenPref] = useState(true);
const [activeRadio, setActiveRadioId] = useState('');
const [radioBusy, setRadioBusy] = useState(false);
const [catCfg, setCatCfg] = useState<CATSettings>({ const [catCfg, setCatCfg] = useState<CATSettings>({
enabled: false, backend: 'omnirig', omnirig_rig: 1, omnirig_vfo: '', flex_host: '', flex_port: 4992, flex_spots: false, flex_decode_spots: false, flex_decode_secs: 120, flex_dvk_dax: false, enabled: false, backend: 'omnirig', omnirig_rig: 1, omnirig_vfo: '', flex_host: '', flex_port: 4992, flex_spots: false, flex_decode_spots: false, flex_decode_secs: 120, flex_dvk_dax: false,
yaesu_port: '', yaesu_baud: 38400, yaesu_low_lines: false, kenwood_low_lines: false, kenwood_port: '', kenwood_baud: 9600, kenwood_host: '', kenwood_link: 'usb', kenwood_data_mode: 'usb', xiegu_port: '', xiegu_baud: 19200, xiegu_addr: 0x70, xiegu_ptt_line: '', yaesu_port: '', yaesu_baud: 38400, yaesu_low_lines: false, kenwood_low_lines: false, kenwood_port: '', kenwood_baud: 9600, kenwood_host: '', kenwood_link: 'usb', kenwood_data_mode: 'usb', xiegu_port: '', xiegu_baud: 19200, xiegu_addr: 0x70, xiegu_ptt_line: '',
@@ -1685,6 +1719,8 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
// DVK voice-keyer messages (F1F6). // DVK voice-keyer messages (F1F6).
type DVKMsg = { slot: number; label: string; has_audio: boolean; duration_sec: number }; type DVKMsg = { slot: number; label: string; has_audio: boolean; duration_sec: number };
type DVKStat = { recording: boolean; playing: boolean; rec_slot: number }; type DVKStat = { recording: boolean; playing: boolean; rec_slot: number };
const [chaseCfg, setChaseCfg] = useState<{ mode: string; sources: string[] }>({ mode: 'new', sources: ['lotw', 'card', 'eqsl'] });
useEffect(() => { GetChaseSettings().then((c: any) => setChaseCfg({ mode: c?.mode ?? 'new', sources: c?.sources ?? ['lotw', 'card', 'eqsl'] })).catch(() => {}); }, []);
const [dvkMsgs, setDvkMsgs] = useState<DVKMsg[]>([]); const [dvkMsgs, setDvkMsgs] = useState<DVKMsg[]>([]);
const [dvkStat, setDvkStat] = useState<DVKStat>({ recording: false, playing: false, rec_slot: 0 }); const [dvkStat, setDvkStat] = useState<DVKStat>({ recording: false, playing: false, rec_slot: 0 });
const [dvkErr, setDvkErr] = useState(''); const [dvkErr, setDvkErr] = useState('');
@@ -1718,6 +1754,8 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
const [startEqEnd, setStartEqEnd] = useState(() => localStorage.getItem('opslog.startEqualsEnd') === '1'); const [startEqEnd, setStartEqEnd] = useState(() => localStorage.getItem('opslog.startEqualsEnd') === '1');
const [lookupOnBlur, setLookupOnBlur] = useState(() => localStorage.getItem('opslog.lookupOnBlur') === '1'); const [lookupOnBlur, setLookupOnBlur] = useState(() => localStorage.getItem('opslog.lookupOnBlur') === '1');
const [groupDigital, setGroupDigital] = useState(() => localStorage.getItem('opslog.groupDigitalSlots') === '1'); const [groupDigital, setGroupDigital] = useState(() => localStorage.getItem('opslog.groupDigitalSlots') === '1');
const [milesUnit, setMilesUnit] = useState(() => localStorage.getItem('opslog.distanceMiles') === '1');
const [region, setRegion] = useState<IaruRegion>(() => iaruRegion());
const [clusterWorkedSameSlot, setClusterWorkedSameSlot] = useState(() => localStorage.getItem('opslog.clusterWorkedSameSlot') === '1'); const [clusterWorkedSameSlot, setClusterWorkedSameSlot] = useState(() => localStorage.getItem('opslog.clusterWorkedSameSlot') === '1');
// Declared HERE and not in ClusterPanel: that renderer is called as a plain // Declared HERE and not in ClusterPanel: that renderer is called as a plain
// function by the PANELS map, so it must stay hooks-free. // function by the PANELS map, so it must stay hooks-free.
@@ -1946,6 +1984,11 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
// nobody had pressed, and the one that had been pressed showed nothing at // nobody had pressed, and the one that had been pressed showed nothing at
// all, which reads as "the button does nothing". // all, which reads as "the button does nothing".
const [rdaCmpMsg, setRdaCmpMsg] = useState<string>(''); const [rdaCmpMsg, setRdaCmpMsg] = useState<string>('');
// Which source the operator kept, per QSO id. By id and not by row: a second
// comparison rebuilds the list, and a choice that followed a row number would
// then be applied to somebody else's contact.
const [rdaPick, setRdaPick] = useState<Record<number, 'log' | 'db'>>({});
const [rdaApplyBusy, setRdaApplyBusy] = useState(false);
const runRDACompare = async () => { const runRDACompare = async () => {
setRdaCmpBusy(true); setRdaCmp(null); setRdaCmpMsg(''); setRdaCmpBusy(true); setRdaCmp(null); setRdaCmpMsg('');
try { try {
@@ -2031,6 +2074,8 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
try { await SaveGridScopeSettings(next); } catch { /* the panel keeps the choice either way */ } try { await SaveGridScopeSettings(next); } catch { /* the panel keeps the choice either way */ }
}; };
const [chaseGrids, setChaseGrids] = useState(false); const [chaseGrids, setChaseGrids] = useState(false);
const [chasePotaOn, setChasePotaOn] = useState(() => localStorage.getItem('opslog.chasePota') !== '0');
const [chaseSotaOn, setChaseSotaOn] = useState(() => localStorage.getItem('opslog.chaseSota') !== '0');
const [chaseNew, setChaseNew] = useState(false); const [chaseNew, setChaseNew] = useState(false);
const [spotTTL, setSpotTTL] = useState(0); const [spotTTL, setSpotTTL] = useState(0);
const [spotTTLText, setSpotTTLText] = useState('0'); const [spotTTLText, setSpotTTLText] = useState('0');
@@ -2163,6 +2208,19 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
// on a normal open and Save then wrote an empty list over the operator's // on a normal open and Save then wrote an empty list over the operator's
// buttons. See rotorPresetsLoaded for the belt to this brace. // buttons. See rotorPresetsLoaded for the belt to this brace.
try { setRotorPresets((((await GetRotorPresets()) ?? []) as any)); setRotorPresetsLoaded(true); } catch {} try { setRotorPresets((((await GetRotorPresets()) ?? []) as any)); setRotorPresetsLoaded(true); } catch {}
try {
try { setListenPref(!!(await GetAudioMonitorPref())); } catch {}
const rl: any = await GetRadios();
setRadios(rl ?? []);
// The backend is the only one who knows which radio is on the air —
// the list entries carry no 'active' flag, and guessing the first
// meant reopening the panel showed Radio 1's name over the settings
// of whichever radio was actually selected.
let actId = '';
try { actId = (await ActiveRadioID()) ?? ''; } catch {}
if (!actId || !(rl ?? []).some((r: any) => r.id === actId)) actId = (rl ?? [])[0]?.id ?? '';
setActiveRadioId(actId);
} catch { /* one radio, never listed — the panel works as it always did */ }
try { setUltrabeam(await GetUltrabeamSettings() as any); } catch {} try { setUltrabeam(await GetUltrabeamSettings() as any); } catch {}
try { setAntgenius(await GetAntGeniusSettings() as any); } catch {} try { setAntgenius(await GetAntGeniusSettings() as any); } catch {}
try { setTunergenius(await GetTunerGeniusSettings() as any); } catch {} try { setTunergenius(await GetTunerGeniusSettings() as any); } catch {}
@@ -3160,6 +3218,87 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
hint={t('cat.hint')} hint={t('cat.hint')}
/> />
<div className="space-y-4 max-w-3xl"> <div className="space-y-4 max-w-3xl">
{/* RADIOS. Everything below edits the one selected here, and the status
bar's CAT chip switches between them without moving the rest of the
station which is what making a profile per radio used to do. */}
<div className="rounded-lg border border-border p-3 space-y-2">
<div className="flex items-center gap-2">
<Label className="shrink-0">{t('cat.radio')}</Label>
<Select value={activeRadio || undefined} onValueChange={(v) => {
if (v === activeRadio || radioBusy) return;
// Saving first: the panel may hold edits to the radio being left
// behind, and switching without them would throw them away.
setRadioBusy(true);
SaveCATSettings(catCfg as any)
.then(() => SetActiveRadio(v))
.then(async () => {
setActiveRadioId(v);
setCatCfg(await GetCATSettings() as any);
setRadios(((await GetRadios()) ?? []) as any[]);
})
.catch((e: any) => setErr(String(e?.message ?? e)))
.finally(() => setRadioBusy(false));
}}>
<SelectTrigger className="h-9 flex-1"><SelectValue placeholder={t('cat.radio')} /></SelectTrigger>
<SelectContent>
{radios.map((r: any, i: number) => (
<SelectItem key={r.id} value={r.id}>{r.name?.trim() || r.label || `Radio ${i + 1}`}</SelectItem>
))}
</SelectContent>
</Select>
<Input className="h-9 w-44" placeholder={t('cat.radioNamePh')}
value={(radios.find((r: any) => r.id === activeRadio)?.name) ?? ''}
onChange={(e) => setRadios((l) => l.map((r: any) => r.id === activeRadio ? { ...r, name: e.target.value } : r))}
onBlur={() => { SaveRadios(radios as any).catch(() => {}); }} />
<Button type="button" variant="outline" size="sm" className="h-9 shrink-0" disabled={radioBusy}
title={t('cat.radioAddHint')}
onClick={() => {
// A new radio starts from the CURRENT one rather than from
// nothing: a second rig is usually the same shape as the first
// with one port changed, and an empty form is a form to fill in
// twice.
const next = [...radios, { id: '', name: '', backend: catCfg.backend, settings: catCfg }];
setRadioBusy(true);
SaveRadios(next as any)
.then(() => GetRadios())
.then((rl: any) => setRadios(rl ?? []))
.catch((e: any) => setErr(String(e?.message ?? e)))
.finally(() => setRadioBusy(false));
}}>+</Button>
<Button type="button" variant="ghost" size="sm" className="h-9 shrink-0 text-danger"
disabled={radioBusy || radios.length < 2}
title={t('cat.radioRemoveHint')}
onClick={() => {
const next = radios.filter((r: any) => r.id !== activeRadio);
setRadioBusy(true);
SaveRadios(next as any)
.then(() => SetActiveRadio(next[0].id))
.then(async () => {
setActiveRadioId(next[0].id);
setCatCfg(await GetCATSettings() as any);
setRadios(((await GetRadios()) ?? []) as any[]);
})
.catch((e: any) => setErr(String(e?.message ?? e)))
.finally(() => setRadioBusy(false));
}}>
<Trash2 className="size-3.5" />
</Button>
</div>
{/* MY_RIG follows the radio, not the profile.
Operating conditions describe a PLAN "on 20 m I use the beam
and the 7300" while this is the fact of which rig is keying.
Empty leaves the old chain alone. */}
<div className="flex items-center gap-2">
<Label className="shrink-0 w-24">{t('cat.radioMyRig')}</Label>
<Input className="h-9 flex-1" placeholder={t('cat.radioMyRigPh')}
value={(radios.find((r: any) => r.id === activeRadio)?.my_rig) ?? ''}
onChange={(e) => setRadios((l) => l.map((r: any) => r.id === activeRadio ? { ...r, my_rig: e.target.value } : r))}
onBlur={() => { SaveRadios(radios as any).catch(() => {}); }} />
</div>
<p className="text-[11px] text-muted-foreground">{t('cat.radioHint')}</p>
<p className="text-[11px] text-muted-foreground">{t('cat.radioMyRigHint')}</p>
</div>
<label className="flex items-center gap-2 text-sm cursor-pointer"> <label className="flex items-center gap-2 text-sm cursor-pointer">
<Checkbox checked={catCfg.enabled} onCheckedChange={(c) => setCatCfg((s) => ({ ...s, enabled: !!c }))} /> <Checkbox checked={catCfg.enabled} onCheckedChange={(c) => setCatCfg((s) => ({ ...s, enabled: !!c }))} />
{t('cat.enable')} {t('cat.enable')}
@@ -3493,6 +3632,22 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
<span className="block text-[11px] text-muted-foreground">{t('cat.icomNetAudioHint')}</span> <span className="block text-[11px] text-muted-foreground">{t('cat.icomNetAudioHint')}</span>
</span> </span>
</label> </label>
{!!(catCfg as any).icom_net_audio && (
<label className="col-span-2 flex items-start gap-2 text-sm cursor-pointer pl-6">
{/* The speaker choice, right where the stream is enabled. Same
remembered preference as the console's speaker button
applied immediately, no save needed. */}
<Checkbox checked={listenPref}
onCheckedChange={(c) => {
setListenPref(!!c);
(c ? AudioStartMonitor() : Promise.resolve(AudioStopMonitor())).catch(() => setListenPref(!c));
}} />
<span>
{t('cat.icomNetListen')}
<span className="block text-[11px] text-muted-foreground">{t('cat.icomNetListenHint')}</span>
</span>
</label>
)}
</> </>
)} )}
{catCfg.backend === 'tci' && ( {catCfg.backend === 'tci' && (
@@ -3778,23 +3933,25 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
<div className="grid grid-cols-3 gap-3"> <div className="grid grid-cols-3 gap-3">
<div className="space-y-1 col-span-2"> <div className="space-y-1 col-span-2">
<Label>{t('hw.motorCom')}{!isSteppir && <span className="ml-1.5 font-normal text-muted-foreground">{t('hw.motorComUb')}</span>}</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 {/* THE SAME Select every other serial device uses.
not the Select the other serial devices use: the port for a This was a Combobox a list you could also type into so
USB adapter that is currently unplugged does not appear in that the port of an adapter currently unplugged could still
the list, and refusing to accept it typed means the antenna be configured. In practice the list could not be picked from
cannot be configured until the adapter is in. The detected at all, which is a worse failure than the one it was avoiding:
ports are offered; anything else is still accepted. */} the port an operator wants is nearly always one that is
plugged in and detected. A configured port that has since
gone missing is added to the list so it stays selected and
visible rather than silently disappearing. */}
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
<Combobox <Select value={ultrabeam.com || undefined}
value={ultrabeam.com ?? ''} onValueChange={(v) => setUltrabeam((s) => ({ ...s, com: v }))}>
options={wkPorts} <SelectTrigger className="h-9 font-mono flex-1"><SelectValue placeholder="COM3" /></SelectTrigger>
allowFreeText <SelectContent>
commitOnType {wkPorts.length === 0 && !ultrabeam.com && <SelectItem value="_" disabled>{t('cat.noPorts')}</SelectItem>}
showToggle {[...wkPorts, ...(ultrabeam.com && !wkPorts.includes(ultrabeam.com) ? [ultrabeam.com] : [])]
placeholder="COM3" .map((pt) => <SelectItem key={pt} value={pt}>{pt}</SelectItem>)}
className="font-mono flex-1" </SelectContent>
onChange={(v) => setUltrabeam((s) => ({ ...s, com: v.trim().toUpperCase() }))} </Select>
/>
<Button type="button" variant="outline" size="sm" className="shrink-0" <Button type="button" variant="outline" size="sm" className="shrink-0"
onClick={() => ListSerialPorts().then((ps) => setWkPorts((ps ?? []) as string[])).catch(() => {})}></Button> onClick={() => ListSerialPorts().then((ps) => setWkPorts((ps ?? []) as string[])).catch(() => {})}></Button>
</div> </div>
@@ -3943,7 +4100,7 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
<p className="text-xs text-muted-foreground pl-6">{t('hw.motorTxInhibitHint')}</p> <p className="text-xs text-muted-foreground pl-6">{t('hw.motorTxInhibitHint')}</p>
</div> </div>
<div className="flex items-center gap-2 pt-2"> <div className="flex items-center gap-2 pt-2">
<Button variant="outline" size="sm" onClick={testUltrabeam} disabled={ubTesting || (isSerial ? !ultrabeam.com.trim() : !ultrabeam.host.trim())}> <Button variant="outline" size="sm" onClick={testUltrabeam} disabled={ubTesting || (isSerial ? !(ultrabeam.com || '').trim() : !(ultrabeam.host || '').trim())}>
{ubTesting ? t('hw.connecting') : t('hw.testConn')} {ubTesting ? t('hw.connecting') : t('hw.testConn')}
</Button> </Button>
</div> </div>
@@ -4137,15 +4294,28 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
{ value: 'acom1200', label: '1200S' }, { value: 'acom1200', label: '1200S' },
{ value: 'acom2020', label: '2020S' }, { value: 'acom2020', label: '2020S' },
], ],
kpa: [
{ value: 'kpa1500', label: 'KPA1500' },
{ value: 'kpa500', label: 'KPA500' },
],
}; };
const brandOf = (ty: string) => (!ty || ty === 'pgxl') ? 'pgxl' : ty.startsWith('acom') ? 'acom' : 'spe'; const brandOf = (ty: string) => (!ty || ty === 'pgxl') ? 'pgxl'
: ty.startsWith('acom') ? 'acom'
: ty.startsWith('kpa') ? 'kpa' : 'spe';
const patchAmp = (i: number, patch: Partial<AmpUI>) => setAmps((l) => l.map((a, j) => (j === i ? { ...a, ...patch } : a))); const patchAmp = (i: number, patch: Partial<AmpUI>) => setAmps((l) => l.map((a, j) => (j === i ? { ...a, ...patch } : a)));
// Each family has a fixed serial speed: SPE talks 115200, the ACOM S-series is // Each family has a fixed serial speed: SPE talks 115200, the ACOM S-series is
// 9600 8N1 — preset it so switching brand just works. PGXL is TCP-only. // 9600 8N1 — preset it so switching brand just works. PGXL is TCP-only.
// Each family has its own fixed serial speed and its own default port, so
// switching model leaves a working configuration rather than one the
// operator has to repair. A KPA500 has no network side at all — it is put
// on serial here rather than being allowed to sit on a TCP setting that
// could never connect.
const applyType = (i: number, v: string) => patchAmp(i, { const applyType = (i: number, v: string) => patchAmp(i, {
type: v, type: v,
transport: v === 'pgxl' ? 'tcp' : amps[i].transport, freq_out: v.startsWith('kpa') ? true : amps[i].freq_out,
baud: v.startsWith('acom') ? 9600 : v.startsWith('spe') ? 115200 : amps[i].baud, transport: v === 'pgxl' ? 'tcp' : v === 'kpa500' ? 'serial' : amps[i].transport,
baud: v.startsWith('acom') ? 9600 : v.startsWith('spe') ? 115200 : v.startsWith('kpa') ? 38400 : amps[i].baud,
port: v === 'kpa1500' ? 1500 : amps[i].port,
}); });
const addAmp = () => setAmps((l) => [...l, { const addAmp = () => setAmps((l) => [...l, {
id: '', name: '', enabled: true, type: 'spe13', transport: 'tcp', host: '', port: 9008, com_port: '', baud: 115200, id: '', name: '', enabled: true, type: 'spe13', transport: 'tcp', host: '', port: 9008, com_port: '', baud: 115200,
@@ -4162,6 +4332,7 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
const brand = brandOf(amp.type); const brand = brandOf(amp.type);
const isPGXL = brand === 'pgxl'; const isPGXL = brand === 'pgxl';
const isACOM = brand === 'acom'; const isACOM = brand === 'acom';
const isKPA = brand === 'kpa';
const isSerial = !isPGXL && amp.transport === 'serial'; const isSerial = !isPGXL && amp.transport === 'serial';
return ( return (
<div key={amp.id || `new-${i}`} className="rounded-lg border border-border p-3 space-y-3"> <div key={amp.id || `new-${i}`} className="rounded-lg border border-border p-3 space-y-3">
@@ -4189,7 +4360,8 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
<SelectContent> <SelectContent>
<SelectItem value="pgxl">4O3A</SelectItem> <SelectItem value="pgxl">4O3A</SelectItem>
<SelectItem value="spe">SPE</SelectItem> <SelectItem value="spe">SPE</SelectItem>
<SelectItem value="acom">ACOM</SelectItem> <SelectItem value="acom">Acom</SelectItem>
<SelectItem value="kpa">Elecraft</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
@@ -4247,8 +4419,17 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
</div> </div>
<div className="space-y-1"> <div className="space-y-1">
<Label>Baud</Label> <Label>Baud</Label>
<Input type="number" min={1200} value={amp.baud} {/* A list, not a free number: the KPA500 report that
onChange={(e) => patchAmp(i, { baud: parseInt(e.target.value) || 115200 })} className="font-mono" /> began this had its operator wondering whether a typed
baud was the whole problem. These are the rates the
supported amplifiers actually speak. */}
<select value={String(amp.baud)}
onChange={(e) => patchAmp(i, { baud: parseInt(e.target.value) })}
className="h-9 w-full px-2 rounded-md border border-border bg-background text-sm font-mono">
{[4800, 9600, 19200, 38400, 57600, 115200].map((b) => (
<option key={b} value={String(b)}>{b}</option>
))}
</select>
</div> </div>
</div> </div>
) : ( ) : (
@@ -4279,10 +4460,27 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
)} )}
{/* Band-follow, for any amp that takes its band from a transceiver {/* Band-follow, for any amp that takes its band from a transceiver
CAT link (ACOM and SPE both do) never PowerGenius, which is CAT link (Acom and SPE both do) never PowerGenius, which is
driven over its network protocol. A SECOND serial port, driven over its network protocol. A SECOND serial port,
separate from the metering one above. */} separate from the metering one above.
{!isPGXL && ( Never a KPA either: it has a band command of its own (^BN),
so OpsLog tells it directly on the link it is already using.
Offering a second serial port and a transceiver emulator for
that would be a workaround for a problem this amplifier does
not have. */}
{isKPA && (
<div className="border-t border-border/60 pt-3 space-y-1">
<label className="flex items-center gap-2 text-sm cursor-pointer">
<Checkbox
checked={!!amp.freq_out}
onCheckedChange={(c) => patchAmp(i, { freq_out: !!c })}
/>
{t('amp.kpaBandFollow')}
</label>
<p className="text-[11px] text-muted-foreground">{t('amp.kpaBandFollowHint')}</p>
</div>
)}
{!isPGXL && !isKPA && (
<div className="border-t border-border/60 pt-3 space-y-3"> <div className="border-t border-border/60 pt-3 space-y-3">
<label className="flex items-center gap-2 text-sm cursor-pointer"> <label className="flex items-center gap-2 text-sm cursor-pointer">
<Checkbox <Checkbox
@@ -4710,7 +4908,7 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
<SelectItem value="yaesu">{t('wk.engYaesu')}</SelectItem> <SelectItem value="yaesu">{t('wk.engYaesu')}</SelectItem>
<SelectItem value="kenwood">{t('wk.engKenwood')}</SelectItem> <SelectItem value="kenwood">{t('wk.engKenwood')}</SelectItem>
<SelectItem value="flex">{t('wk.engFlex')}</SelectItem> <SelectItem value="flex">{t('wk.engFlex')}</SelectItem>
<SelectItem value="tci" disabled>{t('wk.engTci')}</SelectItem> <SelectItem value="tci">{t('wk.engTci')}</SelectItem>
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
@@ -4726,7 +4924,7 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
{wk.engine === 'icom' ? ( {wk.engine === 'icom' ? (
<> <>
{(!catCfg.enabled || catCfg.backend !== 'icom') && ( {(!catCfg.enabled || (catCfg.backend !== 'icom' && catCfg.backend !== 'icom-net')) && (
<p className="text-xs font-medium text-warning -mt-1 flex items-start gap-1.5"> <p className="text-xs font-medium text-warning -mt-1 flex items-start gap-1.5">
<span aria-hidden></span> <span aria-hidden></span>
<span>{t('wk.catWarnIcom', { backend: catCfg.enabled ? (catCfg.backend || 'none') : 'disabled' })}</span> <span>{t('wk.catWarnIcom', { backend: catCfg.enabled ? (catCfg.backend || 'none') : 'disabled' })}</span>
@@ -4771,6 +4969,22 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
</div> </div>
</div> </div>
</> </>
) : wk.engine === 'tci' ? (
<>
{(!catCfg.enabled || catCfg.backend !== 'tci') && (
<p className="text-xs font-medium text-warning -mt-1 flex items-start gap-1.5">
<span aria-hidden></span>
<span>{t('wk.catWarnTci', { backend: catCfg.enabled ? (catCfg.backend || 'none') : 'disabled' })}</span>
</p>
)}
<p className="text-xs text-muted-foreground -mt-1">{t('wk.tciHint')}</p>
<div className="grid grid-cols-4 gap-3">
<div className="space-y-1">
<Label>{t('wk.speed')}</Label>
<Input type="number" min={5} max={60} value={wk.wpm} onChange={(e) => setWkField({ wpm: num(e.target.value, 25) })} className="font-mono" />
</div>
</div>
</>
) : wk.engine === 'flex' ? ( ) : wk.engine === 'flex' ? (
<> <>
{(!catCfg.enabled || catCfg.backend !== 'flex') && ( {(!catCfg.enabled || catCfg.backend !== 'flex') && (
@@ -5140,11 +5354,6 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
))} ))}
</div> </div>
</div> </div>
<p className="text-xs text-muted-foreground">
{t('clu.freeNodes')} <span className="font-mono">dxc.k0xm.net:7300</span>,{' '}
<span className="font-mono">dx.maritimecontestclub.net:7300</span>,{' '}
<span className="font-mono">w8avi.net:7300</span>.
</p>
<label className="flex items-start gap-2 text-sm cursor-pointer border-t border-border/60 pt-3"> <label className="flex items-start gap-2 text-sm cursor-pointer border-t border-border/60 pt-3">
<Checkbox checked={clusterWorkedSameSlot} className="mt-0.5" <Checkbox checked={clusterWorkedSameSlot} className="mt-0.5"
onCheckedChange={(c) => { const v = !!c; setClusterWorkedSameSlot(v); writeUiPref('opslog.clusterWorkedSameSlot', v ? '1' : '0'); }} /> onCheckedChange={(c) => { const v = !!c; setClusterWorkedSameSlot(v); writeUiPref('opslog.clusterWorkedSameSlot', v ? '1' : '0'); }} />
@@ -5206,11 +5415,56 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
const n = parseInt(raw, 10); const n = parseInt(raw, 10);
if (Number.isFinite(n) && n > 0) SetSpotMax(Math.min(10000, n)).catch(() => {}); if (Number.isFinite(n) && n > 0) SetSpotMax(Math.min(10000, n)).catch(() => {});
}} /> }} />
<span className="text-xs text-muted-foreground">{t('clu.spotMaxHint')}</span>
</div> </div>
</div> </div>
<div className="border-t border-border/60 pt-3 space-y-2"> <div className="border-t border-border/60 pt-3 space-y-2">
{/* Chase switches: off, the marker stops being TOLD, everywhere at
once badge, colour, filter chip, reference column. A "new band
+ new POTA" spot then reads NEW BAND alone. */}
{/* The GLOBAL hunt: every category (DXCC, band, mode, slot, prefix,
county, state, grid) judged as new-only or new-plus-unconfirmed,
against the confirmation sources the operator trusts. */}
<div className="rounded-lg border border-border p-3 space-y-2">
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground w-28 shrink-0">{t('chg.mode')}</span>
<Select value={chaseCfg.mode} onValueChange={(v) => { const next = { ...chaseCfg, mode: v }; setChaseCfg(next); void SaveChaseSettings(next as any); }}>
<SelectTrigger className="h-7 w-64 text-xs"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="new">{t('gsc.huntNew')}</SelectItem>
<SelectItem value="new_unconfirmed">{t('gsc.huntUnconf')}</SelectItem>
</SelectContent>
</Select>
</div>
{chaseCfg.mode === 'new_unconfirmed' && (
<div className="flex items-center gap-4 flex-wrap pl-2">
<span className="text-xs text-muted-foreground">{t('chg.sources')}</span>
{([['lotw', 'LoTW'], ['card', t('chg.card')], ['eqsl', 'eQSL'], ['qrz', 'QRZ.com']] as const).map(([k, label]) => (
<label key={k} className="flex items-center gap-1.5 text-xs cursor-pointer">
<Checkbox checked={chaseCfg.sources.includes(k)}
onCheckedChange={(c) => {
const sources = c ? [...chaseCfg.sources, k] : chaseCfg.sources.filter((x) => x !== k);
const next = { ...chaseCfg, sources };
setChaseCfg(next); void SaveChaseSettings(next as any);
}} />
{label}
</label>
))}
</div>
)}
</div>
<label className="flex items-center gap-2 text-sm cursor-pointer" title={t('clu.chasePotaHint')}>
<Checkbox checked={chasePotaOn}
onCheckedChange={(c) => { const v = !!c; setChasePotaOn(v); writeUiPref('opslog.chasePota', v ? '1' : '0'); }} />
{t('clu.chasePota')}
</label>
<label className="flex items-center gap-2 text-sm cursor-pointer" title={t('clu.chaseSotaHint')}>
<Checkbox checked={chaseSotaOn}
onCheckedChange={(c) => { const v = !!c; setChaseSotaOn(v); writeUiPref('opslog.chaseSota', v ? '1' : '0'); }} />
{t('clu.chaseSota')}
</label>
<label className="flex items-start gap-2 text-sm cursor-pointer"> <label className="flex items-start gap-2 text-sm cursor-pointer">
<Checkbox checked={chaseGrids} className="mt-0.5" <Checkbox checked={chaseGrids} className="mt-0.5"
onCheckedChange={(c) => { setChaseGrids(!!c); SetChaseNewGrids(!!c).catch(() => {}); }} /> onCheckedChange={(c) => { setChaseGrids(!!c); SetChaseNewGrids(!!c).catch(() => {}); }} />
@@ -5240,19 +5494,11 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
</SelectContent> </SelectContent>
</Select> </Select>
</div> </div>
<div className="flex items-center gap-2 flex-wrap">
<span className="text-xs text-muted-foreground w-28 shrink-0">{t('gsc.hunt')}</span>
<Select value={gridScope.hunt} onValueChange={(v) => saveGridScope({ ...gridScope, hunt: v })}>
<SelectTrigger className="h-7 w-64 text-xs"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="new">{t('gsc.huntNew')}</SelectItem>
<SelectItem value="new_unconfirmed">{t('gsc.huntUnconf')}</SelectItem>
</SelectContent>
</Select>
</div>
</div> </div>
</div> </div>
{/* Chase new its own option, NOT nested under grid chasing. Chasing {/* Chase new its own option, NOT nested under grid chasing. Chasing
squares and chasing entities are different wants; they only share squares and chasing entities are different wants; they only share
the PSK Reporter feed, which either one brings up. */} the PSK Reporter feed, which either one brings up. */}
@@ -5506,10 +5752,7 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
function UDPIntegrationsPanelWrapper() { function UDPIntegrationsPanelWrapper() {
return ( return (
<> <>
<SectionHeader <SectionHeader title={t('sec.udp')} />
title={t('sec.udp')}
hint={t('udp.hint')}
/>
<UDPIntegrationsPanel onError={(m) => setErr(m)} /> <UDPIntegrationsPanel onError={(m) => setErr(m)} />
</> </>
); );
@@ -6604,7 +6847,7 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
useLocalLogbook(); // SQLite → default logbook file (clears any per-profile path) useLocalLogbook(); // SQLite → default logbook file (clears any per-profile path)
}} }}
> >
<SelectTrigger className="h-8 w-72"><SelectValue /></SelectTrigger> <SelectTrigger className="h-8 w-72" title={t('gen.iaruHint')}><SelectValue /></SelectTrigger>
<SelectContent> <SelectContent>
<SelectItem value="sqlite">{t('db.optSqlite')}</SelectItem> <SelectItem value="sqlite">{t('db.optSqlite')}</SelectItem>
<SelectItem value="mysql">{t('db.optMysql')}</SelectItem> <SelectItem value="mysql">{t('db.optMysql')}</SelectItem>
@@ -6710,6 +6953,13 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
xiegu: t('cat.optXiegu'), xiegu: t('cat.optXiegu'),
} as Record<string, string>)[catCfg.backend] ?? ''; } as Record<string, string>)[catCfg.backend] ?? '';
// The radio-over-network entry, which ListAudioInputDevices and
// ListAudioOutputDevices add when the CAT link can carry audio. It is a
// real choice for two of the four fields and nonsense for the other two.
const NET_DEVICE = 'net:radio';
const soundCardsOnly = (devs: AudioDev[]) => devs.filter((d) => d.id !== NET_DEVICE);
const fromRadioIsNetwork = audioCfg.from_radio === NET_DEVICE;
const deviceSelect = ( const deviceSelect = (
field: keyof AudioSettings, field: keyof AudioSettings,
devices: AudioDev[], devices: AudioDev[],
@@ -6744,10 +6994,16 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
{deviceSelect('from_radio', audioInputs, t('aud.phFromRadio'))} {deviceSelect('from_radio', audioInputs, t('aud.phFromRadio'))}
<Label className="text-sm">{t('aud.toRadio')}</Label> <Label className="text-sm">{t('aud.toRadio')}</Label>
{deviceSelect('to_radio', audioOutputs, t('aud.phToRadio'))} {deviceSelect('to_radio', audioOutputs, t('aud.phToRadio'))}
{/* The radio is offered for the two fields it can BE where the
received audio comes from, and where the voice keyer sends
its messages and taken out of the other two. It is not a
microphone: choosing it here would record the station you are
listening to instead of your own voice. And it is not a pair of
speakers: the audio going that way is transmit audio. */}
<Label className="text-sm">{t('aud.recMic')}</Label> <Label className="text-sm">{t('aud.recMic')}</Label>
{deviceSelect('recording_device', audioInputs, t('aud.phRecMic'))} {deviceSelect('recording_device', soundCardsOnly(audioInputs), t('aud.phRecMic'))}
<Label className="text-sm">{t('aud.listening')}</Label> <Label className="text-sm">{t('aud.listening')}</Label>
{deviceSelect('listening_device', audioOutputs, t('aud.phListening'))} {deviceSelect('listening_device', soundCardsOnly(audioOutputs), t('aud.phListening'))}
</div> </div>
<p className="text-[11px] text-muted-foreground"> <p className="text-[11px] text-muted-foreground">
<strong>{t('aud.fromRadioShort')}</strong> {t('aud.explainFrom')}{' '} <strong>{t('aud.fromRadioShort')}</strong> {t('aud.explainFrom')}{' '}
@@ -6765,8 +7021,9 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
size="sm" size="sm"
className="h-8" className="h-8"
onClick={toggleMonitor} onClick={toggleMonitor}
disabled={!monitorOn && !audioCfg.from_radio} disabled={!monitorOn && (!audioCfg.from_radio || fromRadioIsNetwork)
title={t('aud.monitorTitle')} && !(catCfg.backend === 'icom-net' && (catCfg as any).icom_net_audio)}
title={fromRadioIsNetwork ? t('aud.monitorNoTci') : t('aud.monitorTitle')}
> >
{monitorOn ? t('aud.stopListening') : t('aud.listenRadio')} {monitorOn ? t('aud.stopListening') : t('aud.listenRadio')}
</Button> </Button>
@@ -6948,6 +7205,15 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
> >
{dvkStat.playing ? t('aud.stop') : t('aud.play')} {dvkStat.playing ? t('aud.stop') : t('aud.play')}
</Button> </Button>
<Button
type="button"
variant="outline" size="sm" className="h-8 w-9 shrink-0 px-0 text-danger hover:text-danger"
title={t('aud.deleteMsg')}
disabled={!m.has_audio || dvkStat.recording || dvkStat.playing}
onClick={() => DVKDelete(m.slot).then(reloadDvk).catch((err) => setDvkErr(String(err?.message ?? err)))}
>
<Trash2 className="size-3.5" />
</Button>
</div> </div>
); );
})} })}
@@ -6961,7 +7227,7 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
const { lang, setLang, t } = useI18n(); const { lang, setLang, t } = useI18n();
return ( return (
<> <>
<SectionHeader title={t('sec.general')} hint={t('gen.hint')} /> <SectionHeader title={t('sec.general')} />
<div className="space-y-3 max-w-3xl"> <div className="space-y-3 max-w-3xl">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Label className="text-sm w-40">{t('settings.language')}</Label> <Label className="text-sm w-40">{t('settings.language')}</Label>
@@ -6989,15 +7255,32 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
['us', t('gen.dateUS'), '07-30-2026 14:25']] as [DateFormat, string, string][]).map(([code, label, sample]) => ( ['us', t('gen.dateUS'), '07-30-2026 14:25']] as [DateFormat, string, string][]).map(([code, label, sample]) => (
<button key={code} type="button" title={sample} <button key={code} type="button" title={sample}
onClick={() => { setDateFormat(code); setDateFmtSel(code); }} onClick={() => { setDateFormat(code); setDateFmtSel(code); }}
className={cn('flex flex-col items-start px-3 py-1 text-sm font-medium border-l border-border first:border-l-0', className={cn('px-3 py-1.5 text-sm font-medium border-l border-border first:border-l-0',
dateFmtSel === code ? 'bg-primary text-primary-foreground' : 'bg-card text-muted-foreground hover:bg-muted')}> dateFmtSel === code ? 'bg-primary text-primary-foreground' : 'bg-card text-muted-foreground hover:bg-muted')}>
{label} {label}
<span className="text-[10px] font-mono opacity-70">{sample}</span>
</button> </button>
))} ))}
</div> </div>
</div> </div>
<div className="flex items-center gap-2 text-sm">
{/* The IARU region drives the band edges and mode segments the band
maps draw Region 2's 40 m runs to 7300, Region 1's stops at
7200 and nothing else: spots and logging are region-blind. */}
<Label className="text-sm w-40 shrink-0">{t('gen.iaruRegion')}</Label>
<Select value={String(region)} onValueChange={(v) => {
const r = (v === '2' ? 2 : v === '3' ? 3 : 1) as IaruRegion;
setRegion(r); setIaruRegion(r);
}}>
<SelectTrigger className="h-8 w-72"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="1">{t('gen.iaruR1')}</SelectItem>
<SelectItem value="2">{t('gen.iaruR2')}</SelectItem>
<SelectItem value="3">{t('gen.iaruR3')}</SelectItem>
</SelectContent>
</Select>
</div>
<ThemeSelector /> <ThemeSelector />
<label className="flex items-center gap-2 text-sm cursor-pointer"> <label className="flex items-center gap-2 text-sm cursor-pointer">
@@ -7019,11 +7302,10 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
{/* Super Check Partial / N+1 downloads the community MASTER.SCP list and {/* Super Check Partial / N+1 downloads the community MASTER.SCP list and
shows a two-column callsign helper (partial matches + one-edit calls). */} shows a two-column callsign helper (partial matches + one-edit calls). */}
<div className="border-t border-border/60 pt-3 space-y-2"> <div className="border-t border-border/60 pt-3 space-y-2">
<label className="flex items-center gap-2 text-sm cursor-pointer"> <label className="flex items-center gap-2 text-sm cursor-pointer" title={t('scp.settingsHint')}>
<Checkbox checked={scp.enabled} disabled={scpBusy} onCheckedChange={(c) => toggleScp(!!c)} /> <Checkbox checked={scp.enabled} disabled={scpBusy} onCheckedChange={(c) => toggleScp(!!c)} />
{t('scp.enable')} {t('scp.enable')}
</label> </label>
<p className="text-[11px] text-muted-foreground">{t('scp.settingsHint')}</p>
{scp.enabled && ( {scp.enabled && (
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Button variant="outline" size="sm" onClick={downloadScp} disabled={scpBusy}> <Button variant="outline" size="sm" onClick={downloadScp} disabled={scpBusy}>
@@ -7051,15 +7333,22 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
</label> </label>
<label className="flex items-center gap-2 text-sm cursor-pointer"> <label className="flex items-center gap-2 text-sm cursor-pointer">
<Checkbox checked={groupDigital} onCheckedChange={(c) => { const v = !!c; setGroupDigital(v); writeUiPref('opslog.groupDigitalSlots', v ? '1' : '0'); }} /> <Checkbox checked={groupDigital} onCheckedChange={(c) => { const v = !!c; setGroupDigital(v); writeUiPref('opslog.groupDigitalSlots', v ? '1' : '0'); }} />
{t('gen.groupDigital')} <span className="text-xs text-muted-foreground">{t('gen.groupDigitalHint')}</span> <span title={t('gen.groupDigitalHint')}>{t('gen.groupDigital')}</span>
</label>
<label className="flex items-center gap-2 text-sm cursor-pointer">
{/* Distances are computed in km everywhere and converted at display
time see lib/units. Changing this repaints the columns that
already carry a distance; nothing stored moves. */}
<Checkbox checked={milesUnit} onCheckedChange={(c) => { const v = !!c; setMilesUnit(v); setUseMiles(v); }} />
{t('gen.miles')}
</label> </label>
<label className="flex items-center gap-2 text-sm cursor-pointer"> <label className="flex items-center gap-2 text-sm cursor-pointer">
<Checkbox checked={checkUpdates} onCheckedChange={(c) => { const v = !!c; setCheckUpdates(v); writeUiPref('opslog.checkUpdates', v ? '1' : '0'); }} /> <Checkbox checked={checkUpdates} onCheckedChange={(c) => { const v = !!c; setCheckUpdates(v); writeUiPref('opslog.checkUpdates', v ? '1' : '0'); }} />
{t('gen.checkUpdates')} <span className="text-xs text-muted-foreground">{t('gen.checkUpdatesHint')}</span> {t('gen.checkUpdates')}
</label> </label>
<TelemetryToggle /> <TelemetryToggle />
<MainViewPanes onChanged={onMainPaneChanged} flexAvailable={flexAvailable} icomAvailable={icomAvailable} yaesuAvailable={yaesuAvailable} /> <MainViewPanes onChanged={onMainPaneChanged} flexAvailable={flexAvailable} icomAvailable={icomAvailable} yaesuAvailable={yaesuAvailable} elecraftAvailable={elecraftAvailable} tciAvailable={tciAvailable} />
<div className="border-t border-border/60 pt-4 space-y-2"> <div className="border-t border-border/60 pt-4 space-y-2">
<h4 className="text-sm font-semibold text-foreground">{t('gen.pwEnc')}</h4> <h4 className="text-sm font-semibold text-foreground">{t('gen.pwEnc')}</h4>
@@ -7118,12 +7407,7 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
}} }}
className="mt-0.5" className="mt-0.5"
/> />
<span> <span title={t('gen.clubDesc')}>{t('gen.clubUse')}</span>
{t('gen.clubUse')}
<span className="block text-xs text-muted-foreground mt-0.5">
{t('gen.clubDesc')}
</span>
</span>
</label> </label>
<div className="flex items-center gap-3 pl-6"> <div className="flex items-center gap-3 pl-6">
<Button variant="outline" size="sm" className="h-8" disabled={clubBusy} <Button variant="outline" size="sm" className="h-8" disabled={clubBusy}
@@ -7517,6 +7801,7 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
<th className="py-1 pr-2 font-medium">{t('rda.cmpFromLog')}</th> <th className="py-1 pr-2 font-medium">{t('rda.cmpFromLog')}</th>
<th className="py-1 pr-2 font-medium">{t('rda.cmpFromDb')}</th> <th className="py-1 pr-2 font-medium">{t('rda.cmpFromDb')}</th>
<th className="py-1 pr-2 font-medium">{t('rda.cmpKind')}</th> <th className="py-1 pr-2 font-medium">{t('rda.cmpKind')}</th>
<th className="py-1 pr-2 font-medium text-center">{t('rda.cmpKeep')}</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -7541,11 +7826,100 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
<td className="py-1 pr-2 text-muted-foreground"> <td className="py-1 pr-2 text-muted-foreground">
{c.dated ? t('rda.cmpDated') : t('rda.cmpCurrent')} {c.dated ? t('rda.cmpDated') : t('rda.cmpCurrent')}
</td> </td>
{/* Which one wins, on the row that shows the two values.
Two buttons rather than a tick box: a tick box would
have to mean one of the sources silently, and an
operator arbitrating between "RO-19" and "KO-05"
should be picking the value they can read, not
remembering what a checked box stands for. */}
<td className="py-1 pr-2 whitespace-nowrap text-center">
<div className="inline-flex rounded border border-border overflow-hidden">
{(['log', 'db'] as const).map((side) => (
<button
key={side}
type="button"
onClick={() => setRdaPick((p) => {
const next = { ...p };
if (next[c.qso_id] === side) delete next[c.qso_id];
else next[c.qso_id] = side;
return next;
})}
className={`px-2 py-0.5 font-mono text-[10px] ${rdaPick[c.qso_id] === side
? 'bg-primary text-primary-foreground'
: 'hover:bg-muted'}`}
title={side === 'log' ? t('rda.cmpKeepLog') : t('rda.cmpKeepDb')}
>
{side === 'log' ? c.from_log : c.from_db}
</button>
))}
</div>
</td>
</tr> </tr>
))} ))}
</tbody> </tbody>
</table> </table>
</div> </div>
{/* Applying is a separate, deliberate act. Clicking through two
hundred rows and having each one written as it is clicked would
make a slip permanent before the operator had finished
reading. */}
<div className="flex items-center gap-3 flex-wrap">
<Button size="sm" variant="secondary" disabled={rdaApplyBusy || Object.keys(rdaPick).length === 0}
onClick={async () => {
setRdaApplyBusy(true);
try {
const choices = rdaCmp.conflicts
.filter((c: any) => rdaPick[c.qso_id])
.map((c: any) => ({
qso_id: c.qso_id,
district: rdaPick[c.qso_id] === 'log' ? c.from_log : c.from_db,
}));
const r: any = await ApplyRDAChoices(choices);
setRdaCmpMsg(r?.message || '');
setRdaPick({});
// The settled rows leave the list, and the counters follow.
//
// They used to stay, which made a working button look like a
// broken one: the operator decided a hundred contacts, the
// hundred rows stayed exactly as they were, and there was
// nothing anywhere to say the writing had happened. Dropping
// them here rather than re-running the comparison, because
// that reads the whole log — seconds of silence on a remote
// database, to be told what is already known.
if (r?.applied > 0) {
const settled = new Set(choices.map((c: any) => c.qso_id));
setRdaCmp((prev: any) => prev && ({
...prev,
disagree: Math.max(0, (prev.disagree ?? 0) - r.applied),
agree: (prev.agree ?? 0) + r.applied,
conflicts: (prev.conflicts ?? []).filter((c: any) => !settled.has(c.qso_id)),
}));
}
} catch (e: any) {
setRdaCmpMsg(String(e?.message ?? e));
} finally {
setRdaApplyBusy(false);
}
}}>
{rdaApplyBusy ? <Loader2 className="size-3.5 animate-spin mr-1.5" /> : null}
{t('rda.cmpApply', { n: Object.keys(rdaPick).length })}
</Button>
<button type="button" className="text-[11px] underline decoration-dotted hover:text-primary"
onClick={() => setRdaPick(Object.fromEntries(rdaCmp.conflicts.map((c: any) => [c.qso_id, 'db'])))}>
{t('rda.cmpAllDb')}
</button>
<button type="button" className="text-[11px] underline decoration-dotted hover:text-primary"
onClick={() => setRdaPick(Object.fromEntries(rdaCmp.conflicts.map((c: any) => [c.qso_id, 'log'])))}>
{t('rda.cmpAllLog')}
</button>
{Object.keys(rdaPick).length > 0 && (
<button type="button" className="text-[11px] underline decoration-dotted hover:text-primary"
onClick={() => setRdaPick({})}>
{t('rda.cmpClear')}
</button>
)}
</div>
<p className="text-[11px] text-muted-foreground">{t('rda.cmpApplyHint')}</p>
</> </>
)} )}
</div> </div>
+91
View File
@@ -0,0 +1,91 @@
import { useEffect, useRef, useState } from 'react';
import { cn } from '@/lib/utils';
// ShiftRow — the RIT / XIT offset control, shared by the radio consoles.
//
// It began inside the Icom panel and is here because the next console needed
// exactly it. Consoles that each invent their own way of nudging an offset make
// an operator learn the same thing twice, which is the complaint that moved it:
// "none of the consoles look alike".
//
// Three ways to move it, because operators reach for different ones: the ± keys,
// the wheel over the number, and TYPING a value straight in. The last one is
// what a button row cannot do — 'put me 300 Hz down' is one keystroke sequence,
// not thirty clicks.
export function ShiftRow({ label, on, hz, accent, disabled, step = 10, onToggle, onSet }: {
label: string;
on: boolean;
hz: number;
accent: string;
disabled?: boolean;
step?: number;
onToggle: () => void;
onSet: (hz: number) => void;
}) {
const ref = useRef<HTMLDivElement>(null);
const [editing, setEditing] = useState<string | null>(null);
const cb = useRef(onSet); cb.current = onSet;
const cur = useRef({ hz, on, disabled }); cur.current = { hz, on, disabled };
// Wheel over the row. A native non-passive listener, because React's onWheel
// is passive and cannot preventDefault — without that the panel scrolls under
// the pointer while the number changes.
useEffect(() => {
const el = ref.current;
if (!el) return;
const onWheel = (e: WheelEvent) => {
const c = cur.current;
if (c.disabled || !c.on) return;
e.preventDefault();
cb.current(c.hz + (e.deltaY < 0 ? step : -step));
};
el.addEventListener('wheel', onWheel, { passive: false });
return () => el.removeEventListener('wheel', onWheel);
}, [step]);
const commit = (raw: string) => {
setEditing(null);
const v = parseInt(raw.replace(/[^0-9+-]/g, ''), 10);
if (!Number.isNaN(v)) onSet(v);
};
const dead = disabled || !on;
return (
<div className="flex items-center gap-2">
<button type="button" onClick={onToggle} disabled={disabled}
className={cn('w-14 shrink-0 px-2 py-1 rounded-md text-[11px] font-bold border transition-colors disabled:opacity-30',
on ? 'bg-success border-success text-success-foreground' : 'bg-card text-muted-foreground border-border hover:bg-muted')}>
{label}
</button>
<div ref={ref} title="Wheel, ± or type"
className={cn('flex-1 flex items-center justify-between rounded-md border px-1 py-0.5 select-none',
dead ? 'border-border/60 bg-muted/20 opacity-60' : 'border-border bg-muted/40 cursor-ns-resize')}>
<button type="button" disabled={dead} onClick={() => onSet(hz - step)}
className="px-2 text-sm font-bold text-muted-foreground hover:text-foreground disabled:opacity-40"></button>
{editing !== null ? (
<input
autoFocus
value={editing}
onChange={(e) => setEditing(e.target.value)}
onBlur={(e) => commit(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') commit((e.target as HTMLInputElement).value);
else if (e.key === 'Escape') setEditing(null);
}}
className="w-20 bg-transparent text-center text-sm font-mono font-bold tabular-nums outline-none"
/>
) : (
<button type="button" disabled={dead} onClick={() => setEditing(String(hz))}
className="text-sm font-mono font-bold tabular-nums disabled:cursor-default"
style={{ color: on ? accent : undefined }}>
{hz > 0 ? '+' : hz < 0 ? '' : ''}{Math.abs(hz)} Hz
</button>
)}
<button type="button" disabled={dead} onClick={() => onSet(hz + step)}
className="px-2 text-sm font-bold text-muted-foreground hover:text-foreground disabled:opacity-40">+</button>
</div>
<button type="button" disabled={dead} onClick={() => onSet(0)}
className="w-8 shrink-0 py-1 rounded-md text-[11px] font-bold border border-border bg-card text-muted-foreground hover:bg-muted disabled:opacity-30">0</button>
</div>
);
}
+411
View File
@@ -0,0 +1,411 @@
import { useEffect, useRef, useState } from 'react';
import { Radio, Activity, AudioLines, SlidersHorizontal, Mic } from 'lucide-react';
import {
GetTCIPanel, GetCATState,
SetTCIDrive, SetTCITuneDrive, SetTCIMicLevel, SetTCIVolume, SetTCIMute,
SetTCIAGC, SetTCISquelch, SetTCISquelchLevel,
SetTCINB, SetTCINR, SetTCIANF, SetTCIAPF, SetTCIFilter,
SetTCIRIT, SetTCIXIT, SetTCIRITOffset, SetTCIXITOffset, SetTCILock, SetTCITune,
} from '../../wailsjs/go/main/App';
import { cn } from '@/lib/utils';
import { useI18n } from '@/lib/i18n';
import { sMeterRST } from '@/lib/rst';
import { MeterBar } from '@/components/MeterBar';
import { WheelRange } from '@/components/WheelRange';
import { ShiftRow } from '@/components/ShiftRow';
import { LevelRow } from '@/components/LevelRow';
type TCIState = {
connected: boolean; device?: string; protocol?: string;
drive: number; tune_drive: number; mic_level: number; tx_enabled: boolean; tx: boolean; tuning: boolean;
volume: number; mute: boolean; agc?: string; squelch_on: boolean; squelch: number;
nb: boolean; nr: boolean; anf: boolean; apf: boolean;
filter_lo: number; filter_hi: number;
rit: boolean; rit_offset: number; xit: boolean; xit_offset: number; lock: boolean; split: boolean;
smeter: number; modulations?: string[];
tx_power_w: number; tx_swr: number;
};
const ZERO: TCIState = {
connected: false, drive: 0, tune_drive: 0, mic_level: 0, tx_enabled: false, tx: false, tuning: false,
volume: 0, mute: false, squelch_on: false, squelch: 0,
nb: false, nr: false, anf: false, apf: false, filter_lo: 0, filter_hi: 0,
rit: false, rit_offset: 0, xit: false, xit_offset: 0, lock: false, split: false, smeter: 0,
tx_power_w: 0, tx_swr: 0,
};
// The widths worth a button, PER MODE — because 250 Hz is useless in SSB and
// 2.8 kHz is useless in CW, and a row offering both is a row where half the
// buttons are never pressed.
//
// CW gets the narrow end, where the difference between 250 and 500 is the
// difference between one signal and three. Voice gets the range a passband is
// actually shaped over. Digital sits between: wide enough for a whole FT8
// sub-band, narrow enough for RTTY.
const WIDTHS_CW = [100, 250, 400, 500, 700, 1000, 1800];
const WIDTHS_SSB = [1800, 2100, 2400, 2700, 2800, 3000, 3500];
const WIDTHS_DIGI = [500, 1000, 1800, 2400, 2800, 3000, 3500];
// widthsFor picks the row from the mode the radio reports.
function widthsFor(mode: string): number[] {
if (/CW/i.test(mode)) return WIDTHS_CW;
if (/SSB|USB|LSB|AM|FM/i.test(mode)) return WIDTHS_SSB;
return WIDTHS_DIGI;
}
// isCW says whether the CW-only controls belong on screen at all.
function isCW(mode: string): boolean { return /CW/i.test(mode); }
function widthLabel(w: number): string {
return w >= 1000 ? `${(w / 1000).toFixed(1)}k` : String(w);
}
// edgesFor turns a width into the pair TCI wants: 0 to the width, and nothing
// clever.
//
// It centred narrow filters on the CW note first — 250 became 575-825 — on the
// reasoning that a CW filter should contain the note. That reasoning may even be
// right for a radio, but it is not what the button says, and a button that does
// not do what it says is worse than one that does something simple. 250 means
// 0-250. The two edges are editable underneath for anything else.
function edgesFor(w: number, _mode: string): { lo: number; hi: number } {
return { lo: 0, hi: w };
}
// dBm → S units. TCI reports a real signal level rather than a meter position,
// which is the useful way round: S9 is -73 dBm by the IARU definition and every
// S unit below it is 6 dB, so this is arithmetic rather than a calibration
// table — nothing here is provisional the way the K3's meter reading is.
function sParts(dbm: number): { s: number; over: number; label: string } {
if (dbm === 0) return { s: 0, over: 0, label: '—' };
if (dbm >= -73) {
const over = Math.round((dbm + 73) / 10) * 10;
return { s: 9, over, label: over > 0 ? `S9+${over}` : 'S9' };
}
const s = Math.max(0, Math.min(9, Math.round(9 + (dbm + 73) / 6)));
return { s, over: 0, label: `S${s}` };
}
// The meter bar wants 0-100; -127 dBm is the bottom of the scale and -13 dBm
// (S9+60) the top.
function sBar(dbm: number): number {
if (dbm === 0) return 0;
return Math.max(0, Math.min(100, ((dbm + 127) / 114) * 100));
}
function sSegColor(frac: number): string {
return frac > 0.75 ? '#dc2626' : frac > 0.55 ? '#f59e0b' : '#16a34a';
}
function Card({ icon: Icon, title, children }: { icon: any; title: string; children: React.ReactNode }) {
return (
<div className="rounded-xl border border-border bg-card shadow-sm overflow-hidden">
<div className="flex items-center gap-2 px-3 py-2 border-b border-border/60 bg-muted/30">
<Icon className="size-4 text-primary" />
<span className="text-xs font-bold uppercase tracking-wider text-foreground/80">{title}</span>
</div>
<div className="p-3 space-y-3">{children}</div>
</div>
);
}
// One button shape for every on/off control, as on the other consoles.
function Toggle({ label, on, off, onClick, title }: {
label: string; on: boolean; off: boolean; onClick: () => void; title?: string;
}) {
return (
<button type="button" disabled={off} onClick={onClick} title={title}
className={cn('rounded-lg border-2 px-2 py-1.5 text-xs font-bold transition-all disabled:opacity-30',
on ? 'bg-primary text-primary-foreground border-primary shadow-[0_0_10px] shadow-primary/40'
: 'bg-card text-muted-foreground border-border hover:bg-muted')}>
{label}
</button>
);
}
function Row({ label, value, children }: { label: string; value: string; children: React.ReactNode }) {
return (
<div className="space-y-1">
<div className="flex items-baseline justify-between">
<span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">{label}</span>
<span className="text-xs font-mono tabular-nums">{value}</span>
</div>
{children}
</div>
);
}
export function TCIPanel({ onReportRST }: { onReportRST?: (rst: string) => void } = {}) {
const { t } = useI18n();
const [st, setSt] = useState<TCIState>(ZERO);
const [freqHz, setFreqHz] = useState(0);
const [mode, setMode] = useState('');
const [err, setErr] = useState('');
// OPTIMISTIC, like the Icom console — and for a reason found on a real radio.
//
// This panel used to show only what the radio reported back, on the principle
// that the radio is the truth. But ExpertSDR3 does not echo every setting it
// is given: press MED and the radio changes, says nothing, and the button
// stays lit on SLOW. Waiting for an answer that never comes reads as a dead
// control.
//
// So a change is shown at once and held for a moment. Whatever the radio
// announces afterwards — the new value, or a refusal that leaves the old one
// — wins once the hold expires, which keeps a clamped or rejected setting
// honest without making every working one look broken.
// Held UNTIL THE RADIO SPEAKS, not for a fixed moment.
//
// A timeout was wrong in both directions. Too short and a setting the radio
// never echoes — AGC is one — snapped back to its old value a second after
// the click. Too long and a setting the radio REFUSES looked accepted: a real
// log shows this one answering 'sql_enable:0,false' and then, eighty
// milliseconds later, 'sql_enable:0,true' — it puts the squelch straight back
// on. Holding through that would have shown the operator a lie.
//
// So the requested value stands while the radio says nothing about it, and
// the instant it reports ANY change for that setting, its word replaces ours.
const holdRef = useRef<Record<string, { v: any; reported: any }>>({});
const [, forceRender] = useState(0);
const hold = <T,>(key: string, reported: T): T => {
const h = holdRef.current[key];
if (!h) return reported;
// The radio has said something different from what it was saying when the
// click happened — whether that is our value or a refusal, it is now the
// truth and the hold is over.
if (reported !== h.reported) {
delete holdRef.current[key];
return reported;
}
return h.v as T;
};
const setHold = (key: string, v: any, reported: any) => {
holdRef.current[key] = { v, reported };
forceRender((n) => n + 1);
};
useEffect(() => {
let alive = true;
const tick = async () => {
try {
const p: any = await GetTCIPanel();
if (!alive) return;
setSt(p as TCIState);
const cs: any = await GetCATState();
if (!alive) return;
setFreqHz(Number(cs?.rx_freq_hz) || Number(cs?.freq_hz) || 0);
setMode(String(cs?.mode || ''));
} catch (e: any) {
if (alive) setErr(String(e?.message ?? e));
}
};
tick();
const id = window.setInterval(tick, 400);
return () => { alive = false; window.clearInterval(id); };
}, []);
const off = !st.connected;
const call = (fn: () => Promise<any>) => { fn().catch((e: any) => setErr(String(e?.message ?? e))); };
const drive = hold('drive', st.drive);
const tuneDrive = hold('tune_drive', st.tune_drive);
const mic = hold('mic', st.mic_level);
const vol = hold('vol', st.volume);
const sql = hold('sql', st.squelch);
const agc = hold('agc', st.agc || '');
const nb = hold('nb', st.nb), nr = hold('nr', st.nr);
const anf = hold('anf', st.anf), apf = hold('apf', st.apf);
const sqlOn = hold('sql_on', st.squelch_on), muted = hold('mute', st.mute);
const rit = hold('rit', st.rit), xit = hold('xit', st.xit);
const ritHz = hold('rit_hz', st.rit_offset), xitHz = hold('xit_hz', st.xit_offset);
const s = sParts(st.smeter);
// Ctrl+Left/Right shifts the RIT by ±10 Hz, the same keys the Icom console
// uses. Two consoles for two radios should not need two habits.
const ritRef = useRef({ on: false, hz: 0, off: true });
ritRef.current = { on: rit, hz: ritHz, off };
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (!e.ctrlKey || (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight')) return;
const r = ritRef.current;
if (r.off || !r.on) return;
e.preventDefault();
const v = r.hz + (e.key === 'ArrowRight' ? 10 : -10);
setHold('rit_hz', v, ritRef.current.hz);
SetTCIRITOffset(v).catch(() => {});
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, []);
return (
<div className="h-full min-h-0 overflow-auto bg-background">
{/* Capped and centred, like the Elecraft, Yaesu, Icom and Flex consoles.
Stretched across a wide window a console puts each slider a hand's
width from its own label and stops reading as one instrument. */}
<div className="max-w-5xl mx-auto p-3 space-y-3">
{/* VFO + identity */}
<div className="rounded-xl border border-border bg-card shadow-sm px-4 py-3 flex items-center justify-between gap-3 flex-wrap">
<div>
<div className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground flex items-center gap-1.5">
<Radio className="size-3.5" />
{st.device || 'SunSDR'} {st.protocol ? `· ${st.protocol}` : ''}
<span className={cn('size-2 rounded-full', off ? 'bg-muted-foreground/40' : 'bg-success')} />
</div>
<div className="text-2xl font-mono tabular-nums font-bold">
{freqHz > 0 ? (freqHz / 1e6).toFixed(6) : '—'}
</div>
</div>
<div className="flex items-center gap-2">
{st.tx && <span className="rounded-md bg-danger px-2 py-1 text-[11px] font-bold text-danger-foreground">TX</span>}
{st.split && <span className="rounded-md border border-border px-2 py-1 text-[11px] font-bold">SPLIT</span>}
<Toggle label={t('tcip.lock')} on={st.lock} off={off} onClick={() => call(() => SetTCILock(!st.lock))} />
</div>
</div>
{off && <div className="text-xs text-muted-foreground px-1">{t('tcip.waiting')}</div>}
{!!err && <div className="text-[11px] text-danger px-1">{err}</div>}
{/* Meters. The S-meter while receiving, power and SWR while
transmitting the radio answers TX_POWER and TX_SWR only when it is
keyed, so showing them the rest of the time would be showing the
last thing that happened as if it were now.
There is no temperature: the protocol has no such command, and a
made-up figure on a transmitter is the kind somebody trusts. */}
<Card icon={Activity} title={t('tcip.meters')}>
<MeterBar label="S-METER" value={st.tx || st.tuning ? 0 : sBar(st.smeter)} lo={0} hi={100}
accent="#16a34a" segColor={sSegColor}
display={st.tx || st.tuning ? '—' : `${s.label} ${st.smeter} dBm`}
onClick={() => {
if (st.tx || !onReportRST) return;
onReportRST(sMeterRST(s.s, s.over, mode));
}}
title={t('tcip.sMeterHint')} />
{(st.tx || st.tuning) && (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
<MeterBar label="PWR" value={st.tx_power_w} lo={0} hi={Math.max(10, Math.ceil(st.tx_power_w / 10) * 10)}
accent="#0ea5e9" display={`${st.tx_power_w.toFixed(1)} W`} />
{/* 0 is "not measured yet", and it must not draw as a perfect
match: an SWR of 1.0 on an antenna nobody has measured is the
one reading an operator should not be handed. */}
<MeterBar label="SWR" value={st.tx_swr > 0 ? Math.min(100, (st.tx_swr - 1) * 50) : 0} lo={0} hi={100}
accent="#f59e0b" display={st.tx_swr > 0 ? st.tx_swr.toFixed(1) : '—'}
segColor={(f) => (f > 0.5 ? '#dc2626' : f > 0.25 ? '#f59e0b' : '#16a34a')} />
</div>
)}
</Card>
{/* Transmit */}
<Card icon={SlidersHorizontal} title={t('tcip.transmit')}>
{/* One level per ROW, full width. Two half-width sliders side by side
left each of them a couple of centimetres long small enough that
setting 15% took aim. */}
<LevelRow label={t('tcip.drive')} unit="%" value={drive} disabled={off}
onSet={(v) => { setHold('drive', v, st.drive); call(() => SetTCIDrive(v)); }} />
<LevelRow label={t('tcip.tuneDrive')} unit="%" value={tuneDrive} disabled={off} accent="#f59e0b"
onSet={(v) => { setHold('tune_drive', v, st.tune_drive); call(() => SetTCITuneDrive(v)); }} />
<div className="flex items-center gap-2 flex-wrap">
{/* TUNE transmits, and at the tune drive rather than the main one
which is why both numbers are above the button rather than one of
them being in a menu somewhere. */}
<button type="button" disabled={off || !st.tx_enabled}
onClick={() => call(() => SetTCITune(!st.tuning))}
className={cn('rounded-lg border-2 px-4 py-2 text-sm font-extrabold tracking-wide transition-all disabled:opacity-30',
st.tuning ? 'bg-warning text-warning-foreground border-warning shadow-[0_0_14px] shadow-warning/50'
: 'bg-card text-warning border-warning hover:bg-warning-muted')}>
{st.tuning ? t('tcip.tuning') : t('tcip.tune')}
</button>
{!st.tx_enabled && !off && (
<span className="text-[11px] text-muted-foreground">{t('tcip.txDisabled')}</span>
)}
</div>
<LevelRow label={t('tcip.mic')} unit="%" value={mic} disabled={off} accent="#a855f7"
onSet={(v) => { setHold('mic', v, st.mic_level); call(() => SetTCIMicLevel(v)); }} />
</Card>
{/* Receive */}
<Card icon={AudioLines} title={t('tcip.receive')}>
{/* Both in the radio's OWN units volume in dB, negative, and the
squelch as a dBm threshold so the numbers match the ones in
ExpertSDR3's window rather than being percentages of something. */}
<LevelRow label={t('tcip.volume')} unit=" dB" min={-60} max={0} value={vol} disabled={off}
onSet={(v) => { setHold('vol', v, st.volume); call(() => SetTCIVolume(v)); }} />
<LevelRow label={t('tcip.squelch')} unit=" dBm" min={-140} max={0} value={sql}
disabled={off || !sqlOn} accent="#38bdf8"
onSet={(v) => { setHold('sql', v, st.squelch); call(() => SetTCISquelchLevel(v)); }} />
<div className={cn('grid gap-2', isCW(mode) ? 'grid-cols-3 sm:grid-cols-6' : 'grid-cols-3 sm:grid-cols-5')}>
<Toggle label="NB" on={nb} off={off} onClick={() => { setHold('nb', !nb, st.nb); call(() => SetTCINB(!nb)); }} />
<Toggle label="NR" on={nr} off={off} onClick={() => { setHold('nr', !nr, st.nr); call(() => SetTCINR(!nr)); }} />
<Toggle label="ANF" on={anf} off={off} onClick={() => { setHold('anf', !anf, st.anf); call(() => SetTCIANF(!anf)); }} />
{/* APF is an audio PEAK filter it rings a single tone out of the
noise, which is a CW tool and nothing else. Shown only there:
off CW it is not a control, it is a puzzle. */}
{isCW(mode) && (
<Toggle label="APF" on={apf} off={off} onClick={() => { setHold('apf', !apf, st.apf); call(() => SetTCIAPF(!apf)); }} />
)}
<Toggle label="SQL" on={sqlOn} off={off} onClick={() => { setHold('sql_on', !sqlOn, st.squelch_on); call(() => SetTCISquelch(!sqlOn)); }} />
<Toggle label={t('tcip.mute')} on={muted} off={off} onClick={() => { setHold('mute', !muted, st.mute); call(() => SetTCIMute(!muted)); }} />
</div>
<div className="space-y-1">
<span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">{t('tcip.agc')}</span>
{/* LONG is gone. The protocol accepts it, but it is a hang time
nobody reaches for between overs, and a fifth button that has to
be explained is worse than four that do not. */}
<div className="grid grid-cols-4 gap-2">
{['off', 'slow', 'med', 'fast'].map((m) => (
<Toggle key={m} label={m.toUpperCase()} on={agc === m} off={off}
onClick={() => { setHold('agc', m, st.agc || ''); call(() => SetTCIAGC(m)); }} />
))}
</div>
</div>
<div className="space-y-1">
<div className="flex items-baseline justify-between">
<span className="text-[10px] font-bold uppercase tracking-wider text-muted-foreground">{t('tcip.filter')}</span>
<span className="text-xs font-mono tabular-nums">{st.filter_lo}{st.filter_hi} Hz</span>
</div>
<div className="flex items-center gap-2 pb-1">
<LevelRow label="LO" unit=" Hz" min={-5000} max={5000} step={10}
value={st.filter_lo} disabled={off}
onSet={(v) => call(() => SetTCIFilter(v, st.filter_hi))} />
</div>
<div className="flex items-center gap-2 pb-1">
<LevelRow label="HI" unit=" Hz" min={-5000} max={5000} step={10}
value={st.filter_hi} disabled={off}
onSet={(v) => call(() => SetTCIFilter(st.filter_lo, v))} />
</div>
<div className="grid grid-cols-4 sm:grid-cols-7 gap-2">
{widthsFor(mode).map((w) => {
const e = edgesFor(w, mode);
// Lit by the WIDTH the radio is actually using, not by an exact
// pair of edges: the operator may have moved one edge on the
// radio, and a button that only lights on our own numbers would
// go dark for a filter that is plainly 500 Hz wide.
const on = Math.abs((st.filter_hi - st.filter_lo) - w) <= 50;
return (
<Toggle key={w} label={widthLabel(w)} on={on} off={off}
title={`${e.lo}${e.hi} Hz`}
onClick={() => call(() => SetTCIFilter(e.lo, e.hi))} />
);
})}
</div>
</div>
</Card>
{/* RIT / XIT the SAME control the Icom console uses, now shared
rather than reinvented: a chip, a signed offset you can type into,
scroll on, or step with ±, and a zero. Ctrl+/ shifts the RIT. */}
<Card icon={Mic} title="RIT / XIT">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<ShiftRow label="RIT" on={rit} hz={ritHz} accent="#38bdf8" disabled={off}
onToggle={() => { setHold('rit', !rit, st.rit); call(() => SetTCIRIT(!rit)); }}
onSet={(v) => { setHold('rit_hz', v, st.rit_offset); call(() => SetTCIRITOffset(v)); }} />
<ShiftRow label="XIT" on={xit} hz={xitHz} accent="#f59e0b" disabled={off}
onToggle={() => { setHold('xit', !xit, st.xit); call(() => SetTCIXIT(!xit)); }}
onSet={(v) => { setHold('xit_hz', v, st.xit_offset); call(() => SetTCIXITOffset(v)); }} />
</div>
</Card>
</div>
</div>
);
}
@@ -2,6 +2,7 @@ import React, { useCallback, useEffect, useState } from 'react';
import { Plus, Trash2, Edit2, RefreshCcw, ArrowDownToLine, ArrowUpFromLine } from 'lucide-react'; import { Plus, Trash2, Edit2, RefreshCcw, ArrowDownToLine, ArrowUpFromLine } from 'lucide-react';
import { import {
ListUDPIntegrations, SaveUDPIntegration, DeleteUDPIntegration, ReloadUDPIntegrations, ListUDPIntegrations, SaveUDPIntegration, DeleteUDPIntegration, ReloadUDPIntegrations,
GetWsjtHighlight, SetWsjtHighlight, GetWsjtFollowMode, SetWsjtFollowMode,
} from '../../wailsjs/go/main/App'; } from '../../wailsjs/go/main/App';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
@@ -158,6 +159,12 @@ const TRIGGERS = [
type Props = { onError: (msg: string) => void }; type Props = { onError: (msg: string) => void };
export function UDPIntegrationsPanel({ onError }: Props) { export function UDPIntegrationsPanel({ onError }: Props) {
const [highlightOn, setHighlightOn] = useState(false);
const [followMode, setFollowMode] = useState(true);
useEffect(() => {
GetWsjtHighlight().then((v) => setHighlightOn(!!v)).catch(() => {});
GetWsjtFollowMode().then((v) => setFollowMode(!!v)).catch(() => {});
}, []);
const { t } = useI18n(); const { t } = useI18n();
const [items, setItems] = useState<UDPConfig[]>([]); const [items, setItems] = useState<UDPConfig[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
@@ -229,10 +236,24 @@ export function UDPIntegrationsPanel({ onError }: Props) {
return ( return (
<div className="space-y-4"> <div className="space-y-4">
<div className="text-[11px] text-muted-foreground max-w-2xl leading-relaxed"> {/* Log-aware colours in WSJT-X / JTDX's own window lives HERE because
{t('udpp.intro')} this panel is where the WSJT-X link is configured. */}
</div> <label className="flex items-start gap-2 text-sm cursor-pointer max-w-2xl">
<Checkbox checked={highlightOn}
onCheckedChange={(c) => { setHighlightOn(!!c); void SetWsjtHighlight(!!c); }} />
<span>
{t('udpp.highlight')}
<span className="block text-[11px] text-muted-foreground">{t('udpp.highlightHint')}</span>
</span>
</label>
<label className="flex items-start gap-2 text-sm cursor-pointer max-w-2xl">
<Checkbox checked={followMode}
onCheckedChange={(c) => { setFollowMode(!!c); void SetWsjtFollowMode(!!c); }} />
<span>
{t('udpp.followMode')}
<span className="block text-[11px] text-muted-foreground">{t('udpp.followModeHint')}</span>
</span>
</label>
<Section <Section
title={t('udpp.inboundTitle')} title={t('udpp.inboundTitle')}
icon={<ArrowDownToLine className="size-4" />} icon={<ArrowDownToLine className="size-4" />}
+421
View File
@@ -0,0 +1,421 @@
// Watchlist — the DXHunter concept as an OpsLog tab.
//
// One card per watched callsign (or prefix), the live spots that match it
// underneath, and the two questions an operator actually asks answered on every
// line: is this slot still NEEDED, and what would it be worth (the same NEW
// DXCC / band / mode / slot badges the cluster shows, resolved from the same
// index). A CONTEST entry is judged against the current UTC day — at midnight
// everything reads "work today" again; the boundary lives in the backend query,
// so there is nothing to reset.
//
// The design is DXHunter's — the layout, the badges, the wording — repainted in
// the app's theme tokens rather than its hard-coded slate/pink.
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Eye, Plus, Trash2, Bell, BellOff, Trophy, Search } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Checkbox } from '@/components/ui/checkbox';
import { cn } from '@/lib/utils';
import { useI18n } from '@/lib/i18n';
import {
WatchlistEntries, WatchlistAdd, WatchlistRemove, WatchlistSetNotify,
WatchlistSetContest, WatchlistWorkedSlots,
GetWatchlistContestPattern, SetWatchlistContestPattern, OpenExternalURL,
} from '../../wailsjs/go/main/App';
import { EventsOn } from '../../wailsjs/runtime/runtime';
import type { ClusterSpot, SpotStatusEntry } from '@/components/ClusterGrid';
import { inferSpotMode, spotStatusKey } from '@/lib/spot';
interface WLEntry {
callsign: string; lastSeenStr: string; addedAt: string; spotCount: number;
isContest: boolean; notify: boolean;
isExpedition: boolean; clubLogQSOs24h: number; clubLogTotalQSOs: number;
clubLogHasOQRS: boolean; clubLogLiveStream: boolean;
}
interface Props {
spots: ClusterSpot[];
spotStatus: Record<string, SpotStatusEntry>;
onSpotSelect?: (s: ClusterSpot) => void;
onSpotClick?: (s: ClusterSpot) => void;
}
// A spot is ON AIR for the badge while its last sighting is this fresh.
const ON_AIR_MS = 10 * 60 * 1000;
// Exact unless the entry carries a trailing * — the same rule the backend's
// Match applies to the live stream, mirrored so the tab and the alerts can
// never disagree about what an entry covers.
function matchesEntry(call: string, pattern: string): boolean {
const c = call.toUpperCase();
if (pattern.endsWith('*')) {
const p = pattern.slice(0, -1);
return p !== '' && c.startsWith(p);
}
return c === pattern;
}
export function WatchlistTab({ spots, spotStatus, onSpotSelect, onSpotClick }: Props) {
const { t } = useI18n();
const [entries, setEntries] = useState<WLEntry[]>([]);
const [addCall, setAddCall] = useState('');
const [addContest, setAddContest] = useState(false);
const [search, setSearch] = useState('');
// The filters survive leaving the tab: the component unmounts on every tab
// switch, and filters that reset each time are filters nobody trusts.
const [neededOnly, setNeededOnlyRaw] = useState(() => localStorage.getItem('opslog.wlNeededOnly') === '1');
const [activeOnly, setActiveOnlyRaw] = useState(() => localStorage.getItem('opslog.wlActiveOnly') === '1');
const [family, setFamilyRaw] = useState<'all' | 'normal' | 'contest'>(() => {
const v = localStorage.getItem('opslog.wlFamily');
return v === 'normal' || v === 'contest' ? v : 'all';
});
const setNeededOnly = (f: (v: boolean) => boolean) => setNeededOnlyRaw((v) => { const nv = f(v); try { localStorage.setItem('opslog.wlNeededOnly', nv ? '1' : '0'); } catch {} return nv; });
const setActiveOnly = (f: (v: boolean) => boolean) => setActiveOnlyRaw((v) => { const nv = f(v); try { localStorage.setItem('opslog.wlActiveOnly', nv ? '1' : '0'); } catch {} return nv; });
const setFamily = (v: 'all' | 'normal' | 'contest') => { setFamilyRaw(v); try { localStorage.setItem('opslog.wlFamily', v); } catch {} };
// Mode filter — DXHunter's "All Modes" select. DIGI matches the digital class
// (FT8, FT4, a generic DATA spot…), the named modes match exactly.
const [modeFilter, setModeFilterRaw] = useState(() => localStorage.getItem('opslog.wlMode') || 'ALL');
const setModeFilter = (v: string) => { setModeFilterRaw(v); try { localStorage.setItem('opslog.wlMode', v); } catch {} };
const modeMatches = (s2: ClusterSpot): boolean => {
if (modeFilter === 'ALL') return true;
const m = (inferSpotMode(s2.comment ?? '', s2.freq_hz) || '').toUpperCase();
if (modeFilter === 'DIGI') return !['', 'CW', 'SSB', 'USB', 'LSB', 'FM', 'AM'].includes(m);
if (modeFilter === 'SSB') return m === 'SSB' || m === 'USB' || m === 'LSB';
return m === modeFilter;
};
const [error, setError] = useState('');
// A quiet confirmation under the toolbar; both messages clear themselves —
// a stale "added" from ten minutes ago reads as a fresh one.
const [notice, setNotice] = useState('');
const noticeTimer = useRef<number | undefined>(undefined);
const flash = (msg: string, isError: boolean) => {
if (noticeTimer.current) window.clearTimeout(noticeTimer.current);
setError(isError ? msg : '');
setNotice(isError ? '' : msg);
noticeTimer.current = window.setTimeout(() => { setError(''); setNotice(''); }, 4000) as unknown as number;
};
// worked answer per "call|band|modeclass|contest" key.
const [worked, setWorked] = useState<Record<string, boolean>>({});
const refresh = useCallback(async () => {
try { setEntries(((await WatchlistEntries()) ?? []) as any as WLEntry[]); }
catch (e: any) { setError(String(e?.message ?? e)); }
}, []);
// Refreshed on mount, when the backend auto-adds (event), and on a slow tick
// so last-seen and the spot counters stay honest while the tab sits open.
useEffect(() => {
void refresh();
const off = EventsOn('watchlist:changed', () => { void refresh(); });
const id = window.setInterval(() => { void refresh(); }, 30_000);
return () => { off(); window.clearInterval(id); };
}, [refresh]);
// The auto-contest pattern (DXHunter's contest_prefix): spots whose call
// contains it are added as contest entries by the backend.
const [pattern, setPattern] = useState('');
useEffect(() => { GetWatchlistContestPattern().then((p: string) => setPattern(p ?? '')).catch(() => {}); }, []);
// Live spots per entry — prefix-matched, newest first, deduped per band+mode
// (one line per slot; the freshest spot represents it).
const spotsFor = useMemo(() => {
const map = new Map<string, ClusterSpot[]>();
for (const e of entries) map.set(e.callsign, []);
for (const s of spots) {
for (const e of entries) {
if (matchesEntry(s.dx_call ?? '', e.callsign)) { map.get(e.callsign)!.push(s); break; }
}
}
for (const [k, list] of map) {
const seen = new Set<string>();
map.set(k, list.filter((s) => {
const key = `${(s.band ?? '')}|${inferSpotMode(s.comment ?? '', s.freq_hz)}|${s.dx_call}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
}));
}
return map;
}, [spots, entries]);
// The worked answers, refreshed when the visible slots change. Debounced: a
// spot burst must cost one round trip, not one per spot.
const queryTimer = useRef<number | undefined>(undefined);
useEffect(() => {
if (queryTimer.current) window.clearTimeout(queryTimer.current);
queryTimer.current = window.setTimeout(async () => {
const queries: { call: string; band: string; mode: string; contest: boolean }[] = [];
const keys: string[] = [];
for (const e of entries) {
for (const s of spotsFor.get(e.callsign) ?? []) {
const mode = inferSpotMode(s.comment ?? '', s.freq_hz) || '';
queries.push({ call: s.dx_call, band: s.band ?? '', mode, contest: e.isContest });
keys.push(`${s.dx_call}|${s.band ?? ''}|${mode}|${e.isContest ? 1 : 0}`);
}
}
if (queries.length === 0) { setWorked({}); return; }
try {
const res: boolean[] = (await WatchlistWorkedSlots(queries as any)) ?? [];
// MERGED, not replaced: replacing made every already-answered key
// momentarily unknown on each refresh, which re-hid settled lines.
setWorked((prev) => {
const next = { ...prev };
keys.forEach((k, i) => { next[k] = !!res[i]; });
return next;
});
} catch { /* the badges just stay conservative */ }
}, 150) as unknown as number;
return () => { if (queryTimer.current) window.clearTimeout(queryTimer.current); };
}, [spotsFor, entries]);
const wkey = (e: WLEntry, s: ClusterSpot) =>
`${s.dx_call}|${s.band ?? ''}|${inferSpotMode(s.comment ?? '', s.freq_hz) || ''}|${e.isContest ? 1 : 0}`;
const workedFor = (e: WLEntry, s: ClusterSpot): boolean => worked[wkey(e, s)] ?? false;
// A spot whose verdict has not come back yet is NOT drawn. Showing it as
// Needed and withdrawing it half a second later made the list twitch on
// every burst — and nobody needs a spot 400 ms early, they need it settled.
const settled = (e: WLEntry, s: ClusterSpot): boolean => wkey(e, s) in worked;
const add = async () => {
const c = addCall.trim().toUpperCase();
if (!c) return;
try {
await WatchlistAdd(c, addContest);
setAddCall('');
flash(t(addContest ? 'wl.addedContest' : 'wl.added', { call: c }), false);
await refresh();
} catch (e: any) { flash(String(e?.message ?? e), true); }
};
// One click, like the bell and the trophy beside it: removing a watchlist
// entry is cheap to undo (type it again), so it does not earn a confirmation
// the other two buttons do not have.
const remove = async (call: string) => {
try { await WatchlistRemove(call); flash(t('wl.removed', { call }), false); await refresh(); }
catch (e: any) { flash(String(e?.message ?? e), true); }
};
const isOnAir = (e: WLEntry): boolean =>
(spotsFor.get(e.callsign) ?? []).some((s) => {
const ts = Date.parse(String((s as any).received_at ?? ''));
return ts > 0 && Date.now() - ts < ON_AIR_MS;
});
const shown = entries.filter((e) => {
if (family === 'normal' && e.isContest) return false;
if (family === 'contest' && !e.isContest) return false;
if (search && !e.callsign.includes(search.trim().toUpperCase())) return false;
const list = (spotsFor.get(e.callsign) ?? []).filter(modeMatches).filter((s2) => settled(e, s2));
if (activeOnly && list.length === 0) return false;
if (neededOnly && !list.some((s2) => !workedFor(e, s2))) return false;
return true;
});
const counters = useMemo(() => {
let active = 0, needed = 0;
for (const e of entries) {
const list = (spotsFor.get(e.callsign) ?? []).filter(modeMatches).filter((s2) => settled(e, s2));
if (list.length > 0) active++;
if (list.some((s2) => !workedFor(e, s2))) needed++;
}
return { total: entries.length, active, needed };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [entries, spotsFor, worked, modeFilter]);
// The cluster's own badge for a spot, read from the shared status index.
const dxccBadge = (s: ClusterSpot): { label: string; color: string } | null => {
const st = spotStatus[spotStatusKey(s.dx_call, s.band ?? '', s.comment ?? '', s.freq_hz)];
switch (st?.status) {
case 'new': return { label: t('wl.newDxcc'), color: 'var(--danger)' };
case 'new-band-mode': return { label: t('clg2.newBandMode'), color: 'var(--danger)' };
case 'new-band': return { label: t('clg2.newBand'), color: 'var(--warning)' };
case 'new-mode': return { label: t('clg2.newMode'), color: 'var(--caution)' };
case 'new-slot': return { label: t('clg2.newSlot'), color: '#5AC8FA' };
default: return null;
}
};
const chip = (color: string, text: string, extra?: string) => (
<span className={cn('px-1.5 py-0.5 rounded text-[10px] font-bold border', extra)}
style={{ color, borderColor: `color-mix(in srgb, ${color} 40%, transparent)`, background: `color-mix(in srgb, ${color} 12%, transparent)` }}>
{text}
</span>
);
return (
// Capped and centred: a card is a reading surface, and callsign-to-badge
// lines stretched across a 34-inch window are not readable, they are long.
<div className="flex flex-col min-h-0 flex-1 gap-2 p-2 w-full max-w-5xl mx-auto">
{/* Header: the counters alone, centred they are the tab's headline.
Everything one INTERACTS with lives on the second row. */}
<div className="flex items-center justify-center gap-2.5 text-xs text-muted-foreground">
<Eye className="size-4 text-primary shrink-0" />
<span className="flex items-center gap-1.5">{t('wl.cTotal')}
<b className="px-2 py-0.5 rounded bg-muted text-foreground">{counters.total}</b></span>
<span className="opacity-40">|</span>
<span className="flex items-center gap-1.5">{t('wl.cActive')}
<b className="px-2 py-0.5 rounded text-info border border-info/30 bg-info/10">{counters.active}</b></span>
<span className="opacity-40">|</span>
<span className="flex items-center gap-1.5">{t('wl.cNeeded')}
<b className={cn('px-2 py-0.5 rounded border', counters.needed > 0
? 'text-warning border-warning/40 bg-warning/10'
: 'text-muted-foreground border-border bg-muted/40')}>{counters.needed}</b></span>
</div>
{/* toolbar */}
<div className="flex items-start justify-between gap-x-3 gap-y-1.5 flex-wrap">
<div className="flex items-center gap-2 shrink-0">
<Input className="h-8 w-40 font-mono placeholder:font-sans placeholder:normal-case" placeholder={t('wl.addPh')} value={addCall}
onChange={(e) => setAddCall(e.target.value.toUpperCase())}
onKeyDown={(e) => { if (e.key === 'Enter') void add(); }} />
<label className="flex items-center gap-1.5 text-xs cursor-pointer" title={t('wl.contestHint')}>
<Checkbox checked={addContest} onCheckedChange={(c) => setAddContest(!!c)} />
<Trophy className="size-3.5 text-warning" /> {t('wl.addAsContest')}
</label>
<Button size="sm" className="h-8" onClick={() => void add()} disabled={!addCall.trim()}>
<Plus className="size-3.5" /> {t('wl.add')}
</Button>
<Input className="h-8 w-28 font-mono placeholder:font-sans placeholder:normal-case" placeholder={t('wl.patternPh')}
title={t('wl.patternHint')}
value={pattern}
onChange={(e) => setPattern(e.target.value.toUpperCase())}
onBlur={() => { void SetWatchlistContestPattern(pattern.trim()); }} />
</div>
<div className="flex items-center gap-2 shrink-0">
<div className="relative">
<Search className="size-3.5 absolute left-2 top-1/2 -translate-y-1/2 text-muted-foreground" />
<Input className="h-8 w-28 pl-7 text-sm" placeholder={t('wl.searchPh')} value={search}
onChange={(e) => setSearch(e.target.value)} />
</div>
{/* families kept together, told apart per review of the DXHunter port,
no global contest mode: each entry carries its own rule. */}
<div className="inline-flex rounded-md border border-border overflow-hidden text-xs">
{([['all', t('wl.famAll')], ['normal', t('wl.famNormal')], ['contest', t('wl.famContest')]] as const).map(([k, label]) => (
<button key={k} type="button" onClick={() => setFamily(k)}
className={cn('px-2 py-1 border-l border-border first:border-l-0',
family === k ? 'bg-accent font-medium' : 'text-muted-foreground hover:bg-accent/50')}>
{label}
</button>
))}
</div>
<select value={modeFilter} onChange={(e) => setModeFilter(e.target.value)}
title={t('wl.modeFilter')}
className="h-7 px-1.5 rounded-md border border-border bg-background text-xs text-foreground">
{['ALL', 'CW', 'SSB', 'FT8', 'FT4', 'RTTY', 'DIGI'].map((m) => (
<option key={m} value={m}>{m === 'ALL' ? t('wl.allModes') : m}</option>
))}
</select>
<button type="button" onClick={() => setActiveOnly((v) => !v)}
className={cn('px-2 py-1 rounded-md border text-xs', activeOnly ? 'bg-accent border-border font-medium' : 'border-border text-muted-foreground hover:bg-accent/50')}>
{t('wl.activeOnly')}
</button>
<button type="button" onClick={() => setNeededOnly((v) => !v)}
className={cn('px-2 py-1 rounded-md border text-xs', neededOnly ? 'bg-accent border-border font-medium' : 'border-border text-muted-foreground hover:bg-accent/50')}>
{t('wl.neededOnly')}
</button>
</div>
</div>
{error && <div className="text-xs text-danger px-1">{error}</div>}
{notice && <div className="text-xs text-success px-1">{notice}</div>}
{/* cards */}
<div className="flex-1 min-h-0 overflow-y-auto space-y-2 pr-1">
{shown.length === 0 ? (
<div className="text-sm text-muted-foreground text-center pt-16 max-w-md mx-auto leading-relaxed">
{entries.length === 0 ? t('wl.empty') : t('wl.noneMatch')}
</div>
) : shown.map((e) => {
const all = (spotsFor.get(e.callsign) ?? []).filter(modeMatches).filter((s2) => settled(e, s2));
const needed = all.filter((s) => !workedFor(e, s)).length;
// Needed-only hides the worked LINES as well as the all-worked cards:
// a filter that says needed and still lists five green Worked rows is
// answering a different question than the one asked.
const list = neededOnly ? all.filter((s) => !workedFor(e, s)) : all;
return (
<div key={e.callsign}
className={cn('rounded-lg border bg-card/70 p-3 transition-colors hover:bg-accent/20',
needed > 0 ? 'border-warning/40' : 'border-border/70',
e.isContest && 'border-l-4 border-l-warning')}>
<div className="flex items-center gap-2 flex-wrap">
<span className="text-lg font-bold font-mono" style={{ color: '#f472b6' }}>{e.callsign}</span>
{isOnAir(e) && chip('var(--danger)', t('wl.onAir'), 'animate-pulse')}
{e.isContest && (
<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-bold bg-warning-muted text-warning-muted-foreground border border-warning-border"
title={t('wl.contestHint')}>
<Trophy className="size-3" /> {t('wl.contest')}
</span>
)}
{e.isExpedition && chip('var(--chart-5)', '⚡ ' + t('wl.expedition'))}
{e.clubLogTotalQSOs > 0 && <span className="text-[11px] text-muted-foreground">{e.clubLogTotalQSOs.toLocaleString()} QSOs{e.clubLogQSOs24h > 0 ? ` · ${e.clubLogQSOs24h}/24h` : ''}</span>}
{e.clubLogHasOQRS && chip('var(--success)', 'OQRS')}
{e.clubLogLiveStream && (
<a href="#" onClick={(ev) => { ev.preventDefault(); void OpenExternalURL(`https://clublog.org/livestream/${e.callsign.replace('*', '')}`); }}
className="px-1.5 py-0.5 rounded text-[10px] font-bold border text-info border-info/40 bg-info/10 hover:bg-info/20">Live</a>
)}
{list.length > 0 && (needed > 0
? chip('var(--warning)', e.isContest ? t('wl.nToday', { n: needed }) : t('wl.nNeeded', { n: needed }))
: chip('var(--success)', e.isContest ? t('wl.workedToday') : t('wl.allWorked')))}
{e.lastSeenStr && e.lastSeenStr !== 'Never' && (
<span className="text-[11px] text-muted-foreground">· {e.lastSeenStr}</span>
)}
{e.spotCount > 0 && (
<span className="text-[11px] text-muted-foreground/70">· {t('wl.totalSpots', { n: e.spotCount })}</span>
)}
<div className="flex-1" />
<button type="button" title={t('wl.toggleContest')}
onClick={() => void WatchlistSetContest(e.callsign, !e.isContest).then(refresh)}
className={cn('p-1 rounded hover:bg-muted', e.isContest ? 'text-warning' : 'text-muted-foreground/40')}>
<Trophy className="size-3.5" />
</button>
<button type="button" title={e.notify ? t('wl.notifyOff') : t('wl.notifyOn')}
onClick={() => void WatchlistSetNotify(e.callsign, !e.notify).then(refresh)}
className={cn('p-1 rounded hover:bg-muted', e.notify ? 'text-warning' : 'text-muted-foreground/40')}>
{e.notify ? <Bell className="size-3.5" /> : <BellOff className="size-3.5" />}
</button>
<button type="button" title={t('wl.remove')}
onClick={() => void remove(e.callsign)}
className="p-1 rounded hover:bg-muted text-muted-foreground/40 hover:text-danger">
<Trash2 className="size-3.5" />
</button>
</div>
{list.length > 0 ? (
<div className="mt-2 space-y-1 max-h-52 overflow-y-auto">
{list.slice(0, 12).map((s, i) => {
const done = workedFor(e, s);
const badge = dxccBadge(s);
const mode = inferSpotMode(s.comment ?? '', s.freq_hz);
return (
<button key={i} type="button"
onClick={() => onSpotSelect?.(s)}
onDoubleClick={() => onSpotClick?.(s)}
title={t('wl.spotTip')}
className={cn('w-full flex items-center gap-2 px-2 py-1.5 rounded text-[11px] bg-muted/25 hover:bg-muted/70 transition-colors text-left',
!done && 'border-l-[3px] border-warning')}>
{done && <span className='font-bold shrink-0 text-success'></span>}
{/* Fixed columns: an elastic country made band/mode/freq start wherever the name ended — every row its own ruler. */}
<span className="font-mono font-bold text-info shrink-0 w-24 truncate">{s.dx_call}</span>
<span className="text-muted-foreground truncate shrink-0 w-44">{(s as any).country ?? ''}</span>
<span className="px-1.5 rounded bg-muted shrink-0 w-11 text-center">{s.band}</span>
<span className="px-1.5 rounded shrink-0 w-11 text-center" style={mode ? { color: 'var(--chart-5)', background: 'color-mix(in srgb, var(--chart-5) 12%, transparent)' } : undefined}>{mode || ' '}</span>
<span className="font-mono text-muted-foreground shrink-0 w-16 text-right">{(s.freq_hz / 1e6).toFixed(4)}</span>
{badge && chip(badge.color, badge.label)}
<div className="flex-1" />
{done
? chip('var(--success)', e.isContest ? t('wl.todayOk') : t('wl.worked'))
: chip('var(--warning)', e.isContest ? t('wl.workToday') : t('wl.needed'))}
<span className="text-muted-foreground/70 shrink-0">{s.time_utc ?? ''}</span>
</button>
);
})}
</div>
) : (
<div className="mt-2 text-[11px] text-muted-foreground text-center py-1.5 bg-muted/30 rounded">
{t('wl.noSpots')}
</div>
)}
</div>
);
})}
</div>
</div>
);
}
+4 -4
View File
@@ -26,7 +26,7 @@ interface Props {
wpm: number; wpm: number;
macros: WKMacro[]; macros: WKMacro[];
sent: string; // text echoed back by the keyer as it transmits sent: string; // text echoed back by the keyer as it transmits
source: 'winkeyer' | 'icom' | 'flex' | 'yaesu' | 'kenwood'; // CW output engine (chosen in Settings → CW Keyer) source: 'winkeyer' | 'icom' | 'flex' | 'yaesu' | 'kenwood' | 'tci'; // CW output engine (chosen in Settings → CW Keyer)
breakIn?: number; // Icom CW break-in: 0=OFF, 1=SEMI, 2=FULL breakIn?: number; // Icom CW break-in: 0=OFF, 1=SEMI, 2=FULL
onSetBreakIn?: (mode: number) => void; onSetBreakIn?: (mode: number) => void;
onSelectPort: (p: string) => void; onSelectPort: (p: string) => void;
@@ -109,16 +109,16 @@ export function WinkeyerPanel({
<Radio className="size-4 text-primary shrink-0" /> <Radio className="size-4 text-primary shrink-0" />
{/* CW output engine (chosen in Settings → CW Keyer). */} {/* CW output engine (chosen in Settings → CW Keyer). */}
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground shrink-0"> <span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground shrink-0">
{source === 'icom' ? 'Icom CW' : source === 'flex' ? 'Flex CWX' : source === 'yaesu' ? 'Yaesu CW' : source === 'kenwood' ? 'Kenwood CW' : 'WinKeyer'} {source === 'icom' ? 'Icom CW' : source === 'flex' ? 'Flex CWX' : source === 'yaesu' ? 'Yaesu CW' : source === 'kenwood' ? 'Kenwood CW' : source === 'tci' ? 'TCI CW' : 'WinKeyer'}
</span> </span>
<span className={cn('size-2 rounded-full', connected ? (status.busy ? 'bg-warning animate-pulse' : 'bg-success') : 'bg-muted-foreground/40')} <span className={cn('size-2 rounded-full', connected ? (status.busy ? 'bg-warning animate-pulse' : 'bg-success') : 'bg-muted-foreground/40')}
title={connected ? (status.busy ? t('wkp.sending') : t('wkp.connectedV', { version: status.version })) : t('wkp.disconnected')} /> title={connected ? (status.busy ? t('wkp.sending') : t('wkp.connectedV', { version: status.version })) : t('wkp.disconnected')} />
<div className="flex-1" /> <div className="flex-1" />
{source === 'icom' || source === 'flex' || source === 'yaesu' || source === 'kenwood' ? ( {source === 'icom' || source === 'flex' || source === 'yaesu' || source === 'kenwood' || source === 'tci' ? (
<span className="text-[11px] font-medium text-muted-foreground"> <span className="text-[11px] font-medium text-muted-foreground">
{source === 'flex' {source === 'flex'
? (connected ? t('wkp.cwxReady') : t('wkp.cwxOffline')) ? (connected ? t('wkp.cwxReady') : t('wkp.cwxOffline'))
: source === 'yaesu' || source === 'kenwood' : source === 'yaesu' || source === 'kenwood' || source === 'tci'
? (connected ? t('wkp.rigReady') : t('wkp.rigOffline')) ? (connected ? t('wkp.rigReady') : t('wkp.rigOffline'))
: (connected ? t('wkp.civReady') : t('wkp.civOffline'))} : (connected ? t('wkp.civReady') : t('wkp.civOffline'))}
</span> </span>
+113
View File
@@ -0,0 +1,113 @@
// IARU band plans, by region.
//
// The band maps used to carry one hard-coded table — Region 1's — so a US or
// Australian operator saw 40 m stop at 7200 while stations sat spotted at 7250,
// and the SSB wash started 25 kHz early. The region is a station-level fact the
// operator states once (Settings → General); everything drawing a band edge or
// a mode segment reads it from here.
//
// The tables are deliberately coarse: a band map's wash is CONTEXT, not a
// regulatory chart. Only the segments that differ between regions in ways an
// operator notices are split out; national fine print (US licence classes,
// beacon slots) does not belong in a background tint.
import { writeUiPref } from '@/lib/uiPref';
export type IaruRegion = 1 | 2 | 3;
export const KEY_IARU_REGION = 'opslog.iaruRegion';
export function iaruRegion(): IaruRegion {
try {
const v = localStorage.getItem(KEY_IARU_REGION);
return v === '2' ? 2 : v === '3' ? 3 : 1;
} catch { return 1; }
}
export function setIaruRegion(r: IaruRegion): void {
writeUiPref(KEY_IARU_REGION, String(r));
listeners.forEach((l) => l());
}
// The band maps capture the plan inside their render, so a change must reach
// them the way the distance unit reaches the grids.
const listeners = new Set<() => void>();
export function subscribeIaruRegion(fn: () => void): () => void {
listeners.add(fn);
return () => { listeners.delete(fn); };
}
export type SegMode = 'cw' | 'digi' | 'phone';
type Seg = [number, number, SegMode];
interface Plan {
ranges: Record<string, [number, number]>;
segments: Record<string, Seg[]>;
}
// Region 1 — Europe / Africa / Middle East / northern Asia. The baseline the
// other two override.
const R1: Plan = {
ranges: {
'160m': [1800, 2000], '80m': [3500, 3800], '60m': [5350, 5450],
'40m': [7000, 7200], '30m': [10100, 10150], '20m': [14000, 14350],
'17m': [18068, 18168], '15m': [21000, 21450], '12m': [24890, 24990],
'10m': [28000, 29700], '6m': [50000, 50500], '4m': [70000, 70500],
'2m': [144000, 146000], '70cm': [430000, 440000],
},
segments: {
'160m': [[1800, 1838, 'cw'], [1838, 1840, 'digi'], [1840, 2000, 'phone']],
'80m': [[3500, 3580, 'cw'], [3580, 3600, 'digi'], [3600, 3800, 'phone']],
'60m': [[5350, 5450, 'phone']],
'40m': [[7000, 7040, 'cw'], [7040, 7100, 'digi'], [7100, 7200, 'phone']],
'30m': [[10100, 10130, 'cw'], [10130, 10150, 'digi']],
'20m': [[14000, 14070, 'cw'], [14070, 14100, 'digi'], [14100, 14350, 'phone']],
'17m': [[18068, 18095, 'cw'], [18095, 18110, 'digi'], [18110, 18168, 'phone']],
'15m': [[21000, 21070, 'cw'], [21070, 21150, 'digi'], [21150, 21450, 'phone']],
'12m': [[24890, 24915, 'cw'], [24915, 24940, 'digi'], [24940, 24990, 'phone']],
'10m': [[28000, 28070, 'cw'], [28070, 28300, 'digi'], [28300, 29700, 'phone']],
'6m': [[50000, 50100, 'cw'], [50100, 50500, 'phone']],
},
};
// Region 2 — the Americas. 80 m runs to 4000 and 40 m to 7300, with phone from
// 7125 (the whole point of asking the region: a KP4 ragchew on 7250 must not
// hang past the top of the map).
const R2: Plan = {
ranges: {
...R1.ranges,
'80m': [3500, 4000], '40m': [7000, 7300],
'6m': [50000, 54000], '2m': [144000, 148000], '70cm': [420000, 450000],
},
segments: {
...R1.segments,
'80m': [[3500, 3570, 'cw'], [3570, 3600, 'digi'], [3600, 4000, 'phone']],
'40m': [[7000, 7040, 'cw'], [7040, 7125, 'digi'], [7125, 7300, 'phone']],
'6m': [[50000, 50100, 'cw'], [50100, 54000, 'phone']],
},
};
// Region 3 — Asia-Pacific. 80 m to 3900; 40 m as Region 1's shape.
const R3: Plan = {
ranges: {
...R1.ranges,
'80m': [3500, 3900],
'6m': [50000, 54000], '2m': [144000, 148000], '70cm': [430000, 450000],
},
segments: {
...R1.segments,
'80m': [[3500, 3535, 'cw'], [3535, 3600, 'digi'], [3600, 3900, 'phone']],
'6m': [[50000, 50100, 'cw'], [50100, 54000, 'phone']],
},
};
function plan(): Plan {
const r = iaruRegion();
return r === 2 ? R2 : r === 3 ? R3 : R1;
}
export function bandRange(band: string): [number, number] | undefined {
return plan().ranges[band];
}
export function bandSegments(band: string): Seg[] {
return plan().segments[band] ?? [];
}
+119 -51
View File
File diff suppressed because one or more lines are too long
+6 -1
View File
@@ -14,9 +14,11 @@ export type MatrixColors = {
entity_worked: string; entity_worked: string;
not_worked: string; not_worked: string;
current_entry: string; current_entry: string;
mark_worked: string;
mark_confirmed: string;
}; };
// The six settings fields and the CSS custom property each one drives. Also the // The settings fields and the CSS custom property each one drives. Also the
// display order — the same order the legend under the matrix reads in, so the // display order — the same order the legend under the matrix reads in, so the
// settings panel and the grid can never disagree about which green is which. // settings panel and the grid can never disagree about which green is which.
export const MATRIX_VARS: { key: keyof Omit<MatrixColors, 'enabled'>; cssVar: string; label: string }[] = [ export const MATRIX_VARS: { key: keyof Omit<MatrixColors, 'enabled'>; cssVar: string; label: string }[] = [
@@ -26,12 +28,15 @@ export const MATRIX_VARS: { key: keyof Omit<MatrixColors, 'enabled'>; cssVar: st
{ key: 'entity_worked', cssVar: '--mx-dx-work', label: 'mx.dxWork' }, { key: 'entity_worked', cssVar: '--mx-dx-work', label: 'mx.dxWork' },
{ key: 'not_worked', cssVar: '--mx-none', label: 'mx.none' }, { key: 'not_worked', cssVar: '--mx-none', label: 'mx.none' },
{ key: 'current_entry', cssVar: '--mx-cur', label: 'mx.current' }, { key: 'current_entry', cssVar: '--mx-cur', label: 'mx.current' },
{ key: 'mark_worked', cssVar: '--mx-mark-work', label: 'mx.markWork' },
{ key: 'mark_confirmed', cssVar: '--mx-mark-conf', label: 'mx.markConf' },
]; ];
export const emptyMatrixColors = (): MatrixColors => ({ export const emptyMatrixColors = (): MatrixColors => ({
enabled: false, enabled: false,
call_confirmed: '', call_worked: '', entity_confirmed: '', call_confirmed: '', call_worked: '', entity_confirmed: '',
entity_worked: '', not_worked: '', current_entry: '', entity_worked: '', not_worked: '', current_entry: '',
mark_worked: '', mark_confirmed: '',
}); });
// applyMatrixColors stamps (or clears) the overrides on <html>. Safe to call as // applyMatrixColors stamps (or clears) the overrides on <html>. Safe to call as
+5 -5
View File
@@ -36,17 +36,17 @@ export function inferSpotMode(comment: string, freqHz: number): string {
type Seg = [number, number, string]; type Seg = [number, number, string];
const segs: Seg[] = [ const segs: Seg[] = [
[1.8, 1.838, 'CW'], [1.838, 1.84, 'FT8'], [1.84, 2.0, 'SSB'], [1.8, 1.838, 'CW'], [1.838, 1.84, 'FT8'], [1.84, 2.0, 'SSB'],
[3.5, 3.58, 'CW'], [3.573, 3.576, 'FT8'], [3.58, 3.6, 'DATA'], [3.6, 4.0, 'SSB'], [3.573, 3.575, 'FT8'], [3.575, 3.578, 'FT4'], [3.5, 3.58, 'CW'], [3.58, 3.6, 'DATA'], [3.6, 4.0, 'SSB'],
[5.3, 5.5, 'SSB'], [5.357, 5.36, 'FT8'], [5.3, 5.5, 'SSB'],
[7.0, 7.04, 'CW'], [7.074, 7.077, 'FT8'], [7.0475, 7.0485, 'FT4'], [7.0, 7.04, 'CW'], [7.074, 7.077, 'FT8'], [7.0475, 7.0485, 'FT4'],
[7.04, 7.1, 'DATA'], [7.1, 7.3, 'SSB'], [7.04, 7.1, 'DATA'], [7.1, 7.3, 'SSB'],
[10.1, 10.13, 'CW'], [10.13, 10.15, 'DATA'], [10.136, 10.139, 'FT8'], [10.14, 10.143, 'FT4'], [10.1, 10.13, 'CW'], [10.13, 10.15, 'DATA'],
[14.0, 14.07, 'CW'], [14.074, 14.077, 'FT8'], [14.08, 14.0815, 'FT4'], [14.0, 14.07, 'CW'], [14.074, 14.077, 'FT8'], [14.08, 14.0815, 'FT4'],
[14.07, 14.1, 'DATA'], [14.1, 14.35, 'SSB'], [14.07, 14.1, 'DATA'], [14.1, 14.35, 'SSB'],
[18.068, 18.095, 'CW'], [18.1, 18.103, 'FT8'], [18.095, 18.11, 'DATA'], [18.11, 18.168, 'SSB'], [18.1, 18.103, 'FT8'], [18.104, 18.107, 'FT4'], [18.068, 18.095, 'CW'], [18.095, 18.11, 'DATA'], [18.11, 18.168, 'SSB'],
[21.0, 21.07, 'CW'], [21.074, 21.077, 'FT8'], [21.14, 21.143, 'FT4'], [21.0, 21.07, 'CW'], [21.074, 21.077, 'FT8'], [21.14, 21.143, 'FT4'],
[21.07, 21.15, 'DATA'], [21.15, 21.45, 'SSB'], [21.07, 21.15, 'DATA'], [21.15, 21.45, 'SSB'],
[24.89, 24.915, 'CW'], [24.915, 24.917, 'FT8'], [24.915, 24.94, 'DATA'], [24.94, 24.99, 'SSB'], [24.915, 24.918, 'FT8'], [24.919, 24.922, 'FT4'], [24.89, 24.915, 'CW'], [24.915, 24.94, 'DATA'], [24.94, 24.99, 'SSB'],
[28.0, 28.07, 'CW'], [28.074, 28.077, 'FT8'], [28.18, 28.183, 'FT4'], [28.0, 28.07, 'CW'], [28.074, 28.077, 'FT8'], [28.18, 28.183, 'FT4'],
[28.07, 28.3, 'DATA'], [28.3, 29.7, 'SSB'], [28.07, 28.3, 'DATA'], [28.3, 29.7, 'SSB'],
[50.0, 50.1, 'CW'], [50.313, 50.316, 'FT8'], [50.318, 50.321, 'FT4'], [50.0, 50.1, 'CW'], [50.313, 50.316, 'FT8'], [50.318, 50.321, 'FT4'],
+29 -3
View File
@@ -11,7 +11,25 @@
// //
// They compose deliberately: mute what is done, light up what is not. // They compose deliberately: mute what is done, light up what is not.
export type SpotDisplayOptions = { muteWorked: boolean; slotHighlight: boolean }; export type SpotDisplayOptions = {
muteWorked: boolean; slotHighlight: boolean;
// Chase switches (Settings → DX Cluster), ON by default. An operator who does
// not chase parks does not want NEW POTA shouting from every activator spot:
// off, the marker is withdrawn at the display layer — a "new band + new POTA"
// spot simply reads NEW BAND — and the reference column goes quiet. The facts
// keep being computed; only the telling stops, so ticking the box back on
// needs no rescan.
chasePota: boolean; chaseSota: boolean;
};
// chasePota/chaseSota read the switches directly — for the places that show a
// REFERENCE rather than a status (the POTA and SOTA columns).
export function chasePota(): boolean {
try { return localStorage.getItem('opslog.chasePota') !== '0'; } catch { return true; }
}
export function chaseSota(): boolean {
try { return localStorage.getItem('opslog.chaseSota') !== '0'; } catch { return true; }
}
// Both options are withdrawn from the filter panel for now. The machinery below // Both options are withdrawn from the filter panel for now. The machinery below
// is deliberately kept whole — it is correct and hard-won — so putting the two // is deliberately kept whole — it is correct and hard-won — so putting the two
@@ -23,14 +41,19 @@ export type SpotDisplayOptions = { muteWorked: boolean; slotHighlight: boolean }
export const SPOT_DISPLAY_OPTIONS_EXPOSED = false; export const SPOT_DISPLAY_OPTIONS_EXPOSED = false;
export function readSpotDisplayOptions(): SpotDisplayOptions { export function readSpotDisplayOptions(): SpotDisplayOptions {
if (!SPOT_DISPLAY_OPTIONS_EXPOSED) return { muteWorked: false, slotHighlight: false }; // The EXPOSED flag only withdraws the two original switches; the chase
// switches are live regardless.
if (!SPOT_DISPLAY_OPTIONS_EXPOSED) {
return { muteWorked: false, slotHighlight: false, chasePota: chasePota(), chaseSota: chaseSota() };
}
try { try {
return { return {
muteWorked: localStorage.getItem('opslog.clusterMuteWorked') === '1', muteWorked: localStorage.getItem('opslog.clusterMuteWorked') === '1',
slotHighlight: localStorage.getItem('opslog.clusterSlotHighlight') === '1', slotHighlight: localStorage.getItem('opslog.clusterSlotHighlight') === '1',
chasePota: chasePota(), chaseSota: chaseSota(),
}; };
} catch { } catch {
return { muteWorked: false, slotHighlight: false }; return { muteWorked: false, slotHighlight: false, chasePota: true, chaseSota: true };
} }
} }
@@ -72,6 +95,9 @@ export function applySpotDisplay<T extends Entry>(s: T, o: SpotDisplayOptions):
if (o.muteWorked) { if (o.muteWorked) {
e = { ...e, worked_call: false } as NonNullable<T>; e = { ...e, worked_call: false } as NonNullable<T>;
} }
if (!o.chasePota && e.new_pota) {
e = { ...e, new_pota: false } as NonNullable<T>;
}
return e; return e;
} }
+2 -1
View File
@@ -18,7 +18,7 @@
// grid magenta — the last hue in the categorical set that is not already // grid magenta — the last hue in the categorical set that is not already
// spoken for here and does not read as a status; a grid is // spoken for here and does not read as a status; a grid is
// never urgent the way a new entity is // never urgent the way a new entity is
export type SpotMarkerKey = 'new_pota' | 'new_county' | 'new_pfx' | 'worked_call' | 'new_grid'; export type SpotMarkerKey = 'new_pota' | 'new_county' | 'new_pfx' | 'worked_call' | 'new_grid' | 'new_state';
export type SpotMarker = { export type SpotMarker = {
key: SpotMarkerKey; key: SpotMarkerKey;
@@ -32,6 +32,7 @@ export const SPOT_MARKERS: SpotMarker[] = [
{ key: 'new_county', colour: 'var(--chart-5)', labelKey: 'clg2.newCounty' }, { key: 'new_county', colour: 'var(--chart-5)', labelKey: 'clg2.newCounty' },
{ key: 'new_pfx', colour: 'var(--caution)', labelKey: 'clg2.newPfx' }, { key: 'new_pfx', colour: 'var(--caution)', labelKey: 'clg2.newPfx' },
{ key: 'new_grid', colour: 'var(--chart-7)', labelKey: 'clg2.newGrid' }, { key: 'new_grid', colour: 'var(--chart-7)', labelKey: 'clg2.newGrid' },
{ key: 'new_state', colour: 'var(--chart-3)', labelKey: 'clg2.newState' },
{ key: 'worked_call', colour: 'var(--info)', labelKey: 'clg2.wkdCall' }, { key: 'worked_call', colour: 'var(--info)', labelKey: 'clg2.wkdCall' },
]; ];
+4
View File
@@ -40,6 +40,10 @@ const PORTABLE_KEYS = [
'opslog.clusterFilterSource', 'opslog.clusterGroup', 'opslog.clusterBands', 'opslog.clusterFilterSource', 'opslog.clusterGroup', 'opslog.clusterBands',
'opslog.clusterLockBand', 'opslog.clusterLockMode', 'opslog.clusterStatusFilter', 'opslog.clusterLockBand', 'opslog.clusterLockMode', 'opslog.clusterStatusFilter',
'opslog.clusterModeFilter', 'opslog.clusterSearch', 'opslog.clusterHideWorked', 'opslog.clusterModeFilter', 'opslog.clusterSearch', 'opslog.clusterHideWorked',
'opslog.distanceMiles', // distances shown in statute miles rather than km
'opslog.iaruRegion', // IARU region (1/2/3) — band edges and segments on the band maps
'opslog.chasePota', // show POTA references and the NEW POTA marker on spots
'opslog.chaseSota', // show SOTA references on spots
'opslog.activeTab', // last selected tab 'opslog.activeTab', // last selected tab
'opslog.mainSplit', // Main tab: width share of the left pane (percent) — legacy, read once to seed mainShares 'opslog.mainSplit', // Main tab: width share of the left pane (percent) — legacy, read once to seed mainShares
'opslog.mainShares', // Main tab: column shares per column count, as {2:[..],3:[..],4:[..]} 'opslog.mainShares', // Main tab: column shares per column count, as {2:[..],3:[..],4:[..]}
+49
View File
@@ -0,0 +1,49 @@
// Distance units.
//
// Everything is COMPUTED in kilometres — the great-circle maths, the backend's
// distance_km on a spot, the map's path lengths — and converted once, here, at
// display time. Storing miles anywhere would mean two sources of truth for the
// same number and a rounding error that grows with every hop.
//
// The preference is portable (see lib/uiPref): an operator who works in miles
// works in miles on every machine they copy their folder to.
import { writeUiPref } from '@/lib/uiPref';
export const KEY_MILES = 'opslog.distanceMiles';
const KM_PER_MILE = 1.609344; // statute miles, the ones a US licence is used in
export function useMiles(): boolean {
try { return localStorage.getItem(KEY_MILES) === '1'; } catch { return false; }
}
export function setUseMiles(on: boolean): void {
writeUiPref(KEY_MILES, on ? '1' : '0');
listeners.forEach((l) => l());
}
// subscribeDistanceUnit notifies on a change. The grids capture the unit inside
// their column definitions (header text and formatter both), so without this a
// toggle would only show up on the next language change or restart.
const listeners = new Set<() => void>();
export function subscribeDistanceUnit(fn: () => void): () => void {
listeners.add(fn);
return () => { listeners.delete(fn); };
}
// distanceValue converts a distance in km to the operator's unit, rounded to a
// whole unit — the precision the inputs actually justify (a 4-character grid is
// a square tens of kilometres wide).
export function distanceValue(km: number): number {
if (!isFinite(km)) return 0;
return Math.round(useMiles() ? km / KM_PER_MILE : km);
}
// distanceUnit is the short label: "km" or "mi".
export function distanceUnit(): string {
return useMiles() ? 'mi' : 'km';
}
// formatDistance is value + unit, thousands-separated: "12 345 km".
export function formatDistance(km: number): string {
return `${distanceValue(km).toLocaleString()} ${distanceUnit()}`;
}
+14
View File
@@ -91,6 +91,11 @@
be recoloured on its own without dragging every other warning in the app be recoloured on its own without dragging every other warning in the app
with it (Appearance matrix colours). */ with it (Appearance matrix colours). */
--mx-cur: var(--warning); --mx-cur: var(--warning);
/* The "worked with this callsign" dot. Declared ONCE, like --mx-cur: it is
drawn over every one of the five cell colours, so it follows the theme's own
foreground/background pair rather than a per-theme colour of its own. */
--mx-mark-work: var(--foreground);
--mx-mark-conf: var(--foreground);
--scrollbar-thumb: #b8a880; --scrollbar-thumb: #b8a880;
--scrollbar-thumb-hover: #968455; --scrollbar-thumb-hover: #968455;
@@ -981,6 +986,8 @@
--color-mx-dx-work: var(--mx-dx-work); --color-mx-dx-work: var(--mx-dx-work);
--color-mx-none: var(--mx-none); --color-mx-none: var(--mx-none);
--color-mx-cur: var(--mx-cur); --color-mx-cur: var(--mx-cur);
--color-mx-mark-work: var(--mx-mark-work);
--color-mx-mark-conf: var(--mx-mark-conf);
--radius: 0.5rem; --radius: 0.5rem;
@@ -1079,3 +1086,10 @@
.overflow-scroll { .overflow-scroll {
overscroll-behavior: contain; overscroll-behavior: contain;
} }
/* The ground beside the planet, on every map: Leaflet paints its container a
hard-coded light grey (#ddd), which reads as a broken tile against any
theme. The surround follows the theme's own card surface instead. */
.leaflet-container {
background: var(--card) !important;
}
+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.26.16'; export const APP_VERSION = '0.27.4';
// Author / credits, shown in Help -> About. // Author / credits, shown in Help -> About.
export const APP_AUTHOR = 'F4BPO'; export const APP_AUTHOR = 'F4BPO';
+113
View File
@@ -30,6 +30,7 @@ import {lotwusers} from '../models';
import {lookup} from '../models'; import {lookup} from '../models';
import {netctl} from '../models'; import {netctl} from '../models';
import {scp} from '../models'; import {scp} from '../models';
import {watchlist} from '../models';
export function ACOMSetOperate(arg1:boolean):Promise<void>; export function ACOMSetOperate(arg1:boolean):Promise<void>;
@@ -43,6 +44,10 @@ export function ADIFVersion():Promise<string>;
export function ActivateProfile(arg1:number):Promise<void>; export function ActivateProfile(arg1:number):Promise<void>;
export function ActiveRadioID():Promise<string>;
export function ActiveRadioMyRig():Promise<string>;
export function AddQSO(arg1:qso.QSO):Promise<number>; export function AddQSO(arg1:qso.QSO):Promise<number>;
export function AmpFanMode(arg1:string,arg2:string):Promise<void>; export function AmpFanMode(arg1:string,arg2:string):Promise<void>;
@@ -65,6 +70,8 @@ export function ApplyAwardPreset(arg1:string,arg2:string):Promise<number>;
export function ApplyAwardUpdate(arg1:string):Promise<void>; export function ApplyAwardUpdate(arg1:string):Promise<void>;
export function ApplyRDAChoices(arg1:Array<main.RDAChoice>):Promise<main.RDAApplyResult>;
export function AssignAwardRefToQSOs(arg1:string,arg2:string,arg3:Array<number>):Promise<number>; export function AssignAwardRefToQSOs(arg1:string,arg2:string,arg3:Array<number>):Promise<number>;
export function AudioApplyLevels(arg1:number,arg2:number):Promise<void>; export function AudioApplyLevels(arg1:number,arg2:number):Promise<void>;
@@ -135,6 +142,8 @@ export function ComputeQSOAwardRefs(arg1:qso.QSO):Promise<Array<main.QSOAwardRef
export function ComputeStationInfo(arg1:string,arg2:string):Promise<main.StationInfoComputed>; export function ComputeStationInfo(arg1:string,arg2:string):Promise<main.StationInfoComputed>;
export function ConfigureDecoderMode(arg1:string):Promise<void>;
export function ConnectAllClusters():Promise<void>; export function ConnectAllClusters():Promise<void>;
export function ConnectClusterServer(arg1:number):Promise<void>; export function ConnectClusterServer(arg1:number):Promise<void>;
@@ -151,6 +160,8 @@ export function CreateDatabase(arg1:string):Promise<void>;
export function DVKCancelRecord():Promise<void>; export function DVKCancelRecord():Promise<void>;
export function DVKDelete(arg1:number):Promise<void>;
export function DVKPlay(arg1:number):Promise<void>; export function DVKPlay(arg1:number):Promise<void>;
export function DVKPreview(arg1:number):Promise<void>; export function DVKPreview(arg1:number):Promise<void>;
@@ -399,6 +410,8 @@ export function GetAntGeniusSettings():Promise<main.AntGeniusSettings>;
export function GetAntGeniusStatus():Promise<antgenius.Status>; export function GetAntGeniusStatus():Promise<antgenius.Status>;
export function GetAudioMonitorPref():Promise<boolean>;
export function GetAudioSettings():Promise<main.AudioSettings>; export function GetAudioSettings():Promise<main.AudioSettings>;
export function GetAutostartPrograms():Promise<Array<main.AutostartProgram>>; export function GetAutostartPrograms():Promise<Array<main.AutostartProgram>>;
@@ -439,6 +452,8 @@ export function GetChaseNewGrids():Promise<boolean>;
export function GetChaseNewSpots():Promise<Array<main.ChaseNewSpot>>; export function GetChaseNewSpots():Promise<Array<main.ChaseNewSpot>>;
export function GetChaseSettings():Promise<main.ChaseSettings>;
export function GetChatHistory(arg1:number):Promise<Array<main.ChatMessage>>; export function GetChatHistory(arg1:number):Promise<Array<main.ChatMessage>>;
export function GetClublogCtyInfo():Promise<main.ClublogCtyInfo>; export function GetClublogCtyInfo():Promise<main.ClublogCtyInfo>;
@@ -499,6 +514,10 @@ export function GetLiveOpenings():Promise<Array<bandopen.Opening>>;
export function GetLiveStations():Promise<Array<main.LiveStation>>; export function GetLiveStations():Promise<Array<main.LiveStation>>;
export function GetLoTWDownloadAllCalls():Promise<boolean>;
export function GetLoTWQSLDetail():Promise<boolean>;
export function GetLoTWUsersStatus():Promise<main.LoTWUsersStatus>; export function GetLoTWUsersStatus():Promise<main.LoTWUsersStatus>;
export function GetLogFilePath():Promise<string>; export function GetLogFilePath():Promise<string>;
@@ -539,6 +558,8 @@ export function GetQSO(arg1:number):Promise<qso.QSO>;
export function GetQSORate():Promise<main.QSORate>; export function GetQSORate():Promise<main.QSORate>;
export function GetRadios():Promise<Array<main.RadioConfig>>;
export function GetRelayAuto():Promise<main.RelayAutoConfig>; export function GetRelayAuto():Promise<main.RelayAutoConfig>;
export function GetRotatorHeading():Promise<main.RotatorHeading>; export function GetRotatorHeading():Promise<main.RotatorHeading>;
@@ -575,6 +596,8 @@ export function GetStationSettings():Promise<main.StationSettings>;
export function GetStationStatus():Promise<Array<main.StationDeviceStatus>>; export function GetStationStatus():Promise<Array<main.StationDeviceStatus>>;
export function GetTCIPanel():Promise<cat.TCIPanelState>;
export function GetTelemetryEnabled():Promise<boolean>; export function GetTelemetryEnabled():Promise<boolean>;
export function GetTrackedAwards():Promise<Array<string>>; export function GetTrackedAwards():Promise<Array<string>>;
@@ -589,6 +612,8 @@ export function GetUltrabeamSettings():Promise<main.UltrabeamSettings>;
export function GetUltrabeamStatus():Promise<main.UltrabeamStatusInfo>; export function GetUltrabeamStatus():Promise<main.UltrabeamStatusInfo>;
export function GetWatchlistContestPattern():Promise<string>;
export function GetWebPublishConfig():Promise<webpub.Config>; export function GetWebPublishConfig():Promise<webpub.Config>;
export function GetWebPublishStatus():Promise<main.WebPublishStatus>; export function GetWebPublishStatus():Promise<main.WebPublishStatus>;
@@ -601,6 +626,10 @@ export function GetWinkeyerStatus():Promise<winkeyer.Status>;
export function GetWorkedCallVariants():Promise<boolean>; export function GetWorkedCallVariants():Promise<boolean>;
export function GetWsjtFollowMode():Promise<boolean>;
export function GetWsjtHighlight():Promise<boolean>;
export function GetYaesuBandAntennas():Promise<Record<string, number>>; export function GetYaesuBandAntennas():Promise<Record<string, number>>;
export function GetYaesuState():Promise<cat.YaesuTXState>; export function GetYaesuState():Promise<cat.YaesuTXState>;
@@ -611,6 +640,8 @@ export function HaltDecodeTx(arg1:string,arg2:boolean):Promise<void>;
export function HasBuiltinReferences(arg1:string):Promise<boolean>; export function HasBuiltinReferences(arg1:string):Promise<boolean>;
export function IcomConsolePTT(arg1:boolean):Promise<void>;
export function IcomRefresh():Promise<void>; export function IcomRefresh():Promise<void>;
export function IcomScopeData():Promise<cat.ScopeSweep>; export function IcomScopeData():Promise<cat.ScopeSweep>;
@@ -625,6 +656,8 @@ export function IcomSetANF(arg1:boolean):Promise<void>;
export function IcomSetAPF(arg1:boolean):Promise<void>; export function IcomSetAPF(arg1:boolean):Promise<void>;
export function IcomSetATU(arg1:boolean):Promise<void>;
export function IcomSetAntenna(arg1:number):Promise<void>; export function IcomSetAntenna(arg1:number):Promise<void>;
export function IcomSetAntiVOX(arg1:number):Promise<void>; export function IcomSetAntiVOX(arg1:number):Promise<void>;
@@ -685,6 +718,8 @@ export function IcomSetScopeMode(arg1:boolean):Promise<void>;
export function IcomSetSplit(arg1:boolean):Promise<void>; export function IcomSetSplit(arg1:boolean):Promise<void>;
export function IcomSetSplitOffset(arg1:number):Promise<void>;
export function IcomSetSquelch(arg1:number):Promise<void>; export function IcomSetSquelch(arg1:number):Promise<void>;
export function IcomSetVOX(arg1:boolean):Promise<void>; export function IcomSetVOX(arg1:boolean):Promise<void>;
@@ -741,6 +776,8 @@ export function ListQSO(arg1:qso.ListFilter):Promise<Array<qso.QSO>>;
export function ListQSOFiltered(arg1:qso.QueryFilter):Promise<Array<qso.QSO>>; export function ListQSOFiltered(arg1:qso.QueryFilter):Promise<Array<qso.QSO>>;
export function ListRadios():Promise<Array<main.RadioListEntry>>;
export function ListSerialPorts():Promise<Array<string>>; export function ListSerialPorts():Promise<Array<string>>;
export function ListTQSLStationLocations():Promise<Array<extsvc.StationLocation>>; export function ListTQSLStationLocations():Promise<Array<extsvc.StationLocation>>;
@@ -993,6 +1030,8 @@ export function SaveCATSettings(arg1:main.CATSettings):Promise<void>;
export function SaveCabrilloFile():Promise<string>; export function SaveCabrilloFile():Promise<string>;
export function SaveChaseSettings(arg1:main.ChaseSettings):Promise<void>;
export function SaveClusterServer(arg1:cluster.ServerConfig):Promise<cluster.ServerConfig>; export function SaveClusterServer(arg1:cluster.ServerConfig):Promise<cluster.ServerConfig>;
export function SaveEmailSettings(arg1:main.EmailSettings):Promise<void>; export function SaveEmailSettings(arg1:main.EmailSettings):Promise<void>;
@@ -1033,6 +1072,8 @@ export function SaveProfile(arg1:profile.Profile):Promise<profile.Profile>;
export function SaveQSLDefaults(arg1:main.QSLDefaults):Promise<void>; export function SaveQSLDefaults(arg1:main.QSLDefaults):Promise<void>;
export function SaveRadios(arg1:Array<main.RadioConfig>):Promise<void>;
export function SaveRelayAuto(arg1:main.RelayAutoConfig):Promise<void>; export function SaveRelayAuto(arg1:main.RelayAutoConfig):Promise<void>;
export function SaveRotators(arg1:Array<main.RotatorDevice>):Promise<void>; export function SaveRotators(arg1:Array<main.RotatorDevice>):Promise<void>;
@@ -1079,6 +1120,8 @@ export function SendLogToDeveloper():Promise<void>;
export function SendQSORecordingEmail(arg1:number):Promise<void>; export function SendQSORecordingEmail(arg1:number):Promise<void>;
export function SetActiveRadio(arg1:string):Promise<void>;
export function SetActiveRotor(arg1:number):Promise<void>; export function SetActiveRotor(arg1:number):Promise<void>;
export function SetAlertEmailTo(arg1:string):Promise<void>; export function SetAlertEmailTo(arg1:string):Promise<void>;
@@ -1127,6 +1170,8 @@ export function SetKenwoodNB(arg1:boolean):Promise<void>;
export function SetKenwoodNR(arg1:boolean):Promise<void>; export function SetKenwoodNR(arg1:boolean):Promise<void>;
export function SetKenwoodPanelMode(arg1:string):Promise<void>;
export function SetKenwoodPower(arg1:number):Promise<void>; export function SetKenwoodPower(arg1:number):Promise<void>;
export function SetKenwoodPreamp(arg1:boolean):Promise<void>; export function SetKenwoodPreamp(arg1:boolean):Promise<void>;
@@ -1135,6 +1180,8 @@ export function SetKenwoodRFGain(arg1:number):Promise<void>;
export function SetKenwoodRIT(arg1:boolean):Promise<void>; export function SetKenwoodRIT(arg1:boolean):Promise<void>;
export function SetKenwoodRITOffset(arg1:number):Promise<void>;
export function SetKenwoodSquelch(arg1:number):Promise<void>; export function SetKenwoodSquelch(arg1:number):Promise<void>;
export function SetKenwoodTX(arg1:boolean):Promise<void>; export function SetKenwoodTX(arg1:boolean):Promise<void>;
@@ -1143,6 +1190,10 @@ export function SetKenwoodXIT(arg1:boolean):Promise<void>;
export function SetLinkedAmps(arg1:Array<string>):Promise<void>; export function SetLinkedAmps(arg1:Array<string>):Promise<void>;
export function SetLoTWDownloadAllCalls(arg1:boolean):Promise<void>;
export function SetLoTWQSLDetail(arg1:boolean):Promise<void>;
export function SetMotorFollow(arg1:boolean,arg2:number,arg3:string):Promise<void>; export function SetMotorFollow(arg1:boolean,arg2:number,arg3:string):Promise<void>;
export function SetOpsLogQSLReceived(arg1:number,arg2:boolean):Promise<void>; export function SetOpsLogQSLReceived(arg1:number,arg2:boolean):Promise<void>;
@@ -1157,16 +1208,60 @@ export function SetSpotMax(arg1:number):Promise<void>;
export function SetSpotTTLMinutes(arg1:number):Promise<void>; export function SetSpotTTLMinutes(arg1:number):Promise<void>;
export function SetTCIAGC(arg1:string):Promise<void>;
export function SetTCIANF(arg1:boolean):Promise<void>;
export function SetTCIAPF(arg1:boolean):Promise<void>;
export function SetTCIDrive(arg1:number):Promise<void>;
export function SetTCIFilter(arg1:number,arg2:number):Promise<void>;
export function SetTCILock(arg1:boolean):Promise<void>;
export function SetTCIMicLevel(arg1:number):Promise<void>;
export function SetTCIMute(arg1:boolean):Promise<void>;
export function SetTCINB(arg1:boolean):Promise<void>;
export function SetTCINR(arg1:boolean):Promise<void>;
export function SetTCIRIT(arg1:boolean):Promise<void>;
export function SetTCIRITOffset(arg1:number):Promise<void>;
export function SetTCISquelch(arg1:boolean):Promise<void>;
export function SetTCISquelchLevel(arg1:number):Promise<void>;
export function SetTCITune(arg1:boolean):Promise<void>;
export function SetTCITuneDrive(arg1:number):Promise<void>;
export function SetTCIVolume(arg1:number):Promise<void>;
export function SetTCIXIT(arg1:boolean):Promise<void>;
export function SetTCIXITOffset(arg1:number):Promise<void>;
export function SetTelemetryEnabled(arg1:boolean):Promise<void>; export function SetTelemetryEnabled(arg1:boolean):Promise<void>;
export function SetUIPref(arg1:string,arg2:string):Promise<void>; export function SetUIPref(arg1:string,arg2:string):Promise<void>;
export function SetUltrabeamDirection(arg1:number):Promise<void>; export function SetUltrabeamDirection(arg1:number):Promise<void>;
export function SetWatchlistContestPattern(arg1:string):Promise<void>;
export function SetWinkeyerTrace(arg1:boolean):Promise<void>; export function SetWinkeyerTrace(arg1:boolean):Promise<void>;
export function SetWorkedCallVariants(arg1:boolean):Promise<void>; export function SetWorkedCallVariants(arg1:boolean):Promise<void>;
export function SetWsjtFollowMode(arg1:boolean):Promise<void>;
export function SetWsjtHighlight(arg1:boolean):Promise<void>;
export function SetYaesuAFGain(arg1:number):Promise<void>; export function SetYaesuAFGain(arg1:number):Promise<void>;
export function SetYaesuAGC(arg1:string):Promise<void>; export function SetYaesuAGC(arg1:string):Promise<void>;
@@ -1219,6 +1314,12 @@ export function SyncFolderNow():Promise<number>;
export function SyncPOTAHunterLog(arg1:boolean,arg2:boolean):Promise<main.POTASyncResult>; export function SyncPOTAHunterLog(arg1:boolean,arg2:boolean):Promise<main.POTASyncResult>;
export function TCISendCW(arg1:string):Promise<void>;
export function TCISetKeySpeed(arg1:number):Promise<void>;
export function TCIStopCW():Promise<void>;
export function TailLogFile(arg1:number):Promise<string>; export function TailLogFile(arg1:number):Promise<string>;
export function TestCloudlogUpload():Promise<string>; export function TestCloudlogUpload():Promise<string>;
@@ -1287,6 +1388,18 @@ export function UploadCallsign(arg1:string):Promise<string>;
export function UploadQSOsManual(arg1:string,arg2:Array<number>):Promise<void>; export function UploadQSOsManual(arg1:string,arg2:Array<number>):Promise<void>;
export function WatchlistAdd(arg1:string,arg2:boolean):Promise<void>;
export function WatchlistEntries():Promise<Array<watchlist.Entry>>;
export function WatchlistRemove(arg1:string):Promise<void>;
export function WatchlistSetContest(arg1:string,arg2:boolean):Promise<void>;
export function WatchlistSetNotify(arg1:string,arg2:boolean):Promise<void>;
export function WatchlistWorkedSlots(arg1:Array<main.WatchlistSlotQuery>):Promise<Array<boolean>>;
export function WebPublishColumns():Promise<Array<Record<string, string>>>; export function WebPublishColumns():Promise<Array<Record<string, string>>>;
export function WinkeyerBackspace():Promise<void>; export function WinkeyerBackspace():Promise<void>;
+224
View File
@@ -26,6 +26,14 @@ export function ActivateProfile(arg1) {
return window['go']['main']['App']['ActivateProfile'](arg1); return window['go']['main']['App']['ActivateProfile'](arg1);
} }
export function ActiveRadioID() {
return window['go']['main']['App']['ActiveRadioID']();
}
export function ActiveRadioMyRig() {
return window['go']['main']['App']['ActiveRadioMyRig']();
}
export function AddQSO(arg1) { export function AddQSO(arg1) {
return window['go']['main']['App']['AddQSO'](arg1); return window['go']['main']['App']['AddQSO'](arg1);
} }
@@ -70,6 +78,10 @@ export function ApplyAwardUpdate(arg1) {
return window['go']['main']['App']['ApplyAwardUpdate'](arg1); return window['go']['main']['App']['ApplyAwardUpdate'](arg1);
} }
export function ApplyRDAChoices(arg1) {
return window['go']['main']['App']['ApplyRDAChoices'](arg1);
}
export function AssignAwardRefToQSOs(arg1, arg2, arg3) { export function AssignAwardRefToQSOs(arg1, arg2, arg3) {
return window['go']['main']['App']['AssignAwardRefToQSOs'](arg1, arg2, arg3); return window['go']['main']['App']['AssignAwardRefToQSOs'](arg1, arg2, arg3);
} }
@@ -210,6 +222,10 @@ export function ComputeStationInfo(arg1, arg2) {
return window['go']['main']['App']['ComputeStationInfo'](arg1, arg2); return window['go']['main']['App']['ComputeStationInfo'](arg1, arg2);
} }
export function ConfigureDecoderMode(arg1) {
return window['go']['main']['App']['ConfigureDecoderMode'](arg1);
}
export function ConnectAllClusters() { export function ConnectAllClusters() {
return window['go']['main']['App']['ConnectAllClusters'](); return window['go']['main']['App']['ConnectAllClusters']();
} }
@@ -242,6 +258,10 @@ export function DVKCancelRecord() {
return window['go']['main']['App']['DVKCancelRecord'](); return window['go']['main']['App']['DVKCancelRecord']();
} }
export function DVKDelete(arg1) {
return window['go']['main']['App']['DVKDelete'](arg1);
}
export function DVKPlay(arg1) { export function DVKPlay(arg1) {
return window['go']['main']['App']['DVKPlay'](arg1); return window['go']['main']['App']['DVKPlay'](arg1);
} }
@@ -738,6 +758,10 @@ export function GetAntGeniusStatus() {
return window['go']['main']['App']['GetAntGeniusStatus'](); return window['go']['main']['App']['GetAntGeniusStatus']();
} }
export function GetAudioMonitorPref() {
return window['go']['main']['App']['GetAudioMonitorPref']();
}
export function GetAudioSettings() { export function GetAudioSettings() {
return window['go']['main']['App']['GetAudioSettings'](); return window['go']['main']['App']['GetAudioSettings']();
} }
@@ -818,6 +842,10 @@ export function GetChaseNewSpots() {
return window['go']['main']['App']['GetChaseNewSpots'](); return window['go']['main']['App']['GetChaseNewSpots']();
} }
export function GetChaseSettings() {
return window['go']['main']['App']['GetChaseSettings']();
}
export function GetChatHistory(arg1) { export function GetChatHistory(arg1) {
return window['go']['main']['App']['GetChatHistory'](arg1); return window['go']['main']['App']['GetChatHistory'](arg1);
} }
@@ -938,6 +966,14 @@ export function GetLiveStations() {
return window['go']['main']['App']['GetLiveStations'](); return window['go']['main']['App']['GetLiveStations']();
} }
export function GetLoTWDownloadAllCalls() {
return window['go']['main']['App']['GetLoTWDownloadAllCalls']();
}
export function GetLoTWQSLDetail() {
return window['go']['main']['App']['GetLoTWQSLDetail']();
}
export function GetLoTWUsersStatus() { export function GetLoTWUsersStatus() {
return window['go']['main']['App']['GetLoTWUsersStatus'](); return window['go']['main']['App']['GetLoTWUsersStatus']();
} }
@@ -1018,6 +1054,10 @@ export function GetQSORate() {
return window['go']['main']['App']['GetQSORate'](); return window['go']['main']['App']['GetQSORate']();
} }
export function GetRadios() {
return window['go']['main']['App']['GetRadios']();
}
export function GetRelayAuto() { export function GetRelayAuto() {
return window['go']['main']['App']['GetRelayAuto'](); return window['go']['main']['App']['GetRelayAuto']();
} }
@@ -1090,6 +1130,10 @@ export function GetStationStatus() {
return window['go']['main']['App']['GetStationStatus'](); return window['go']['main']['App']['GetStationStatus']();
} }
export function GetTCIPanel() {
return window['go']['main']['App']['GetTCIPanel']();
}
export function GetTelemetryEnabled() { export function GetTelemetryEnabled() {
return window['go']['main']['App']['GetTelemetryEnabled'](); return window['go']['main']['App']['GetTelemetryEnabled']();
} }
@@ -1118,6 +1162,10 @@ export function GetUltrabeamStatus() {
return window['go']['main']['App']['GetUltrabeamStatus'](); return window['go']['main']['App']['GetUltrabeamStatus']();
} }
export function GetWatchlistContestPattern() {
return window['go']['main']['App']['GetWatchlistContestPattern']();
}
export function GetWebPublishConfig() { export function GetWebPublishConfig() {
return window['go']['main']['App']['GetWebPublishConfig'](); return window['go']['main']['App']['GetWebPublishConfig']();
} }
@@ -1142,6 +1190,14 @@ export function GetWorkedCallVariants() {
return window['go']['main']['App']['GetWorkedCallVariants'](); return window['go']['main']['App']['GetWorkedCallVariants']();
} }
export function GetWsjtFollowMode() {
return window['go']['main']['App']['GetWsjtFollowMode']();
}
export function GetWsjtHighlight() {
return window['go']['main']['App']['GetWsjtHighlight']();
}
export function GetYaesuBandAntennas() { export function GetYaesuBandAntennas() {
return window['go']['main']['App']['GetYaesuBandAntennas'](); return window['go']['main']['App']['GetYaesuBandAntennas']();
} }
@@ -1162,6 +1218,10 @@ export function HasBuiltinReferences(arg1) {
return window['go']['main']['App']['HasBuiltinReferences'](arg1); return window['go']['main']['App']['HasBuiltinReferences'](arg1);
} }
export function IcomConsolePTT(arg1) {
return window['go']['main']['App']['IcomConsolePTT'](arg1);
}
export function IcomRefresh() { export function IcomRefresh() {
return window['go']['main']['App']['IcomRefresh'](); return window['go']['main']['App']['IcomRefresh']();
} }
@@ -1190,6 +1250,10 @@ export function IcomSetAPF(arg1) {
return window['go']['main']['App']['IcomSetAPF'](arg1); return window['go']['main']['App']['IcomSetAPF'](arg1);
} }
export function IcomSetATU(arg1) {
return window['go']['main']['App']['IcomSetATU'](arg1);
}
export function IcomSetAntenna(arg1) { export function IcomSetAntenna(arg1) {
return window['go']['main']['App']['IcomSetAntenna'](arg1); return window['go']['main']['App']['IcomSetAntenna'](arg1);
} }
@@ -1310,6 +1374,10 @@ export function IcomSetSplit(arg1) {
return window['go']['main']['App']['IcomSetSplit'](arg1); return window['go']['main']['App']['IcomSetSplit'](arg1);
} }
export function IcomSetSplitOffset(arg1) {
return window['go']['main']['App']['IcomSetSplitOffset'](arg1);
}
export function IcomSetSquelch(arg1) { export function IcomSetSquelch(arg1) {
return window['go']['main']['App']['IcomSetSquelch'](arg1); return window['go']['main']['App']['IcomSetSquelch'](arg1);
} }
@@ -1422,6 +1490,10 @@ export function ListQSOFiltered(arg1) {
return window['go']['main']['App']['ListQSOFiltered'](arg1); return window['go']['main']['App']['ListQSOFiltered'](arg1);
} }
export function ListRadios() {
return window['go']['main']['App']['ListRadios']();
}
export function ListSerialPorts() { export function ListSerialPorts() {
return window['go']['main']['App']['ListSerialPorts'](); return window['go']['main']['App']['ListSerialPorts']();
} }
@@ -1926,6 +1998,10 @@ export function SaveCabrilloFile() {
return window['go']['main']['App']['SaveCabrilloFile'](); return window['go']['main']['App']['SaveCabrilloFile']();
} }
export function SaveChaseSettings(arg1) {
return window['go']['main']['App']['SaveChaseSettings'](arg1);
}
export function SaveClusterServer(arg1) { export function SaveClusterServer(arg1) {
return window['go']['main']['App']['SaveClusterServer'](arg1); return window['go']['main']['App']['SaveClusterServer'](arg1);
} }
@@ -2006,6 +2082,10 @@ export function SaveQSLDefaults(arg1) {
return window['go']['main']['App']['SaveQSLDefaults'](arg1); return window['go']['main']['App']['SaveQSLDefaults'](arg1);
} }
export function SaveRadios(arg1) {
return window['go']['main']['App']['SaveRadios'](arg1);
}
export function SaveRelayAuto(arg1) { export function SaveRelayAuto(arg1) {
return window['go']['main']['App']['SaveRelayAuto'](arg1); return window['go']['main']['App']['SaveRelayAuto'](arg1);
} }
@@ -2098,6 +2178,10 @@ export function SendQSORecordingEmail(arg1) {
return window['go']['main']['App']['SendQSORecordingEmail'](arg1); return window['go']['main']['App']['SendQSORecordingEmail'](arg1);
} }
export function SetActiveRadio(arg1) {
return window['go']['main']['App']['SetActiveRadio'](arg1);
}
export function SetActiveRotor(arg1) { export function SetActiveRotor(arg1) {
return window['go']['main']['App']['SetActiveRotor'](arg1); return window['go']['main']['App']['SetActiveRotor'](arg1);
} }
@@ -2194,6 +2278,10 @@ export function SetKenwoodNR(arg1) {
return window['go']['main']['App']['SetKenwoodNR'](arg1); return window['go']['main']['App']['SetKenwoodNR'](arg1);
} }
export function SetKenwoodPanelMode(arg1) {
return window['go']['main']['App']['SetKenwoodPanelMode'](arg1);
}
export function SetKenwoodPower(arg1) { export function SetKenwoodPower(arg1) {
return window['go']['main']['App']['SetKenwoodPower'](arg1); return window['go']['main']['App']['SetKenwoodPower'](arg1);
} }
@@ -2210,6 +2298,10 @@ export function SetKenwoodRIT(arg1) {
return window['go']['main']['App']['SetKenwoodRIT'](arg1); return window['go']['main']['App']['SetKenwoodRIT'](arg1);
} }
export function SetKenwoodRITOffset(arg1) {
return window['go']['main']['App']['SetKenwoodRITOffset'](arg1);
}
export function SetKenwoodSquelch(arg1) { export function SetKenwoodSquelch(arg1) {
return window['go']['main']['App']['SetKenwoodSquelch'](arg1); return window['go']['main']['App']['SetKenwoodSquelch'](arg1);
} }
@@ -2226,6 +2318,14 @@ export function SetLinkedAmps(arg1) {
return window['go']['main']['App']['SetLinkedAmps'](arg1); return window['go']['main']['App']['SetLinkedAmps'](arg1);
} }
export function SetLoTWDownloadAllCalls(arg1) {
return window['go']['main']['App']['SetLoTWDownloadAllCalls'](arg1);
}
export function SetLoTWQSLDetail(arg1) {
return window['go']['main']['App']['SetLoTWQSLDetail'](arg1);
}
export function SetMotorFollow(arg1, arg2, arg3) { export function SetMotorFollow(arg1, arg2, arg3) {
return window['go']['main']['App']['SetMotorFollow'](arg1, arg2, arg3); return window['go']['main']['App']['SetMotorFollow'](arg1, arg2, arg3);
} }
@@ -2254,6 +2354,82 @@ export function SetSpotTTLMinutes(arg1) {
return window['go']['main']['App']['SetSpotTTLMinutes'](arg1); return window['go']['main']['App']['SetSpotTTLMinutes'](arg1);
} }
export function SetTCIAGC(arg1) {
return window['go']['main']['App']['SetTCIAGC'](arg1);
}
export function SetTCIANF(arg1) {
return window['go']['main']['App']['SetTCIANF'](arg1);
}
export function SetTCIAPF(arg1) {
return window['go']['main']['App']['SetTCIAPF'](arg1);
}
export function SetTCIDrive(arg1) {
return window['go']['main']['App']['SetTCIDrive'](arg1);
}
export function SetTCIFilter(arg1, arg2) {
return window['go']['main']['App']['SetTCIFilter'](arg1, arg2);
}
export function SetTCILock(arg1) {
return window['go']['main']['App']['SetTCILock'](arg1);
}
export function SetTCIMicLevel(arg1) {
return window['go']['main']['App']['SetTCIMicLevel'](arg1);
}
export function SetTCIMute(arg1) {
return window['go']['main']['App']['SetTCIMute'](arg1);
}
export function SetTCINB(arg1) {
return window['go']['main']['App']['SetTCINB'](arg1);
}
export function SetTCINR(arg1) {
return window['go']['main']['App']['SetTCINR'](arg1);
}
export function SetTCIRIT(arg1) {
return window['go']['main']['App']['SetTCIRIT'](arg1);
}
export function SetTCIRITOffset(arg1) {
return window['go']['main']['App']['SetTCIRITOffset'](arg1);
}
export function SetTCISquelch(arg1) {
return window['go']['main']['App']['SetTCISquelch'](arg1);
}
export function SetTCISquelchLevel(arg1) {
return window['go']['main']['App']['SetTCISquelchLevel'](arg1);
}
export function SetTCITune(arg1) {
return window['go']['main']['App']['SetTCITune'](arg1);
}
export function SetTCITuneDrive(arg1) {
return window['go']['main']['App']['SetTCITuneDrive'](arg1);
}
export function SetTCIVolume(arg1) {
return window['go']['main']['App']['SetTCIVolume'](arg1);
}
export function SetTCIXIT(arg1) {
return window['go']['main']['App']['SetTCIXIT'](arg1);
}
export function SetTCIXITOffset(arg1) {
return window['go']['main']['App']['SetTCIXITOffset'](arg1);
}
export function SetTelemetryEnabled(arg1) { export function SetTelemetryEnabled(arg1) {
return window['go']['main']['App']['SetTelemetryEnabled'](arg1); return window['go']['main']['App']['SetTelemetryEnabled'](arg1);
} }
@@ -2266,6 +2442,10 @@ export function SetUltrabeamDirection(arg1) {
return window['go']['main']['App']['SetUltrabeamDirection'](arg1); return window['go']['main']['App']['SetUltrabeamDirection'](arg1);
} }
export function SetWatchlistContestPattern(arg1) {
return window['go']['main']['App']['SetWatchlistContestPattern'](arg1);
}
export function SetWinkeyerTrace(arg1) { export function SetWinkeyerTrace(arg1) {
return window['go']['main']['App']['SetWinkeyerTrace'](arg1); return window['go']['main']['App']['SetWinkeyerTrace'](arg1);
} }
@@ -2274,6 +2454,14 @@ export function SetWorkedCallVariants(arg1) {
return window['go']['main']['App']['SetWorkedCallVariants'](arg1); return window['go']['main']['App']['SetWorkedCallVariants'](arg1);
} }
export function SetWsjtFollowMode(arg1) {
return window['go']['main']['App']['SetWsjtFollowMode'](arg1);
}
export function SetWsjtHighlight(arg1) {
return window['go']['main']['App']['SetWsjtHighlight'](arg1);
}
export function SetYaesuAFGain(arg1) { export function SetYaesuAFGain(arg1) {
return window['go']['main']['App']['SetYaesuAFGain'](arg1); return window['go']['main']['App']['SetYaesuAFGain'](arg1);
} }
@@ -2378,6 +2566,18 @@ export function SyncPOTAHunterLog(arg1, arg2) {
return window['go']['main']['App']['SyncPOTAHunterLog'](arg1, arg2); return window['go']['main']['App']['SyncPOTAHunterLog'](arg1, arg2);
} }
export function TCISendCW(arg1) {
return window['go']['main']['App']['TCISendCW'](arg1);
}
export function TCISetKeySpeed(arg1) {
return window['go']['main']['App']['TCISetKeySpeed'](arg1);
}
export function TCIStopCW() {
return window['go']['main']['App']['TCIStopCW']();
}
export function TailLogFile(arg1) { export function TailLogFile(arg1) {
return window['go']['main']['App']['TailLogFile'](arg1); return window['go']['main']['App']['TailLogFile'](arg1);
} }
@@ -2514,6 +2714,30 @@ export function UploadQSOsManual(arg1, arg2) {
return window['go']['main']['App']['UploadQSOsManual'](arg1, arg2); return window['go']['main']['App']['UploadQSOsManual'](arg1, arg2);
} }
export function WatchlistAdd(arg1, arg2) {
return window['go']['main']['App']['WatchlistAdd'](arg1, arg2);
}
export function WatchlistEntries() {
return window['go']['main']['App']['WatchlistEntries']();
}
export function WatchlistRemove(arg1) {
return window['go']['main']['App']['WatchlistRemove'](arg1);
}
export function WatchlistSetContest(arg1, arg2) {
return window['go']['main']['App']['WatchlistSetContest'](arg1, arg2);
}
export function WatchlistSetNotify(arg1, arg2) {
return window['go']['main']['App']['WatchlistSetNotify'](arg1, arg2);
}
export function WatchlistWorkedSlots(arg1) {
return window['go']['main']['App']['WatchlistWorkedSlots'](arg1);
}
export function WebPublishColumns() { export function WebPublishColumns() {
return window['go']['main']['App']['WebPublishColumns'](); return window['go']['main']['App']['WebPublishColumns']();
} }
+323
View File
@@ -983,6 +983,7 @@ export namespace cat {
mode?: string; mode?: string;
transmitting: boolean; transmitting: boolean;
split: boolean; split: boolean;
sub_hz: number;
s_meter: number; s_meter: number;
power_meter: number; power_meter: number;
swr_meter: number; swr_meter: number;
@@ -1006,6 +1007,7 @@ export namespace cat {
att: number; att: number;
filter: number; filter: number;
antenna: number; antenna: number;
atu_on: boolean;
pbt_inner: number; pbt_inner: number;
pbt_outer: number; pbt_outer: number;
manual_notch: boolean; manual_notch: boolean;
@@ -1030,6 +1032,7 @@ export namespace cat {
this.mode = source["mode"]; this.mode = source["mode"];
this.transmitting = source["transmitting"]; this.transmitting = source["transmitting"];
this.split = source["split"]; this.split = source["split"];
this.sub_hz = source["sub_hz"];
this.s_meter = source["s_meter"]; this.s_meter = source["s_meter"];
this.power_meter = source["power_meter"]; this.power_meter = source["power_meter"];
this.swr_meter = source["swr_meter"]; this.swr_meter = source["swr_meter"];
@@ -1053,6 +1056,7 @@ export namespace cat {
this.att = source["att"]; this.att = source["att"];
this.filter = source["filter"]; this.filter = source["filter"];
this.antenna = source["antenna"]; this.antenna = source["antenna"];
this.atu_on = source["atu_on"];
this.pbt_inner = source["pbt_inner"]; this.pbt_inner = source["pbt_inner"];
this.pbt_outer = source["pbt_outer"]; this.pbt_outer = source["pbt_outer"];
this.manual_notch = source["manual_notch"]; this.manual_notch = source["manual_notch"];
@@ -1072,12 +1076,14 @@ export namespace cat {
model?: string; model?: string;
elecraft: boolean; elecraft: boolean;
mode?: string; mode?: string;
data_sub?: string;
transmitting: boolean; transmitting: boolean;
split: boolean; split: boolean;
split_tx_hz: number; split_tx_hz: number;
s_meter: number; s_meter: number;
s_meter_raw: number; s_meter_raw: number;
power_meter: number; power_meter: number;
power_w: number;
swr: number; swr: number;
swr_raw: number; swr_raw: number;
rf_power: number; rf_power: number;
@@ -1108,12 +1114,14 @@ export namespace cat {
this.model = source["model"]; this.model = source["model"];
this.elecraft = source["elecraft"]; this.elecraft = source["elecraft"];
this.mode = source["mode"]; this.mode = source["mode"];
this.data_sub = source["data_sub"];
this.transmitting = source["transmitting"]; this.transmitting = source["transmitting"];
this.split = source["split"]; this.split = source["split"];
this.split_tx_hz = source["split_tx_hz"]; this.split_tx_hz = source["split_tx_hz"];
this.s_meter = source["s_meter"]; this.s_meter = source["s_meter"];
this.s_meter_raw = source["s_meter_raw"]; this.s_meter_raw = source["s_meter_raw"];
this.power_meter = source["power_meter"]; this.power_meter = source["power_meter"];
this.power_w = source["power_w"];
this.swr = source["swr"]; this.swr = source["swr"];
this.swr_raw = source["swr_raw"]; this.swr_raw = source["swr_raw"];
this.rf_power = source["rf_power"]; this.rf_power = source["rf_power"];
@@ -1196,6 +1204,7 @@ export namespace cat {
low_hz: number; low_hz: number;
high_hz: number; high_hz: number;
fixed: boolean; fixed: boolean;
unsupported: boolean;
static createFrom(source: any = {}) { static createFrom(source: any = {}) {
return new ScopeSweep(source); return new ScopeSweep(source);
@@ -1208,6 +1217,77 @@ export namespace cat {
this.low_hz = source["low_hz"]; this.low_hz = source["low_hz"];
this.high_hz = source["high_hz"]; this.high_hz = source["high_hz"];
this.fixed = source["fixed"]; this.fixed = source["fixed"];
this.unsupported = source["unsupported"];
}
}
export class TCIPanelState {
connected: boolean;
device?: string;
protocol?: string;
drive: number;
tune_drive: number;
mic_level: number;
tx_enabled: boolean;
tx: boolean;
tuning: boolean;
volume: number;
mute: boolean;
agc?: string;
squelch_on: boolean;
squelch: number;
nb: boolean;
nr: boolean;
anf: boolean;
apf: boolean;
filter_lo: number;
filter_hi: number;
rit: boolean;
rit_offset: number;
xit: boolean;
xit_offset: number;
lock: boolean;
split: boolean;
smeter: number;
tx_power_w: number;
tx_swr: number;
modulations?: string[];
static createFrom(source: any = {}) {
return new TCIPanelState(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.connected = source["connected"];
this.device = source["device"];
this.protocol = source["protocol"];
this.drive = source["drive"];
this.tune_drive = source["tune_drive"];
this.mic_level = source["mic_level"];
this.tx_enabled = source["tx_enabled"];
this.tx = source["tx"];
this.tuning = source["tuning"];
this.volume = source["volume"];
this.mute = source["mute"];
this.agc = source["agc"];
this.squelch_on = source["squelch_on"];
this.squelch = source["squelch"];
this.nb = source["nb"];
this.nr = source["nr"];
this.anf = source["anf"];
this.apf = source["apf"];
this.filter_lo = source["filter_lo"];
this.filter_hi = source["filter_hi"];
this.rit = source["rit"];
this.rit_offset = source["rit_offset"];
this.xit = source["xit"];
this.xit_offset = source["xit_offset"];
this.lock = source["lock"];
this.split = source["split"];
this.smeter = source["smeter"];
this.tx_power_w = source["tx_power_w"];
this.tx_swr = source["tx_swr"];
this.modulations = source["modulations"];
} }
} }
export class YaesuTXState { export class YaesuTXState {
@@ -1500,6 +1580,51 @@ export namespace extsvc {
} }
export namespace kpa {
export class Status {
connected: boolean;
transport: string;
model?: string;
last_error?: string;
power_on: boolean;
operate: boolean;
fwd_w: number;
swr: number;
volt_v: number;
cur_a: number;
temp_c: number;
band?: string;
tuning: boolean;
fault_code: number;
fault_text?: string;
static createFrom(source: any = {}) {
return new Status(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.connected = source["connected"];
this.transport = source["transport"];
this.model = source["model"];
this.last_error = source["last_error"];
this.power_on = source["power_on"];
this.operate = source["operate"];
this.fwd_w = source["fwd_w"];
this.swr = source["swr"];
this.volt_v = source["volt_v"];
this.cur_a = source["cur_a"];
this.temp_c = source["temp_c"];
this.band = source["band"];
this.tuning = source["tuning"];
this.fault_code = source["fault_code"];
this.fault_text = source["fault_text"];
}
}
}
export namespace lookup { export namespace lookup {
export class Result { export class Result {
@@ -1701,6 +1826,7 @@ export namespace main {
pgxl?: powergenius.Status; pgxl?: powergenius.Status;
spe?: spe.Status; spe?: spe.Status;
acom?: acom.Status; acom?: acom.Status;
kpa?: kpa.Status;
static createFrom(source: any = {}) { static createFrom(source: any = {}) {
return new AmpStatus(source); return new AmpStatus(source);
@@ -1714,6 +1840,7 @@ export namespace main {
this.pgxl = this.convertValues(source["pgxl"], powergenius.Status); this.pgxl = this.convertValues(source["pgxl"], powergenius.Status);
this.spe = this.convertValues(source["spe"], spe.Status); this.spe = this.convertValues(source["spe"], spe.Status);
this.acom = this.convertValues(source["acom"], acom.Status); this.acom = this.convertValues(source["acom"], acom.Status);
this.kpa = this.convertValues(source["kpa"], kpa.Status);
} }
convertValues(a: any, classs: any, asMap: boolean = false): any { convertValues(a: any, classs: any, asMap: boolean = false): any {
@@ -2303,6 +2430,20 @@ export namespace main {
this.at = source["at"]; this.at = source["at"];
} }
} }
export class ChaseSettings {
mode: string;
sources: string[];
static createFrom(source: any = {}) {
return new ChaseSettings(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.mode = source["mode"];
this.sources = source["sources"];
}
}
export class ChatMessage { export class ChatMessage {
id: number; id: number;
operator: string; operator: string;
@@ -2949,6 +3090,8 @@ export namespace main {
entity_worked: string; entity_worked: string;
not_worked: string; not_worked: string;
current_entry: string; current_entry: string;
mark_worked: string;
mark_confirmed: string;
static createFrom(source: any = {}) { static createFrom(source: any = {}) {
return new MatrixColors(source); return new MatrixColors(source);
@@ -2963,6 +3106,8 @@ export namespace main {
this.entity_worked = source["entity_worked"]; this.entity_worked = source["entity_worked"];
this.not_worked = source["not_worked"]; this.not_worked = source["not_worked"];
this.current_entry = source["current_entry"]; this.current_entry = source["current_entry"];
this.mark_worked = source["mark_worked"];
this.mark_confirmed = source["mark_confirmed"];
} }
} }
@@ -3349,6 +3494,36 @@ export namespace main {
this.team_last60 = source["team_last60"]; this.team_last60 = source["team_last60"];
} }
} }
export class RDAApplyResult {
applied: number;
failed: number;
message: string;
static createFrom(source: any = {}) {
return new RDAApplyResult(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.applied = source["applied"];
this.failed = source["failed"];
this.message = source["message"];
}
}
export class RDAChoice {
qso_id: number;
district: string;
static createFrom(source: any = {}) {
return new RDAChoice(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.qso_id = source["qso_id"];
this.district = source["district"];
}
}
export class RDAConflict { export class RDAConflict {
qso_id: number; qso_id: number;
callsign: string; callsign: string;
@@ -3422,6 +3597,62 @@ export namespace main {
} }
} }
export class RadioConfig {
id: string;
name: string;
settings: CATSettings;
my_rig: string;
static createFrom(source: any = {}) {
return new RadioConfig(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.id = source["id"];
this.name = source["name"];
this.settings = this.convertValues(source["settings"], CATSettings);
this.my_rig = source["my_rig"];
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
if (!a) {
return a;
}
if (a.slice && a.map) {
return (a as any[]).map(elem => this.convertValues(elem, classs));
} else if ("object" === typeof a) {
if (asMap) {
for (const key of Object.keys(a)) {
a[key] = new classs(a[key]);
}
return a;
}
return new classs(a);
}
return a;
}
}
export class RadioListEntry {
id: string;
name: string;
label: string;
backend: string;
active: boolean;
static createFrom(source: any = {}) {
return new RadioListEntry(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.id = source["id"];
this.name = source["name"];
this.label = source["label"];
this.backend = source["backend"];
this.active = source["active"];
}
}
export class RelayAutoRule { export class RelayAutoRule {
device_id: string; device_id: string;
relay: number; relay: number;
@@ -3740,6 +3971,11 @@ export namespace main {
new_county: boolean; new_county: boolean;
county?: string; county?: string;
state?: string; state?: string;
new_state: boolean;
unconf_status?: boolean;
unconf_pfx?: boolean;
unconf_cty?: boolean;
unconf_state?: boolean;
new_pota: boolean; new_pota: boolean;
grid?: string; grid?: string;
new_grid: boolean; new_grid: boolean;
@@ -3766,6 +4002,11 @@ export namespace main {
this.new_county = source["new_county"]; this.new_county = source["new_county"];
this.county = source["county"]; this.county = source["county"];
this.state = source["state"]; this.state = source["state"];
this.new_state = source["new_state"];
this.unconf_status = source["unconf_status"];
this.unconf_pfx = source["unconf_pfx"];
this.unconf_cty = source["unconf_cty"];
this.unconf_state = source["unconf_state"];
this.new_pota = source["new_pota"]; this.new_pota = source["new_pota"];
this.grid = source["grid"]; this.grid = source["grid"];
this.new_grid = source["new_grid"]; this.new_grid = source["new_grid"];
@@ -4090,6 +4331,24 @@ export namespace main {
this.text = source["text"]; this.text = source["text"];
} }
} }
export class WatchlistSlotQuery {
call: string;
band: string;
mode: string;
contest: boolean;
static createFrom(source: any = {}) {
return new WatchlistSlotQuery(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.call = source["call"];
this.band = source["band"];
this.mode = source["mode"];
this.contest = source["contest"];
}
}
export class WebPublishStatus { export class WebPublishStatus {
last_run: string; last_run: string;
last_err: string; last_err: string;
@@ -4824,6 +5083,7 @@ export namespace qso {
band: string; band: string;
class: string; class: string;
status: string; status: string;
call?: string;
static createFrom(source: any = {}) { static createFrom(source: any = {}) {
return new BandStatus(source); return new BandStatus(source);
@@ -4834,6 +5094,7 @@ export namespace qso {
this.band = source["band"]; this.band = source["band"];
this.class = source["class"]; this.class = source["class"];
this.status = source["status"]; this.status = source["status"];
this.call = source["call"];
} }
} }
export class Bucket { export class Bucket {
@@ -5777,6 +6038,68 @@ export namespace udp {
} }
export namespace watchlist {
export class Entry {
callsign: string;
// Go type: time
lastSeen: any;
lastSeenStr: string;
// Go type: time
addedAt: any;
spotCount: number;
isContest: boolean;
notify: boolean;
isExpedition: boolean;
clubLogQSOs24h: number;
clubLogTotalQSOs: number;
clubLogHasOQRS: boolean;
clubLogLiveStream: boolean;
// Go type: time
clubLogUpdatedAt?: any;
static createFrom(source: any = {}) {
return new Entry(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.callsign = source["callsign"];
this.lastSeen = this.convertValues(source["lastSeen"], null);
this.lastSeenStr = source["lastSeenStr"];
this.addedAt = this.convertValues(source["addedAt"], null);
this.spotCount = source["spotCount"];
this.isContest = source["isContest"];
this.notify = source["notify"];
this.isExpedition = source["isExpedition"];
this.clubLogQSOs24h = source["clubLogQSOs24h"];
this.clubLogTotalQSOs = source["clubLogTotalQSOs"];
this.clubLogHasOQRS = source["clubLogHasOQRS"];
this.clubLogLiveStream = source["clubLogLiveStream"];
this.clubLogUpdatedAt = this.convertValues(source["clubLogUpdatedAt"], null);
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
if (!a) {
return a;
}
if (a.slice && a.map) {
return (a as any[]).map(elem => this.convertValues(elem, classs));
} else if ("object" === typeof a) {
if (asMap) {
for (const key of Object.keys(a)) {
a[key] = new classs(a[key]);
}
return a;
}
return new classs(a);
}
return a;
}
}
}
export namespace webpub { export namespace webpub {
export class Config { export class Config {
+18 -26
View File
@@ -264,9 +264,18 @@ func matchWildcard(pattern, v string) bool {
return re.MatchString(v) return re.MatchString(v)
} }
// InferMode guesses a spot's mode from its comment and frequency. Cluster spots // InferMode works out a spot's mode from its comment, then from the band plan.
// don't carry a mode field, so we read common tags (FT8/FT4/CW/RTTY/…) then fall //
// back to the digital watering holes and the band-plan CW/phone split. // Cluster lines carry no mode field, so this is all there is — and it feeds the
// alert rules, the FlexRadio panadapter colours and the spot the radio is told
// about. It used to end with a bare "return SSB" for anything its handful of CW
// ranges did not cover, which is how a 30 m FT8 spot at 10131.5 raised an alert
// announcing SSB while the cluster list beside it said DATA.
//
// The comment still wins when it names a mode: a spotter who wrote FT8 knows
// better than any table. Below that is the shared band plan (bandplan.go), and
// below THAT is nothing — an empty mode, which callers read as "unknown" rather
// than as a claim.
func InferMode(comment string, freqHz int64) string { func InferMode(comment string, freqHz int64) string {
c := strings.ToUpper(comment) c := strings.ToUpper(comment)
switch { switch {
@@ -280,30 +289,13 @@ func InferMode(comment string, freqHz int64) string {
return "PSK" return "PSK"
case strings.Contains(c, "JS8"): case strings.Contains(c, "JS8"):
return "JS8" return "JS8"
case strings.Contains(c, "CW"): // WPM is as good as the word CW: nothing else is reported in words per
// minute, and RBN spots carry it on every line.
case strings.Contains(c, "CW"), strings.Contains(c, "WPM"):
return "CW" return "CW"
case strings.Contains(c, "SSB") || strings.Contains(c, "USB") || strings.Contains(c, "LSB") || strings.Contains(c, "PH"): case strings.Contains(c, "SSB"), strings.Contains(c, "USB"),
strings.Contains(c, "LSB"), strings.Contains(c, "PH"):
return "SSB" return "SSB"
} }
khz := float64(freqHz) / 1000 return modeFromFrequency(freqHz)
// FT8 watering holes (…074) and FT4 (…080/…140) as a fallback.
for _, f := range []float64{1840, 3573, 7074, 10136, 14074, 18100, 21074, 24915, 28074, 50313} {
if khz >= f-1 && khz <= f+3 {
return "FT8"
}
}
// Band-plan CW segments (bottom of each band).
switch {
case khz >= 1810 && khz <= 1840,
khz >= 3500 && khz <= 3570,
khz >= 7000 && khz <= 7040,
khz >= 10100 && khz <= 10130,
khz >= 14000 && khz <= 14070,
khz >= 18068 && khz <= 18095,
khz >= 21000 && khz <= 21070,
khz >= 24890 && khz <= 24910,
khz >= 28000 && khz <= 28070:
return "CW"
}
return "SSB"
} }
+80
View File
@@ -0,0 +1,80 @@
package alerts
// The band plan behind InferMode, and why it is written out segment by segment.
//
// A cluster line carries no mode, so it has to be inferred — and OpsLog was
// inferring it TWICE, in two places, from two different tables. The frontend
// knew that 10.130-10.150 is the 30 m data segment; this side only knew a CW
// range that stopped at 10.130 and called everything after it SSB. So a spot at
// 10131.5 showed as DATA in the cluster list and raised an alert saying SSB.
// Reported with a screenshot of exactly that, on RI1FJL.
//
// The two tables are now the same table, transcribed from the frontend's
// (frontend/src/lib/spot.ts) with its segment boundaries kept intact. They stay
// two files because they are two languages, and the test next door is what
// keeps them one answer.
// modeSeg is one stretch of a band, in Hz, and what is worked there.
type modeSeg struct {
loHz, hiHz int64
mode string
}
// bandPlan is scanned IN ORDER, so a narrow watering hole listed before the
// wide segment it sits inside wins — FT8 at 14.074 before the 14.070-14.100
// data block. Order is the whole mechanism here; sorting this table by
// frequency would quietly turn every FT8 hole into "DATA".
var bandPlan = []modeSeg{
{1_800_000, 1_838_000, "CW"}, {1_838_000, 1_840_000, "FT8"}, {1_840_000, 2_000_000, "SSB"},
{3_573_000, 3_575_000, "FT8"}, {3_575_000, 3_578_000, "FT4"}, {3_500_000, 3_580_000, "CW"},
{3_580_000, 3_600_000, "DATA"}, {3_600_000, 4_000_000, "SSB"},
{5_357_000, 5_360_000, "FT8"}, {5_300_000, 5_500_000, "SSB"},
{7_074_000, 7_077_000, "FT8"}, {7_047_500, 7_048_500, "FT4"},
{7_000_000, 7_040_000, "CW"}, {7_040_000, 7_100_000, "DATA"}, {7_100_000, 7_300_000, "SSB"},
// 30 m: CW to 10.130, data above it — and nothing else. No SSB on this band.
// The FT8/FT4 watering holes come first, or a 10.136 spot with a bare
// comment reads as generic DATA — which is what every skimmerless spot of a
// DXpedition's 30 m FT8 slot did.
{10_136_000, 10_139_000, "FT8"}, {10_140_000, 10_143_000, "FT4"},
{10_100_000, 10_130_000, "CW"}, {10_130_000, 10_150_000, "DATA"},
{14_074_000, 14_077_000, "FT8"}, {14_080_000, 14_081_500, "FT4"},
{14_000_000, 14_070_000, "CW"}, {14_070_000, 14_100_000, "DATA"}, {14_100_000, 14_350_000, "SSB"},
{18_100_000, 18_103_000, "FT8"}, {18_104_000, 18_107_000, "FT4"},
{18_068_000, 18_095_000, "CW"}, {18_095_000, 18_110_000, "DATA"}, {18_110_000, 18_168_000, "SSB"},
{21_074_000, 21_077_000, "FT8"}, {21_140_000, 21_143_000, "FT4"},
{21_000_000, 21_070_000, "CW"}, {21_070_000, 21_150_000, "DATA"}, {21_150_000, 21_450_000, "SSB"},
{24_915_000, 24_918_000, "FT8"}, {24_919_000, 24_922_000, "FT4"},
{24_890_000, 24_915_000, "CW"}, {24_915_000, 24_940_000, "DATA"}, {24_940_000, 24_990_000, "SSB"},
{28_074_000, 28_077_000, "FT8"}, {28_180_000, 28_183_000, "FT4"},
{28_000_000, 28_070_000, "CW"}, {28_070_000, 28_300_000, "DATA"}, {28_300_000, 29_700_000, "SSB"},
{50_313_000, 50_316_000, "FT8"}, {50_318_000, 50_321_000, "FT4"},
{50_000_000, 50_100_000, "CW"}, {50_100_000, 50_500_000, "SSB"},
{144_174_000, 144_177_000, "FT8"},
{144_000_000, 144_150_000, "CW"}, {144_150_000, 144_500_000, "SSB"},
}
// modeFromFrequency returns what the band plan says is worked at freqHz, or ""
// where it says nothing.
//
// Empty rather than a guess: a spot outside every listed segment is on a band
// this table does not cover, and answering "SSB" for it is how a 30 m data spot
// came to raise an SSB alert.
func modeFromFrequency(freqHz int64) string {
for _, s := range bandPlan {
if freqHz >= s.loHz && freqHz < s.hiHz {
return s.mode
}
}
return ""
}
+71
View File
@@ -0,0 +1,71 @@
package alerts
import "testing"
// The spot that started it: RI1FJL on 10131.5, an FT8 station in the 30 m data
// segment. The cluster list showed DATA and the alert announced SSB, because
// this side's table stopped its CW range at 10.130 and called everything above
// it phone.
func TestInferModeDoesNotCallThirtyMetresSSB(t *testing.T) {
if got := InferMode("", 10_131_500); got != "DATA" {
t.Errorf("10131.5 kHz → %q, want DATA (there is no SSB on 30 m)", got)
}
// And the CW half of the same band still reads as CW.
if got := InferMode("", 10_110_000); got != "CW" {
t.Errorf("10110 kHz → %q, want CW", got)
}
}
// The comment beats the band plan. A spotter who names the mode knows something
// no table does — an FT8 station calling outside the usual watering hole, a CW
// operation in a data segment during a contest.
func TestInferModeTrustsTheCommentFirst(t *testing.T) {
cases := map[string]struct {
comment string
freqHz int64
want string
}{
"FT8 said outright": {"-14 dB FT8", 14_200_000, "FT8"},
"CW in a data segment": {"CW 599", 14_080_000, "CW"},
"RBN reports WPM not CW": {"18 dB 25 WPM CQ", 14_080_000, "CW"},
"phone below the split": {"SSB net", 7_010_000, "SSB"},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
if got := InferMode(c.comment, c.freqHz); got != c.want {
t.Errorf("InferMode(%q, %d) = %q, want %q", c.comment, c.freqHz, got, c.want)
}
})
}
}
// The watering holes are listed before the wide data blocks they sit inside, and
// the table is scanned in order — so sorting it by frequency would quietly turn
// every FT8 hole into "DATA". This is what would fail if somebody did.
func TestBandPlanKeepsTheWateringHolesAheadOfTheDataBlocks(t *testing.T) {
holes := map[int64]string{
3_573_500: "FT8",
7_074_500: "FT8",
7_048_000: "FT4",
14_074_500: "FT8",
14_080_500: "FT4",
21_074_500: "FT8",
28_074_500: "FT8",
50_313_500: "FT8",
}
for hz, want := range holes {
if got := modeFromFrequency(hz); got != want {
t.Errorf("%d Hz → %q, want %q", hz, got, want)
}
}
}
// Nothing is claimed for a frequency the plan does not cover. Answering "SSB"
// for whatever fell through is the exact fault this file exists to fix.
func TestModeFromFrequencyIsSilentWhenItDoesNotKnow(t *testing.T) {
for _, hz := range []int64{500_000, 6_000_000, 70_200_000, 432_100_000} {
if got := modeFromFrequency(hz); got != "" {
t.Errorf("%d Hz → %q, want \"\" (outside the plan)", hz, got)
}
}
}
+23
View File
@@ -356,6 +356,29 @@ func (m *Manager) StartTXAudio(micDev, toRadioDev string) error {
return nil return nil
} }
// StartTXAudioNetwork pipes the live microphone into a SEND function instead
// of a render device — the talk button when the radio is reached over its own
// link. No ring and no pacing goroutine: the microphone delivers in real time,
// and the sender re-frames to the rig's cadence, so the capture callback IS
// the clock.
func (m *Manager) StartTXAudioNetwork(micDev string, send func([]byte) error) error {
m.mu.Lock()
if m.txStop != nil {
m.mu.Unlock()
return fmt.Errorf("TX audio already running")
}
stop := make(chan struct{})
m.txStop = stop
m.mu.Unlock()
go func() {
if err := captureStream(micDev, stop, func(chunk []byte) { _ = send(chunk) }); err != nil {
LogSink("audio: network TX capture from %q failed: %v", DeviceName(micDev), err)
}
}()
m.notify()
return nil
}
// StopTXAudio stops the TX mic→rig passthrough. // StopTXAudio stops the TX mic→rig passthrough.
func (m *Manager) StopTXAudio() { func (m *Manager) StopTXAudio() {
m.mu.Lock() m.mu.Lock()
+1 -1
View File
@@ -64,4 +64,4 @@ func NetworkPlayerReady() bool { return networkPlayer() != nil }
// comes back with. Named, because "the device could not be opened" would send // comes back with. Named, because "the device could not be opened" would send
// an operator hunting through Windows sound settings for a device that never // an operator hunting through Windows sound settings for a device that never
// existed. // existed.
var errNoNetworkRadio = errors.New("no radio is connected to take the audio — check the CAT link (the radio output only works with a TCI radio)") var errNoNetworkRadio = errors.New("no radio is connected to take the audio — check the CAT link (a TCI radio, or a network Icom with RX audio enabled)")
+17 -4
View File
@@ -572,9 +572,13 @@ type IcomTXState struct {
// Transmit + live status (polled). // Transmit + live status (polled).
Transmitting bool `json:"transmitting"` Transmitting bool `json:"transmitting"`
Split bool `json:"split"` Split bool `json:"split"`
SMeter int `json:"s_meter"` // 0-100 (raw 0-255; S9≈120) // SubHz is the unselected VFO / sub receiver's frequency — shown on the
PowerMeter int `json:"power_meter"` // 0-100 (TX Po) // console's SUB display whether or not split is on: a dual-receiver rig
SWRMeter int `json:"swr_meter"` // 0-100 (TX SWR) // (IC-7610/7760) has a second dial worth seeing at all times.
SubHz int64 `json:"sub_hz"`
SMeter int `json:"s_meter"` // 0-100 (raw 0-255; S9≈120)
PowerMeter int `json:"power_meter"` // 0-100 (TX Po)
SWRMeter int `json:"swr_meter"` // 0-100 (TX SWR)
// RIT / ΔTX (XIT). // RIT / ΔTX (XIT).
RITHz int `json:"rit_hz"` // RIT/XIT offset, signed Hz RITHz int `json:"rit_hz"` // RIT/XIT offset, signed Hz
RITOn bool `json:"rit_on"` RITOn bool `json:"rit_on"`
@@ -598,7 +602,8 @@ type IcomTXState struct {
Att int `json:"att"` // dB attenuation, 0=off Att int `json:"att"` // dB attenuation, 0=off
Filter int `json:"filter"` // 1 | 2 | 3 (FIL1/2/3) Filter int `json:"filter"` // 1 | 2 | 3 (FIL1/2/3)
// Antenna (IC-7610 = ANT1/ANT2). // Antenna (IC-7610 = ANT1/ANT2).
Antenna int `json:"antenna"` // 1 | 2 (0 = unknown) Antenna int `json:"antenna"` // 1 | 2 (0 = unknown)
ATUOn bool `json:"atu_on"` // internal tuner engaged
// Filter fine controls: Twin PBT + manual notch (0-100, 50 = centre). // Filter fine controls: Twin PBT + manual notch (0-100, 50 = centre).
PBTInner int `json:"pbt_inner"` PBTInner int `json:"pbt_inner"`
PBTOuter int `json:"pbt_outer"` PBTOuter int `json:"pbt_outer"`
@@ -636,6 +641,8 @@ type IcomController interface {
SetRFPower(int) error SetRFPower(int) error
SetMicGain(int) error SetMicGain(int) error
SetIcomSplit(bool) error SetIcomSplit(bool) error
SetIcomSplitOffset(bool, int64) error
SetATU(bool) error
TuneATU() error TuneATU() error
SetScope(bool) error // enable/disable the spectrum-scope waveform stream SetScope(bool) error // enable/disable the spectrum-scope waveform stream
SetScopeMode(bool) error // true = fixed span, false = center-on-VFO SetScopeMode(bool) error // true = fixed span, false = center-on-VFO
@@ -674,6 +681,12 @@ type ScopeSweep struct {
LowHz int64 `json:"low_hz"` // left edge frequency (0 when unknown) LowHz int64 `json:"low_hz"` // left edge frequency (0 when unknown)
HighHz int64 `json:"high_hz"` // right edge frequency (0 when unknown) HighHz int64 `json:"high_hz"` // right edge frequency (0 when unknown)
Fixed bool `json:"fixed"` // true = fixed-span mode, false = center-on-VFO Fixed bool `json:"fixed"` // true = fixed-span mode, false = center-on-VFO
// Unsupported: this radio refuses the waveform-output command, so there will
// never be a sweep. The IC-7851 does — its last firmware is from 2016, older
// than the CI-V waveform stream — while still answering the scope's other
// commands. Reported so the panadapter can say so instead of showing a black
// rectangle that looks like a bug in OpsLog.
Unsupported bool `json:"unsupported"`
} }
// IcomState returns the current Icom DSP state, or (zero, false) when the active // IcomState returns the current Icom DSP state, or (zero, false) when the active
+7
View File
@@ -36,6 +36,7 @@ const (
CmdVfoFreq = 0x25 // read a specific VFO's freq (sub 0x00 selected, 0x01 unselected) CmdVfoFreq = 0x25 // read a specific VFO's freq (sub 0x00 selected, 0x01 unselected)
CmdPTT = 0x1C // sub 0x00 = PTT CmdPTT = 0x1C // sub 0x00 = PTT
CmdExtra = 0x1A // sub 0x06 = data mode on modern Icoms CmdExtra = 0x1A // sub 0x06 = data mode on modern Icoms
CmdModeDataFil = 0x26 // sub 0x00 = selected VFO: mode + data flag + filter in one frame
CmdReadID = 0x19 // sub 0x00 = rig's own CI-V address (identifies model) CmdReadID = 0x19 // sub 0x00 = rig's own CI-V address (identifies model)
CmdPower = 0x18 // power on/off (sub 0x01 = on, 0x00 = off; on needs an FE wake preamble) CmdPower = 0x18 // power on/off (sub 0x01 = on, 0x00 = off; on needs an FE wake preamble)
@@ -130,6 +131,8 @@ const (
ModeFM = 0x05 ModeFM = 0x05
ModeCWR = 0x07 ModeCWR = 0x07
ModeRTTYR = 0x08 ModeRTTYR = 0x08
ModePSK = 0x12 // native PSK (IC-7610/7760/7851 class; older rigs NAK it)
ModePSKR = 0x13
) )
// Frame builds a complete CI-V frame (preamble … end) for payload, which is the // Frame builds a complete CI-V frame (preamble … end) for payload, which is the
@@ -305,6 +308,8 @@ func ModeToADIF(m byte, data bool) string {
return "CW" return "CW"
case ModeRTTY, ModeRTTYR: case ModeRTTY, ModeRTTYR:
return "RTTY" return "RTTY"
case ModePSK, ModePSKR:
return "PSK31"
case ModeAM: case ModeAM:
return "AM" return "AM"
case ModeFM: case ModeFM:
@@ -357,6 +362,8 @@ func ModelName(addr byte) string {
return "IC-9700" return "IC-9700"
case 0xA4: case 0xA4:
return "IC-705" return "IC-705"
case 0xB2:
return "IC-7760"
case 0xB6: case 0xB6:
return "IC-7300MKII" return "IC-7300MKII"
} }
+1 -1
View File
@@ -59,7 +59,7 @@ type Flex struct {
meterRawLogged bool // log the first raw meter-definition status once meterRawLogged bool // log the first raw meter-definition status once
txRawLogged bool // log the first raw transmit status once (field-name audit) txRawLogged bool // log the first raw transmit status once (field-name audit)
spotsEnabled bool // push cluster spots + manage the panadapter overlay spotsEnabled bool // push cluster spots + manage the panadapter overlay
// foreignSpotSeen counts what probeForeignSpot has already reported, so a // foreignSpotSeen counts what probeForeignSpot has already reported, so a
// skimmer posting all evening cannot turn the log into its own transcript. // skimmer posting all evening cannot turn the log into its own transcript.
foreignSpotSeen int foreignSpotSeen int
+132 -11
View File
@@ -22,17 +22,20 @@ package cat
// audio stream is opt-in and entirely separate from control/CI-V. // audio stream is opt-in and entirely separate from control/CI-V.
import ( import (
"fmt"
"net" "net"
"sync" "sync"
"sync/atomic" "sync/atomic"
"time" "time"
) )
// icaAudioOffset is where the PCM payload begins inside an audio data packet // icaAudioOffset is where the PCM payload begins inside an audio data packet.
// (wfview audio_packet: 16-byte common header + ident@0x10 + datalen@0x12 + // CONFIRMED on a real IC-7760 (2026-08-29): 16-byte common header, ident@0x10,
// sendseq@0x14 → audio@0x16). Isolated as a const so a capture-confirmed change // send seq (BE) @0x12, payload length (BE uint32) @0x14 — 0x500 observed on
// is a one-line edit. // every packet — and the PCM starts at 0x18. The 0x16 first guessed from
const icaAudioOffset = 0x16 // wfview's struct swallowed two header bytes into the audio, one broken sample
// per packet: a 50 Hz click track under everything.
const icaAudioOffset = 0x18
// icaDumpFirst is how many initial audio packets to hex-dump to the debug log for // icaDumpFirst is how many initial audio packets to hex-dump to the debug log for
// offset verification. After the layout is confirmed on a real rig this can go to // offset verification. After the layout is confirmed on a real rig this can go to
@@ -54,8 +57,16 @@ type icomAudio struct {
rxLastSeq uint16 rxLastSeq uint16
rxMissing map[uint16]int rxMissing map[uint16]int
dumped int // packets hex-dumped so far (≤ icaDumpFirst) dumped int // packets hex-dumped so far (≤ icaDumpFirst)
lastRx atomic.Int64 // UnixNano of last packet (liveness) pingSeq uint16 // client-ping counter — the rig wants OUR pings too (see icnPing)
started time.Time
// Live-TX state — see SendTXChunk.
txMu sync.Mutex
txRem []byte
txOuter uint16
txSend uint16
lastRx atomic.Int64 // UnixNano of last packet (liveness)
done chan struct{} done chan struct{}
closeOnce sync.Once closeOnce sync.Once
@@ -100,6 +111,7 @@ func dialIcomAudio(host string, sink func([]byte), cancel <-chan struct{}) (*ico
_ = conn.SetReadBuffer(1 << 20) _ = conn.SetReadBuffer(1 << 20)
a := &icomAudio{ a := &icomAudio{
conn: conn, aID: aID, aRemote: aRemote, conn: conn, aID: aID, aRemote: aRemote,
started: time.Now(),
sink: sink, sink: sink,
rxMissing: make(map[uint16]int), rxMissing: make(map[uint16]int),
done: make(chan struct{}), done: make(chan struct{}),
@@ -115,6 +127,7 @@ func dialIcomAudio(host string, sink func([]byte), cancel <-chan struct{}) (*ico
func (a *icomAudio) audioPump() { func (a *icomAudio) audioPump() {
buf := make([]byte, 8192) buf := make([]byte, 8192)
lastIdle := time.Now() lastIdle := time.Now()
lastPing := time.Now()
lastReq := time.Now() lastReq := time.Now()
for { for {
select { select {
@@ -132,12 +145,19 @@ func (a *icomAudio) audioPump() {
case typ == 0x05: // rig-initiated disconnect case typ == 0x05: // rig-initiated disconnect
debugLog.Printf("icom audio: rig sent DISCONNECT — audio stream dropped by the rig") debugLog.Printf("icom audio: rig sent DISCONNECT — audio stream dropped by the rig")
case typ == 0x00 && k > icaAudioOffset: // audio data packet case typ == 0x00 && k > icaAudioOffset: // audio data packet
a.trackRxSeq(icnLE.Uint16(buf[6:])) fresh := a.trackRxSeq(icnLE.Uint16(buf[6:]))
if a.dumped < icaDumpFirst { if a.dumped < icaDumpFirst {
a.dumped++ a.dumped++
debugLog.Printf("icom audio raw #%d: len=%d head=% X", a.dumped, k, buf[:min(icaAudioOffset+8, k)]) debugLog.Printf("icom audio raw #%d: len=%d head=% X", a.dumped, k, buf[:min(icaAudioOffset+8, k)])
} }
if a.sink != nil { // Only a packet that ADVANCES the sequence reaches the sink. A
// duplicate or a late retransmit used to be delivered as if it
// were the next 20 ms of audio: the monitor's capped ring threw
// the surplus away (the speakers stayed clean), but the recorder
// keeps every sample it is given — the file grew longer than the
// QSO and played back slowed and stuttering, each lost-then-
// resent packet heard twice.
if fresh && a.sink != nil {
payload := append([]byte(nil), buf[icaAudioOffset:k]...) payload := append([]byte(nil), buf[icaAudioOffset:k]...)
a.sink(payload) a.sink(payload)
} }
@@ -147,6 +167,11 @@ func (a *icomAudio) audioPump() {
_, _ = a.conn.Write(icnCtrl(0x00, 0, a.aID, a.aRemote)) _, _ = a.conn.Write(icnCtrl(0x00, 0, a.aID, a.aRemote))
lastIdle = time.Now() lastIdle = time.Now()
} }
if time.Since(lastPing) > 500*time.Millisecond {
a.pingSeq++
_, _ = a.conn.Write(icnPing(a.pingSeq, a.aID, a.aRemote, uint32(time.Since(a.started).Milliseconds())))
lastPing = time.Now()
}
if time.Since(lastReq) > 100*time.Millisecond { if time.Since(lastReq) > 100*time.Millisecond {
a.sendRetransmitReq() a.sendRetransmitReq()
lastReq = time.Now() lastReq = time.Now()
@@ -157,26 +182,36 @@ func (a *icomAudio) audioPump() {
// trackRxSeq / sendRetransmitReq mirror icomNet's receive-side retransmit exactly // trackRxSeq / sendRetransmitReq mirror icomNet's receive-side retransmit exactly
// (audio is as loss-sensitive as the scope stream). Duplicated deliberately so // (audio is as loss-sensitive as the scope stream). Duplicated deliberately so
// the audio stream owns its own seq state with no shared locking. // the audio stream owns its own seq state with no shared locking.
func (a *icomAudio) trackRxSeq(seq uint16) { //
// The return value says whether this packet moves the stream FORWARD — the
// only kind the sink may hear. A duplicate is the same 20 ms again; a late
// retransmit would play old audio in the middle of new. Both are accounted
// for here and dropped by the caller.
func (a *icomAudio) trackRxSeq(seq uint16) bool {
if !a.rxHaveSeq { if !a.rxHaveSeq {
a.rxHaveSeq = true a.rxHaveSeq = true
a.rxLastSeq = seq a.rxLastSeq = seq
return return true
} }
switch d := int16(seq - a.rxLastSeq); { switch d := int16(seq - a.rxLastSeq); {
case d == 0: case d == 0:
return false
case d < 0: case d < 0:
delete(a.rxMissing, seq) delete(a.rxMissing, seq)
return false
case d == 1: case d == 1:
a.rxLastSeq = seq a.rxLastSeq = seq
return true
case int(d) <= icnMaxMissing: case int(d) <= icnMaxMissing:
for f := a.rxLastSeq + 1; f != seq; f++ { for f := a.rxLastSeq + 1; f != seq; f++ {
a.rxMissing[f] = 0 a.rxMissing[f] = 0
} }
a.rxLastSeq = seq a.rxLastSeq = seq
return true
default: default:
a.rxMissing = make(map[uint16]int) a.rxMissing = make(map[uint16]int)
a.rxLastSeq = seq a.rxLastSeq = seq
return true
} }
} }
@@ -217,3 +252,89 @@ func (a *icomAudio) sendRetransmitReq() {
_, _ = a.conn.Write(b) _, _ = a.conn.Write(b)
} }
} }
// PlayTX sends one already-decoded message out over the audio session, paced
// at the stream's own 20 ms / 320-sample cadence, and returns when the last
// packet has gone or stop is closed.
//
// The frame mirrors what the rig itself sends on this socket byte for byte —
// ident 0x81 0x01 (LPCM mono 16-bit), a big-endian send sequence at 0x12, the
// payload length at 0x14, PCM from 0x18 — with the IDs swapped for direction.
// PTT is the caller's business, exactly as on the TCI and sound-card paths.
func (a *icomAudio) PlayTX(pcm []byte, rate, ch, bits int, stop <-chan struct{}) error {
mono := decodeToMono(pcm, ch, bits)
if len(mono) == 0 {
return fmt.Errorf("the message is empty")
}
if rate > 0 && rate != 16000 {
mono = resampleLinear(mono, rate, 16000)
}
// Through the SAME framer and counters as the live microphone. Each of the
// two used to number its own packets from 1, and a voice-keyer message sent
// after a talk session re-used sequence numbers the rig had already seen —
// it keyed for the full length of the message and modulated none of it.
const frame = 320 // samples per packet: 20 ms at 16 kHz, the rig's own cadence
tick := time.NewTicker(20 * time.Millisecond)
defer tick.Stop()
buf := make([]byte, frame*2)
for pos := 0; pos < len(mono); pos += frame {
select {
case <-stop:
return nil
case <-a.done:
return fmt.Errorf("the audio stream closed mid-message")
case <-tick.C:
}
for i := 0; i < frame; i++ {
var v float32
if pos+i < len(mono) {
v = mono[pos+i] * 32767
}
if v > 32767 {
v = 32767
} else if v < -32768 {
v = -32768
}
icnLE.PutUint16(buf[i*2:], uint16(int16(v)))
}
if err := a.SendTXChunk(buf); err != nil {
return err
}
}
return nil
}
// Live TX — the microphone, not a recorded message. Chunks arrive at the
// microphone's own real-time pace (16 kHz mono 16-bit, whatever length the
// capture delivers) and are re-framed into the rig's 320-sample packets; the
// remainder waits for the next chunk. Counters and remainder live on the
// stream so a talk session survives across calls.
func (a *icomAudio) SendTXChunk(pcm []byte) error {
a.txMu.Lock()
defer a.txMu.Unlock()
a.txRem = append(a.txRem, pcm...)
const frameBytes = 640
for len(a.txRem) >= frameBytes {
select {
case <-a.done:
return fmt.Errorf("the audio stream closed")
default:
}
pkt := make([]byte, 0x18+frameBytes)
icnLE.PutUint32(pkt[0:], uint32(len(pkt)))
a.txOuter++
icnLE.PutUint16(pkt[6:], a.txOuter)
icnLE.PutUint32(pkt[8:], a.aID)
icnLE.PutUint32(pkt[12:], a.aRemote)
pkt[0x10], pkt[0x11] = 0x81, 0x01
icnBE.PutUint16(pkt[0x12:], a.txSend)
a.txSend++
icnBE.PutUint32(pkt[0x14:], frameBytes)
copy(pkt[0x18:], a.txRem[:frameBytes])
a.txRem = a.txRem[frameBytes:]
if _, err := a.conn.Write(pkt); err != nil {
return fmt.Errorf("sending mic audio to the rig: %w", err)
}
}
return nil
}
+212 -9
View File
@@ -56,6 +56,15 @@ func NewIcomNet(host, user, pass string, civAddr int, digitalDefault string, aud
model: "Icom", model: "Icom",
scopeFixed: true, scopeFixed: true,
} }
// lastNetConnect is when the previous session came up, and it drives a
// deliberate pause: on a real IC-7760 a session sometimes goes deaf on CI-V
// while the rig still holds it half-open, and a session dialled straight
// back in answers for a second and is then strangled when the rig finally
// purges the old one — reconnect, die, reconnect, die, twenty seconds a
// lap and no audio the whole time. When the last session died YOUNG, wait
// out the rig's cleanup before dialling again; a session that lived long
// reconnects immediately, as ever.
var lastNetConnect time.Time
b.open = func() (civTransport, error) { b.open = func() (civTransport, error) {
if strings.TrimSpace(host) == "" { if strings.TrimSpace(host) == "" {
return nil, fmt.Errorf("no rig host configured") return nil, fmt.Errorf("no rig host configured")
@@ -63,7 +72,20 @@ func NewIcomNet(host, user, pass string, civAddr int, digitalDefault string, aud
b.dialMu.Lock() b.dialMu.Lock()
cancel := b.dialCancel cancel := b.dialCancel
b.dialMu.Unlock() b.dialMu.Unlock()
return dialIcomNet(host, user, pass, "OpsLog", b.rigAddr, cancel, audioSink) if !lastNetConnect.IsZero() && time.Since(lastNetConnect) < 90*time.Second {
debugLog.Printf("icom net: the last session died young — pausing 20 s before redialling so the rig can purge it first")
for i := 0; i < 40; i++ {
if icnCanceled(cancel) {
return nil, errDialCanceled
}
time.Sleep(500 * time.Millisecond)
}
}
tr, err := dialIcomNet(host, user, pass, "OpsLog", b.rigAddr, cancel, audioSink)
if err == nil {
lastNetConnect = time.Now()
}
return tr, err
} }
return b return b
} }
@@ -97,6 +119,19 @@ type icomNet struct {
// CAT goroutine) and during dial — never by the pump — so no lock is needed. // CAT goroutine) and during dial — never by the pump — so no lock is needed.
vTracked uint16 vTracked uint16
vCivSeq uint16 vCivSeq uint16
seqMu sync.Mutex // guards vTracked/vCivSeq: the command loop AND the pump's quiet-recovery both send
// Client-ping sequence counters, one per stream, and the connection's epoch
// for the ping timestamps. Owned by their pump goroutines — no locking.
civPingSeq uint16
ctrlPingSeq uint16
started time.Time
// txCiv counts CI-V command packets sent, and txAtData snapshots it at the
// last received CI-V data. Their difference during a silence answers the
// question the reconnects cannot: were we still ASKING when the answers
// stopped? Zero writes-since-data would mean the fault is our own poll
// loop, not the rig — and RS-BA1 showing no such dropouts points that way.
txCiv atomic.Uint32
txAtData atomic.Uint32
rx chan []byte // CI-V byte chunks from civPump → Read (control replies) rx chan []byte // CI-V byte chunks from civPump → Read (control replies)
scopeRx chan []byte // scope (0x27) frames, kept off rx so the panadapter scopeRx chan []byte // scope (0x27) frames, kept off rx so the panadapter
@@ -227,10 +262,13 @@ func (n *icomNet) Write(p []byte) (int, error) {
if icnTrace { if icnTrace {
debugLog.Printf("icom net TX: % X", p) debugLog.Printf("icom net TX: % X", p)
} }
seq := n.vTracked n.seqMu.Lock()
pkt := icnCivData(seq, n.vID, n.vRemote, n.vCivSeq, p) seq, civSeq := n.vTracked, n.vCivSeq
n.vTracked++ n.vTracked++
n.vCivSeq++ n.vCivSeq++
n.seqMu.Unlock()
n.txCiv.Add(1)
pkt := icnCivData(seq, n.vID, n.vRemote, civSeq, p)
n.sentMu.Lock() n.sentMu.Lock()
n.sentBuf[seq] = pkt n.sentBuf[seq] = pkt
delete(n.sentBuf, seq-1024) // keep the buffer bounded (~last 1024 packets) so delete(n.sentBuf, seq-1024) // keep the buffer bounded (~last 1024 packets) so
@@ -281,6 +319,7 @@ func (n *icomNet) Close() error {
func (n *icomNet) ctrlPump() { func (n *icomNet) ctrlPump() {
buf := make([]byte, 4096) buf := make([]byte, 4096)
lastIdle := time.Now() lastIdle := time.Now()
lastCtrlPing := time.Now()
lastToken := time.Now() // token was just granted during dial lastToken := time.Now() // token was just granted during dial
for { for {
select { select {
@@ -321,6 +360,11 @@ func (n *icomNet) ctrlPump() {
} }
// Renew well inside the rig's ~2-min token timeout. 30 s (was 45) leaves room // Renew well inside the rig's ~2-min token timeout. 30 s (was 45) leaves room
// for one lost renewal + its retransmit before the token would lapse. // for one lost renewal + its retransmit before the token would lapse.
if time.Since(lastCtrlPing) > 500*time.Millisecond {
n.ctrlPingSeq++
_, _ = n.ctrl.Write(icnPing(n.ctrlPingSeq, n.cID, n.cRemote, uint32(time.Since(n.started).Milliseconds())))
lastCtrlPing = time.Now()
}
if time.Since(lastToken) > 30*time.Second { if time.Since(lastToken) > 30*time.Second {
n.renewToken() n.renewToken()
lastToken = time.Now() lastToken = time.Now()
@@ -359,6 +403,25 @@ func (n *icomNet) civPump() {
buf := make([]byte, 8192) buf := make([]byte, 8192)
lastIdle := time.Now() lastIdle := time.Now()
lastReq := time.Now() lastReq := time.Now()
// Diagnosis for the recurring 2-3-minute silence a real IC-7760 shows on
// this stream while the control link stays alive: when the stream has been
// quiet for 10 s, say so ONCE, with the last read error — a socket error
// and a rig that stopped talking are different repairs, and the 30 s
// watchdog that follows cannot tell them apart from where it sits.
debugLog.Printf("icom net: client pings armed on the CI-V stream (every 500 ms)")
lastPkt := time.Now()
lastPing := time.Now()
lastData := time.Now() // CI-V payload packets (replies + transceive)
lastScope := time.Time{} // scope frames within those
var lastErr error
quietSaid := false
gaveUp := false
// sawData: this session has heard at least one CI-V payload. A radio in
// STANDBY is silent on CI-V by design — only the transport chats — and the
// quiet-recovery below must not treat that as a fault: it was tearing the
// session down every 15 s, and with it the console and its ON button, so a
// radio that was off when OpsLog started could never be turned on at all.
sawData := false
for { for {
select { select {
case <-n.done: case <-n.done:
@@ -366,7 +429,14 @@ func (n *icomNet) civPump() {
default: default:
} }
_ = n.civ.SetReadDeadline(time.Now().Add(100 * time.Millisecond)) _ = n.civ.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
if k, err := n.civ.Read(buf); err == nil && k >= 16 { k, err := n.civ.Read(buf)
if err != nil {
if e, ok := err.(net.Error); !ok || !e.Timeout() {
lastErr = err // a REAL socket error, not the read deadline
}
}
if err == nil && k >= 16 {
lastPkt = time.Now()
n.markRx() n.markRx()
switch typ := icnLE.Uint16(buf[4:]); { switch typ := icnLE.Uint16(buf[4:]); {
case typ == 0x07: // ping case typ == 0x07: // ping
@@ -379,6 +449,13 @@ func (n *icomNet) civPump() {
n.dead.Store(true) // make Alive() fail now → prompt clean reconnect n.dead.Store(true) // make Alive() fail now → prompt clean reconnect
debugLog.Printf("icom net: rig sent DISCONNECT on CI-V stream — session dropped by the rig") debugLog.Printf("icom net: rig sent DISCONNECT on CI-V stream — session dropped by the rig")
case typ == 0x00 && k > 0x15 && buf[0x10] == 0xc1: // CI-V data case typ == 0x00 && k > 0x15 && buf[0x10] == 0xc1: // CI-V data
if quietSaid {
debugLog.Printf("icom net: CI-V replies are back after %s", time.Since(lastData).Round(time.Second))
quietSaid, gaveUp = false, false
}
sawData = true
lastData = time.Now()
n.txAtData.Store(n.txCiv.Load())
n.trackRxSeq(icnLE.Uint16(buf[6:])) // note gaps for retransmit n.trackRxSeq(icnLE.Uint16(buf[6:])) // note gaps for retransmit
civBytes := buf[0x15:k] civBytes := buf[0x15:k]
cp := append([]byte(nil), civBytes...) cp := append([]byte(nil), civBytes...)
@@ -388,6 +465,7 @@ func (n *icomNet) civPump() {
// feeder in IcomSerial picks them up. Everything else is a control // feeder in IcomSerial picks them up. Everything else is a control
// reply → rx → Read. // reply → rx → Read.
if len(civBytes) >= 5 && civBytes[4] == 0x27 { if len(civBytes) >= 5 && civBytes[4] == 0x27 {
lastScope = time.Now()
icnEnqueueDrop(n.scopeRx, cp) icnEnqueueDrop(n.scopeRx, cp)
break break
} }
@@ -410,14 +488,69 @@ func (n *icomNet) civPump() {
} }
} }
} }
if !quietSaid && sawData && time.Since(lastData) > 10*time.Second {
quietSaid = true
scopeAge := "never"
if !lastScope.IsZero() {
scopeAge = time.Since(lastScope).Round(time.Second).String()
}
debugLog.Printf("icom net: no CI-V DATA for 10 s (transport last heard %s ago; last scope frame %s ago; last socket error: %v; missing-seq backlog: %d; CI-V commands SENT since the last answer: %d)",
time.Since(lastPkt).Round(time.Second), scopeAge, lastErr, len(n.rxMissing), n.txCiv.Load()-n.txAtData.Load())
// And try the gentle repair before the 30 s watchdog tears the whole
// session down: if the rig quietly closed the CI-V data flow (the
// transport is still chatting, so the session itself stands), saying
// "open" again on the same stream is all it should take. Harmless
// when the cause is elsewhere — the watchdog still fires at 30 s.
n.seqMu.Lock()
seq, civSeq := n.vTracked, n.vCivSeq
n.vTracked++
n.vCivSeq++
n.seqMu.Unlock()
ocPkt := icnOpenClose(seq, n.vID, n.vRemote, civSeq, 0x04)
n.sentMu.Lock()
n.sentBuf[seq] = ocPkt
n.sentMu.Unlock()
_, _ = n.civ.Write(ocPkt)
debugLog.Printf("icom net: re-sent the CI-V open on the existing stream")
}
// The reopen was given five seconds. On a real IC-7760 it never works —
// the rig ignores it and only a fresh session brings CI-V back — so
// rather than sit out the 30 s watchdog, fail the link NOW and let the
// manager rebuild it: the outage drops from ~35 s to ~15.
if quietSaid && !gaveUp && time.Since(lastData) > 15*time.Second {
gaveUp = true
n.dead.Store(true)
debugLog.Printf("icom net: the reopen did not bring CI-V back — forcing a fresh session")
}
if time.Since(lastIdle) > 150*time.Millisecond { if time.Since(lastIdle) > 150*time.Millisecond {
_, _ = n.civ.Write(icnCtrl(0x00, 0, n.vID, n.vRemote)) // Idles carry a REAL sequence number, drawn from the same counter as
// the data packets, and sit in the retransmit buffer like them —
// which is how RS-BA1 and wfview number theirs. Ours used seq 0 on
// every idle, seven a second, interleaved with properly-numbered
// data; a rig that follows the sequence tolerates that for a minute
// or so and then stops serving CI-V data on the stream — which is
// the shape of every dropout this loaner IC-7760 has shown, with
// the scope and the TX path both since eliminated.
n.seqMu.Lock()
iseq := n.vTracked
n.vTracked++
n.seqMu.Unlock()
ipkt := icnCtrl(0x00, iseq, n.vID, n.vRemote)
n.sentMu.Lock()
n.sentBuf[iseq] = ipkt
n.sentMu.Unlock()
_, _ = n.civ.Write(ipkt)
lastIdle = time.Now() lastIdle = time.Now()
} }
if time.Since(lastReq) > 100*time.Millisecond { if time.Since(lastReq) > 100*time.Millisecond {
n.sendRetransmitReq() n.sendRetransmitReq()
lastReq = time.Now() lastReq = time.Now()
} }
if time.Since(lastPing) > 500*time.Millisecond {
n.civPingSeq++
_, _ = n.civ.Write(icnPing(n.civPingSeq, n.vID, n.vRemote, uint32(time.Since(n.started).Milliseconds())))
lastPing = time.Now()
}
} }
} }
@@ -661,6 +794,7 @@ func dialIcomNet(host, user, pass, compName string, rigAddr byte, cancel <-chan
cTracked: cTracked, cAuthSeq: cInner, cTracked: cTracked, cAuthSeq: cInner,
cToken: token, cTokReq: tokReq, cToken: token, cTokReq: tokReq,
cSentBuf: make(map[uint16][]byte), cSentBuf: make(map[uint16][]byte),
started: time.Now(),
} }
n.markRx() // the successful handshake counts as initial rig activity n.markRx() // the successful handshake counts as initial rig activity
// openClose(open) starts the CI-V data flow. We intentionally DO NOT power the // openClose(open) starts the CI-V data flow. We intentionally DO NOT power the
@@ -712,6 +846,11 @@ func icnHandshake(c *net.UDPConn, myID uint32, cancel <-chan struct{}) (uint32,
} }
typ := icnLE.Uint16(p[4:]) typ := icnLE.Uint16(p[4:])
sentid := icnLE.Uint32(p[8:]) sentid := icnLE.Uint32(p[8:])
// Every packet the rig sends during the handshake, verbatim. A radio that
// answers SOMETHING unrecognised (a newer model, a different firmware) and
// a radio that answers nothing are different faults, and a silent timeout
// hides which one this is.
icnHandshakeProbe(p)
switch typ { switch typ {
case 0x04: // iAmHere case 0x04: // iAmHere
remoteID = sentid remoteID = sentid
@@ -843,11 +982,20 @@ func icnConnInfo(seq, innerSeq, tokReq uint16, sentid, rcvdid, token uint32, use
copy(b[0x40:0x60], []byte("IC-7610")) copy(b[0x40:0x60], []byte("IC-7610"))
copy(b[0x60:0x70], icnPasscode(user)) copy(b[0x60:0x70], icnPasscode(user))
b[0x70] = rxEnable // rxenable: 1 opens the 50003 RX audio stream, 0 = CI-V only b[0x70] = rxEnable // rxenable: 1 opens the 50003 RX audio stream, 0 = CI-V only
b[0x71] = 0x00 // txenable (Phase 5) // TX rides the same audio session: whenever the operator wants RX audio the
b[0x72] = 0x10 // rxcodec // TX side is opened with it, so the voice keyer can play to the radio with
b[0x73] = 0x04 // txcodec // no cable. Costs nothing when unused — no packets flow until a message is
// actually played.
b[0x71] = rxEnable // txenable
// rxcodec 0x04 = LPCM, ONE channel, 16-BIT — settled by experiment on a
// real IC-7760, one wrong guess at a time: 0x10 produced 1280-byte payloads
// of interleaved 16-bit stereo, 0x02 produced 320-byte payloads of 8-bit
// mono (samples hugging 0x80). 0x04 sits between them in the codec table
// (as in wfview): 16-bit mono, the format the 16 kHz playback path plays.
b[0x72] = 0x04 // rxcodec
b[0x73] = 0x04 // txcodec
icnBE.PutUint32(b[0x74:], 16000) icnBE.PutUint32(b[0x74:], 16000)
icnBE.PutUint32(b[0x78:], 8000) icnBE.PutUint32(b[0x78:], 16000) // TX sample rate — the same 16 kHz everything else here runs at
icnBE.PutUint32(b[0x7c:], uint32(civPort)) icnBE.PutUint32(b[0x7c:], uint32(civPort))
icnBE.PutUint32(b[0x80:], uint32(audioPort)) icnBE.PutUint32(b[0x80:], uint32(audioPort))
icnBE.PutUint32(b[0x84:], 100) icnBE.PutUint32(b[0x84:], 100)
@@ -855,6 +1003,26 @@ func icnConnInfo(seq, innerSeq, tokReq uint16, sentid, rcvdid, token uint32, use
return b return b
} }
// PlayTXAudio plays one voice-keyer message through the 50003 audio session.
// On the transport because the transport owns the session; the IcomSerial
// controller forwards here after a type assertion, exactly as the TCI path
// reaches its radio.
func (n *icomNet) PlayTXAudio(pcm []byte, rate, ch, bits int, stop <-chan struct{}) error {
if n.audio == nil {
return fmt.Errorf("the radio's audio stream is not open — enable RX audio in Settings → CAT first")
}
return n.audio.PlayTX(pcm, rate, ch, bits, stop)
}
// TXAudioSender returns a function that streams live microphone chunks to the
// rig — the talk button's road, where PlayTXAudio is the voice keyer's.
func (n *icomNet) TXAudioSender() (func([]byte) error, error) {
if n.audio == nil {
return nil, fmt.Errorf("the radio's audio stream is not open — enable RX audio in Settings → CAT first")
}
return n.audio.SendTXChunk, nil
}
func icnOpenClose(seq uint16, sentid, rcvdid uint32, civSeq uint16, magic byte) []byte { func icnOpenClose(seq uint16, sentid, rcvdid uint32, civSeq uint16, magic byte) []byte {
b := make([]byte, 0x16) b := make([]byte, 0x16)
icnLE.PutUint32(b[0:], 0x16) icnLE.PutUint32(b[0:], 0x16)
@@ -903,3 +1071,38 @@ func icnPasscode(s string) []byte {
} }
return out return out
} }
// icnHandshakeProbe logs the first packets seen during a control handshake —
// capped hard, because a working handshake would log for ever.
var icnProbeCount int
func icnHandshakeProbe(p []byte) {
if icnProbeCount >= 12 {
return
}
icnProbeCount++
n := len(p)
if n > 32 {
n = 32
}
debugLog.Printf("icom net: handshake rx %d bytes: % X", len(p), p[:n])
}
// icnPing builds a CLIENT ping request (wfview's ping_packet: 0x15 bytes,
// type 0x07, reply=0, a monotonic time at 0x11). The rig answers each one —
// and, decisively, treats them as the client's sign of life: wfview sends one
// every 500 ms on every stream, and OpsLog, which only ever REPLIED to the
// rig's pings, watched the IC-7760 stop serving CI-V data about a minute into
// every session. Same socket answered, same transport alive: the rig had
// simply concluded nobody was listening.
func icnPing(seq uint16, sentid, rcvdid uint32, ms uint32) []byte {
b := make([]byte, 0x15)
icnLE.PutUint32(b[0:], 0x15)
icnLE.PutUint16(b[4:], 0x07)
icnLE.PutUint16(b[6:], seq)
icnLE.PutUint32(b[8:], sentid)
icnLE.PutUint32(b[12:], rcvdid)
b[0x10] = 0x00
icnLE.PutUint32(b[0x11:], ms)
return b
}
+247 -38
View File
@@ -93,15 +93,18 @@ type IcomSerial struct {
// leading main/sub selector byte (IC-7610/9700). scopeAmp is the latest // leading main/sub selector byte (IC-7610/9700). scopeAmp is the latest
// reassembled sweep; scopeMu guards it (written by the scope goroutine, read // reassembled sweep; scopeMu guards it (written by the scope goroutine, read
// via ScopeData from the binding goroutine). // via ScopeData from the binding goroutine).
dualScope bool dualScope bool
scopeMu sync.Mutex // Set when the rig rejects the waveform-output command in both shapes: it has
scopeAmp []byte // no stream to give, and asking again on every enable is noise.
scopeLow int64 // spectrum left-edge frequency (from the sweep's header frame) scopeUnsupported bool
scopeHigh int64 // spectrum right-edge frequency scopeMu sync.Mutex
scopeSeq int scopeAmp []byte
scopeOn bool scopeLow int64 // spectrum left-edge frequency (from the sweep's header frame)
scopeFixed bool // true = fixed-span mode (tracked optimistically) scopeHigh int64 // spectrum right-edge frequency
scopeSeen bool // logged the first sweep's structure once (on-rig verification) scopeSeq int
scopeOn bool
scopeFixed bool // true = fixed-span mode (tracked optimistically)
scopeSeen bool // logged the first sweep's structure once (on-rig verification)
curFreq int64 // last frequency read (for sideband choice) curFreq int64 // last frequency read (for sideband choice)
curModeByte byte // last raw Icom mode byte (for filter re-send) curModeByte byte // last raw Icom mode byte (for filter re-send)
@@ -113,7 +116,13 @@ type IcomSerial struct {
// "alive but silent" tolerance below, which used to be // "alive but silent" tolerance below, which used to be
// unbounded and left the display frozen for ever // unbounded and left the display frozen for ever
silentGrace time.Duration // current width of that tolerance (backs off, see ReadState) silentGrace time.Duration // current width of that tolerance (backs off, see ReadState)
dspLoaded bool // readDSP has run since the rig became responsive (loads all // Needle inertia for the TX meters — the CI-V meters are point samples, and
// between two SSB syllables a poll lands on 0 W and a perfect SWR. See
// meterPeak (yaesu_panel.go): power decays like a needle, SWR holds then
// snaps back to the live truth.
powerPeak meterPeak
swrPeak meterPeak
dspLoaded bool // readDSP has run since the rig became responsive (loads all
// the panel's set-once controls once the rig actually answers) // the panel's set-once controls once the rig actually answers)
// When the console last asked for the DSP snapshot. The meters and the // When the console last asked for the DSP snapshot. The meters and the
// front-panel rotation are polled ONLY while something is displaying them: // front-panel rotation are polled ONLY while something is displaying them:
@@ -259,6 +268,21 @@ func (b *IcomSerial) Connect() error {
// non-default address still RENDERS; this flag only drives the SET/read commands // non-default address still RENDERS; this flag only drives the SET/read commands
// (mode, span, edges), which need the 0x00 selector to be accepted on the 7300. // (mode, span, edges), which need the 0x00 selector to be accepted on the 7300.
b.dualScope = idAddr == 0x98 || idAddr == 0xA2 || idAddr == 0x94 b.dualScope = idAddr == 0x98 || idAddr == 0xA2 || idAddr == 0x94
// Silence any LEFTOVER waveform stream, BLIND, before anything else. The
// 0x27 output flag lives in the RADIO and survives sessions; its flood is
// what makes the IC-7760 stop answering CI-V — so waiting for CI-V to
// answer before sending this (the first attempt did) was the egg asking
// the chicken to hatch it. Fire-and-forget: an unanswered set costs one
// frame, and the rig acts on what it decodes whether or not we hear the
// acknowledgement. The front-panel display is deliberately untouched.
// Synchronously: Connect already runs on the CAT goroutine, and a stray
// goroutine writing to the shared link would interleave with the command
// loop. Two forms, because the selector byte differs by model and a NAK
// costs one frame — and the results are LOGGED, because a kill that quietly
// fails leaves the flood running and the next dropout unexplained.
err1 := b.execScope("waveform output off (leftover)", civ.SubScopeOn, 0)
err2 := b.exec(civ.CmdScope, civ.SubScopeOn, 0x00, 0x00) // main-selector form
applog.Printf("icom: waveform-off sent at connect (plain: %v, with selector: %v)", err1, err2)
// Defer the DSP snapshot until the rig actually answers CI-V. Over the network // Defer the DSP snapshot until the rig actually answers CI-V. Over the network
// the rig may still be booting (or off) at Connect, so an immediate readDSP // the rig may still be booting (or off) at Connect, so an immediate readDSP
// would time out and leave every control at 0 / off with no retry. ReadState // would time out and leave every control at 0 / off with no retry. ReadState
@@ -344,7 +368,12 @@ func (b *IcomSerial) ReadState() (RigState, error) {
case readerGone: case readerGone:
debugLog.Printf("icom net: the CI-V reader has exited — the connection is dead however alive the control link looks → reconnecting") debugLog.Printf("icom net: the CI-V reader has exited — the connection is dead however alive the control link looks → reconnecting")
case at.Alive(): case at.Alive():
debugLog.Printf("icom net: control link answers but no CI-V reply for %s → reconnecting. Another program (WSJT-X/OmniRig, the Remote Utility) has most likely taken the CI-V session.", silentFor.Round(time.Second)) // No verdict on WHY: this fires for a session taken by another
// program (WSJT-X, the Remote Utility) AND for a rig that simply
// stopped answering — a real IC-7760 did exactly that once with
// nothing else on the network. Blaming a hijacker sent that
// operator hunting software that was not installed.
debugLog.Printf("icom net: control link answers but no CI-V reply for %s → reconnecting. Either another program took the CI-V session (WSJT-X/OmniRig/Remote Utility), or the rig stopped answering on its own.", silentFor.Round(time.Second))
default: default:
debugLog.Printf("icom net: control link went quiet (no rig packets for >6 s) → reconnecting. If this recurs every ~2-3 min, the rig is invalidating the session (token renewal rejected).") debugLog.Printf("icom net: control link went quiet (no rig packets for >6 s) → reconnecting. If this recurs every ~2-3 min, the rig is invalidating the session (token renewal rejected).")
} }
@@ -393,6 +422,19 @@ func (b *IcomSerial) ReadState() (RigState, error) {
} }
b.dspMu.Lock() b.dspMu.Lock()
b.dsp.Mode = s.Mode b.dsp.Mode = s.Mode
// The console says which SIDEBAND, not the ADIF family: "SSB" on 40 m
// leaves the operator guessing whether the rig is where convention puts
// it. The log keeps SSB; the panel shows what the radio is actually doing.
switch b.curModeByte {
case civ.ModeUSB:
if s.Mode == "SSB" {
b.dsp.Mode = "USB"
}
case civ.ModeLSB:
if s.Mode == "SSB" {
b.dsp.Mode = "LSB"
}
}
b.dspMu.Unlock() b.dspMu.Unlock()
} }
@@ -406,8 +448,13 @@ func (b *IcomSerial) ReadState() (RigState, error) {
// all, for the user's Set* commands. // all, for the user's Set* commands.
if b.pollN%4 == 1 { if b.pollN%4 == 1 {
b.splitOn, b.splitTXFreq = false, 0 b.splitOn, b.splitTXFreq = false, 0
if on, ok := b.readSplit(); ok && on { on, okSplit := b.readSplit()
if txHz, ok2 := b.readTXFreq(); ok2 && txHz > 0 { // The unselected VFO is read split or NOT: on a dual-receiver rig it is
// the sub receiver's dial, and the console showed it blank until split
// was engaged.
if txHz, ok2 := b.readTXFreq(); ok2 && txHz > 0 {
b.setCache(func(st *IcomTXState) { st.SubHz = txHz })
if okSplit && on {
b.splitOn, b.splitTXFreq = true, txHz b.splitOn, b.splitTXFreq = true, txHz
} }
} }
@@ -432,12 +479,16 @@ func (b *IcomSerial) ReadState() (RigState, error) {
sm, _ = b.readMeter(civ.SubMeterS) sm, _ = b.readMeter(civ.SubMeterS)
po, swr = 0, 0 po, swr = 0, 0
if tx { if tx {
now := time.Now()
if v, ok := b.readMeter(civ.SubMeterPo); ok { if v, ok := b.readMeter(civ.SubMeterPo); ok {
po = v po = b.powerPeak.update(v, now)
} }
if v, ok := b.readMeter(civ.SubMeterSWR); ok { if v, ok := b.readMeter(civ.SubMeterSWR); ok {
swr = v swr = b.swrPeak.updateSnap(v, now)
} }
} else {
// Cleared with the carrier, so the next transmission starts fresh.
b.powerPeak, b.swrPeak = meterPeak{}, meterPeak{}
} }
} }
b.dspMu.Lock() b.dspMu.Lock()
@@ -506,6 +557,13 @@ func (b *IcomSerial) refreshFrontPanel() {
b.dsp.Filter = int(f) b.dsp.Filter = int(f)
b.dspMu.Unlock() b.dspMu.Unlock()
} }
case 2:
// Tuner in/out — the radio's own TUNER button changes it mid-session.
if v, ok := b.readSwitchSub(civ.CmdATU, civ.SubATU); ok {
b.dspMu.Lock()
b.dsp.ATUOn = v == 1
b.dspMu.Unlock()
}
} }
} }
@@ -556,6 +614,18 @@ func (b *IcomSerial) SetMode(mode string) error {
} }
// Filter 0x01 (FIL1) is the conventional default for the data-mode set. // Filter 0x01 (FIL1) is the conventional default for the data-mode set.
_ = b.execIdempotent("set data mode", civ.CmdExtra, civ.SubDataMode, dataByte, 0x01) _ = b.execIdempotent("set data mode", civ.CmdExtra, civ.SubDataMode, dataByte, 0x01)
// Trust, then verify: the IC-7760 acknowledges 1A 06 and stays in USB-D
// anyway, which left an operator unable to get back to plain USB at all.
// When the readback disagrees, say it again with 0x26 — mode, data flag and
// filter in one frame, the command the newer rigs actually honour. Only on
// a mismatch, so rigs that predate 0x26 never see it.
if got := b.readDataMode(); got != data {
if err := b.execIdempotent("set mode+data (0x26)", civ.CmdModeDataFil, 0x00, code, dataByte, 0x01); err != nil {
applog.Printf("icom: data flag stuck at %v after mode %s, and 0x26 failed too: %v", got, mode, err)
} else {
applog.Printf("icom: data flag stuck after 1A06, corrected via 0x26 (mode %s)", mode)
}
}
return nil return nil
} }
@@ -848,6 +918,19 @@ func (b *IcomSerial) scopeLoop(spec chan civ.Decoded, done chan struct{}) {
loggedCfg[f.Data[0]] = true loggedCfg[f.Data[0]] = true
applog.Printf("icom scope cfg 0x%02X: data=[% X]", f.Data[0], f.Data) applog.Printf("icom scope cfg 0x%02X: data=[% X]", f.Data[0], f.Data)
} }
// The rig just told us its own layout: a mode/span/edge answer of
// three bytes or more carries the main/sub selector, one of two
// bytes does not. Worth reading, because the SET commands take the
// same shape and several firmwares answer a wrong-shaped set with
// silence rather than a rejection — which is not something the
// retry in execScope can act on.
if f.Data[0] == civ.SubScopeMode && len(f.Data) >= 2 {
if sel := len(f.Data) >= 3; sel != b.dualScope {
applog.Printf("icom scope: the rig answers 0x%02X with %d bytes — using the %s form",
f.Data[0], len(f.Data)-1, map[bool]string{true: "27 xx 00 …", false: "27 xx …"}[sel])
b.dualScope = sel
}
}
continue continue
} }
if rawN < 24 { if rawN < 24 {
@@ -982,6 +1065,43 @@ func (b *IcomSerial) assembleSweep(regions map[byte][]byte, total byte) {
} }
} }
// execScope sends a 0x27 SET and, if the rig rejects it, sends it once more in
// the other shape — with or without the leading main/sub selector byte — and
// remembers which one this rig speaks.
//
// The shape used to be decided from the CI-V address, which meant every new
// model was a blank scope until someone reported it: the IC-7851 (0x8E) rejects
// "27 11 01" outright and wants "27 11 00 01", exactly as the IC-7610 does not.
// A rejection is a cheap and unambiguous answer, so ask the rig instead of
// keeping a list. Only the SET commands need this — the waveform parser already
// detects the selector per frame.
func (b *IcomSerial) execScope(what string, sub byte, args ...byte) error {
try := func(sel bool) error {
p := []byte{civ.CmdScope, sub}
if sel {
p = append(p, 0x00) // main scope
}
return b.exec(append(p, args...)...)
}
err := try(b.dualScope)
// Only a REJECTION means "wrong shape". A timeout says nothing (several
// firmwares simply don't ack a 0x27 set), and retrying it in the other shape
// would flip a working rig onto the wrong one.
if err == nil || !strings.Contains(err.Error(), "rejected") {
return err
}
err2 := try(!b.dualScope)
applog.Printf("icom scope: %s rejected in the %s form — the other form gave: %v",
what, map[bool]string{true: "27 xx 00 …", false: "27 xx …"}[b.dualScope], err2)
if err2 == nil {
b.dualScope = !b.dualScope
applog.Printf("icom scope: %s rejected — this rig wants the %s form (selector=%v)",
what, map[bool]string{true: "27 xx 00 …", false: "27 xx …"}[b.dualScope], b.dualScope)
return nil
}
return err
}
// SetScope enables or disables the spectrum scope. Two commands are needed and // SetScope enables or disables the spectrum scope. Two commands are needed and
// RS-BA1 sends both: 0x27 0x10 turns the scope DISPLAY on (without it the rig // RS-BA1 sends both: 0x27 0x10 turns the scope DISPLAY on (without it the rig
// streams nothing — the case when we're remote and can't touch the front panel), // streams nothing — the case when we're remote and can't touch the front panel),
@@ -1000,15 +1120,25 @@ func (b *IcomSerial) SetScope(on bool) error {
// radio, and closing OpsLog (SetScope(false)) blanking a local IC-7300's // radio, and closing OpsLog (SetScope(false)) blanking a local IC-7300's
// screen is exactly the regression this avoids. Some firmwares don't ack a // screen is exactly the regression this avoids. Some firmwares don't ack a
// 0x27 set; a timeout isn't fatal, so log and continue. // 0x27 set; a timeout isn't fatal, so log and continue.
if err := b.exec(civ.CmdScope, civ.SubScopeOnOff, 0x01); err != nil { if err := b.execScope("display on", civ.SubScopeOnOff, 0x01); err != nil {
applog.Printf("icom scope: display on ack: %v", err) applog.Printf("icom scope: display on ack: %v", err)
} }
} }
// Waveform data OUTPUT over CI-V: enabled with the scope, and — crucially — // Waveform data OUTPUT over CI-V: enabled with the scope, and — crucially —
// the ONLY thing we switch off on disable, so the radio's own scope display is // the ONLY thing we switch off on disable, so the radio's own scope display is
// left exactly as the operator had it. // left exactly as the operator had it.
if err := b.exec(civ.CmdScope, civ.SubScopeOn, boolByte(on)); err != nil { if err := b.execScope("data output", civ.SubScopeOn, boolByte(on)); err != nil {
applog.Printf("icom scope: output on=%v ack: %v", on, err) applog.Printf("icom scope: output on=%v ack: %v", on, err)
// Rejected in both shapes = the command does not exist on this rig, which
// is a permanent answer and not a bad guess on our part. Remember it: the
// panel can then say so, and we stop asking a radio that has already
// said no.
if strings.Contains(err.Error(), "rejected") {
applog.Printf("icom scope: %s does not stream its scope over CI-V — control commands only", b.model)
b.scopeMu.Lock()
b.scopeUnsupported = true
b.scopeMu.Unlock()
}
} }
b.scopeMu.Lock() b.scopeMu.Lock()
b.scopeOn = on b.scopeOn = on
@@ -1041,13 +1171,7 @@ func (b *IcomSerial) scopeReadCfg() {
// makes the scope follow the VFO, so tuning pans the view left/right. // makes the scope follow the VFO, so tuning pans the view left/right.
func (b *IcomSerial) SetScopeMode(fixed bool) error { func (b *IcomSerial) SetScopeMode(fixed bool) error {
mode := boolByte(fixed) // 0 = center, 1 = fixed (verify on rig via the cfg log) mode := boolByte(fixed) // 0 = center, 1 = fixed (verify on rig via the cfg log)
var payload []byte if err := b.execScope("set mode", civ.SubScopeMode, mode); err != nil {
if b.dualScope {
payload = []byte{civ.CmdScope, civ.SubScopeMode, 0x00, mode}
} else {
payload = []byte{civ.CmdScope, civ.SubScopeMode, mode}
}
if err := b.exec(payload...); err != nil {
applog.Printf("icom scope: set mode fixed=%v ack: %v", fixed, err) applog.Printf("icom scope: set mode fixed=%v ack: %v", fixed, err)
} }
b.scopeMu.Lock() b.scopeMu.Lock()
@@ -1093,13 +1217,8 @@ func (b *IcomSerial) SetScopeEdges(low, high int64) error {
if rangeID == 0 { if rangeID == 0 {
return fmt.Errorf("icom scope: freq out of range") return fmt.Errorf("icom scope: freq out of range")
} }
if b.dualScope { _ = b.execScope("fixed mode", civ.SubScopeMode, 0x01)
_ = b.exec(civ.CmdScope, civ.SubScopeMode, 0x00, 0x01) // fixed mode (main) _ = b.execScope("edge set 1", civ.SubScopeEdge, 0x01)
_ = b.exec(civ.CmdScope, civ.SubScopeEdge, 0x00, 0x01) // activate edge set 1
} else {
_ = b.exec(civ.CmdScope, civ.SubScopeMode, 0x01)
_ = b.exec(civ.CmdScope, civ.SubScopeEdge, 0x01)
}
payload := append([]byte{civ.CmdScope, civ.SubScopeFixEdge, rangeID, 0x01}, civ.FreqToBCD(low)...) payload := append([]byte{civ.CmdScope, civ.SubScopeFixEdge, rangeID, 0x01}, civ.FreqToBCD(low)...)
payload = append(payload, civ.FreqToBCD(high)...) payload = append(payload, civ.FreqToBCD(high)...)
b.scopeMu.Lock() b.scopeMu.Lock()
@@ -1263,7 +1382,8 @@ func (b *IcomSerial) ScopeData() ScopeSweep {
for i, v := range b.scopeAmp { for i, v := range b.scopeAmp {
amp[i] = int(v) amp[i] = int(v)
} }
return ScopeSweep{Amp: amp, Seq: b.scopeSeq, LowHz: b.scopeLow, HighHz: b.scopeHigh, Fixed: b.scopeFixed} return ScopeSweep{Amp: amp, Seq: b.scopeSeq, LowHz: b.scopeLow, HighHz: b.scopeHigh, Fixed: b.scopeFixed,
Unsupported: b.scopeUnsupported}
} }
// exec sends a set command and waits for the rig's OK (FB) / NG (FA) ack. // exec sends a set command and waits for the rig's OK (FB) / NG (FA) ack.
@@ -1429,6 +1549,12 @@ func (b *IcomSerial) modeCode(mode string) (code byte, data bool, err error) {
return civ.ModeFM, false, nil return civ.ModeFM, false, nil
case "RTTY", "FSK": case "RTTY", "FSK":
return civ.ModeRTTY, false, nil return civ.ModeRTTY, false, nil
case "PSK":
// The console button, not the ADIF mode: the rigs that HAVE a native PSK
// mode (7610/7760/7851 class) get it; a 7300 NAKs 0x12 and the button
// stays dead there, exactly as RS-BA1's does. Soundcard PSK31 stays on
// USB-D below, where every rig can do it.
return civ.ModePSK, false, nil
case "FT8", "FT4", "PSK31", "MFSK", "JS8", "JT65", "JT9", "OLIVIA", "DATA", "DIGITALVOICE": case "FT8", "FT4", "PSK31", "MFSK", "JS8", "JT65", "JT9", "OLIVIA", "DATA", "DIGITALVOICE":
// Digital data modes ride on USB with the data flag set (FT8 etc.). // Digital data modes ride on USB with the data flag set (FT8 etc.).
return civ.ModeUSB, true, nil return civ.ModeUSB, true, nil
@@ -1779,10 +1905,16 @@ func (b *IcomSerial) SetMicGain(p int) error {
} }
func (b *IcomSerial) SetIcomSplit(on bool) error { func (b *IcomSerial) SetIcomSplit(on bool) error {
return b.SetIcomSplitOffset(on, 0)
}
// SetIcomSplitOffset enables split with a CHOSEN TX offset in Hz (0 = the
// usual convention: +1 kHz on CW, +5 kHz otherwise). The console offers
// +1/+5/+10 directly, DXpedition style.
func (b *IcomSerial) SetIcomSplitOffset(on bool, offsetHz int64) error {
if on { if on {
// Enable split with the usual "work him up" TX offset: +1 kHz on CW, // Set the unselected (TX) VFO to RX+offset first, then turn split on.
// +5 kHz otherwise (SSB). Set the unselected (TX) VFO to RX+offset first, // 0x25 0x01 + BCD sets the unselected VFO's frequency.
// then turn split on. 0x25 0x01 + BCD sets the unselected VFO's frequency.
rx := b.curFreq rx := b.curFreq
if rx <= 0 { if rx <= 0 {
if hz, err := b.readFreq(); err == nil { if hz, err := b.readFreq(); err == nil {
@@ -1790,12 +1922,39 @@ func (b *IcomSerial) SetIcomSplit(on bool) error {
} }
} }
if rx > 0 { if rx > 0 {
offset := int64(5000) offset := offsetHz
if b.curModeByte == civ.ModeCW || b.curModeByte == civ.ModeCWR { if offset <= 0 {
offset = 1000 offset = 5000
if b.curModeByte == civ.ModeCW || b.curModeByte == civ.ModeCWR {
offset = 1000
}
} }
_ = b.exec(append([]byte{civ.CmdVfoFreq, civ.SubVfoUnselected}, civ.FreqToBCD(rx+offset)...)...) _ = b.exec(append([]byte{civ.CmdVfoFreq, civ.SubVfoUnselected}, civ.FreqToBCD(rx+offset)...)...)
} }
// And the MODE crosses with it: a split where the TX VFO is still on
// yesterday's mode transmits FM into a CW pileup. 0x26 0x01 sets the
// unselected VFO's mode + data flag in one frame; rigs that predate
// 0x26 NAK it harmlessly and behave as they always did.
if b.curModeByte == 0 {
// A fresh session may not have read the mode yet — ask, or the copy
// below would send mode 0 (LSB) whatever the main is on.
if m, ok := b.readMode(); ok {
b.curModeByte = m
}
}
if b.curModeByte != 0 {
dataByte := byte(0)
if got := b.readDataMode(); got {
dataByte = 1
}
// Logged, not discarded: the first version swallowed the error and a
// real 7760's sub VFO kept yesterday's mode with nothing to show why.
if err := b.exec(civ.CmdModeDataFil, 0x01, b.curModeByte, dataByte, 0x01); err != nil {
applog.Printf("icom: split mode-align (26 01 %02X %d) refused: %v", b.curModeByte, dataByte, err)
} else {
applog.Printf("icom: split mode-align OK (26 01 %02X %d)", b.curModeByte, dataByte)
}
}
} }
if err := b.exec(civ.CmdSplit, boolByte(on)); err != nil { if err := b.exec(civ.CmdSplit, boolByte(on)); err != nil {
return err return err
@@ -1929,6 +2088,17 @@ func (b *IcomSerial) TuneATU() error {
return b.exec(civ.CmdATU, civ.SubATU, 0x02) return b.exec(civ.CmdATU, civ.SubATU, 0x02)
} }
// SetATU engages or DISENGAGES the internal tuner (0x1C 0x01: 1 = in line,
// 0 = through). Tune existed without this, which meant a tuner once engaged
// could not be taken out of line again from the console.
func (b *IcomSerial) SetATU(on bool) error {
if err := b.exec(civ.CmdATU, civ.SubATU, boolByte(on)); err != nil {
return err
}
b.setCache(func(s *IcomTXState) { s.ATUOn = on })
return nil
}
func (b *IcomSerial) setCache(fn func(*IcomTXState)) { func (b *IcomSerial) setCache(fn func(*IcomTXState)) {
b.dspMu.Lock() b.dspMu.Lock()
fn(&b.dsp) fn(&b.dsp)
@@ -1971,3 +2141,42 @@ func agcValue(name string) byte {
} }
return 0 return 0
} }
// PlayTXAudio hands a voice-keyer message to the network audio session, when
// this rig is reached over one. A USB-connected Icom takes its audio through
// its own sound card instead, and says so.
func (b *IcomSerial) PlayTXAudio(pcm []byte, rate, ch, bits int, stop <-chan struct{}) error {
// port is written once per Connect, on the CAT goroutine this is fetched
// from (IcomDo); at worst a reconnect leaves this one connection stale, and
// a stale transport fails fast on its closed done channel.
port := b.port
// A nil port fails the assertions below too — and used to fail them with
// the sound-card message, sending an operator whose radio was simply OFF
// hunting through their audio devices.
if port == nil {
return fmt.Errorf("not connected to the radio — check the CAT link")
}
type txPlayer interface {
PlayTXAudio(pcm []byte, rate, ch, bits int, stop <-chan struct{}) error
}
if p, ok := port.(txPlayer); ok {
return p.PlayTXAudio(pcm, rate, ch, bits, stop)
}
return fmt.Errorf("this rig takes transmit audio through its USB sound card, not the CAT link")
}
// TXAudioSender hands back the network transport's live-mic sender, when this
// rig is reached over one.
func (b *IcomSerial) TXAudioSender() (func([]byte) error, error) {
port := b.port
if port == nil {
return nil, fmt.Errorf("not connected to the radio — check the CAT link")
}
type sender interface {
TXAudioSender() (func([]byte) error, error)
}
if p, ok := port.(sender); ok {
return p.TXAudioSender()
}
return nil, fmt.Errorf("this rig takes transmit audio through its USB sound card, not the CAT link")
}
+3 -3
View File
@@ -98,11 +98,11 @@ type Kenwood struct {
// Panel state — the K3/K4 control panel, see kenwood_panel.go. Read on the // Panel state — the K3/K4 control panel, see kenwood_panel.go. Read on the
// same serialised link as everything else, on a slow beat for the settings // same serialised link as everything else, on a slow beat for the settings
// and every poll for the meters. // and every poll for the meters.
panel KenwoodTXState panel KenwoodTXState
// The icon/status word, for working out which bit says "ATU in line" — see // The icon/status word, for working out which bit says "ATU in line" — see
// probeIcons. Kept so only CHANGES are logged. // probeIcons. Kept so only CHANGES are logged.
lastIcons string lastIcons string
iconProbes int iconProbes int
panelCycle int panelCycle int
panelLoaded bool panelLoaded bool
metersLogged int metersLogged int
+98 -4
View File
@@ -35,6 +35,11 @@ type KenwoodTXState struct {
Model string `json:"model,omitempty"` Model string `json:"model,omitempty"`
Elecraft bool `json:"elecraft"` // a K3/K4 rather than a Kenwood Elecraft bool `json:"elecraft"` // a K3/K4 rather than a Kenwood
Mode string `json:"mode,omitempty"` Mode string `json:"mode,omitempty"`
// DataSub is the K3/K4 DATA submode while in DATA mode (DT): "DATA A",
// "AFSK A", "FSK D" or "PSK D". Empty on a Kenwood, and outside DATA. The
// panel's two DATA buttons need it to show WHICH data mode the rig is in —
// FT8 wants DATA A, RTTY wants FSK D, and MD6 alone cannot say which.
DataSub string `json:"data_sub,omitempty"`
Transmitting bool `json:"transmitting"` Transmitting bool `json:"transmitting"`
Split bool `json:"split"` Split bool `json:"split"`
@@ -47,9 +52,15 @@ type KenwoodTXState struct {
SMeterRaw int `json:"s_meter_raw"` SMeterRaw int `json:"s_meter_raw"`
// PowerMeter is 0-100 while transmitting. SWR is the ratio; 0 means "not // PowerMeter is 0-100 while transmitting. SWR is the ratio; 0 means "not
// measured", NOT a perfect match. // measured", NOT a perfect match.
PowerMeter int `json:"power_meter"` PowerMeter int `json:"power_meter"`
SWR float64 `json:"swr"` // PowerW is the transmit power in WATTS, derived from the bargraph and the
SWRRaw int `json:"swr_raw"` // meter's RANGE. The K3's bar is relative to a range that flips at 12 W —
// calibrated against a real one: 10 W showed 83 (10/12), 100 W showed 83
// too (100/120). The bar alone never was watts; with the PC setting to
// pick the range, it converts. 0 while receiving.
PowerW int `json:"power_w"`
SWR float64 `json:"swr"`
SWRRaw int `json:"swr_raw"`
RFPower int `json:"rf_power"` // watts, the PC setting RFPower int `json:"rf_power"` // watts, the PC setting
AFGain int `json:"af_gain"` // 0-100 AFGain int `json:"af_gain"` // 0-100
@@ -107,10 +118,12 @@ type KenwoodPanelController interface {
SetKenwoodRIT(bool) error SetKenwoodRIT(bool) error
SetKenwoodXIT(bool) error SetKenwoodXIT(bool) error
NudgeKenwoodRIT(int) error NudgeKenwoodRIT(int) error
SetKenwoodRITOffset(int) error
ClearKenwoodRIT() error ClearKenwoodRIT() error
SetKenwoodTX(bool) error SetKenwoodTX(bool) error
TuneKenwoodATU() error TuneKenwoodATU() error
ToggleKenwoodATU() error ToggleKenwoodATU() error
SetKenwoodPanelMode(string) error
} }
// kenwoodPanelSlowBeat is how many polls pass between full re-reads of the // kenwoodPanelSlowBeat is how many polls pass between full re-reads of the
@@ -155,6 +168,7 @@ func (k *Kenwood) readPanel(mode string, split bool, txHz int64, txNow bool) {
// Cleared, not frozen: a power bar left standing after the carrier drops // Cleared, not frozen: a power bar left standing after the carrier drops
// reads as a live transmission. // reads as a live transmission.
k.panel.PowerMeter = 0 k.panel.PowerMeter = 0
k.panel.PowerW = 0
k.panel.SWR, k.panel.SWRRaw = 0, 0 k.panel.SWR, k.panel.SWRRaw = 0, 0
k.powerPeak, k.swrPeak = meterPeak{}, meterPeak{} k.powerPeak, k.swrPeak = meterPeak{}, meterPeak{}
// The S-meter only means anything while receiving. // The S-meter only means anything while receiving.
@@ -212,6 +226,14 @@ func (k *Kenwood) readPanelSettings() {
if v, ok := k.askNum("NR;", "NR", 1); ok { if v, ok := k.askNum("NR;", "NR", 1); ok {
k.panel.NR = v != 0 k.panel.NR = v != 0
} }
// The DATA submode, Elecraft only (a plain Kenwood has no DT and would "?;"
// it). Read every settings beat: the operator changes it from the rig's own
// front panel mid-session, and the two DATA buttons must follow.
if k.elecraft {
if v, ok := k.askNum("DT;", "DT", 1); ok {
k.panel.DataSub = kenwoodDataSubName(v)
}
}
if v, ok := k.askNum("GT;", "GT", 3); ok { if v, ok := k.askNum("GT;", "GT", 3); ok {
k.panel.AGC = kenwoodAGCName(v) k.panel.AGC = kenwoodAGCName(v)
} }
@@ -326,6 +348,13 @@ func (k *Kenwood) readTXMeters() {
defer func() { k.noLatch = false }() defer func() { k.noLatch = false }()
if v, ok := k.askNum("BG;", "BG", 2); ok { if v, ok := k.askNum("BG;", "BG", 2); ok {
k.panel.PowerMeter = k.powerPeak.update(kenwoodBargraphPercent(v), now) k.panel.PowerMeter = k.powerPeak.update(kenwoodBargraphPercent(v), now)
if k.elecraft {
scale := 120
if k.panel.RFPower > 0 && k.panel.RFPower <= 12 {
scale = 12 // the K3's QRP range
}
k.panel.PowerW = k.panel.PowerMeter * scale / 100
}
} }
// SW; — SETTLED, from Elecraft's own release note: three digits, tenths of a // SW; — SETTLED, from Elecraft's own release note: three digits, tenths of a
// ratio. "SW023;" is 2.3:1, and "SW999;" is the 99.9:1 it reports instead of // ratio. "SW023;" is 2.3:1, and "SW999;" is the 99.9:1 it reports instead of
@@ -334,7 +363,7 @@ func (k *Kenwood) readTXMeters() {
if v, ok := k.askNum("SW;", "SW", 3); ok { if v, ok := k.askNum("SW;", "SW", 3); ok {
k.panel.SWRRaw = v k.panel.SWRRaw = v
if v > 0 { if v > 0 {
k.panel.SWR = float64(k.swrPeak.update(v, now)) / 10 k.panel.SWR = float64(k.swrPeak.updateSnap(v, now)) / 10
} }
} }
if k.metersLogged >= 20 { if k.metersLogged >= 20 {
@@ -564,6 +593,16 @@ func (k *Kenwood) SetKenwoodXIT(on bool) error {
// ClearKenwoodRIT zeroes the RIT/XIT offset, both at once — which is what RC // ClearKenwoodRIT zeroes the RIT/XIT offset, both at once — which is what RC
// does and what the operator means by "clear it". // does and what the operator means by "clear it".
// SetKenwoodRITOffset writes the offset as an ABSOLUTE value — what the shared
// ShiftRow control speaks. Nudge stays for the keyboard clarifier; both funnel
// into the same RO write.
func (k *Kenwood) SetKenwoodRITOffset(hz int) error {
k.mu.Lock()
cur := k.panel.RITOffset
k.mu.Unlock()
return k.NudgeKenwoodRIT(hz - cur)
}
func (k *Kenwood) ClearKenwoodRIT() error { func (k *Kenwood) ClearKenwoodRIT() error {
return k.setPanel("RC;") return k.setPanel("RC;")
} }
@@ -650,3 +689,58 @@ func (k *Kenwood) askNum(cmd, prefix string, digits int) (int, bool) {
} }
return n, true return n, true
} }
// kenwoodDataSubName decodes DT (K3/K4 programmer's reference).
func kenwoodDataSubName(v int) string {
switch v {
case 0:
return "DATA A"
case 1:
return "AFSK A"
case 2:
return "FSK D"
case 3:
return "PSK D"
}
return ""
}
// SetKenwoodPanelMode is the panel's mode row: CW / USB / LSB / DATA / RTTY.
//
// It exists because SetMode is the LOGGER's path — it maps an ADIF mode and
// honours the data-mode preference — while a panel button is the operator
// saying exactly what the rig should do. The two DATA cases are the point:
// "DATA" is MD6 + DT0 (DATA A, the soundcard submode FT8/FT4 modulate through)
// and "RTTY" is MD6 + DT2 (FSK D, the K3's direct-keyed RTTY). MD6 alone keeps
// whatever submode a prior session left, which is how a K3 "in DATA" transmits
// FT8 with no audio — the report behind this row.
func (k *Kenwood) SetKenwoodPanelMode(mode string) error {
k.mu.Lock()
defer k.mu.Unlock()
if k.port == nil {
return fmt.Errorf("kenwood: not connected")
}
var cmds []string
switch strings.ToUpper(strings.TrimSpace(mode)) {
case "CW":
cmds = []string{"MD3;"}
case "USB":
cmds = []string{"MD2;"}
case "LSB":
cmds = []string{"MD1;"}
case "DATA":
cmds = []string{"MD6;", "DT0;"}
case "RTTY":
cmds = []string{"MD6;", "DT2;"}
default:
return fmt.Errorf("kenwood panel: unknown mode %q", mode)
}
for _, c := range cmds {
if err := k.write(c); err != nil {
return err
}
}
// Re-read the settings on the next poll so Mode and DataSub confirm at once.
k.panelCycle = kenwoodPanelSlowBeat
return nil
}
+7
View File
@@ -553,6 +553,13 @@ func (o *OmniRig) SetFrequency(hz int64) error {
props := []string{prop, "Freq"} props := []string{prop, "Freq"}
if onSubVFO { if onSubVFO {
props = []string{prop} props = []string{prop}
} else if isYaesu && split&pmSplitOn != 0 && split&pmSplitOff == 0 {
// Yaesu with SPLIT engaged: the generic Freq write lands on the TX
// VFO — an FT-2000 moved B and left A (the receiver) behind, so a
// spot click QSYed the transmitter and nothing audible changed.
// Both VFOs are written: the radio arrives on the spot RX and TX
// together, split left as the operator had it.
props = []string{"FreqA", "FreqB", "Freq"}
} }
for _, p := range props { for _, p := range props {
if _, e := oleutil.PutProperty(o.rig, p, hz32); e != nil { if _, e := oleutil.PutProperty(o.rig, p, hz32); e != nil {
+146 -8
View File
@@ -27,6 +27,14 @@ type TCI struct {
digitalDefault string // surfaced when the rig reports a digital mode (FT8/…) digitalDefault string // surfaced when the rig reports a digital mode (FT8/…)
spotsEnabled bool // mirror cluster spots onto the TCI panorama spotsEnabled bool // mirror cluster spots onto the TCI panorama
// wantFreq is the frequency last COMMANDED and not yet echoed back, used to
// pick the sideband before the radio has confirmed the move.
wantFreq int64
// What the server said it is, from its "protocol:" announcement.
serverName string
serverVersion string
// How many spots have been logged verbatim (the first few only).
spotsSent int
// OnSpotClick is called when the user clicks one of our spots on the TCI // OnSpotClick is called when the user clicks one of our spots on the TCI
// panorama (callsign + freq), so the host can fill the entry form. Set before // panorama (callsign + freq), so the host can fill the entry form. Set before
@@ -34,6 +42,10 @@ type TCI struct {
OnSpotClick func(callsign string, freqHz int64) OnSpotClick func(callsign string, freqHz int64)
unhandledSeen map[string]bool // log each unknown TCI message type once unhandledSeen map[string]bool // log each unknown TCI message type once
// panel is the control-console state — everything the radio announces about
// itself that is not frequency or mode. See tci_panel.go.
panel tciPanel
// audio holds the receive-audio stream — see tci_audio.go. TCI carries it // audio holds the receive-audio stream — see tci_audio.go. TCI carries it
// on this same WebSocket, which is what lets a SunSDR record and decode // on this same WebSocket, which is what lets a SunSDR record and decode
// without a virtual audio cable in the way. // without a virtual audio cable in the way.
@@ -145,6 +157,15 @@ func (t *TCI) Connect() error {
t.mu.Unlock() t.mu.Unlock()
debugLog.Printf("TCI: connected to %s", url) debugLog.Printf("TCI: connected to %s", url)
go t.reader(conn) go t.reader(conn)
// Ask for the meters. Nothing measures anything until this goes out: the
// S-meter, the transmit power and the SWR are all pushed by the radio, and
// only to a client that has subscribed. 200 ms is the rate the protocol's own
// examples use — fast enough for a needle, slow enough not to flood a socket
// that also carries audio.
if t.spotsEnabled {
debugLog.Printf("TCI: panorama spots are ON — spots will be sent to the radio")
}
t.subscribeSensors("connect")
if t.spotsEnabled { if t.spotsEnabled {
// Forget what we thought was on the panorama at the same moment the radio // Forget what we thought was on the panorama at the same moment the radio
// is told to drop it. Kept, the memory would suppress the next spot for // is told to drop it. Kept, the memory would suppress the next spot for
@@ -224,11 +245,19 @@ func (t *TCI) SendSpot(s SpotInfo) error {
// other two matching what already works here. // other two matching what already works here.
_ = t.send(fmt.Sprintf("spot_delete:%s;", call)) _ = t.send(fmt.Sprintf("spot_delete:%s;", call))
} }
// TCI's SPOT command wants the colour as a signed 32-bit DECIMAL integer in // The colour is a DECIMAL ARGB integer, and an UNSIGNED one.
// 0xAARRGGBB order — NOT a "0x…" hex string (e.g. "spot:UN7GK,cw,14025000, //
// -16776961,test;"). ExpertSDR silently drops a spot whose colour field it // Expert Electronics' own protocol document gives the whole command:
// can't parse as a number, which is why spots never showed on the panorama //
// while tuning (a separate command) still worked. // SPOT:RN6LHF,CW,7100000,16711680,ANY_TEXT;
//
// 16711680 is 0x00FF0000 — positive, alpha zero. This backend was sending
// the same number as a SIGNED 32-bit value, taken from a third-party
// example: with the alpha byte set to FF for opacity, 0xFFFFA500 becomes
// -22336, and a spot whose colour field ExpertSDR cannot read is dropped in
// silence. Reported on ExpertSDR3 1.3 (which speaks TCI 2.x, so the version
// was never the problem): everything else worked and the panorama stayed
// empty.
hex := strings.TrimPrefix(strings.TrimPrefix(strings.TrimSpace(s.Color), "#"), "0x") hex := strings.TrimPrefix(strings.TrimPrefix(strings.TrimSpace(s.Color), "#"), "0x")
if hex == "" { if hex == "" {
hex = "FFFFA500" // opaque orange default hex = "FFFFA500" // opaque orange default
@@ -249,7 +278,15 @@ func (t *TCI) SendSpot(s SpotInfo) error {
} }
// Commas/semicolons would break TCI's comma-separated argument parsing. // Commas/semicolons would break TCI's comma-separated argument parsing.
text := strings.NewReplacer(",", " ", ";", " ").Replace(s.Comment) text := strings.NewReplacer(",", " ", ";", " ").Replace(s.Comment)
return t.send(fmt.Sprintf("spot:%s,%s,%d,%d,%s;", call, mode, s.FreqHz, int32(argb), text)) cmd := fmt.Sprintf("spot:%s,%s,%d,%d,%s;", call, mode, s.FreqHz, argb, text)
// The first few, verbatim. A spot that the radio ignores leaves no trace at
// all — no reply, no error — so the only evidence that OpsLog sent one, and
// in what shape, is this line.
if n := t.spotsSent; n < 3 {
t.spotsSent = n + 1
debugLog.Printf("TCI: sending spot #%d: %s", n+1, strings.TrimSuffix(cmd, ";"))
}
return t.send(cmd)
} }
// Disconnect closes the WebSocket; the reader goroutine then exits. // Disconnect closes the WebSocket; the reader goroutine then exits.
@@ -300,6 +337,22 @@ func (t *TCI) ReadState() (RigState, error) {
} else { } else {
st.FreqHz = t.freqA st.FreqHz = t.freqA
} }
// The transmit meters are asked for, not pushed: TX_POWER and TX_SWR are
// read-only commands the radio answers when asked, and asking is only worth
// anything while it is keyed. Fired and forgotten from here — the answers
// arrive on the reader like everything else — and only while transmitting,
// so a receiving station pays nothing for a meter nobody is watching.
// Keyed by PTT **or** by TUNE. A tune carrier is exactly when the meters
// matter most — it is the carrier an operator is watching an SWR on — and
// asking only on t.tx left them at zero for the whole tune, because the
// radio reports tuning as its own state and not as a transmission.
if t.tx || t.panel.st.Tuning {
tx := t
go func() {
_ = tx.send("tx_power;")
_ = tx.send("tx_swr;")
}()
}
st.Mode = tciModeToADIF(t.mode, t.digitalDefault) st.Mode = tciModeToADIF(t.mode, t.digitalDefault)
if st.FreqHz > 0 { if st.FreqHz > 0 {
st.Band = BandFromHz(st.FreqHz) st.Band = BandFromHz(st.FreqHz)
@@ -314,6 +367,11 @@ func (t *TCI) ReadState() (RigState, error) {
// SetFrequency tunes VFO A (the main/RX VFO). // SetFrequency tunes VFO A (the main/RX VFO).
func (t *TCI) SetFrequency(hz int64) error { func (t *TCI) SetFrequency(hz int64) error {
// Remember what we ASKED for. SetMode reads it to choose the sideband, and
// the radio's own echo can be a moment behind — see SetMode.
t.mu.Lock()
t.wantFreq = hz
t.mu.Unlock()
return t.send(fmt.Sprintf("vfo:0,0,%d;", hz)) return t.send(fmt.Sprintf("vfo:0,0,%d;", hz))
} }
@@ -322,6 +380,17 @@ func (t *TCI) SetFrequency(hz int64) error {
func (t *TCI) SetMode(mode string) error { func (t *TCI) SetMode(mode string) error {
t.mu.Lock() t.mu.Lock()
freq := t.freqA freq := t.freqA
// Prefer the frequency we just COMMANDED over the one the radio has echoed.
//
// Clicking a spot sets the frequency and then the mode, and the sideband is
// chosen from the frequency (below 10 MHz → LSB). Read from the echo, that
// is the frequency we were on BEFORE the click whenever the echo has not
// landed yet: a 14 MHz spot clicked from 7 MHz got LSB, and clicking the same
// spot again — now that the echo has arrived — got USB. Reported from a
// SunSDR as "the frequency is right, the mode is wrong until I click twice".
if t.wantFreq > 0 {
freq = t.wantFreq
}
t.mu.Unlock() t.mu.Unlock()
m := adifToTCIMode(mode, freq) m := adifToTCIMode(mode, freq)
if m == "" { if m == "" {
@@ -391,6 +460,24 @@ func (t *TCI) SetTXAudioSource(src string) {
} }
// send writes a command to the WebSocket (one writer at a time). // send writes a command to the WebSocket (one writer at a time).
// subscribeSensors asks the radio to push its meters. Nothing measures anything
// until this goes out — the S-meter, the transmit power and the SWR are all
// subscription-only (TCI §4.4) — and it is sent at connect AND again at every
// "ready", because a subscription sent during the server's initial dump can be
// dropped. 200 ms is the rate the protocol's own examples use.
func (t *TCI) subscribeSensors(when string) {
// Both cases, deliberately. Every other command this backend sends works in
// lower case, but the meters stayed silent on a real SunSDR through two
// rounds of fixes — and the protocol document's own examples are upper case
// (TX_SENSORS_ENABLE:true,200;). A server that is case-insensitive ignores
// the duplicate; one that is not finally hears the subscription.
e1 := t.send("rx_sensors_enable:true,200;")
e2 := t.send("tx_sensors_enable:true,200;")
_ = t.send("RX_SENSORS_ENABLE:true,200;")
_ = t.send("TX_SENSORS_ENABLE:true,200;")
debugLog.Printf("TCI: sensor subscription sent (%s, both cases): rx=%v tx=%v", when, e1, e2)
}
func (t *TCI) send(cmd string) error { func (t *TCI) send(cmd string) error {
t.mu.Lock() t.mu.Lock()
c := t.conn c := t.conn
@@ -457,9 +544,34 @@ func (t *TCI) handle(msg string) {
} }
t.mu.Lock() t.mu.Lock()
defer t.mu.Unlock() defer t.mu.Unlock()
switch strings.ToLower(name) { lower := strings.ToLower(name)
// The console's own messages first. Most of them were being logged once as
// unhandled and thrown away — the radio has been announcing its drive, its
// filters and its noise blanker since the first connection.
if t.handlePanel(lower, get, args) {
// Still falls through for the few the rig state also needs (split, tune),
// which is why this does not return.
switch lower {
case "split_enable", "trx", "modulation", "vfo":
default:
return
}
}
switch lower {
case "device": case "device":
t.device = strings.TrimSpace(args) t.device = strings.TrimSpace(args)
// The server's own announcement: "protocol:ExpertSDR3,1.9;" — its name and
// the TCI version it speaks. Worth keeping rather than filing under
// "unhandled": panorama spots need a version that HAS the spot command, and
// without this an operator on an older ExpertSDR sees nothing on the
// waterfall and nothing anywhere saying why.
case "protocol":
t.serverName, t.serverVersion = get(0), get(1)
debugLog.Printf("TCI: server is %s, TCI %s", t.serverName, t.serverVersion)
if t.spotsEnabled && tciSpotsUnsupported(t.serverVersion) {
debugLog.Printf("TCI: this server speaks TCI %s — panorama spots need 1.5 or later, so they will not appear",
t.serverVersion)
}
// The radio ANNOUNCES its audio format at connect — // The radio ANNOUNCES its audio format at connect —
// "audio_stream_sample_type:float32" and "audio_stream_channels:2" — which // "audio_stream_sample_type:float32" and "audio_stream_channels:2" — which
// is better evidence than anything derived from a frame, and it arrives // is better evidence than anything derived from a frame, and it arrives
@@ -472,6 +584,13 @@ func (t *TCI) handle(msg string) {
} }
case "ready", "start": case "ready", "start":
t.ready = true t.ready = true
// (Re)subscribe to the meters HERE, not only at connect. ExpertSDR3
// dumps its whole state and then says "ready"; a unidirectional control
// command sent while that dump is still in flight can be ignored, and
// the report from a real SunSDR — transmit meters still empty after the
// connect-time subscription — has exactly that shape. From a goroutine:
// send takes t.mu, which this handler holds.
go t.subscribeSensors("ready")
case "stop": case "stop":
t.ready = false t.ready = false
case "vfo": case "vfo":
@@ -483,6 +602,10 @@ func (t *TCI) handle(msg string) {
switch get(1) { switch get(1) {
case "0": case "0":
t.freqA = hz t.freqA = hz
// The radio has caught up: from here the echo IS the truth.
if t.wantFreq != 0 && absInt64(hz-t.wantFreq) < 100 {
t.wantFreq = 0
}
case "1": case "1":
t.freqB = hz t.freqB = hz
} }
@@ -524,7 +647,7 @@ func (t *TCI) handle(msg string) {
t.txAllowed, t.txAllowedKnown = allowed, true t.txAllowed, t.txAllowedKnown = allowed, true
} }
default: default:
lname := strings.ToLower(name) lname := lower
// A click on one of our panorama spots comes back as // A click on one of our panorama spots comes back as
// CLICKED_ON_SPOT:<call>,<hz> (legacy) // CLICKED_ON_SPOT:<call>,<hz> (legacy)
// RX_CLICKED_ON_SPOT:<rx>,<ch>,<call>,<hz> // RX_CLICKED_ON_SPOT:<rx>,<ch>,<call>,<hz>
@@ -618,3 +741,18 @@ func adifToTCIMode(mode string, freqHz int64) string {
return "digu" return "digu"
} }
} }
// tciSpotsUnsupported reports whether a TCI version predates the spot commands.
//
// SPOT / SPOT_DELETE / SPOT_CLEAR arrived in TCI 1.5. An older ExpertSDR accepts
// the connection, answers frequency and mode perfectly, and silently ignores
// every spot — which is indistinguishable from a bug in the logger unless
// somebody says so. Anything unparseable is treated as supported: refusing to
// draw on a doubt would be the worse mistake.
func tciSpotsUnsupported(version string) bool {
var maj, min int
if n, err := fmt.Sscanf(strings.TrimSpace(version), "%d.%d", &maj, &min); n < 2 || err != nil {
return false
}
return maj < 1 || (maj == 1 && min < 5)
}
+72
View File
@@ -0,0 +1,72 @@
package cat
import (
"fmt"
"strings"
)
// CW keying over TCI — a sixth CW engine, so a SunSDR needs no WinKeyer and no
// second serial port: the radio's own macro keyer is driven over the WebSocket
// that already carries the CAT.
//
// The commands, from the TCI command table (confirmed against ars-ka0s/eesdr-tci,
// the same source that settled SPOT):
//
// CW_MACROS:<trx>,<text>; send text through the radio's keyer
// CW_MACROS_SPEED:<wpm>; the speed those macros are keyed at
// CW_MACROS_STOP; abort what is being keyed
// CW_MACROS_EMPTY; the radio saying the buffer has run dry
//
// CW_MSG (TCI 2.0) does the same with separate before/after callsign fields.
// CW_MACROS is used instead because it exists from 1.6 and OpsLog resolves the
// variables itself — the text handed here is already what should go on the air.
//
// Notably absent: there is no backspace. The FlexRadio CWX keyer can un-type
// what has not been sent yet; TCI can only stop. So the type-ahead correction
// the Flex engine offers is not offered here rather than faked.
// tciCWTextLimit caps one macro. A runaway paste down a WebSocket that also
// carries audio is worth refusing, and no real CW message is this long.
const tciCWTextLimit = 512
// SendCW keys a message through the radio's macro keyer.
func (t *TCI) SendCW(text string) error {
msg := sanitiseTCICW(text)
if msg == "" {
return nil
}
return t.send(fmt.Sprintf("cw_macros:0,%s;", msg))
}
// StopCW aborts the message being keyed.
func (t *TCI) StopCW() error { return t.send("cw_macros_stop;") }
// SetCWSpeed sets the macro keyer speed in words per minute.
//
// Only the MACRO speed: the paddle keyer has its own (CW_KEYER_SPEED) and an
// operator who has set their paddle to 28 wpm did not ask the logger to change
// it because a macro went out at 25.
func (t *TCI) SetCWSpeed(wpm int) error {
if wpm < 5 {
wpm = 5
}
if wpm > 60 {
wpm = 60
}
return t.send(fmt.Sprintf("cw_macros_speed:%d;", wpm))
}
// sanitiseTCICW makes a message safe to put in a TCI command.
//
// Commas and semicolons are the protocol's own separators — a comma inside the
// text would be read as another argument and a semicolon would end the command
// early, keying half a message and leaving the rest to be parsed as a command of
// its own. Neither belongs in Morse anyway.
func sanitiseTCICW(text string) string {
s := strings.ToUpper(strings.TrimSpace(text))
s = strings.NewReplacer(",", " ", ";", " ", "\r", " ", "\n", " ").Replace(s)
if len(s) > tciCWTextLimit {
s = s[:tciCWTextLimit]
}
return strings.TrimSpace(s)
}
+82
View File
@@ -37,3 +37,85 @@ func (m *Manager) TCIAudioDo(fn func(TCIAudioController) error) error {
return fn(tc) return fn(tc)
}) })
} }
// TCIPanelController is the control console of a TCI radio — everything the
// panel reads and everything it sets.
//
// Listed one by one rather than accepted as *TCI, for the same reason the audio
// controller is: the manager hands out capabilities, not backends, and a
// station on OmniRig asking for the TCI console gets a sentence instead of a
// crash.
type TCIPanelController interface {
TCIPanel() TCIPanelState
SetDrive(v int) error
SetTuneDrive(v int) error
SetMicLevel(v int) error
SetVolume(db int) error
SetMute(on bool) error
SetAGC(mode string) error
SetSquelch(on bool) error
SetSquelchLevel(v int) error
SetNB(on bool) error
SetNR(on bool) error
SetANF(on bool) error
SetAPF(on bool) error
SetFilter(lo, hi int) error
SetRIT(on bool) error
SetXIT(on bool) error
SetRITOffset(hz int) error
SetXITOffset(hz int) error
SetLock(on bool) error
SetTune(on bool) error
}
// TCIPanelState returns the console snapshot, or (zero, false) when the active
// backend is not a TCI radio.
//
// Read WITHOUT going through the CAT goroutine: the state is a cached copy of
// what the radio pushed, guarded by its own lock, and the panel polls it several
// times a second. Queueing that behind whatever the poll loop is doing would put
// the console's smoothness at the mercy of a rig command's timeout.
func (m *Manager) TCIPanelState() (TCIPanelState, bool) {
m.mu.RLock()
b := m.backend
m.mu.RUnlock()
if tc, ok := b.(TCIPanelController); ok {
return tc.TCIPanel(), true
}
return TCIPanelState{}, false
}
// TCIPanelDo dispatches one console command onto the CAT goroutine, where every
// other write to the radio goes.
func (m *Manager) TCIPanelDo(fn func(TCIPanelController) error) error {
return m.exec(func(b Backend) error {
tc, ok := b.(TCIPanelController)
if !ok {
return fmt.Errorf("the active CAT backend is not a TCI radio")
}
return fn(tc)
})
}
// TCICWController is the radio's CW keyer, as the CW engine uses it.
//
// Three methods, and no backspace: TCI can stop a message but cannot un-type one
// (see tci_cw.go). Kept as its own interface rather than folded into the console
// one so a CW engine does not have to depend on forty panel setters to key a
// message.
type TCICWController interface {
SendCW(text string) error
StopCW() error
SetCWSpeed(wpm int) error
}
// TCICWDo dispatches one keyer command onto the CAT goroutine.
func (m *Manager) TCICWDo(fn func(TCICWController) error) error {
return m.exec(func(b Backend) error {
tc, ok := b.(TCICWController)
if !ok {
return fmt.Errorf("the active CAT backend is not a TCI radio")
}
return fn(tc)
})
}
+418
View File
@@ -0,0 +1,418 @@
//go:build windows
package cat
// The TCI control panel: what the radio already tells us, gathered up.
//
// This is the cheapest panel in OpsLog, and the reason is worth saying. A K3 is
// asked — every value on its console costs a command and a reply on a serial
// line, which is why that panel reads its settings in a rotation and its meters
// only while it is on screen. TCI PUSHES: the radio announces its drive, its
// volume, its filters, its noise blanker and everything else when a client
// connects, and again whenever any of them changes, whoever changed it. There
// is nothing to poll.
//
// So this file is mostly a place to PUT what was already arriving and being
// logged as "(unhandled once)". The setters are the same names sent back the
// other way, which is how TCI works throughout: one vocabulary, both directions.
import (
"fmt"
"strconv"
"strings"
)
// TCIPanelState is the whole console in one snapshot, polled by the frontend.
//
// Values the radio has not mentioned keep their zero, which is why the
// "Known" flags exist for the ones where zero is a real setting: a squelch at 0
// and a squelch never reported are different, and a panel that cannot tell them
// apart draws a control that lies until the operator touches it.
type TCIPanelState struct {
Connected bool `json:"connected"`
Device string `json:"device,omitempty"` // what the radio calls itself
Protocol string `json:"protocol,omitempty"` // "ExpertSDR3,1.5"
// Transmit.
Drive int `json:"drive"` // 0-100
TuneDrive int `json:"tune_drive"` // 0-100, used by TUNE
MicLevel int `json:"mic_level"` // 0-100
TXEnabled bool `json:"tx_enabled"` // the radio's own permission (tx_enable)
TX bool `json:"tx"`
Tuning bool `json:"tuning"`
// Receive.
Volume int `json:"volume"` // dB, negative — TCI's own scale
Mute bool `json:"mute"`
AGC string `json:"agc,omitempty"` // off/long/slow/med/fast
SquelchOn bool `json:"squelch_on"`
Squelch int `json:"squelch"` // dBm threshold
NB bool `json:"nb"`
NR bool `json:"nr"`
ANF bool `json:"anf"`
APF bool `json:"apf"`
// Filter edges in Hz, relative to the carrier (TCI's own convention).
FilterLo int `json:"filter_lo"`
FilterHi int `json:"filter_hi"`
// Tuning aids.
RIT bool `json:"rit"`
RITOffset int `json:"rit_offset"`
XIT bool `json:"xit"`
XITOffset int `json:"xit_offset"`
Lock bool `json:"lock"`
Split bool `json:"split"`
// SMeter is the last reported signal level in dBm — the radio pushes it
// several times a second while receiving.
SMeter int `json:"smeter"`
// TXPowerW and TXSWR are the transmit meters. READ-ONLY in TCI, and only
// answered while transmitting — asked for on every poll of a keyed radio,
// see ReadState.
//
// There is no temperature in this protocol. The command list has TX_POWER
// and TX_SWR and nothing thermal at all, so a temperature reading here would
// have to be invented, and an invented temperature on a transmitter is the
// kind of number somebody trusts.
TXPowerW float64 `json:"tx_power_w"`
TXSWR float64 `json:"tx_swr"`
// Modulations is what this radio will accept, straight from its own
// announcement, so the mode buttons are the radio's and not a guess.
Modulations []string `json:"modulations,omitempty"`
}
// tciPanel is the backing state. Guarded by TCI.mu with everything else it
// arrives alongside.
type tciPanel struct {
st TCIPanelState
// logged counts what has been written per message type — see handlePanel.
logged map[string]int
}
// handlePanel takes the messages the console cares about.
//
// Returns false when the message is none of its business, so the caller can go
// on to its own cases and to the unknown-message log. Called with t.mu held.
func (t *TCI) handlePanel(name string, get func(int) string, args string) bool {
// Most of these are per-receiver ("sql_level:0,20"), and OpsLog follows
// receiver 0 throughout. A message for another receiver is accepted as
// handled and dropped: it is understood, it is simply not ours.
forRX0 := func() bool { return get(0) == "0" || get(0) == "" }
num := func(s string) (int, bool) {
n, err := strconv.Atoi(strings.TrimSpace(s))
return n, err == nil
}
yes := func(s string) bool { return strings.EqualFold(strings.TrimSpace(s), "true") }
p := &t.panel.st
// Mute and squelch are LOGGED as they change, because a report from a real
// radio says pressing MUTE lights the squelch and nothing here can explain
// it. What the radio actually announces after the command settles whether
// this is our reading or its doing, and no amount of reasoning will.
switch name {
case "mute", "sql_enable", "sql_level", "tx_power", "tx_swr", "tune",
"tx_sensors", "rx_sensors", "rx_channel_sensors":
// Logged on arrival so an ANSWER can be told from a SILENCE: the log
// showed the transmit meters being asked for and nothing coming back,
// which on its own proves nothing — a reply that arrived and failed to
// parse leaves exactly the same trace as one that never came.
//
// Capped per message type. The meters are asked for four times a second
// while transmitting, and a diagnostic that fills an evening's log is
// one that gets switched off instead of read.
if t.panel.logged == nil {
t.panel.logged = map[string]int{}
}
if n := t.panel.logged[name]; n < 20 {
t.panel.logged[name] = n + 1
debugLog.Printf("TCI: %s:%s", name, args)
}
}
switch name {
case "protocol":
p.Protocol = strings.TrimSpace(args)
case "drive":
if n, ok := num(get(1)); ok && forRX0() {
p.Drive = n
} else if n, ok := num(get(0)); ok && get(1) == "" {
// Some firmware sends "drive:85" with no receiver index.
p.Drive = n
}
case "tune_drive":
if n, ok := num(get(1)); ok && forRX0() {
p.TuneDrive = n
} else if n, ok := num(get(0)); ok && get(1) == "" {
p.TuneDrive = n
}
case "mic_level":
if n, ok := num(get(0)); ok {
p.MicLevel = n
}
case "volume":
if n, ok := num(get(0)); ok {
p.Volume = n
}
case "mute":
// Both shapes. This radio reports "mute:0,false" and the reference shows
// "mute:true" elsewhere — reading only one of them left the button
// showing the opposite of the truth, which is worse than showing
// nothing.
if get(1) != "" {
p.Mute = yes(get(1))
} else {
p.Mute = yes(get(0))
}
case "agc_mode":
if forRX0() {
p.AGC = strings.ToLower(strings.TrimSpace(get(1)))
}
case "sql_enable":
if forRX0() {
p.SquelchOn = yes(get(1))
}
case "sql_level":
if n, ok := num(get(1)); ok && forRX0() {
p.Squelch = n
}
case "rx_nb_enable":
if forRX0() {
p.NB = yes(get(1))
}
case "rx_nr_enable":
if forRX0() {
p.NR = yes(get(1))
}
case "rx_anf_enable":
if forRX0() {
p.ANF = yes(get(1))
}
case "rx_apf_enable":
if forRX0() {
p.APF = yes(get(1))
}
case "rx_filter_band":
if forRX0() {
if lo, ok := num(get(1)); ok {
p.FilterLo = lo
}
if hi, ok := num(get(2)); ok {
p.FilterHi = hi
}
}
case "rit_enable":
if forRX0() {
p.RIT = yes(get(1))
}
case "xit_enable":
if forRX0() {
p.XIT = yes(get(1))
}
case "rit_offset":
if n, ok := num(get(1)); ok && forRX0() {
p.RITOffset = n
}
case "xit_offset":
if n, ok := num(get(1)); ok && forRX0() {
p.XITOffset = n
}
case "lock":
if forRX0() {
p.Lock = yes(get(1))
}
case "tx_power":
if v, err := strconv.ParseFloat(strings.TrimSpace(get(0)), 64); err == nil {
p.TXPowerW = v
}
case "tx_swr":
if v, err := strconv.ParseFloat(strings.TrimSpace(get(0)), 64); err == nil {
p.TXSWR = v
}
case "rx_smeter":
if n, ok := num(get(1)); ok && forRX0() {
p.SMeter = n
}
// The meters of ExpertSDR3. The S-meter used to be read only from RX_SMETER
// and the transmit ones from TX_POWER / TX_SWR — commands this radio simply
// never sends, which is why the console's meters sat empty on a SunSDR in
// both RX and TX while everything else worked.
//
// The protocol's own answer (TCI Protocol.pdf, §4.4) is a SUBSCRIPTION:
//
// RX_SENSORS:<rx>,<dBm>; (deprecated in 2.0)
// RX_CHANNEL_SENSORS:<rx>,<channel>,<dBm>; (its replacement)
// TX_SENSORS:<trx>,<mic dBm>,<power W>,<peak W>,<SWR>;
//
// none of which arrives until the client asks with RX_SENSORS_ENABLE and
// TX_SENSORS_ENABLE — see Connect.
case "rx_sensors":
if v, err := strconv.ParseFloat(strings.TrimSpace(get(1)), 64); err == nil && forRX0() {
p.SMeter = int(v)
}
case "rx_channel_sensors":
// Main channel (A) of receiver 0: the one the console is showing.
if v, err := strconv.ParseFloat(strings.TrimSpace(get(2)), 64); err == nil &&
get(0) == "0" && get(1) == "0" {
p.SMeter = int(v)
}
case "tx_sensors":
if get(0) != "0" {
break
}
// arg3 is RMS power, arg4 the peak. The peak is what a power meter's
// needle does on speech; the RMS is what the operator is asked to keep
// under the amplifier's limit — so RMS is the number, as elsewhere.
if v, err := strconv.ParseFloat(strings.TrimSpace(get(2)), 64); err == nil {
p.TXPowerW = v
}
if v, err := strconv.ParseFloat(strings.TrimSpace(get(4)), 64); err == nil {
p.TXSWR = v
}
case "tune":
if forRX0() {
p.Tuning = yes(get(1))
}
case "modulations_list":
p.Modulations = splitAndTrim(args)
default:
return false
}
return true
}
// splitAndTrim turns "usb,lsb,cw" into a slice, upper-cased for display.
func splitAndTrim(s string) []string {
parts := strings.Split(s, ",")
out := make([]string, 0, len(parts))
for _, p := range parts {
if v := strings.ToUpper(strings.TrimSpace(p)); v != "" {
out = append(out, v)
}
}
return out
}
// TCIPanel returns the console snapshot.
func (t *TCI) TCIPanel() TCIPanelState {
t.mu.Lock()
defer t.mu.Unlock()
st := t.panel.st
st.Connected = t.conn != nil
st.Device = t.device
st.TX = t.tx
st.Split = t.split
st.TXEnabled = t.txAllowed || !t.txAllowedKnown
return st
}
// ── Setters ───────────────────────────────────────────────────────────────
//
// Every one of them is a SET in the same vocabulary the radio reports in, and
// none of them updates the cached state: the radio answers with the new value,
// and taking its word rather than our own is what keeps the panel honest when a
// setting is refused, clamped, or changed from the radio's own window a second
// later.
// SetDrive sets the transmit drive, 0-100.
//
// THE TRX INDEX IS PART OF THE COMMAND — "drive:0,15;", not "drive:15;". Sent
// without it the radio simply ignores it: no error, no answer, the power
// unchanged. The rule is the one the radio's own reports follow, and it was
// there to read all along: this radio announces "drive:0,85" at connect.
func (t *TCI) SetDrive(v int) error { return t.send(fmt.Sprintf("drive:0,%d;", clampTCIPct(v))) }
// SetTuneDrive sets the drive used by TUNE, 0-100. Indexed, like drive.
func (t *TCI) SetTuneDrive(v int) error {
return t.send(fmt.Sprintf("tune_drive:0,%d;", clampTCIPct(v)))
}
// SetMicLevel sets the microphone gain, 0-100.
// Mic gain and volume are the two that are NOT indexed — the radio reports
// them as "mic_level:100" and "volume:-12", with no receiver in front. Sending
// the shape the radio speaks in is the whole rule here.
func (t *TCI) SetMicLevel(v int) error { return t.send(fmt.Sprintf("mic_level:%d;", clampTCIPct(v))) }
// SetVolume sets the receive volume in dB. TCI's scale is negative — 0 is full
// and -60 is inaudible — so this is NOT clamped to a percentage.
func (t *TCI) SetVolume(db int) error {
if db > 0 {
db = 0
}
if db < -60 {
db = -60
}
return t.send(fmt.Sprintf("volume:%d;", db))
}
// SetMute mutes or unmutes the receiver. Indexed — the radio reports
// "mute:0,false", and a mute sent without the index goes nowhere.
func (t *TCI) SetMute(on bool) error { return t.send(fmt.Sprintf("mute:0,%t;", on)) }
// SetAGC picks the AGC speed: off, long, slow, med, fast.
func (t *TCI) SetAGC(mode string) error {
m := strings.ToLower(strings.TrimSpace(mode))
switch m {
case "off", "long", "slow", "med", "fast":
default:
return fmt.Errorf("unknown AGC mode %q", mode)
}
return t.send(fmt.Sprintf("agc_mode:0,%s;", m))
}
// SetSquelch turns the squelch on or off.
func (t *TCI) SetSquelch(on bool) error { return t.send(fmt.Sprintf("sql_enable:0,%t;", on)) }
// SetSquelchLevel sets the threshold in dBm.
func (t *TCI) SetSquelchLevel(v int) error { return t.send(fmt.Sprintf("sql_level:0,%d;", v)) }
// SetNB, SetNR, SetANF, SetAPF switch the receive processing.
func (t *TCI) SetNB(on bool) error { return t.send(fmt.Sprintf("rx_nb_enable:0,%t;", on)) }
func (t *TCI) SetNR(on bool) error { return t.send(fmt.Sprintf("rx_nr_enable:0,%t;", on)) }
func (t *TCI) SetANF(on bool) error { return t.send(fmt.Sprintf("rx_anf_enable:0,%t;", on)) }
func (t *TCI) SetAPF(on bool) error { return t.send(fmt.Sprintf("rx_apf_enable:0,%t;", on)) }
// SetFilter sets the passband edges in Hz.
func (t *TCI) SetFilter(lo, hi int) error {
if lo > hi {
lo, hi = hi, lo
}
return t.send(fmt.Sprintf("rx_filter_band:0,%d,%d;", lo, hi))
}
// SetRIT / SetXIT switch the offsets on, SetRITOffset / SetXITOffset move them.
func (t *TCI) SetRIT(on bool) error { return t.send(fmt.Sprintf("rit_enable:0,%t;", on)) }
func (t *TCI) SetXIT(on bool) error { return t.send(fmt.Sprintf("xit_enable:0,%t;", on)) }
func (t *TCI) SetRITOffset(hz int) error { return t.send(fmt.Sprintf("rit_offset:0,%d;", hz)) }
func (t *TCI) SetXITOffset(hz int) error { return t.send(fmt.Sprintf("xit_offset:0,%d;", hz)) }
// SetLock locks the VFO knob on the radio.
func (t *TCI) SetLock(on bool) error { return t.send(fmt.Sprintf("lock:0,%t;", on)) }
// SetTune starts or stops the tune carrier.
//
// It TRANSMITS, at tune_drive rather than at drive — which is the setting to
// check before pressing it, and why the panel shows the two side by side.
//
// The state is recorded HERE rather than waited for. This radio does not echo
// "tune:0,true", so the panel had no way of knowing a tune was running: the
// button stayed on TUNE and every further press sent another START, which is
// why it could not be switched off again. Whatever the radio says afterwards
// still wins — it simply never says anything.
func (t *TCI) SetTune(on bool) error {
t.mu.Lock()
t.panel.st.Tuning = on
t.mu.Unlock()
return t.send(fmt.Sprintf("tune:0,%t;", on))
}
func clampTCIPct(v int) int {
if v < 0 {
return 0
}
if v > 100 {
return 100
}
return v
}
+41
View File
@@ -0,0 +1,41 @@
package cat
import "testing"
func TestTCISpotsUnsupported(t *testing.T) {
// SPOT arrived in TCI 1.5. The SunSDR2 PRO report that prompted this was an
// ExpertSDR announcing 1.3 — spots accepted and silently dropped.
for _, c := range []struct {
version string
old bool
}{
{"1.3", true},
{"1.4", true},
{"1.5", false},
{"1.9", false},
{"2.0", false},
{"", false}, // unparseable → assume it works
{"weird", false}, // refusing to draw on a doubt is the worse mistake
} {
if got := tciSpotsUnsupported(c.version); got != c.old {
t.Errorf("tciSpotsUnsupported(%q) = %v, want %v", c.version, got, c.old)
}
}
}
func TestSanitiseTCICW(t *testing.T) {
// The separators must never survive: a comma would become another argument
// and a semicolon would end the command with the message half sent.
for _, c := range []struct{ in, want string }{
{"cq cq de f4bpo", "CQ CQ DE F4BPO"},
{" tu 599 ", "TU 599"},
{"73, gl", "73 GL"},
{"test;cw_macros_stop", "TEST CW_MACROS_STOP"},
{"line\r\nbreak", "LINE BREAK"},
{" ", ""},
} {
if got := sanitiseTCICW(c.in); got != c.want {
t.Errorf("sanitiseTCICW(%q) = %q, want %q", c.in, got, c.want)
}
}
}
+26 -7
View File
@@ -51,13 +51,13 @@ type YaesuTXState struct {
// NarrowSupported says the rig answered NA at all. A button that reports a // NarrowSupported says the rig answered NA at all. A button that reports a
// state the radio never gave, and does nothing when pressed, is worse than // state the radio never gave, and does nothing when pressed, is worse than
// an absent one: it looks like a fault in the radio. // an absent one: it looks like a fault in the radio.
NarrowSupported bool `json:"narrow_supported"` NarrowSupported bool `json:"narrow_supported"`
MicGain int `json:"mic_gain"` // 0-100 MicGain int `json:"mic_gain"` // 0-100
AFGain int `json:"af_gain"` // 0-100 AFGain int `json:"af_gain"` // 0-100
RFGain int `json:"rf_gain"` // 0-100 RFGain int `json:"rf_gain"` // 0-100
Squelch int `json:"squelch"` // 0-100 Squelch int `json:"squelch"` // 0-100
AGC string `json:"agc,omitempty"` AGC string `json:"agc,omitempty"`
Preamp int `json:"preamp"` // 0=IPO, 1=AMP1, 2=AMP2 Preamp int `json:"preamp"` // 0=IPO, 1=AMP1, 2=AMP2
// Antenna is the selected jack, 1-3, or 0 when the rig has no AN command — // Antenna is the selected jack, 1-3, or 0 when the rig has no AN command —
// an FT-891 or FT-991A has a single socket and answers nothing. 0 is what // an FT-891 or FT-991A has a single socket and answers nothing. 0 is what
// tells the panel to draw no selector at all rather than a dead one. // tells the panel to draw no selector at all rather than a dead one.
@@ -905,3 +905,22 @@ func yaesuSplitCommand(cmd, vfo string, on bool) string {
} }
return cmd + "0;" return cmd + "0;"
} }
// updateSnap is update for a meter where lingering is misinformation: the peak
// stands for the hold, then the display returns to the live sample AT ONCE.
// Made for the K3's SWR — the radio throws a brief SWR spike as an FT8 frame
// ends, and the quarter-of-the-gap decay above turned that one bad sample into
// twelve seconds of alarming red on the next transmission. A needle's inertia
// suits a power meter; an SWR reading is a warning light, and a warning that
// fades slowly reads as a fault that is slowly getting better.
func (m *meterPeak) updateSnap(sample int, now time.Time) int {
if sample >= m.val {
m.val, m.at = sample, now
return m.val
}
if now.Sub(m.at) < meterHold {
return m.val
}
m.val, m.at = sample, now
return m.val
}
+24 -20
View File
@@ -44,30 +44,30 @@ type ServerConfig struct {
// is emitted to the UI, so the table never has empty country cells // is emitted to the UI, so the table never has empty country cells
// flickering in for a few hundred ms. // flickering in for a few hundred ms.
type Spot struct { type Spot struct {
SourceID int64 `json:"source_id"` // ID of the cluster server this came from SourceID int64 `json:"source_id"` // ID of the cluster server this came from
SourceName string `json:"source_name"` // display name (handy in the UI when multiple servers) SourceName string `json:"source_name"` // display name (handy in the UI when multiple servers)
Spotter string `json:"spotter"` // DE field Spotter string `json:"spotter"` // DE field
// SpotterContinent belongs to the SPOT, not to the DX station: one call is // SpotterContinent belongs to the SPOT, not to the DX station: one call is
// spotted by dozens of skimmers on every continent within a minute. It is // spotted by dozens of skimmers on every continent within a minute. It is
// resolved per spot at ingest for exactly that reason — see the note on the // resolved per spot at ingest for exactly that reason — see the note on the
// spotter-continent filter in App.tsx. // spotter-continent filter in App.tsx.
SpotterContinent string `json:"spotter_continent,omitempty"` SpotterContinent string `json:"spotter_continent,omitempty"`
DXCall string `json:"dx_call"` // the DX station heard DXCall string `json:"dx_call"` // the DX station heard
FreqKHz float64 `json:"freq_khz"` FreqKHz float64 `json:"freq_khz"`
FreqHz int64 `json:"freq_hz"` FreqHz int64 `json:"freq_hz"`
Band string `json:"band,omitempty"` Band string `json:"band,omitempty"`
Comment string `json:"comment,omitempty"` Comment string `json:"comment,omitempty"`
Locator string `json:"locator,omitempty"` // spotter grid (optional) Locator string `json:"locator,omitempty"` // spotter grid (optional)
TimeUTC string `json:"time_utc,omitempty"` TimeUTC string `json:"time_utc,omitempty"`
Country string `json:"country,omitempty"` // DXCC entity name (cty.dat) Country string `json:"country,omitempty"` // DXCC entity name (cty.dat)
Continent string `json:"continent,omitempty"` // 2-letter continent Continent string `json:"continent,omitempty"` // 2-letter continent
CQZone int `json:"cqz,omitempty"` // DXCC entity CQ zone CQZone int `json:"cqz,omitempty"` // DXCC entity CQ zone
ITUZone int `json:"ituz,omitempty"` // DXCC entity ITU zone ITUZone int `json:"ituz,omitempty"` // DXCC entity ITU zone
DistanceKm int `json:"distance_km,omitempty"` // great-circle km from operator's grid DistanceKm int `json:"distance_km,omitempty"` // great-circle km from operator's grid
ShortPath int `json:"sp_deg,omitempty"` // azimuth (deg) short path from operator ShortPath int `json:"sp_deg,omitempty"` // azimuth (deg) short path from operator
LongPath int `json:"lp_deg,omitempty"` // azimuth (deg) long path = SP + 180 mod 360 LongPath int `json:"lp_deg,omitempty"` // azimuth (deg) long path = SP + 180 mod 360
ReceivedAt time.Time `json:"received_at"` ReceivedAt time.Time `json:"received_at"`
Raw string `json:"raw"` Raw string `json:"raw"`
// Historical marks a spot recovered from a SH/DX table rather than heard live. // Historical marks a spot recovered from a SH/DX table rather than heard live.
// It belongs in the grid, but must NOT fire alerts or reach the panadapter: // It belongs in the grid, but must NOT fire alerts or reach the panadapter:
// replaying 100 past spots would spam both, and a station spotted three hours // replaying 100 past spots would spam both, and a station spotted three hours
@@ -75,6 +75,10 @@ type Spot struct {
Historical bool `json:"historical,omitempty"` Historical bool `json:"historical,omitempty"`
POTARef string `json:"pota_ref,omitempty"` // park id if this station is activating (api.pota.app) POTARef string `json:"pota_ref,omitempty"` // park id if this station is activating (api.pota.app)
POTAName string `json:"pota_name,omitempty"` // park name POTAName string `json:"pota_name,omitempty"` // park name
// SOTARef comes from the COMMENT, not from an API: the SOTA clusters put the
// summit in the text of the spot they send ("W9/WI-001"), and there is no
// per-callsign endpoint to ask the way POTA has one.
SOTARef string `json:"sota_ref,omitempty"`
} }
// State enumerates the per-server lifecycle. // State enumerates the per-server lifecycle.
+1 -1
View File
@@ -110,7 +110,7 @@ func TestParseShowDX(t *testing.T) {
// chatter turned into fake spots would be worse than no parser at all. // chatter turned into fake spots would be worse than no parser at all.
func TestParseShowDXRejectsNoise(t *testing.T) { func TestParseShowDXRejectsNoise(t *testing.T) {
noise := []string{ noise := []string{
"DX de F5ABC: 14195.0 EA8DHH CQ DX 1234Z", // the broadcast form: spotRE owns it "DX de F5ABC: 14195.0 EA8DHH CQ DX 1234Z", // the broadcast form: spotRE owns it
"Hello and welcome to the DXSpider cluster", "Hello and welcome to the DXSpider cluster",
"WWV de VE7CC <18Z> : SFI=110, A=16, K=2", "WWV de VE7CC <18Z> : SFI=110, A=16, K=2",
"F4BPO de GB7DXC 12-Jul-2026 2130Z dxspider >", "F4BPO de GB7DXC 12-Jul-2026 2130Z dxspider >",
+21
View File
@@ -0,0 +1,21 @@
package cluster
import "regexp"
// sotaRefRe matches a SOTA summit reference inside a spot comment.
//
// The shape is association/region-NNN — "W9/WI-001", "DM/BM-063", "VK3/VC-014",
// "F/AM-123" — and the association may carry digits. Anchored on both sides so
// a callsign like DL/SP9DPM/P can never be read as one, and deliberately
// narrower than "anything with a slash and a dash": POTA (US-4475) and WWFF
// (DLFF-0001) refs share the comment field and must not be caught here.
var sotaRefRe = regexp.MustCompile(`\b([A-Z0-9]{1,4}(?:/[A-Z0-9]{1,4})?/[A-Z]{2}-[0-9]{3})\b`)
// SOTARefFrom returns the first SOTA reference in a spot comment, or "".
func SOTARefFrom(comment string) string {
m := sotaRefRe.FindStringSubmatch(comment)
if m == nil {
return ""
}
return m[1]
}
+25
View File
@@ -0,0 +1,25 @@
package cluster
import "testing"
func TestSOTARefFrom(t *testing.T) {
// Left column: real comments seen on the SOTA cluster feed.
cases := []struct{ in, want string }{
{"W9/WI-001", "W9/WI-001"},
{"DM/BM-063", "DM/BM-063"},
{"W7Y/TT-122", "W7Y/TT-122"},
{"VK3/VC-014 s2s", "VK3/VC-014"},
{"[SOTA] F/AM-123 cq", "F/AM-123"},
{"", ""},
// The other reference schemes that share this field.
{"POTA US-4475", ""},
{"WWFF DLFF-0001", ""},
// A portable callsign is not a summit.
{"DL/SP9DPM/P calling", ""},
}
for _, c := range cases {
if got := SOTARefFrom(c.in); got != c.want {
t.Errorf("SOTARefFrom(%q) = %q, want %q", c.in, got, c.want)
}
}
}
+97
View File
@@ -0,0 +1,97 @@
package dxcc
// The DELETED DXCC entities, and why a lookup table needs to know about them.
//
// cty.dat answers one question: what entity is this callsign in TODAY. That is
// the right answer for a spot and the wrong one for a log. R1MVI was Malyj
// Vysotskij Island, entity 151, until the ARRL deleted it in February 2012;
// today the same callsign resolves to European Russia, 54. A 2004 contact
// re-stamped from cty.dat therefore loses the entity it was made with — and
// with it a DXCC credit that cannot be worked again, because the place no
// longer counts.
//
// Reported by an operator importing a Logger32 export: his ADIF said
// <DXCC:3>151 and OpsLog stored 54.
//
// So this list exists to be able to say "that number belongs to something that
// no longer exists, leave it alone". It is the ADIF specification's own
// enumeration of deleted entities, and it does not change except when the ARRL
// deletes another one.
var deletedEntities = map[int]string{
2: "Abu Ail Is.",
8: "Aldabra",
19: "Bajo Nuevo",
23: "Blenheim Reef",
25: "British North Borneo",
26: "British Somaliland",
28: "Canal Zone",
30: "Celebe & Molucca Is.",
39: "Comoros",
42: "Damao, Diu",
44: "Desroches",
55: "Farquhar",
57: "French Equatorial Africa",
58: "French Indo-China",
59: "French West Africa",
67: "French India",
68: "Kuwait/Saudi Arabia Neutral Zone",
81: "Germany",
85: "Bonaire, Curacao",
93: "Geyser Reef",
101: "Goa",
102: "Gold Coast, Togoland",
113: "Ifni",
115: "Italian Somaliland",
119: "Java",
127: "Kamaran Is.",
128: "Karelo-Finnish Republic",
134: "Kingman Reef",
139: "Kuria Muria I.",
151: "Malyj Vysotskij I.",
154: "Yemen Arab Republic",
155: "Malaya",
164: "Manchuria",
178: "Minerva Reef",
183: "Netherlands Borneo",
184: "Netherlands New Guinea",
186: "Newfoundland, Labrador",
193: "Okinawa (Ryukyu Is.)",
194: "Okino Tori-shima",
196: "Palestine",
200: "Portuguese Timor",
208: "Ruanda-Urundi",
210: "Saar",
218: "Czechoslovakia",
220: "Sarawak",
226: "Saudi Arabia/Iraq Neutral Zone",
228: "Serrana Bank & Roncador Cay",
229: "German Democratic Republic",
231: "Sikkim",
243: "People's Democratic Rep. of Yemen",
244: "Southern Sudan",
255: "St. Maarten, Saba, St. Eustatius",
258: "Sumatra",
261: "Swan Is.",
264: "Tangier",
267: "Territory of New Guinea",
268: "Tibet",
271: "Trieste",
307: "Zanzibar",
488: "Walvis Bay",
493: "Penguin Is.",
}
// IsDeleted reports whether a DXCC entity number names an entity the ARRL has
// deleted.
//
// The one thing every caller does with a true answer is the same: stop. A
// deleted entity cannot be looked up from a callsign, cannot be worked again,
// and cannot be corrected by anything that only knows about today.
func IsDeleted(n int) bool {
_, ok := deletedEntities[n]
return ok
}
// DeletedName is what entity n was called, or "" if it is not a deleted entity.
// Used to say WHICH entity was preserved rather than only that one was.
func DeletedName(n int) string { return deletedEntities[n] }
+46
View File
@@ -0,0 +1,46 @@
package dxcc
import "testing"
// The contact that reported this: R1MVI, worked in 2004 on Malyj Vysotskij
// Island, entity 151, deleted in February 2012. cty.dat resolves that callsign
// to European Russia (54) today, so anything that re-stamps an old QSO from a
// callsign has to know to stop here.
func TestMalyjVysotskijIsKnownDeleted(t *testing.T) {
if !IsDeleted(151) {
t.Fatal("151 (Malyj Vysotskij I.) must be known as deleted — the whole guard hangs on it")
}
if got := DeletedName(151); got == "" {
t.Error("a deleted entity should be able to say what it was called")
}
}
// The guard must not fire on entities that are alive, or every log would freeze
// at whatever DXCC number it was imported with — including the wrong ones.
func TestLiveEntitiesAreNotTreatedAsDeleted(t *testing.T) {
live := map[int]string{
54: "European Russia — what R1MVI resolves to today",
227: "France",
291: "United States",
339: "Japan",
1: "Canada",
}
for n, what := range live {
if IsDeleted(n) {
t.Errorf("%d (%s) must not be listed as deleted", n, what)
}
}
if got := DeletedName(54); got != "" {
t.Errorf("DeletedName(54) = %q, want empty", got)
}
}
// A few more from the ADIF enumeration, so a careless edit to the table is
// caught rather than discovered by an operator whose credits moved.
func TestSomeOtherDeletedEntities(t *testing.T) {
for _, n := range []int{218 /* Czechoslovakia */, 229 /* German DR */, 255 /* St. Maarten, Saba, St. Eustatius */, 28 /* Canal Zone */} {
if !IsDeleted(n) {
t.Errorf("%d should be a deleted entity", n)
}
}
}
+33 -2
View File
@@ -5,6 +5,7 @@ package email
import ( import (
"fmt" "fmt"
"os" "os"
"strings"
"time" "time"
"github.com/wneessen/go-mail" "github.com/wneessen/go-mail"
@@ -86,12 +87,42 @@ func SendFiles(cfg Config, to, subject, body string, attachPaths []string) error
return fmt.Errorf("smtp client: %w", err) return fmt.Errorf("smtp client: %w", err)
} }
if err := client.DialAndSend(m); err != nil { if err := client.DialAndSend(m); err != nil {
return fmt.Errorf("send via %s:%d (%s, %s): %w", return fmt.Errorf("send via %s:%d (%s, %s): %w%s",
cfg.Host, cfg.Port, cfg.Encryption, describeSize(attachPaths), err) cfg.Host, cfg.Port, cfg.Encryption, describeSize(attachPaths), err, explainSMTP(err))
} }
return nil return nil
} }
// explainSMTP turns a server's refusal into the thing to go and do.
//
// A rejection is quoted verbatim above it — the server's own words are the
// evidence — but several of them name a policy rather than a mistake, and no
// amount of re-checking the password will fix those. Microsoft's is the one
// operators keep hitting: basic authentication for SMTP is switched off across
// Microsoft 365 and outlook.com, and an app password does not bring it back.
func explainSMTP(err error) string {
msg := strings.ToLower(err.Error())
switch {
case strings.Contains(msg, "basic authentication is disabled"),
strings.Contains(msg, "5.7.139"):
return "\n\nMicrosoft has switched off password-based SMTP for this account. " +
"An app password does not restore it — the server refuses the password itself, not the one you typed. " +
"On a Microsoft 365 tenant an administrator can re-enable it for this mailbox " +
"(Set-CASMailbox -SmtpClientAuthenticationDisabled $false, plus the tenant-wide setting); " +
"otherwise use another provider for alerts (a Gmail account with an app password works, so does any ordinary IMAP/SMTP host)."
case strings.Contains(msg, "application-specific password"),
strings.Contains(msg, "5.7.9"):
return "\n\nThis account needs an APP PASSWORD rather than the one you sign in with " +
"(Google, Yahoo and others require it once two-factor authentication is on)."
case strings.Contains(msg, "5.7.8"), strings.Contains(msg, "authentication failed"),
strings.Contains(msg, "535"):
return "\n\nThe server rejected the username or the password."
case strings.Contains(msg, "must issue a starttls"):
return "\n\nThe server requires encryption: set STARTTLS (usually port 587) or SSL (465)."
}
return ""
}
// describeSize reports what was attached, in bytes. // describeSize reports what was attached, in bytes.
// //
// "An existing connection was forcibly closed" during DATA is the same message // "An existing connection was forcibly closed" during DATA is the same message
+29
View File
@@ -0,0 +1,29 @@
package email
import (
"errors"
"strings"
"testing"
)
func TestExplainSMTP(t *testing.T) {
// The real refusal, from an operator's Outlook account.
outlook := errors.New("SMTP AUTH failed: 535 5.7.139 Authentication unsuccessful, basic authentication is disabled.")
if got := explainSMTP(outlook); !strings.Contains(got, "Microsoft has switched off") {
t.Errorf("the Microsoft policy refusal is not explained: %q", got)
}
// A plain wrong password must NOT claim a policy: the advice would send the
// operator to an administrator over a typo.
wrong := errors.New("535 5.7.8 authentication failed")
got := explainSMTP(wrong)
if strings.Contains(got, "Microsoft") {
t.Errorf("a wrong password was explained as a Microsoft policy: %q", got)
}
if !strings.Contains(got, "rejected the username") {
t.Errorf("a wrong password is not explained: %q", got)
}
// Anything else is left to speak for itself.
if got := explainSMTP(errors.New("dial tcp: i/o timeout")); got != "" {
t.Errorf("an unrelated error got an explanation: %q", got)
}
}
+162 -9
View File
@@ -12,6 +12,7 @@ import (
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"strings" "strings"
"sync"
"syscall" "syscall"
"time" "time"
) )
@@ -20,6 +21,67 @@ import (
// document of the user's QSOs (optionally only confirmed ones). // document of the user's QSOs (optionally only confirmed ones).
const lotwReportURL = "https://lotw.arrl.org/lotwuser/lotwreport.adi" const lotwReportURL = "https://lotw.arrl.org/lotwuser/lotwreport.adi"
const (
// How long LoTW may take to START answering. It builds the whole report
// before sending anything, so this is the slow part of a big account.
lotwHeaderTimeout = 10 * time.Minute
// How long the transfer may stall once it HAS started. A download that has
// not moved in this long is not slow, it is dead — and saying so beats a
// progress window that sits at "working" until someone gives up.
lotwIdleTimeout = 2 * time.Minute
lotwMaxBytes = 256 * 1024 * 1024
)
// readWithProgress reads the body in chunks, reporting the running total and
// failing fast on a stall.
//
// Reported as it arrives rather than at the end: an 18 MB report over a slow
// link is minutes of silence otherwise, which is indistinguishable from a hang —
// and that is exactly what operators were reporting.
func say(note func(string), msg string) {
if note != nil {
note(msg)
}
LogSink("%s", msg)
}
func readWithProgress(ctx context.Context, r io.Reader, note func(string)) ([]byte, error) {
var (
out []byte
total int64
last = time.Now()
buf = make([]byte, 64*1024)
next = int64(256 * 1024) // first report early — proof it is moving
)
for {
if err := ctx.Err(); err != nil {
return nil, err
}
n, err := r.Read(buf)
if n > 0 {
out = append(out, buf[:n]...)
total += int64(n)
last = time.Now()
if total >= next {
say(note, fmt.Sprintf(" … %.1f MB received", float64(total)/(1024*1024)))
next = total + 512*1024
}
if total >= lotwMaxBytes {
return out, nil
}
}
if err == io.EOF {
return out, nil
}
if err != nil {
return nil, err
}
if time.Since(last) > lotwIdleTimeout {
return nil, fmt.Errorf("the transfer stalled after %d KB — LoTW stopped sending", total/1024)
}
}
}
// DownloadLoTWConfirmations fetches confirmed QSOs from LoTW as ADIF text. // DownloadLoTWConfirmations fetches confirmed QSOs from LoTW as ADIF text.
// Uses the LoTW *website* login (Username/Password), not the TQSL cert. When // Uses the LoTW *website* login (Username/Password), not the TQSL cert. When
// since is non-empty (YYYY-MM-DD) only confirmations received since then are // since is non-empty (YYYY-MM-DD) only confirmations received since then are
@@ -27,7 +89,7 @@ const lotwReportURL = "https://lotw.arrl.org/lotwuser/lotwreport.adi"
// non-empty, only confirmations for that station callsign are returned (an // non-empty, only confirmations for that station callsign are returned (an
// LoTW account holds every call you operate — F4BPO, F4BPO/P, TM2Q — so this // LoTW account holds every call you operate — F4BPO, F4BPO/P, TM2Q — so this
// scopes the pull to the active profile's call). // scopes the pull to the active profile's call).
func DownloadLoTWConfirmations(ctx context.Context, client *http.Client, cfg ServiceConfig, since, ownCall string) (string, error) { func DownloadLoTWConfirmations(ctx context.Context, client *http.Client, cfg ServiceConfig, since, ownCall string, detail bool, note func(string)) (string, error) {
user := strings.TrimSpace(cfg.Username) user := strings.TrimSpace(cfg.Username)
if user == "" || cfg.Password == "" { if user == "" || cfg.Password == "" {
return "", fmt.Errorf("lotw: website login (username/password) not set") return "", fmt.Errorf("lotw: website login (username/password) not set")
@@ -36,28 +98,119 @@ func DownloadLoTWConfirmations(ctx context.Context, client *http.Client, cfg Ser
q.Set("login", user) q.Set("login", user)
q.Set("password", cfg.Password) q.Set("password", cfg.Password)
q.Set("qso_query", "1") q.Set("qso_query", "1")
q.Set("qso_qsl", "yes") // only QSLed (confirmed) records q.Set("qso_qsl", "yes") // only QSLed (confirmed) records
q.Set("qso_qsldetail", "yes") // include QSL_RCVD / QSLRDATE detail // qso_qsldetail is what LoTW charges for: it adds the QSL date and the
// station's own DXCC / grid / state / county to every record, and takes an
// order of magnitude longer to build — a report that arrives in two minutes
// without it takes twenty with it, measured on the same account.
//
// What we actually need to mark a confirmation is call, date, band and mode.
// The rest is worth its price only when the download is also ADDING the QSOs
// it cannot find, which is the one case where the extra fields are the only
// source for them.
if detail {
q.Set("qso_qsldetail", "yes")
}
if c := strings.TrimSpace(ownCall); c != "" { if c := strings.TrimSpace(ownCall); c != "" {
q.Set("qso_owncall", c) // restrict to this station callsign q.Set("qso_owncall", c) // restrict to this station callsign
} }
if s := strings.TrimSpace(since); s != "" { // qso_qslsince is ALWAYS sent, even for "everything".
q.Set("qso_qslsince", s) //
// Left out, LoTW does not answer "all confirmations" — it answers with a
// handful of recent ones, which arrives as a 200 and a valid ADIF and reads
// as a successful download of a nearly empty account. Asking from a date
// older than the service itself is the only way to mean "all".
sinceDate := strings.TrimSpace(since)
if sinceDate == "" {
sinceDate = "1945-11-15" // older than any QSO LoTW will accept
} }
q.Set("qso_qslsince", sinceDate)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, lotwReportURL+"?"+q.Encode(), nil) req, err := http.NewRequestWithContext(ctx, http.MethodGet, lotwReportURL+"?"+q.Encode(), nil)
if err != nil { if err != nil {
return "", fmt.Errorf("lotw: build request: %w", err) return "", fmt.Errorf("lotw: build request: %w", err)
} }
// Named, because LoTW's front end throttles unidentified clients harder than
// it throttles known ones, and an operator reporting a 503 deserves a request
// that says who is asking.
req.Header.Set("User-Agent", "OpsLog")
if client == nil { if client == nil {
client = &http.Client{Timeout: 120 * time.Second} // NO overall deadline. A full account is tens of megabytes and LoTW spends
// minutes building it before the first byte; a total timeout turns a slow
// but healthy download into "context deadline exceeded", and a longer one
// turns a dead connection into a window that says "working" for twenty
// minutes. What matters is not how long it takes but whether it is still
// moving — see the idle watchdog below.
client = &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
ResponseHeaderTimeout: lotwHeaderTimeout,
TLSHandshakeTimeout: 30 * time.Second,
},
}
}
// LoTW answers 503 when it is busy, which for a report covering more than a
// few days is often — other loggers get the same answer and simply ask
// again. Three tries, spaced, and each one said out loud: an operator whose
// download takes four minutes because the ARRL is loaded should be able to
// see that rather than guess it.
// LoTW sends nothing at all until the whole report is built — minutes for a
// large account. That silence was the entire complaint: a window saying
// "working" with no way to tell a busy server from a dead one. Count it out
// loud until the first byte.
beat := make(chan struct{})
go func() {
start := time.Now()
tick := time.NewTicker(15 * time.Second)
defer tick.Stop()
for {
select {
case <-beat:
return
case <-ctx.Done():
return
case <-tick.C:
say(note, fmt.Sprintf(" … still waiting for LoTW to build the report (%.0f s)", time.Since(start).Seconds()))
}
}
}()
// Stopped where the WAIT ends, not where the function does: deferred, the
// heartbeat went on counting between the megabyte lines and read as if the
// report were still being built while it was already arriving.
stopBeat := sync.OnceFunc(func() { close(beat) })
defer stopBeat()
var resp *http.Response
for attempt := 1; ; attempt++ {
resp, err = client.Do(req) //nolint:bodyclose // closed below or in the retry
if err == nil && resp.StatusCode != http.StatusServiceUnavailable &&
resp.StatusCode != http.StatusBadGateway && resp.StatusCode != http.StatusGatewayTimeout {
break
}
if attempt >= 3 {
break
}
wait := time.Duration(attempt*20) * time.Second
if resp != nil {
say(note, fmt.Sprintf("LoTW is busy (HTTP %d) — asking again in %s…", resp.StatusCode, wait))
resp.Body.Close()
} else {
say(note, fmt.Sprintf("LoTW did not answer (%v) — asking again in %s…", err, wait))
}
select {
case <-ctx.Done():
return "", ctx.Err()
case <-time.After(wait):
}
req = req.Clone(ctx)
} }
resp, err := client.Do(req)
if err != nil { if err != nil {
return "", fmt.Errorf("lotw: request failed: %w", err) return "", fmt.Errorf("lotw: request failed: %w", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
body, err := io.ReadAll(io.LimitReader(resp.Body, 32*1024*1024)) stopBeat()
say(note, fmt.Sprintf("LoTW answered (HTTP %d) — receiving…", resp.StatusCode))
body, err := readWithProgress(ctx, resp.Body, note)
if err != nil { if err != nil {
return "", fmt.Errorf("lotw: read response: %w", err) return "", fmt.Errorf("lotw: read response: %w", err)
} }
@@ -365,7 +518,7 @@ func TestLoTW(cfg ServiceConfig, stationDataPath string) (string, error) {
} }
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel() defer cancel()
if _, err := DownloadLoTWConfirmations(ctx, nil, cfg, "2099-01-01", ""); err != nil { if _, err := DownloadLoTWConfirmations(ctx, nil, cfg, "2099-01-01", "", false, nil); err != nil {
return "", fmt.Errorf("%s — but the DOWNLOAD login failed: %w", up, err) return "", fmt.Errorf("%s — but the DOWNLOAD login failed: %w", up, err)
} }
return up + ". Download login accepted.", nil return up + ". Download login accepted.", nil
+34 -5
View File
@@ -156,6 +156,8 @@ type Event struct {
DecodeModeRaw string DecodeModeRaw string
// DecodeMsgRaw is the message as sent, untrimmed — see DecodeModeRaw. // DecodeMsgRaw is the message as sent, untrimmed — see DecodeModeRaw.
DecodeMsgRaw string DecodeMsgRaw string
// DecodeIsNew is false on the history a Replay resends: display-only lines.
DecodeIsNew bool
// ProgramID is the sending application's own id ("WSJT-X", "MSHV", or // ProgramID is the sending application's own id ("WSJT-X", "MSHV", or
// "WSJT-X - 2" for a second instance started with --rig-name). It is what // "WSJT-X - 2" for a second instance started with --rig-name). It is what
// tells two receivers apart on one multicast group — and it is the address a // tells two receivers apart on one multicast group — and it is the address a
@@ -212,6 +214,9 @@ type Server struct {
// lastFrom is the address each program's packets arrive from — where a Reply // lastFrom is the address each program's packets arrive from — where a Reply
// has to be sent. See SendReply. // has to be sent. See SendReply.
lastFrom map[string]*net.UDPAddr lastFrom map[string]*net.UDPAddr
// onNewInstance fires (off the read loop) the first time a program id is
// heard on this listener — the hook the startup replay hangs from.
onNewInstance func(programID string)
// instLabel names each running application, keyed by id AND sending address. // instLabel names each running application, keyed by id AND sending address.
// //
// WSJT-X requires --rig-name for a second instance, so its ids differ. MSHV // WSJT-X requires --rig-name for a second instance, so its ids differ. MSHV
@@ -285,11 +290,12 @@ func describePacket(pkt []byte) string {
func newServer(cfg Config, out chan<- Event, mgr *Manager) *Server { func newServer(cfg Config, out chan<- Event, mgr *Manager) *Server {
return &Server{ return &Server{
cfg: cfg, cfg: cfg,
out: out, out: out,
mgr: mgr, mgr: mgr,
stop: make(chan struct{}), onNewInstance: mgr.onNewInstance,
done: make(chan struct{}), stop: make(chan struct{}),
done: make(chan struct{}),
} }
} }
@@ -515,13 +521,23 @@ func (s *Server) handle(pkt []byte, remote *net.UDPAddr) {
// must go to the sender's own address, never to the group. // must go to the sender's own address, never to the group.
s.mu.Lock() s.mu.Lock()
inst := s.instanceLabel(w.ProgramID, remote) inst := s.instanceLabel(w.ProgramID, remote)
newInstance := false
if inst != "" && remote != nil { if inst != "" && remote != nil {
if s.lastFrom == nil { if s.lastFrom == nil {
s.lastFrom = map[string]*net.UDPAddr{} s.lastFrom = map[string]*net.UDPAddr{}
} }
if _, known := s.lastFrom[inst]; !known {
newInstance = true
}
s.lastFrom[inst] = remote s.lastFrom[inst] = remote
} }
onNew := s.onNewInstance
s.mu.Unlock() s.mu.Unlock()
// A program just heard for the first time this session: tell the app, so
// it can ask for a replay of the decodes already on that program's screen.
if newInstance && onNew != nil {
go onNew(inst)
}
// Status carries the current dial frequency; remember it so Decode audio // Status carries the current dial frequency; remember it so Decode audio
// offsets can be turned into RF frequencies for the panadapter. // offsets can be turned into RF frequencies for the panadapter.
if w.FreqHz > 0 && !w.IsDecode { if w.FreqHz > 0 && !w.IsDecode {
@@ -580,6 +596,7 @@ func (s *Server) handle(pkt []byte, remote *net.UDPAddr) {
ev.DecodeModeRaw = w.Mode ev.DecodeModeRaw = w.Mode
ev.DecodeMsg = w.DecodeMsg ev.DecodeMsg = w.DecodeMsg
ev.DecodeMsgRaw = w.DecodeMsgRaw ev.DecodeMsgRaw = w.DecodeMsgRaw
ev.DecodeIsNew = w.DecodeIsNew
ev.DecodeAt = decodeTime(w.DecodeMsSinceMidnight) ev.DecodeAt = decodeTime(w.DecodeMsSinceMidnight)
ev.DecodeTRPeriod = tr ev.DecodeTRPeriod = tr
ev.DecodeDial = dial ev.DecodeDial = dial
@@ -803,6 +820,10 @@ type Manager struct {
repo *Repo repo *Repo
out chan Event out chan Event
// onNewInstance is copied onto every inbound listener as it starts; see
// Server.onNewInstance.
onNewInstance func(programID string)
// noADIFOnce keeps the "nothing to forward to" note to one line a session // noADIFOnce keeps the "nothing to forward to" note to one line a session
// rather than one per QSO logged. // rather than one per QSO logged.
noADIFOnce sync.Once noADIFOnce sync.Once
@@ -940,3 +961,11 @@ func (m *Manager) StopAll() {
s.close() s.close()
} }
} }
// SetOnNewInstance installs the first-sighting hook. Call before Reload so
// listeners are born with it.
func (m *Manager) SetOnNewInstance(fn func(programID string)) {
m.mu.Lock()
m.onNewInstance = fn
m.mu.Unlock()
}
@@ -0,0 +1,47 @@
package udp
import (
"bytes"
"encoding/binary"
"hamlog/internal/applog"
)
// WSJT-X Configure (message 15) — change the decoder's settings remotely. Used
// for ONE thing here: clicking an FT4 spot while the decoder sits in FT8
// switches its mode too, so the operator lands ready to decode instead of
// staring at a band of gibberish. Every other field is sent as "no change"
// (empty strings, max-quint32), per the protocol.
const wsjtMsgConfigure = 15
// EncodeConfigureMode builds a Configure datagram that changes only the mode.
func EncodeConfigureMode(programID, mode string) []byte {
const noChange32 = ^uint32(0)
var b bytes.Buffer
_ = binary.Write(&b, binary.BigEndian, uint32(wsjtMagic))
_ = binary.Write(&b, binary.BigEndian, uint32(2))
_ = binary.Write(&b, binary.BigEndian, uint32(wsjtMsgConfigure))
writeQString(&b, programID)
writeQString(&b, mode) // Mode
_ = binary.Write(&b, binary.BigEndian, noChange32) // Frequency Tolerance — no change
writeQString(&b, "") // Submode — no change
_ = binary.Write(&b, binary.BigEndian, uint8(0)) // Fast Mode — off (right for every HF mode)
_ = binary.Write(&b, binary.BigEndian, noChange32) // T/R Period — no change
_ = binary.Write(&b, binary.BigEndian, noChange32) // Rx DF — no change
writeQString(&b, "") // DX Call — no change
writeQString(&b, "") // DX Grid — no change
_ = binary.Write(&b, binary.BigEndian, uint8(0)) // Generate Messages — no
return b.Bytes()
}
// SendConfigureMode asks every decoder heard this session to switch mode.
// Sent to all instances rather than one: the spot click does not say which
// decoder the operator is looking at, and a second instance already in the
// right mode treats the message as a no-op.
func (m *Manager) SendConfigureMode(mode string) {
for _, inst := range m.Instances() {
if err := m.sendToInstance(inst, EncodeConfigureMode(inst, mode), "configure-mode"); err == nil {
applog.Printf("udp: asked %q to switch to %s", inst, mode)
}
}
}
+146
View File
@@ -0,0 +1,146 @@
package udp
import (
"bytes"
"encoding/binary"
"fmt"
"strings"
"hamlog/internal/applog"
)
// WSJT-X Highlight Callsign (13) and Replay (7) — the two halves of making the
// Band Activity window log-aware.
//
// Highlight paints a callsign in the decoding application's own window with the
// colours OpsLog chooses — new DXCC, new band, a watchlist member — the way
// JTAlert does. Replay asks a freshly-discovered instance to resend the decodes
// it already has on screen, so the FT decodes panel starts full instead of
// empty until the next period.
const (
wsjtMsgReplay = 7
wsjtMsgHighlight = 13
)
// RGB is one highlight colour. A nil *RGB means "invalid QColor", which is the
// protocol's way of saying "remove the highlight".
type RGB struct{ R, G, B uint8 }
// writeQColor serializes a QColor as QDataStream does: a spec byte (1 = RGB,
// 0 = invalid) followed by five 16-bit channels (alpha, red, green, blue, pad),
// each 8-bit value doubled into 16 bits the way Qt stores them.
func writeQColor(b *bytes.Buffer, c *RGB) {
if c == nil {
b.WriteByte(0) // invalid — clears the highlight
for i := 0; i < 5; i++ {
_ = binary.Write(b, binary.BigEndian, uint16(0))
}
return
}
b.WriteByte(1) // spec = RGB
wide := func(v uint8) uint16 { return uint16(v) * 0x101 }
_ = binary.Write(b, binary.BigEndian, uint16(0xFFFF)) // alpha, opaque
_ = binary.Write(b, binary.BigEndian, wide(c.R))
_ = binary.Write(b, binary.BigEndian, wide(c.G))
_ = binary.Write(b, binary.BigEndian, wide(c.B))
_ = binary.Write(b, binary.BigEndian, uint16(0)) // pad
}
// EncodeHighlight builds a Highlight Callsign datagram. bg/fg nil = invalid
// colour; both nil clears the callsign's highlight.
func EncodeHighlight(programID, callsign string, bg, fg *RGB, lastPeriodOnly bool) []byte {
var b bytes.Buffer
_ = binary.Write(&b, binary.BigEndian, uint32(wsjtMagic))
_ = binary.Write(&b, binary.BigEndian, uint32(2))
_ = binary.Write(&b, binary.BigEndian, uint32(wsjtMsgHighlight))
writeQString(&b, programID)
writeQString(&b, callsign)
writeQColor(&b, bg)
writeQColor(&b, fg)
var last uint8
if lastPeriodOnly {
last = 1
}
_ = binary.Write(&b, binary.BigEndian, last)
return b.Bytes()
}
// EncodeReplay builds a Replay datagram — "resend what your window holds".
func EncodeReplay(programID string) []byte {
var b bytes.Buffer
_ = binary.Write(&b, binary.BigEndian, uint32(wsjtMagic))
_ = binary.Write(&b, binary.BigEndian, uint32(2))
_ = binary.Write(&b, binary.BigEndian, uint32(wsjtMsgReplay))
writeQString(&b, programID)
return b.Bytes()
}
// sendToInstance routes a raw datagram to the application that owns programID,
// the same way SendReply does: to the address its packets actually arrive from.
func (m *Manager) sendToInstance(programID string, pkt []byte, what string) error {
if strings.TrimSpace(programID) == "" {
return fmt.Errorf("no application id")
}
m.mu.Lock()
servers := make([]*Server, 0, len(m.inbound))
for _, s := range m.inbound {
servers = append(servers, s)
}
m.mu.Unlock()
for _, s := range servers {
conn, addr := s.replyTarget(programID)
if conn == nil || addr == nil {
continue
}
if _, err := conn.WriteToUDP(pkt, addr); err != nil {
return fmt.Errorf("send %s to %s at %s: %w", what, programID, addr, err)
}
return nil
}
return fmt.Errorf("no packet has arrived from %q yet", programID)
}
// SendHighlight paints (or clears) one callsign in the given instance.
func (m *Manager) SendHighlight(programID, callsign string, bg, fg *RGB, lastPeriodOnly bool) error {
return m.sendToInstance(programID, EncodeHighlight(programID, callsign, bg, fg, lastPeriodOnly), "highlight")
}
// SendClearHighlights removes every highlighting instruction OpsLog installed
// in the instance. "CLEARALL!" is the protocol's own magic callsign for it.
func (m *Manager) SendClearHighlights(programID string) error {
return m.sendToInstance(programID, EncodeHighlight(programID, "CLEARALL!", nil, nil, false), "clear-highlights")
}
// SendReplay asks the instance to resend its on-screen decodes.
func (m *Manager) SendReplay(programID string) error {
err := m.sendToInstance(programID, EncodeReplay(programID), "replay")
if err == nil {
applog.Printf("udp: replay requested from %q — its existing decodes will arrive marked not-new", programID)
}
return err
}
// Instances lists every program id a packet has arrived from, for "clear the
// highlights everywhere" and the startup replay.
func (m *Manager) Instances() []string {
m.mu.Lock()
servers := make([]*Server, 0, len(m.inbound))
for _, s := range m.inbound {
servers = append(servers, s)
}
m.mu.Unlock()
seen := map[string]struct{}{}
var out []string
for _, s := range servers {
s.mu.Lock()
for id := range s.lastFrom {
if _, dup := seen[id]; !dup {
seen[id] = struct{}{}
out = append(out, id)
}
}
s.mu.Unlock()
}
return out
}
+60
View File
@@ -0,0 +1,60 @@
// Package kpa talks to the Elecraft KPA500 and KPA1500 amplifiers.
//
// One package for both: they share the Elecraft command set — ASCII, a caret
// prefix, a semicolon terminator, case-insensitive on the way in and upper case
// on the way back — which is the same family as the K3/K4 panel in
// internal/cat. What differs between the two models is the transport and which
// commands exist, not the grammar.
//
// # Transports
//
// KPA500: serial only.
//
// KPA1500: serial, and a network server. Four things may be connected AT ONCE,
// which is unusual enough to design around — the Host PC USB port, the XCVR
// SERIAL connector when repurposed as a second host, ONE TCP client, and any
// number of UDP clients:
//
// - TCP on port 1500 (changed with ^CP). Single client. If the operator
// already has the Elecraft utility or another program on TCP, OpsLog will
// not get in, and the failure is a refused connection rather than anything
// the amplifier says.
// - UDP on the same port. Many clients, one command per packet and at most
// one response, and packets may be dropped under congestion — so it is the
// right choice for sharing the amplifier and the wrong one for a command
// that must not be missed.
//
// # Pacing
//
// There is NO flow control. The reference is explicit: pace commands by waiting
// for the response to the previous one. So this client is strictly
// question-and-answer on one connection, like the ACOM and SPE clients, rather
// than firing a poll cycle and sorting out the replies afterwards.
//
// # Serial speed
//
// 4800 to 230400, 8N1, set on the amplifier (^BR / SERIAL SPEED HOST) and not
// negotiated. Elecraft's own utility finds it by sending bare semicolons at
// each speed until something answers — worth copying if operators turn up with
// amplifiers whose speed they do not know.
//
// # What is settled, and how
//
// From the KPA1500 Programming Reference:
//
// - ^SW is the SWR IN TENTHS. "123 is 12.3:1", so ^SW015 is 1.5:1. This was
// first taken from Hamlib's backend and is now confirmed by the document,
// which matters more than it sounds: a wrongly scaled SWR bar reports a
// good match on a bad antenna.
// - ^WS returns forward power AND SWR together, ^VI returns PA voltage AND
// current together. Two round trips instead of four on the link the display
// depends on while the operator is transmitting.
// - ^SF returns the fault log: index, fault code, a short name in quotes, a
// timestamp, and fault-specific values. ^FC describes the codes.
//
// # Not touched
//
// ^TX simulates a KEY IN — it makes the amplifier transmit from software — and
// ^ON0 switches the main supplies off. Neither belongs on a poll loop or behind
// a button that can be pressed by accident.
package kpa
+435
View File
@@ -0,0 +1,435 @@
package kpa
// The client: one connection, strict question-and-answer, a cached status.
//
// Shaped like internal/acom and internal/spe so a third amplifier is the same
// thing to read — but the traffic is the opposite kind. Those two are told to
// stream and are then listened to; this one is asked, and answers. The
// reference is explicit that there is no flow control and that commands are
// paced by waiting for the previous reply, so nothing here ever has two
// questions outstanding.
import (
"bufio"
"fmt"
"io"
"net"
"strings"
"sync"
"time"
"go.bug.st/serial"
"hamlog/internal/applog"
)
const (
dialTimeout = 5 * time.Second
ioTimeout = 2 * time.Second
// pollInterval is the fast cycle: forward power, SWR, and whether a fault has
// appeared. Four times a second is enough for a bar that is read while
// talking, and it is four round trips a second on a link with no flow
// control — faster buys nothing and costs the set commands their latency.
pollInterval = 250 * time.Millisecond
// slowEvery is how many fast cycles pass between the readings that do not
// move: mode, band, temperature, supply. Once a second.
slowEvery = 4
)
// Status is what the panel polls.
type Status struct {
Connected bool `json:"connected"`
Transport string `json:"transport"` // "serial" | "tcp"
Model string `json:"model,omitempty"`
LastError string `json:"last_error,omitempty"`
// PowerOn is the main supplies (^ON), Operate is OPERATE vs STANDBY (^OS).
// They are different questions: an amplifier can be switched on and in
// standby, which is the normal state between overs.
PowerOn bool `json:"power_on"`
Operate bool `json:"operate"`
FwdW int `json:"fwd_w"`
SWR float64 `json:"swr"`
VoltV float64 `json:"volt_v"`
CurA int `json:"cur_a"`
TempC int `json:"temp_c"`
Band string `json:"band,omitempty"`
// Tuning is the ATU mid-cycle (^TP), so a panel can say so rather than
// showing a wild SWR and a power reading nobody should act on.
Tuning bool `json:"tuning"`
// Fault is the current fault code and its meaning. A fault puts the
// amplifier in STANDBY by itself, so it is the first thing to show.
FaultCode int `json:"fault_code"`
FaultText string `json:"fault_text,omitempty"`
}
// Config selects the model and how to reach it.
type Config struct {
Model string // "KPA500" | "KPA1500"
Transport string // "serial" | "tcp"
ComPort string // serial
Baud int // serial: 4800…230400, set on the amplifier and not negotiated
Host string // tcp (KPA1500 only)
Port int // tcp, default 1500
}
type Client struct {
cfg Config
mu sync.Mutex // serialises the connection: one question at a time
conn io.ReadWriteCloser
rd *bufio.Reader
skipTP bool // ^TP went unanswered once — a KPA500, no ATU; never ask again
statusMu sync.RWMutex
status Status
stop chan struct{}
running bool
}
// New builds a client. Nothing is opened until Start.
func New(cfg Config) *Client {
if cfg.Baud <= 0 {
cfg.Baud = 38400
}
if cfg.Port <= 0 {
cfg.Port = 1500
}
if strings.TrimSpace(cfg.Model) == "" {
cfg.Model = "KPA1500"
}
c := &Client{cfg: cfg, stop: make(chan struct{})}
c.status.Transport = cfg.Transport
c.status.Model = strings.ToUpper(strings.TrimSpace(cfg.Model))
return c
}
func (c *Client) Start() error {
if c.running {
return nil
}
c.running = true
go c.pollLoop()
return nil
}
func (c *Client) Stop() {
if !c.running {
return
}
c.running = false
close(c.stop)
c.mu.Lock()
c.dropLocked()
c.mu.Unlock()
}
func (c *Client) GetStatus() Status {
c.statusMu.RLock()
defer c.statusMu.RUnlock()
return c.status
}
func (c *Client) setErr(msg string) {
c.statusMu.Lock()
was := c.status.LastError
c.status.Connected = false
c.status.LastError = msg
c.statusMu.Unlock()
// Logged on CHANGE only: a disconnected amplifier is polled four times a
// second, and the log is where a hardware problem is diagnosed hours later.
if msg != "" && msg != was {
applog.Printf("kpa: %s", msg)
}
}
// dropLocked closes the connection. Caller holds c.mu.
func (c *Client) dropLocked() {
if c.conn != nil {
_ = c.conn.Close()
c.conn = nil
c.rd = nil
}
}
// connectLocked opens the transport. Caller holds c.mu.
func (c *Client) connectLocked() error {
if c.conn != nil {
return nil
}
switch strings.ToLower(strings.TrimSpace(c.cfg.Transport)) {
case "tcp":
if strings.TrimSpace(c.cfg.Host) == "" {
return fmt.Errorf("no address configured for the amplifier")
}
addr := net.JoinHostPort(c.cfg.Host, fmt.Sprint(c.cfg.Port))
conn, err := net.DialTimeout("tcp", addr, dialTimeout)
if err != nil {
// Named for what it usually is. The KPA1500 accepts ONE TCP client,
// so the common failure is not a wrong address but the Elecraft
// utility already holding the socket — and "connection refused"
// sends an operator looking at their network instead.
return fmt.Errorf("cannot reach the amplifier on %s: %w (it accepts a single TCP connection — close the Elecraft utility or any other program using it)", addr, err)
}
c.conn = conn
default:
if strings.TrimSpace(c.cfg.ComPort) == "" {
return fmt.Errorf("no serial port configured for the amplifier")
}
p, err := serial.Open(c.cfg.ComPort, &serial.Mode{BaudRate: c.cfg.Baud})
if err != nil {
return fmt.Errorf("cannot open %s: %w", c.cfg.ComPort, err)
}
// The KPA500 is POWER-CONTROLLED by these lines: the Elecraft utility
// switches the amplifier on by raising them. Held asserted, once, and
// never touched again — reconnect cycles that toggled them were
// switching a KPA500 OFF twenty seconds after its operator pressed
// nothing but Standby.
_ = p.SetDTR(true)
_ = p.SetRTS(true)
_ = p.SetReadTimeout(ioTimeout)
c.conn = p
}
c.rd = bufio.NewReader(c.conn)
applog.Printf("kpa: connected to the %s", c.status.Model)
return nil
}
// ask sends one command and reads its answer.
//
// The whole exchange is under the lock: with no flow control, two questions in
// flight means two answers to sort out, and the only thing distinguishing them
// is the prefix — which is exactly what payload() has to reject when it
// happens.
func (c *Client) ask(cmd string) (string, error) {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.connectLocked(); err != nil {
return "", err
}
if tc, ok := c.conn.(net.Conn); ok {
_ = tc.SetDeadline(time.Now().Add(ioTimeout))
}
if _, err := c.conn.Write([]byte(cmd)); err != nil {
c.dropLocked()
return "", fmt.Errorf("writing %s: %w", cmd, err)
}
// Answers end with a semicolon and nothing else does, so the terminator is
// the frame.
line, err := c.rd.ReadString(';')
if err != nil {
// NOT dropped. A command this model simply does not know (^TP is the
// KPA1500's ATU — a KPA500 never answers it) is silence, not a dead
// link, and dropping here tore the connection down on every slow poll
// cycle: two seconds of stalled commands, a reconnect, and a DTR
// toggle the amplifier read as the off switch. Nothing arrived, so
// nothing is left to desynchronise the next exchange. Write errors —
// the genuinely dead link — still drop, above.
return "", fmt.Errorf("no answer to %s: %w", cmd, err)
}
return strings.TrimSpace(line), nil
}
// send is a SET: written, and not answered. The reference says SET commands do
// not generally produce a response, so waiting for one would stall the poll
// loop for a whole timeout every time the operator pressed a button.
func (c *Client) send(cmd string) error {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.connectLocked(); err != nil {
return err
}
if tc, ok := c.conn.(net.Conn); ok {
_ = tc.SetDeadline(time.Now().Add(ioTimeout))
}
if _, err := c.conn.Write([]byte(cmd)); err != nil {
c.dropLocked()
return fmt.Errorf("writing %s: %w", cmd, err)
}
applog.Printf("kpa: → %s", cmd)
return nil
}
// Operate puts the amplifier in OPERATE (true) or STANDBY (false).
//
// Worth knowing, and worth saying in the UI: from firmware 01.41 onwards,
// going to OPERATE also CLEARS the current fault — every one except
// temperature, which clears by cooling. So this button is the way out of a
// fault as well as the way into transmit.
func (c *Client) Operate(on bool) error {
if on {
return c.send("^OS1;")
}
return c.send("^OS0;")
}
// ClearFault clears the current fault without changing mode (^FLC).
func (c *Client) ClearFault() error { return c.send("^FLC;") }
// PowerOn switches the main supplies on or off (^ON1 / ^ON0).
//
// Off is a real power-down, not standby, and the way back on over the network
// is Wake-on-LAN or the front panel — so a caller should be asking the operator
// first. The sleeping microcontroller does answer ^ON while the supplies are
// off, which is why "off" is a state this can report rather than a silence.
func (c *Client) PowerOn(on bool) error {
if on {
return c.send("^ON1;")
}
return c.send("^ON0;")
}
// Tune starts an ATU tune cycle (^FT). It needs drive from the transceiver.
func (c *Client) Tune() error { return c.send("^FT;") }
// pollLoop keeps the status fresh, reconnecting as needed.
func (c *Client) pollLoop() {
t := time.NewTicker(pollInterval)
defer t.Stop()
var n uint64
for {
select {
case <-c.stop:
return
case <-t.C:
c.pollOnce(n)
n++
}
}
}
func (c *Client) pollOnce(n uint64) {
// Forward power and SWR in ONE exchange (^WS), which is why that command
// exists and why the two are not asked separately.
reply, err := c.ask("^WS;")
if err != nil {
c.setErr(err.Error())
return
}
w, swr, err := parseWS(reply)
if err != nil {
c.setErr(err.Error())
return
}
c.statusMu.Lock()
c.status.Connected = true
c.status.LastError = ""
c.status.FwdW, c.status.SWR = w, swr
c.statusMu.Unlock()
// The fault, every cycle: it puts the amplifier in standby by itself, and an
// operator watching a power bar needs to know why it stopped moving.
if reply, err := c.ask("^FL;"); err == nil {
if code, err := parseFault(reply); err == nil {
c.statusMu.Lock()
was := c.status.FaultCode
c.status.FaultCode = code
c.status.FaultText = FaultName(code)
c.statusMu.Unlock()
if code != was && code != 0 {
applog.Printf("kpa: FAULT %02X — %s", code, FaultName(code))
}
}
}
if n%slowEvery != 0 {
return
}
// The readings that do not move fast. Each is optional: an older firmware or
// a KPA500 that does not know one of these must not take the rest down with
// it, so a failure here leaves the previous value standing.
if reply, err := c.ask("^OS;"); err == nil {
if v, err := parseInt(reply, "^OS"); err == nil {
c.statusMu.Lock()
c.status.Operate = v == 1
c.statusMu.Unlock()
}
}
if reply, err := c.ask("^ON;"); err == nil {
if v, err := parseInt(reply, "^ON"); err == nil {
c.statusMu.Lock()
c.status.PowerOn = v == 1
c.statusMu.Unlock()
}
}
if reply, err := c.ask("^VI;"); err == nil {
if v, a, err := parseVI(reply); err == nil {
c.statusMu.Lock()
c.status.VoltV, c.status.CurA = v, a
c.statusMu.Unlock()
}
}
if reply, err := c.ask("^TM;"); err == nil {
if v, err := parseInt(reply, "^TM"); err == nil {
c.statusMu.Lock()
c.status.TempC = v
c.statusMu.Unlock()
}
}
if reply, err := c.ask("^BN;"); err == nil {
if v, err := parseInt(reply, "^BN"); err == nil {
c.statusMu.Lock()
c.status.Band = BandName(v)
c.statusMu.Unlock()
}
}
if c.skipTP {
return
}
if reply, err := c.ask("^TP;"); err == nil {
if v, err := parseInt(reply, "^TP"); err == nil {
c.statusMu.Lock()
c.status.Tuning = v == 1
c.statusMu.Unlock()
}
} else {
// One silence is the model's answer for good: a KPA500 has no ATU and
// will never answer ^TP — asking again every cycle cost a two-second
// stall each time.
c.skipTP = true
applog.Printf("kpa: ^TP unanswered — no ATU on this model, not asking again")
}
}
// SetBand puts the amplifier on a band by its ADIF name.
//
// The KPA takes its band from the transceiver on its own XCVR connector, but it
// also accepts ^BN — so OpsLog can simply say it on the link it is already
// using. That is worth knowing: an Acom has no such command, which is why
// following it needs a second serial port and a transceiver emulator answering
// its polls (internal/catemu). None of that applies here.
//
// Sent only when it CHANGES. Repeating the current band four times a second
// would be traffic on a link with no flow control, in exchange for nothing.
func (c *Client) SetBand(adifBand string) error {
n, ok := bandNumber(adifBand)
if !ok {
// Not an error the operator should see: the KPA covers 160-6 m, and
// tuning to 23 cm is not a fault, it is simply not this amplifier's
// business.
return nil
}
c.statusMu.Lock()
same := c.status.Band == adifBand
c.statusMu.Unlock()
if same {
return nil
}
return c.send(fmt.Sprintf("^BN%02d;", n))
}
// bandNumber is BandName backwards.
func bandNumber(adifBand string) (int, bool) {
b := strings.ToLower(strings.TrimSpace(adifBand))
for n, name := range bandNames {
if name == b {
return n, true
}
}
return 0, false
}
+157
View File
@@ -0,0 +1,157 @@
package kpa
// Decoding the amplifier's answers.
//
// Every format here is quoted from the KPA1500 Programming Reference, with the
// document's own example kept in the test next door. That is the whole
// discipline: a meter decoded from a guess reports a good match on a bad
// antenna, and nobody finds out until something is damaged.
import (
"fmt"
"strconv"
"strings"
)
// payload strips the leading "^", the command letters and the trailing ";",
// leaving the value. Returns false when the answer is not for this command —
// which happens on a shared serial line and on the first read after a
// reconnect, where a stale reply is still in flight.
func payload(reply, cmd string) (string, bool) {
r := strings.TrimSpace(reply)
r = strings.TrimSuffix(r, ";")
r = strings.TrimPrefix(r, "^")
cmd = strings.TrimSuffix(strings.TrimPrefix(cmd, "^"), ";")
if !strings.HasPrefix(strings.ToUpper(r), strings.ToUpper(cmd)) {
return "", false
}
return strings.TrimSpace(r[len(cmd):]), true
}
// parseWS reads forward power and SWR from one answer.
//
// ^WS1204 014; → 1204 W, SWR 1.4
//
// The watts field is FOUR digits on a KPA1500 and THREE on a KPA500 — the
// reference says so where it explains that ^WS exists for KPA500 compatibility
// — so the split is on the space and not on a width. The SWR is in tenths, the
// same units as everywhere else in this protocol.
func parseWS(reply string) (watts int, swr float64, err error) {
v, ok := payload(reply, "^WS")
if !ok {
return 0, 0, fmt.Errorf("not a ^WS answer: %q", reply)
}
f := strings.Fields(v)
if len(f) != 2 {
return 0, 0, fmt.Errorf("^WS wants two fields, got %q", v)
}
w, err1 := strconv.Atoi(f[0])
s, err2 := strconv.Atoi(f[1])
if err1 != nil || err2 != nil {
return 0, 0, fmt.Errorf("^WS not numeric: %q", v)
}
return w, float64(s) / 10, nil
}
// parseVI reads the PA supply voltage and current.
//
// ^VI513 061; → 51.3 V, 61 A
//
// Volts in TENTHS, amps whole. Two different scales in one answer, which is
// exactly the kind of detail that is wrong when it is assumed.
func parseVI(reply string) (volts float64, amps int, err error) {
v, ok := payload(reply, "^VI")
if !ok {
return 0, 0, fmt.Errorf("not a ^VI answer: %q", reply)
}
f := strings.Fields(v)
if len(f) != 2 {
return 0, 0, fmt.Errorf("^VI wants two fields, got %q", v)
}
dv, err1 := strconv.Atoi(f[0])
a, err2 := strconv.Atoi(f[1])
if err1 != nil || err2 != nil {
return 0, 0, fmt.Errorf("^VI not numeric: %q", v)
}
return float64(dv) / 10, a, nil
}
// parseInt reads the plain numeric answers: ^TMxxx (°C), ^PCnnn (A),
// ^BNbb (band number), ^OSx, ^ONx, ^TPx.
func parseInt(reply, cmd string) (int, error) {
v, ok := payload(reply, cmd)
if !ok {
return 0, fmt.Errorf("not a %s answer: %q", cmd, reply)
}
n, err := strconv.Atoi(strings.TrimSpace(v))
if err != nil {
return 0, fmt.Errorf("%s not numeric: %q", cmd, v)
}
return n, nil
}
// parseFault reads ^FLhh — TWO HEX DIGITS, not decimal. Fault 90 is reflected
// power and fault 91 is "antenna not connected"; read as decimal they would be
// 144 and 145 and match nothing in the table.
func parseFault(reply string) (int, error) {
v, ok := payload(reply, "^FL")
if !ok {
return 0, fmt.Errorf("not a ^FL answer: %q", reply)
}
n, err := strconv.ParseInt(strings.TrimSpace(v), 16, 32)
if err != nil {
return 0, fmt.Errorf("^FL not hex: %q", v)
}
return int(n), nil
}
// faultNames is the table from the reference, keyed by the hex code.
//
// Said in the operator's terms rather than the amplifier's: "the antenna is not
// connected" is a thing to go and fix, "fault 91" is a thing to go and look up.
var faultNames = map[int]string{
0x00: "no fault",
0x10: "watchdog timer reset",
0x20: "PA current too high",
0x40: "too hot — clears as it cools",
0x60: "drive power too high",
0x61: "gain too low for the drive",
0x70: "frequency outside a ham band",
0x80: "50 V supply out of range",
0x81: "5 V supply out of range",
0x82: "10 V supply out of range",
0x83: "12 V supply out of range",
0x84: "-12 V supply out of range",
0x85: "no LPF board supply detected",
0x90: "reflected power too high",
0x91: "SWR very high — antenna not connected?",
0x92: "the ATU found no match",
0xB0: "dissipated power too high",
0xC0: "forward power too high",
0xC1: "forward power too high for this ATU setting",
0xF0: "gain too high for the drive",
}
// FaultName describes a fault code, or says the code itself when the firmware
// reports one this table does not know — a newer amplifier must not be able to
// produce a blank explanation.
func FaultName(code int) string {
if code == 0 {
return ""
}
if s, ok := faultNames[code]; ok {
return s
}
return fmt.Sprintf("fault %02X", code)
}
// bandNames maps ^BN to the ADIF band. The numbering is the K3/K4 one, which is
// why it is worth writing down: it is not frequency order beyond 6 m and there
// is no arithmetic that produces it.
var bandNames = map[int]string{
0: "160m", 1: "80m", 2: "60m", 3: "40m", 4: "30m", 5: "20m",
6: "17m", 7: "15m", 8: "12m", 9: "10m", 10: "6m",
}
// BandName is the ADIF band for a ^BN number, or "" when unknown.
func BandName(n int) string { return bandNames[n] }
+104
View File
@@ -0,0 +1,104 @@
package kpa
import "testing"
// The reference's own examples, kept as the test. Every one of these strings is
// quoted from the KPA1500 Programming Reference rather than invented here, so a
// change that breaks the decoding fails against the document.
func TestParseTheDocumentedExamples(t *testing.T) {
t.Run("^WS — forward power and SWR", func(t *testing.T) {
w, swr, err := parseWS("^WS1204 014;")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if w != 1204 || swr != 1.4 {
t.Errorf("got %d W, SWR %.1f; want 1204 W, SWR 1.4", w, swr)
}
})
// A KPA500 sends three digits for the watts. The split is on the space, so
// the same code reads both amplifiers.
t.Run("^WS from a KPA500 — three digits", func(t *testing.T) {
w, swr, err := parseWS("^WS480 021;")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if w != 480 || swr != 2.1 {
t.Errorf("got %d W, SWR %.1f; want 480 W, SWR 2.1", w, swr)
}
})
t.Run("^VI — volts in tenths, amps whole", func(t *testing.T) {
v, a, err := parseVI("^VI513 061;")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if v != 51.3 || a != 61 {
t.Errorf("got %.1f V, %d A; want 51.3 V, 61 A", v, a)
}
})
t.Run("^TM — heat sink temperature", func(t *testing.T) {
c, err := parseInt("^TM045;", "^TM")
if err != nil || c != 45 {
t.Errorf("got %d, %v; want 45", c, err)
}
})
t.Run("^OS — operate or standby", func(t *testing.T) {
for reply, want := range map[string]int{"^OS0;": 0, "^OS1;": 1} {
got, err := parseInt(reply, "^OS")
if err != nil || got != want {
t.Errorf("%s → %d, %v; want %d", reply, got, err, want)
}
}
})
t.Run("^BN — the K3 band numbering", func(t *testing.T) {
n, err := parseInt("^BN05;", "^BN")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got := BandName(n); got != "20m" {
t.Errorf("^BN05 → %q, want 20m", got)
}
if got := BandName(10); got != "6m" {
t.Errorf("^BN10 → %q, want 6m", got)
}
})
}
// ^FL is HEX. Read as decimal, 90 and 91 — reflected power and "antenna not
// connected" — become 144 and 145 and match nothing at all, so the amplifier
// would be shut down by a fault OpsLog could not name.
func TestFaultCodesAreHex(t *testing.T) {
code, err := parseFault("^FL91;")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if code != 0x91 {
t.Fatalf("^FL91 → %d, want %d (0x91)", code, 0x91)
}
if name := FaultName(code); name == "" || name == "fault 91" {
t.Errorf("0x91 should be named, got %q", name)
}
if got := FaultName(0); got != "" {
t.Errorf("no fault should be empty, got %q", got)
}
// A code from a firmware newer than this table still says something.
if got := FaultName(0xAB); got != "fault AB" {
t.Errorf("unknown code → %q, want \"fault AB\"", got)
}
}
// Answers to somebody else's question are refused rather than misread. On a
// serial line shared with the amplifier's own utility, or on the first read
// after a reconnect, a stale reply is still in flight.
func TestPayloadRefusesAnotherCommandsAnswer(t *testing.T) {
if _, _, err := parseWS("^VI513 061;"); err == nil {
t.Error("a ^VI answer was accepted as ^WS")
}
if _, err := parseInt("^TM045;", "^PC"); err == nil {
t.Error("a ^TM answer was accepted as ^PC")
}
}
+58
View File
@@ -0,0 +1,58 @@
package qso
import "testing"
// The colour of a matrix cell is a claim about what the operator still needs,
// and it was wrong for several releases: a callsign worked and not confirmed
// outranked an entity CONFIRMED on the same band and mode, so a slot that was
// finished showed as unfinished.
//
// Reported by VK4DX with the case that names itself: YB confirmed on 20m
// digital, shown blue, because one unconfirmed YB station had also been worked
// there.
func TestBandStatusConfirmedOutranksWorked(t *testing.T) {
cases := []struct {
name string
callWorked, callConfirmed, entityConfirm bool
want string
}{
{"entity worked only", false, false, false, "dxcc_w"},
{"this call worked, nothing confirmed", true, false, false, "call_w"},
// The regression, in one line.
{"entity confirmed, this call worked but not confirmed", true, false, true, "dxcc_c"},
{"entity confirmed, this call not worked here", false, false, true, "dxcc_c"},
{"this call confirmed", true, true, true, "call_c"},
// A confirmed contact with this call implies it was worked, but the flags
// arrive from separate SQL aggregates and nothing guarantees the pair.
{"call confirmed without the worked flag", false, true, true, "call_c"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got := bandStatusNames[bandStatusCode(c.callWorked, c.callConfirmed, c.entityConfirm)]
if got != c.want {
t.Errorf("bandStatusCode(worked=%v, callConf=%v, entityConf=%v) = %s, want %s",
c.callWorked, c.callConfirmed, c.entityConfirm, got, c.want)
}
})
}
}
// The ladder itself, stated once: every confirmed code must beat every worked
// code. A future edit that reorders the constants fails here rather than in a
// screenshot from an operator.
func TestBandStatusLadderPutsConfirmedAbove(t *testing.T) {
for _, worked := range []int{stDxccW, stCallW} {
for _, confirmed := range []int{stDxccC, stCallC} {
if confirmed <= worked {
t.Errorf("%s (%d) does not outrank %s (%d)",
bandStatusNames[confirmed], confirmed, bandStatusNames[worked], worked)
}
}
}
if stCallC <= stDxccC {
t.Error("call_c must outrank dxcc_c: the callsign is the more specific claim")
}
if stCallW <= stDxccW {
t.Error("call_w must outrank dxcc_w for the same reason")
}
}
+384 -93
View File
@@ -722,15 +722,14 @@ func (r *Repo) MarkUploadedBatch(ctx context.Context, statusCol, dateCol, date s
if len(ids) == 0 { if len(ids) == 0 {
return nil return nil
} }
ph := strings.TrimSuffix(strings.Repeat("?,", len(ids)), ",") now := db.NowISO()
args := make([]any, 0, len(ids)+2) _, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
args = append(args, date, db.NowISO()) args := append([]any{date, now}, idArgs...)
for _, id := range ids { _, err := r.db.ExecContext(ctx,
args = append(args, id) `UPDATE qso SET `+statusCol+` = 'Y', `+dateCol+` = ?, updated_at = ? WHERE id IN (`+ph+`)`,
} args...)
_, err := r.db.ExecContext(ctx, return 0, err
`UPDATE qso SET `+statusCol+` = 'Y', `+dateCol+` = ?, updated_at = ? WHERE id IN (`+ph+`)`, })
args...)
if err != nil { if err != nil {
return fmt.Errorf("mark uploaded batch (%d): %w", len(ids), err) return fmt.Errorf("mark uploaded batch (%d): %w", len(ids), err)
} }
@@ -868,6 +867,73 @@ var bulkEditableCols = map[string]bool{
// BulkSetField sets one whitelisted column to value on every listed QSO in a // BulkSetField sets one whitelisted column to value on every listed QSO in a
// single statement. value "" clears the field. Returns rows affected. // single statement. value "" clears the field. Returns rows affected.
// bulkEditableIntCols are the NUMERIC columns the bulk editor may touch. Their
// own path, not the text one: the columns are nullable integers, and while
// SQLite would coerce "14" quietly, a shared MySQL logbook would not — and an
// empty string is NULL here, never "".
// bulkByIDChunks runs one UPDATE per slice of ids, small enough for SQLite's
// bound-variable cap: the single IN (…) with one placeholder per id worked at
// 10 000 QSOs and failed at 168 000 with "too many SQL variables". Each call
// gets the placeholder string and the id arguments for its slice; affected
// rows are summed. 500 per statement keeps every backend far from any limit
// while costing a few hundred statements on the largest logs.
func bulkByIDChunks(ctx context.Context, ids []int64, run func(ph string, idArgs []any) (int64, error)) (int64, error) {
const chunk = 500
var total int64
for start := 0; start < len(ids); start += chunk {
end := start + chunk
if end > len(ids) {
end = len(ids)
}
part := ids[start:end]
ph := strings.Repeat("?,", len(part)-1) + "?"
args := make([]any, len(part))
for i, id := range part {
args[i] = id
}
n, err := run(ph, args)
if err != nil {
return total, err
}
total += n
}
return total, nil
}
var bulkEditableIntCols = map[string]bool{
"my_dxcc": true,
"my_cq_zone": true,
"my_itu_zone": true,
}
// BulkSetIntField sets one integer column across the ids; v nil clears it.
func (r *Repo) BulkSetIntField(ctx context.Context, ids []int64, column string, v *int) (int64, error) {
if !bulkEditableIntCols[column] {
return 0, fmt.Errorf("field %q is not bulk-editable", column)
}
if len(ids) == 0 {
return 0, nil
}
var val any
if v != nil {
val = *v
}
now := db.NowISO()
n, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
args := append([]any{val, now}, idArgs...)
res, err := r.db.ExecContext(ctx,
"UPDATE qso SET "+column+" = ?, updated_at = ? WHERE id IN ("+ph+")", args...)
if err != nil {
return 0, err
}
return res.RowsAffected()
})
if err != nil {
return n, fmt.Errorf("bulk set %s: %w", column, err)
}
return n, nil
}
func (r *Repo) BulkSetField(ctx context.Context, ids []int64, column, value string) (int64, error) { func (r *Repo) BulkSetField(ctx context.Context, ids []int64, column, value string) (int64, error) {
if !bulkEditableCols[column] { if !bulkEditableCols[column] {
return 0, fmt.Errorf("field %q is not bulk-editable", column) return 0, fmt.Errorf("field %q is not bulk-editable", column)
@@ -875,13 +941,6 @@ func (r *Repo) BulkSetField(ctx context.Context, ids []int64, column, value stri
if len(ids) == 0 { if len(ids) == 0 {
return 0, nil return 0, nil
} }
ph := make([]string, len(ids))
args := make([]any, 0, len(ids)+2)
args = append(args, value, db.NowISO())
for i, id := range ids {
ph[i] = "?"
args = append(args, id)
}
set := column + " = ?, updated_at = ?" set := column + " = ?, updated_at = ?"
if column == "mode" { if column == "mode" {
// A submode belongs to the mode it was recorded under. Left behind, it // A submode belongs to the mode it was recorded under. Left behind, it
@@ -890,13 +949,19 @@ func (r *Repo) BulkSetField(ctx context.Context, ids []int64, column, value stri
// only outcome that leaves the row meaning what the operator asked for. // only outcome that leaves the row meaning what the operator asked for.
set += ", submode = ''" set += ", submode = ''"
} }
res, err := r.db.ExecContext(ctx, now := db.NowISO()
`UPDATE qso SET `+set+` WHERE id IN (`+strings.Join(ph, ",")+`)`, n, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
args...) args := append([]any{value, now}, idArgs...)
res, err := r.db.ExecContext(ctx,
`UPDATE qso SET `+set+` WHERE id IN (`+ph+`)`, args...)
if err != nil {
return 0, err
}
return res.RowsAffected()
})
if err != nil { if err != nil {
return 0, fmt.Errorf("bulk set %s: %w", column, err) return n, fmt.Errorf("bulk set %s: %w", column, err)
} }
n, _ := res.RowsAffected()
return n, nil return n, nil
} }
@@ -957,26 +1022,26 @@ func (r *Repo) BulkSetExtra(ctx context.Context, ids []int64, adifKey, value str
if len(ids) == 0 { if len(ids) == 0 {
return 0, nil return 0, nil
} }
ph := make([]string, len(ids)) head := []any{}
args := make([]any, 0, len(ids)+2)
expr := `json_set(COALESCE(extras_json, '{}'), '$.` + adifKey + `', ?)` expr := `json_set(COALESCE(extras_json, '{}'), '$.` + adifKey + `', ?)`
if value == "" { if value == "" {
expr = `json_remove(COALESCE(extras_json, '{}'), '$.` + adifKey + `')` expr = `json_remove(COALESCE(extras_json, '{}'), '$.` + adifKey + `')`
} else { } else {
args = append(args, value) head = append(head, value)
} }
args = append(args, db.NowISO()) head = append(head, db.NowISO())
for i, id := range ids { n, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
ph[i] = "?" args := append(append([]any{}, head...), idArgs...)
args = append(args, id) res, err := r.db.ExecContext(ctx,
} `UPDATE qso SET extras_json = `+expr+`, updated_at = ? WHERE id IN (`+ph+`)`, args...)
res, err := r.db.ExecContext(ctx, if err != nil {
`UPDATE qso SET extras_json = `+expr+`, updated_at = ? WHERE id IN (`+strings.Join(ph, ",")+`)`, return 0, err
args...) }
return res.RowsAffected()
})
if err != nil { if err != nil {
return 0, fmt.Errorf("bulk set extra %s: %w", adifKey, err) return n, fmt.Errorf("bulk set extra %s: %w", adifKey, err)
} }
n, _ := res.RowsAffected()
return n, nil return n, nil
} }
@@ -988,20 +1053,19 @@ func (r *Repo) BulkSetFrequency(ctx context.Context, ids []int64, freqHz int64,
if len(ids) == 0 { if len(ids) == 0 {
return 0, nil return 0, nil
} }
ph := make([]string, len(ids)) now := db.NowISO()
args := make([]any, 0, len(ids)+3) n, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
args = append(args, freqHz, band, db.NowISO()) args := append([]any{freqHz, band, now}, idArgs...)
for i, id := range ids { res, err := r.db.ExecContext(ctx,
ph[i] = "?" `UPDATE qso SET freq_hz = ?, band = ?, updated_at = ? WHERE id IN (`+ph+`)`, args...)
args = append(args, id) if err != nil {
} return 0, err
res, err := r.db.ExecContext(ctx, }
`UPDATE qso SET freq_hz = ?, band = ?, updated_at = ? WHERE id IN (`+strings.Join(ph, ",")+`)`, return res.RowsAffected()
args...) })
if err != nil { if err != nil {
return 0, fmt.Errorf("bulk set frequency: %w", err) return n, fmt.Errorf("bulk set frequency: %w", err)
} }
n, _ := res.RowsAffected()
return n, nil return n, nil
} }
@@ -1163,17 +1227,16 @@ func (r *Repo) DeleteMany(ctx context.Context, ids []int64) (int64, error) {
if len(ids) == 0 { if len(ids) == 0 {
return 0, nil return 0, nil
} }
ph := make([]string, len(ids)) n, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
args := make([]any, len(ids)) res, err := r.db.ExecContext(ctx, `DELETE FROM qso WHERE id IN (`+ph+`)`, idArgs...)
for i, id := range ids { if err != nil {
ph[i] = "?" return 0, err
args[i] = id }
} return res.RowsAffected()
res, err := r.db.ExecContext(ctx, `DELETE FROM qso WHERE id IN (`+strings.Join(ph, ",")+`)`, args...) })
if err != nil { if err != nil {
return 0, fmt.Errorf("delete qsos: %w", err) return n, fmt.Errorf("delete qsos: %w", err)
} }
n, _ := res.RowsAffected()
return n, nil return n, nil
} }
@@ -1663,27 +1726,42 @@ func (r *Repo) IterateByIDs(ctx context.Context, ids []int64, fn func(QSO) error
if len(ids) == 0 { if len(ids) == 0 {
return nil return nil
} }
ph := strings.TrimSuffix(strings.Repeat("?,", len(ids)), ",") // Chunked like every other by-ids statement (the one-placeholder-per-id IN
args := make([]any, len(ids)) // died at 168k with "too many SQL variables") — and because each chunk is
for i, id := range ids { // only locally ordered, the rows are collected and sorted once at the end
args[i] = id // so the chronological contract holds across chunks.
} var all []QSO
rows, err := r.db.QueryContext(ctx, _, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
`SELECT `+selectCols+` FROM qso WHERE id IN (`+ph+`) ORDER BY qso_date ASC, id ASC`, args...) rows, err := r.db.QueryContext(ctx,
`SELECT `+selectCols+` FROM qso WHERE id IN (`+ph+`)`, idArgs...)
if err != nil {
return 0, err
}
defer rows.Close()
for rows.Next() {
q, err := scanQSO(rows)
if err != nil {
return 0, err
}
all = append(all, q)
}
return 0, rows.Err()
})
if err != nil { if err != nil {
return fmt.Errorf("query qso: %w", err) return fmt.Errorf("query qso: %w", err)
} }
defer rows.Close() sort.Slice(all, func(i, j int) bool {
for rows.Next() { if !all[i].QSODate.Equal(all[j].QSODate) {
q, err := scanQSO(rows) return all[i].QSODate.Before(all[j].QSODate)
if err != nil {
return err
} }
return all[i].ID < all[j].ID
})
for _, q := range all {
if err := fn(q); err != nil { if err := fn(q); err != nil {
return err return err
} }
} }
return rows.Err() return nil
} }
// GridKey builds the lookup key for the worked-grid index. // GridKey builds the lookup key for the worked-grid index.
@@ -1895,19 +1973,109 @@ type WorkedBefore struct {
// Status grid driving the band×class matrix in the UI. One entry per // Status grid driving the band×class matrix in the UI. One entry per
// (band, class) where ANY QSO exists in this DXCC. Only the highest // (band, class) where ANY QSO exists in this DXCC. Only the highest
// status for that cell is kept (call_c > call_w > dxcc_c > dxcc_w). // status for that cell is kept (call_c > dxcc_c > call_w > dxcc_w —
// confirmed outranks worked).
BandStatus []BandStatus `json:"band_status"` BandStatus []BandStatus `json:"band_status"`
} }
// BandStatus is one cell in the worked-before grid. // BandStatus is one cell in the worked-before grid.
//
// Status is the single highest thing true of the cell, which is what colours
// it. Call is the SAME cell's answer to a different question — "have I worked
// THIS callsign here" — kept separately because the two are asked at the same
// moment and one was hiding the other.
//
// Chasing an expedition, an operator needs both: whether the slot is still
// missing for the entity (does this fill a DXCC hole) and whether this
// expedition has already been worked on it (would this be a dupe). A confirmed
// entity outranks a worked callsign in Status — correctly, for awards — so a
// slot worked with the DX yesterday can read "entity confirmed" and say nothing
// at all about yesterday.
type BandStatus struct { type BandStatus struct {
Band string `json:"band"` // ADIF lowercase band, e.g. "20m" Band string `json:"band"` // ADIF lowercase band, e.g. "20m"
Class string `json:"class"` // "PH" | "CW" | "DIG" Class string `json:"class"` // "PH" | "CW" | "DIG"
Status string `json:"status"` // "call_c" | "call_w" | "dxcc_c" | "dxcc_w" Status string `json:"status"` // "call_c" | "call_w" | "dxcc_c" | "dxcc_w"
// Call is "", "w" (worked with this callsign) or "c" (confirmed with it).
Call string `json:"call,omitempty"`
}
// Band-status codes, lowest first. The ORDER is the rule: a cell shows the
// highest that applies.
const (
stDxccW = iota // the entity was worked on this slot
stCallW // …and this callsign was one of them
stDxccC // the entity is CONFIRMED here
stCallC // …and by this callsign
)
// bandStatusNames maps those codes to what the UI colours by.
var bandStatusNames = [...]string{"dxcc_w", "call_w", "dxcc_c", "call_c"}
// bandStatusCode picks the status of one cell of the band × mode matrix.
//
// CONFIRMED OUTRANKS WORKED, and that is the whole of it. The ladder used to
// run call_c > call_w > dxcc_c > dxcc_w, so a callsign worked and not confirmed
// beat an entity confirmed on the same slot: an operator with YB confirmed on
// 20m digital saw that cell as "worked, not confirmed" because he had also
// worked one unconfirmed YB station there. The grid answers "what do I still
// need", and a confirmed entity needs nothing, whoever was worked afterwards.
//
// Taken as a MAXIMUM rather than as a run of assignments, which is how the
// later test came to overwrite the earlier one in the first place.
func bandStatusCode(callWorked, callConfirmed, entityConfirmed bool) int {
code := stDxccW // there is a row at all ⇒ the entity was worked here
raise := func(c int) {
if c > code {
code = c
}
}
if callWorked {
raise(stCallW)
}
if entityConfirmed {
raise(stDxccC)
}
if callConfirmed {
raise(stCallC)
}
return code
} }
// modeClass collapses ADIF modes into the three buckets DXers care about. // modeClass collapses ADIF modes into the three buckets DXers care about.
// Anything not voice and not CW is treated as digital. // Anything not voice and not CW is treated as digital.
// ModeClass is modeClass for callers outside the package — the watchlist
// judges slots at the same grain the cluster does.
func ModeClass(mode string) string { return modeClass(mode) }
// SlotRow is one (callsign, band, mode) triple from SlotsSince.
type SlotRow struct {
Callsign string
Band string
Mode string
}
// SlotsSince lists the slots of every contact made since the given instant —
// the contest watchlist's "worked today", where the day boundary lives in this
// query's bound and nowhere else.
func (r *Repo) SlotsSince(ctx context.Context, since time.Time) ([]SlotRow, error) {
rows, err := r.db.QueryContext(ctx,
"SELECT callsign, band, mode FROM qso WHERE qso_date >= ?",
since.UTC().Format(isoMillis))
if err != nil {
return nil, err
}
defer rows.Close()
var out []SlotRow
for rows.Next() {
var sr SlotRow
if err := rows.Scan(&sr.Callsign, &sr.Band, &sr.Mode); err != nil {
return nil, err
}
out = append(out, sr)
}
return out, rows.Err()
}
func modeClass(mode string) string { func modeClass(mode string) string {
switch strings.ToUpper(mode) { switch strings.ToUpper(mode) {
case "SSB", "USB", "LSB", "AM", "FM", "DIGITALVOICE", "PHONE": case "SSB", "USB", "LSB", "AM", "FM", "DIGITALVOICE", "PHONE":
@@ -2167,14 +2335,29 @@ func (r *Repo) WorkedBefore(ctx context.Context, callsign string, dxccHint int,
// ---- Per-(band, class) status grid ---- // ---- Per-(band, class) status grid ----
// One pass over every distinct (band, mode) in the DXCC, aggregating // One pass over every distinct (band, mode) in the DXCC, aggregating
// "did this call work it?" and "was anything confirmed?" via MAX. // "did this call work it?" and "was anything confirmed?" via MAX.
// Status precedence: call_c > call_w > dxcc_c > dxcc_w. // Status precedence: CONFIRMED OUTRANKS WORKED — call_c > dxcc_c > call_w >
// dxcc_w.
//
// It used to run call_c > call_w > dxcc_c > dxcc_w, which made a call worked
// and not confirmed outrank an entity confirmed on the same slot. Reported
// from a real log: YB confirmed on 20m digital showed BLUE, because that
// operator had also worked one unconfirmed YB station there. The cell said
// "not confirmed" about a slot that is confirmed.
//
// The grid answers "what do I still need on this band and mode", and for
// that question confirmation is the axis that matters: a confirmed entity
// needs nothing, whoever else was worked afterwards.
// The two per-callsign columns use the SAME predicate as the callsign count
// above, portable variants included: a cell that counts RI1FJL/1 in "worked
// with this call" and a header that does not would be two answers to one
// question.
// Filter NULL/empty band+mode rows — they'd create a NULL group key // Filter NULL/empty band+mode rows — they'd create a NULL group key
// that Scan into *string can't handle and would error out the whole // that Scan into *string can't handle and would error out the whole
// WorkedBefore call, blanking the matrix in the UI. // WorkedBefore call, blanking the matrix in the UI.
statusRows, err := r.db.QueryContext(ctx, ` statusRows, err := r.db.QueryContext(ctx, `
SELECT band, mode, SELECT band, mode,
MAX(CASE WHEN callsign = ? THEN 1 ELSE 0 END), MAX(CASE WHEN `+pred+` THEN 1 ELSE 0 END),
MAX(CASE WHEN callsign = ? MAX(CASE WHEN `+pred+`
AND (lotw_rcvd IN `+ConfirmedValues+` OR qsl_rcvd IN `+ConfirmedValues+` OR eqsl_rcvd IN `+ConfirmedValues+`) AND (lotw_rcvd IN `+ConfirmedValues+` OR qsl_rcvd IN `+ConfirmedValues+` OR eqsl_rcvd IN `+ConfirmedValues+`)
THEN 1 ELSE 0 END), THEN 1 ELSE 0 END),
MAX(CASE WHEN lotw_rcvd IN `+ConfirmedValues+` OR qsl_rcvd IN `+ConfirmedValues+` OR eqsl_rcvd IN `+ConfirmedValues+` MAX(CASE WHEN lotw_rcvd IN `+ConfirmedValues+` OR qsl_rcvd IN `+ConfirmedValues+` OR eqsl_rcvd IN `+ConfirmedValues+`
@@ -2183,18 +2366,14 @@ func (r *Repo) WorkedBefore(ctx context.Context, callsign string, dxccHint int,
WHERE dxcc = ? WHERE dxcc = ?
AND band IS NOT NULL AND band != '' AND band IS NOT NULL AND band != ''
AND mode IS NOT NULL AND mode != '' AND mode IS NOT NULL AND mode != ''
GROUP BY band, mode`, wb.Callsign, wb.Callsign, dxcc) GROUP BY band, mode`, append(append(append([]any{}, predArgs...), predArgs...), dxcc)...)
if err != nil { if err != nil {
return wb, fmt.Errorf("band status: %w", err) return wb, fmt.Errorf("band status: %w", err)
} }
type cellKey struct{ band, class string } type cellKey struct{ band, class string }
const (
stDxccW = 0
stDxccC = 1
stCallW = 2
stCallC = 3
)
best := map[cellKey]int{} best := map[cellKey]int{}
// The call's own answer per cell, independent of the ladder above.
callByCell := map[cellKey]string{}
for statusRows.Next() { for statusRows.Next() {
var band, mode string var band, mode string
var callW, callC, dxccConfirmed int var callW, callC, dxccConfirmed int
@@ -2202,26 +2381,26 @@ func (r *Repo) WorkedBefore(ctx context.Context, callsign string, dxccHint int,
statusRows.Close() statusRows.Close()
return wb, fmt.Errorf("scan band status: %w", err) return wb, fmt.Errorf("scan band status: %w", err)
} }
code := stDxccW // row exists ⇒ entity worked at minimum code := bandStatusCode(callW == 1, callC == 1, dxccConfirmed == 1)
if dxccConfirmed == 1 {
code = stDxccC
}
if callW == 1 {
code = stCallW
}
if callC == 1 {
code = stCallC
}
k := cellKey{band: band, class: modeClass(mode)} k := cellKey{band: band, class: modeClass(mode)}
if cur, ok := best[k]; !ok || code > cur { if cur, ok := best[k]; !ok || code > cur {
best[k] = code best[k] = code
} }
// Confirmed beats worked here too, and neither is ever erased by the
// entity: this is only ever about the callsign.
switch {
case callC == 1:
callByCell[k] = "c"
case callW == 1 && callByCell[k] == "":
callByCell[k] = "w"
}
} }
statusRows.Close() statusRows.Close()
codeStr := [...]string{"dxcc_w", "dxcc_c", "call_w", "call_c"} codeStr := bandStatusNames
for k, code := range best { for k, code := range best {
wb.BandStatus = append(wb.BandStatus, BandStatus{ wb.BandStatus = append(wb.BandStatus, BandStatus{
Band: k.band, Class: k.class, Status: codeStr[code], Band: k.band, Class: k.class, Status: codeStr[code],
Call: callByCell[k],
}) })
} }
return wb, nil return wb, nil
@@ -2478,10 +2657,20 @@ type EntitySlot struct {
// Modes/Slots key — pass GroupDigitalMode to collapse all digital modes into // Modes/Slots key — pass GroupDigitalMode to collapse all digital modes into
// one bucket. Callers must normalise their lookup mode the same way. // one bucket. Callers must normalise their lookup mode the same way.
func (r *Repo) EntitySlotMap(ctx context.Context, keyFor func(call string, storedDXCC int, country string) int, normMode func(string) string) (map[int]*EntitySlot, error) { func (r *Repo) EntitySlotMap(ctx context.Context, keyFor func(call string, storedDXCC int, country string) int, normMode func(string) string) (map[int]*EntitySlot, error) {
return r.EntitySlotMapPred(ctx, keyFor, normMode, "")
}
// EntitySlotMapPred is EntitySlotMap over only the QSOs matching pred — the
// confirmed-only ledger the "chase unconfirmed too" mode judges against.
func (r *Repo) EntitySlotMapPred(ctx context.Context, keyFor func(call string, storedDXCC int, country string) int, normMode func(string) string, pred string) (map[int]*EntitySlot, error) {
where := ""
if pred != "" {
where = " AND " + pred
}
rows, err := r.db.QueryContext(ctx, rows, err := r.db.QueryContext(ctx,
`SELECT callsign, coalesce(dxcc,0), lower(coalesce(country,'')), lower(band), upper(mode) FROM qso `SELECT callsign, coalesce(dxcc,0), lower(coalesce(country,'')), lower(band), upper(mode) FROM qso
WHERE band IS NOT NULL AND band != '' WHERE band IS NOT NULL AND band != ''
AND mode IS NOT NULL AND mode != ''`) AND mode IS NOT NULL AND mode != ''`+where)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -2531,8 +2720,18 @@ func (r *Repo) EntitySlotMap(ctx context.Context, keyFor func(call string, store
// One pass, used by the cluster spot colouring to flag "already worked this // One pass, used by the cluster spot colouring to flag "already worked this
// exact call" regardless of band/mode — Log4OM/RUMlogNG-style call highlight. // exact call" regardless of band/mode — Log4OM/RUMlogNG-style call highlight.
func (r *Repo) WorkedCallsigns(ctx context.Context) (map[string]struct{}, error) { func (r *Repo) WorkedCallsigns(ctx context.Context) (map[string]struct{}, error) {
return r.WorkedCallsignsPred(ctx, "")
}
// WorkedCallsignsPred restricts the callsign ledger to QSOs matching pred —
// the confirmed-prefix (WPX) chase reads its prefixes off this set.
func (r *Repo) WorkedCallsignsPred(ctx context.Context, pred string) (map[string]struct{}, error) {
where := ""
if pred != "" {
where = " AND " + pred
}
rows, err := r.db.QueryContext(ctx, rows, err := r.db.QueryContext(ctx,
`SELECT DISTINCT upper(callsign) FROM qso WHERE callsign != ''`) `SELECT DISTINCT upper(callsign) FROM qso WHERE callsign != ''`+where)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -2553,9 +2752,18 @@ func (r *Repo) WorkedCallsigns(ctx context.Context) (map[string]struct{}, error)
// the award package here). Only US-entity QSOs (DXCC 291/110/6) with a county // the award package here). Only US-entity QSOs (DXCC 291/110/6) with a county
// are considered. Empty keys (unresolvable state/county) are skipped. // are considered. Empty keys (unresolvable state/county) are skipped.
func (r *Repo) WorkedCountyKeys(ctx context.Context, keyFn func(state, cnty string) string) (map[string]struct{}, error) { func (r *Repo) WorkedCountyKeys(ctx context.Context, keyFn func(state, cnty string) string) (map[string]struct{}, error) {
return r.WorkedCountyKeysPred(ctx, keyFn, "")
}
// WorkedCountyKeysPred restricts the county ledger to QSOs matching pred.
func (r *Repo) WorkedCountyKeysPred(ctx context.Context, keyFn func(state, cnty string) string, pred string) (map[string]struct{}, error) {
where := ""
if pred != "" {
where = " AND " + pred
}
rows, err := r.db.QueryContext(ctx, rows, err := r.db.QueryContext(ctx,
`SELECT DISTINCT COALESCE(state,''), COALESCE(cnty,'') FROM qso `SELECT DISTINCT COALESCE(state,''), COALESCE(cnty,'') FROM qso
WHERE dxcc IN (291,110,6) AND cnty IS NOT NULL AND cnty != ''`) WHERE dxcc IN (291,110,6) AND cnty IS NOT NULL AND cnty != ''`+where)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -2573,6 +2781,38 @@ func (r *Repo) WorkedCountyKeys(ctx context.Context, keyFn func(state, cnty stri
return out, rows.Err() return out, rows.Err()
} }
// WorkedStateKeys returns the set of US states already worked, uppercased —
// the WAS ledger the cluster and decode panels judge NEW STATE against.
func (r *Repo) WorkedStateKeys(ctx context.Context) (map[string]struct{}, error) {
return r.WorkedStateKeysPred(ctx, "")
}
// WorkedStateKeysPred restricts the state ledger to QSOs matching pred.
func (r *Repo) WorkedStateKeysPred(ctx context.Context, pred string) (map[string]struct{}, error) {
where := ""
if pred != "" {
where = " AND " + pred
}
rows, err := r.db.QueryContext(ctx,
`SELECT DISTINCT UPPER(COALESCE(state,'')) FROM qso
WHERE dxcc IN (291,110,6) AND state IS NOT NULL AND state != ''`+where)
if err != nil {
return nil, err
}
defer rows.Close()
out := make(map[string]struct{}, 64)
for rows.Next() {
var st string
if err := rows.Scan(&st); err != nil {
return nil, err
}
if st != "" {
out[st] = struct{}{}
}
}
return out, rows.Err()
}
// CountQSLViaRouting counts the QSOs whose qsl_via holds a routing method // CountQSLViaRouting counts the QSOs whose qsl_via holds a routing method
// instead of a manager, per isRouting. // instead of a manager, per isRouting.
// //
@@ -2916,6 +3156,33 @@ func DedupeKey(callsign, qsoDateMinute, band, mode string) string {
return strings.ToUpper(callsign) + "|" + qsoDateMinute + "|" + strings.ToLower(band) + "|" + strings.ToUpper(mode) return strings.ToUpper(callsign) + "|" + qsoDateMinute + "|" + strings.ToLower(band) + "|" + strings.ToUpper(mode)
} }
// StationCallsigns lists the distinct station callsigns the logbook was worked
// under, upper-cased and without the blanks.
//
// Used to decide whether a downloaded confirmation belongs to THIS log at all:
// one LoTW account can hold several stations (a home call, a portable, an
// expedition), and a confirmation for a station this logbook has never used is
// somebody else's log — here, another profile's.
func (r *Repo) StationCallsigns(ctx context.Context) (map[string]bool, error) {
rows, err := r.db.QueryContext(ctx,
`SELECT DISTINCT COALESCE(station_callsign,'') FROM qso`)
if err != nil {
return nil, err
}
defer rows.Close()
out := map[string]bool{}
for rows.Next() {
var c string
if err := rows.Scan(&c); err != nil {
return nil, err
}
if c = strings.ToUpper(strings.TrimSpace(c)); c != "" {
out[c] = true
}
}
return out, rows.Err()
}
// DedupeKeyIDs returns a map of dedupe key → QSO id, for matching downloaded // DedupeKeyIDs returns a map of dedupe key → QSO id, for matching downloaded
// confirmations back to local QSOs. // confirmations back to local QSOs.
func (r *Repo) DedupeKeyIDs(ctx context.Context) (map[string]int64, error) { func (r *Repo) DedupeKeyIDs(ctx context.Context) (map[string]int64, error) {
@@ -3156,6 +3423,30 @@ type SlotStats struct {
// only way those two agree. // only way those two agree.
const ConfirmedValues = "('Y','V')" const ConfirmedValues = "('Y','V')"
// ConfirmSourcesPredicate builds the SQL that says "this QSO is confirmed",
// from the operator's chosen sources — the same choice the award engine's
// fixed three (LoTW, card, eQSL) used to hard-code. QRZ.com's confirmation is
// its download status; HRDLog has no confirmation field in ADIF at all, which
// is why it cannot be offered. Empty input falls back to the classic three.
func ConfirmSourcesPredicate(sources []string) string {
cols := map[string]string{
"lotw": "lotw_rcvd",
"card": "qsl_rcvd",
"eqsl": "eqsl_rcvd",
"qrz": "qrzcom_qso_download_status",
}
var parts []string
for _, src := range sources {
if col, ok := cols[strings.ToLower(strings.TrimSpace(src))]; ok {
parts = append(parts, col+" IN "+ConfirmedValues)
}
}
if len(parts) == 0 {
return "(lotw_rcvd IN " + ConfirmedValues + " OR qsl_rcvd IN " + ConfirmedValues + " OR eqsl_rcvd IN " + ConfirmedValues + ")"
}
return "(" + strings.Join(parts, " OR ") + ")"
}
// GetSlotStats computes the worked/confirmed slot and DXCC tallies in one pass. // GetSlotStats computes the worked/confirmed slot and DXCC tallies in one pass.
// "Confirmed" = LoTW or paper QSL received (the award-valid sources). // "Confirmed" = LoTW or paper QSL received (the award-valid sources).
func (r *Repo) GetSlotStats(ctx context.Context) (SlotStats, error) { func (r *Repo) GetSlotStats(ctx context.Context) (SlotStats, error) {
+12 -2
View File
@@ -44,7 +44,11 @@ import (
// Rig is what the server needs from OpsLog's CAT manager. An interface, so this // Rig is what the server needs from OpsLog's CAT manager. An interface, so this
// package stays testable without a radio and without importing internal/cat. // package stays testable without a radio and without importing internal/cat.
type Rig interface { type Rig interface {
Freq() int64 // current TX frequency in Hz, 0 if unknown // Freq is the frequency of the CURRENT VFO — where the operator is
// listening. Hamlib's "f" means the VFO in use, not the transmit one; the
// split TX frequency is a separate question, asked with "i". Answering "f"
// with the TX frequency invites a client to write it back as the dial.
Freq() int64 // current (RX) frequency in Hz, 0 if unknown
Mode() string // ADIF mode (SSB, CW, FT8…) Mode() string // ADIF mode (SSB, CW, FT8…)
Split() (bool, int64) // split on?, and the other VFO's frequency Split() (bool, int64) // split on?, and the other VFO's frequency
SetFreq(hz int64) error SetFreq(hz int64) error
@@ -242,6 +246,11 @@ func (s *Server) serve(c net.Conn) {
s.releasePTT(fmt.Sprintf("client %s left", c.RemoteAddr())) s.releasePTT(fmt.Sprintf("client %s left", c.RemoteAddr()))
}() }()
s.log("rigctld: client connected from %s", c.RemoteAddr()) s.log("rigctld: client connected from %s", c.RemoteAddr())
// The HANDSHAKE is always traced — the first few commands are where a
// client decides to stay or hang up, and a connect that lasted 50 ms left
// nothing in the log to say which answer it disliked. Steady-state polling
// stays behind the CAT trace switch.
traced := 0
r := bufio.NewReader(c) r := bufio.NewReader(c)
w := bufio.NewWriter(c) w := bufio.NewWriter(c)
for { for {
@@ -261,7 +270,8 @@ func (s *Server) serve(c net.Conn) {
// that preceded it — the one thing needed to tell whether OpsLog answered // that preceded it — the one thing needed to tell whether OpsLog answered
// something the client could not accept. Behind the same switch as the CAT // something the client could not accept. Behind the same switch as the CAT
// wire trace: this is one line per poll and would drown an ordinary log. // wire trace: this is one line per poll and would drown an ordinary log.
if req != "" && cat.CIVTraceEnabled() { if req != "" && (traced < 6 || cat.CIVTraceEnabled()) {
traced++
s.log("rigctld: %s → %q ⇒ %q", c.RemoteAddr(), req, strings.TrimRight(resp, "\r\n")) s.log("rigctld: %s → %q ⇒ %q", c.RemoteAddr(), req, strings.TrimRight(resp, "\r\n"))
} }
if resp != "" { if resp != "" {
+131
View File
@@ -0,0 +1,131 @@
package watchlist
// ClubLog enrichment — phase 2 of the DXHunter port. clublog.org/watch.php
// answers, per callsign: is this an expedition, does it run OQRS, is there a
// LiveStream, the log's QSO total and the last 24 hours' rate. That block has
// been in the Entry schema since phase 1 (the file round-trips DXHunter's);
// this file finally fills it.
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
)
// WatchData is clublog.org/watch.php's answer, reduced to what the tab shows.
type WatchData struct {
IsExpedition bool `json:"is_expedition"`
HasOQRS bool `json:"has_oqrs"`
LiveStream bool `json:"livestream"`
ClubLogInfo *struct {
TotalQSOs int `json:"total_qsos"`
} `json:"clublog_info"`
// {} when populated, [] when empty — RawMessage swallows both shapes.
QSOsPerBand json.RawMessage `json:"24h_qsos_per_band_mode"`
}
// QSOs24h sums the per-band/per-mode counts.
func (d *WatchData) QSOs24h() int {
if len(d.QSOsPerBand) == 0 {
return 0
}
var parsed map[string]map[string]int
if err := json.Unmarshal(d.QSOsPerBand, &parsed); err != nil {
return 0 // "[]" for an empty answer lands here, which is the right zero
}
n := 0
for _, modes := range parsed {
for _, c := range modes {
n += c
}
}
return n
}
// FetchWatch asks ClubLog about one callsign. A 404 is "ClubLog has no log for
// this call" — an ordinary answer, not an error.
func FetchWatch(ctx context.Context, client *http.Client, apiKey, callsign string) (*WatchData, error) {
url := fmt.Sprintf("https://clublog.org/watch.php?call=%s&api=%s",
strings.ToUpper(strings.TrimSpace(callsign)), apiKey)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "OpsLog")
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return &WatchData{}, nil
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("clublog watch %s: HTTP %d", callsign, resp.StatusCode)
}
body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
return nil, err
}
if len(strings.TrimSpace(string(body))) == 0 {
return &WatchData{}, nil
}
var data WatchData
if err := json.Unmarshal(body, &data); err != nil {
return nil, fmt.Errorf("clublog watch %s: %w", callsign, err)
}
return &data, nil
}
// ApplyClubLog writes one answer into the entry and reports whether anything
// the tab shows actually changed — the caller only broadcasts on true.
func (s *Store) ApplyClubLog(callsign string, d *WatchData) bool {
s.mu.Lock()
defer s.mu.Unlock()
e, ok := s.entries[strings.ToUpper(strings.TrimSpace(callsign))]
if !ok {
return false
}
total := e.ClubLogTotalQSOs
if d.ClubLogInfo != nil {
total = d.ClubLogInfo.TotalQSOs
}
q24 := d.QSOs24h()
changed := e.IsExpedition != d.IsExpedition || e.ClubLogHasOQRS != d.HasOQRS ||
e.ClubLogLiveStream != d.LiveStream || e.ClubLogTotalQSOs != total ||
e.ClubLogQSOs24h != q24
e.IsExpedition = d.IsExpedition
e.ClubLogHasOQRS = d.HasOQRS
e.ClubLogLiveStream = d.LiveStream
e.ClubLogTotalQSOs = total
e.ClubLogQSOs24h = q24
e.ClubLogUpdatedAt = time.Now()
s.scheduleSave()
return changed
}
// StaleEntries lists the callsigns whose ClubLog block is due a refresh.
// Expeditions age faster — their totals are the interesting number and move by
// the hour; a quiet call is asked about four times a day at most.
func (s *Store) StaleEntries(expTTL, otherTTL time.Duration) []string {
s.mu.RLock()
defer s.mu.RUnlock()
now := time.Now()
var out []string
for call, e := range s.entries {
// A starred pattern is a family, not a station — ClubLog has no log
// for "VK9*". The base (star stripped) is what gets asked about.
ttl := otherTTL
if e.IsExpedition {
ttl = expTTL
}
if now.Sub(e.ClubLogUpdatedAt) >= ttl {
out = append(out, call)
}
}
return out
}
+268
View File
@@ -0,0 +1,268 @@
// Package watchlist is the DXHunter watchlist, transplanted: a list of
// callsigns (or prefixes) the operator is hunting, matched against the live
// spot stream, with per-entry state that survives restarts.
//
// The JSON file is DXHunter's OWN schema, field for field — including the
// ClubLog expedition block this phase does not fill yet. Deliberate: the
// operator asked to carry their watchlist.json across, and a file that
// round-trips unchanged is the whole of "same format". The file is GLOBAL
// (dataDir, beside nets.json), not per profile: a DXpedition worth hunting is
// worth hunting whichever station is on.
//
// The CONTEST idea is per entry, not a global mode as in DXHunter: an entry
// marked contest is judged against the CURRENT UTC DAY — at midnight UTC
// yesterday's contacts stop counting and every slot reads "work today" again.
// Nothing resets and nothing is stored for it: the day boundary lives in the
// query, which is why it cannot drift or need a timer.
package watchlist
import (
"encoding/json"
"fmt"
"os"
"sort"
"strings"
"sync"
"time"
)
// Entry is one watched callsign. JSON tags match DXHunter's watchlist.json
// exactly — see the package comment before renaming anything.
type Entry struct {
Callsign string `json:"callsign"`
LastSeen time.Time `json:"lastSeen"`
LastSeenStr string `json:"lastSeenStr"`
AddedAt time.Time `json:"addedAt"`
SpotCount int `json:"spotCount"`
IsContest bool `json:"isContest"`
Notify bool `json:"notify"`
// ClubLog expedition enrichment — phase 2. Carried so a DXHunter file
// round-trips; not filled by OpsLog yet.
IsExpedition bool `json:"isExpedition"`
ClubLogQSOs24h int `json:"clubLogQSOs24h"`
ClubLogTotalQSOs int `json:"clubLogTotalQSOs"`
ClubLogHasOQRS bool `json:"clubLogHasOQRS"`
ClubLogLiveStream bool `json:"clubLogLiveStream"`
ClubLogUpdatedAt time.Time `json:"clubLogUpdatedAt,omitempty"`
}
// Store owns the file. All methods are safe for concurrent use; writes are
// debounced so a burst of MarkSeen calls costs one disk write.
type Store struct {
mu sync.RWMutex
entries map[string]*Entry
path string
saveMu sync.Mutex
saveTimer *time.Timer
ioMu sync.Mutex
}
func New(path string) *Store {
s := &Store{entries: map[string]*Entry{}, path: path}
s.load()
return s
}
func (s *Store) load() {
data, err := os.ReadFile(s.path)
if err != nil {
return // absent on first run — created on first save
}
var list []Entry
if err := json.Unmarshal(data, &list); err != nil {
return // a corrupt file must not take the app down; it is left for repair
}
s.mu.Lock()
defer s.mu.Unlock()
for i := range list {
e := list[i]
e.Callsign = strings.ToUpper(strings.TrimSpace(e.Callsign))
if e.Callsign == "" {
continue
}
s.entries[e.Callsign] = &e
}
}
// Entries returns a snapshot, watched-first ordering left to the UI.
func (s *Store) Entries() []Entry {
s.mu.RLock()
defer s.mu.RUnlock()
out := make([]Entry, 0, len(s.entries))
for _, e := range s.entries {
c := *e
c.LastSeenStr = lastSeenLabel(c.LastSeen)
out = append(out, c)
}
sort.Slice(out, func(i, j int) bool { return out[i].Callsign < out[j].Callsign })
return out
}
// Add creates an entry; contest marks it as re-workable every UTC day. A
// trailing * makes the entry a prefix (VK9* catches every VK9…); anywhere else
// the star is refused rather than silently matching nothing.
func (s *Store) Add(callsign string, contest bool) error {
call := strings.ToUpper(strings.TrimSpace(callsign))
if call == "" {
return fmt.Errorf("callsign required")
}
if i := strings.Index(call, "*"); i >= 0 && i != len(call)-1 {
return fmt.Errorf("* is only allowed at the end (VK9*)")
}
if call == "*" {
return fmt.Errorf("a bare * would match every spot")
}
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.entries[call]; ok {
return fmt.Errorf("%s is already on the watchlist", call)
}
s.entries[call] = &Entry{Callsign: call, AddedAt: time.Now(), IsContest: contest}
s.scheduleSave()
return nil
}
// Remove deletes an entry.
func (s *Store) Remove(callsign string) error {
call := strings.ToUpper(strings.TrimSpace(callsign))
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.entries[call]; !ok {
return fmt.Errorf("%s is not on the watchlist", call)
}
delete(s.entries, call)
s.scheduleSave()
return nil
}
// SetNotify arms or disarms the alert for one entry.
func (s *Store) SetNotify(callsign string, on bool) error {
return s.patch(callsign, func(e *Entry) { e.Notify = on })
}
// SetContest flips the per-entry contest rule.
func (s *Store) SetContest(callsign string, on bool) error {
return s.patch(callsign, func(e *Entry) { e.IsContest = on })
}
func (s *Store) patch(callsign string, fn func(*Entry)) error {
call := strings.ToUpper(strings.TrimSpace(callsign))
s.mu.Lock()
defer s.mu.Unlock()
e, ok := s.entries[call]
if !ok {
return fmt.Errorf("%s is not on the watchlist", call)
}
fn(e)
s.scheduleSave()
return nil
}
// Match returns the entry a spotted callsign belongs to, or "".
//
// EXACT unless the entry says otherwise: N8W matches only N8W, and it takes
// N8W* to catch N8WCR. The first version prefix-matched everything, DXHunter
// style, and a three-letter special-event call swallowed every longer call
// sharing its start — N8W lit up for N8WCR, which is a different station
// entirely. The operator writes the star when they MEAN a family (VK9*, an
// expedition's portable forms via RI0SP*); a bare entry means that call.
func (s *Store) Match(callsign string) (string, bool) {
call := strings.ToUpper(strings.TrimSpace(callsign))
if call == "" {
return "", false
}
s.mu.RLock()
defer s.mu.RUnlock()
for pattern := range s.entries {
if PatternMatches(pattern, call) {
return pattern, true
}
}
return "", false
}
// PatternMatches reports whether one watchlist pattern covers a callsign:
// exact equality, or — with a trailing * — a prefix.
func PatternMatches(pattern, call string) bool {
if p, ok := strings.CutSuffix(pattern, "*"); ok {
return p != "" && strings.HasPrefix(call, p)
}
return call == pattern
}
// MarkSeen records a spot against the matching entry and reports whether the
// entry wants an alert.
func (s *Store) MarkSeen(callsign string) (entry string, notify bool, ok bool) {
pattern, found := s.Match(callsign)
if !found {
return "", false, false
}
s.mu.Lock()
defer s.mu.Unlock()
e := s.entries[pattern]
if e == nil {
return "", false, false
}
e.LastSeen = time.Now()
e.SpotCount++
s.scheduleSave()
return e.Callsign, e.Notify, true
}
// scheduleSave debounces the write: a burst of spots costs one file write two
// seconds after the last of them. Callers hold s.mu.
func (s *Store) scheduleSave() {
s.saveMu.Lock()
defer s.saveMu.Unlock()
if s.saveTimer != nil {
s.saveTimer.Stop()
}
s.saveTimer = time.AfterFunc(2*time.Second, func() { s.persist() })
}
func (s *Store) persist() {
list := s.Entries()
data, err := json.MarshalIndent(list, "", " ")
if err != nil {
return
}
s.ioMu.Lock()
defer s.ioMu.Unlock()
_ = os.WriteFile(s.path, data, 0o644)
}
// Flush writes now — for shutdown, where the two-second debounce would lose
// the last edits.
func (s *Store) Flush() { s.persist() }
// lastSeenLabel is DXHunter's "Just now / 5m ago / 3h ago / 2d ago" string,
// computed at read time so it never goes stale in the file.
func lastSeenLabel(t time.Time) string {
if t.IsZero() {
return "Never"
}
d := time.Since(t)
switch {
case d < time.Minute:
return "Just now"
case d < time.Hour:
return fmt.Sprintf("%dm ago", int(d.Minutes()))
case d < 24*time.Hour:
return fmt.Sprintf("%dh ago", int(d.Hours()))
default:
return fmt.Sprintf("%dd ago", int(d.Hours()/24))
}
}
// Get returns one entry by its exact name — the alert path needs its contest
// flag after MarkSeen named it.
func (s *Store) Get(callsign string) (Entry, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
e, ok := s.entries[strings.ToUpper(strings.TrimSpace(callsign))]
if !ok {
return Entry{}, false
}
return *e, true
}
+92
View File
@@ -0,0 +1,92 @@
package watchlist
import (
"encoding/json"
"os"
"path/filepath"
"testing"
)
func TestGlobMatch(t *testing.T) {
s := New(filepath.Join(t.TempDir(), "watchlist.json"))
if err := s.Add("RI0SP*", false); err != nil {
t.Fatal(err)
}
if err := s.Add("N8W", false); err != nil {
t.Fatal(err)
}
// A starred entry is a family: the expedition's portable forms.
for _, call := range []string{"RI0SP", "RI0SP/MM", "RI0SP/P"} {
if _, ok := s.Match(call); !ok {
t.Errorf("Match(%q) = false, want true", call)
}
}
// A bare entry is THAT call — the reported bug was N8W lighting up for
// N8WCR, a different station entirely.
if _, ok := s.Match("N8W"); !ok {
t.Error("exact entry must match its own call")
}
if _, ok := s.Match("N8WCR"); ok {
t.Error("exact entry must NOT match a longer call")
}
if _, ok := s.Match("RI0S"); ok {
t.Error("a SHORTER call must not match a starred entry")
}
if err := s.Add("VK*9", false); err == nil {
t.Error("a mid-string star must be refused")
}
if err := s.Add("*", false); err == nil {
t.Error("a bare star must be refused")
}
}
func TestDXHunterFileRoundTrips(t *testing.T) {
// A real DXHunter entry, ClubLog block included. It must survive
// load → save byte-meaningfully: same keys, values preserved.
src := `[{"callsign":"C5SP","lastSeen":"0001-01-01T00:00:00Z","lastSeenStr":"Never",
"addedAt":"2026-01-17T00:18:43.89Z","spotCount":7,"isContest":true,"notify":true,
"isExpedition":true,"clubLogQSOs24h":120,"clubLogTotalQSOs":30500,
"clubLogHasOQRS":true,"clubLogLiveStream":true,"clubLogUpdatedAt":"2026-08-28T22:32:18Z"}]`
dir := t.TempDir()
path := filepath.Join(dir, "watchlist.json")
if err := os.WriteFile(path, []byte(src), 0o644); err != nil {
t.Fatal(err)
}
s := New(path)
s.Flush()
out, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
var list []map[string]any
if err := json.Unmarshal(out, &list); err != nil {
t.Fatal(err)
}
if len(list) != 1 {
t.Fatalf("got %d entries", len(list))
}
e := list[0]
for k, want := range map[string]any{
"callsign": "C5SP", "isContest": true, "notify": true,
"isExpedition": true, "clubLogQSOs24h": float64(120),
"clubLogTotalQSOs": float64(30500), "clubLogHasOQRS": true,
} {
if e[k] != want {
t.Errorf("%s = %v, want %v", k, e[k], want)
}
}
}
func TestMarkSeenAndNotify(t *testing.T) {
s := New(filepath.Join(t.TempDir(), "watchlist.json"))
_ = s.Add("HB040A", false)
_ = s.SetNotify("HB040A", true)
entry, notify, ok := s.MarkSeen("HB040A")
if !ok || !notify || entry != "HB040A" {
t.Fatalf("MarkSeen = %q %v %v", entry, notify, ok)
}
list := s.Entries()
if list[0].SpotCount != 1 || list[0].LastSeenStr != "Just now" {
t.Errorf("entry after MarkSeen: %+v", list[0])
}
}
+70
View File
@@ -148,3 +148,73 @@ func isHamlogConfirmed(v string) bool {
v = strings.ToUpper(strings.TrimSpace(v)) v = strings.ToUpper(strings.TrimSpace(v))
return v != "" && v != "N" && v != "NO" return v != "" && v != "N" && v != "NO"
} }
// RDAChoice is one arbitrated contact: which district the operator decided is
// right for that QSO.
type RDAChoice struct {
QSOID int64 `json:"qso_id"`
District string `json:"district"`
}
// RDAApplyResult reports what an arbitration did.
type RDAApplyResult struct {
Applied int `json:"applied"`
Failed int `json:"failed"`
Message string `json:"message"`
}
// ApplyRDAChoices writes the chosen district onto each contact — into CNTY and
// as the award reference, both.
//
// The first version wrote only the award override, to keep the imported CNTY as
// a record of what HAMLOG said. That was wrong in the way that matters: CNTY is
// what the comparison READS, so the contact went on disagreeing for ever. The
// operator settled a hundred contacts, ran the comparison again and got the
// same hundred rows — the decision had no visible effect anywhere, which is
// indistinguishable from a button that does nothing.
//
// So the chosen district lands in CNTY, where it settles the disagreement, and
// in the award reference, where it decides what the contact counts for. This is
// the operator's own log: correcting a field in it is the point of the exercise,
// not a loss of evidence.
func (a *App) ApplyRDAChoices(choices []RDAChoice) (RDAApplyResult, error) {
var res RDAApplyResult
if a.qso == nil {
return res, fmt.Errorf("db not initialized")
}
for _, c := range choices {
district := strings.ToUpper(strings.TrimSpace(c.District))
if !rdaDistrictRe.MatchString(district) {
res.Failed++
applog.Printf("rda apply: qso %d — %q is not a district reference", c.QSOID, c.District)
continue
}
q, err := a.qso.GetByID(a.ctx, c.QSOID)
if err != nil {
res.Failed++
applog.Printf("rda apply: qso %d could not be read: %v", c.QSOID, err)
continue
}
if q.Extras == nil {
q.Extras = map[string]string{}
}
q.County = district
q.Extras[award.ManualRefsKey] = setOverrideRef(q.Extras[award.ManualRefsKey], "RDA", district)
if err := a.qso.Update(a.ctx, q); err != nil {
res.Failed++
applog.Printf("rda apply: qso %d update failed: %v", c.QSOID, err)
continue
}
res.Applied++
}
if res.Applied > 0 {
// The award totals were computed from the old answers.
a.invalidateAwardStats()
}
applog.Printf("rda apply: %d contacts settled, %d failed", res.Applied, res.Failed)
res.Message = fmt.Sprintf("%d settled", res.Applied)
if res.Failed > 0 {
res.Message += fmt.Sprintf(", %d failed (see the log)", res.Failed)
}
return res, nil
}
+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.26.16" appVersion = "0.27.4"
// 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.
+7
View File
@@ -0,0 +1,7 @@
//go:build !windows
package main
// Placing a window at an absolute desktop coordinate is Windows-specific; every
// caller falls back to the toolkit's own call when this says no.
func setWindowPosAbsolute(x, y int) bool { return false }
+93
View File
@@ -0,0 +1,93 @@
//go:build windows
package main
import (
"syscall"
"unsafe"
"hamlog/internal/applog"
)
// Moving the window to an ABSOLUTE virtual-desktop position.
//
// Wails' own WindowSetPosition cannot do it. Its Windows implementation reads:
//
// func (cba *ControlBase) SetPos(x, y int) {
// info := getMonitorInfo(cba.hwnd)
// w32.SetWindowPos(cba.hwnd, HWND_TOP, int(info.RcWork.Left)+x, int(info.RcWork.Top)+y, ...)
// }
//
// — the coordinates are relative to the CURRENT monitor's work area, while
// WindowGetPosition returns GetWindowRect, which is absolute. Saving one and
// restoring the other is only harmless on the primary monitor, where the work
// area starts at 0.
//
// On a second monitor to the LEFT it compounds at every launch. Reported from a
// two-screen station with the left monitor at x = -3840: OpsLog saved -3844,
// reopened on that monitor, added the monitor's own origin, and stored -7684 —
// then -11524, each launch one screen further into nowhere.
//
// So we place the window ourselves. Same call the toolkit makes, without the
// offset.
const (
swpNoSize = 0x0001
swpNoZOrder = 0x0004
swpNoActivate = 0x0010
)
var (
procSetWindowPos = user32Dll.NewProc("SetWindowPos")
procEnumWindows = user32Dll.NewProc("EnumWindows")
procGetWindowThreadProcessID = user32Dll.NewProc("GetWindowThreadProcessId")
procGetWindowTextLengthW = user32Dll.NewProc("GetWindowTextLengthW")
procGetWindow = user32Dll.NewProc("GetWindow")
kernel32Dll = syscall.NewLazyDLL("kernel32.dll")
procGetCurrentProcessIDWinPos = kernel32Dll.NewProc("GetCurrentProcessId")
)
// mainWindowHandle finds this process's own top-level window.
//
// Wails does not expose the handle, so it is looked up: the first top-level
// window belonging to this process id that has no owner and a title. The window
// is created hidden (StartHidden), and EnumWindows lists hidden windows too,
// which is what makes this usable before the window is shown.
func mainWindowHandle() uintptr {
self, _, _ := procGetCurrentProcessIDWinPos.Call()
var found uintptr
cb := syscall.NewCallback(func(hwnd uintptr, _ uintptr) uintptr {
var pid uint32
procGetWindowThreadProcessID.Call(hwnd, uintptr(unsafe.Pointer(&pid)))
if uintptr(pid) != self {
return 1 // keep going
}
// GW_OWNER = 4: skip tool windows and dialogs owned by the main one.
if owner, _, _ := procGetWindow.Call(hwnd, 4); owner != 0 {
return 1
}
if n, _, _ := procGetWindowTextLengthW.Call(hwnd); n == 0 {
return 1
}
found = hwnd
return 0 // stop
})
procEnumWindows.Call(cb, 0)
return found
}
// setWindowPosAbsolute moves the window to a virtual-desktop coordinate.
// Reports whether it could; the caller falls back to the toolkit's own call.
func setWindowPosAbsolute(x, y int) bool {
hwnd := mainWindowHandle()
if hwnd == 0 {
applog.Printf("window: could not find our own window handle — falling back to the toolkit's placement")
return false
}
r, _, err := procSetWindowPos.Call(hwnd, 0, uintptr(int32(x)), uintptr(int32(y)), 0, 0,
swpNoSize|swpNoZOrder|swpNoActivate)
if r == 0 {
applog.Printf("window: SetWindowPos(%d,%d) failed: %v", x, y, err)
return false
}
return true
}