Compare commits

...
Author SHA1 Message Date
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
35 changed files with 1851 additions and 574 deletions
+212 -63
View File
@@ -159,6 +159,7 @@ const (
keyCATIcomNetUser = "cat.icom.net.user" // Icom network: Network User1 ID
keyCATIcomNetPass = "cat.icom.net.pass" // Icom network: Network User1 password
keyCATIcomNetAudio = "cat.icom.net.audio" // Icom network: stream RX audio on 50003 (experimental)
keyAudioMonitorOn = "audio.monitor.on" // play the network RX audio through the Listening device (the stream itself stays open for the recorder either way)
keyCATTCIHost = "cat.tci.host" // TCI host (Expert Electronics SunSDR / ExpertSDR2)
keyCATTCIPort = "cat.tci.port" // TCI WebSocket port (default 40001)
keyCATTCISpots = "cat.tci.spots" // push cluster spots to the TCI panorama
@@ -740,10 +741,15 @@ type App struct {
watchlist *watchlist.Store // Tools → Watchlist (global watchlist.json)
watchAlertMu sync.Mutex // throttles watchlist alerts…
watchAlertAt map[string]time.Time // …per entry
watchPattern atomic.Value // auto-contest pattern (string), loaded at startup
operating *operating.Repo
udp *udp.Manager
udpRepo *udp.Repo
// WSJT-X decode highlighting (message 13) — see app_wsjt_highlight.go.
wsjtHighlightOn atomic.Bool
wsjtHLMu sync.Mutex
wsjtHLSent map[string]string
watchPattern atomic.Value // auto-contest pattern (string), loaded at startup
operating *operating.Repo
udp *udp.Manager
udpRepo *udp.Repo
// Program id of the last decoding application that reported its status.
// Halt Tx is routed by id, and the panel's Halt button must work even when
// nothing is transmitting at that instant — so the id is remembered from
@@ -1204,6 +1210,11 @@ func (a *App) startup(ctx context.Context) {
a.operating = operating.NewRepo(conn)
a.udpRepo = udp.NewRepo(conn)
a.udp = udp.NewManager(a.udpRepo)
// A program heard for the first time is asked to replay the decodes already
// on its screen, so the FT decodes panel starts full instead of waiting a
// period. Replayed decodes arrive marked not-new and are shown but never
// auto-answered.
a.udp.SetOnNewInstance(func(id string) { _ = a.udp.SendReplay(id) })
go a.consumeUDPEvents()
a.cache = lookup.NewCache(conn, 30*24*time.Hour)
a.lookup = lookup.NewManager(a.cache)
@@ -1252,6 +1263,49 @@ func (a *App) startup(ctx context.Context) {
go a.applyRelayAuto(s.FreqHz, s.Band)
}
})
// Digital Voice Keyer + QSO recorder (WASAPI). Idle until used. Created
// BEFORE the CAT link comes up, and it matters: a network Icom with RX
// audio enabled builds its audio sink inside reloadCAT, gated on audioMgr —
// when the manager was created later, every fresh launch connected with
// audio silently off, and the operator had to untick/save/retick the option
// to hear anything.
a.audioMgr = audio.NewManager(func() {
st := a.dvkStatus()
// When a voice message finishes (or is stopped), drop the PTT we keyed
// for it — but tag the release with the current key generation so it
// can't cut a transmission a newer message already started.
if !st.Playing {
a.pttMu.Lock()
keyed := a.dvkPttKeyed
gen := a.pttGen
if keyed {
a.dvkPttKeyed = false
}
a.pttMu.Unlock()
if keyed {
go a.dvkUnkeyPTT(gen)
}
// And give the microphone back, if we took it (see raiseFlexDVKDax).
// Off the callback's goroutine: this talks to the radio, and the
// audio manager is reporting a state change, not waiting on us.
go a.lowerFlexDVKDax()
}
if a.ctx != nil {
wruntime.EventsEmit(a.ctx, "audio:status", st)
}
})
a.qsoRec = audio.NewRecorder()
if a.audioMgr != nil {
// A running monitor picks the new level up immediately: the operator is
// listening while they move the slider, and asking them to stop and
// restart it to hear the change is how a working control gets reported
// as broken.
if cfg, err := a.GetAudioSettings(); err == nil {
a.audioMgr.SetMonitorGain(cfg.FromGain)
}
}
a.startQSORecorderIfEnabled()
a.reloadCAT()
// The QSO logbook lives where the ACTIVE PROFILE points it: the local SQLite
@@ -1400,6 +1454,7 @@ func (a *App) startup(ctx context.Context) {
a.pota = pota.New(func(format string, args ...any) { applog.Printf(format, args...) })
a.startWatchlistClubLog()
a.watchPattern.Store(strings.ToUpper(strings.TrimSpace(a.settingOr(keyWatchlistContestPattern, ""))))
a.wsjtHighlightOn.Store(a.settingOr(keyWsjtHighlight, "0") == "1")
go a.pota.Run(a.ctx)
// DX Cluster (multi-server): the spot callback enriches each spot
@@ -1479,44 +1534,6 @@ func (a *App) startup(ctx context.Context) {
})
a.solar.Start()
// Digital Voice Keyer + QSO recorder (WASAPI). Idle until used.
a.audioMgr = audio.NewManager(func() {
st := a.dvkStatus()
// When a voice message finishes (or is stopped), drop the PTT we keyed
// for it — but tag the release with the current key generation so it
// can't cut a transmission a newer message already started.
if !st.Playing {
a.pttMu.Lock()
keyed := a.dvkPttKeyed
gen := a.pttGen
if keyed {
a.dvkPttKeyed = false
}
a.pttMu.Unlock()
if keyed {
go a.dvkUnkeyPTT(gen)
}
// And give the microphone back, if we took it (see raiseFlexDVKDax).
// Off the callback's goroutine: this talks to the radio, and the
// audio manager is reporting a state change, not waiting on us.
go a.lowerFlexDVKDax()
}
if a.ctx != nil {
wruntime.EventsEmit(a.ctx, "audio:status", st)
}
})
a.qsoRec = audio.NewRecorder()
if a.audioMgr != nil {
// A running monitor picks the new level up immediately: the operator is
// listening while they move the slider, and asking them to stop and
// restart it to hear the change is how a working control gets reported
// as broken.
if cfg, err := a.GetAudioSettings(); err == nil {
a.audioMgr.SetMonitorGain(cfg.FromGain)
}
}
a.startQSORecorderIfEnabled()
// NET Control store (global JSON, shared across logbooks).
if ns, err := netctl.Open(filepath.Join(a.dataDir, "nets.json")); err != nil {
applog.Printf("netctl: open failed: %v", err)
@@ -8435,7 +8452,7 @@ func (a *App) ListAudioInputDevices() ([]audio.Device, error) {
return devs, err
}
if a.tciAudioAvailable() {
devs = append([]audio.Device{{ID: audio.NetworkDeviceID, Name: "Radio (TCI network audio)"}}, devs...)
devs = append([]audio.Device{{ID: audio.NetworkDeviceID, Name: "Radio (network audio)"}}, devs...)
}
return devs, nil
}
@@ -8462,7 +8479,7 @@ func (a *App) ListAudioOutputDevices() ([]audio.Device, error) {
return devs, err
}
if audio.NetworkPlayerReady() {
devs = append([]audio.Device{{ID: audio.NetworkDeviceID, Name: "Radio (TCI network audio)"}}, devs...)
devs = append([]audio.Device{{ID: audio.NetworkDeviceID, Name: "Radio (network audio)"}}, devs...)
}
return devs, nil
}
@@ -9262,7 +9279,9 @@ func (a *App) QSOAudioManualReady() bool {
return false
}
cfg, _ := a.GetAudioSettings()
return !cfg.QSORecord && strings.TrimSpace(cfg.FromRadio) != ""
// Over the network the radio needs no sound card: the 50003 stream is the
// source, so the button is offered even with "From radio" empty.
return !cfg.QSORecord && (strings.TrimSpace(cfg.FromRadio) != "" || a.icomNetAudioActive())
}
// QSOAudioManualStart begins a recording when automatic recording is off.
@@ -9279,10 +9298,19 @@ func (a *App) QSOAudioManualStart() bool {
}
if !a.qsoRec.Running() {
cfg, _ := a.GetAudioSettings()
if strings.TrimSpace(cfg.FromRadio) == "" {
// Same source rule as the automatic recorder: when the RX audio arrives
// over the network, record THAT — not the "From radio" sound card, which
// on a mixed station is another radio entirely. A manual take on the
// network IC-7760 was capturing the Flex's DAX: technically a recording,
// just not of the QSO being made.
from := cfg.FromRadio
a.qsoRecPushed = a.icomNetAudioActive() || cfg.FromRadio == audio.NetworkDeviceID
if a.qsoRecPushed {
from = audio.PushedSource
} else if strings.TrimSpace(from) == "" {
return false
}
if err := a.qsoRec.Start(cfg.FromRadio, cfg.RecordingDevice, cfg.PrerollSeconds); err != nil {
if err := a.qsoRec.Start(from, cfg.RecordingDevice, cfg.PrerollSeconds); err != nil {
applog.Printf("qso-rec: manual start failed: %v", err)
return false
}
@@ -10664,6 +10692,26 @@ func (a *App) AudioStartMonitor() error {
return fmt.Errorf("audio not initialized")
}
cfg, _ := a.GetAudioSettings()
// Idempotent: asking to listen while a monitor is already running restarts
// it instead of refusing. The refusal surfaced as a checkbox that unticked
// itself the instant it was ticked, whenever the UI's idea of the state and
// the real monitor had drifted apart.
a.audioMgr.StopMonitor()
// When the rig's audio arrives over the NETWORK (Icom 50003), the monitor
// must be render-only: this button used to start a USB capture from the
// "From radio" device as well, and that second producer — often another
// radio's DAX — interleaved its chunks with the network stream's pushes.
// The result was audio chopped to pieces the moment the operator toggled
// Listening off and on while connected to a network Icom.
if cs, err := a.GetCATSettings(); err == nil && cs.Enabled && cs.Backend == "icom-net" && cs.IcomNetAudio {
a.setSetting(keyAudioMonitorOn, "1")
applog.Printf("audio: RX monitor start (network sink only → listen=%q)", cfg.ListeningDevice)
return a.audioMgr.StartMonitorSink(cfg.ListeningDevice)
}
// Only the USB path needs a capture device — checked AFTER the network
// branch, which needs none: with From-radio empty (the normal network
// setup) this refusal was un-ticking the speakers checkbox the instant it
// was ticked.
if strings.TrimSpace(cfg.FromRadio) == "" {
return fmt.Errorf(`no "From radio" capture device set — pick the rig's USB Audio CODEC in Settings → Audio`)
}
@@ -10674,6 +10722,7 @@ func (a *App) AudioStartMonitor() error {
// AudioStopMonitor stops the RX monitor passthrough.
func (a *App) AudioStopMonitor() {
a.setSetting(keyAudioMonitorOn, "0")
if a.audioMgr != nil {
a.audioMgr.StopMonitor()
applog.Printf("audio: RX monitor stopped")
@@ -10696,9 +10745,44 @@ func (a *App) AudioStartTX() error {
if strings.TrimSpace(cfg.ToRadio) == "" {
return fmt.Errorf(`no "To radio" device set — pick the rig's USB Audio CODEC output in Settings → Audio`)
}
// Live mic over the radio's own link: the To-radio "device" is the radio.
// Fetched before keying so a missing stream refuses cleanly with the PTT
// never touched.
var netSend func([]byte) error
if cfg.ToRadio == audio.NetworkDeviceID {
if strings.TrimSpace(cfg.RecordingDevice) == "" {
return fmt.Errorf("pick your microphone as the Recording mic in Settings → Audio")
}
type sender interface {
TXAudioSender() (func([]byte) error, error)
}
err := a.cat.IcomDo(func(ic cat.IcomController) error {
p, ok := ic.(sender)
if !ok {
return fmt.Errorf("this radio cannot take live microphone audio over its link yet")
}
fn, err := p.TXAudioSender()
if err != nil {
return err
}
netSend = fn
return nil
})
if err != nil {
return err
}
}
if err := a.pttKey(cfg); err != nil { // key first — no point streaming to a rig that isn't transmitting
return err
}
if netSend != nil {
if err := a.audioMgr.StartTXAudioNetwork(cfg.RecordingDevice, netSend); err != nil {
a.pttUnkey()
return err
}
applog.Printf("audio: TX start (mic=%q → the radio over the network, ptt=%q)", cfg.RecordingDevice, cfg.PTTMethod)
return nil
}
if err := a.audioMgr.StartTXAudio(cfg.RecordingDevice, cfg.ToRadio); err != nil {
a.pttUnkey()
return err
@@ -13832,7 +13916,13 @@ func (a *App) consumeUDPEvents() {
"low_conf": ev.DecodeLowConf,
"mode_raw": ev.DecodeModeRaw,
"msg_raw": ev.DecodeMsgRaw,
// false on a Replay's resent history — shown, never auto-answered.
"is_new": ev.DecodeIsNew,
})
// Log-aware colour in the decoder's own window (see
// app_wsjt_highlight.go). After the emit: painting must never delay
// the panel.
a.maybeHighlightDecode(ev.ProgramID, ev.DecodeCall, bandForHz(ev.DecodeFreqHz))
// A WSJT-X decode (heard station). Render it on the FlexRadio
// panadapter when the option is on; green + SNR comment, auto-expiring
// after the configured duration. De-duped per call in the Flex backend.
@@ -14460,6 +14550,23 @@ func (a *App) IcomSetSplit(on bool) error {
return a.cat.IcomDo(func(ic cat.IcomController) error { return ic.SetIcomSplit(on) })
}
// IcomSetATU puts the internal tuner in or out of line.
func (a *App) IcomSetATU(on bool) error {
if a.cat == nil {
return fmt.Errorf("cat not initialized")
}
return a.cat.IcomDo(func(ic cat.IcomController) error { return ic.SetATU(on) })
}
// IcomSetSplitOffset turns split on with a chosen TX offset (Hz) — the
// console's +1/+5/+10 kHz buttons.
func (a *App) IcomSetSplitOffset(hz int64) error {
if a.cat == nil {
return fmt.Errorf("cat not initialized")
}
return a.cat.IcomDo(func(ic cat.IcomController) error { return ic.SetIcomSplitOffset(true, hz) })
}
func (a *App) IcomSetAntenna(n int) error {
if a.cat == nil {
return fmt.Errorf("cat not initialized")
@@ -15564,27 +15671,42 @@ func (a *App) reloadCAT() {
// verification (see icomaudio.go) — hence experimental + opt-in.
acfg, _ := a.GetAudioSettings()
a.audioMgr.StopMonitor() // clear any prior monitor/sink so a re-save restarts cleanly
if err := a.audioMgr.StartMonitorSink(acfg.ListeningDevice); err != nil {
applog.Printf("icom-net audio: cannot start output sink: %v", err)
} else {
codec := audio.NewPCM16Codec()
audioSink = func(payload []byte) {
pcm, err := codec.Decode(payload)
if err != nil {
return
}
a.audioMgr.PushMonitorAudio(pcm)
// And to the QSO recorder, which has no device to capture from
// on this backend. It drops the samples unless a recording is
// actually running, so this costs a function call when idle.
if a.qsoRec != nil {
a.qsoRec.PushRX(pcm)
}
// The SINK — decode + recorder feed — exists whenever the stream is
// on. It used to be built only when the speakers were also wanted,
// so "speakers off" (or a sink that failed to open) silently turned
// the whole stream off: audio=false on the wire, no recordings, no
// voice keyer, and a ticked RX-audio checkbox that did nothing.
codec := audio.NewPCM16Codec()
audioSink = func(payload []byte) {
pcm, err := codec.Decode(payload)
if err != nil {
return
}
a.audioMgr.PushMonitorAudio(pcm)
// And to the QSO recorder, which has no device to capture from
// on this backend. It drops the samples unless a recording is
// actually running, so this costs a function call when idle.
if a.qsoRec != nil {
a.qsoRec.PushRX(pcm)
}
}
// Listening is a CHOICE, remembered: an operator sitting next to the
// radio hears it in the room and wants the stream only for the
// recorder and the voice keyer. Stop listening turns this off, the
// Listen button turns it back on, and reconnects respect it instead
// of switching the speakers back on every time.
if a.settingOr(keyAudioMonitorOn, "1") != "1" {
applog.Printf("icom-net audio: stream on, speakers off (Listening was stopped by the operator)")
} else if err := a.audioMgr.StartMonitorSink(acfg.ListeningDevice); err != nil {
applog.Printf("icom-net audio: stream on, but the output sink failed: %v", err)
} else {
applog.Printf("icom-net audio: RX audio streaming ENABLED (experimental) → %q", acfg.ListeningDevice)
}
}
a.cat.Start(cat.NewIcomNet(s.IcomNetHost, s.IcomNetUser, s.IcomNetPass, s.IcomAddr, s.DigitalDefault, audioSink))
// With the audio session open the radio can also TAKE audio: offer it to
// the voice keyer, the way a TCI radio is offered.
a.installIcomTXPlayer(audioSink != nil)
case "tci":
// Expert Electronics TCI (WebSocket) — SunSDR / ExpertSDR2, or any
// TCI-compatible server. The receive audio rides the same socket, so
@@ -21052,3 +21174,30 @@ func (a *App) CheckHamlogKey(key string) (string, error) {
defer cancel()
return extsvc.CheckHamlogKey(ctx, nil, key)
}
// GetAudioMonitorPref says whether the network RX audio should be played
// through the Listening device — the remembered speaker choice behind the
// console's speaker button and the CAT panel's checkbox.
func (a *App) GetAudioMonitorPref() bool {
return a.settingOr(keyAudioMonitorOn, "1") == "1"
}
// IcomConsolePTT is the console's PTT button. On a USB station it keys the
// rig and nothing more — the operator talks into the radio's own microphone.
// When the transmit audio goes over the NETWORK, keying alone transmits
// silence: the PC microphone must be routed with it, exactly as the Talk
// button does. One button, the right road picked here.
func (a *App) IcomConsolePTT(on bool) error {
cfg, _ := a.GetAudioSettings()
if cfg.ToRadio == audio.NetworkDeviceID {
if on {
return a.AudioStartTX()
}
a.AudioStopTX()
return nil
}
if a.cat == nil {
return fmt.Errorf("cat not initialized")
}
return a.cat.SetPTT(on)
}
+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")
}
+9
View File
@@ -235,3 +235,12 @@ func (a *App) activeRadioMyRig() string {
}
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()
}
+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, ""
}
+102
View File
@@ -1,4 +1,106 @@
[
{
"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": "",
+66 -12
View File
@@ -33,7 +33,7 @@ import {
GetSolarData,
GetQSORate,
LoTWUserInfo,
OperatingDefaultForBand,
OperatingDefaultForBand, ActiveRadioMyRig, ConfigureDecoderMode,
LogUDPLoggedADIF,
ListCountries,
GetWinkeyerSettings, SaveWinkeyerSettings, ListSerialPorts, GetWinkeyerStatus,
@@ -934,11 +934,16 @@ export default function App() {
useEffect(() => {
if (!band) return;
let cancelled = false;
OperatingDefaultForBand(band).then((d) => {
OperatingDefaultForBand(band).then(async (d) => {
if (cancelled) return;
// The radio actually CONNECTED names itself ahead of the per-band plan:
// an IC-7760 on the air must not log as the Flex the band default names.
let liveRig = '';
try { liveRig = (await ActiveRadioMyRig()) || ''; } catch {}
if (cancelled) return;
setDetails((cur) => ({
...cur,
my_rig: d?.station_name || '',
my_rig: liveRig || d?.station_name || '',
my_antenna: d?.antenna_name || '',
tx_pwr: d?.tx_pwr ?? cur.tx_pwr,
}));
@@ -1051,6 +1056,13 @@ export default function App() {
if (!active) setError(t('rec.manualFailed'));
}).catch((e: any) => setError(String(e?.message ?? e)));
};
// recTick means "a fresh take" — that is the only case where the clock returns
// to zero, as opposed to resuming after a stop. Declared BEFORE the ticking
// effect below and deliberately so: effects run in declaration order, and the
// other way round the ticker captured the PREVIOUS take's elapsed as its
// starting point — the counter showed 0 for one second, then jumped straight
// back to the old thirty minutes.
useEffect(() => { setRecSeconds(0); recSecondsRef.current = 0; setRecStopped(false); }, [recTick]);
useEffect(() => {
if (!recording) { setRecSeconds(0); return; }
// A stopped take freezes the clock where it is: it must show the length of
@@ -1061,9 +1073,6 @@ export default function App() {
const id = window.setInterval(() => setRecSeconds(from + Math.floor((Date.now() - start) / 1000)), 1000);
return () => window.clearInterval(id);
}, [recording, recTick, recStopped]);
// recTick means "a fresh take" — that is the only case where the clock returns
// to zero, as opposed to resuming after a stop.
useEffect(() => { setRecSeconds(0); recSecondsRef.current = 0; setRecStopped(false); }, [recTick]);
// The callsign the in-progress recording belongs to (uppercased; '' = none).
// Lets us restart from zero when the operator edits the call to a different
// station mid-recording, instead of continuing the old take.
@@ -1523,7 +1532,7 @@ export default function App() {
// Seed the current break-in from the rig when the CW panel becomes active in
// Icom mode (so the control reflects the radio's real state).
useEffect(() => {
if (cwSource !== 'icom' || !wkEnabled || !(catState.backend === 'icom' && catState.connected)) return;
if (cwSource !== 'icom' || !wkEnabled || !((catState.backend === 'icom' || catState.backend === 'icom-net') && catState.connected)) return;
GetIcomState().then((s: any) => { if (s && typeof s.break_in === 'number') setIcomBreakIn(s.break_in); }).catch(() => {});
}, [cwSource, wkEnabled, catState.backend, catState.connected]);
// Auto-call: repeat the clicked macro (e.g. F1 CQ) every (message + N seconds)
@@ -1547,7 +1556,7 @@ export default function App() {
// skips the log that hasn't happened yet.
const wkSendGenRef = useRef(0);
useEffect(() => {
const connected = cwSource === 'icom' ? (catState.backend === 'icom' && catState.connected)
const connected = cwSource === 'icom' ? ((catState.backend === 'icom' || catState.backend === 'icom-net') && catState.connected)
: cwSource === 'flex' ? (catState.backend === 'flex' && catState.connected)
: cwSource === 'yaesu' ? (catState.backend === 'yaesu' && catState.connected)
: cwSource === 'kenwood' ? (catState.backend === 'kenwood' && catState.connected)
@@ -1737,15 +1746,29 @@ export default function App() {
const gen = ++dvkAutoCqGenRef.current;
dvkAutoCqSlotRef.current = slot;
const sleep = (ms: number) => new Promise((r) => window.setTimeout(r, ms));
// Traced into the app log deliberately: the loop kept 'not repeating' on a
// network rig and every guess at which guard was tripping proved wrong.
const trace = (m: string) => UILog(`dvk auto-cq: ${m}`).catch(() => {});
trace(`start slot=${slot} gen=${gen}`);
let round = 0;
while (dvkAutoCqSlotRef.current === slot && gen === dvkAutoCqGenRef.current && dvkActiveRef.current) {
if (!isPhoneMode(modeRef.current)) { stopDvkAutoCq(); break; }
await DVKPlay(slot).catch(() => {});
// An EMPTY mode is not a mode change: over the network the rig's mode
// read fails transiently and the CAT push blanks the field for a poll or
// two — killing the auto-CQ loop mid-run for nothing. Only a known
// non-phone mode stops the loop.
if (modeRef.current && !isPhoneMode(modeRef.current)) { trace(`stopped: mode ${modeRef.current} is not phone`); stopDvkAutoCq(); break; }
round++;
trace(`round ${round}: play`);
await DVKPlay(slot).catch((e: any) => trace(`play failed: ${e?.message ?? e}`));
await sleep(300); // let playback flip "playing" true
trace(`round ${round}: playing=${dvkPlayingRef.current}`);
let guard = 0; // then wait for it to finish (cap ~90 s)
while (dvkPlayingRef.current && gen === dvkAutoCqGenRef.current && guard < 600) { await sleep(150); guard++; }
if (gen !== dvkAutoCqGenRef.current) break;
if (gen !== dvkAutoCqGenRef.current) { trace(`stopped mid-round: superseded (gen ${dvkAutoCqGenRef.current})`); break; }
trace(`round ${round}: message over after ~${(guard * 150 / 1000).toFixed(1)}s, gap ${dvkAutoCqSecsRef.current}s`);
await sleep(Math.max(0, dvkAutoCqSecsRef.current) * 1000); // gap before the next CQ
}
trace(`exit: slotRef=${dvkAutoCqSlotRef.current} gen=${gen}/${dvkAutoCqGenRef.current} active=${dvkActiveRef.current}`);
}
const dvkPlay = useCallback((slot: number) => {
if (!isPhoneMode(modeRef.current)) { setError(t('dvkp.notPhone')); return; }
@@ -2543,6 +2566,10 @@ export default function App() {
for (const d of decodes) {
const seenKey = `${d.call}|${d.ms ?? d.at}|${d.instance ?? ''}`;
if (autoSeenRef.current.has(seenKey)) continue;
// A Replay's resent history is display-only: answering a line the far
// end already dropped would fail anyway, and doing it at startup — the
// moment replays arrive — would be a transmitter firing on old news.
if ((d as any).is_new === false) { autoSeenRef.current.add(seenKey); continue; }
// Only decodes from the CURRENT period are worth answering: replying to a
// slot that has closed asks the far end to match a decode it has dropped.
if (now - Date.parse(d.at) > 30_000) { autoSeenRef.current.add(seenKey); continue; }
@@ -2640,6 +2667,11 @@ export default function App() {
// "the field still shows the previous broadcast" (safe to update) from "the
// user has typed a different call" (must not clobber).
const lastUdpCallRef = useRef('');
// Edge detection for the DECODER'S stream: WSJT-X/JTDX/MSHV re-broadcast the
// same DX Call in every Status packet, seconds apart, forever. Applying each
// one meant a spot clicked in OpsLog was overwritten moments later by the
// decoder restating old news. Only a CHANGE in this stream is an event.
const lastWsjtEdgeRef = useRef('');
// When the entered callsign turns out to be worked-before, jump to the
// Worked-before tab so the history is front-and-centre. Only once per call,
@@ -3315,6 +3347,10 @@ export default function App() {
void tuneRigCAT(s.freq_hz, m).then(() => window.setTimeout(zoom, 300));
} else zoom();
if (m) applyModeFromSpot(m);
// And the DECODER follows too: an FT4 spot clicked while WSJT-X sits in
// FT8 switches its mode (Configure, message 15). The backend filters —
// only modes the decoder speaks, only when the option is on.
if (m) ConfigureDecoderMode(m).catch(() => {});
onCallsignInput(s.dx_call, { force: true });
applySpotRefs((s as any).pota_ref, (s as any).sota_ref);
if (s.dx_call?.trim()) restartRecordingForNewTarget(s.dx_call);
@@ -3769,6 +3805,13 @@ export default function App() {
// Anything that isn't WSJT-X (N1MM, ADIF, a panadapter/cluster click relayed
// over UDP…) is an explicit pick → force it over an existing call.
const force = String(p?.service ?? '').toLowerCase() !== 'wsjt';
if (!force) {
// The decoder's stream: same value as last time = no edge = no update.
// Only a changed DX Call is the operator doing something over there.
const upper = String(p?.call ?? '').trim().toUpperCase();
if (upper && upper === lastWsjtEdgeRef.current) return;
lastWsjtEdgeRef.current = upper;
}
// External app moved to a new station → fresh recording for the new target.
if (applyUdpCall(p?.call, force)) restartRecordingForNewTarget(String(p?.call ?? ''));
});
@@ -3779,6 +3822,9 @@ export default function App() {
// Only when something is actually in the entry, so an idle digital app doesn't
// wipe a call being typed by hand.
const unsubClear = EventsOn('udp:clear_call', () => {
// The decoder cleared its DX Call: the next call it announces — even the
// same one re-selected — is a fresh edge.
lastWsjtEdgeRef.current = '';
if (callsignRef.current?.value?.trim() || callsign.trim()) resetEntry();
});
// Clicked one of OpsLog's spots on the FlexRadio panadapter → fill the call
@@ -4592,10 +4638,17 @@ export default function App() {
return () => { dead = true; };
}, [selQso, callsign]);
const wbTokenRef = useRef(0);
async function runWorkedBefore(call: string, dxccHint: number = 0) {
// Latest-wins: two lookups race when the operator types a second call
// before the first answered, and the SLOW one used to land last — the
// grid then showed the previous call's QSOs under the new call's name
// (LU5AVM's contact filed under LW8ETV, screenshot in hand).
const token = ++wbTokenRef.current;
setWbBusy(true);
try {
const w = await WorkedBefore(call, dxccHint);
if (token !== wbTokenRef.current) return; // a newer lookup owns the panel
setWb(w);
// Mirrored synchronously rather than through the effect above: a backfill
// parked by the lookup has to read this on the very next line, not a
@@ -4610,10 +4663,11 @@ export default function App() {
fillFromLastQso(p.r, call);
}
} catch {
if (token !== wbTokenRef.current) return;
setWb(null);
wbRef.current = null;
wbCallRef.current = '';
} finally { setWbBusy(false); }
} finally { if (token === wbTokenRef.current) setWbBusy(false); }
}
// fillFromLastQso enriches the entry from the LAST QSO we logged with this call
// when the live lookup came up short — the callsign isn't on QRZ/HamQTH, or no
+19 -14
View File
@@ -18,7 +18,7 @@ type KenwoodState = {
available: boolean; model?: string; elecraft: boolean; mode?: string; data_sub?: string;
transmitting: boolean; split: boolean; split_tx_hz?: 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;
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;
@@ -42,18 +42,22 @@ const ZERO: KenwoodState = {
// nobody notices are missing.
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 9 and each step above it as 6 dB. PROVISIONAL, like the rest of the
// scaling: the raw value is on screen and in the log, so a real radio settles
// it rather than this comment.
const S9_RAW = 9;
const DB_PER_RAW = 6;
function sParts(rawV: number): { s: number; over: number; label: string } {
if (rawV >= S9_RAW) {
const over = Math.max(0, Math.round((rawV - S9_RAW) * DB_PER_RAW));
// Raw S-meter → S units, CALIBRATED against a real K3 beside its own display
// (2026-08): raw 5 reads S7 on the radio, raw 9 reads S9+20. So S9 sits near
// raw 6.5 — not 9, which showed everything two S-units low — and each raw step
// above it is worth ~8 dB, shown in the 10 dB steps the K3's own meter uses.
// A Kenwood answers 0-30 on the same command and keeps the simple 1-per-raw
// scale until someone calibrates one against a real radio too.
const K3_S9_RAW = 6.5;
const K3_DB_PER_RAW = 8;
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' };
}
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}` };
}
@@ -211,14 +215,15 @@ export function ElecraftPanel({ onReportRST }: { onReportRST?: (rst: string) =>
<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}
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={() => {
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));
}}
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:
a match that looks ideal on an antenna nobody has measured is the one
reading that can cost a radio. */}
+114 -309
View File
@@ -1,11 +1,12 @@
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 {
GetIcomState, IcomRefresh,
IcomSetAFGain, IcomSetRFGain, IcomSetNB, IcomSetNBLevel, IcomSetNR, IcomSetNRLevel,
IcomSetANF, IcomSetAPF, IcomSetAGC, IcomSetPreamp, IcomSetAtt, IcomSetFilter,
IcomSetRFPower, IcomSetMicGain, IcomSetSplit, IcomTune, IcomSetPTT,
IcomSetScope, IcomScopeData, IcomSetScopeMode, IcomSetScopeEdges, GetCATState, SetCATFrequency, SetCATMode,
AudioMonitorActive, AudioStartMonitor, AudioStopMonitor,
IcomSetRFPower, IcomSetMicGain, IcomSetSplit, IcomTune, IcomSetATU, IcomConsolePTT,
GetCATState, SetCATFrequency, SetCATMode,
IcomSetRIT, IcomSetRITOn, IcomSetXITOn,
IcomSetAntenna, IcomSetPBTInner, IcomSetPBTOuter, IcomSetManualNotch, IcomSetNotchPos,
IcomSetSquelch, IcomSetComp, IcomSetCompLevel, IcomSetMonitor, IcomSetMonLevel,
@@ -19,7 +20,7 @@ import { ShiftRow } from '@/components/ShiftRow';
type IcomState = {
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;
rf_power: number; mic_gain: number;
af_gain: number; rf_gain: number;
@@ -79,17 +80,18 @@ function bandsFor(model?: string): Band[] {
// 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.
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
// 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
// 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 }[] {
const m = (model ?? '').toUpperCase();
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' }];
}
if (m.includes('9700')) return [OFF, { v: '10', l: '10dB' }];
@@ -128,9 +130,38 @@ function fmtVFO(hz?: number): string {
}
// 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 {
if (!cur) return false;
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;
}
@@ -241,11 +272,11 @@ 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="h-full rounded-full transition-[width] duration-150" style={{ width: `${v}%`, background: accent }} />
</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) {
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>;
}
@@ -253,6 +284,13 @@ function Meter({ label, value, accent, scale, onClick, title }: { label: string;
// 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
// 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 } {
if (v >= 47) {
const over = Math.max(0, Math.round((v - 47) * 60 / 47));
@@ -280,294 +318,31 @@ function wfColor(v: number): [number, number, number] {
return WF_STOPS[WF_STOPS.length - 1][1];
}
// ScopePanadapter — enables the rig's spectrum-scope stream and draws the
// reassembled sweep as a modern SDR panadapter: a glowing filled spectrum trace
// on top and a scrolling colour waterfall below. Amplitudes are raw rig scale
// (~0-160), normalised to the tallest recent peak so the trace fills the height.
function ScopePanadapter() {
const { t } = useI18n();
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
// Some radios control their scope over CI-V but never stream it (IC-7851).
// Saying so beats a black rectangle, which reads as a bug in OpsLog.
const [unsupported, setUnsupported] = useState(false);
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 ◀/▶)
// The spectrum scope is GONE, deliberately. 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
// audio down with it — and chasing a per-model frame layout for a decoration
// is not worth a console that drops the link. The radio has a better scope
// on its own front panel.
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?.unsupported) setUnsupported(true);
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 && unsupported && (
<div className="px-3 py-2 text-xs text-muted-foreground">{t('icmp.scopeNoStream')}</div>
)}
{on && !unsupported && (
<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 } = {}) {
// 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 [st, setSt] = useState<IcomState>(ZERO);
const [cat, setCat] = useState<any>(null); // RigState (freq/mode/split) for the VFO display
@@ -603,7 +378,9 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
const toggleMox = () => {
const next = !txRef.current;
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 () => {
@@ -646,8 +423,13 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
// other is TX (freq_hz); otherwise there's a single VFO (freq_hz).
const split = !!cat?.split;
const mainHz: number = split ? (cat?.freq_rx_hz || 0) : (cat?.freq_hz || 0);
const subHz: number = split ? (cat?.freq_hz || 0) : 0;
const curMode: string = cat?.mode || st.mode || '';
// The sub receiver's dial is worth seeing whether or not split is on —
// 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
// CW and data); APF (audio peak filter) is CW-only. Fold USB/LSB into phone.
const um = curMode.toUpperCase();
@@ -676,6 +458,14 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
rig's LAN server stays alive in standby, so both work. */}
{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')}
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
@@ -717,7 +507,7 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
</div>
</div>
{/* 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) => {
const on = modeMatches(m, curMode);
return (
@@ -731,20 +521,28 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
</div>
</div>
{/* Live meters — always visible: S (RX, click → RST), Po in watts, SWR. */}
<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">
{/* Live meters — the SAME LED MeterBar every other console uses (Flex,
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 (
<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}
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>
{/* Spectrum panadapter (full width). */}
<ScopePanadapter />
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
{/* Band buttons + antenna selection. */}
<Card icon={Antenna} title={t('icmp.bandsAntenna')} accent="#0891b2">
@@ -784,7 +582,11 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
<Card icon={Mic} title={t('icmp.transmit')} accent="#ef4444">
<Row label={t('icmp.power')}>
<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>
{isPhone && (
<Row label={t('icmp.mic')}>
@@ -799,6 +601,9 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
{tx ? 'TX ON' : 'MOX'}
</button>
<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}
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')}>
+8 -2
View File
@@ -370,8 +370,14 @@ export function WorldMap({ fromGrid, toGrid, fromLabel, toLabel, beamAzimuths, b
if (autoZoom) {
if (from && to && arcPts) {
const bounds = L.latLngBounds([[from.lat, from.lon], [to.lat, to.lon]]);
arcPts.forEach((p) => bounds.extend(p as L.LatLngExpression));
// Latitudes clamped to Mercator's edge (±85°): the arc to a polar
// 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 });
} else if (to) {
wm.setView([to.lat, to.lon], 3);
+33 -9
View File
@@ -9,7 +9,8 @@ import {
import {
GetLookupSettings, SaveLookupSettings, ClearLookupCache, TestLookupProvider,
GetListsSettings, SaveListsSettings,
GetCATSettings, SaveCATSettings, GetRadios, SaveRadios, SetActiveRadio, DiscoverFlexRadios,
GetCATSettings, SaveCATSettings, GetRadios, SaveRadios, SetActiveRadio, ActiveRadioID, DiscoverFlexRadios,
GetAudioMonitorPref,
ListProfiles, GetActiveProfile, SaveProfile, DeleteProfile, ActivateProfile, DuplicateProfile,
GetRotators, SaveRotators, TestRotatorDevice, RotatorPark, RotatorStop,
GetRotorPresets, SaveRotorPresets, ResetRotorPresets,
@@ -1503,6 +1504,7 @@ const ICOM_MODELS: { name: string; addr: number }[] = [
{ name: 'IC-7600', addr: 0x7A },
{ name: 'IC-7610', addr: 0x98 },
{ name: 'IC-7700', addr: 0x74 },
{ name: 'IC-7760', addr: 0xB2 },
{ name: 'IC-7800', addr: 0x6A },
{ name: 'IC-7851', addr: 0x8E },
{ name: 'IC-9100', addr: 0x7C },
@@ -1600,6 +1602,7 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
// 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>({
@@ -2203,10 +2206,17 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
// buttons. See rotorPresetsLoaded for the belt to this brace.
try { setRotorPresets((((await GetRotorPresets()) ?? []) as any)); setRotorPresetsLoaded(true); } catch {}
try {
try { setListenPref(!!(await GetAudioMonitorPref())); } catch {}
const rl: any = await GetRadios();
setRadios(rl ?? []);
const act = (rl ?? []).find((r: any) => r.active) ?? (rl ?? [])[0];
setActiveRadioId(act?.id ?? '');
// 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 { setAntgenius(await GetAntGeniusSettings() as any); } catch {}
@@ -3619,6 +3629,22 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
<span className="block text-[11px] text-muted-foreground">{t('cat.icomNetAudioHint')}</span>
</span>
</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' && (
@@ -4886,7 +4912,7 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
{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">
<span aria-hidden></span>
<span>{t('wk.catWarnIcom', { backend: catCfg.enabled ? (catCfg.backend || 'none') : 'disabled' })}</span>
@@ -5690,10 +5716,7 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
function UDPIntegrationsPanelWrapper() {
return (
<>
<SectionHeader
title={t('sec.udp')}
hint={t('udp.hint')}
/>
<SectionHeader title={t('sec.udp')} />
<UDPIntegrationsPanel onError={(m) => setErr(m)} />
</>
);
@@ -6962,7 +6985,8 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
size="sm"
className="h-8"
onClick={toggleMonitor}
disabled={!monitorOn && (!audioCfg.from_radio || fromRadioIsNetwork)}
disabled={!monitorOn && (!audioCfg.from_radio || fromRadioIsNetwork)
&& !(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')}
@@ -2,6 +2,7 @@ import React, { useCallback, useEffect, useState } from 'react';
import { Plus, Trash2, Edit2, RefreshCcw, ArrowDownToLine, ArrowUpFromLine } from 'lucide-react';
import {
ListUDPIntegrations, SaveUDPIntegration, DeleteUDPIntegration, ReloadUDPIntegrations,
GetWsjtHighlight, SetWsjtHighlight, GetWsjtFollowMode, SetWsjtFollowMode,
} from '../../wailsjs/go/main/App';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
@@ -158,6 +159,12 @@ const TRIGGERS = [
type Props = { onError: (msg: string) => void };
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 [items, setItems] = useState<UDPConfig[]>([]);
const [loading, setLoading] = useState(true);
@@ -229,10 +236,24 @@ export function UDPIntegrationsPanel({ onError }: Props) {
return (
<div className="space-y-4">
<div className="text-[11px] text-muted-foreground max-w-2xl leading-relaxed">
{t('udpp.intro')}
</div>
{/* Log-aware colours in WSJT-X / JTDX's own window — lives HERE because
this panel is where the WSJT-X link is configured. */}
<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
title={t('udpp.inboundTitle')}
icon={<ArrowDownToLine className="size-4" />}
+17 -14
View File
@@ -247,15 +247,18 @@ export function WatchlistTab({ spots, spotStatus, onSpotSelect, onSpotClick }: P
<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 text-sm text-muted-foreground">
<div className="flex items-center justify-center gap-2.5 text-xs text-muted-foreground">
<Eye className="size-4 text-primary shrink-0" />
<span>
{t('wl.cTotal')} <b className="text-foreground">{counters.total}</b>
<span className="mx-1.5 opacity-50">|</span>
{t('wl.cActive')} <b className="text-info">{counters.active}</b>
<span className="mx-1.5 opacity-50">|</span>
{t('wl.cNeeded')} <b className="text-warning">{counters.needed}</b>
</span>
<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">
@@ -328,11 +331,11 @@ export function WatchlistTab({ spots, spotStatus, onSpotSelect, onSpotClick }: P
const list = neededOnly ? all.filter((s) => !workedFor(e, s)) : all;
return (
<div key={e.callsign}
className={cn('rounded-lg border bg-card p-3',
needed > 0 ? 'border-warning/50' : 'border-border',
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 text-primary">{e.callsign}</span>
<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"
@@ -340,7 +343,7 @@ export function WatchlistTab({ spots, spotStatus, onSpotSelect, onSpotClick }: P
<Trophy className="size-3" /> {t('wl.contest')}
</span>
)}
{e.isExpedition && chip('var(--chart-5)', t('wl.expedition'))}
{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 && (
@@ -385,8 +388,8 @@ export function WatchlistTab({ spots, spotStatus, onSpotSelect, onSpotClick }: P
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/40 hover:bg-muted text-left',
!done && 'border-l-2 border-warning')}>
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>}
<span className="font-mono font-bold text-info shrink-0">{s.dx_call}</span>
<span className="text-muted-foreground truncate flex-1 min-w-0 max-w-56">{(s as any).country ?? ''}</span>
File diff suppressed because one or more lines are too long
+5 -5
View File
@@ -36,17 +36,17 @@ export function inferSpotMode(comment: string, freqHz: number): string {
type Seg = [number, number, string];
const segs: Seg[] = [
[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'],
[5.3, 5.5, '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.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.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.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.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.07, 28.3, 'DATA'], [28.3, 29.7, 'SSB'],
[50.0, 50.1, 'CW'], [50.313, 50.316, 'FT8'], [50.318, 50.321, 'FT4'],
+1 -1
View File
@@ -1,6 +1,6 @@
// Single source of truth for the app version shown in the UI (header + About).
// Bump this on a release (the release script updates it alongside telemetry.go).
export const APP_VERSION = '0.26.23';
export const APP_VERSION = '0.27.2';
// Author / credits, shown in Help -> About.
export const APP_AUTHOR = 'F4BPO';
+20
View File
@@ -46,6 +46,8 @@ 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 AmpFanMode(arg1:string,arg2:string):Promise<void>;
@@ -140,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 ConfigureDecoderMode(arg1:string):Promise<void>;
export function ConnectAllClusters():Promise<void>;
export function ConnectClusterServer(arg1:number):Promise<void>;
@@ -404,6 +408,8 @@ export function GetAntGeniusSettings():Promise<main.AntGeniusSettings>;
export function GetAntGeniusStatus():Promise<antgenius.Status>;
export function GetAudioMonitorPref():Promise<boolean>;
export function GetAudioSettings():Promise<main.AudioSettings>;
export function GetAutostartPrograms():Promise<Array<main.AutostartProgram>>;
@@ -616,6 +622,10 @@ export function GetWinkeyerStatus():Promise<winkeyer.Status>;
export function GetWorkedCallVariants():Promise<boolean>;
export function GetWsjtFollowMode():Promise<boolean>;
export function GetWsjtHighlight():Promise<boolean>;
export function GetYaesuBandAntennas():Promise<Record<string, number>>;
export function GetYaesuState():Promise<cat.YaesuTXState>;
@@ -626,6 +636,8 @@ export function HaltDecodeTx(arg1:string,arg2:boolean):Promise<void>;
export function HasBuiltinReferences(arg1:string):Promise<boolean>;
export function IcomConsolePTT(arg1:boolean):Promise<void>;
export function IcomRefresh():Promise<void>;
export function IcomScopeData():Promise<cat.ScopeSweep>;
@@ -640,6 +652,8 @@ export function IcomSetANF(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 IcomSetAntiVOX(arg1:number):Promise<void>;
@@ -700,6 +714,8 @@ export function IcomSetScopeMode(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 IcomSetVOX(arg1:boolean):Promise<void>;
@@ -1236,6 +1252,10 @@ export function SetWinkeyerTrace(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 SetYaesuAGC(arg1:string):Promise<void>;
+40
View File
@@ -30,6 +30,10 @@ export function ActiveRadioID() {
return window['go']['main']['App']['ActiveRadioID']();
}
export function ActiveRadioMyRig() {
return window['go']['main']['App']['ActiveRadioMyRig']();
}
export function AddQSO(arg1) {
return window['go']['main']['App']['AddQSO'](arg1);
}
@@ -218,6 +222,10 @@ export function 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() {
return window['go']['main']['App']['ConnectAllClusters']();
}
@@ -746,6 +754,10 @@ export function GetAntGeniusStatus() {
return window['go']['main']['App']['GetAntGeniusStatus']();
}
export function GetAudioMonitorPref() {
return window['go']['main']['App']['GetAudioMonitorPref']();
}
export function GetAudioSettings() {
return window['go']['main']['App']['GetAudioSettings']();
}
@@ -1170,6 +1182,14 @@ export function 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() {
return window['go']['main']['App']['GetYaesuBandAntennas']();
}
@@ -1190,6 +1210,10 @@ export function HasBuiltinReferences(arg1) {
return window['go']['main']['App']['HasBuiltinReferences'](arg1);
}
export function IcomConsolePTT(arg1) {
return window['go']['main']['App']['IcomConsolePTT'](arg1);
}
export function IcomRefresh() {
return window['go']['main']['App']['IcomRefresh']();
}
@@ -1218,6 +1242,10 @@ export function IcomSetAPF(arg1) {
return window['go']['main']['App']['IcomSetAPF'](arg1);
}
export function IcomSetATU(arg1) {
return window['go']['main']['App']['IcomSetATU'](arg1);
}
export function IcomSetAntenna(arg1) {
return window['go']['main']['App']['IcomSetAntenna'](arg1);
}
@@ -1338,6 +1366,10 @@ export function IcomSetSplit(arg1) {
return window['go']['main']['App']['IcomSetSplit'](arg1);
}
export function IcomSetSplitOffset(arg1) {
return window['go']['main']['App']['IcomSetSplitOffset'](arg1);
}
export function IcomSetSquelch(arg1) {
return window['go']['main']['App']['IcomSetSquelch'](arg1);
}
@@ -2410,6 +2442,14 @@ export function 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) {
return window['go']['main']['App']['SetYaesuAFGain'](arg1);
}
+6
View File
@@ -983,6 +983,7 @@ export namespace cat {
mode?: string;
transmitting: boolean;
split: boolean;
sub_hz: number;
s_meter: number;
power_meter: number;
swr_meter: number;
@@ -1006,6 +1007,7 @@ export namespace cat {
att: number;
filter: number;
antenna: number;
atu_on: boolean;
pbt_inner: number;
pbt_outer: number;
manual_notch: boolean;
@@ -1030,6 +1032,7 @@ export namespace cat {
this.mode = source["mode"];
this.transmitting = source["transmitting"];
this.split = source["split"];
this.sub_hz = source["sub_hz"];
this.s_meter = source["s_meter"];
this.power_meter = source["power_meter"];
this.swr_meter = source["swr_meter"];
@@ -1053,6 +1056,7 @@ export namespace cat {
this.att = source["att"];
this.filter = source["filter"];
this.antenna = source["antenna"];
this.atu_on = source["atu_on"];
this.pbt_inner = source["pbt_inner"];
this.pbt_outer = source["pbt_outer"];
this.manual_notch = source["manual_notch"];
@@ -1079,6 +1083,7 @@ export namespace cat {
s_meter: number;
s_meter_raw: number;
power_meter: number;
power_w: number;
swr: number;
swr_raw: number;
rf_power: number;
@@ -1116,6 +1121,7 @@ export namespace cat {
this.s_meter = source["s_meter"];
this.s_meter_raw = source["s_meter_raw"];
this.power_meter = source["power_meter"];
this.power_w = source["power_w"];
this.swr = source["swr"];
this.swr_raw = source["swr_raw"];
this.rf_power = source["rf_power"];
+8 -4
View File
@@ -27,27 +27,31 @@ type modeSeg struct {
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_576_000, "FT8"}, {3_500_000, 3_580_000, "CW"},
{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_300_000, 5_500_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_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_917_000, "FT8"},
{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"},
+23
View File
@@ -356,6 +356,29 @@ func (m *Manager) StartTXAudio(micDev, toRadioDev string) error {
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.
func (m *Manager) StopTXAudio() {
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
// an operator hunting through Windows sound settings for a device that never
// 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)")
+11 -4
View File
@@ -572,9 +572,13 @@ type IcomTXState struct {
// Transmit + live status (polled).
Transmitting bool `json:"transmitting"`
Split bool `json:"split"`
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)
// SubHz is the unselected VFO / sub receiver's frequency — shown on the
// console's SUB display whether or not split is on: a dual-receiver rig
// (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).
RITHz int `json:"rit_hz"` // RIT/XIT offset, signed Hz
RITOn bool `json:"rit_on"`
@@ -598,7 +602,8 @@ type IcomTXState struct {
Att int `json:"att"` // dB attenuation, 0=off
Filter int `json:"filter"` // 1 | 2 | 3 (FIL1/2/3)
// 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).
PBTInner int `json:"pbt_inner"`
PBTOuter int `json:"pbt_outer"`
@@ -636,6 +641,8 @@ type IcomController interface {
SetRFPower(int) error
SetMicGain(int) error
SetIcomSplit(bool) error
SetIcomSplitOffset(bool, int64) error
SetATU(bool) error
TuneATU() error
SetScope(bool) error // enable/disable the spectrum-scope waveform stream
SetScopeMode(bool) error // true = fixed span, false = center-on-VFO
+7
View File
@@ -36,6 +36,7 @@ const (
CmdVfoFreq = 0x25 // read a specific VFO's freq (sub 0x00 selected, 0x01 unselected)
CmdPTT = 0x1C // sub 0x00 = PTT
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)
CmdPower = 0x18 // power on/off (sub 0x01 = on, 0x00 = off; on needs an FE wake preamble)
@@ -130,6 +131,8 @@ const (
ModeFM = 0x05
ModeCWR = 0x07
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
@@ -305,6 +308,8 @@ func ModeToADIF(m byte, data bool) string {
return "CW"
case ModeRTTY, ModeRTTYR:
return "RTTY"
case ModePSK, ModePSKR:
return "PSK31"
case ModeAM:
return "AM"
case ModeFM:
@@ -357,6 +362,8 @@ func ModelName(addr byte) string {
return "IC-9700"
case 0xA4:
return "IC-705"
case 0xB2:
return "IC-7760"
case 0xB6:
return "IC-7300MKII"
}
+132 -11
View File
@@ -22,17 +22,20 @@ package cat
// audio stream is opt-in and entirely separate from control/CI-V.
import (
"fmt"
"net"
"sync"
"sync/atomic"
"time"
)
// icaAudioOffset is where the PCM payload begins inside an audio data packet
// (wfview audio_packet: 16-byte common header + ident@0x10 + datalen@0x12 +
// sendseq@0x14 → audio@0x16). Isolated as a const so a capture-confirmed change
// is a one-line edit.
const icaAudioOffset = 0x16
// icaAudioOffset is where the PCM payload begins inside an audio data packet.
// CONFIRMED on a real IC-7760 (2026-08-29): 16-byte common header, ident@0x10,
// send seq (BE) @0x12, payload length (BE uint32) @0x14 — 0x500 observed on
// every packet — and the PCM starts at 0x18. The 0x16 first guessed from
// 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
// offset verification. After the layout is confirmed on a real rig this can go to
@@ -54,8 +57,16 @@ type icomAudio struct {
rxLastSeq uint16
rxMissing map[uint16]int
dumped int // packets hex-dumped so far (≤ icaDumpFirst)
lastRx atomic.Int64 // UnixNano of last packet (liveness)
dumped int // packets hex-dumped so far (≤ icaDumpFirst)
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{}
closeOnce sync.Once
@@ -100,6 +111,7 @@ func dialIcomAudio(host string, sink func([]byte), cancel <-chan struct{}) (*ico
_ = conn.SetReadBuffer(1 << 20)
a := &icomAudio{
conn: conn, aID: aID, aRemote: aRemote,
started: time.Now(),
sink: sink,
rxMissing: make(map[uint16]int),
done: make(chan struct{}),
@@ -115,6 +127,7 @@ func dialIcomAudio(host string, sink func([]byte), cancel <-chan struct{}) (*ico
func (a *icomAudio) audioPump() {
buf := make([]byte, 8192)
lastIdle := time.Now()
lastPing := time.Now()
lastReq := time.Now()
for {
select {
@@ -132,12 +145,19 @@ func (a *icomAudio) audioPump() {
case typ == 0x05: // rig-initiated disconnect
debugLog.Printf("icom audio: rig sent DISCONNECT — audio stream dropped by the rig")
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 {
a.dumped++
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]...)
a.sink(payload)
}
@@ -147,6 +167,11 @@ func (a *icomAudio) audioPump() {
_, _ = a.conn.Write(icnCtrl(0x00, 0, a.aID, a.aRemote))
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 {
a.sendRetransmitReq()
lastReq = time.Now()
@@ -157,26 +182,36 @@ func (a *icomAudio) audioPump() {
// trackRxSeq / sendRetransmitReq mirror icomNet's receive-side retransmit exactly
// (audio is as loss-sensitive as the scope stream). Duplicated deliberately so
// 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 {
a.rxHaveSeq = true
a.rxLastSeq = seq
return
return true
}
switch d := int16(seq - a.rxLastSeq); {
case d == 0:
return false
case d < 0:
delete(a.rxMissing, seq)
return false
case d == 1:
a.rxLastSeq = seq
return true
case int(d) <= icnMaxMissing:
for f := a.rxLastSeq + 1; f != seq; f++ {
a.rxMissing[f] = 0
}
a.rxLastSeq = seq
return true
default:
a.rxMissing = make(map[uint16]int)
a.rxLastSeq = seq
return true
}
}
@@ -217,3 +252,89 @@ func (a *icomAudio) sendRetransmitReq() {
_, _ = 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",
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) {
if strings.TrimSpace(host) == "" {
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()
cancel := b.dialCancel
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
}
@@ -97,6 +119,19 @@ type icomNet struct {
// CAT goroutine) and during dial — never by the pump — so no lock is needed.
vTracked 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)
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 {
debugLog.Printf("icom net TX: % X", p)
}
seq := n.vTracked
pkt := icnCivData(seq, n.vID, n.vRemote, n.vCivSeq, p)
n.seqMu.Lock()
seq, civSeq := n.vTracked, n.vCivSeq
n.vTracked++
n.vCivSeq++
n.seqMu.Unlock()
n.txCiv.Add(1)
pkt := icnCivData(seq, n.vID, n.vRemote, civSeq, p)
n.sentMu.Lock()
n.sentBuf[seq] = pkt
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() {
buf := make([]byte, 4096)
lastIdle := time.Now()
lastCtrlPing := time.Now()
lastToken := time.Now() // token was just granted during dial
for {
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
// 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 {
n.renewToken()
lastToken = time.Now()
@@ -359,6 +403,25 @@ func (n *icomNet) civPump() {
buf := make([]byte, 8192)
lastIdle := 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 {
select {
case <-n.done:
@@ -366,7 +429,14 @@ func (n *icomNet) civPump() {
default:
}
_ = 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()
switch typ := icnLE.Uint16(buf[4:]); {
case typ == 0x07: // ping
@@ -379,6 +449,13 @@ func (n *icomNet) civPump() {
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")
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
civBytes := buf[0x15:k]
cp := append([]byte(nil), civBytes...)
@@ -388,6 +465,7 @@ func (n *icomNet) civPump() {
// feeder in IcomSerial picks them up. Everything else is a control
// reply → rx → Read.
if len(civBytes) >= 5 && civBytes[4] == 0x27 {
lastScope = time.Now()
icnEnqueueDrop(n.scopeRx, cp)
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 {
_, _ = 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()
}
if time.Since(lastReq) > 100*time.Millisecond {
n.sendRetransmitReq()
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,
cToken: token, cTokReq: tokReq,
cSentBuf: make(map[uint16][]byte),
started: time.Now(),
}
n.markRx() // the successful handshake counts as initial rig activity
// 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:])
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 {
case 0x04: // iAmHere
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[0x60:0x70], icnPasscode(user))
b[0x70] = rxEnable // rxenable: 1 opens the 50003 RX audio stream, 0 = CI-V only
b[0x71] = 0x00 // txenable (Phase 5)
b[0x72] = 0x10 // rxcodec
b[0x73] = 0x04 // txcodec
// TX rides the same audio session: whenever the operator wants RX audio the
// TX side is opened with it, so the voice keyer can play to the radio with
// 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[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[0x80:], uint32(audioPort))
icnBE.PutUint32(b[0x84:], 100)
@@ -855,6 +1003,26 @@ func icnConnInfo(seq, innerSeq, tokReq uint16, sentid, rcvdid, token uint32, use
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 {
b := make([]byte, 0x16)
icnLE.PutUint32(b[0:], 0x16)
@@ -903,3 +1071,38 @@ func icnPasscode(s string) []byte {
}
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
}
+168 -12
View File
@@ -116,7 +116,13 @@ type IcomSerial struct {
// "alive but silent" tolerance below, which used to be
// unbounded and left the display frozen for ever
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)
// When the console last asked for the DSP snapshot. The meters and the
// front-panel rotation are polled ONLY while something is displaying them:
@@ -262,6 +268,21 @@ func (b *IcomSerial) Connect() error {
// 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.
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
// 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
@@ -347,7 +368,12 @@ func (b *IcomSerial) ReadState() (RigState, error) {
case readerGone:
debugLog.Printf("icom net: the CI-V reader has exited — the connection is dead however alive the control link looks → reconnecting")
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:
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).")
}
@@ -396,6 +422,19 @@ func (b *IcomSerial) ReadState() (RigState, error) {
}
b.dspMu.Lock()
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()
}
@@ -409,8 +448,13 @@ func (b *IcomSerial) ReadState() (RigState, error) {
// all, for the user's Set* commands.
if b.pollN%4 == 1 {
b.splitOn, b.splitTXFreq = false, 0
if on, ok := b.readSplit(); ok && on {
if txHz, ok2 := b.readTXFreq(); ok2 && txHz > 0 {
on, okSplit := b.readSplit()
// 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
}
}
@@ -435,12 +479,16 @@ func (b *IcomSerial) ReadState() (RigState, error) {
sm, _ = b.readMeter(civ.SubMeterS)
po, swr = 0, 0
if tx {
now := time.Now()
if v, ok := b.readMeter(civ.SubMeterPo); ok {
po = v
po = b.powerPeak.update(v, now)
}
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()
@@ -509,6 +557,13 @@ func (b *IcomSerial) refreshFrontPanel() {
b.dsp.Filter = int(f)
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()
}
}
}
@@ -559,6 +614,18 @@ func (b *IcomSerial) SetMode(mode string) error {
}
// Filter 0x01 (FIL1) is the conventional default for the data-mode set.
_ = 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
}
@@ -1482,6 +1549,12 @@ func (b *IcomSerial) modeCode(mode string) (code byte, data bool, err error) {
return civ.ModeFM, false, nil
case "RTTY", "FSK":
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":
// Digital data modes ride on USB with the data flag set (FT8 etc.).
return civ.ModeUSB, true, nil
@@ -1832,10 +1905,16 @@ func (b *IcomSerial) SetMicGain(p int) 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 {
// Enable split with the usual "work him up" TX offset: +1 kHz on CW,
// +5 kHz otherwise (SSB). Set the unselected (TX) VFO to RX+offset first,
// then turn split on. 0x25 0x01 + BCD sets the unselected VFO's frequency.
// Set the unselected (TX) VFO to RX+offset first, then turn split on.
// 0x25 0x01 + BCD sets the unselected VFO's frequency.
rx := b.curFreq
if rx <= 0 {
if hz, err := b.readFreq(); err == nil {
@@ -1843,12 +1922,39 @@ func (b *IcomSerial) SetIcomSplit(on bool) error {
}
}
if rx > 0 {
offset := int64(5000)
if b.curModeByte == civ.ModeCW || b.curModeByte == civ.ModeCWR {
offset = 1000
offset := offsetHz
if offset <= 0 {
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)...)...)
}
// 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 {
return err
@@ -1982,6 +2088,17 @@ func (b *IcomSerial) TuneATU() error {
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)) {
b.dspMu.Lock()
fn(&b.dsp)
@@ -2024,3 +2141,42 @@ func agcValue(name string) byte {
}
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")
}
+18 -4
View File
@@ -52,9 +52,15 @@ type KenwoodTXState struct {
SMeterRaw int `json:"s_meter_raw"`
// PowerMeter is 0-100 while transmitting. SWR is the ratio; 0 means "not
// measured", NOT a perfect match.
PowerMeter int `json:"power_meter"`
SWR float64 `json:"swr"`
SWRRaw int `json:"swr_raw"`
PowerMeter int `json:"power_meter"`
// PowerW is the transmit power in WATTS, derived from the bargraph and the
// 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
AFGain int `json:"af_gain"` // 0-100
@@ -162,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
// reads as a live transmission.
k.panel.PowerMeter = 0
k.panel.PowerW = 0
k.panel.SWR, k.panel.SWRRaw = 0, 0
k.powerPeak, k.swrPeak = meterPeak{}, meterPeak{}
// The S-meter only means anything while receiving.
@@ -341,6 +348,13 @@ func (k *Kenwood) readTXMeters() {
defer func() { k.noLatch = false }()
if v, ok := k.askNum("BG;", "BG", 2); ok {
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
// ratio. "SW023;" is 2.3:1, and "SW999;" is the 99.9:1 it reports instead of
@@ -349,7 +363,7 @@ func (k *Kenwood) readTXMeters() {
if v, ok := k.askNum("SW;", "SW", 3); ok {
k.panel.SWRRaw = v
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 {
+7
View File
@@ -553,6 +553,13 @@ func (o *OmniRig) SetFrequency(hz int64) error {
props := []string{prop, "Freq"}
if onSubVFO {
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 {
if _, e := oleutil.PutProperty(o.rig, p, hz32); e != nil {
+19
View File
@@ -905,3 +905,22 @@ func yaesuSplitCommand(cmd, vfo string, on bool) string {
}
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
}
+34 -5
View File
@@ -156,6 +156,8 @@ type Event struct {
DecodeModeRaw string
// DecodeMsgRaw is the message as sent, untrimmed — see DecodeModeRaw.
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
// "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
@@ -212,6 +214,9 @@ type Server struct {
// lastFrom is the address each program's packets arrive from — where a Reply
// has to be sent. See SendReply.
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.
//
// 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 {
return &Server{
cfg: cfg,
out: out,
mgr: mgr,
stop: make(chan struct{}),
done: make(chan struct{}),
cfg: cfg,
out: out,
mgr: mgr,
onNewInstance: mgr.onNewInstance,
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.
s.mu.Lock()
inst := s.instanceLabel(w.ProgramID, remote)
newInstance := false
if inst != "" && remote != nil {
if s.lastFrom == nil {
s.lastFrom = map[string]*net.UDPAddr{}
}
if _, known := s.lastFrom[inst]; !known {
newInstance = true
}
s.lastFrom[inst] = remote
}
onNew := s.onNewInstance
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
// offsets can be turned into RF frequencies for the panadapter.
if w.FreqHz > 0 && !w.IsDecode {
@@ -580,6 +596,7 @@ func (s *Server) handle(pkt []byte, remote *net.UDPAddr) {
ev.DecodeModeRaw = w.Mode
ev.DecodeMsg = w.DecodeMsg
ev.DecodeMsgRaw = w.DecodeMsgRaw
ev.DecodeIsNew = w.DecodeIsNew
ev.DecodeAt = decodeTime(w.DecodeMsSinceMidnight)
ev.DecodeTRPeriod = tr
ev.DecodeDial = dial
@@ -803,6 +820,10 @@ type Manager struct {
repo *Repo
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
// rather than one per QSO logged.
noADIFOnce sync.Once
@@ -940,3 +961,11 @@ func (m *Manager) StopAll() {
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
}
+119 -79
View File
@@ -722,15 +722,14 @@ func (r *Repo) MarkUploadedBatch(ctx context.Context, statusCol, dateCol, date s
if len(ids) == 0 {
return nil
}
ph := strings.TrimSuffix(strings.Repeat("?,", len(ids)), ",")
args := make([]any, 0, len(ids)+2)
args = append(args, date, db.NowISO())
for _, id := range ids {
args = append(args, id)
}
_, err := r.db.ExecContext(ctx,
`UPDATE qso SET `+statusCol+` = 'Y', `+dateCol+` = ?, updated_at = ? WHERE id IN (`+ph+`)`,
args...)
now := db.NowISO()
_, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
args := append([]any{date, now}, idArgs...)
_, err := r.db.ExecContext(ctx,
`UPDATE qso SET `+statusCol+` = 'Y', `+dateCol+` = ?, updated_at = ? WHERE id IN (`+ph+`)`,
args...)
return 0, err
})
if err != nil {
return fmt.Errorf("mark uploaded batch (%d): %w", len(ids), err)
}
@@ -872,6 +871,35 @@ var bulkEditableCols = map[string]bool{
// 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,
@@ -886,23 +914,23 @@ func (r *Repo) BulkSetIntField(ctx context.Context, ids []int64, column string,
if len(ids) == 0 {
return 0, nil
}
ph := make([]string, len(ids))
args := make([]any, 0, len(ids)+2)
var val any
if v != nil {
val = *v
}
args = append(args, val, db.NowISO())
for i, id := range ids {
ph[i] = "?"
args = append(args, id)
}
res, err := r.db.ExecContext(ctx,
"UPDATE qso SET "+column+" = ?, updated_at = ? WHERE id IN ("+strings.Join(ph, ",")+")", args...)
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 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
}
@@ -913,13 +941,6 @@ func (r *Repo) BulkSetField(ctx context.Context, ids []int64, column, value stri
if len(ids) == 0 {
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 = ?"
if column == "mode" {
// A submode belongs to the mode it was recorded under. Left behind, it
@@ -928,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.
set += ", submode = ''"
}
res, err := r.db.ExecContext(ctx,
`UPDATE qso SET `+set+` WHERE id IN (`+strings.Join(ph, ",")+`)`,
args...)
now := db.NowISO()
n, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
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 {
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
}
@@ -995,26 +1022,26 @@ func (r *Repo) BulkSetExtra(ctx context.Context, ids []int64, adifKey, value str
if len(ids) == 0 {
return 0, nil
}
ph := make([]string, len(ids))
args := make([]any, 0, len(ids)+2)
head := []any{}
expr := `json_set(COALESCE(extras_json, '{}'), '$.` + adifKey + `', ?)`
if value == "" {
expr = `json_remove(COALESCE(extras_json, '{}'), '$.` + adifKey + `')`
} else {
args = append(args, value)
head = append(head, value)
}
args = append(args, db.NowISO())
for i, id := range ids {
ph[i] = "?"
args = append(args, id)
}
res, err := r.db.ExecContext(ctx,
`UPDATE qso SET extras_json = `+expr+`, updated_at = ? WHERE id IN (`+strings.Join(ph, ",")+`)`,
args...)
head = append(head, db.NowISO())
n, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
args := append(append([]any{}, head...), idArgs...)
res, err := r.db.ExecContext(ctx,
`UPDATE qso SET extras_json = `+expr+`, updated_at = ? WHERE id IN (`+ph+`)`, args...)
if err != nil {
return 0, err
}
return res.RowsAffected()
})
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
}
@@ -1026,20 +1053,19 @@ func (r *Repo) BulkSetFrequency(ctx context.Context, ids []int64, freqHz int64,
if len(ids) == 0 {
return 0, nil
}
ph := make([]string, len(ids))
args := make([]any, 0, len(ids)+3)
args = append(args, freqHz, band, db.NowISO())
for i, id := range ids {
ph[i] = "?"
args = append(args, id)
}
res, err := r.db.ExecContext(ctx,
`UPDATE qso SET freq_hz = ?, band = ?, updated_at = ? WHERE id IN (`+strings.Join(ph, ",")+`)`,
args...)
now := db.NowISO()
n, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
args := append([]any{freqHz, band, now}, idArgs...)
res, err := r.db.ExecContext(ctx,
`UPDATE qso SET freq_hz = ?, band = ?, updated_at = ? WHERE id IN (`+ph+`)`, args...)
if err != nil {
return 0, err
}
return res.RowsAffected()
})
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
}
@@ -1201,17 +1227,16 @@ func (r *Repo) DeleteMany(ctx context.Context, ids []int64) (int64, error) {
if len(ids) == 0 {
return 0, nil
}
ph := make([]string, len(ids))
args := make([]any, len(ids))
for i, id := range ids {
ph[i] = "?"
args[i] = id
}
res, err := r.db.ExecContext(ctx, `DELETE FROM qso WHERE id IN (`+strings.Join(ph, ",")+`)`, args...)
n, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
res, err := r.db.ExecContext(ctx, `DELETE FROM qso WHERE id IN (`+ph+`)`, idArgs...)
if err != nil {
return 0, err
}
return res.RowsAffected()
})
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
}
@@ -1701,27 +1726,42 @@ func (r *Repo) IterateByIDs(ctx context.Context, ids []int64, fn func(QSO) error
if len(ids) == 0 {
return nil
}
ph := strings.TrimSuffix(strings.Repeat("?,", len(ids)), ",")
args := make([]any, len(ids))
for i, id := range ids {
args[i] = id
}
rows, err := r.db.QueryContext(ctx,
`SELECT `+selectCols+` FROM qso WHERE id IN (`+ph+`) ORDER BY qso_date ASC, id ASC`, args...)
// Chunked like every other by-ids statement (the one-placeholder-per-id IN
// died at 168k with "too many SQL variables") — and because each chunk is
// only locally ordered, the rows are collected and sorted once at the end
// so the chronological contract holds across chunks.
var all []QSO
_, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
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 {
return fmt.Errorf("query qso: %w", err)
}
defer rows.Close()
for rows.Next() {
q, err := scanQSO(rows)
if err != nil {
return err
sort.Slice(all, func(i, j int) bool {
if !all[i].QSODate.Equal(all[j].QSODate) {
return all[i].QSODate.Before(all[j].QSODate)
}
return all[i].ID < all[j].ID
})
for _, q := range all {
if err := fn(q); err != nil {
return err
}
}
return rows.Err()
return nil
}
// GridKey builds the lookup key for the worked-grid index.
+7 -1
View File
@@ -246,6 +246,11 @@ func (s *Server) serve(c net.Conn) {
s.releasePTT(fmt.Sprintf("client %s left", 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)
w := bufio.NewWriter(c)
for {
@@ -265,7 +270,8 @@ func (s *Server) serve(c net.Conn) {
// 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
// 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"))
}
if resp != "" {
+1 -1
View File
@@ -21,7 +21,7 @@ import (
const (
// appVersion is stamped on every heartbeat (and could feed the About box).
appVersion = "0.26.23"
appVersion = "0.27.2"
// posthogHost is the PostHog ingestion endpoint. EU cloud by default; change
// to https://us.i.posthog.com for a US project.