Compare commits
110
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2cde1a2c27 | ||
|
|
53100eb6c8 | ||
|
|
3b555219d2 | ||
|
|
ba35d4094c | ||
|
|
9bd6d988aa | ||
|
|
daabbc63c7 | ||
|
|
997bc81d5e | ||
|
|
3c59507bc3 | ||
|
|
721c43d569 | ||
|
|
25eda98612 | ||
|
|
0b909a4d63 | ||
|
|
37298afd77 | ||
|
|
5a77fdf68f | ||
|
|
31c898ad7f | ||
|
|
88c9756edf | ||
|
|
7b15b534cd | ||
|
|
8e7ecc3d51 | ||
|
|
7f9019c7bc | ||
|
|
a1a3bad682 | ||
|
|
1b746f2452 | ||
|
|
3db49e1213 | ||
|
|
605c934d33 | ||
|
|
dad762a0f1 | ||
|
|
97567d15dd | ||
|
|
fc080f3719 | ||
|
|
ce9ea10d68 | ||
|
|
dc94aa94b6 | ||
|
|
db7ac771b1 | ||
|
|
19134ea23c | ||
|
|
b12011fab7 | ||
|
|
d62cd10478 | ||
|
|
7de7cb96c3 | ||
|
|
dbc97ad61b | ||
|
|
7966b01900 | ||
|
|
f98e95fe9e | ||
|
|
392b93f089 | ||
|
|
9c459c754f | ||
|
|
ec967e29cf | ||
|
|
58e36667a7 | ||
|
|
77aba73096 | ||
|
|
da8f60a7b3 | ||
|
|
e8b5444fc2 | ||
|
|
08bc401681 | ||
|
|
7ac342e2d4 | ||
|
|
b244575937 | ||
|
|
c878742e50 | ||
|
|
13434ca36c | ||
|
|
6345710de5 | ||
|
|
0cab1c1e6b | ||
|
|
1c71495446 | ||
|
|
2c0158b75c | ||
|
|
a2b019b280 | ||
|
|
1fba7d2d57 | ||
|
|
490941f506 | ||
|
|
6bf759b6ae | ||
|
|
43e5088e96 | ||
|
|
582fa561b2 | ||
|
|
7f328d4eb5 | ||
|
|
b2eb6a4b1e | ||
|
|
c2db4c5f7e | ||
|
|
b246c4d10a | ||
|
|
6d4a110949 | ||
|
|
ffbbff80d6 | ||
|
|
bd2edf6624 | ||
|
|
6321948415 | ||
|
|
89e239d83f | ||
|
|
0e48ad7bb2 | ||
|
|
ad82c21dbc | ||
|
|
6f126802cd | ||
|
|
704b614c38 | ||
|
|
6eb6f1b339 | ||
|
|
dbd2fff121 | ||
|
|
dc6da67cbf | ||
|
|
ea6fb1c29c | ||
|
|
29267a865c | ||
|
|
e93d2d36a8 | ||
|
|
107c6fccf6 | ||
|
|
9350af9589 | ||
|
|
a9a6579a9a | ||
|
|
7795e13432 | ||
|
|
c9e98d5fdd | ||
|
|
72253f99fa | ||
|
|
f0d3bed8a2 | ||
|
|
30c9acf0d2 | ||
|
|
e3175ef6a3 | ||
|
|
441eb295c6 | ||
|
|
cb2f8aba72 | ||
|
|
7b9cda93bc | ||
|
|
8f64e3fee3 | ||
|
|
c4de5f2ea0 | ||
|
|
9172f504e5 | ||
|
|
7322e2ab66 | ||
|
|
29d79fb5d1 | ||
|
|
f6b70184a7 | ||
|
|
e4abcda94f | ||
|
|
284ee4ba7c | ||
|
|
10ef984962 | ||
|
|
bd8719ce99 | ||
|
|
5e38319379 | ||
|
|
7e7ad50f60 | ||
|
|
0f4e31853b | ||
|
|
c222468021 | ||
|
|
2fb4a4d0ce | ||
|
|
e4828482c4 | ||
|
|
8acfda4e42 | ||
|
|
db24c38e63 | ||
|
|
06868e9ed1 | ||
|
|
3ed643e072 | ||
|
|
f0f9898f7c | ||
|
|
73cae855ed |
@@ -44,7 +44,6 @@ import (
|
|||||||
"hamlog/internal/gridcache"
|
"hamlog/internal/gridcache"
|
||||||
"hamlog/internal/integrations/udp"
|
"hamlog/internal/integrations/udp"
|
||||||
"hamlog/internal/kpa"
|
"hamlog/internal/kpa"
|
||||||
"hamlog/internal/labels"
|
|
||||||
"hamlog/internal/lookup"
|
"hamlog/internal/lookup"
|
||||||
"hamlog/internal/lotwusers"
|
"hamlog/internal/lotwusers"
|
||||||
"hamlog/internal/netctl"
|
"hamlog/internal/netctl"
|
||||||
@@ -75,6 +74,7 @@ import (
|
|||||||
"hamlog/internal/tunergenius"
|
"hamlog/internal/tunergenius"
|
||||||
"hamlog/internal/uls"
|
"hamlog/internal/uls"
|
||||||
"hamlog/internal/ultrabeam"
|
"hamlog/internal/ultrabeam"
|
||||||
|
"hamlog/internal/watchlist"
|
||||||
"hamlog/internal/winkeyer"
|
"hamlog/internal/winkeyer"
|
||||||
|
|
||||||
wruntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
wruntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||||
@@ -96,12 +96,13 @@ const (
|
|||||||
keyLookupFailsafe = "lookup.failsafe"
|
keyLookupFailsafe = "lookup.failsafe"
|
||||||
keyLookupImages = "lookup.download_images" // 1 = expose QRZ ImageURL to UI
|
keyLookupImages = "lookup.download_images" // 1 = expose QRZ ImageURL to UI
|
||||||
|
|
||||||
keyStationCallsign = "station.callsign"
|
keyStationCallsign = "station.callsign"
|
||||||
keyStationOperator = "station.operator"
|
keyStationOperator = "station.operator"
|
||||||
keyStationMyGrid = "station.my_grid"
|
keyWatchlistContestPattern = "watchlist.contest_pattern" // auto-add contest calls containing this
|
||||||
keyStationCountry = "station.my_country"
|
keyStationMyGrid = "station.my_grid"
|
||||||
keyStationSOTA = "station.my_sota_ref"
|
keyStationCountry = "station.my_country"
|
||||||
keyStationPOTA = "station.my_pota_ref"
|
keyStationSOTA = "station.my_sota_ref"
|
||||||
|
keyStationPOTA = "station.my_pota_ref"
|
||||||
|
|
||||||
keyListsBands = "lists.bands"
|
keyListsBands = "lists.bands"
|
||||||
keyListsModes = "lists.modes"
|
keyListsModes = "lists.modes"
|
||||||
@@ -158,6 +159,7 @@ const (
|
|||||||
keyCATIcomNetUser = "cat.icom.net.user" // Icom network: Network User1 ID
|
keyCATIcomNetUser = "cat.icom.net.user" // Icom network: Network User1 ID
|
||||||
keyCATIcomNetPass = "cat.icom.net.pass" // Icom network: Network User1 password
|
keyCATIcomNetPass = "cat.icom.net.pass" // Icom network: Network User1 password
|
||||||
keyCATIcomNetAudio = "cat.icom.net.audio" // Icom network: stream RX audio on 50003 (experimental)
|
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)
|
keyCATTCIHost = "cat.tci.host" // TCI host (Expert Electronics SunSDR / ExpertSDR2)
|
||||||
keyCATTCIPort = "cat.tci.port" // TCI WebSocket port (default 40001)
|
keyCATTCIPort = "cat.tci.port" // TCI WebSocket port (default 40001)
|
||||||
keyCATTCISpots = "cat.tci.spots" // push cluster spots to the TCI panorama
|
keyCATTCISpots = "cat.tci.spots" // push cluster spots to the TCI panorama
|
||||||
@@ -736,10 +738,18 @@ type App struct {
|
|||||||
uls *uls.Store // US callsign→county/grid (offline FCC ULS), lazily opened
|
uls *uls.Store // US callsign→county/grid (offline FCC ULS), lazily opened
|
||||||
awardRefs *awardref.Repo
|
awardRefs *awardref.Repo
|
||||||
qslTemplates *qslcard.Repo
|
qslTemplates *qslcard.Repo
|
||||||
labelRepo *labels.Repo // label designer (stocks + templates)
|
watchlist *watchlist.Store // Tools → Watchlist (global watchlist.json)
|
||||||
operating *operating.Repo
|
watchAlertMu sync.Mutex // throttles watchlist alerts…
|
||||||
udp *udp.Manager
|
watchAlertAt map[string]time.Time // …per entry
|
||||||
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.
|
// 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
|
// 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
|
// nothing is transmitting at that instant — so the id is remembered from
|
||||||
@@ -1017,6 +1027,13 @@ func (a *App) startup(ctx context.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
a.dataDir = dataDir
|
a.dataDir = dataDir
|
||||||
|
// The watchlist needs nothing but its file, so it opens FIRST. It used to be
|
||||||
|
// created after the logbook connect, and a remote MySQL dial of 10-30 s left
|
||||||
|
// the tab saying "Watchlist: 0" until the next refresh tick — twenty seconds
|
||||||
|
// of an empty list for a JSON file that reads in a millisecond. (The
|
||||||
|
// auto-contest pattern still loads later, once the settings store is open.)
|
||||||
|
a.watchlist = watchlist.New(filepath.Join(dataDir, "watchlist.json"))
|
||||||
|
a.watchAlertAt = map[string]time.Time{}
|
||||||
// Settings/config database (settings + profiles). Fresh installs use
|
// Settings/config database (settings + profiles). Fresh installs use
|
||||||
// settings.db; existing installs keep their opslog.db (which also held the
|
// settings.db; existing installs keep their opslog.db (which also held the
|
||||||
// QSOs before they were split into a dedicated logbook file — see below).
|
// QSOs before they were split into a dedicated logbook file — see below).
|
||||||
@@ -1187,13 +1204,17 @@ func (a *App) startup(ctx context.Context) {
|
|||||||
}
|
}
|
||||||
a.awardRefs = awardref.NewRepo(conn)
|
a.awardRefs = awardref.NewRepo(conn)
|
||||||
a.qslTemplates = qslcard.NewRepo(conn)
|
a.qslTemplates = qslcard.NewRepo(conn)
|
||||||
a.labelRepo = labels.NewRepo(conn)
|
|
||||||
a.migrateAwardDefs() // upgrade legacy award definitions (enable + new fields)
|
a.migrateAwardDefs() // upgrade legacy award definitions (enable + new fields)
|
||||||
a.seedBuiltinReferences() // first-run: populate built-in award reference lists
|
a.seedBuiltinReferences() // first-run: populate built-in award reference lists
|
||||||
a.mirrorAwards() // keep <data>/awards/*.json in step with the database
|
a.mirrorAwards() // keep <data>/awards/*.json in step with the database
|
||||||
a.operating = operating.NewRepo(conn)
|
a.operating = operating.NewRepo(conn)
|
||||||
a.udpRepo = udp.NewRepo(conn)
|
a.udpRepo = udp.NewRepo(conn)
|
||||||
a.udp = udp.NewManager(a.udpRepo)
|
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()
|
go a.consumeUDPEvents()
|
||||||
a.cache = lookup.NewCache(conn, 30*24*time.Hour)
|
a.cache = lookup.NewCache(conn, 30*24*time.Hour)
|
||||||
a.lookup = lookup.NewManager(a.cache)
|
a.lookup = lookup.NewManager(a.cache)
|
||||||
@@ -1242,6 +1263,49 @@ func (a *App) startup(ctx context.Context) {
|
|||||||
go a.applyRelayAuto(s.FreqHz, s.Band)
|
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()
|
a.reloadCAT()
|
||||||
|
|
||||||
// The QSO logbook lives where the ACTIVE PROFILE points it: the local SQLite
|
// The QSO logbook lives where the ACTIVE PROFILE points it: the local SQLite
|
||||||
@@ -1388,6 +1452,9 @@ func (a *App) startup(ctx context.Context) {
|
|||||||
// POTA: background poller of api.pota.app so cluster spots can be tagged
|
// POTA: background poller of api.pota.app so cluster spots can be tagged
|
||||||
// when the DX station is currently activating a park. Best-effort.
|
// when the DX station is currently activating a park. Best-effort.
|
||||||
a.pota = pota.New(func(format string, args ...any) { applog.Printf(format, args...) })
|
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)
|
go a.pota.Run(a.ctx)
|
||||||
|
|
||||||
// DX Cluster (multi-server): the spot callback enriches each spot
|
// DX Cluster (multi-server): the spot callback enriches each spot
|
||||||
@@ -1467,44 +1534,6 @@ func (a *App) startup(ctx context.Context) {
|
|||||||
})
|
})
|
||||||
a.solar.Start()
|
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).
|
// NET Control store (global JSON, shared across logbooks).
|
||||||
if ns, err := netctl.Open(filepath.Join(a.dataDir, "nets.json")); err != nil {
|
if ns, err := netctl.Open(filepath.Join(a.dataDir, "nets.json")); err != nil {
|
||||||
applog.Printf("netctl: open failed: %v", err)
|
applog.Printf("netctl: open failed: %v", err)
|
||||||
@@ -1799,6 +1828,9 @@ func (a *App) setSettingGlobal(key, val string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) shutdown(ctx context.Context) {
|
func (a *App) shutdown(ctx context.Context) {
|
||||||
|
if a.watchlist != nil {
|
||||||
|
a.watchlist.Flush() // the save debounce would lose the last edits
|
||||||
|
}
|
||||||
// If the user managed to skip beforeClose (force kill, OS shutdown,
|
// If the user managed to skip beforeClose (force kill, OS shutdown,
|
||||||
// crash recovery) we still try the backup here as a best-effort
|
// crash recovery) we still try the backup here as a best-effort
|
||||||
// safety net. HasBackupToday makes a double-run a no-op.
|
// safety net. HasBackupToday makes a double-run a no-op.
|
||||||
@@ -6941,6 +6973,28 @@ func (a *App) BulkUpdateField(ids []int64, field, value string) (int64, error) {
|
|||||||
if field == "freq" {
|
if field == "freq" {
|
||||||
return a.bulkSetFrequency(ids, value)
|
return a.bulkSetFrequency(ids, value)
|
||||||
}
|
}
|
||||||
|
// The station-side numbers. Bounded so a slip cannot stamp CQ zone 400 on a
|
||||||
|
// thousand rows: DXCC entities stop short of 1000, CQ zones at 40, ITU at 90.
|
||||||
|
// Empty clears (NULL).
|
||||||
|
if field == "my_dxcc" || field == "my_cq_zone" || field == "my_itu_zone" {
|
||||||
|
var vp *int
|
||||||
|
if t := strings.TrimSpace(value); t != "" {
|
||||||
|
v, err := strconv.Atoi(t)
|
||||||
|
max := map[string]int{"my_dxcc": 999, "my_cq_zone": 40, "my_itu_zone": 90}[field]
|
||||||
|
if err != nil || v < 1 || v > max {
|
||||||
|
return 0, fmt.Errorf("%s must be a number between 1 and %d (empty to clear)", field, max)
|
||||||
|
}
|
||||||
|
vp = &v
|
||||||
|
}
|
||||||
|
n, err := a.qso.BulkSetIntField(a.ctx, ids, field, vp)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if n > 0 {
|
||||||
|
a.invalidateAwardStats()
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
// Some ADIF fields have no promoted column and live in extras_json
|
// Some ADIF fields have no promoted column and live in extras_json
|
||||||
// (OWNER_CALLSIGN) — those take the JSON path so the rest of the extras on
|
// (OWNER_CALLSIGN) — those take the JSON path so the rest of the extras on
|
||||||
// each QSO survive the edit.
|
// each QSO survive the edit.
|
||||||
@@ -8398,7 +8452,7 @@ func (a *App) ListAudioInputDevices() ([]audio.Device, error) {
|
|||||||
return devs, err
|
return devs, err
|
||||||
}
|
}
|
||||||
if a.tciAudioAvailable() {
|
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
|
return devs, nil
|
||||||
}
|
}
|
||||||
@@ -8425,7 +8479,7 @@ func (a *App) ListAudioOutputDevices() ([]audio.Device, error) {
|
|||||||
return devs, err
|
return devs, err
|
||||||
}
|
}
|
||||||
if audio.NetworkPlayerReady() {
|
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
|
return devs, nil
|
||||||
}
|
}
|
||||||
@@ -8984,6 +9038,10 @@ func (a *App) clusterEventWorker() {
|
|||||||
a.detectBandOpening(s)
|
a.detectBandOpening(s)
|
||||||
// Fire any matching alert rules (sound / visual / e-mail).
|
// Fire any matching alert rules (sound / visual / e-mail).
|
||||||
a.evaluateAlerts(s)
|
a.evaluateAlerts(s)
|
||||||
|
// The watchlist sees the same live stream the alerts do — never the
|
||||||
|
// SH/DX replay above, which would mark forty stations "just seen" with
|
||||||
|
// spots from three hours ago.
|
||||||
|
a.watchSpot(s.DXCall, s.Band, alerts.InferMode(s.Comment, s.FreqHz), s.Country, s.Comment, s.FreqHz)
|
||||||
// Mirror the spot onto the FlexRadio panadapter when enabled. Infer the
|
// Mirror the spot onto the FlexRadio panadapter when enabled. Infer the
|
||||||
// mode (from the comment, else the band plan) so clicking the spot on the
|
// mode (from the comment, else the band plan) so clicking the spot on the
|
||||||
// panadapter tunes AND switches mode — a DX cluster line carries no mode,
|
// panadapter tunes AND switches mode — a DX cluster line carries no mode,
|
||||||
@@ -9221,7 +9279,9 @@ func (a *App) QSOAudioManualReady() bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
cfg, _ := a.GetAudioSettings()
|
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.
|
// QSOAudioManualStart begins a recording when automatic recording is off.
|
||||||
@@ -9238,10 +9298,19 @@ func (a *App) QSOAudioManualStart() bool {
|
|||||||
}
|
}
|
||||||
if !a.qsoRec.Running() {
|
if !a.qsoRec.Running() {
|
||||||
cfg, _ := a.GetAudioSettings()
|
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
|
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)
|
applog.Printf("qso-rec: manual start failed: %v", err)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -10623,6 +10692,26 @@ func (a *App) AudioStartMonitor() error {
|
|||||||
return fmt.Errorf("audio not initialized")
|
return fmt.Errorf("audio not initialized")
|
||||||
}
|
}
|
||||||
cfg, _ := a.GetAudioSettings()
|
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) == "" {
|
if strings.TrimSpace(cfg.FromRadio) == "" {
|
||||||
return fmt.Errorf(`no "From radio" capture device set — pick the rig's USB Audio CODEC in Settings → Audio`)
|
return fmt.Errorf(`no "From radio" capture device set — pick the rig's USB Audio CODEC in Settings → Audio`)
|
||||||
}
|
}
|
||||||
@@ -10633,6 +10722,7 @@ func (a *App) AudioStartMonitor() error {
|
|||||||
|
|
||||||
// AudioStopMonitor stops the RX monitor passthrough.
|
// AudioStopMonitor stops the RX monitor passthrough.
|
||||||
func (a *App) AudioStopMonitor() {
|
func (a *App) AudioStopMonitor() {
|
||||||
|
a.setSetting(keyAudioMonitorOn, "0")
|
||||||
if a.audioMgr != nil {
|
if a.audioMgr != nil {
|
||||||
a.audioMgr.StopMonitor()
|
a.audioMgr.StopMonitor()
|
||||||
applog.Printf("audio: RX monitor stopped")
|
applog.Printf("audio: RX monitor stopped")
|
||||||
@@ -10655,9 +10745,44 @@ func (a *App) AudioStartTX() error {
|
|||||||
if strings.TrimSpace(cfg.ToRadio) == "" {
|
if strings.TrimSpace(cfg.ToRadio) == "" {
|
||||||
return fmt.Errorf(`no "To radio" device set — pick the rig's USB Audio CODEC output in Settings → Audio`)
|
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
|
if err := a.pttKey(cfg); err != nil { // key first — no point streaming to a rig that isn't transmitting
|
||||||
return err
|
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 {
|
if err := a.audioMgr.StartTXAudio(cfg.RecordingDevice, cfg.ToRadio); err != nil {
|
||||||
a.pttUnkey()
|
a.pttUnkey()
|
||||||
return err
|
return err
|
||||||
@@ -13791,7 +13916,13 @@ func (a *App) consumeUDPEvents() {
|
|||||||
"low_conf": ev.DecodeLowConf,
|
"low_conf": ev.DecodeLowConf,
|
||||||
"mode_raw": ev.DecodeModeRaw,
|
"mode_raw": ev.DecodeModeRaw,
|
||||||
"msg_raw": ev.DecodeMsgRaw,
|
"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
|
// A WSJT-X decode (heard station). Render it on the FlexRadio
|
||||||
// panadapter when the option is on; green + SNR comment, auto-expiring
|
// panadapter when the option is on; green + SNR comment, auto-expiring
|
||||||
// after the configured duration. De-duped per call in the Flex backend.
|
// after the configured duration. De-duped per call in the Flex backend.
|
||||||
@@ -14419,6 +14550,23 @@ func (a *App) IcomSetSplit(on bool) error {
|
|||||||
return a.cat.IcomDo(func(ic cat.IcomController) error { return ic.SetIcomSplit(on) })
|
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 {
|
func (a *App) IcomSetAntenna(n int) error {
|
||||||
if a.cat == nil {
|
if a.cat == nil {
|
||||||
return fmt.Errorf("cat not initialized")
|
return fmt.Errorf("cat not initialized")
|
||||||
@@ -15523,27 +15671,42 @@ func (a *App) reloadCAT() {
|
|||||||
// verification (see icomaudio.go) — hence experimental + opt-in.
|
// verification (see icomaudio.go) — hence experimental + opt-in.
|
||||||
acfg, _ := a.GetAudioSettings()
|
acfg, _ := a.GetAudioSettings()
|
||||||
a.audioMgr.StopMonitor() // clear any prior monitor/sink so a re-save restarts cleanly
|
a.audioMgr.StopMonitor() // clear any prior monitor/sink so a re-save restarts cleanly
|
||||||
if err := a.audioMgr.StartMonitorSink(acfg.ListeningDevice); err != nil {
|
// The SINK — decode + recorder feed — exists whenever the stream is
|
||||||
applog.Printf("icom-net audio: cannot start output sink: %v", err)
|
// on. It used to be built only when the speakers were also wanted,
|
||||||
} else {
|
// so "speakers off" (or a sink that failed to open) silently turned
|
||||||
codec := audio.NewPCM16Codec()
|
// the whole stream off: audio=false on the wire, no recordings, no
|
||||||
audioSink = func(payload []byte) {
|
// voice keyer, and a ticked RX-audio checkbox that did nothing.
|
||||||
pcm, err := codec.Decode(payload)
|
codec := audio.NewPCM16Codec()
|
||||||
if err != nil {
|
audioSink = func(payload []byte) {
|
||||||
return
|
pcm, err := codec.Decode(payload)
|
||||||
}
|
if err != nil {
|
||||||
a.audioMgr.PushMonitorAudio(pcm)
|
return
|
||||||
// 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)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
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)
|
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))
|
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":
|
case "tci":
|
||||||
// Expert Electronics TCI (WebSocket) — SunSDR / ExpertSDR2, or any
|
// Expert Electronics TCI (WebSocket) — SunSDR / ExpertSDR2, or any
|
||||||
// TCI-compatible server. The receive audio rides the same socket, so
|
// TCI-compatible server. The receive audio rides the same socket, so
|
||||||
@@ -19685,10 +19848,11 @@ type SpotStatus struct {
|
|||||||
// that already holds the pointer keeps reading valid (stale-by-one-log) data
|
// that already holds the pointer keeps reading valid (stale-by-one-log) data
|
||||||
// while a newer snapshot is being built. See clusterStatusMaps.
|
// while a newer snapshot is being built. See clusterStatusMaps.
|
||||||
type clusterStatusCache struct {
|
type clusterStatusCache struct {
|
||||||
entities map[int]*qso.EntitySlot
|
entities map[int]*qso.EntitySlot
|
||||||
workedCalls map[string]struct{}
|
workedCalls map[string]struct{}
|
||||||
workedCallSlots map[string]struct{} // nil unless the "same slot" option is on
|
workedCallSlots map[string]struct{}
|
||||||
workedCounties map[string]struct{}
|
workedCallSlotsDig map[string]struct{} // same set, digital modes folded to DIG // nil unless the "same slot" option is on
|
||||||
|
workedCounties map[string]struct{}
|
||||||
// callCounties holds callsign → "STATE,County" for stations already logged
|
// callCounties holds callsign → "STATE,County" for stations already logged
|
||||||
// with a county, so a spot shows the county the entry panel showed rather
|
// with a county, so a spot shows the county the entry panel showed rather
|
||||||
// than the one derived from the licence ZIP. See qso.CallCounties.
|
// than the one derived from the licence ZIP. See qso.CallCounties.
|
||||||
@@ -19771,8 +19935,18 @@ func (a *App) clusterStatusMaps() *clusterStatusCache {
|
|||||||
// "Already worked only on the same slot" option (Settings → DX Cluster): the
|
// "Already worked only on the same slot" option (Settings → DX Cluster): the
|
||||||
// WORKED-call flag then needs the SAME band and mode (digital-grouped through
|
// WORKED-call flag then needs the SAME band and mode (digital-grouped through
|
||||||
// the same normMode when that option is on) rather than the call anywhere.
|
// the same normMode when that option is on) rather than the call anywhere.
|
||||||
if sameSlot || slotHighlight {
|
// Built UNCONDITIONALLY since the watchlist arrived: its per-slot verdict
|
||||||
c.workedCallSlots, _ = a.qso.WorkedCallSlotKeys(a.ctx, c.normMode)
|
// needs this set whatever the cluster's own display options say, and the
|
||||||
|
// scan already runs at cache-rebuild cadence, not per batch.
|
||||||
|
c.workedCallSlots, _ = a.qso.WorkedCallSlotKeys(a.ctx, c.normMode)
|
||||||
|
// And once more at digital-CLASS grain, for the spots whose mode the band
|
||||||
|
// plan can only call "DATA": a generic mode cannot be matched exactly, so it
|
||||||
|
// is judged against "any digital mode of this call on this band". When the
|
||||||
|
// grouping option is on, workedCallSlots is already at that grain.
|
||||||
|
if c.normMode != nil {
|
||||||
|
c.workedCallSlotsDig = c.workedCallSlots
|
||||||
|
} else {
|
||||||
|
c.workedCallSlotsDig, _ = a.qso.WorkedCallSlotKeys(a.ctx, qso.GroupDigitalMode)
|
||||||
}
|
}
|
||||||
// Orthogonal dimensions: worked US counties (for the ULS callsign→county
|
// Orthogonal dimensions: worked US counties (for the ULS callsign→county
|
||||||
// lookup) and worked POTA parks.
|
// lookup) and worked POTA parks.
|
||||||
@@ -21000,3 +21174,30 @@ func (a *App) CheckHamlogKey(key string) (string, error) {
|
|||||||
defer cancel()
|
defer cancel()
|
||||||
return extsvc.CheckHamlogKey(ctx, nil, key)
|
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)
|
||||||
|
}
|
||||||
|
|||||||
@@ -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")
|
||||||
|
}
|
||||||
@@ -24,6 +24,17 @@ func (a *App) GetKenwoodState() cat.KenwoodTXState {
|
|||||||
return st
|
return st
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetKenwoodPanelMode sets the operating mode from the panel's mode row —
|
||||||
|
// CW / USB / LSB / DATA (soundcard, DT0) / RTTY (FSK D, DT2).
|
||||||
|
func (a *App) SetKenwoodPanelMode(mode string) error {
|
||||||
|
return a.kenwoodPanelDo(func(k cat.KenwoodPanelController) error { return k.SetKenwoodPanelMode(mode) })
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetKenwoodRITOffset sets the RIT/XIT offset to an absolute value in Hz.
|
||||||
|
func (a *App) SetKenwoodRITOffset(hz int) error {
|
||||||
|
return a.kenwoodPanelDo(func(k cat.KenwoodPanelController) error { return k.SetKenwoodRITOffset(hz) })
|
||||||
|
}
|
||||||
|
|
||||||
func (a *App) SetKenwoodPower(w int) error {
|
func (a *App) SetKenwoodPower(w int) error {
|
||||||
return a.kenwoodPanelDo(func(k cat.KenwoodPanelController) error { return k.SetKenwoodPower(w) })
|
return a.kenwoodPanelDo(func(k cat.KenwoodPanelController) error { return k.SetKenwoodPower(w) })
|
||||||
}
|
}
|
||||||
|
|||||||
-208
@@ -1,208 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
// Label designer — the Wails boundary for internal/labels.
|
|
||||||
//
|
|
||||||
// The designer edits two things: STOCKS (the physical roll in the printer,
|
|
||||||
// geometry in mm) and TEMPLATES (one design per label kind: the QSO label glued
|
|
||||||
// on a card, the address label for the envelope). Printing — a later module —
|
|
||||||
// will ask for the default template of each kind and hand the rasterised pages
|
|
||||||
// to a PDF; nothing here prints.
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"hamlog/internal/applog"
|
|
||||||
"hamlog/internal/labels"
|
|
||||||
"hamlog/internal/qso"
|
|
||||||
)
|
|
||||||
|
|
||||||
// LabelTemplateInfo is one row of the designer's template list.
|
|
||||||
type LabelTemplateInfo struct {
|
|
||||||
ID int64 `json:"id"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Kind string `json:"kind"`
|
|
||||||
StockID int64 `json:"stock_id"`
|
|
||||||
ProfileID *int64 `json:"profile_id,omitempty"`
|
|
||||||
IsDefault bool `json:"is_default"`
|
|
||||||
UpdatedAt string `json:"updated_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// LabelListStocks returns every label stock, seeding the builtin Brother rolls
|
|
||||||
// on first use.
|
|
||||||
func (a *App) LabelListStocks() ([]labels.Stock, error) {
|
|
||||||
if a.labelRepo == nil {
|
|
||||||
return nil, fmt.Errorf("db not initialized")
|
|
||||||
}
|
|
||||||
if err := a.labelRepo.SeedStocks(a.ctx); err != nil {
|
|
||||||
applog.Printf("labels: seeding stocks failed: %v", err)
|
|
||||||
}
|
|
||||||
return a.labelRepo.Stocks(a.ctx)
|
|
||||||
}
|
|
||||||
|
|
||||||
// LabelSaveStock creates or updates one stock and returns its id.
|
|
||||||
func (a *App) LabelSaveStock(s labels.Stock) (int64, error) {
|
|
||||||
if a.labelRepo == nil {
|
|
||||||
return 0, fmt.Errorf("db not initialized")
|
|
||||||
}
|
|
||||||
if err := a.labelRepo.SaveStock(a.ctx, &s); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
return s.ID, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// LabelDeleteStock removes a stock; designs pointing at it keep their content.
|
|
||||||
func (a *App) LabelDeleteStock(id int64) error {
|
|
||||||
if a.labelRepo == nil {
|
|
||||||
return fmt.Errorf("db not initialized")
|
|
||||||
}
|
|
||||||
return a.labelRepo.DeleteStock(a.ctx, id)
|
|
||||||
}
|
|
||||||
|
|
||||||
// LabelListTemplates lists the designs visible to the active profile.
|
|
||||||
func (a *App) LabelListTemplates() ([]LabelTemplateInfo, error) {
|
|
||||||
if a.labelRepo == nil {
|
|
||||||
return nil, fmt.Errorf("db not initialized")
|
|
||||||
}
|
|
||||||
var recs []labels.Record
|
|
||||||
var err error
|
|
||||||
if p, e := a.profiles.Active(a.ctx); e == nil {
|
|
||||||
recs, err = a.labelRepo.ListFor(a.ctx, p.ID)
|
|
||||||
} else {
|
|
||||||
recs, err = a.labelRepo.List(a.ctx)
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
out := make([]LabelTemplateInfo, 0, len(recs))
|
|
||||||
for _, r := range recs {
|
|
||||||
info := LabelTemplateInfo{
|
|
||||||
ID: r.ID, Name: r.Name, Kind: r.Kind, ProfileID: r.ProfileID,
|
|
||||||
IsDefault: r.IsDefault, UpdatedAt: r.UpdatedAt.Format("2006-01-02 15:04"),
|
|
||||||
}
|
|
||||||
if r.StockID != nil {
|
|
||||||
info.StockID = *r.StockID
|
|
||||||
}
|
|
||||||
out = append(out, info)
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// LabelGetTemplate returns one stored design document (JSON).
|
|
||||||
func (a *App) LabelGetTemplate(id int64) (string, error) {
|
|
||||||
if a.labelRepo == nil {
|
|
||||||
return "", fmt.Errorf("db not initialized")
|
|
||||||
}
|
|
||||||
rec, err := a.labelRepo.Get(a.ctx, id)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return rec.JSON, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// LabelSaveTemplate validates and stores a design; id 0 creates. Returns the id.
|
|
||||||
func (a *App) LabelSaveTemplate(id int64, name string, doc string, forActiveProfile bool) (int64, error) {
|
|
||||||
if a.labelRepo == nil {
|
|
||||||
return 0, fmt.Errorf("db not initialized")
|
|
||||||
}
|
|
||||||
name = strings.TrimSpace(name)
|
|
||||||
if name == "" {
|
|
||||||
return 0, fmt.Errorf("template name required")
|
|
||||||
}
|
|
||||||
t, err := labels.Parse([]byte(doc))
|
|
||||||
if err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
if err := labels.Validate(t); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
rec := labels.Record{ID: id, Name: name, Kind: t.Kind, JSON: doc}
|
|
||||||
if t.StockID != 0 {
|
|
||||||
sid := t.StockID
|
|
||||||
rec.StockID = &sid
|
|
||||||
}
|
|
||||||
if forActiveProfile {
|
|
||||||
if p, err := a.profiles.Active(a.ctx); err == nil {
|
|
||||||
rec.ProfileID = &p.ID
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := a.labelRepo.Save(a.ctx, &rec); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
applog.Printf("labels: template %q (%s) saved (id %d)", name, t.Kind, rec.ID)
|
|
||||||
return rec.ID, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// LabelDeleteTemplate removes a design.
|
|
||||||
func (a *App) LabelDeleteTemplate(id int64) error {
|
|
||||||
if a.labelRepo == nil {
|
|
||||||
return fmt.Errorf("db not initialized")
|
|
||||||
}
|
|
||||||
return a.labelRepo.Delete(a.ctx, id)
|
|
||||||
}
|
|
||||||
|
|
||||||
// LabelSetDefaultTemplate marks a design as the default for its kind.
|
|
||||||
func (a *App) LabelSetDefaultTemplate(id int64) error {
|
|
||||||
if a.labelRepo == nil {
|
|
||||||
return fmt.Errorf("db not initialized")
|
|
||||||
}
|
|
||||||
return a.labelRepo.SetDefault(a.ctx, id)
|
|
||||||
}
|
|
||||||
|
|
||||||
// LabelSampleQSO is one row of preview data for the designer's QSO table.
|
|
||||||
type LabelSampleQSO struct {
|
|
||||||
Callsign string `json:"callsign"`
|
|
||||||
QSODate string `json:"qso_date"` // YYYY-MM-DD
|
|
||||||
TimeOn string `json:"time_on"` // HH:MM
|
|
||||||
Band string `json:"band"`
|
|
||||||
FreqMHz string `json:"freq"`
|
|
||||||
Mode string `json:"mode"`
|
|
||||||
RSTSent string `json:"rst_sent"`
|
|
||||||
RSTRcvd string `json:"rst_rcvd"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
QTH string `json:"qth"`
|
|
||||||
Country string `json:"country"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// LabelSampleQSOs returns the last few real contacts for the designer's live
|
|
||||||
// preview — real data shows a too-narrow column immediately ("14074.0" does not
|
|
||||||
// fit where "7.1" did). Falls back to plausible fakes on an empty log; the
|
|
||||||
// preview must never be blank.
|
|
||||||
func (a *App) LabelSampleQSOs(limit int) []LabelSampleQSO {
|
|
||||||
if limit <= 0 || limit > 20 {
|
|
||||||
limit = 4
|
|
||||||
}
|
|
||||||
fake := []LabelSampleQSO{
|
|
||||||
{Callsign: "DL1ABC", QSODate: "2026-08-01", TimeOn: "14:32", Band: "20m", FreqMHz: "14.074", Mode: "FT8", RSTSent: "-08", RSTRcvd: "-12", Name: "Hans", QTH: "Berlin", Country: "Germany"},
|
|
||||||
{Callsign: "VK3XYZ", QSODate: "2026-08-02", TimeOn: "09:15", Band: "15m", FreqMHz: "21.245", Mode: "SSB", RSTSent: "59", RSTRcvd: "57", Name: "Bruce", QTH: "Melbourne", Country: "Australia"},
|
|
||||||
{Callsign: "JA1TOK", QSODate: "2026-08-03", TimeOn: "21:47", Band: "40m", FreqMHz: "7.012", Mode: "CW", RSTSent: "599", RSTRcvd: "579", Name: "Ken", QTH: "Tokyo", Country: "Japan"},
|
|
||||||
{Callsign: "W1AW", QSODate: "2026-08-04", TimeOn: "18:03", Band: "10m", FreqMHz: "28.480", Mode: "SSB", RSTSent: "59", RSTRcvd: "59", Name: "Hiram", QTH: "Newington", Country: "United States"},
|
|
||||||
}
|
|
||||||
if a.qso == nil {
|
|
||||||
return fake[:min(limit, len(fake))]
|
|
||||||
}
|
|
||||||
rows, err := a.qso.List(a.ctx, qso.ListFilter{Limit: limit})
|
|
||||||
if err != nil || len(rows) == 0 {
|
|
||||||
return fake[:min(limit, len(fake))]
|
|
||||||
}
|
|
||||||
out := make([]LabelSampleQSO, 0, len(rows))
|
|
||||||
for _, q := range rows {
|
|
||||||
s := LabelSampleQSO{
|
|
||||||
Callsign: q.Callsign,
|
|
||||||
QSODate: q.QSODate.UTC().Format("2006-01-02"),
|
|
||||||
TimeOn: q.QSODate.UTC().Format("15:04"),
|
|
||||||
Band: q.Band,
|
|
||||||
Mode: q.Mode,
|
|
||||||
RSTSent: q.RSTSent,
|
|
||||||
RSTRcvd: q.RSTRcvd,
|
|
||||||
Name: q.Name,
|
|
||||||
QTH: q.QTH,
|
|
||||||
Country: q.Country,
|
|
||||||
}
|
|
||||||
if q.FreqHz != nil && *q.FreqHz > 0 {
|
|
||||||
s.FreqMHz = fmt.Sprintf("%.3f", float64(*q.FreqHz)/1e6)
|
|
||||||
}
|
|
||||||
out = append(out, s)
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
// The label PRINT path: pick the paper-QSL queue, review each address, choose
|
|
||||||
// the routing, and export PDFs whose pages are the exact label size — one PDF
|
|
||||||
// per label kind, because a roll printer holds one stock at a time and a file
|
|
||||||
// mixing 29 mm addresses with 62 mm QSO labels could not be printed at all.
|
|
||||||
//
|
|
||||||
// The pages arrive from the frontend already rasterised: the designer's canvas
|
|
||||||
// renderer draws them at the stock's dpi, so what was previewed is — pixel for
|
|
||||||
// pixel — what lands in the PDF. Go only carries them to disk.
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/base64"
|
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"os/exec"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"hamlog/internal/applog"
|
|
||||||
"hamlog/internal/pdf"
|
|
||||||
"hamlog/internal/qso"
|
|
||||||
)
|
|
||||||
|
|
||||||
// LabelPaperQueue returns the contacts whose paper QSL is REQUESTED or QUEUED
|
|
||||||
// (ADIF qsl_sent R/Q) — the natural worklist for a labelling session. The
|
|
||||||
// frontend groups them by callsign.
|
|
||||||
func (a *App) LabelPaperQueue() ([]qso.QSO, error) {
|
|
||||||
if a.qso == nil {
|
|
||||||
return nil, fmt.Errorf("db not initialized")
|
|
||||||
}
|
|
||||||
return a.qso.List(a.ctx, qso.ListFilter{
|
|
||||||
QSLSentIn: []string{"R", "Q"},
|
|
||||||
Limit: 10_000,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// LabelPDFPage is one page of the session's output: a rasterised label and its
|
|
||||||
// physical size. Sizes vary WITHIN one document — the operator asked for a
|
|
||||||
// single PDF holding QSO labels, addresses and return labels together, and PDF
|
|
||||||
// pages each carry their own MediaBox, so a 90×29 page can follow a 100×62 one.
|
|
||||||
type LabelPDFPage struct {
|
|
||||||
PNG string `json:"png"` // base64, data-URL prefix tolerated
|
|
||||||
WMm float64 `json:"w_mm"`
|
|
||||||
HMm float64 `json:"h_mm"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// LabelOpenPDF writes the session's labels to ONE temporary PDF and opens it in
|
|
||||||
// the system viewer, from which the operator prints. No save dialog by choice:
|
|
||||||
// the file is a print run, not a document to keep — anyone who wants to keep it
|
|
||||||
// saves from the viewer.
|
|
||||||
func (a *App) LabelOpenPDF(pages []LabelPDFPage) (string, error) {
|
|
||||||
if len(pages) == 0 {
|
|
||||||
return "", fmt.Errorf("nothing to print")
|
|
||||||
}
|
|
||||||
var doc pdf.Doc
|
|
||||||
for i, pg := range pages {
|
|
||||||
if pg.WMm < 5 || pg.HMm < 5 || pg.WMm > 400 || pg.HMm > 400 {
|
|
||||||
return "", fmt.Errorf("page %d: label size out of range", i+1)
|
|
||||||
}
|
|
||||||
p := pg.PNG
|
|
||||||
if idx := strings.Index(p, ","); idx >= 0 && strings.Contains(p[:idx], "base64") {
|
|
||||||
p = p[idx+1:]
|
|
||||||
}
|
|
||||||
raw, err := base64.StdEncoding.DecodeString(p)
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("page %d: %w", i+1, err)
|
|
||||||
}
|
|
||||||
if err := doc.AddImagePage(raw, pg.WMm, pg.HMm); err != nil {
|
|
||||||
return "", fmt.Errorf("page %d: %w", i+1, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
out, err := doc.Bytes()
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
// A timestamped name in the temp dir: two sessions in one evening must not
|
|
||||||
// fight over the file, least of all while a viewer holds the first one open.
|
|
||||||
path := filepath.Join(os.TempDir(), fmt.Sprintf("opslog-labels-%s.pdf", time.Now().Format("20060102-150405")))
|
|
||||||
if err := os.WriteFile(path, out, 0o644); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
applog.Printf("labels: wrote %d page(s) to %s", len(pages), path)
|
|
||||||
if err := exec.Command("rundll32", "url.dll,FileProtocolHandler", path).Start(); err != nil {
|
|
||||||
applog.Printf("labels: could not open the PDF viewer: %v", err)
|
|
||||||
return "", fmt.Errorf("the PDF was written to %s but no viewer opened: %w", path, err)
|
|
||||||
}
|
|
||||||
return path, nil
|
|
||||||
}
|
|
||||||
@@ -235,3 +235,12 @@ func (a *App) activeRadioMyRig() string {
|
|||||||
}
|
}
|
||||||
return ""
|
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()
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,293 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
// Watchlist bindings — the DXHunter watchlist concept as an OpsLog tab.
|
||||||
|
// The store lives in internal/watchlist (global watchlist.json, DXHunter's own
|
||||||
|
// schema); this file is the Wails boundary plus the two places the list meets
|
||||||
|
// the rest of the app: the spot stream (MarkSeen + alert) and the logbook (the
|
||||||
|
// worked-today answer contest entries are judged by).
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"hamlog/internal/applog"
|
||||||
|
"hamlog/internal/qso"
|
||||||
|
"hamlog/internal/watchlist"
|
||||||
|
|
||||||
|
wruntime "github.com/wailsapp/wails/v2/pkg/runtime"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The auto-contest pattern, DXHunter's contest_prefix: while non-empty, any
|
||||||
|
// spotted callsign CONTAINING it is added to the watchlist as a contest entry
|
||||||
|
// by itself — a special-event fleet (HB9WWA, DL0WWA, F4WWA…) is collected as
|
||||||
|
// it appears instead of typed in one by one. Held in an atomic so the spot
|
||||||
|
// pipeline never touches the settings store per spot.
|
||||||
|
func (a *App) GetWatchlistContestPattern() string {
|
||||||
|
if v := a.watchPattern.Load(); v != nil {
|
||||||
|
return v.(string)
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetWatchlistContestPattern stores the pattern (global, like the list itself).
|
||||||
|
// Emptying it stops the auto-add; entries already collected stay — deleting an
|
||||||
|
// operator's list because a setting changed is DXHunter behaviour this port
|
||||||
|
// deliberately drops.
|
||||||
|
func (a *App) SetWatchlistContestPattern(p string) {
|
||||||
|
p = strings.ToUpper(strings.TrimSpace(p))
|
||||||
|
a.watchPattern.Store(p)
|
||||||
|
a.setSettingGlobal(keyWatchlistContestPattern, p)
|
||||||
|
}
|
||||||
|
|
||||||
|
// WatchlistEntries returns the list for the tab.
|
||||||
|
func (a *App) WatchlistEntries() []watchlist.Entry {
|
||||||
|
if a.watchlist == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return a.watchlist.Entries()
|
||||||
|
}
|
||||||
|
|
||||||
|
// WatchlistAdd adds a callsign or prefix; contest entries are judged per UTC day.
|
||||||
|
func (a *App) WatchlistAdd(callsign string, contest bool) error {
|
||||||
|
if a.watchlist == nil {
|
||||||
|
return fmt.Errorf("watchlist not initialized")
|
||||||
|
}
|
||||||
|
return a.watchlist.Add(callsign, contest)
|
||||||
|
}
|
||||||
|
|
||||||
|
// WatchlistRemove deletes an entry.
|
||||||
|
func (a *App) WatchlistRemove(callsign string) error {
|
||||||
|
if a.watchlist == nil {
|
||||||
|
return fmt.Errorf("watchlist not initialized")
|
||||||
|
}
|
||||||
|
return a.watchlist.Remove(callsign)
|
||||||
|
}
|
||||||
|
|
||||||
|
// WatchlistSetNotify arms the existing alert path (sound + toast) for an entry.
|
||||||
|
func (a *App) WatchlistSetNotify(callsign string, on bool) error {
|
||||||
|
if a.watchlist == nil {
|
||||||
|
return fmt.Errorf("watchlist not initialized")
|
||||||
|
}
|
||||||
|
return a.watchlist.SetNotify(callsign, on)
|
||||||
|
}
|
||||||
|
|
||||||
|
// WatchlistSetContest flips the per-entry contest rule.
|
||||||
|
func (a *App) WatchlistSetContest(callsign string, on bool) error {
|
||||||
|
if a.watchlist == nil {
|
||||||
|
return fmt.Errorf("watchlist not initialized")
|
||||||
|
}
|
||||||
|
return a.watchlist.SetContest(callsign, on)
|
||||||
|
}
|
||||||
|
|
||||||
|
// WatchlistSlotQuery asks whether one spot's slot is worked — against the whole
|
||||||
|
// log for a normal entry, against TODAY (UTC) for a contest one.
|
||||||
|
type WatchlistSlotQuery struct {
|
||||||
|
Call string `json:"call"`
|
||||||
|
Band string `json:"band"`
|
||||||
|
Mode string `json:"mode"`
|
||||||
|
Contest bool `json:"contest"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// WatchlistWorkedSlots answers a batch of slot questions for the tab.
|
||||||
|
//
|
||||||
|
// Normal entries read the CLUSTER's own slot set — the same cached
|
||||||
|
// WorkedCallSlotKeys index that colours the grid — so the watchlist can never
|
||||||
|
// contradict the cluster about the same spot. That index normalises the mode
|
||||||
|
// exactly as the operator configured (digital grouping on → FT4 counts as FT8's
|
||||||
|
// class; off → exact mode), and the first version of this ignored that: it
|
||||||
|
// asked the alerts' raw-mode index with a CLASS name, matched nothing, and
|
||||||
|
// showed a fully-worked DXpedition as all Needed.
|
||||||
|
//
|
||||||
|
// Contest entries read TODAY's contacts instead — the midnight-UTC reset is
|
||||||
|
// the query's date bound, nothing stored, nothing to reset — normalised through
|
||||||
|
// the same function so the two answers use one grammar.
|
||||||
|
func (a *App) WatchlistWorkedSlots(queries []WatchlistSlotQuery) []bool {
|
||||||
|
out := make([]bool, len(queries))
|
||||||
|
if a.qso == nil || len(queries) == 0 {
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
idx := a.clusterStatusMaps()
|
||||||
|
norm := func(m string) string {
|
||||||
|
m = strings.ToUpper(strings.TrimSpace(m))
|
||||||
|
if idx.normMode != nil {
|
||||||
|
m = idx.normMode(m)
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
slotKey := func(call, band, mode string) string {
|
||||||
|
up := strings.ToUpper(strings.TrimSpace(call))
|
||||||
|
b := strings.ToLower(strings.TrimSpace(band))
|
||||||
|
if m := norm(mode); m != "" {
|
||||||
|
return up + "|" + b + "|" + m
|
||||||
|
}
|
||||||
|
return up + "|" + b
|
||||||
|
}
|
||||||
|
// A spot whose mode the band plan could only call "DATA" (an F/H DXpedition
|
||||||
|
// off the standard dials, a comment with no mode) cannot be matched exactly:
|
||||||
|
// "DATA" is in nobody's log. Such a spot is judged at digital-CLASS grain —
|
||||||
|
// worked if ANY digital mode of that call is logged on that band. Claiming
|
||||||
|
// NEW MODE because the label differs from FT8 was the reported bug.
|
||||||
|
generic := func(m string) bool {
|
||||||
|
switch strings.ToUpper(strings.TrimSpace(m)) {
|
||||||
|
case "", "DATA", "DIG", "DIGI", "DIGITAL":
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
digKey := func(call, band string) string {
|
||||||
|
return strings.ToUpper(strings.TrimSpace(call)) + "|" + strings.ToLower(strings.TrimSpace(band)) + "|DIG"
|
||||||
|
}
|
||||||
|
needToday := false
|
||||||
|
for _, q := range queries {
|
||||||
|
if q.Contest {
|
||||||
|
needToday = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
today := map[string]bool{}
|
||||||
|
if needToday {
|
||||||
|
midnight := time.Now().UTC().Truncate(24 * time.Hour)
|
||||||
|
rows, err := a.qso.SlotsSince(a.ctx, midnight)
|
||||||
|
if err == nil {
|
||||||
|
for _, r := range rows {
|
||||||
|
today[slotKey(r.Callsign, r.Band, r.Mode)] = true
|
||||||
|
today[digKey(r.Callsign, r.Band)] = qso.ModeClass(r.Mode) == "DIG" || today[digKey(r.Callsign, r.Band)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i, q := range queries {
|
||||||
|
if q.Contest {
|
||||||
|
if generic(q.Mode) {
|
||||||
|
out[i] = today[digKey(q.Call, q.Band)]
|
||||||
|
} else {
|
||||||
|
out[i] = today[slotKey(q.Call, q.Band, q.Mode)]
|
||||||
|
}
|
||||||
|
} else if generic(q.Mode) {
|
||||||
|
if idx.workedCallSlotsDig != nil {
|
||||||
|
_, out[i] = idx.workedCallSlotsDig[digKey(q.Call, q.Band)]
|
||||||
|
}
|
||||||
|
} else if idx.workedCallSlots != nil {
|
||||||
|
_, out[i] = idx.workedCallSlots[slotKey(q.Call, q.Band, q.Mode)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// watchSpot runs one live spot through the watchlist: last-seen bookkeeping and
|
||||||
|
// the alert, through the SAME event the alert rules fire — the frontend already
|
||||||
|
// knows how to toast and sound it, and a second notification path would be a
|
||||||
|
// second thing to misconfigure.
|
||||||
|
func (a *App) watchSpot(dxCall, band, mode, country, comment string, freqHz int64) {
|
||||||
|
if a.watchlist == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
entry, notify, ok := a.watchlist.MarkSeen(dxCall)
|
||||||
|
if !ok {
|
||||||
|
// Not watched yet — the auto-contest pattern may claim it. Contains, not
|
||||||
|
// prefix: the event string sits anywhere in these calls (HB9WWA, F4WWA/P).
|
||||||
|
if p := a.GetWatchlistContestPattern(); p != "" &&
|
||||||
|
strings.Contains(strings.ToUpper(dxCall), p) {
|
||||||
|
if err := a.watchlist.Add(dxCall, true); err == nil {
|
||||||
|
applog.Printf("watchlist: auto-added %s (contest pattern %q)", dxCall, p)
|
||||||
|
entry, notify, ok = a.watchlist.MarkSeen(dxCall)
|
||||||
|
if a.ctx != nil {
|
||||||
|
wruntime.EventsEmit(a.ctx, "watchlist:changed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !ok || !notify || a.ctx == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Already worked? Then nothing to announce. Judged HERE, before the sound —
|
||||||
|
// the report was an alert ringing for a slot the tab showed as Worked a
|
||||||
|
// moment later, because the frontend's verdict arrives on a debounce while
|
||||||
|
// the alert used to fire on the raw spot. Same verdict as the tab: exact
|
||||||
|
// slot for named modes, digital class for a generic DATA spot, today-only
|
||||||
|
// for a contest entry.
|
||||||
|
if e, found := a.watchlist.Get(entry); found {
|
||||||
|
if a.WatchlistWorkedSlots([]WatchlistSlotQuery{{Call: dxCall, Band: band, Mode: mode, Contest: e.IsContest}})[0] {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Throttled per entry: a DXpedition lights up every skimmer on the planet,
|
||||||
|
// and forty alerts a minute for one station is a alarm nobody keeps on.
|
||||||
|
a.watchAlertMu.Lock()
|
||||||
|
last := a.watchAlertAt[entry]
|
||||||
|
now := time.Now()
|
||||||
|
if now.Sub(last) < 2*time.Minute {
|
||||||
|
a.watchAlertMu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
a.watchAlertAt[entry] = now
|
||||||
|
a.watchAlertMu.Unlock()
|
||||||
|
wruntime.EventsEmit(a.ctx, "alert:fired", map[string]any{
|
||||||
|
"rule": "Watchlist " + entry,
|
||||||
|
"call": strings.ToUpper(strings.TrimSpace(dxCall)),
|
||||||
|
"band": band,
|
||||||
|
"mode": mode,
|
||||||
|
"freq_hz": freqHz,
|
||||||
|
"country": country,
|
||||||
|
"comment": comment,
|
||||||
|
"sound": true,
|
||||||
|
"visual": true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// startWatchlistClubLog begins the expedition enrichment: every entry's
|
||||||
|
// ClubLog block (expedition flag, OQRS, LiveStream, QSO totals and 24 h rate)
|
||||||
|
// is refreshed on a rolling schedule — hourly for expeditions, six-hourly for
|
||||||
|
// the rest, DXHunter's own cadence. OpsLog's application API key is used, so
|
||||||
|
// there is nothing to configure.
|
||||||
|
//
|
||||||
|
// Two at a time with a breath between requests: the key is shared by every
|
||||||
|
// OpsLog install, and a hundred-entry watchlist must read as a trickle at
|
||||||
|
// ClubLog's end, not a burst.
|
||||||
|
func (a *App) startWatchlistClubLog() {
|
||||||
|
if a.watchlist == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
client := &http.Client{Timeout: 30 * time.Second}
|
||||||
|
// Let the app finish starting before the first network pass.
|
||||||
|
time.Sleep(15 * time.Second)
|
||||||
|
for {
|
||||||
|
stale := a.watchlist.StaleEntries(1*time.Hour, 6*time.Hour)
|
||||||
|
changed := false
|
||||||
|
for _, call := range stale {
|
||||||
|
// The pattern's BASE is what ClubLog knows: VK9* has no log.
|
||||||
|
base := strings.TrimSuffix(call, "*")
|
||||||
|
if base == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
d, err := watchlist.FetchWatch(ctx, client, clublogAppAPIKey, base)
|
||||||
|
cancel()
|
||||||
|
if err != nil {
|
||||||
|
applog.Printf("watchlist clublog: %s: %v", base, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if a.watchlist.ApplyClubLog(call, d) {
|
||||||
|
changed = true
|
||||||
|
if d.IsExpedition {
|
||||||
|
applog.Printf("watchlist clublog: %s is a DXpedition (%d QSOs, %d/24h, OQRS=%v)",
|
||||||
|
base, func() int {
|
||||||
|
if d.ClubLogInfo != nil {
|
||||||
|
return d.ClubLogInfo.TotalQSOs
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}(), d.QSOs24h(), d.HasOQRS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
time.Sleep(400 * time.Millisecond)
|
||||||
|
}
|
||||||
|
if changed && a.ctx != nil {
|
||||||
|
wruntime.EventsEmit(a.ctx, "watchlist:changed")
|
||||||
|
}
|
||||||
|
time.Sleep(10 * time.Minute)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
@@ -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, ""
|
||||||
|
}
|
||||||
+133
-5
@@ -1,16 +1,144 @@
|
|||||||
[
|
[
|
||||||
|
{
|
||||||
|
"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 K3’s bargraph is relative to a range that flips at 12 W — calibrated against a real radio’s full table, the PC setting picks the range and the bar converts to watts.",
|
||||||
|
"Watchlist: a visual pass toward DXHunter’s 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 decoder’s 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 map’s ±85°, the path still draws.",
|
||||||
|
"WSJT-X / JTDX / MSHV: clicking a spot in a digital mode the decoder speaks (FT8, FT4, JT65…) switches the decoder’s 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 d’une 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 radio’s own display (they read about two S-units low).",
|
||||||
|
"Elecraft console: an SWR spike (the K3’s 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-7760’s 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 take’s 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 radio’s 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 one’s 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 console’s 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 receiver’s 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 console’s 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 VFO’s 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 radio’s 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-7760’s 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 call’s QSOs displayed under the new call’s 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 à l’affichage 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 s’estompe plus pendant douze secondes — le pic s’affiche brièvement, puis le ros-mètre revient directement à la valeur réelle.",
|
||||||
|
"Icom : l’IC-7760 rejoint la liste des modèles (adresse CI-V B2h).",
|
||||||
|
"Console Icom : l’IC-7760 reçoit ses vrais crans d’atténuateur — 6/12/18 dB.",
|
||||||
|
"Audio réseau Icom : le flux RX est décodé correctement — le mono est demandé et l’offset du payload a été confirmé sur un vrai IC-7760, ce qui guérit le son inaudible et les clics.",
|
||||||
|
"Icom : revenir d’un 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 l’IC-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 l’IC-7760.",
|
||||||
|
"Audio réseau Icom : le bon codec est demandé (LPCM mono 16 bits), déterminé par l’expé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 d’ouvrir 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 d’abord la radio active, avant le défaut par bande — un IC-7760 à l’antenne 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 d’une autre radio sur une station mixte).",
|
||||||
|
"Audio réseau Icom : les paquets dupliqués ou retransmis en retard n’atteignent plus l’enregistreur — 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 l’application — au lancement, la connexion se faisait audio coupé, et il fallait décocher/recocher l’option pour entendre quelque chose.",
|
||||||
|
"Réseau Icom : quand la radio se tait sur le CI-V alors que la session tient (constaté sur l’IC-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 d’abord l’ancienne session — stoppe la spirale reconnexion-mort-reconnexion vue sur l’IC-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 l’audio — 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 l’IC-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 l’enregistreur 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 l’aller-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 l’option 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 : l’affichage 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 qu’il suive le main.",
|
||||||
|
"Audio réseau Icom : le flux s’ouvre 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 d’OpsLog 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 d’onde différemment — et sur l’IC-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 l’IC-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 d’aiguille — 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 l’affichage 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 d’un 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 n’atteignait 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 d’une minute : les coupures récurrentes de son/CAT."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "0.27.0",
|
||||||
|
"date": "",
|
||||||
|
"en": [
|
||||||
|
"⭐ NEW — Watchlist (Tools): the DXHunter watchlist as an OpsLog tab — callsigns you are hunting (exact, or a family with a trailing * — VK9* catches every VK9), the live cluster spots under each with the NEW badges and a Needed/Worked verdict per slot, an ON AIR badge, per-entry alerts through the normal alert path, and CONTEST entries judged per UTC day (at midnight everything is workable again).Each entry is enriched from ClubLog automatically: DXpedition badge, OQRS, LiveStream link, QSO total and 24-hour rate — nothing to configure. Reads and writes DXHunter’s own watchlist.json format — drop your existing file into the data folder to carry it over.",
|
||||||
|
"TCI (SunSDR): the meter subscription is renewed when the radio announces it is ready — sent only at connect, it could fall inside the initial state dump and be ignored, which left the transmit power and SWR empty. The log now also records the subscription and the first sensor frames, so a report can tell “the radio never sends them” from “they arrived and were dropped”.",
|
||||||
|
"Sending a spot while in split now pre-fills the RX frequency — where the station actually is — instead of the TX frequency, which spotted the pile-up five up from the DX.",
|
||||||
|
"Cluster: NEW SLOT gets its own colour — the sky cyan the panadapter palette already uses for it, clearly apart from POTA green and the yellows. The NEW SLOT and NEW COUNTY filter chips now wear the same colours as the badges they select, and the NEW CALL filter works even when the slot-highlight display option is off.",
|
||||||
|
"Elecraft console: a mode row — CW, USB, LSB, DATA and DATA RTTY. The two DATA buttons set the K3’s submode as well (DATA A for FT8/FT4, FSK D for RTTY): switching to DATA by mode alone kept whatever submode the last session left, which is how a K3 “in DATA” keys FT8 with no audio.",
|
||||||
|
"DX Cluster settings: “I chase POTA” and “I chase SOTA”, on by default. Unticked, the NEW POTA badge, colour and filter disappear — a new-band + new-POTA spot reads NEW BAND alone — and the reference columns stay empty.",
|
||||||
|
"Elecraft console: RIT and XIT use the same control as the Icom and TCI consoles — ± buttons, mouse wheel, typed value, Ctrl+←/→ — and the power slider moves in 1 W steps instead of 5.",
|
||||||
|
"Bulk edit: My DXCC, My CQ zone and My ITU zone join the My-station fields — numbers checked against their real ranges, empty clears.",
|
||||||
|
"Clicking a spot in the Chase new panel now applies the FlexRadio panadapter width/zoom, like every other spot click.",
|
||||||
|
"FlexRadio: the panadapter width/zoom now applies reliably when double-clicking a cluster spot — the zoom is sent after the tune settles, so SmartSDR’s own pan-follow on a band change no longer overrides it."
|
||||||
|
],
|
||||||
|
"fr": [
|
||||||
|
"⭐ NOUVEAU — Watchlist (Outils) : la watchlist de DXHunter en onglet OpsLog — indicatifs chassés (exacts, ou une famille avec une * finale — VK9* attrape tous les VK9), les spots cluster en direct sous chaque entrée avec les badges NOUVEAU et un verdict Manquant/Contacté par créneau, un badge ON AIR, des alertes par entrée via le circuit d'alerte normal, et des entrées CONTEST jugées par jour UTC (à minuit tout redevient à faire).Chaque entrée est enrichie automatiquement depuis ClubLog : badge DXpedition, OQRS, lien LiveStream, total de QSO et rythme sur 24 h — rien à configurer. Lit et écrit le format watchlist.json de DXHunter — déposez votre fichier existant dans le dossier data pour le récupérer.",
|
||||||
|
"TCI (SunSDR) : l'abonnement aux mesures est renouvelé quand la radio annonce qu'elle est prête — envoyé seulement à la connexion, il pouvait tomber pendant l'envoi initial de l'état et être ignoré, laissant la puissance et le ROS vides en émission. Le journal enregistre aussi l'abonnement et les premières trames de mesure, pour distinguer « la radio ne les envoie jamais » de « elles arrivaient et étaient perdues ».",
|
||||||
|
"Envoyer un spot en split préremplit désormais la fréquence RX — là où la station se trouve réellement — au lieu de la fréquence TX, qui spottait le pile-up cinq au-dessus du DX.",
|
||||||
|
"Cluster : NOUVEAU SLOT reçoit sa propre couleur — le cyan ciel que la palette du panadapter lui donne déjà, bien distinct du vert POTA et des jaunes. Les puces de filtre NOUVEAU SLOT et NOUVEAU COMTÉ portent désormais les couleurs des badges qu'elles sélectionnent, et le filtre NOUVEAU CALL fonctionne même quand l'option de surlignage par slot est désactivée.",
|
||||||
|
"Console Elecraft : une rangée de modes — CW, USB, LSB, DATA et DATA RTTY. Les deux boutons DATA règlent aussi le sous-mode du K3 (DATA A pour FT8/FT4, FSK D pour le RTTY) : passer en DATA par le seul mode gardait le sous-mode de la session précédente, et un K3 « en DATA » manipulait le FT8 sans audio.",
|
||||||
|
"Réglages DX Cluster : « Je chasse le POTA » et « Je chasse le SOTA », cochés par défaut. Décochés, le badge, la couleur et le filtre NOUVEAU POTA disparaissent — un spot nouvelle bande + nouveau POTA affiche seulement NOUVELLE BANDE — et les colonnes de références restent vides.",
|
||||||
|
"Console Elecraft : le RIT et le XIT utilisent la même commande que les consoles Icom et TCI — boutons ±, molette, valeur tapée, Ctrl+←/→ — et le curseur de puissance avance par pas de 1 W au lieu de 5.",
|
||||||
|
"Édition groupée : My DXCC, My CQ zone et My ITU zone rejoignent les champs Ma station — valeurs vérifiées contre leurs bornes réelles, vide efface.",
|
||||||
|
"Cliquer un spot dans le panneau Chase new applique désormais la largeur/zoom du panadapter FlexRadio, comme tout autre clic de spot.",
|
||||||
|
"FlexRadio : la largeur/zoom du panadapter s’applique désormais de façon fiable au double-clic sur un spot du cluster — le zoom est envoyé après le tune, pour que le suivi du panadapter de SmartSDR lors d’un changement de bande ne l’écrase plus."
|
||||||
|
]
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"version": "0.26.23",
|
"version": "0.26.23",
|
||||||
"date": "",
|
"date": "",
|
||||||
"en": [
|
"en": [
|
||||||
"LoTW: the downloaded confirmations list gains a Station column, so a list spanning several callsigns says which one each confirmation belongs to. Shown only when the report actually carries more than the one station.",
|
"LoTW: the downloaded confirmations list gains a Station column, so a list spanning several callsigns says which one each confirmation belongs to. Shown only when the report actually carries more than the one station.",
|
||||||
"Label Designer (Tools): design the labels for paper QSL work — a QSO label for the card (repeating QSO table, several contacts of the same station per label) and address labels for the envelope. Label sizes are profiles in millimetres with margins, seeded with the common Brother DK rolls; elements are dragged in place on a millimetre-true preview fed with your latest contacts. Printing to PDF comes next.",
|
"The band maps follow your IARU region (Settings → General): Region 2’s 40 m runs to 7300 kHz with phone from 7125 and its 80 m to 4000, Region 3’s 80 m to 3900 — the band edges and the CW/digital/phone shading all adjust."
|
||||||
"Label printing (Tools → Print QSL labels): a three-step session — pick from the paper-QSL queue (sent status R/Q), check each address with a routing choice (direct / bureau / via manager) and a QRZ fetch (the MANAGER’s address when routing says via), then ONE PDF holding every label at its exact size, opened straight in the viewer to print from. Finishing marks the contacts sent with the date and the via."
|
|
||||||
],
|
],
|
||||||
"fr": [
|
"fr": [
|
||||||
"LoTW : la liste des confirmations téléchargées gagne une colonne Station, pour savoir à quel indicatif appartient chaque confirmation quand le téléchargement en couvre plusieurs. Affichée seulement si le rapport en contient effectivement.",
|
"LoTW : la liste des confirmations téléchargées gagne une colonne Station, pour savoir à quel indicatif appartient chaque confirmation quand le téléchargement en couvre plusieurs. Affichée seulement si le rapport en contient effectivement.",
|
||||||
"Créateur d'étiquettes (Outils) : dessinez les étiquettes de vos QSL papier — étiquette QSO pour la carte (tableau de QSO répétable, plusieurs contacts de la même station par étiquette) et étiquettes adresse pour l'enveloppe. Les formats sont des profils en millimètres avec marges, préremplis avec les rouleaux Brother DK courants ; les éléments se placent à la souris sur un aperçu fidèle au millimètre nourri de vos derniers contacts. L'impression en PDF viendra ensuite.",
|
"Les cartes de bande suivent votre région IARU (Réglages → Général) : le 40 m de la Région 2 va jusqu'à 7300 kHz avec la phonie dès 7125 et son 80 m jusqu'à 4000, le 80 m de la Région 3 jusqu'à 3900 — les limites de bande et les zones CW/numérique/phonie s'ajustent."
|
||||||
"Impression des étiquettes (Outils → Imprimer les étiquettes QSL) : une session en trois étapes — choisir dans la file QSL papier (statut envoyé R/Q), vérifier chaque adresse avec le routage (direct / bureau / via manager) et une récupération QRZ (l'adresse du MANAGER quand le routage le dit), puis UN PDF contenant toutes les étiquettes à leur taille exacte, ouvert directement dans le lecteur pour impression. La fin de session marque les contacts envoyés avec la date et le moyen."
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -2005,4 +2133,4 @@
|
|||||||
"Ce résumé « Nouveautés » s'affiche désormais au premier lancement après chaque mise à jour."
|
"Ce résumé « Nouveautés » s'affiche désormais au premier lancement après chaque mise à jour."
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
+148
-41
@@ -33,7 +33,7 @@ import {
|
|||||||
GetSolarData,
|
GetSolarData,
|
||||||
GetQSORate,
|
GetQSORate,
|
||||||
LoTWUserInfo,
|
LoTWUserInfo,
|
||||||
OperatingDefaultForBand,
|
OperatingDefaultForBand, ActiveRadioMyRig, ConfigureDecoderMode,
|
||||||
LogUDPLoggedADIF,
|
LogUDPLoggedADIF,
|
||||||
ListCountries,
|
ListCountries,
|
||||||
GetWinkeyerSettings, SaveWinkeyerSettings, ListSerialPorts, GetWinkeyerStatus,
|
GetWinkeyerSettings, SaveWinkeyerSettings, ListSerialPorts, GetWinkeyerStatus,
|
||||||
@@ -69,9 +69,8 @@ import {
|
|||||||
} from '@/components/ui/dropdown-menu';
|
} from '@/components/ui/dropdown-menu';
|
||||||
import { APP_VERSION, APP_AUTHOR } from '@/version';
|
import { APP_VERSION, APP_AUTHOR } from '@/version';
|
||||||
import { QSLManagerPanel } from '@/components/QSLManagerModal';
|
import { QSLManagerPanel } from '@/components/QSLManagerModal';
|
||||||
|
import { WatchlistTab } from '@/components/WatchlistTab';
|
||||||
import { QslDesignerModal } from '@/components/qsl/QslDesignerModal';
|
import { QslDesignerModal } from '@/components/qsl/QslDesignerModal';
|
||||||
import { LabelDesignerModal } from '@/components/labels/LabelDesignerModal';
|
|
||||||
import { LabelPrintModal } from '@/components/labels/LabelPrintModal';
|
|
||||||
import { SendEQSLModal } from '@/components/qsl/SendEQSLModal';
|
import { SendEQSLModal } from '@/components/qsl/SendEQSLModal';
|
||||||
import { AutoEQSL } from '@/components/qsl/AutoEQSL';
|
import { AutoEQSL } from '@/components/qsl/AutoEQSL';
|
||||||
import { ConfirmDialog } from '@/components/ConfirmDialog';
|
import { ConfirmDialog } from '@/components/ConfirmDialog';
|
||||||
@@ -100,7 +99,7 @@ import { ExportFieldsDialog } from '@/components/ExportFieldsDialog';
|
|||||||
import { ShutdownProgress } from '@/components/ShutdownProgress';
|
import { ShutdownProgress } from '@/components/ShutdownProgress';
|
||||||
import { ClusterGrid } from '@/components/ClusterGrid';
|
import { ClusterGrid } from '@/components/ClusterGrid';
|
||||||
import { cleanSpotter, inferSpotMode, spotModeCategory, spotStatusKey } from '@/lib/spot';
|
import { cleanSpotter, inferSpotMode, spotModeCategory, spotStatusKey } from '@/lib/spot';
|
||||||
import { applySpotDisplay, readSpotDisplayOptions, spotIsWorked, SPOT_DISPLAY_OPTIONS_EXPOSED } from '@/lib/spotDisplay';
|
import { applySpotDisplay, chasePota, readSpotDisplayOptions, spotIsWorked, SPOT_DISPLAY_OPTIONS_EXPOSED } from '@/lib/spotDisplay';
|
||||||
import { AnswerDecode, HaltDecodeTx, LogUIError, FlexTXOnBand, GetMatrixColors, GetRotorPresets, GetRowColors, GetSpotTTLMinutes, GetSpotMax, IsNewUSCounty } from '../wailsjs/go/main/App';
|
import { AnswerDecode, HaltDecodeTx, LogUIError, FlexTXOnBand, GetMatrixColors, GetRotorPresets, GetRowColors, GetSpotTTLMinutes, GetSpotMax, IsNewUSCounty } from '../wailsjs/go/main/App';
|
||||||
import { applyMatrixColors } from '@/lib/matrixColors';
|
import { applyMatrixColors } from '@/lib/matrixColors';
|
||||||
import { WorkedBeforeGrid } from '@/components/WorkedBeforeGrid';
|
import { WorkedBeforeGrid } from '@/components/WorkedBeforeGrid';
|
||||||
@@ -935,11 +934,16 @@ export default function App() {
|
|||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!band) return;
|
if (!band) return;
|
||||||
let cancelled = false;
|
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;
|
if (cancelled) return;
|
||||||
setDetails((cur) => ({
|
setDetails((cur) => ({
|
||||||
...cur,
|
...cur,
|
||||||
my_rig: d?.station_name || '',
|
my_rig: liveRig || d?.station_name || '',
|
||||||
my_antenna: d?.antenna_name || '',
|
my_antenna: d?.antenna_name || '',
|
||||||
tx_pwr: d?.tx_pwr ?? cur.tx_pwr,
|
tx_pwr: d?.tx_pwr ?? cur.tx_pwr,
|
||||||
}));
|
}));
|
||||||
@@ -1052,6 +1056,13 @@ export default function App() {
|
|||||||
if (!active) setError(t('rec.manualFailed'));
|
if (!active) setError(t('rec.manualFailed'));
|
||||||
}).catch((e: any) => setError(String(e?.message ?? e)));
|
}).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(() => {
|
useEffect(() => {
|
||||||
if (!recording) { setRecSeconds(0); return; }
|
if (!recording) { setRecSeconds(0); return; }
|
||||||
// A stopped take freezes the clock where it is: it must show the length of
|
// A stopped take freezes the clock where it is: it must show the length of
|
||||||
@@ -1062,9 +1073,6 @@ export default function App() {
|
|||||||
const id = window.setInterval(() => setRecSeconds(from + Math.floor((Date.now() - start) / 1000)), 1000);
|
const id = window.setInterval(() => setRecSeconds(from + Math.floor((Date.now() - start) / 1000)), 1000);
|
||||||
return () => window.clearInterval(id);
|
return () => window.clearInterval(id);
|
||||||
}, [recording, recTick, recStopped]);
|
}, [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).
|
// The callsign the in-progress recording belongs to (uppercased; '' = none).
|
||||||
// Lets us restart from zero when the operator edits the call to a different
|
// Lets us restart from zero when the operator edits the call to a different
|
||||||
// station mid-recording, instead of continuing the old take.
|
// station mid-recording, instead of continuing the old take.
|
||||||
@@ -1269,8 +1277,6 @@ export default function App() {
|
|||||||
setQslPaperReq((r) => ({ call: c, n: (r?.n ?? 0) + 1 }));
|
setQslPaperReq((r) => ({ call: c, n: (r?.n ?? 0) + 1 }));
|
||||||
}
|
}
|
||||||
const [qslDesignerOpen, setQslDesignerOpen] = useState(false);
|
const [qslDesignerOpen, setQslDesignerOpen] = useState(false);
|
||||||
const [labelDesignerOpen, setLabelDesignerOpen] = useState(false);
|
|
||||||
const [labelPrintOpen, setLabelPrintOpen] = useState(false);
|
|
||||||
const [eqslQsoId, setEqslQsoId] = useState<number | null>(null); // QSO being sent as eQSL
|
const [eqslQsoId, setEqslQsoId] = useState<number | null>(null); // QSO being sent as eQSL
|
||||||
function closeQslTab() {
|
function closeQslTab() {
|
||||||
setQslTabOpen(false);
|
setQslTabOpen(false);
|
||||||
@@ -1526,7 +1532,7 @@ export default function App() {
|
|||||||
// Seed the current break-in from the rig when the CW panel becomes active in
|
// 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).
|
// Icom mode (so the control reflects the radio's real state).
|
||||||
useEffect(() => {
|
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(() => {});
|
GetIcomState().then((s: any) => { if (s && typeof s.break_in === 'number') setIcomBreakIn(s.break_in); }).catch(() => {});
|
||||||
}, [cwSource, wkEnabled, catState.backend, catState.connected]);
|
}, [cwSource, wkEnabled, catState.backend, catState.connected]);
|
||||||
// Auto-call: repeat the clicked macro (e.g. F1 CQ) every (message + N seconds)
|
// Auto-call: repeat the clicked macro (e.g. F1 CQ) every (message + N seconds)
|
||||||
@@ -1550,7 +1556,7 @@ export default function App() {
|
|||||||
// skips the log that hasn't happened yet.
|
// skips the log that hasn't happened yet.
|
||||||
const wkSendGenRef = useRef(0);
|
const wkSendGenRef = useRef(0);
|
||||||
useEffect(() => {
|
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 === 'flex' ? (catState.backend === 'flex' && catState.connected)
|
||||||
: cwSource === 'yaesu' ? (catState.backend === 'yaesu' && catState.connected)
|
: cwSource === 'yaesu' ? (catState.backend === 'yaesu' && catState.connected)
|
||||||
: cwSource === 'kenwood' ? (catState.backend === 'kenwood' && catState.connected)
|
: cwSource === 'kenwood' ? (catState.backend === 'kenwood' && catState.connected)
|
||||||
@@ -1688,6 +1694,9 @@ export default function App() {
|
|||||||
// NET Control tab — enabled from Tools (persisted; once on it's a tab like Cluster).
|
// NET Control tab — enabled from Tools (persisted; once on it's a tab like Cluster).
|
||||||
const [netEnabled, setNetEnabled] = useState(() => localStorage.getItem('opslog.netEnabled') === '1');
|
const [netEnabled, setNetEnabled] = useState(() => localStorage.getItem('opslog.netEnabled') === '1');
|
||||||
useEffect(() => { localStorage.setItem('opslog.netEnabled', netEnabled ? '1' : '0'); }, [netEnabled]);
|
useEffect(() => { localStorage.setItem('opslog.netEnabled', netEnabled ? '1' : '0'); }, [netEnabled]);
|
||||||
|
// Watchlist tab — opt-in from Tools, persisted, closable like NET Control.
|
||||||
|
const [watchlistEnabled, setWatchlistEnabled] = useState(() => localStorage.getItem('opslog.watchlistEnabled') === '1');
|
||||||
|
useEffect(() => { localStorage.setItem('opslog.watchlistEnabled', watchlistEnabled ? '1' : '0'); }, [watchlistEnabled]);
|
||||||
// Contest tab is hidden until enabled from Tools → Contest mode.
|
// Contest tab is hidden until enabled from Tools → Contest mode.
|
||||||
const [contestTabEnabled, setContestTabEnabled] = useState(() => localStorage.getItem('opslog.contestTab') === '1');
|
const [contestTabEnabled, setContestTabEnabled] = useState(() => localStorage.getItem('opslog.contestTab') === '1');
|
||||||
useEffect(() => { localStorage.setItem('opslog.contestTab', contestTabEnabled ? '1' : '0'); }, [contestTabEnabled]);
|
useEffect(() => { localStorage.setItem('opslog.contestTab', contestTabEnabled ? '1' : '0'); }, [contestTabEnabled]);
|
||||||
@@ -1737,15 +1746,29 @@ export default function App() {
|
|||||||
const gen = ++dvkAutoCqGenRef.current;
|
const gen = ++dvkAutoCqGenRef.current;
|
||||||
dvkAutoCqSlotRef.current = slot;
|
dvkAutoCqSlotRef.current = slot;
|
||||||
const sleep = (ms: number) => new Promise((r) => window.setTimeout(r, ms));
|
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) {
|
while (dvkAutoCqSlotRef.current === slot && gen === dvkAutoCqGenRef.current && dvkActiveRef.current) {
|
||||||
if (!isPhoneMode(modeRef.current)) { stopDvkAutoCq(); break; }
|
// An EMPTY mode is not a mode change: over the network the rig's mode
|
||||||
await DVKPlay(slot).catch(() => {});
|
// 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
|
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)
|
let guard = 0; // then wait for it to finish (cap ~90 s)
|
||||||
while (dvkPlayingRef.current && gen === dvkAutoCqGenRef.current && guard < 600) { await sleep(150); guard++; }
|
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
|
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) => {
|
const dvkPlay = useCallback((slot: number) => {
|
||||||
if (!isPhoneMode(modeRef.current)) { setError(t('dvkp.notPhone')); return; }
|
if (!isPhoneMode(modeRef.current)) { setError(t('dvkp.notPhone')); return; }
|
||||||
@@ -2018,7 +2041,7 @@ export default function App() {
|
|||||||
// so it's loaded async on mount and re-read on profile:changed below.
|
// so it's loaded async on mount and re-read on profile:changed below.
|
||||||
// 'none' is only ever stored for the third and fourth panes: the first two are
|
// 'none' is only ever stored for the third and fourth panes: the first two are
|
||||||
// the Main view, and a layout with no panes at all is not a layout.
|
// the Main view, and a layout with no panes at all is not a layout.
|
||||||
type MainPaneKind = 'map1' | 'map2' | 'cluster' | 'worked' | 'flex' | 'recent' | 'icom' | 'yaesu' | 'elecraft' | 'tci' | 'netcontrol' | 'decodes' | 'none';
|
type MainPaneKind = 'map1' | 'map2' | 'cluster' | 'worked' | 'flex' | 'recent' | 'icom' | 'yaesu' | 'elecraft' | 'tci' | 'netcontrol' | 'decodes' | 'watchlist' | 'none';
|
||||||
const [mapZoomSignal, setMapZoomSignal] = useState(0); // bump → world map auto-zooms now
|
const [mapZoomSignal, setMapZoomSignal] = useState(0); // bump → world map auto-zooms now
|
||||||
const [mainPaneLeft, setMainPaneLeft] = useState<MainPaneKind>('map1');
|
const [mainPaneLeft, setMainPaneLeft] = useState<MainPaneKind>('map1');
|
||||||
const [mainPaneRight, setMainPaneRight] = useState<MainPaneKind>('map2');
|
const [mainPaneRight, setMainPaneRight] = useState<MainPaneKind>('map2');
|
||||||
@@ -2029,7 +2052,7 @@ export default function App() {
|
|||||||
// quarter-width map is unreadable.
|
// quarter-width map is unreadable.
|
||||||
const [mainLayout4, setMainLayout4] = useState<'cols' | 'quad'>('quad');
|
const [mainLayout4, setMainLayout4] = useState<'cols' | 'quad'>('quad');
|
||||||
const loadMainPanes = useCallback(async () => {
|
const loadMainPanes = useCallback(async () => {
|
||||||
const valid = (v: string): v is MainPaneKind => v === 'map1' || v === 'map2' || v === 'cluster' || v === 'worked' || v === 'flex' || v === 'recent' || v === 'icom' || v === 'yaesu' || v === 'elecraft' || v === 'tci' || v === 'netcontrol' || v === 'decodes';
|
const valid = (v: string): v is MainPaneKind => v === 'map1' || v === 'map2' || v === 'cluster' || v === 'worked' || v === 'flex' || v === 'recent' || v === 'icom' || v === 'yaesu' || v === 'elecraft' || v === 'tci' || v === 'netcontrol' || v === 'decodes' || v === 'watchlist';
|
||||||
const [l, r, p3, p4, lay] = await Promise.all([
|
const [l, r, p3, p4, lay] = await Promise.all([
|
||||||
GetUIPref('mainPaneLeft').catch(() => ''),
|
GetUIPref('mainPaneLeft').catch(() => ''),
|
||||||
GetUIPref('mainPaneRight').catch(() => ''),
|
GetUIPref('mainPaneRight').catch(() => ''),
|
||||||
@@ -2543,6 +2566,10 @@ export default function App() {
|
|||||||
for (const d of decodes) {
|
for (const d of decodes) {
|
||||||
const seenKey = `${d.call}|${d.ms ?? d.at}|${d.instance ?? ''}`;
|
const seenKey = `${d.call}|${d.ms ?? d.at}|${d.instance ?? ''}`;
|
||||||
if (autoSeenRef.current.has(seenKey)) continue;
|
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
|
// 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.
|
// 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; }
|
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
|
// "the field still shows the previous broadcast" (safe to update) from "the
|
||||||
// user has typed a different call" (must not clobber).
|
// user has typed a different call" (must not clobber).
|
||||||
const lastUdpCallRef = useRef('');
|
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
|
// 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,
|
// Worked-before tab so the history is front-and-centre. Only once per call,
|
||||||
@@ -3304,12 +3336,21 @@ export default function App() {
|
|||||||
noteManualEdit();
|
noteManualEdit();
|
||||||
}
|
}
|
||||||
if (s.band) setBand(s.band);
|
if (s.band) setBand(s.band);
|
||||||
if (catState.connected) tuneRigCAT(s.freq_hz, m);
|
|
||||||
// The panadapter width follows the MODE of the spot, when the option is on.
|
// The panadapter width follows the MODE of the spot, when the option is on.
|
||||||
// AFTER the tune, deliberately: a view change must never delay the frequency
|
// A no-op on any backend but a Flex. Sequenced AFTER the tune settles, not
|
||||||
// change the operator is waiting for. A no-op on any backend but a Flex.
|
// fired alongside it: on a cross-band jump SmartSDR moves the panadapter
|
||||||
FlexZoomForSpot(m ?? '', s.freq_hz ?? 0).catch(() => {});
|
// itself to follow the slice, and that follow lands after — and overrides —
|
||||||
|
// a zoom sent in the same instant. (A spot clicked ON the panadapter never
|
||||||
|
// hit this: the radio had already tuned before our zoom arrived.)
|
||||||
|
const zoom = () => FlexZoomForSpot(m ?? '', s.freq_hz ?? 0).catch(() => {});
|
||||||
|
if (catState.connected) {
|
||||||
|
void tuneRigCAT(s.freq_hz, m).then(() => window.setTimeout(zoom, 300));
|
||||||
|
} else zoom();
|
||||||
if (m) applyModeFromSpot(m);
|
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 });
|
onCallsignInput(s.dx_call, { force: true });
|
||||||
applySpotRefs((s as any).pota_ref, (s as any).sota_ref);
|
applySpotRefs((s as any).pota_ref, (s as any).sota_ref);
|
||||||
if (s.dx_call?.trim()) restartRecordingForNewTarget(s.dx_call);
|
if (s.dx_call?.trim()) restartRecordingForNewTarget(s.dx_call);
|
||||||
@@ -3764,6 +3805,13 @@ export default function App() {
|
|||||||
// Anything that isn't WSJT-X (N1MM, ADIF, a panadapter/cluster click relayed
|
// 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.
|
// over UDP…) is an explicit pick → force it over an existing call.
|
||||||
const force = String(p?.service ?? '').toLowerCase() !== 'wsjt';
|
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.
|
// External app moved to a new station → fresh recording for the new target.
|
||||||
if (applyUdpCall(p?.call, force)) restartRecordingForNewTarget(String(p?.call ?? ''));
|
if (applyUdpCall(p?.call, force)) restartRecordingForNewTarget(String(p?.call ?? ''));
|
||||||
});
|
});
|
||||||
@@ -3774,6 +3822,9 @@ export default function App() {
|
|||||||
// Only when something is actually in the entry, so an idle digital app doesn't
|
// Only when something is actually in the entry, so an idle digital app doesn't
|
||||||
// wipe a call being typed by hand.
|
// wipe a call being typed by hand.
|
||||||
const unsubClear = EventsOn('udp:clear_call', () => {
|
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();
|
if (callsignRef.current?.value?.trim() || callsign.trim()) resetEntry();
|
||||||
});
|
});
|
||||||
// Clicked one of OpsLog's spots on the FlexRadio panadapter → fill the call
|
// Clicked one of OpsLog's spots on the FlexRadio panadapter → fill the call
|
||||||
@@ -4587,10 +4638,17 @@ export default function App() {
|
|||||||
return () => { dead = true; };
|
return () => { dead = true; };
|
||||||
}, [selQso, callsign]);
|
}, [selQso, callsign]);
|
||||||
|
|
||||||
|
const wbTokenRef = useRef(0);
|
||||||
async function runWorkedBefore(call: string, dxccHint: number = 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);
|
setWbBusy(true);
|
||||||
try {
|
try {
|
||||||
const w = await WorkedBefore(call, dxccHint);
|
const w = await WorkedBefore(call, dxccHint);
|
||||||
|
if (token !== wbTokenRef.current) return; // a newer lookup owns the panel
|
||||||
setWb(w);
|
setWb(w);
|
||||||
// Mirrored synchronously rather than through the effect above: a backfill
|
// 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
|
// parked by the lookup has to read this on the very next line, not a
|
||||||
@@ -4605,10 +4663,11 @@ export default function App() {
|
|||||||
fillFromLastQso(p.r, call);
|
fillFromLastQso(p.r, call);
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
|
if (token !== wbTokenRef.current) return;
|
||||||
setWb(null);
|
setWb(null);
|
||||||
wbRef.current = null;
|
wbRef.current = null;
|
||||||
wbCallRef.current = '';
|
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
|
// 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
|
// when the live lookup came up short — the callsign isn't on QRZ/HamQTH, or no
|
||||||
@@ -5002,14 +5061,13 @@ export default function App() {
|
|||||||
{ type: 'item', label: t('dec.tab'), action: 'tools.decodes' },
|
{ type: 'item', label: t('dec.tab'), action: 'tools.decodes' },
|
||||||
{ type: 'item', label: t('gsm.title'), action: 'tools.grids' },
|
{ type: 'item', label: t('gsm.title'), action: 'tools.grids' },
|
||||||
{ type: 'item', label: t('tools.qslDesigner'), action: 'tools.qsldesigner' },
|
{ type: 'item', label: t('tools.qslDesigner'), action: 'tools.qsldesigner' },
|
||||||
{ type: 'item', label: t('tools.labelDesigner'), action: 'tools.labeldesigner' },
|
|
||||||
{ type: 'item', label: t('tools.labelPrint'), action: 'tools.labelprint' },
|
|
||||||
{ type: 'separator' },
|
{ type: 'separator' },
|
||||||
{ type: 'item', label: (wkEnabled ? '✓ ' : '') + t('tools.winkeyer'), action: 'tools.winkeyer' },
|
{ type: 'item', label: (wkEnabled ? '✓ ' : '') + t('tools.winkeyer'), action: 'tools.winkeyer' },
|
||||||
{ type: 'item', label: (dvkEnabled ? '✓ ' : '') + t('tools.dvk'), action: 'tools.dvk' },
|
{ type: 'item', label: (dvkEnabled ? '✓ ' : '') + t('tools.dvk'), action: 'tools.dvk' },
|
||||||
{ type: 'item', label: (cwEnabled ? '✓ ' : '') + t('tools.cwDecoder'), action: 'tools.cwdecoder' },
|
{ type: 'item', label: (cwEnabled ? '✓ ' : '') + t('tools.cwDecoder'), action: 'tools.cwdecoder' },
|
||||||
{ type: 'separator' },
|
{ type: 'separator' },
|
||||||
{ type: 'item', label: (netEnabled ? '✓ ' : '') + t('tools.net'), action: 'tools.net' },
|
{ type: 'item', label: (netEnabled ? '✓ ' : '') + t('tools.net'), action: 'tools.net' },
|
||||||
|
{ type: 'item', label: (watchlistEnabled ? '✓ ' : '') + t('tools.watchlist'), action: 'tools.watchlist' },
|
||||||
{ type: 'item', label: (contestTabEnabled ? '✓ ' : '') + t('tools.contest'), action: 'tools.contest' },
|
{ type: 'item', label: (contestTabEnabled ? '✓ ' : '') + t('tools.contest'), action: 'tools.contest' },
|
||||||
{ type: 'item', label: t('tools.alerts'), action: 'tools.alerts' },
|
{ type: 'item', label: t('tools.alerts'), action: 'tools.alerts' },
|
||||||
{ type: 'separator' },
|
{ type: 'separator' },
|
||||||
@@ -5033,7 +5091,7 @@ export default function App() {
|
|||||||
{ type: 'separator' },
|
{ type: 'separator' },
|
||||||
{ type: 'item', label: t('help.about'), action: 'help.about' },
|
{ type: 'item', label: t('help.about'), action: 'help.about' },
|
||||||
]},
|
]},
|
||||||
], [total, selectedId, selectedIds, exporting, wkEnabled, dvkEnabled, cwEnabled, netEnabled, contestTabEnabled, smtpConfigured, sendingLog, t]);
|
], [total, selectedId, selectedIds, exporting, wkEnabled, dvkEnabled, cwEnabled, netEnabled, watchlistEnabled, contestTabEnabled, smtpConfigured, sendingLog, t]);
|
||||||
|
|
||||||
function handleMenu(action: string) {
|
function handleMenu(action: string) {
|
||||||
switch (action) {
|
switch (action) {
|
||||||
@@ -5057,12 +5115,11 @@ export default function App() {
|
|||||||
case 'tools.decodes': openDecodesTab(); break;
|
case 'tools.decodes': openDecodesTab(); break;
|
||||||
case 'tools.grids': openGridsTab(); break;
|
case 'tools.grids': openGridsTab(); break;
|
||||||
case 'tools.qsldesigner': setQslDesignerOpen(true); break;
|
case 'tools.qsldesigner': setQslDesignerOpen(true); break;
|
||||||
case 'tools.labeldesigner': setLabelDesignerOpen(true); break;
|
|
||||||
case 'tools.labelprint': setLabelPrintOpen(true); break;
|
|
||||||
case 'tools.winkeyer': wkSetEnabled(!wkEnabled); break;
|
case 'tools.winkeyer': wkSetEnabled(!wkEnabled); break;
|
||||||
case 'tools.dvk': setDvkEnabled((v) => !v); break;
|
case 'tools.dvk': setDvkEnabled((v) => !v); break;
|
||||||
case 'tools.cwdecoder': toggleCwDecoder(); break;
|
case 'tools.cwdecoder': toggleCwDecoder(); break;
|
||||||
case 'tools.net': setNetEnabled((v) => { const nv = !v; if (nv) setActiveTab('net'); return nv; }); break;
|
case 'tools.net': setNetEnabled((v) => { const nv = !v; if (nv) setActiveTab('net'); return nv; }); break;
|
||||||
|
case 'tools.watchlist': setWatchlistEnabled((v) => { const nv = !v; if (nv) setActiveTab('watchlist'); return nv; }); break;
|
||||||
case 'tools.contest': setContestTabEnabled((v) => { const nv = !v; if (nv) setActiveTab('contest'); else setActiveTab((tb) => (tb === 'contest' ? 'recent' : tb)); return nv; }); break;
|
case 'tools.contest': setContestTabEnabled((v) => { const nv = !v; if (nv) setActiveTab('contest'); else setActiveTab((tb) => (tb === 'contest' ? 'recent' : tb)); return nv; }); break;
|
||||||
case 'tools.alerts': setAlertsOpen(true); break;
|
case 'tools.alerts': setAlertsOpen(true); break;
|
||||||
case 'tools.duplicates': setShowDuplicates(true); break;
|
case 'tools.duplicates': setShowDuplicates(true); break;
|
||||||
@@ -5878,6 +5935,13 @@ export default function App() {
|
|||||||
// worked call still matches its own entity status too (new-band/new-slot),
|
// worked call still matches its own entity status too (new-band/new-slot),
|
||||||
// so it stays visible under those chips.
|
// so it stays visible under those chips.
|
||||||
const matches = (st !== 'worked' && clusterStatusFilter.has(st))
|
const matches = (st !== 'worked' && clusterStatusFilter.has(st))
|
||||||
|
// NEW CALL is a FACT about the callsign (never worked on this band and
|
||||||
|
// mode), surfaced as a status only by the slot-highlight option. The
|
||||||
|
// chip filters on the fact itself, so it works whether or not that
|
||||||
|
// display option is on — worked_slot is computed whenever either
|
||||||
|
// slot option is enabled.
|
||||||
|
|| (clusterStatusFilter.has('new-call') && e?.worked_slot === false
|
||||||
|
&& (!e?.status || e?.status === 'worked' || e?.status === 'new-call'))
|
||||||
|| (!!e?.worked_call && clusterStatusFilter.has('worked'))
|
|| (!!e?.worked_call && clusterStatusFilter.has('worked'))
|
||||||
|| (!!e?.new_pota && clusterStatusFilter.has('new-pota'))
|
|| (!!e?.new_pota && clusterStatusFilter.has('new-pota'))
|
||||||
|| (!!e?.new_county && clusterStatusFilter.has('new-county'))
|
|| (!!e?.new_county && clusterStatusFilter.has('new-county'))
|
||||||
@@ -5984,12 +6048,20 @@ export default function App() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
const F_CHIP = 'px-1.5 py-[3px] rounded-md border text-[10px] font-bold tracking-wider transition-opacity';
|
const F_CHIP = 'px-1.5 py-[3px] rounded-md border text-[10px] font-bold tracking-wider transition-opacity';
|
||||||
const fChip = (key: string, label: string, cls: string, on: boolean, toggle: () => void) => (
|
const fChip = (key: string, label: string, cls: string, on: boolean, toggle: () => void, style?: React.CSSProperties, title?: string) => (
|
||||||
<button key={key} type="button" onClick={toggle}
|
<button key={key} type="button" onClick={toggle} title={title}
|
||||||
className={cn(F_CHIP, on ? cls : `${cls} opacity-40 hover:opacity-80`)}>
|
className={cn(F_CHIP, on ? cls : `${cls} opacity-40 hover:opacity-80`)} style={style}>
|
||||||
{label}
|
{label}
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
|
// chipStyle builds a filter chip in an arbitrary colour — for the statuses
|
||||||
|
// whose grid badge is not one of the semantic tokens the chip classes cover.
|
||||||
|
// A filter that does not look like what it selects has to be learned twice.
|
||||||
|
const chipStyle = (c: string): React.CSSProperties => ({
|
||||||
|
color: c,
|
||||||
|
borderColor: `color-mix(in srgb, ${c} 45%, transparent)`,
|
||||||
|
background: `color-mix(in srgb, ${c} 14%, transparent)`,
|
||||||
|
});
|
||||||
|
|
||||||
const renderClusterFilters = () => (
|
const renderClusterFilters = () => (
|
||||||
<div className="w-56 shrink-0 border-l border-border/60 flex flex-col min-h-0 bg-muted/10">
|
<div className="w-56 shrink-0 border-l border-border/60 flex flex-col min-h-0 bg-muted/10">
|
||||||
@@ -6105,14 +6177,14 @@ export default function App() {
|
|||||||
{ k: 'new-band-mode' as SpotFilterKey, label: 'NEW B+M', cls: 'bg-danger-muted text-danger-muted-foreground border-danger-border' },
|
{ k: 'new-band-mode' as SpotFilterKey, label: 'NEW B+M', cls: 'bg-danger-muted text-danger-muted-foreground border-danger-border' },
|
||||||
{ k: 'new-band' as SpotFilterKey, label: 'NEW BAND', cls: 'bg-warning-muted text-warning-muted-foreground border-warning-border' },
|
{ k: 'new-band' as SpotFilterKey, label: 'NEW BAND', cls: 'bg-warning-muted text-warning-muted-foreground border-warning-border' },
|
||||||
{ k: 'new-mode' as SpotFilterKey, label: 'NEW MODE', cls: 'bg-caution-muted text-caution-muted-foreground border-caution-border' },
|
{ k: 'new-mode' as SpotFilterKey, label: 'NEW MODE', cls: 'bg-caution-muted text-caution-muted-foreground border-caution-border' },
|
||||||
{ k: 'new-slot' as SpotFilterKey, label: 'NEW SLOT', cls: 'bg-caution-muted text-caution-muted-foreground border-caution-border' },
|
{ k: 'new-slot' as SpotFilterKey, label: 'NEW SLOT', cls: 'border', style: chipStyle('#5AC8FA') },
|
||||||
// NEW CALL is about the CALLSIGN, not the entity: never worked on this
|
// NEW CALL is about the CALLSIGN, not the entity: never worked on this
|
||||||
// band and mode. Only appears when the slot-highlight option is on.
|
// band and mode. Only appears when the slot-highlight option is on.
|
||||||
{ k: 'new-call' as SpotFilterKey, label: 'NEW CALL', cls: 'bg-caution-muted text-caution-muted-foreground border-caution-border' },
|
{ k: 'new-call' as SpotFilterKey, label: 'NEW CALL', cls: 'bg-caution-muted text-caution-muted-foreground border-caution-border' },
|
||||||
// Same colours as the badges in the grid — a filter that does not
|
// Same colours as the badges in the grid — a filter that does not
|
||||||
// look like what it selects has to be learned twice.
|
// look like what it selects has to be learned twice.
|
||||||
{ k: 'new-pota' as SpotFilterKey, label: 'NEW POTA', cls: 'bg-success-muted text-success-muted-foreground border-success-border' },
|
{ k: 'new-pota' as SpotFilterKey, label: 'NEW POTA', cls: 'bg-success-muted text-success-muted-foreground border-success-border' },
|
||||||
{ k: 'new-county' as SpotFilterKey, label: 'NEW COUNTY', cls: 'bg-success-muted text-success-muted-foreground border-success-border' },
|
{ k: 'new-county' as SpotFilterKey, label: 'NEW COUNTY', cls: 'border', style: chipStyle('var(--chart-5)') },
|
||||||
{ k: 'new-pfx' as SpotFilterKey, label: 'NEW PFX', cls: 'bg-caution-muted text-caution-muted-foreground border-caution-border' },
|
{ k: 'new-pfx' as SpotFilterKey, label: 'NEW PFX', cls: 'bg-caution-muted text-caution-muted-foreground border-caution-border' },
|
||||||
// Only ever set for a station this receiver decoded over the UDP link.
|
// Only ever set for a station this receiver decoded over the UDP link.
|
||||||
{ k: 'new-grid' as SpotFilterKey, label: 'NEW GRID', cls: 'bg-muted text-foreground border-border' },
|
{ k: 'new-grid' as SpotFilterKey, label: 'NEW GRID', cls: 'bg-muted text-foreground border-border' },
|
||||||
@@ -6120,8 +6192,9 @@ export default function App() {
|
|||||||
// worked spots; the separate "Hide worked" checkbox drops them — they
|
// worked spots; the separate "Hide worked" checkbox drops them — they
|
||||||
// are opposite controls, so don't use both at once.
|
// are opposite controls, so don't use both at once.
|
||||||
{ k: 'worked' as SpotFilterKey, label: 'WORKED', cls: 'bg-info-muted text-info-muted-foreground border-info-border' },
|
{ k: 'worked' as SpotFilterKey, label: 'WORKED', cls: 'bg-info-muted text-info-muted-foreground border-info-border' },
|
||||||
]).map((s) => fChip(s.k, s.label, s.cls, clusterStatusFilter.has(s.k),
|
]).filter((s: any) => s.k !== 'new-pota' || chasePota())
|
||||||
() => setClusterStatusFilter((cur) => { const n = new Set(cur); if (n.has(s.k)) n.delete(s.k); else n.add(s.k); return n; })))}
|
.map((s: any) => fChip(s.k, s.label, s.cls, clusterStatusFilter.has(s.k),
|
||||||
|
() => setClusterStatusFilter((cur) => { const n = new Set(cur); if (n.has(s.k)) n.delete(s.k); else n.add(s.k); return n; }), s.style))}
|
||||||
</div>,
|
</div>,
|
||||||
clusterStatusFilter.size > 0 ? (
|
clusterStatusFilter.size > 0 ? (
|
||||||
<button type="button" onClick={() => setClusterStatusFilter(new Set())}
|
<button type="button" onClick={() => setClusterStatusFilter(new Set())}
|
||||||
@@ -6325,6 +6398,13 @@ export default function App() {
|
|||||||
<IcomPanel isNetwork={catBackend === 'icom-net'} onReportRST={(r) => { setRstSent(r); rstUserEditedRef.current = true; }} />
|
<IcomPanel isNetwork={catBackend === 'icom-net'} onReportRST={(r) => { setRstSent(r); rstUserEditedRef.current = true; }} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
case 'watchlist':
|
||||||
|
return (
|
||||||
|
<div className="h-full w-full min-h-0 flex flex-col bg-card border border-border rounded-lg overflow-hidden">
|
||||||
|
<WatchlistTab spots={spots} spotStatus={spotStatus}
|
||||||
|
onSpotSelect={handleSpotSelect} onSpotClick={handleSpotClick} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
case 'netcontrol':
|
case 'netcontrol':
|
||||||
return (
|
return (
|
||||||
<div className="h-full w-full min-h-0 flex flex-col rounded-lg overflow-hidden border border-border">
|
<div className="h-full w-full min-h-0 flex flex-col rounded-lg overflow-hidden border border-border">
|
||||||
@@ -7218,7 +7298,7 @@ export default function App() {
|
|||||||
// relative + absolute inner: the panel's content can't grow the row, so
|
// relative + absolute inner: the panel's content can't grow the row, so
|
||||||
// the row height is set by the ENTRY STRIP. A taller tab (Awards/F3) then
|
// the row height is set by the ENTRY STRIP. A taller tab (Awards/F3) then
|
||||||
// scrolls inside this fixed height instead of pushing everything down.
|
// scrolls inside this fixed height instead of pushing everything down.
|
||||||
<div className="w-[560px] shrink-0 min-h-0 relative">
|
<div className="w-[600px] shrink-0 min-h-0 relative">
|
||||||
<div className="absolute inset-0 flex flex-col min-h-0">
|
<div className="absolute inset-0 flex flex-col min-h-0">
|
||||||
<DetailsPanel
|
<DetailsPanel
|
||||||
callsign={callsign}
|
callsign={callsign}
|
||||||
@@ -7400,7 +7480,10 @@ export default function App() {
|
|||||||
entry, and the rig onto the frequency it was decoded on. */}
|
entry, and the rig onto the frequency it was decoded on. */}
|
||||||
<ChaseNewPanel onPick={(sp) => {
|
<ChaseNewPanel onPick={(sp) => {
|
||||||
onCallsignInput(sp.call, { force: true });
|
onCallsignInput(sp.call, { force: true });
|
||||||
if (sp.freq_hz) void tuneRigCAT(sp.freq_hz, sp.mode);
|
// And the panadapter width too — after the tune settles, for the
|
||||||
|
// same SmartSDR pan-follow reason as handleSpotClick.
|
||||||
|
if (sp.freq_hz) void tuneRigCAT(sp.freq_hz, sp.mode).then(() =>
|
||||||
|
window.setTimeout(() => FlexZoomForSpot(sp.mode ?? '', sp.freq_hz ?? 0).catch(() => {}), 300));
|
||||||
}} onClose={() => { setShowChaseNew(false); writeUiPref('opslog.showChaseNew', '0'); }} />
|
}} onClose={() => { setShowChaseNew(false); writeUiPref('opslog.showChaseNew', '0'); }} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -7593,6 +7676,21 @@ export default function App() {
|
|||||||
</span>
|
</span>
|
||||||
</TabsTrigger>
|
</TabsTrigger>
|
||||||
)}
|
)}
|
||||||
|
{watchlistEnabled && (
|
||||||
|
<TabsTrigger value="watchlist" className="gap-1.5">
|
||||||
|
{t('tab.watchlist')}
|
||||||
|
<span
|
||||||
|
role="button"
|
||||||
|
aria-label="Close Watchlist"
|
||||||
|
title="Close"
|
||||||
|
className="inline-flex items-center justify-center size-4 rounded hover:bg-foreground/10 text-muted-foreground hover:text-foreground"
|
||||||
|
onPointerDown={(e) => { e.stopPropagation(); }}
|
||||||
|
onClick={(e) => { e.stopPropagation(); setWatchlistEnabled(false); setActiveTab((t) => (t === 'watchlist' ? 'recent' : t)); }}
|
||||||
|
>
|
||||||
|
<X className="size-3" />
|
||||||
|
</span>
|
||||||
|
</TabsTrigger>
|
||||||
|
)}
|
||||||
{catState.backend === 'flex' && <TabsTrigger value="flex">Flex Console</TabsTrigger>}
|
{catState.backend === 'flex' && <TabsTrigger value="flex">Flex Console</TabsTrigger>}
|
||||||
{catState.backend === 'icom' && <TabsTrigger value="icom">Icom Console</TabsTrigger>}
|
{catState.backend === 'icom' && <TabsTrigger value="icom">Icom Console</TabsTrigger>}
|
||||||
{catState.backend === 'yaesu' && <TabsTrigger value="yaesu">Yaesu Console</TabsTrigger>}
|
{catState.backend === 'yaesu' && <TabsTrigger value="yaesu">Yaesu Console</TabsTrigger>}
|
||||||
@@ -8304,6 +8402,12 @@ export default function App() {
|
|||||||
{/* Band Map: several bands shown side-by-side (panadapter-style
|
{/* Band Map: several bands shown side-by-side (panadapter-style
|
||||||
strips). Pick bands with the chips; each strip is clickable to
|
strips). Pick bands with the chips; each strip is clickable to
|
||||||
tune the rig. */}
|
tune the rig. */}
|
||||||
|
{watchlistEnabled && (
|
||||||
|
<TabsContent value="watchlist" className="mt-0 flex flex-col min-h-0 flex-1">
|
||||||
|
<WatchlistTab spots={spots} spotStatus={spotStatus}
|
||||||
|
onSpotSelect={handleSpotSelect} onSpotClick={handleSpotClick} />
|
||||||
|
</TabsContent>
|
||||||
|
)}
|
||||||
{netEnabled && (
|
{netEnabled && (
|
||||||
<TabsContent value="net" className="mt-0 flex flex-col min-h-0 flex-1">
|
<TabsContent value="net" className="mt-0 flex flex-col min-h-0 flex-1">
|
||||||
<NetControlPanel onLogged={refresh} countries={countries} bands={bands} modes={modes}
|
<NetControlPanel onLogged={refresh} countries={countries} bands={bands} modes={modes}
|
||||||
@@ -8660,9 +8764,14 @@ export default function App() {
|
|||||||
// freqMhz display string, which the manual-edit freeze / field locks can
|
// freqMhz display string, which the manual-edit freeze / field locks can
|
||||||
// leave stale (that dropped the sub-kHz: on 14134.5 the frozen "14.134"
|
// leave stale (that dropped the sub-kHz: on 14134.5 the frozen "14.134"
|
||||||
// string spotted 14134). Fall back to the entry field, then the last QSO.
|
// string spotted 14134). Fall back to the entry field, then the last QSO.
|
||||||
|
//
|
||||||
|
// The RX frequency when split, deliberately: a spot names where the
|
||||||
|
// STATION is, and in split that is where we listen — freq_hz is where
|
||||||
|
// we transmit, and spotting a 5-up pile-up's TX frequency sent the
|
||||||
|
// whole cluster five kHz above the DX.
|
||||||
defaultFreqKHz={
|
defaultFreqKHz={
|
||||||
catState.connected && (catState.freq_hz ?? 0) > 0
|
catState.connected && ((catState.split && (catState.freq_rx_hz ?? 0) > 0 ? catState.freq_rx_hz : catState.freq_hz) ?? 0) > 0
|
||||||
? Math.round(((catState.freq_hz ?? 0) / 1000) * 10) / 10
|
? Math.round((((catState.split && (catState.freq_rx_hz ?? 0) > 0 ? catState.freq_rx_hz : catState.freq_hz) ?? 0) / 1000) * 10) / 10
|
||||||
: parseFloat(freqMhz) > 0
|
: parseFloat(freqMhz) > 0
|
||||||
? Math.round(parseFloat(freqMhz) * 1000 * 10) / 10
|
? Math.round(parseFloat(freqMhz) * 1000 * 10) / 10
|
||||||
: (qsos[0]?.freq_hz ? Math.round((qsos[0].freq_hz / 1000) * 10) / 10 : 0)
|
: (qsos[0]?.freq_hz ? Math.round((qsos[0].freq_hz / 1000) * 10) / 10 : 0)
|
||||||
@@ -8720,8 +8829,6 @@ export default function App() {
|
|||||||
onError={(msg) => showToast(msg)}
|
onError={(msg) => showToast(msg)}
|
||||||
/>
|
/>
|
||||||
<QslDesignerModal open={qslDesignerOpen} onClose={() => setQslDesignerOpen(false)} />
|
<QslDesignerModal open={qslDesignerOpen} onClose={() => setQslDesignerOpen(false)} />
|
||||||
<LabelDesignerModal open={labelDesignerOpen} onClose={() => setLabelDesignerOpen(false)} />
|
|
||||||
<LabelPrintModal open={labelPrintOpen} onClose={() => setLabelPrintOpen(false)} />
|
|
||||||
<SendEQSLModal
|
<SendEQSLModal
|
||||||
open={eqslQsoId !== null}
|
open={eqslQsoId !== null}
|
||||||
qsoId={eqslQsoId}
|
qsoId={eqslQsoId}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|||||||
import { Minus, Plus, Crosshair, X, PanelLeft, PanelRight } from 'lucide-react';
|
import { Minus, Plus, Crosshair, X, PanelLeft, PanelRight } from 'lucide-react';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { useI18n } from '@/lib/i18n';
|
import { useI18n } from '@/lib/i18n';
|
||||||
|
import { bandRange, bandSegments, subscribeIaruRegion, type SegMode } from '@/lib/bandplan';
|
||||||
import { spotStatusKey, inferSpotMode, spotModeCategory } from '@/lib/spot';
|
import { spotStatusKey, inferSpotMode, spotModeCategory } from '@/lib/spot';
|
||||||
import { SPOT_MARKERS, activeMarkers } from '@/lib/spotMarkers';
|
import { SPOT_MARKERS, activeMarkers } from '@/lib/spotMarkers';
|
||||||
import { applySpotDisplay, readSpotDisplayOptions } from '@/lib/spotDisplay';
|
import { applySpotDisplay, readSpotDisplayOptions } from '@/lib/spotDisplay';
|
||||||
@@ -114,59 +115,26 @@ interface Props {
|
|||||||
keyNav?: boolean;
|
keyNav?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
const BAND_RANGES: Record<string, [number, number]> = {
|
// Band edges and mode segments come from lib/bandplan, which knows the
|
||||||
'160m': [1800, 2000],
|
// operator's IARU region (Settings → General): a Region 2 operator's 40 m runs
|
||||||
'80m': [3500, 3800],
|
// to 7300 with phone from 7125, and drawing Region 1's plan under their spots
|
||||||
'60m': [5350, 5450],
|
// cut the top 100 kHz of the band off the map.
|
||||||
'40m': [7000, 7200],
|
//
|
||||||
'30m': [10100, 10150],
|
// Sub-band shading colours: these are IDENTITIES (which mode the segment is
|
||||||
'20m': [14000, 14350],
|
// for), not states, so they take categorical hues — never the status tokens.
|
||||||
'17m': [18068, 18168],
|
// All three are drawn from the cool end of the categorical order and laid down
|
||||||
'15m': [21000, 21450],
|
// at low opacity, so the band plan stays background context while the warm
|
||||||
'12m': [24890, 24990],
|
// spot pills keep the foreground. Checked with the palette validator in both
|
||||||
'10m': [28000, 29700],
|
// themes (violet failed the dark protan step; magenta clears every check).
|
||||||
'6m': [50000, 50500],
|
const SEG_COLOR: Record<SegMode, string> = {
|
||||||
'4m': [70000, 70500],
|
cw: 'var(--chart-7)', // magenta
|
||||||
'2m': [144000, 146000],
|
digi: 'var(--chart-1)', // blue
|
||||||
'70cm': [430000, 440000],
|
phone: 'var(--chart-2)', // aqua
|
||||||
};
|
};
|
||||||
|
|
||||||
// Sub-band shading: CW / digital / phone.
|
|
||||||
//
|
|
||||||
// These are IDENTITIES (which mode the segment is for), not states, so they take
|
|
||||||
// categorical hues — never the status tokens. They used to use success / info /
|
|
||||||
// warning, which collided head-on with the spot pills drawn ON TOP of them: amber
|
|
||||||
// is "new band" in this very component's legend, so the whole SSB portion read as
|
|
||||||
// a giant "new band" wash. Status colours are reserved for status.
|
|
||||||
//
|
|
||||||
// All three are drawn from the COOL end of the categorical order and laid down at
|
|
||||||
// low opacity, so the band plan stays background context while the warm spot pills
|
|
||||||
// keep the foreground to themselves.
|
|
||||||
// Checked with the palette validator in BOTH themes. Violet was the first pick
|
|
||||||
// for CW and failed on the dark steps — violet and blue land 1.9 ΔE apart for a
|
|
||||||
// protan reader there, i.e. the same colour. Magenta clears every check on both
|
|
||||||
// surfaces (worst adjacent pair 13.0 light / 15.9 dark).
|
|
||||||
const SEG_CW = 'var(--chart-7)'; // magenta
|
|
||||||
const SEG_DIGI = 'var(--chart-1)'; // blue
|
|
||||||
const SEG_PHONE = 'var(--chart-2)'; // aqua
|
|
||||||
// A band-plan wash is CONTEXT, not data: it must stay under the spot pills that
|
// A band-plan wash is CONTEXT, not data: it must stay under the spot pills that
|
||||||
// are read on top of it.
|
// are read on top of it.
|
||||||
const SEG_OPACITY = 0.13;
|
const SEG_OPACITY = 0.13;
|
||||||
|
|
||||||
const SEGMENT_COLORS: Record<string, [number, number, string][]> = {
|
|
||||||
'160m': [[1800, 1838, SEG_CW], [1838, 1840, SEG_DIGI], [1840, 2000, SEG_PHONE]],
|
|
||||||
'80m': [[3500, 3580, SEG_CW], [3580, 3600, SEG_DIGI], [3600, 3800, SEG_PHONE]],
|
|
||||||
'60m': [[5350, 5450, SEG_PHONE]],
|
|
||||||
'40m': [[7000, 7040, SEG_CW], [7040, 7100, SEG_DIGI], [7100, 7200, SEG_PHONE]],
|
|
||||||
'30m': [[10100, 10130, SEG_CW], [10130, 10150, SEG_DIGI]],
|
|
||||||
'20m': [[14000, 14070, SEG_CW], [14070, 14100, SEG_DIGI], [14100, 14350, SEG_PHONE]],
|
|
||||||
'17m': [[18068, 18095, SEG_CW], [18095, 18110, SEG_DIGI], [18110, 18168, SEG_PHONE]],
|
|
||||||
'15m': [[21000, 21070, SEG_CW], [21070, 21150, SEG_DIGI], [21150, 21450, SEG_PHONE]],
|
|
||||||
'12m': [[24890, 24915, SEG_CW], [24915, 24940, SEG_DIGI], [24940, 24990, SEG_PHONE]],
|
|
||||||
'10m': [[28000, 28070, SEG_CW], [28070, 28300, SEG_DIGI], [28300, 29700, SEG_PHONE]],
|
|
||||||
'6m': [[50000, 50100, SEG_CW], [50100, 50500, SEG_PHONE]],
|
|
||||||
};
|
|
||||||
|
|
||||||
// Small coloured dot + label used in the band-map legend strip.
|
// Small coloured dot + label used in the band-map legend strip.
|
||||||
function LegendDot({ cls, colour, label }: { cls?: string; colour?: string; label: string }) {
|
function LegendDot({ cls, colour, label }: { cls?: string; colour?: string; label: string }) {
|
||||||
return (
|
return (
|
||||||
@@ -304,13 +272,16 @@ export function BandMap({ band, spots, spotStatus: spotStatusRaw, currentFreqHz,
|
|||||||
// nothing until the next poll happened to hand over a fresh object.
|
// nothing until the next poll happened to hand over a fresh object.
|
||||||
const dispOpts = readSpotDisplayOptions();
|
const dispOpts = readSpotDisplayOptions();
|
||||||
const spotStatus = useMemo(() => {
|
const spotStatus = useMemo(() => {
|
||||||
if (!dispOpts.muteWorked && !dispOpts.slotHighlight) return spotStatusRaw;
|
if (!dispOpts.muteWorked && !dispOpts.slotHighlight && dispOpts.chasePota) return spotStatusRaw;
|
||||||
const out: Record<string, SpotStatusEntry> = {};
|
const out: Record<string, SpotStatusEntry> = {};
|
||||||
for (const k of Object.keys(spotStatusRaw)) out[k] = applySpotDisplay(spotStatusRaw[k], dispOpts) as SpotStatusEntry;
|
for (const k of Object.keys(spotStatusRaw)) out[k] = applySpotDisplay(spotStatusRaw[k], dispOpts) as SpotStatusEntry;
|
||||||
return out;
|
return out;
|
||||||
}, [spotStatusRaw, dispOpts.muteWorked, dispOpts.slotHighlight]);
|
}, [spotStatusRaw, dispOpts.muteWorked, dispOpts.slotHighlight, dispOpts.chasePota]);
|
||||||
const range = BAND_RANGES[band];
|
// Re-render when the operator changes their IARU region in Settings.
|
||||||
const segments = SEGMENT_COLORS[band] ?? [];
|
const [, setRegionTick] = useState(0);
|
||||||
|
useEffect(() => subscribeIaruRegion(() => setRegionTick((n) => n + 1)), []);
|
||||||
|
const range = bandRange(band);
|
||||||
|
const segments = bandSegments(band).map(([a, b, m]) => [a, b, SEG_COLOR[m]] as [number, number, string]);
|
||||||
const [zoomIdx, setZoomIdx] = useState(() => readZoom(band));
|
const [zoomIdx, setZoomIdx] = useState(() => readZoom(band));
|
||||||
// The docked map follows the rig, so a band change must bring up THAT band's
|
// The docked map follows the rig, so a band change must bring up THAT band's
|
||||||
// remembered zoom.
|
// remembered zoom.
|
||||||
@@ -794,9 +765,9 @@ export function BandMap({ band, spots, spotStatus: spotStatusRaw, currentFreqHz,
|
|||||||
))}
|
))}
|
||||||
{/* Sub-band shading, so the wash behind the pills is never colour-alone. */}
|
{/* Sub-band shading, so the wash behind the pills is never colour-alone. */}
|
||||||
<span className="mx-0.5 opacity-40">|</span>
|
<span className="mx-0.5 opacity-40">|</span>
|
||||||
<LegendDot colour={SEG_CW} label={t("bmp.legendCW")} />
|
<LegendDot colour={SEG_COLOR.cw} label={t("bmp.legendCW")} />
|
||||||
<LegendDot colour={SEG_DIGI} label={t("bmp.legendData")} />
|
<LegendDot colour={SEG_COLOR.digi} label={t("bmp.legendData")} />
|
||||||
<LegendDot colour={SEG_PHONE} label={t("bmp.legendPhone")} />
|
<LegendDot colour={SEG_COLOR.phone} label={t("bmp.legendPhone")} />
|
||||||
</div>
|
</div>
|
||||||
<div className="px-3 py-1 text-[9px] text-muted-foreground bg-muted/30 border-t border-border font-mono text-center shrink-0">
|
<div className="px-3 py-1 text-[9px] text-muted-foreground bg-muted/30 border-t border-border font-mono text-center shrink-0">
|
||||||
{t('bmp.footerHint')}
|
{t('bmp.footerHint')}
|
||||||
|
|||||||
@@ -242,11 +242,11 @@ export function BandSlotGrid({ wb, busy, currentBand, currentMode, bands, hasCal
|
|||||||
return (
|
return (
|
||||||
<section
|
<section
|
||||||
className={cn(
|
className={cn(
|
||||||
'flex items-center gap-4 px-3 py-2 flex-wrap shrink-0',
|
'flex items-center gap-2 px-2 py-2 flex-wrap shrink-0',
|
||||||
newOne && 'bg-gradient-to-br from-warning-muted to-warning-muted rounded-lg',
|
newOne && 'bg-gradient-to-br from-warning-muted to-warning-muted rounded-lg',
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<div className="flex items-center gap-2 min-w-[220px] flex-1">
|
<div className="flex items-center gap-2 min-w-0 flex-1">
|
||||||
{newOne ? (
|
{newOne ? (
|
||||||
<>
|
<>
|
||||||
<Badge className="bg-warning text-warning-foreground gap-1 px-3 py-1 text-[11px]">
|
<Badge className="bg-warning text-warning-foreground gap-1 px-3 py-1 text-[11px]">
|
||||||
@@ -269,7 +269,7 @@ export function BandSlotGrid({ wb, busy, currentBand, currentMode, bands, hasCal
|
|||||||
{forCall}
|
{forCall}
|
||||||
</Badge>
|
</Badge>
|
||||||
)}
|
)}
|
||||||
<Badge className="bg-primary text-primary-foreground px-3 py-1 text-xs normal-case font-semibold tracking-normal">
|
<Badge className="bg-primary text-primary-foreground px-2 py-0.5 text-xs normal-case font-semibold tracking-normal leading-tight">
|
||||||
{dxccName || `DXCC #${dxcc}`}
|
{dxccName || `DXCC #${dxcc}`}
|
||||||
</Badge>
|
</Badge>
|
||||||
{mwBadge}
|
{mwBadge}
|
||||||
|
|||||||
@@ -60,6 +60,9 @@ const FIELDS: FieldDef[] = [
|
|||||||
// No promoted column: written into extras_json (see qso.bulkEditableExtras).
|
// No promoted column: written into extras_json (see qso.bulkEditableExtras).
|
||||||
{ id: 'owner_callsign', label: 'bulk.fOwnerCallsign', group: 'My station', kind: 'text', upper: true },
|
{ id: 'owner_callsign', label: 'bulk.fOwnerCallsign', group: 'My station', kind: 'text', upper: true },
|
||||||
{ id: 'my_grid', label: 'bulk.fMyGrid', group: 'My station', kind: 'text', upper: true },
|
{ id: 'my_grid', label: 'bulk.fMyGrid', group: 'My station', kind: 'text', upper: true },
|
||||||
|
{ id: 'my_dxcc', label: 'bulk.fMyDxcc', group: 'My station', kind: 'text' },
|
||||||
|
{ id: 'my_cq_zone', label: 'bulk.fMyCqZone', group: 'My station', kind: 'text' },
|
||||||
|
{ id: 'my_itu_zone', label: 'bulk.fMyItuZone', group: 'My station', kind: 'text' },
|
||||||
{ id: 'my_antenna', label: 'bulk.fMyAntenna', group: 'My station', kind: 'text' },
|
{ id: 'my_antenna', label: 'bulk.fMyAntenna', group: 'My station', kind: 'text' },
|
||||||
{ id: 'my_rig', label: 'bulk.fMyRig', group: 'My station', kind: 'text' },
|
{ id: 'my_rig', label: 'bulk.fMyRig', group: 'My station', kind: 'text' },
|
||||||
{ id: 'my_street', label: 'bulk.fMyStreet', group: 'My station', kind: 'text' },
|
{ id: 'my_street', label: 'bulk.fMyStreet', group: 'My station', kind: 'text' },
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import { Button } from '@/components/ui/button';
|
|||||||
import { Checkbox } from '@/components/ui/checkbox';
|
import { Checkbox } from '@/components/ui/checkbox';
|
||||||
import { cleanSpotter, inferSpotMode, spotStatusKey } from '@/lib/spot';
|
import { cleanSpotter, inferSpotMode, spotStatusKey } from '@/lib/spot';
|
||||||
import { markerColour } from '@/lib/spotMarkers';
|
import { markerColour } from '@/lib/spotMarkers';
|
||||||
import { applySpotDisplay, readSpotDisplayOptions } from '@/lib/spotDisplay';
|
import { applySpotDisplay, chasePota, chaseSota, readSpotDisplayOptions } from '@/lib/spotDisplay';
|
||||||
import { loadLocal, loadRemote, saveState, seedLocal, whenGridPrefsReady } from '@/lib/gridPrefs';
|
import { loadLocal, loadRemote, saveState, seedLocal, whenGridPrefsReady } from '@/lib/gridPrefs';
|
||||||
import { distanceUnit, distanceValue, subscribeDistanceUnit } from '@/lib/units';
|
import { distanceUnit, distanceValue, subscribeDistanceUnit } from '@/lib/units';
|
||||||
import { useI18n } from '@/lib/i18n';
|
import { useI18n } from '@/lib/i18n';
|
||||||
@@ -148,6 +148,12 @@ function statusFor(p: any): SpotStatusEntry | undefined {
|
|||||||
// filled pfx → new prefix filled POTA → new park filled county → new county
|
// filled pfx → new prefix filled POTA → new park filled county → new county
|
||||||
// blue call → already worked (not a novelty, so text only)
|
// blue call → already worked (not a novelty, so text only)
|
||||||
const NEW = 'var(--warning)'; // yellow: something here is new
|
const NEW = 'var(--warning)'; // yellow: something here is new
|
||||||
|
// NEW SLOT gets its own hue. It shared the amber NEW family while the NEW PFX
|
||||||
|
// marker sits in caution yellow — two different facts, two near-identical
|
||||||
|
// colours in the same cell. Sky cyan, the exact colour the panadapter palette
|
||||||
|
// ships for new-slot (#5AC8FA), so the two views tell one story — and clearly
|
||||||
|
// apart from the POTA green the first attempt (aqua) sat next to.
|
||||||
|
const NEWSLOT = '#5AC8FA';
|
||||||
const WKD = 'var(--info)'; // blue: this callsign is already in the log
|
const WKD = 'var(--info)'; // blue: this callsign is already in the log
|
||||||
|
|
||||||
// FILLING the cell that carries the fact, rather than only tinting its text.
|
// FILLING the cell that carries the fact, rather than only tinting its text.
|
||||||
@@ -190,9 +196,10 @@ function statusColor(s: SpotStatusEntry | undefined): string | null {
|
|||||||
case 'new-band-mode':
|
case 'new-band-mode':
|
||||||
case 'new-band':
|
case 'new-band':
|
||||||
case 'new-mode':
|
case 'new-mode':
|
||||||
case 'new-slot':
|
|
||||||
case 'new-call':
|
case 'new-call':
|
||||||
return NEW;
|
return NEW;
|
||||||
|
case 'new-slot':
|
||||||
|
return NEWSLOT;
|
||||||
default:
|
default:
|
||||||
return s?.worked_call ? WKD : null;
|
return s?.worked_call ? WKD : null;
|
||||||
}
|
}
|
||||||
@@ -336,7 +343,9 @@ const makeColCatalog = (t: TFn): ColEntry[] => [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
group: 'Spot', label: t('clg2.c.pota'), colId: 'pota',
|
group: 'Spot', label: t('clg2.c.pota'), colId: 'pota',
|
||||||
headerName: t('clg2.c.pota'), field: 'pota_ref' as any, width: 92, cellClass: 'font-mono',
|
headerName: t('clg2.c.pota'), width: 92, cellClass: 'font-mono',
|
||||||
|
// Through a valueGetter so the chase switch empties the column live.
|
||||||
|
valueGetter: (p: any) => (chasePota() ? p.data?.pota_ref ?? '' : ''),
|
||||||
defaultVisible: true,
|
defaultVisible: true,
|
||||||
cellStyle: (p: any) => (statusFor(p)?.new_pota
|
cellStyle: (p: any) => (statusFor(p)?.new_pota
|
||||||
? fillStyle(markerColour('new_pota'))
|
? fillStyle(markerColour('new_pota'))
|
||||||
@@ -349,7 +358,8 @@ const makeColCatalog = (t: TFn): ColEntry[] => [
|
|||||||
// which is why the column is off by default rather than an empty column for
|
// which is why the column is off by default rather than an empty column for
|
||||||
// everyone who does not watch summits.
|
// everyone who does not watch summits.
|
||||||
group: 'Spot', label: t('clg2.c.sota'), colId: 'sota',
|
group: 'Spot', label: t('clg2.c.sota'), colId: 'sota',
|
||||||
headerName: t('clg2.c.sota'), field: 'sota_ref' as any, width: 100, cellClass: 'font-mono',
|
headerName: t('clg2.c.sota'), width: 100, cellClass: 'font-mono',
|
||||||
|
valueGetter: (p: any) => (chaseSota() ? p.data?.sota_ref ?? '' : ''),
|
||||||
defaultVisible: false,
|
defaultVisible: false,
|
||||||
cellStyle: () => ({ color: 'var(--success)' }) as any,
|
cellStyle: () => ({ color: 'var(--success)' }) as any,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -4,20 +4,21 @@ import {
|
|||||||
GetKenwoodState, RefreshKenwood, SetKenwoodPower, SetKenwoodAFGain, SetKenwoodTX, TuneKenwoodATU,
|
GetKenwoodState, RefreshKenwood, SetKenwoodPower, SetKenwoodAFGain, SetKenwoodTX, TuneKenwoodATU,
|
||||||
SetKenwoodRFGain, SetKenwoodMicGain, SetKenwoodSquelch, SetKenwoodPreamp, SetKenwoodAtt,
|
SetKenwoodRFGain, SetKenwoodMicGain, SetKenwoodSquelch, SetKenwoodPreamp, SetKenwoodAtt,
|
||||||
SetKenwoodNB, SetKenwoodNR, SetKenwoodAGC, SetKenwoodFilter, SetKenwoodAntenna,
|
SetKenwoodNB, SetKenwoodNR, SetKenwoodAGC, SetKenwoodFilter, SetKenwoodAntenna,
|
||||||
SetKenwoodRIT, SetKenwoodXIT, ClearKenwoodRIT, SetKenwoodKeySpeed, ToggleKenwoodATU, NudgeKenwoodRIT,
|
SetKenwoodRIT, SetKenwoodXIT, ClearKenwoodRIT, SetKenwoodKeySpeed, ToggleKenwoodATU, SetKenwoodRITOffset, SetKenwoodPanelMode,
|
||||||
GetCATState,
|
GetCATState,
|
||||||
} from '../../wailsjs/go/main/App';
|
} from '../../wailsjs/go/main/App';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { useI18n } from '@/lib/i18n';
|
import { useI18n } from '@/lib/i18n';
|
||||||
import { sMeterRST } from '@/lib/rst';
|
import { sMeterRST } from '@/lib/rst';
|
||||||
|
import { ShiftRow } from '@/components/ShiftRow';
|
||||||
import { MeterBar } from '@/components/MeterBar';
|
import { MeterBar } from '@/components/MeterBar';
|
||||||
import { WheelRange } from '@/components/WheelRange';
|
import { WheelRange } from '@/components/WheelRange';
|
||||||
|
|
||||||
type KenwoodState = {
|
type KenwoodState = {
|
||||||
available: boolean; model?: string; elecraft: boolean; mode?: string;
|
available: boolean; model?: string; elecraft: boolean; mode?: string; data_sub?: string;
|
||||||
transmitting: boolean; split: boolean; split_tx_hz?: number;
|
transmitting: boolean; split: boolean; split_tx_hz?: number;
|
||||||
s_meter: number; s_meter_raw: number;
|
s_meter: number; s_meter_raw: number;
|
||||||
power_meter: number; swr: number; swr_raw: number;
|
power_meter: number; power_w?: number; swr: number; swr_raw: number;
|
||||||
rf_power: number; af_gain: number; rf_gain: number; mic_gain: number; squelch: number;
|
rf_power: number; af_gain: number; rf_gain: number; mic_gain: number; squelch: number;
|
||||||
preamp: boolean; att: boolean; nb: boolean; nr: boolean; agc?: string;
|
preamp: boolean; att: boolean; nb: boolean; nr: boolean; agc?: string;
|
||||||
filter_hz: number; antenna: number; rit: boolean; xit: boolean; rit_offset: number; key_speed: number;
|
filter_hz: number; antenna: number; rit: boolean; xit: boolean; rit_offset: number; key_speed: number;
|
||||||
@@ -41,18 +42,22 @@ const ZERO: KenwoodState = {
|
|||||||
// nobody notices are missing.
|
// nobody notices are missing.
|
||||||
const FILTERS = [200, 400, 700, 1000, 1800, 2400, 2800, 4000];
|
const FILTERS = [200, 400, 700, 1000, 1800, 2400, 2800, 4000];
|
||||||
|
|
||||||
// Raw S-meter → S units. The K3 answers 0-21 across S0…S9+60; S9 is taken at
|
// Raw S-meter → S units, CALIBRATED against a real K3 beside its own display
|
||||||
// raw 9 and each step above it as 6 dB. PROVISIONAL, like the rest of the
|
// (2026-08): raw 5 reads S7 on the radio, raw 9 reads S9+20. So S9 sits near
|
||||||
// scaling: the raw value is on screen and in the log, so a real radio settles
|
// raw 6.5 — not 9, which showed everything two S-units low — and each raw step
|
||||||
// it rather than this comment.
|
// above it is worth ~8 dB, shown in the 10 dB steps the K3's own meter uses.
|
||||||
const S9_RAW = 9;
|
// A Kenwood answers 0-30 on the same command and keeps the simple 1-per-raw
|
||||||
const DB_PER_RAW = 6;
|
// scale until someone calibrates one against a real radio too.
|
||||||
function sParts(rawV: number): { s: number; over: number; label: string } {
|
const K3_S9_RAW = 6.5;
|
||||||
if (rawV >= S9_RAW) {
|
const K3_DB_PER_RAW = 8;
|
||||||
const over = Math.max(0, Math.round((rawV - S9_RAW) * DB_PER_RAW));
|
function sParts(rawV: number, elecraft: boolean): { s: number; over: number; label: string } {
|
||||||
|
const s9raw = elecraft ? K3_S9_RAW : 9;
|
||||||
|
if (rawV >= s9raw) {
|
||||||
|
let over = Math.max(0, Math.round((rawV - s9raw) * (elecraft ? K3_DB_PER_RAW : 6)));
|
||||||
|
if (elecraft) over = Math.round(over / 10) * 10;
|
||||||
return { s: 9, over, label: over > 0 ? `S9+${over}` : 'S9' };
|
return { s: 9, over, label: over > 0 ? `S9+${over}` : 'S9' };
|
||||||
}
|
}
|
||||||
const s = Math.max(0, Math.min(9, rawV));
|
const s = Math.max(0, Math.min(9, Math.round(rawV * (elecraft ? 9 / K3_S9_RAW : 1))));
|
||||||
return { s, over: 0, label: `S${s}` };
|
return { s, over: 0, label: `S${s}` };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,9 +94,34 @@ function Toggle({ label, on, off, onClick }: { label: string; on: boolean; off:
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// isDataMode: what the rig reports for MD6 varies — "DATA", or the configured
|
||||||
|
// digital default (FT8…) — so the DATA family is "not one of the native modes".
|
||||||
|
function isDataMode(m?: string): boolean {
|
||||||
|
switch ((m ?? '').toUpperCase()) {
|
||||||
|
case '': case 'CW': case 'USB': case 'LSB': case 'SSB': case 'FM': case 'AM': case 'RTTY':
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
export function ElecraftPanel({ onReportRST }: { onReportRST?: (rst: string) => void }) {
|
export function ElecraftPanel({ onReportRST }: { onReportRST?: (rst: string) => void }) {
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const [st, setSt] = useState<KenwoodState>(ZERO);
|
const [st, setSt] = useState<KenwoodState>(ZERO);
|
||||||
|
// Ctrl+Left/Right shifts the RIT by ±10 Hz while RIT is on — the same
|
||||||
|
// keyboard clarifier the Icom and TCI consoles have, for zero-beating a
|
||||||
|
// caller without touching the mouse.
|
||||||
|
const stRef = useRef(st); stRef.current = st;
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (e: KeyboardEvent) => {
|
||||||
|
if (!e.ctrlKey || (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight')) return;
|
||||||
|
const v = stRef.current;
|
||||||
|
if (!v.available || !v.rit) return;
|
||||||
|
e.preventDefault();
|
||||||
|
SetKenwoodRITOffset((v.rit_offset || 0) + (e.key === 'ArrowRight' ? 10 : -10)).catch(() => {});
|
||||||
|
};
|
||||||
|
window.addEventListener('keydown', onKey);
|
||||||
|
return () => window.removeEventListener('keydown', onKey);
|
||||||
|
}, []);
|
||||||
const [freqHz, setFreqHz] = useState(0);
|
const [freqHz, setFreqHz] = useState(0);
|
||||||
const [err, setErr] = useState('');
|
const [err, setErr] = useState('');
|
||||||
// Optimistic overlay: a slider must follow the finger, not the poll. Dropped
|
// Optimistic overlay: a slider must follow the finger, not the poll. Dropped
|
||||||
@@ -149,6 +179,28 @@ export function ElecraftPanel({ onReportRST }: { onReportRST?: (rst: string) =>
|
|||||||
{freqHz > 0 ? (freqHz / 1e6).toFixed(6) : '—'}
|
{freqHz > 0 ? (freqHz / 1e6).toFixed(6) : '—'}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{/* Mode row. The two DATA buttons are why it exists: MD6 alone keeps
|
||||||
|
whatever submode the last session left, and a K3 "in DATA" with FSK D
|
||||||
|
still armed keys FT8 with no audio. DATA sends MD6+DT0 (DATA A, the
|
||||||
|
soundcard path), RTTY sends MD6+DT2 (FSK D). The active DATA button
|
||||||
|
follows the rig's own DT answer. */}
|
||||||
|
<div className="inline-flex rounded-md border border-border overflow-hidden">
|
||||||
|
{([
|
||||||
|
['CW', 'CW', view.mode === 'CW'],
|
||||||
|
['USB', 'USB', view.mode === 'USB'],
|
||||||
|
['LSB', 'LSB', view.mode === 'LSB'],
|
||||||
|
['DATA', t('k3.modeData'), isDataMode(view.mode) && view.data_sub !== 'FSK D' && view.data_sub !== 'PSK D'],
|
||||||
|
['RTTY', t('k3.modeRtty'), (isDataMode(view.mode) && (view.data_sub === 'FSK D' || view.data_sub === 'PSK D')) || view.mode === 'RTTY'],
|
||||||
|
] as [string, string, boolean][]).map(([cmd, label, on]) => (
|
||||||
|
<button key={cmd} type="button" disabled={off}
|
||||||
|
title={cmd === 'DATA' ? t('k3.modeDataHint') : cmd === 'RTTY' ? t('k3.modeRttyHint') : label}
|
||||||
|
onClick={() => SetKenwoodPanelMode(cmd).catch((e: any) => setErr(String(e?.message ?? e)))}
|
||||||
|
className={cn('px-2.5 py-1.5 text-xs font-bold border-l border-border first:border-l-0',
|
||||||
|
on ? 'bg-primary text-primary-foreground' : 'bg-card text-muted-foreground hover:bg-muted')}>
|
||||||
|
{label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
<button type="button" className="text-[11px] text-muted-foreground hover:text-foreground flex items-center gap-1"
|
<button type="button" className="text-[11px] text-muted-foreground hover:text-foreground flex items-center gap-1"
|
||||||
onClick={() => RefreshKenwood().catch(() => {})} title={t('k3.refreshHint')}>
|
onClick={() => RefreshKenwood().catch(() => {})} title={t('k3.refreshHint')}>
|
||||||
<SlidersHorizontal className="size-3.5" />
|
<SlidersHorizontal className="size-3.5" />
|
||||||
@@ -163,14 +215,15 @@ export function ElecraftPanel({ onReportRST }: { onReportRST?: (rst: string) =>
|
|||||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
|
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
|
||||||
<MeterBar label="S-METER" value={view.transmitting ? 0 : view.s_meter} lo={0} hi={100}
|
<MeterBar label="S-METER" value={view.transmitting ? 0 : view.s_meter} lo={0} hi={100}
|
||||||
accent="#16a34a" segColor={sSegColor}
|
accent="#16a34a" segColor={sSegColor}
|
||||||
display={view.transmitting ? '—' : sParts(view.s_meter_raw).label}
|
display={view.transmitting ? '—' : sParts(view.s_meter_raw, view.elecraft).label}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
if (view.transmitting || !onReportRST) return;
|
if (view.transmitting || !onReportRST) return;
|
||||||
const sp = sParts(view.s_meter_raw);
|
const sp = sParts(view.s_meter_raw, view.elecraft);
|
||||||
onReportRST(sMeterRST(sp.s, sp.over, view.mode));
|
onReportRST(sMeterRST(sp.s, sp.over, view.mode));
|
||||||
}}
|
}}
|
||||||
title={t('k3.sMeterHint', { raw: String(view.s_meter_raw) })} />
|
title={t('k3.sMeterHint', { raw: String(view.s_meter_raw) })} />
|
||||||
<MeterBar label="PWR" value={view.transmitting ? view.power_meter : 0} lo={0} hi={100} accent="#0ea5e9" />
|
<MeterBar label="PWR" value={view.transmitting ? view.power_meter : 0} lo={0} hi={100} accent="#0ea5e9"
|
||||||
|
display={view.transmitting && view.elecraft ? `${view.power_w ?? 0} W` : undefined} />
|
||||||
{/* 0 means "not measured", and it must not render as a perfect 1.0:
|
{/* 0 means "not measured", and it must not render as a perfect 1.0:
|
||||||
a match that looks ideal on an antenna nobody has measured is the one
|
a match that looks ideal on an antenna nobody has measured is the one
|
||||||
reading that can cost a radio. */}
|
reading that can cost a radio. */}
|
||||||
@@ -216,7 +269,7 @@ export function ElecraftPanel({ onReportRST }: { onReportRST?: (rst: string) =>
|
|||||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-x-6 gap-y-2">
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-x-6 gap-y-2">
|
||||||
<label className="flex items-center gap-2 text-xs">
|
<label className="flex items-center gap-2 text-xs">
|
||||||
<span className="w-16 shrink-0 text-muted-foreground">{t('k3.power')}</span>
|
<span className="w-16 shrink-0 text-muted-foreground">{t('k3.power')}</span>
|
||||||
<WheelRange min={0} max={110} step={5} disabled={off}
|
<WheelRange min={0} max={110} step={1} disabled={off}
|
||||||
value={view.rf_power ?? 0}
|
value={view.rf_power ?? 0}
|
||||||
onChange={(n) => put({ rf_power: n }, () => SetKenwoodPower(n))} />
|
onChange={(n) => put({ rf_power: n }, () => SetKenwoodPower(n))} />
|
||||||
<span className="w-12 text-right font-mono tabular-nums">{view.rf_power ?? 0} W</span>
|
<span className="w-12 text-right font-mono tabular-nums">{view.rf_power ?? 0} W</span>
|
||||||
@@ -279,21 +332,18 @@ export function ElecraftPanel({ onReportRST }: { onReportRST?: (rst: string) =>
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* RIT / XIT. Clear zeroes both offsets at once — the radio's own RC,
|
{/* RIT / XIT — the shared ShiftRow, exactly as the Icom and TCI consoles
|
||||||
and what an operator means by "clear it". */}
|
drive theirs: ± / wheel / type, Ctrl+←/→ while RIT is on. The K3 has
|
||||||
|
ONE offset for both, so both rows show it, like the Icom's. */}
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<ShiftRow label="RIT" accent="#8b5cf6" on={view.rit} hz={view.rit_offset || 0} disabled={off}
|
||||||
|
onToggle={() => SetKenwoodRIT(!view.rit).catch(setErrMsg)}
|
||||||
|
onSet={(hz) => SetKenwoodRITOffset(hz).catch(setErrMsg)} />
|
||||||
|
<ShiftRow label="XIT" accent="#f59e0b" on={view.xit} hz={view.rit_offset || 0} disabled={off}
|
||||||
|
onToggle={() => SetKenwoodXIT(!view.xit).catch(setErrMsg)}
|
||||||
|
onSet={(hz) => SetKenwoodRITOffset(hz).catch(setErrMsg)} />
|
||||||
|
</div>
|
||||||
<div className="flex flex-wrap items-center gap-1.5">
|
<div className="flex flex-wrap items-center gap-1.5">
|
||||||
<Toggle label="RIT" on={view.rit} off={off} onClick={() => SetKenwoodRIT(!view.rit).catch(setErrMsg)} />
|
|
||||||
<Toggle label="XIT" on={view.xit} off={off} onClick={() => SetKenwoodXIT(!view.xit).catch(setErrMsg)} />
|
|
||||||
{/* The offset itself. A lit RIT button says the feature is on and
|
|
||||||
nothing about where it has put the receiver. */}
|
|
||||||
{[-100, -10, 10, 100].map((d) => (
|
|
||||||
<Toggle key={d} label={(d > 0 ? '+' : '') + d} on={false} off={off}
|
|
||||||
onClick={() => NudgeKenwoodRIT(d).catch(setErrMsg)} />
|
|
||||||
))}
|
|
||||||
<span className="text-[11px] font-mono tabular-nums text-muted-foreground w-16">
|
|
||||||
{view.rit_offset > 0 ? '+' : ''}{view.rit_offset || 0} Hz
|
|
||||||
</span>
|
|
||||||
<Toggle label={t('k3.clear')} on={false} off={off} onClick={() => ClearKenwoodRIT().catch(setErrMsg)} />
|
|
||||||
{/* Antenna only when the radio answered AN — a K3 without the internal
|
{/* Antenna only when the radio answered AN — a K3 without the internal
|
||||||
ATU has one socket and no switch to offer. */}
|
ATU has one socket and no switch to offer. */}
|
||||||
{view.antenna > 0 && (<>
|
{view.antenna > 0 && (<>
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import { Radio, AudioLines, Mic, Activity, SlidersHorizontal, Antenna, Filter, Power } from 'lucide-react';
|
import { Radio, AudioLines, Mic, Activity, SlidersHorizontal, Antenna, Filter, Power, Volume2, VolumeX } from 'lucide-react';
|
||||||
import {
|
import {
|
||||||
GetIcomState, IcomRefresh,
|
GetIcomState, IcomRefresh,
|
||||||
IcomSetAFGain, IcomSetRFGain, IcomSetNB, IcomSetNBLevel, IcomSetNR, IcomSetNRLevel,
|
IcomSetAFGain, IcomSetRFGain, IcomSetNB, IcomSetNBLevel, IcomSetNR, IcomSetNRLevel,
|
||||||
IcomSetANF, IcomSetAPF, IcomSetAGC, IcomSetPreamp, IcomSetAtt, IcomSetFilter,
|
IcomSetANF, IcomSetAPF, IcomSetAGC, IcomSetPreamp, IcomSetAtt, IcomSetFilter,
|
||||||
IcomSetRFPower, IcomSetMicGain, IcomSetSplit, IcomTune, IcomSetPTT,
|
AudioMonitorActive, AudioStartMonitor, AudioStopMonitor,
|
||||||
IcomSetScope, IcomScopeData, IcomSetScopeMode, IcomSetScopeEdges, GetCATState, SetCATFrequency, SetCATMode,
|
IcomSetRFPower, IcomSetMicGain, IcomSetSplit, IcomTune, IcomSetATU, IcomConsolePTT,
|
||||||
|
GetCATState, SetCATFrequency, SetCATMode,
|
||||||
IcomSetRIT, IcomSetRITOn, IcomSetXITOn,
|
IcomSetRIT, IcomSetRITOn, IcomSetXITOn,
|
||||||
IcomSetAntenna, IcomSetPBTInner, IcomSetPBTOuter, IcomSetManualNotch, IcomSetNotchPos,
|
IcomSetAntenna, IcomSetPBTInner, IcomSetPBTOuter, IcomSetManualNotch, IcomSetNotchPos,
|
||||||
IcomSetSquelch, IcomSetComp, IcomSetCompLevel, IcomSetMonitor, IcomSetMonLevel,
|
IcomSetSquelch, IcomSetComp, IcomSetCompLevel, IcomSetMonitor, IcomSetMonLevel,
|
||||||
@@ -19,7 +20,7 @@ import { ShiftRow } from '@/components/ShiftRow';
|
|||||||
|
|
||||||
type IcomState = {
|
type IcomState = {
|
||||||
available: boolean; model?: string; mode?: string;
|
available: boolean; model?: string; mode?: string;
|
||||||
transmitting: boolean; split: boolean;
|
transmitting: boolean; split: boolean; sub_hz?: number; atu_on?: boolean;
|
||||||
s_meter: number; power_meter: number; swr_meter: number;
|
s_meter: number; power_meter: number; swr_meter: number;
|
||||||
rf_power: number; mic_gain: number;
|
rf_power: number; mic_gain: number;
|
||||||
af_gain: number; rf_gain: number;
|
af_gain: number; rf_gain: number;
|
||||||
@@ -79,17 +80,18 @@ function bandsFor(model?: string): Band[] {
|
|||||||
|
|
||||||
// Mode buttons for the console (like RS-BA1's row). SetCATMode picks USB/LSB for
|
// Mode buttons for the console (like RS-BA1's row). SetCATMode picks USB/LSB for
|
||||||
// SSB by frequency and the rig's data variant for digital modes.
|
// SSB by frequency and the rig's data variant for digital modes.
|
||||||
const MODES = ['SSB', 'CW', 'RTTY', 'PSK', 'AM', 'FM'];
|
const MODES = ['SSB', 'CW', 'RTTY', 'PSK', 'AM', 'FM', 'DATA'];
|
||||||
|
|
||||||
// Attenuator steps are MODEL-dependent even though the CI-V command (0x11) is the
|
// Attenuator steps are MODEL-dependent even though the CI-V command (0x11) is the
|
||||||
// same: the value byte is the dB. The IC-7610 (and 7700/7800/7851) have a 6/12/18
|
// same: the value byte is the dB. The IC-7610 (and 7700/7800/7851) have a 6/12/18
|
||||||
// dB stepped attenuator; the IC-7300/705/7100 have a single 20 dB attenuator; the
|
// dB stepped attenuator, and the IC-7760 the same (confirmed on a real one); the
|
||||||
|
// IC-7300/705/7100 have a single 20 dB attenuator; the
|
||||||
// IC-9700 a single 10 dB. Offering the wrong steps = a dead button (the rig NAKs
|
// IC-9700 a single 10 dB. Offering the wrong steps = a dead button (the rig NAKs
|
||||||
// e.g. 6 dB on a 7300). Default to the common single 20 dB for unknown models.
|
// e.g. 6 dB on a 7300). Default to the common single 20 dB for unknown models.
|
||||||
function attOptions(model?: string): { v: string; l: string }[] {
|
function attOptions(model?: string): { v: string; l: string }[] {
|
||||||
const m = (model ?? '').toUpperCase();
|
const m = (model ?? '').toUpperCase();
|
||||||
const OFF = { v: '0', l: 'OFF' };
|
const OFF = { v: '0', l: 'OFF' };
|
||||||
if (/(7610|7700|7800|7850|7851)/.test(m)) {
|
if (/(7610|7700|7760|7800|7850|7851)/.test(m)) {
|
||||||
return [OFF, { v: '6', l: '6dB' }, { v: '12', l: '12dB' }, { v: '18', l: '18dB' }];
|
return [OFF, { v: '6', l: '6dB' }, { v: '12', l: '12dB' }, { v: '18', l: '18dB' }];
|
||||||
}
|
}
|
||||||
if (m.includes('9700')) return [OFF, { v: '10', l: '10dB' }];
|
if (m.includes('9700')) return [OFF, { v: '10', l: '10dB' }];
|
||||||
@@ -128,9 +130,38 @@ function fmtVFO(hz?: number): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// modeMatches marks a mode button active, folding the rig's USB/LSB into SSB.
|
// modeMatches marks a mode button active, folding the rig's USB/LSB into SSB.
|
||||||
|
// icomWatts turns the backend's 0-100 meter percentage back into watts on the
|
||||||
|
// IC-7760's own meter face. The backend value is linear in the RAW meter byte
|
||||||
|
// (0-255 → 0-100), but Icom's calibration is not: raw 143 is half deflection
|
||||||
|
// and raw 213 is full scale. On a real 7760 a measured 100 W sits at half
|
||||||
|
// deflection of the 250 W face — the linear ×2.5 first tried showed 140 W for
|
||||||
|
// it. Below half scale watts run 0→100, above it 100→250.
|
||||||
|
// The anchors are MEASURED on the real radio, not derived: a known 50 W read
|
||||||
|
// raw ≈89 and a known 100 W read raw 143 (Icom's documented half-deflection),
|
||||||
|
// with raw 213 = full scale = 250 W. The face is not linear in watts at the
|
||||||
|
// bottom — a two-segment guess showed 50 W as 62 — so watts interpolate
|
||||||
|
// between the measured anchors, and a new measurement just adds a row.
|
||||||
|
// Third measured anchor (2026-08-30): a real 200 W read full deflection —
|
||||||
|
// raw 213 is 200 W on this rig, not the 250 the printed face suggests.
|
||||||
|
const ICOM_7760_PO: [number, number][] = [[0, 0], [89, 50], [143, 100], [213, 200]];
|
||||||
|
function icomWatts(pct: number): { w: number; defl: number } {
|
||||||
|
const raw = Math.max(0, pct * 2.55);
|
||||||
|
const defl = raw <= 143 ? (raw / 143) * 50 : Math.min(100, 50 + ((raw - 143) / 70) * 50);
|
||||||
|
let w = 200;
|
||||||
|
for (let i = 1; i < ICOM_7760_PO.length; i++) {
|
||||||
|
const [r0, w0] = ICOM_7760_PO[i - 1], [r1, w1] = ICOM_7760_PO[i];
|
||||||
|
if (raw <= r1) { w = w0 + ((raw - r0) / (r1 - r0)) * (w1 - w0); break; }
|
||||||
|
}
|
||||||
|
return { w: Math.round(w), defl };
|
||||||
|
}
|
||||||
|
|
||||||
function modeMatches(btn: string, cur?: string): boolean {
|
function modeMatches(btn: string, cur?: string): boolean {
|
||||||
if (!cur) return false;
|
if (!cur) return false;
|
||||||
if (btn === 'SSB') return cur === 'SSB' || cur === 'USB' || cur === 'LSB';
|
if (btn === 'SSB') return cur === 'SSB' || cur === 'USB' || cur === 'LSB';
|
||||||
|
// The backend surfaces USB-D as the operator's digital default (FT8…), or as
|
||||||
|
// plain DATA — either way it is the DATA button that should light.
|
||||||
|
if (btn === 'DATA') return ['DATA', 'FT8', 'FT4', 'JS8', 'JT65', 'JT9', 'MFSK', 'OLIVIA'].includes(cur);
|
||||||
|
if (btn === 'PSK') return cur === 'PSK' || cur === 'PSK31';
|
||||||
return btn === cur;
|
return btn === cur;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -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="flex-1 h-2.5 rounded-full bg-muted/60 overflow-hidden">
|
||||||
<div className="h-full rounded-full transition-[width] duration-150" style={{ width: `${v}%`, background: accent }} />
|
<div className="h-full rounded-full transition-[width] duration-150" style={{ width: `${v}%`, background: accent }} />
|
||||||
</div>
|
</div>
|
||||||
<span className="w-10 text-right text-[11px] font-mono tabular-nums text-muted-foreground">{scale ?? v}</span>
|
<span className="w-14 shrink-0 whitespace-nowrap text-right text-[11px] font-mono tabular-nums text-muted-foreground">{scale ?? v}</span>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
if (onClick) {
|
if (onClick) {
|
||||||
return <button type="button" onClick={onClick} title={title} className="flex items-center gap-2 w-full rounded hover:bg-muted/50 -mx-1 px-1 py-0.5">{body}</button>;
|
return <button type="button" onClick={onClick} title={title} className="flex items-center gap-2 w-full rounded cursor-pointer hover:bg-muted/50 -mx-1 px-1 py-0.5">{body}</button>;
|
||||||
}
|
}
|
||||||
return <div className="flex items-center gap-2">{body}</div>;
|
return <div className="flex items-center gap-2">{body}</div>;
|
||||||
}
|
}
|
||||||
@@ -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
|
// sParts turns the raw 0-100 S-meter into S-unit + dB-over-S9 (S9 ≈ 47% on the
|
||||||
// CI-V 0-255 scale, +60 dB near full scale). Used for both the display label and
|
// CI-V 0-255 scale, +60 dB near full scale). Used for both the display label and
|
||||||
// the RST-tx value on click.
|
// the RST-tx value on click.
|
||||||
|
// Green to S9, amber through +20, red above — the Elecraft console's scale.
|
||||||
|
function sSegColor(frac: number) {
|
||||||
|
if (frac > 0.78) return '#dc2626';
|
||||||
|
if (frac > 0.55) return '#f59e0b';
|
||||||
|
return '#16a34a';
|
||||||
|
}
|
||||||
|
|
||||||
function sParts(v: number): { s: number; over: number; label: string } {
|
function sParts(v: number): { s: number; over: number; label: string } {
|
||||||
if (v >= 47) {
|
if (v >= 47) {
|
||||||
const over = Math.max(0, Math.round((v - 47) * 60 / 47));
|
const over = Math.max(0, Math.round((v - 47) * 60 / 47));
|
||||||
@@ -280,294 +318,31 @@ function wfColor(v: number): [number, number, number] {
|
|||||||
return WF_STOPS[WF_STOPS.length - 1][1];
|
return WF_STOPS[WF_STOPS.length - 1][1];
|
||||||
}
|
}
|
||||||
|
|
||||||
// ScopePanadapter — enables the rig's spectrum-scope stream and draws the
|
// The spectrum scope is GONE, deliberately. Every Icom streams its waveform
|
||||||
// reassembled sweep as a modern SDR panadapter: a glowing filled spectrum trace
|
// differently — the IC-7851 controls a scope it never streams, and a real
|
||||||
// on top and a scrolling colour waterfall below. Amplitudes are raw rig scale
|
// IC-7760 stops answering CI-V altogether a few frames in, taking CAT and
|
||||||
// (~0-160), normalised to the tallest recent peak so the trace fills the height.
|
// audio down with it — and chasing a per-model frame layout for a decoration
|
||||||
function ScopePanadapter() {
|
// is not worth a console that drops the link. The radio has a better scope
|
||||||
const { t } = useI18n();
|
// on its own front panel.
|
||||||
const [on, setOn] = useState(false);
|
|
||||||
const [fixed, setFixed] = useState(true);
|
|
||||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
|
||||||
const wfRef = useRef<HTMLCanvasElement>(null); // waterfall
|
|
||||||
const peakRef = useRef(160); // running amplitude ceiling for auto-scale
|
|
||||||
const holdRef = useRef<number[]>([]); // per-bin peak-hold line
|
|
||||||
// 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 ◀/▶)
|
|
||||||
|
|
||||||
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 } = {}) {
|
export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (rst: string) => void; isNetwork?: boolean } = {}) {
|
||||||
|
// The speaker toggle lives HERE, next to ON/OFF, because that is where the
|
||||||
|
// operator is looking — burying "stop listening" behind Settings → Audio
|
||||||
|
// meant a trip through two panels to mute a radio sitting in the same room.
|
||||||
|
const [listening, setListening] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isNetwork) return;
|
||||||
|
let alive = true;
|
||||||
|
const ask = () => AudioMonitorActive().then((v) => { if (alive) setListening(!!v); }).catch(() => {});
|
||||||
|
ask();
|
||||||
|
const id = window.setInterval(ask, 2000);
|
||||||
|
return () => { alive = false; window.clearInterval(id); };
|
||||||
|
}, [isNetwork]);
|
||||||
|
const toggleListening = () => {
|
||||||
|
const next = !listening;
|
||||||
|
setListening(next);
|
||||||
|
(next ? AudioStartMonitor() : Promise.resolve(AudioStopMonitor())).catch(() => setListening(!next));
|
||||||
|
};
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const [st, setSt] = useState<IcomState>(ZERO);
|
const [st, setSt] = useState<IcomState>(ZERO);
|
||||||
const [cat, setCat] = useState<any>(null); // RigState (freq/mode/split) for the VFO display
|
const [cat, setCat] = useState<any>(null); // RigState (freq/mode/split) for the VFO display
|
||||||
@@ -603,7 +378,9 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
|
|||||||
const toggleMox = () => {
|
const toggleMox = () => {
|
||||||
const next = !txRef.current;
|
const next = !txRef.current;
|
||||||
txRef.current = next;
|
txRef.current = next;
|
||||||
set({ transmitting: next }, () => IcomSetPTT(next));
|
// Through the console binding: on a network station the PC microphone
|
||||||
|
// rides with the PTT (silence otherwise); on USB it keys and nothing more.
|
||||||
|
set({ transmitting: next }, () => IcomConsolePTT(next));
|
||||||
};
|
};
|
||||||
|
|
||||||
const tune = async () => {
|
const tune = async () => {
|
||||||
@@ -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).
|
// other is TX (freq_hz); otherwise there's a single VFO (freq_hz).
|
||||||
const split = !!cat?.split;
|
const split = !!cat?.split;
|
||||||
const mainHz: number = split ? (cat?.freq_rx_hz || 0) : (cat?.freq_hz || 0);
|
const mainHz: number = split ? (cat?.freq_rx_hz || 0) : (cat?.freq_hz || 0);
|
||||||
const subHz: number = split ? (cat?.freq_hz || 0) : 0;
|
// The sub receiver's dial is worth seeing whether or not split is on —
|
||||||
const curMode: string = cat?.mode || st.mode || '';
|
// in split the CAT state's TX freq is the authority, otherwise the panel's
|
||||||
|
// own sub_hz read.
|
||||||
|
const subHz: number = split ? (cat?.freq_hz || 0) : (st.sub_hz || 0);
|
||||||
|
// The panel's own mode first: it carries the sideband (USB/LSB) where the
|
||||||
|
// CAT state folds both into ADIF's SSB.
|
||||||
|
const curMode: string = st.mode || cat?.mode || '';
|
||||||
// Mode-dependent controls: VOX / speech-comp / mic are voice-only (hidden on
|
// Mode-dependent controls: VOX / speech-comp / mic are voice-only (hidden on
|
||||||
// CW and data); APF (audio peak filter) is CW-only. Fold USB/LSB into phone.
|
// CW and data); APF (audio peak filter) is CW-only. Fold USB/LSB into phone.
|
||||||
const um = curMode.toUpperCase();
|
const um = curMode.toUpperCase();
|
||||||
@@ -676,6 +458,14 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
|
|||||||
rig's LAN server stays alive in standby, so both work. */}
|
rig's LAN server stays alive in standby, so both work. */}
|
||||||
{isNetwork && (
|
{isNetwork && (
|
||||||
<>
|
<>
|
||||||
|
<button type="button" onClick={toggleListening}
|
||||||
|
title={listening ? t('icmp.speakerOffHint') : t('icmp.speakerOnHint')}
|
||||||
|
className={cn('inline-flex items-center gap-1 rounded-md border px-2 py-1 text-xs font-bold',
|
||||||
|
listening
|
||||||
|
? 'border-primary/60 bg-primary/10 text-primary hover:bg-primary/20'
|
||||||
|
: 'border-border bg-card text-muted-foreground hover:bg-muted')}>
|
||||||
|
{listening ? <Volume2 className="size-3.5" /> : <VolumeX className="size-3.5" />}
|
||||||
|
</button>
|
||||||
<button type="button" onClick={() => IcomSetPower(true).catch(() => {})} title={t('icmp.powerOnHint')}
|
<button type="button" onClick={() => IcomSetPower(true).catch(() => {})} title={t('icmp.powerOnHint')}
|
||||||
className="inline-flex items-center gap-1 rounded-md border border-success/60 bg-success/10 px-2 py-1 text-xs font-bold text-success hover:bg-success/20">
|
className="inline-flex items-center gap-1 rounded-md border border-success/60 bg-success/10 px-2 py-1 text-xs font-bold text-success hover:bg-success/20">
|
||||||
<Power className="size-3.5" /> ON
|
<Power className="size-3.5" /> ON
|
||||||
@@ -717,7 +507,7 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{/* Mode selector row (RS-BA1's SSB/CW/RTTY/PSK/AM/FM). */}
|
{/* Mode selector row (RS-BA1's SSB/CW/RTTY/PSK/AM/FM). */}
|
||||||
<div className="grid grid-cols-6 border-t border-border/60 divide-x divide-border/60">
|
<div className="grid grid-cols-7 border-t border-border/60 divide-x divide-border/60">
|
||||||
{MODES.map((m) => {
|
{MODES.map((m) => {
|
||||||
const on = modeMatches(m, curMode);
|
const on = modeMatches(m, curMode);
|
||||||
return (
|
return (
|
||||||
@@ -731,20 +521,28 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Live meters — always visible: S (RX, click → RST), Po in watts, SWR. */}
|
{/* Live meters — the SAME LED MeterBar every other console uses (Flex,
|
||||||
<div className="rounded-xl border border-border bg-card px-3 py-2.5 shadow-sm grid grid-cols-1 sm:grid-cols-3 gap-x-5 gap-y-2">
|
Elecraft, the amp cards): one instrument look across the app, per the
|
||||||
|
operator's "les consoles doivent se ressembler". S is clickable → RST. */}
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
|
||||||
{(() => { const sp = sParts(st.s_meter); return (
|
{(() => { const sp = sParts(st.s_meter); return (
|
||||||
<Meter label="S" value={st.s_meter} accent="#22c55e" scale={sp.label}
|
<MeterBar label="S-METER" value={st.transmitting ? 0 : st.s_meter} lo={0} hi={100}
|
||||||
|
accent="#16a34a" segColor={sSegColor}
|
||||||
|
display={st.transmitting ? '—' : sp.label}
|
||||||
title={onReportRST ? t('rst.clickToFill') : undefined}
|
title={onReportRST ? t('rst.clickToFill') : undefined}
|
||||||
onClick={onReportRST ? () => onReportRST(sMeterRST(sp.s, sp.over, st.mode)) : undefined} />
|
onClick={onReportRST ? () => { if (!st.transmitting) onReportRST(sMeterRST(sp.s, sp.over, st.mode)); } : undefined} />
|
||||||
); })()}
|
); })()}
|
||||||
<Meter label="Po" value={st.power_meter} accent="#ef4444" scale={`${st.power_meter} W`} />
|
{(() => {
|
||||||
<Meter label="SWR" value={st.swr_meter} accent="#f59e0b" scale={st.swr_meter > 0 ? `${(1 + st.swr_meter / 33.3).toFixed(1)}` : '1.0'} />
|
if ((st.model ?? '').includes('7760')) {
|
||||||
|
const { w, defl } = icomWatts(st.power_meter);
|
||||||
|
return <MeterBar label="PWR" value={defl} lo={0} hi={100} accent="#0ea5e9" display={`${w} W`} />;
|
||||||
|
}
|
||||||
|
return <MeterBar label="PWR" value={st.power_meter} lo={0} hi={100} accent="#0ea5e9" display={`${st.power_meter} W`} />;
|
||||||
|
})()}
|
||||||
|
<MeterBar label="SWR" value={st.swr_meter > 0 ? 1 + st.swr_meter / 33.3 : 0} lo={1} hi={4} accent="#f59e0b"
|
||||||
|
display={st.swr_meter > 0 ? (1 + st.swr_meter / 33.3).toFixed(1) : '—'} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Spectrum panadapter (full width). */}
|
|
||||||
<ScopePanadapter />
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
|
||||||
{/* Band buttons + antenna selection. */}
|
{/* Band buttons + antenna selection. */}
|
||||||
<Card icon={Antenna} title={t('icmp.bandsAntenna')} accent="#0891b2">
|
<Card icon={Antenna} title={t('icmp.bandsAntenna')} accent="#0891b2">
|
||||||
@@ -784,7 +582,11 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
|
|||||||
<Card icon={Mic} title={t('icmp.transmit')} accent="#ef4444">
|
<Card icon={Mic} title={t('icmp.transmit')} accent="#ef4444">
|
||||||
<Row label={t('icmp.power')}>
|
<Row label={t('icmp.power')}>
|
||||||
<Slider value={st.rf_power} accent="#ef4444" onChange={(v) => set({ rf_power: v }, () => IcomSetRFPower(v))} />
|
<Slider value={st.rf_power} accent="#ef4444" onChange={(v) => set({ rf_power: v }, () => IcomSetRFPower(v))} />
|
||||||
<span className="w-8 text-right text-xs font-mono tabular-nums text-muted-foreground">{st.rf_power}</span>
|
{/* PC is a percentage of the rig's rated power; on a 200 W rig the
|
||||||
|
operator thinks in watts, so say it in watts there. */}
|
||||||
|
<span className="w-12 text-right text-xs font-mono tabular-nums text-muted-foreground">
|
||||||
|
{(st.model ?? '').includes('7760') ? `${st.rf_power * 2} W` : st.rf_power}
|
||||||
|
</span>
|
||||||
</Row>
|
</Row>
|
||||||
{isPhone && (
|
{isPhone && (
|
||||||
<Row label={t('icmp.mic')}>
|
<Row label={t('icmp.mic')}>
|
||||||
@@ -799,6 +601,9 @@ export function IcomPanel({ onReportRST, isNetwork = false }: { onReportRST?: (r
|
|||||||
{tx ? 'TX ON' : 'MOX'}
|
{tx ? 'TX ON' : 'MOX'}
|
||||||
</button>
|
</button>
|
||||||
<Chip label="SPLIT" on={st.split} onClick={() => set({ split: !st.split }, () => IcomSetSplit(!st.split))} />
|
<Chip label="SPLIT" on={st.split} onClick={() => set({ split: !st.split }, () => IcomSetSplit(!st.split))} />
|
||||||
|
{/* Tuner IN/OUT — TUNE below starts a cycle but could never take the
|
||||||
|
tuner back out of line. */}
|
||||||
|
<Chip label="ATU" on={!!st.atu_on} onClick={() => set({ atu_on: !st.atu_on } as any, () => IcomSetATU(!st.atu_on))} />
|
||||||
<button type="button" onClick={tune} disabled={tuning}
|
<button type="button" onClick={tune} disabled={tuning}
|
||||||
className={cn('w-14 shrink-0 px-2 py-1.5 rounded-md text-[11px] font-bold border transition-colors',
|
className={cn('w-14 shrink-0 px-2 py-1.5 rounded-md text-[11px] font-bold border transition-colors',
|
||||||
tuning ? 'bg-warning border-warning text-warning-foreground animate-pulse' : 'bg-card text-foreground border-border hover:bg-muted')}>
|
tuning ? 'bg-warning border-warning text-warning-foreground animate-pulse' : 'bg-card text-foreground border-border hover:bg-muted')}>
|
||||||
|
|||||||
@@ -370,8 +370,14 @@ export function WorldMap({ fromGrid, toGrid, fromLabel, toLabel, beamAzimuths, b
|
|||||||
|
|
||||||
if (autoZoom) {
|
if (autoZoom) {
|
||||||
if (from && to && arcPts) {
|
if (from && to && arcPts) {
|
||||||
const bounds = L.latLngBounds([[from.lat, from.lon], [to.lat, to.lon]]);
|
// Latitudes clamped to Mercator's edge (±85°): the arc to a polar
|
||||||
arcPts.forEach((p) => bounds.extend(p as L.LatLngExpression));
|
// entity (Franz Josef Land) peaks near 88°N, and fitting the raw
|
||||||
|
// points framed a band of tile-less white above the top of the world.
|
||||||
|
// The line itself still draws to wherever it goes — only the CAMERA
|
||||||
|
// stays where there is a map to show.
|
||||||
|
const clamp = (lat: number) => Math.max(-85, Math.min(85, lat));
|
||||||
|
const bounds = L.latLngBounds([[clamp(from.lat), from.lon], [clamp(to.lat), to.lon]]);
|
||||||
|
arcPts.forEach((p) => bounds.extend([clamp(p[0]), p[1]] as L.LatLngExpression));
|
||||||
wm.fitBounds(bounds, { padding: [30, 30], maxZoom: 6 });
|
wm.fitBounds(bounds, { padding: [30, 30], maxZoom: 6 });
|
||||||
} else if (to) {
|
} else if (to) {
|
||||||
wm.setView([to.lat, to.lon], 3);
|
wm.setView([to.lat, to.lon], 3);
|
||||||
|
|||||||
@@ -9,7 +9,8 @@ import {
|
|||||||
import {
|
import {
|
||||||
GetLookupSettings, SaveLookupSettings, ClearLookupCache, TestLookupProvider,
|
GetLookupSettings, SaveLookupSettings, ClearLookupCache, TestLookupProvider,
|
||||||
GetListsSettings, SaveListsSettings,
|
GetListsSettings, SaveListsSettings,
|
||||||
GetCATSettings, SaveCATSettings, GetRadios, SaveRadios, SetActiveRadio, DiscoverFlexRadios,
|
GetCATSettings, SaveCATSettings, GetRadios, SaveRadios, SetActiveRadio, ActiveRadioID, DiscoverFlexRadios,
|
||||||
|
GetAudioMonitorPref,
|
||||||
ListProfiles, GetActiveProfile, SaveProfile, DeleteProfile, ActivateProfile, DuplicateProfile,
|
ListProfiles, GetActiveProfile, SaveProfile, DeleteProfile, ActivateProfile, DuplicateProfile,
|
||||||
GetRotators, SaveRotators, TestRotatorDevice, RotatorPark, RotatorStop,
|
GetRotators, SaveRotators, TestRotatorDevice, RotatorPark, RotatorStop,
|
||||||
GetRotorPresets, SaveRotorPresets, ResetRotorPresets,
|
GetRotorPresets, SaveRotorPresets, ResetRotorPresets,
|
||||||
@@ -81,6 +82,7 @@ import {
|
|||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { writeUiPref } from '@/lib/uiPref';
|
import { writeUiPref } from '@/lib/uiPref';
|
||||||
import { setUseMiles } from '@/lib/units';
|
import { setUseMiles } from '@/lib/units';
|
||||||
|
import { iaruRegion, setIaruRegion, type IaruRegion } from '@/lib/bandplan';
|
||||||
import { getDateFormat, setDateFormat, type DateFormat } from '@/lib/dateFormat';
|
import { getDateFormat, setDateFormat, type DateFormat } from '@/lib/dateFormat';
|
||||||
import { useI18n, FlagGB, FlagFR, type Lang } from '@/lib/i18n';
|
import { useI18n, FlagGB, FlagFR, type Lang } from '@/lib/i18n';
|
||||||
import { useTheme, CONCRETE_THEMES, type ThemeChoice } from '@/lib/theme';
|
import { useTheme, CONCRETE_THEMES, type ThemeChoice } from '@/lib/theme';
|
||||||
@@ -689,8 +691,7 @@ function TelemetryToggle() {
|
|||||||
<label className="flex items-center gap-2 text-sm cursor-pointer">
|
<label className="flex items-center gap-2 text-sm cursor-pointer">
|
||||||
<Checkbox checked={on} disabled={!loaded}
|
<Checkbox checked={on} disabled={!loaded}
|
||||||
onCheckedChange={(c) => { const v = !!c; setOn(v); SetTelemetryEnabled(v).catch(() => {}); }} />
|
onCheckedChange={(c) => { const v = !!c; setOn(v); SetTelemetryEnabled(v).catch(() => {}); }} />
|
||||||
{t('settings.telemetry')}
|
<span title={t('settings.telemetryHint')}>{t('settings.telemetry')}</span>
|
||||||
<span className="text-xs text-muted-foreground">({t('settings.telemetryHint')})</span>
|
|
||||||
</label>
|
</label>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1086,7 +1087,7 @@ function RelayAutoPanel() {
|
|||||||
// panes. The first two are the view; the third and fourth can be left empty, and
|
// panes. The first two are the view; the third and fourth can be left empty, and
|
||||||
// an empty one is not drawn at all. Per-profile (stored via SetUIPref, which is
|
// an empty one is not drawn at all. Per-profile (stored via SetUIPref, which is
|
||||||
// profile-prefixed). Self-contained so it owns its async-loaded state.
|
// profile-prefixed). Self-contained so it owns its async-loaded state.
|
||||||
const MAIN_PANE_VALUES = ['map1', 'map2', 'cluster', 'worked', 'recent', 'netcontrol', 'decodes'];
|
const MAIN_PANE_VALUES = ['map1', 'map2', 'cluster', 'worked', 'recent', 'netcontrol', 'decodes', 'watchlist'];
|
||||||
const PANE_NONE = 'none';
|
const PANE_NONE = 'none';
|
||||||
function MainViewPanes({ onChanged, flexAvailable, icomAvailable, yaesuAvailable, elecraftAvailable, tciAvailable }: { onChanged?: (side: 'left' | 'right' | 'p3' | 'p4' | 'layout', value: string) => void; flexAvailable?: boolean; icomAvailable?: boolean; yaesuAvailable?: boolean; elecraftAvailable?: boolean; tciAvailable?: boolean }) {
|
function MainViewPanes({ onChanged, flexAvailable, icomAvailable, yaesuAvailable, elecraftAvailable, tciAvailable }: { onChanged?: (side: 'left' | 'right' | 'p3' | 'p4' | 'layout', value: string) => void; flexAvailable?: boolean; icomAvailable?: boolean; yaesuAvailable?: boolean; elecraftAvailable?: boolean; tciAvailable?: boolean }) {
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
@@ -1503,6 +1504,7 @@ const ICOM_MODELS: { name: string; addr: number }[] = [
|
|||||||
{ name: 'IC-7600', addr: 0x7A },
|
{ name: 'IC-7600', addr: 0x7A },
|
||||||
{ name: 'IC-7610', addr: 0x98 },
|
{ name: 'IC-7610', addr: 0x98 },
|
||||||
{ name: 'IC-7700', addr: 0x74 },
|
{ name: 'IC-7700', addr: 0x74 },
|
||||||
|
{ name: 'IC-7760', addr: 0xB2 },
|
||||||
{ name: 'IC-7800', addr: 0x6A },
|
{ name: 'IC-7800', addr: 0x6A },
|
||||||
{ name: 'IC-7851', addr: 0x8E },
|
{ name: 'IC-7851', addr: 0x8E },
|
||||||
{ name: 'IC-9100', addr: 0x7C },
|
{ name: 'IC-9100', addr: 0x7C },
|
||||||
@@ -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
|
// 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.
|
// — and the list is what makes switching possible without touching profiles.
|
||||||
const [radios, setRadios] = useState<any[]>([]);
|
const [radios, setRadios] = useState<any[]>([]);
|
||||||
|
const [listenPref, setListenPref] = useState(true);
|
||||||
const [activeRadio, setActiveRadioId] = useState('');
|
const [activeRadio, setActiveRadioId] = useState('');
|
||||||
const [radioBusy, setRadioBusy] = useState(false);
|
const [radioBusy, setRadioBusy] = useState(false);
|
||||||
const [catCfg, setCatCfg] = useState<CATSettings>({
|
const [catCfg, setCatCfg] = useState<CATSettings>({
|
||||||
@@ -1749,6 +1752,7 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
|
|||||||
const [lookupOnBlur, setLookupOnBlur] = useState(() => localStorage.getItem('opslog.lookupOnBlur') === '1');
|
const [lookupOnBlur, setLookupOnBlur] = useState(() => localStorage.getItem('opslog.lookupOnBlur') === '1');
|
||||||
const [groupDigital, setGroupDigital] = useState(() => localStorage.getItem('opslog.groupDigitalSlots') === '1');
|
const [groupDigital, setGroupDigital] = useState(() => localStorage.getItem('opslog.groupDigitalSlots') === '1');
|
||||||
const [milesUnit, setMilesUnit] = useState(() => localStorage.getItem('opslog.distanceMiles') === '1');
|
const [milesUnit, setMilesUnit] = useState(() => localStorage.getItem('opslog.distanceMiles') === '1');
|
||||||
|
const [region, setRegion] = useState<IaruRegion>(() => iaruRegion());
|
||||||
const [clusterWorkedSameSlot, setClusterWorkedSameSlot] = useState(() => localStorage.getItem('opslog.clusterWorkedSameSlot') === '1');
|
const [clusterWorkedSameSlot, setClusterWorkedSameSlot] = useState(() => localStorage.getItem('opslog.clusterWorkedSameSlot') === '1');
|
||||||
// Declared HERE and not in ClusterPanel: that renderer is called as a plain
|
// Declared HERE and not in ClusterPanel: that renderer is called as a plain
|
||||||
// function by the PANELS map, so it must stay hooks-free.
|
// function by the PANELS map, so it must stay hooks-free.
|
||||||
@@ -2067,6 +2071,8 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
|
|||||||
try { await SaveGridScopeSettings(next); } catch { /* the panel keeps the choice either way */ }
|
try { await SaveGridScopeSettings(next); } catch { /* the panel keeps the choice either way */ }
|
||||||
};
|
};
|
||||||
const [chaseGrids, setChaseGrids] = useState(false);
|
const [chaseGrids, setChaseGrids] = useState(false);
|
||||||
|
const [chasePotaOn, setChasePotaOn] = useState(() => localStorage.getItem('opslog.chasePota') !== '0');
|
||||||
|
const [chaseSotaOn, setChaseSotaOn] = useState(() => localStorage.getItem('opslog.chaseSota') !== '0');
|
||||||
const [chaseNew, setChaseNew] = useState(false);
|
const [chaseNew, setChaseNew] = useState(false);
|
||||||
const [spotTTL, setSpotTTL] = useState(0);
|
const [spotTTL, setSpotTTL] = useState(0);
|
||||||
const [spotTTLText, setSpotTTLText] = useState('0');
|
const [spotTTLText, setSpotTTLText] = useState('0');
|
||||||
@@ -2200,10 +2206,17 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
|
|||||||
// buttons. See rotorPresetsLoaded for the belt to this brace.
|
// buttons. See rotorPresetsLoaded for the belt to this brace.
|
||||||
try { setRotorPresets((((await GetRotorPresets()) ?? []) as any)); setRotorPresetsLoaded(true); } catch {}
|
try { setRotorPresets((((await GetRotorPresets()) ?? []) as any)); setRotorPresetsLoaded(true); } catch {}
|
||||||
try {
|
try {
|
||||||
|
try { setListenPref(!!(await GetAudioMonitorPref())); } catch {}
|
||||||
const rl: any = await GetRadios();
|
const rl: any = await GetRadios();
|
||||||
setRadios(rl ?? []);
|
setRadios(rl ?? []);
|
||||||
const act = (rl ?? []).find((r: any) => r.active) ?? (rl ?? [])[0];
|
// The backend is the only one who knows which radio is on the air —
|
||||||
setActiveRadioId(act?.id ?? '');
|
// 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 */ }
|
} catch { /* one radio, never listed — the panel works as it always did */ }
|
||||||
try { setUltrabeam(await GetUltrabeamSettings() as any); } catch {}
|
try { setUltrabeam(await GetUltrabeamSettings() as any); } catch {}
|
||||||
try { setAntgenius(await GetAntGeniusSettings() as any); } catch {}
|
try { setAntgenius(await GetAntGeniusSettings() as any); } catch {}
|
||||||
@@ -3616,6 +3629,22 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
|
|||||||
<span className="block text-[11px] text-muted-foreground">{t('cat.icomNetAudioHint')}</span>
|
<span className="block text-[11px] text-muted-foreground">{t('cat.icomNetAudioHint')}</span>
|
||||||
</span>
|
</span>
|
||||||
</label>
|
</label>
|
||||||
|
{!!(catCfg as any).icom_net_audio && (
|
||||||
|
<label className="col-span-2 flex items-start gap-2 text-sm cursor-pointer pl-6">
|
||||||
|
{/* The speaker choice, right where the stream is enabled. Same
|
||||||
|
remembered preference as the console's speaker button —
|
||||||
|
applied immediately, no save needed. */}
|
||||||
|
<Checkbox checked={listenPref}
|
||||||
|
onCheckedChange={(c) => {
|
||||||
|
setListenPref(!!c);
|
||||||
|
(c ? AudioStartMonitor() : Promise.resolve(AudioStopMonitor())).catch(() => setListenPref(!c));
|
||||||
|
}} />
|
||||||
|
<span>
|
||||||
|
{t('cat.icomNetListen')}
|
||||||
|
<span className="block text-[11px] text-muted-foreground">{t('cat.icomNetListenHint')}</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{catCfg.backend === 'tci' && (
|
{catCfg.backend === 'tci' && (
|
||||||
@@ -4883,7 +4912,7 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
|
|||||||
|
|
||||||
{wk.engine === 'icom' ? (
|
{wk.engine === 'icom' ? (
|
||||||
<>
|
<>
|
||||||
{(!catCfg.enabled || catCfg.backend !== 'icom') && (
|
{(!catCfg.enabled || (catCfg.backend !== 'icom' && catCfg.backend !== 'icom-net')) && (
|
||||||
<p className="text-xs font-medium text-warning -mt-1 flex items-start gap-1.5">
|
<p className="text-xs font-medium text-warning -mt-1 flex items-start gap-1.5">
|
||||||
<span aria-hidden>⚠</span>
|
<span aria-hidden>⚠</span>
|
||||||
<span>{t('wk.catWarnIcom', { backend: catCfg.enabled ? (catCfg.backend || 'none') : 'disabled' })}</span>
|
<span>{t('wk.catWarnIcom', { backend: catCfg.enabled ? (catCfg.backend || 'none') : 'disabled' })}</span>
|
||||||
@@ -5313,11 +5342,6 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{t('clu.freeNodes')} <span className="font-mono">dxc.k0xm.net:7300</span>,{' '}
|
|
||||||
<span className="font-mono">dx.maritimecontestclub.net:7300</span>,{' '}
|
|
||||||
<span className="font-mono">w8avi.net:7300</span>.
|
|
||||||
</p>
|
|
||||||
<label className="flex items-start gap-2 text-sm cursor-pointer border-t border-border/60 pt-3">
|
<label className="flex items-start gap-2 text-sm cursor-pointer border-t border-border/60 pt-3">
|
||||||
<Checkbox checked={clusterWorkedSameSlot} className="mt-0.5"
|
<Checkbox checked={clusterWorkedSameSlot} className="mt-0.5"
|
||||||
onCheckedChange={(c) => { const v = !!c; setClusterWorkedSameSlot(v); writeUiPref('opslog.clusterWorkedSameSlot', v ? '1' : '0'); }} />
|
onCheckedChange={(c) => { const v = !!c; setClusterWorkedSameSlot(v); writeUiPref('opslog.clusterWorkedSameSlot', v ? '1' : '0'); }} />
|
||||||
@@ -5379,11 +5403,24 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
|
|||||||
const n = parseInt(raw, 10);
|
const n = parseInt(raw, 10);
|
||||||
if (Number.isFinite(n) && n > 0) SetSpotMax(Math.min(10000, n)).catch(() => {});
|
if (Number.isFinite(n) && n > 0) SetSpotMax(Math.min(10000, n)).catch(() => {});
|
||||||
}} />
|
}} />
|
||||||
<span className="text-xs text-muted-foreground">{t('clu.spotMaxHint')}</span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="border-t border-border/60 pt-3 space-y-2">
|
<div className="border-t border-border/60 pt-3 space-y-2">
|
||||||
|
{/* Chase switches: off, the marker stops being TOLD, everywhere at
|
||||||
|
once — badge, colour, filter chip, reference column. A "new band
|
||||||
|
+ new POTA" spot then reads NEW BAND alone. */}
|
||||||
|
<label className="flex items-center gap-2 text-sm cursor-pointer" title={t('clu.chasePotaHint')}>
|
||||||
|
<Checkbox checked={chasePotaOn}
|
||||||
|
onCheckedChange={(c) => { const v = !!c; setChasePotaOn(v); writeUiPref('opslog.chasePota', v ? '1' : '0'); }} />
|
||||||
|
{t('clu.chasePota')}
|
||||||
|
</label>
|
||||||
|
<label className="flex items-center gap-2 text-sm cursor-pointer" title={t('clu.chaseSotaHint')}>
|
||||||
|
<Checkbox checked={chaseSotaOn}
|
||||||
|
onCheckedChange={(c) => { const v = !!c; setChaseSotaOn(v); writeUiPref('opslog.chaseSota', v ? '1' : '0'); }} />
|
||||||
|
{t('clu.chaseSota')}
|
||||||
|
</label>
|
||||||
<label className="flex items-start gap-2 text-sm cursor-pointer">
|
<label className="flex items-start gap-2 text-sm cursor-pointer">
|
||||||
<Checkbox checked={chaseGrids} className="mt-0.5"
|
<Checkbox checked={chaseGrids} className="mt-0.5"
|
||||||
onCheckedChange={(c) => { setChaseGrids(!!c); SetChaseNewGrids(!!c).catch(() => {}); }} />
|
onCheckedChange={(c) => { setChaseGrids(!!c); SetChaseNewGrids(!!c).catch(() => {}); }} />
|
||||||
@@ -5679,10 +5716,7 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
|
|||||||
function UDPIntegrationsPanelWrapper() {
|
function UDPIntegrationsPanelWrapper() {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<SectionHeader
|
<SectionHeader title={t('sec.udp')} />
|
||||||
title={t('sec.udp')}
|
|
||||||
hint={t('udp.hint')}
|
|
||||||
/>
|
|
||||||
<UDPIntegrationsPanel onError={(m) => setErr(m)} />
|
<UDPIntegrationsPanel onError={(m) => setErr(m)} />
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
@@ -6777,7 +6811,7 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
|
|||||||
useLocalLogbook(); // SQLite → default logbook file (clears any per-profile path)
|
useLocalLogbook(); // SQLite → default logbook file (clears any per-profile path)
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<SelectTrigger className="h-8 w-72"><SelectValue /></SelectTrigger>
|
<SelectTrigger className="h-8 w-72" title={t('gen.iaruHint')}><SelectValue /></SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
<SelectItem value="sqlite">{t('db.optSqlite')}</SelectItem>
|
<SelectItem value="sqlite">{t('db.optSqlite')}</SelectItem>
|
||||||
<SelectItem value="mysql">{t('db.optMysql')}</SelectItem>
|
<SelectItem value="mysql">{t('db.optMysql')}</SelectItem>
|
||||||
@@ -6951,7 +6985,8 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
|
|||||||
size="sm"
|
size="sm"
|
||||||
className="h-8"
|
className="h-8"
|
||||||
onClick={toggleMonitor}
|
onClick={toggleMonitor}
|
||||||
disabled={!monitorOn && (!audioCfg.from_radio || 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')}
|
title={fromRadioIsNetwork ? t('aud.monitorNoTci') : t('aud.monitorTitle')}
|
||||||
>
|
>
|
||||||
{monitorOn ? t('aud.stopListening') : t('aud.listenRadio')}
|
{monitorOn ? t('aud.stopListening') : t('aud.listenRadio')}
|
||||||
@@ -7147,7 +7182,7 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
|
|||||||
const { lang, setLang, t } = useI18n();
|
const { lang, setLang, t } = useI18n();
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<SectionHeader title={t('sec.general')} hint={t('gen.hint')} />
|
<SectionHeader title={t('sec.general')} />
|
||||||
<div className="space-y-3 max-w-3xl">
|
<div className="space-y-3 max-w-3xl">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<Label className="text-sm w-40">{t('settings.language')}</Label>
|
<Label className="text-sm w-40">{t('settings.language')}</Label>
|
||||||
@@ -7175,15 +7210,32 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
|
|||||||
['us', t('gen.dateUS'), '07-30-2026 14:25']] as [DateFormat, string, string][]).map(([code, label, sample]) => (
|
['us', t('gen.dateUS'), '07-30-2026 14:25']] as [DateFormat, string, string][]).map(([code, label, sample]) => (
|
||||||
<button key={code} type="button" title={sample}
|
<button key={code} type="button" title={sample}
|
||||||
onClick={() => { setDateFormat(code); setDateFmtSel(code); }}
|
onClick={() => { setDateFormat(code); setDateFmtSel(code); }}
|
||||||
className={cn('flex flex-col items-start px-3 py-1 text-sm font-medium border-l border-border first:border-l-0',
|
className={cn('px-3 py-1.5 text-sm font-medium border-l border-border first:border-l-0',
|
||||||
dateFmtSel === code ? 'bg-primary text-primary-foreground' : 'bg-card text-muted-foreground hover:bg-muted')}>
|
dateFmtSel === code ? 'bg-primary text-primary-foreground' : 'bg-card text-muted-foreground hover:bg-muted')}>
|
||||||
{label}
|
{label}
|
||||||
<span className="text-[10px] font-mono opacity-70">{sample}</span>
|
|
||||||
</button>
|
</button>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2 text-sm">
|
||||||
|
{/* The IARU region drives the band edges and mode segments the band
|
||||||
|
maps draw — Region 2's 40 m runs to 7300, Region 1's stops at
|
||||||
|
7200 — and nothing else: spots and logging are region-blind. */}
|
||||||
|
<Label className="text-sm w-40 shrink-0">{t('gen.iaruRegion')}</Label>
|
||||||
|
<Select value={String(region)} onValueChange={(v) => {
|
||||||
|
const r = (v === '2' ? 2 : v === '3' ? 3 : 1) as IaruRegion;
|
||||||
|
setRegion(r); setIaruRegion(r);
|
||||||
|
}}>
|
||||||
|
<SelectTrigger className="h-8 w-72"><SelectValue /></SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="1">{t('gen.iaruR1')}</SelectItem>
|
||||||
|
<SelectItem value="2">{t('gen.iaruR2')}</SelectItem>
|
||||||
|
<SelectItem value="3">{t('gen.iaruR3')}</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</div>
|
||||||
|
|
||||||
<ThemeSelector />
|
<ThemeSelector />
|
||||||
|
|
||||||
<label className="flex items-center gap-2 text-sm cursor-pointer">
|
<label className="flex items-center gap-2 text-sm cursor-pointer">
|
||||||
@@ -7205,11 +7257,10 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
|
|||||||
{/* Super Check Partial / N+1 — downloads the community MASTER.SCP list and
|
{/* Super Check Partial / N+1 — downloads the community MASTER.SCP list and
|
||||||
shows a two-column callsign helper (partial matches + one-edit calls). */}
|
shows a two-column callsign helper (partial matches + one-edit calls). */}
|
||||||
<div className="border-t border-border/60 pt-3 space-y-2">
|
<div className="border-t border-border/60 pt-3 space-y-2">
|
||||||
<label className="flex items-center gap-2 text-sm cursor-pointer">
|
<label className="flex items-center gap-2 text-sm cursor-pointer" title={t('scp.settingsHint')}>
|
||||||
<Checkbox checked={scp.enabled} disabled={scpBusy} onCheckedChange={(c) => toggleScp(!!c)} />
|
<Checkbox checked={scp.enabled} disabled={scpBusy} onCheckedChange={(c) => toggleScp(!!c)} />
|
||||||
{t('scp.enable')}
|
{t('scp.enable')}
|
||||||
</label>
|
</label>
|
||||||
<p className="text-[11px] text-muted-foreground">{t('scp.settingsHint')}</p>
|
|
||||||
{scp.enabled && (
|
{scp.enabled && (
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<Button variant="outline" size="sm" onClick={downloadScp} disabled={scpBusy}>
|
<Button variant="outline" size="sm" onClick={downloadScp} disabled={scpBusy}>
|
||||||
@@ -7237,18 +7288,18 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
|
|||||||
</label>
|
</label>
|
||||||
<label className="flex items-center gap-2 text-sm cursor-pointer">
|
<label className="flex items-center gap-2 text-sm cursor-pointer">
|
||||||
<Checkbox checked={groupDigital} onCheckedChange={(c) => { const v = !!c; setGroupDigital(v); writeUiPref('opslog.groupDigitalSlots', v ? '1' : '0'); }} />
|
<Checkbox checked={groupDigital} onCheckedChange={(c) => { const v = !!c; setGroupDigital(v); writeUiPref('opslog.groupDigitalSlots', v ? '1' : '0'); }} />
|
||||||
{t('gen.groupDigital')} <span className="text-xs text-muted-foreground">{t('gen.groupDigitalHint')}</span>
|
<span title={t('gen.groupDigitalHint')}>{t('gen.groupDigital')}</span>
|
||||||
</label>
|
</label>
|
||||||
<label className="flex items-center gap-2 text-sm cursor-pointer">
|
<label className="flex items-center gap-2 text-sm cursor-pointer">
|
||||||
{/* Distances are computed in km everywhere and converted at display
|
{/* Distances are computed in km everywhere and converted at display
|
||||||
time — see lib/units. Changing this repaints the columns that
|
time — see lib/units. Changing this repaints the columns that
|
||||||
already carry a distance; nothing stored moves. */}
|
already carry a distance; nothing stored moves. */}
|
||||||
<Checkbox checked={milesUnit} onCheckedChange={(c) => { const v = !!c; setMilesUnit(v); setUseMiles(v); }} />
|
<Checkbox checked={milesUnit} onCheckedChange={(c) => { const v = !!c; setMilesUnit(v); setUseMiles(v); }} />
|
||||||
{t('gen.miles')} <span className="text-xs text-muted-foreground">{t('gen.milesHint')}</span>
|
{t('gen.miles')}
|
||||||
</label>
|
</label>
|
||||||
<label className="flex items-center gap-2 text-sm cursor-pointer">
|
<label className="flex items-center gap-2 text-sm cursor-pointer">
|
||||||
<Checkbox checked={checkUpdates} onCheckedChange={(c) => { const v = !!c; setCheckUpdates(v); writeUiPref('opslog.checkUpdates', v ? '1' : '0'); }} />
|
<Checkbox checked={checkUpdates} onCheckedChange={(c) => { const v = !!c; setCheckUpdates(v); writeUiPref('opslog.checkUpdates', v ? '1' : '0'); }} />
|
||||||
{t('gen.checkUpdates')} <span className="text-xs text-muted-foreground">{t('gen.checkUpdatesHint')}</span>
|
{t('gen.checkUpdates')}
|
||||||
</label>
|
</label>
|
||||||
<TelemetryToggle />
|
<TelemetryToggle />
|
||||||
|
|
||||||
@@ -7311,12 +7362,7 @@ function SettingsModalImpl({ onClose, onSaved, initialSection, onMainPaneChanged
|
|||||||
}}
|
}}
|
||||||
className="mt-0.5"
|
className="mt-0.5"
|
||||||
/>
|
/>
|
||||||
<span>
|
<span title={t('gen.clubDesc')}>{t('gen.clubUse')}</span>
|
||||||
{t('gen.clubUse')}
|
|
||||||
<span className="block text-xs text-muted-foreground mt-0.5">
|
|
||||||
{t('gen.clubDesc')}
|
|
||||||
</span>
|
|
||||||
</span>
|
|
||||||
</label>
|
</label>
|
||||||
<div className="flex items-center gap-3 pl-6">
|
<div className="flex items-center gap-3 pl-6">
|
||||||
<Button variant="outline" size="sm" className="h-8" disabled={clubBusy}
|
<Button variant="outline" size="sm" className="h-8" disabled={clubBusy}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import React, { useCallback, useEffect, useState } from 'react';
|
|||||||
import { Plus, Trash2, Edit2, RefreshCcw, ArrowDownToLine, ArrowUpFromLine } from 'lucide-react';
|
import { Plus, Trash2, Edit2, RefreshCcw, ArrowDownToLine, ArrowUpFromLine } from 'lucide-react';
|
||||||
import {
|
import {
|
||||||
ListUDPIntegrations, SaveUDPIntegration, DeleteUDPIntegration, ReloadUDPIntegrations,
|
ListUDPIntegrations, SaveUDPIntegration, DeleteUDPIntegration, ReloadUDPIntegrations,
|
||||||
|
GetWsjtHighlight, SetWsjtHighlight, GetWsjtFollowMode, SetWsjtFollowMode,
|
||||||
} from '../../wailsjs/go/main/App';
|
} from '../../wailsjs/go/main/App';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
@@ -158,6 +159,12 @@ const TRIGGERS = [
|
|||||||
type Props = { onError: (msg: string) => void };
|
type Props = { onError: (msg: string) => void };
|
||||||
|
|
||||||
export function UDPIntegrationsPanel({ onError }: Props) {
|
export function UDPIntegrationsPanel({ onError }: Props) {
|
||||||
|
const [highlightOn, setHighlightOn] = useState(false);
|
||||||
|
const [followMode, setFollowMode] = useState(true);
|
||||||
|
useEffect(() => {
|
||||||
|
GetWsjtHighlight().then((v) => setHighlightOn(!!v)).catch(() => {});
|
||||||
|
GetWsjtFollowMode().then((v) => setFollowMode(!!v)).catch(() => {});
|
||||||
|
}, []);
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
const [items, setItems] = useState<UDPConfig[]>([]);
|
const [items, setItems] = useState<UDPConfig[]>([]);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
@@ -229,10 +236,24 @@ export function UDPIntegrationsPanel({ onError }: Props) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<div className="text-[11px] text-muted-foreground max-w-2xl leading-relaxed">
|
{/* Log-aware colours in WSJT-X / JTDX's own window — lives HERE because
|
||||||
{t('udpp.intro')}
|
this panel is where the WSJT-X link is configured. */}
|
||||||
</div>
|
<label className="flex items-start gap-2 text-sm cursor-pointer max-w-2xl">
|
||||||
|
<Checkbox checked={highlightOn}
|
||||||
|
onCheckedChange={(c) => { setHighlightOn(!!c); void SetWsjtHighlight(!!c); }} />
|
||||||
|
<span>
|
||||||
|
{t('udpp.highlight')}
|
||||||
|
<span className="block text-[11px] text-muted-foreground">{t('udpp.highlightHint')}</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
<label className="flex items-start gap-2 text-sm cursor-pointer max-w-2xl">
|
||||||
|
<Checkbox checked={followMode}
|
||||||
|
onCheckedChange={(c) => { setFollowMode(!!c); void SetWsjtFollowMode(!!c); }} />
|
||||||
|
<span>
|
||||||
|
{t('udpp.followMode')}
|
||||||
|
<span className="block text-[11px] text-muted-foreground">{t('udpp.followModeHint')}</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
<Section
|
<Section
|
||||||
title={t('udpp.inboundTitle')}
|
title={t('udpp.inboundTitle')}
|
||||||
icon={<ArrowDownToLine className="size-4" />}
|
icon={<ArrowDownToLine className="size-4" />}
|
||||||
|
|||||||
@@ -0,0 +1,420 @@
|
|||||||
|
// Watchlist — the DXHunter concept as an OpsLog tab.
|
||||||
|
//
|
||||||
|
// One card per watched callsign (or prefix), the live spots that match it
|
||||||
|
// underneath, and the two questions an operator actually asks answered on every
|
||||||
|
// line: is this slot still NEEDED, and what would it be worth (the same NEW
|
||||||
|
// DXCC / band / mode / slot badges the cluster shows, resolved from the same
|
||||||
|
// index). A CONTEST entry is judged against the current UTC day — at midnight
|
||||||
|
// everything reads "work today" again; the boundary lives in the backend query,
|
||||||
|
// so there is nothing to reset.
|
||||||
|
//
|
||||||
|
// The design is DXHunter's — the layout, the badges, the wording — repainted in
|
||||||
|
// the app's theme tokens rather than its hard-coded slate/pink.
|
||||||
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
import { Eye, Plus, Trash2, Bell, BellOff, Trophy, Search } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Checkbox } from '@/components/ui/checkbox';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import { useI18n } from '@/lib/i18n';
|
||||||
|
import {
|
||||||
|
WatchlistEntries, WatchlistAdd, WatchlistRemove, WatchlistSetNotify,
|
||||||
|
WatchlistSetContest, WatchlistWorkedSlots,
|
||||||
|
GetWatchlistContestPattern, SetWatchlistContestPattern, OpenExternalURL,
|
||||||
|
} from '../../wailsjs/go/main/App';
|
||||||
|
import { EventsOn } from '../../wailsjs/runtime/runtime';
|
||||||
|
import type { ClusterSpot, SpotStatusEntry } from '@/components/ClusterGrid';
|
||||||
|
import { inferSpotMode, spotStatusKey } from '@/lib/spot';
|
||||||
|
|
||||||
|
interface WLEntry {
|
||||||
|
callsign: string; lastSeenStr: string; addedAt: string; spotCount: number;
|
||||||
|
isContest: boolean; notify: boolean;
|
||||||
|
isExpedition: boolean; clubLogQSOs24h: number; clubLogTotalQSOs: number;
|
||||||
|
clubLogHasOQRS: boolean; clubLogLiveStream: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
spots: ClusterSpot[];
|
||||||
|
spotStatus: Record<string, SpotStatusEntry>;
|
||||||
|
onSpotSelect?: (s: ClusterSpot) => void;
|
||||||
|
onSpotClick?: (s: ClusterSpot) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A spot is ON AIR for the badge while its last sighting is this fresh.
|
||||||
|
const ON_AIR_MS = 10 * 60 * 1000;
|
||||||
|
|
||||||
|
// Exact unless the entry carries a trailing * — the same rule the backend's
|
||||||
|
// Match applies to the live stream, mirrored so the tab and the alerts can
|
||||||
|
// never disagree about what an entry covers.
|
||||||
|
function matchesEntry(call: string, pattern: string): boolean {
|
||||||
|
const c = call.toUpperCase();
|
||||||
|
if (pattern.endsWith('*')) {
|
||||||
|
const p = pattern.slice(0, -1);
|
||||||
|
return p !== '' && c.startsWith(p);
|
||||||
|
}
|
||||||
|
return c === pattern;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WatchlistTab({ spots, spotStatus, onSpotSelect, onSpotClick }: Props) {
|
||||||
|
const { t } = useI18n();
|
||||||
|
const [entries, setEntries] = useState<WLEntry[]>([]);
|
||||||
|
const [addCall, setAddCall] = useState('');
|
||||||
|
const [addContest, setAddContest] = useState(false);
|
||||||
|
const [search, setSearch] = useState('');
|
||||||
|
// The filters survive leaving the tab: the component unmounts on every tab
|
||||||
|
// switch, and filters that reset each time are filters nobody trusts.
|
||||||
|
const [neededOnly, setNeededOnlyRaw] = useState(() => localStorage.getItem('opslog.wlNeededOnly') === '1');
|
||||||
|
const [activeOnly, setActiveOnlyRaw] = useState(() => localStorage.getItem('opslog.wlActiveOnly') === '1');
|
||||||
|
const [family, setFamilyRaw] = useState<'all' | 'normal' | 'contest'>(() => {
|
||||||
|
const v = localStorage.getItem('opslog.wlFamily');
|
||||||
|
return v === 'normal' || v === 'contest' ? v : 'all';
|
||||||
|
});
|
||||||
|
const setNeededOnly = (f: (v: boolean) => boolean) => setNeededOnlyRaw((v) => { const nv = f(v); try { localStorage.setItem('opslog.wlNeededOnly', nv ? '1' : '0'); } catch {} return nv; });
|
||||||
|
const setActiveOnly = (f: (v: boolean) => boolean) => setActiveOnlyRaw((v) => { const nv = f(v); try { localStorage.setItem('opslog.wlActiveOnly', nv ? '1' : '0'); } catch {} return nv; });
|
||||||
|
const setFamily = (v: 'all' | 'normal' | 'contest') => { setFamilyRaw(v); try { localStorage.setItem('opslog.wlFamily', v); } catch {} };
|
||||||
|
// Mode filter — DXHunter's "All Modes" select. DIGI matches the digital class
|
||||||
|
// (FT8, FT4, a generic DATA spot…), the named modes match exactly.
|
||||||
|
const [modeFilter, setModeFilterRaw] = useState(() => localStorage.getItem('opslog.wlMode') || 'ALL');
|
||||||
|
const setModeFilter = (v: string) => { setModeFilterRaw(v); try { localStorage.setItem('opslog.wlMode', v); } catch {} };
|
||||||
|
const modeMatches = (s2: ClusterSpot): boolean => {
|
||||||
|
if (modeFilter === 'ALL') return true;
|
||||||
|
const m = (inferSpotMode(s2.comment ?? '', s2.freq_hz) || '').toUpperCase();
|
||||||
|
if (modeFilter === 'DIGI') return !['', 'CW', 'SSB', 'USB', 'LSB', 'FM', 'AM'].includes(m);
|
||||||
|
if (modeFilter === 'SSB') return m === 'SSB' || m === 'USB' || m === 'LSB';
|
||||||
|
return m === modeFilter;
|
||||||
|
};
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
// A quiet confirmation under the toolbar; both messages clear themselves —
|
||||||
|
// a stale "added" from ten minutes ago reads as a fresh one.
|
||||||
|
const [notice, setNotice] = useState('');
|
||||||
|
const noticeTimer = useRef<number | undefined>(undefined);
|
||||||
|
const flash = (msg: string, isError: boolean) => {
|
||||||
|
if (noticeTimer.current) window.clearTimeout(noticeTimer.current);
|
||||||
|
setError(isError ? msg : '');
|
||||||
|
setNotice(isError ? '' : msg);
|
||||||
|
noticeTimer.current = window.setTimeout(() => { setError(''); setNotice(''); }, 4000) as unknown as number;
|
||||||
|
};
|
||||||
|
|
||||||
|
// worked answer per "call|band|modeclass|contest" key.
|
||||||
|
const [worked, setWorked] = useState<Record<string, boolean>>({});
|
||||||
|
|
||||||
|
const refresh = useCallback(async () => {
|
||||||
|
try { setEntries(((await WatchlistEntries()) ?? []) as any as WLEntry[]); }
|
||||||
|
catch (e: any) { setError(String(e?.message ?? e)); }
|
||||||
|
}, []);
|
||||||
|
// Refreshed on mount, when the backend auto-adds (event), and on a slow tick
|
||||||
|
// so last-seen and the spot counters stay honest while the tab sits open.
|
||||||
|
useEffect(() => {
|
||||||
|
void refresh();
|
||||||
|
const off = EventsOn('watchlist:changed', () => { void refresh(); });
|
||||||
|
const id = window.setInterval(() => { void refresh(); }, 30_000);
|
||||||
|
return () => { off(); window.clearInterval(id); };
|
||||||
|
}, [refresh]);
|
||||||
|
// The auto-contest pattern (DXHunter's contest_prefix): spots whose call
|
||||||
|
// contains it are added as contest entries by the backend.
|
||||||
|
const [pattern, setPattern] = useState('');
|
||||||
|
useEffect(() => { GetWatchlistContestPattern().then((p: string) => setPattern(p ?? '')).catch(() => {}); }, []);
|
||||||
|
|
||||||
|
// Live spots per entry — prefix-matched, newest first, deduped per band+mode
|
||||||
|
// (one line per slot; the freshest spot represents it).
|
||||||
|
const spotsFor = useMemo(() => {
|
||||||
|
const map = new Map<string, ClusterSpot[]>();
|
||||||
|
for (const e of entries) map.set(e.callsign, []);
|
||||||
|
for (const s of spots) {
|
||||||
|
for (const e of entries) {
|
||||||
|
if (matchesEntry(s.dx_call ?? '', e.callsign)) { map.get(e.callsign)!.push(s); break; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const [k, list] of map) {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
map.set(k, list.filter((s) => {
|
||||||
|
const key = `${(s.band ?? '')}|${inferSpotMode(s.comment ?? '', s.freq_hz)}|${s.dx_call}`;
|
||||||
|
if (seen.has(key)) return false;
|
||||||
|
seen.add(key);
|
||||||
|
return true;
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
return map;
|
||||||
|
}, [spots, entries]);
|
||||||
|
|
||||||
|
// The worked answers, refreshed when the visible slots change. Debounced: a
|
||||||
|
// spot burst must cost one round trip, not one per spot.
|
||||||
|
const queryTimer = useRef<number | undefined>(undefined);
|
||||||
|
useEffect(() => {
|
||||||
|
if (queryTimer.current) window.clearTimeout(queryTimer.current);
|
||||||
|
queryTimer.current = window.setTimeout(async () => {
|
||||||
|
const queries: { call: string; band: string; mode: string; contest: boolean }[] = [];
|
||||||
|
const keys: string[] = [];
|
||||||
|
for (const e of entries) {
|
||||||
|
for (const s of spotsFor.get(e.callsign) ?? []) {
|
||||||
|
const mode = inferSpotMode(s.comment ?? '', s.freq_hz) || '';
|
||||||
|
queries.push({ call: s.dx_call, band: s.band ?? '', mode, contest: e.isContest });
|
||||||
|
keys.push(`${s.dx_call}|${s.band ?? ''}|${mode}|${e.isContest ? 1 : 0}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (queries.length === 0) { setWorked({}); return; }
|
||||||
|
try {
|
||||||
|
const res: boolean[] = (await WatchlistWorkedSlots(queries as any)) ?? [];
|
||||||
|
// MERGED, not replaced: replacing made every already-answered key
|
||||||
|
// momentarily unknown on each refresh, which re-hid settled lines.
|
||||||
|
setWorked((prev) => {
|
||||||
|
const next = { ...prev };
|
||||||
|
keys.forEach((k, i) => { next[k] = !!res[i]; });
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
} catch { /* the badges just stay conservative */ }
|
||||||
|
}, 150) as unknown as number;
|
||||||
|
return () => { if (queryTimer.current) window.clearTimeout(queryTimer.current); };
|
||||||
|
}, [spotsFor, entries]);
|
||||||
|
|
||||||
|
const wkey = (e: WLEntry, s: ClusterSpot) =>
|
||||||
|
`${s.dx_call}|${s.band ?? ''}|${inferSpotMode(s.comment ?? '', s.freq_hz) || ''}|${e.isContest ? 1 : 0}`;
|
||||||
|
const workedFor = (e: WLEntry, s: ClusterSpot): boolean => worked[wkey(e, s)] ?? false;
|
||||||
|
// A spot whose verdict has not come back yet is NOT drawn. Showing it as
|
||||||
|
// Needed and withdrawing it half a second later made the list twitch on
|
||||||
|
// every burst — and nobody needs a spot 400 ms early, they need it settled.
|
||||||
|
const settled = (e: WLEntry, s: ClusterSpot): boolean => wkey(e, s) in worked;
|
||||||
|
|
||||||
|
const add = async () => {
|
||||||
|
const c = addCall.trim().toUpperCase();
|
||||||
|
if (!c) return;
|
||||||
|
try {
|
||||||
|
await WatchlistAdd(c, addContest);
|
||||||
|
setAddCall('');
|
||||||
|
flash(t(addContest ? 'wl.addedContest' : 'wl.added', { call: c }), false);
|
||||||
|
await refresh();
|
||||||
|
} catch (e: any) { flash(String(e?.message ?? e), true); }
|
||||||
|
};
|
||||||
|
|
||||||
|
// One click, like the bell and the trophy beside it: removing a watchlist
|
||||||
|
// entry is cheap to undo (type it again), so it does not earn a confirmation
|
||||||
|
// the other two buttons do not have.
|
||||||
|
const remove = async (call: string) => {
|
||||||
|
try { await WatchlistRemove(call); flash(t('wl.removed', { call }), false); await refresh(); }
|
||||||
|
catch (e: any) { flash(String(e?.message ?? e), true); }
|
||||||
|
};
|
||||||
|
|
||||||
|
const isOnAir = (e: WLEntry): boolean =>
|
||||||
|
(spotsFor.get(e.callsign) ?? []).some((s) => {
|
||||||
|
const ts = Date.parse(String((s as any).received_at ?? ''));
|
||||||
|
return ts > 0 && Date.now() - ts < ON_AIR_MS;
|
||||||
|
});
|
||||||
|
|
||||||
|
const shown = entries.filter((e) => {
|
||||||
|
if (family === 'normal' && e.isContest) return false;
|
||||||
|
if (family === 'contest' && !e.isContest) return false;
|
||||||
|
if (search && !e.callsign.includes(search.trim().toUpperCase())) return false;
|
||||||
|
const list = (spotsFor.get(e.callsign) ?? []).filter(modeMatches).filter((s2) => settled(e, s2));
|
||||||
|
if (activeOnly && list.length === 0) return false;
|
||||||
|
if (neededOnly && !list.some((s2) => !workedFor(e, s2))) return false;
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
const counters = useMemo(() => {
|
||||||
|
let active = 0, needed = 0;
|
||||||
|
for (const e of entries) {
|
||||||
|
const list = (spotsFor.get(e.callsign) ?? []).filter(modeMatches).filter((s2) => settled(e, s2));
|
||||||
|
if (list.length > 0) active++;
|
||||||
|
if (list.some((s2) => !workedFor(e, s2))) needed++;
|
||||||
|
}
|
||||||
|
return { total: entries.length, active, needed };
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, [entries, spotsFor, worked, modeFilter]);
|
||||||
|
|
||||||
|
// The cluster's own badge for a spot, read from the shared status index.
|
||||||
|
const dxccBadge = (s: ClusterSpot): { label: string; color: string } | null => {
|
||||||
|
const st = spotStatus[spotStatusKey(s.dx_call, s.band ?? '', s.comment ?? '', s.freq_hz)];
|
||||||
|
switch (st?.status) {
|
||||||
|
case 'new': return { label: t('wl.newDxcc'), color: 'var(--danger)' };
|
||||||
|
case 'new-band-mode': return { label: t('clg2.newBandMode'), color: 'var(--danger)' };
|
||||||
|
case 'new-band': return { label: t('clg2.newBand'), color: 'var(--warning)' };
|
||||||
|
case 'new-mode': return { label: t('clg2.newMode'), color: 'var(--caution)' };
|
||||||
|
case 'new-slot': return { label: t('clg2.newSlot'), color: '#5AC8FA' };
|
||||||
|
default: return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const chip = (color: string, text: string, extra?: string) => (
|
||||||
|
<span className={cn('px-1.5 py-0.5 rounded text-[10px] font-bold border', extra)}
|
||||||
|
style={{ color, borderColor: `color-mix(in srgb, ${color} 40%, transparent)`, background: `color-mix(in srgb, ${color} 12%, transparent)` }}>
|
||||||
|
{text}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
// Capped and centred: a card is a reading surface, and callsign-to-badge
|
||||||
|
// lines stretched across a 34-inch window are not readable, they are long.
|
||||||
|
<div className="flex flex-col min-h-0 flex-1 gap-2 p-2 w-full max-w-5xl mx-auto">
|
||||||
|
{/* Header: the counters alone, centred — they are the tab's headline.
|
||||||
|
Everything one INTERACTS with lives on the second row. */}
|
||||||
|
<div className="flex items-center justify-center gap-2.5 text-xs text-muted-foreground">
|
||||||
|
<Eye className="size-4 text-primary shrink-0" />
|
||||||
|
<span className="flex items-center gap-1.5">{t('wl.cTotal')}
|
||||||
|
<b className="px-2 py-0.5 rounded bg-muted text-foreground">{counters.total}</b></span>
|
||||||
|
<span className="opacity-40">|</span>
|
||||||
|
<span className="flex items-center gap-1.5">{t('wl.cActive')}
|
||||||
|
<b className="px-2 py-0.5 rounded text-info border border-info/30 bg-info/10">{counters.active}</b></span>
|
||||||
|
<span className="opacity-40">|</span>
|
||||||
|
<span className="flex items-center gap-1.5">{t('wl.cNeeded')}
|
||||||
|
<b className={cn('px-2 py-0.5 rounded border', counters.needed > 0
|
||||||
|
? 'text-warning border-warning/40 bg-warning/10'
|
||||||
|
: 'text-muted-foreground border-border bg-muted/40')}>{counters.needed}</b></span>
|
||||||
|
</div>
|
||||||
|
{/* toolbar */}
|
||||||
|
<div className="flex items-start justify-between gap-x-3 gap-y-1.5 flex-wrap">
|
||||||
|
<div className="flex items-center gap-2 shrink-0">
|
||||||
|
<Input className="h-8 w-40 font-mono placeholder:font-sans placeholder:normal-case" placeholder={t('wl.addPh')} value={addCall}
|
||||||
|
onChange={(e) => setAddCall(e.target.value.toUpperCase())}
|
||||||
|
onKeyDown={(e) => { if (e.key === 'Enter') void add(); }} />
|
||||||
|
<label className="flex items-center gap-1.5 text-xs cursor-pointer" title={t('wl.contestHint')}>
|
||||||
|
<Checkbox checked={addContest} onCheckedChange={(c) => setAddContest(!!c)} />
|
||||||
|
<Trophy className="size-3.5 text-warning" /> {t('wl.addAsContest')}
|
||||||
|
</label>
|
||||||
|
<Button size="sm" className="h-8" onClick={() => void add()} disabled={!addCall.trim()}>
|
||||||
|
<Plus className="size-3.5" /> {t('wl.add')}
|
||||||
|
</Button>
|
||||||
|
<Input className="h-8 w-28 font-mono placeholder:font-sans placeholder:normal-case" placeholder={t('wl.patternPh')}
|
||||||
|
title={t('wl.patternHint')}
|
||||||
|
value={pattern}
|
||||||
|
onChange={(e) => setPattern(e.target.value.toUpperCase())}
|
||||||
|
onBlur={() => { void SetWatchlistContestPattern(pattern.trim()); }} />
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 shrink-0">
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="size-3.5 absolute left-2 top-1/2 -translate-y-1/2 text-muted-foreground" />
|
||||||
|
<Input className="h-8 w-28 pl-7 text-sm" placeholder={t('wl.searchPh')} value={search}
|
||||||
|
onChange={(e) => setSearch(e.target.value)} />
|
||||||
|
</div>
|
||||||
|
{/* families kept together, told apart — per review of the DXHunter port,
|
||||||
|
no global contest mode: each entry carries its own rule. */}
|
||||||
|
<div className="inline-flex rounded-md border border-border overflow-hidden text-xs">
|
||||||
|
{([['all', t('wl.famAll')], ['normal', t('wl.famNormal')], ['contest', t('wl.famContest')]] as const).map(([k, label]) => (
|
||||||
|
<button key={k} type="button" onClick={() => setFamily(k)}
|
||||||
|
className={cn('px-2 py-1 border-l border-border first:border-l-0',
|
||||||
|
family === k ? 'bg-accent font-medium' : 'text-muted-foreground hover:bg-accent/50')}>
|
||||||
|
{label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<select value={modeFilter} onChange={(e) => setModeFilter(e.target.value)}
|
||||||
|
title={t('wl.modeFilter')}
|
||||||
|
className="h-7 px-1.5 rounded-md border border-border bg-background text-xs text-foreground">
|
||||||
|
{['ALL', 'CW', 'SSB', 'FT8', 'FT4', 'RTTY', 'DIGI'].map((m) => (
|
||||||
|
<option key={m} value={m}>{m === 'ALL' ? t('wl.allModes') : m}</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<button type="button" onClick={() => setActiveOnly((v) => !v)}
|
||||||
|
className={cn('px-2 py-1 rounded-md border text-xs', activeOnly ? 'bg-accent border-border font-medium' : 'border-border text-muted-foreground hover:bg-accent/50')}>
|
||||||
|
{t('wl.activeOnly')}
|
||||||
|
</button>
|
||||||
|
<button type="button" onClick={() => setNeededOnly((v) => !v)}
|
||||||
|
className={cn('px-2 py-1 rounded-md border text-xs', neededOnly ? 'bg-accent border-border font-medium' : 'border-border text-muted-foreground hover:bg-accent/50')}>
|
||||||
|
{t('wl.neededOnly')}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{error && <div className="text-xs text-danger px-1">{error}</div>}
|
||||||
|
{notice && <div className="text-xs text-success px-1">{notice}</div>}
|
||||||
|
|
||||||
|
{/* cards */}
|
||||||
|
<div className="flex-1 min-h-0 overflow-y-auto space-y-2 pr-1">
|
||||||
|
{shown.length === 0 ? (
|
||||||
|
<div className="text-sm text-muted-foreground text-center pt-16 max-w-md mx-auto leading-relaxed">
|
||||||
|
{entries.length === 0 ? t('wl.empty') : t('wl.noneMatch')}
|
||||||
|
</div>
|
||||||
|
) : shown.map((e) => {
|
||||||
|
const all = (spotsFor.get(e.callsign) ?? []).filter(modeMatches).filter((s2) => settled(e, s2));
|
||||||
|
const needed = all.filter((s) => !workedFor(e, s)).length;
|
||||||
|
// Needed-only hides the worked LINES as well as the all-worked cards:
|
||||||
|
// a filter that says needed and still lists five green Worked rows is
|
||||||
|
// answering a different question than the one asked.
|
||||||
|
const list = neededOnly ? all.filter((s) => !workedFor(e, s)) : all;
|
||||||
|
return (
|
||||||
|
<div key={e.callsign}
|
||||||
|
className={cn('rounded-lg border bg-card/70 p-3 transition-colors hover:bg-accent/20',
|
||||||
|
needed > 0 ? 'border-warning/40' : 'border-border/70',
|
||||||
|
e.isContest && 'border-l-4 border-l-warning')}>
|
||||||
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
|
<span className="text-lg font-bold font-mono" style={{ color: '#f472b6' }}>{e.callsign}</span>
|
||||||
|
{isOnAir(e) && chip('var(--danger)', t('wl.onAir'), 'animate-pulse')}
|
||||||
|
{e.isContest && (
|
||||||
|
<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-bold bg-warning-muted text-warning-muted-foreground border border-warning-border"
|
||||||
|
title={t('wl.contestHint')}>
|
||||||
|
<Trophy className="size-3" /> {t('wl.contest')}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{e.isExpedition && chip('var(--chart-5)', '⚡ ' + t('wl.expedition'))}
|
||||||
|
{e.clubLogTotalQSOs > 0 && <span className="text-[11px] text-muted-foreground">{e.clubLogTotalQSOs.toLocaleString()} QSOs{e.clubLogQSOs24h > 0 ? ` · ${e.clubLogQSOs24h}/24h` : ''}</span>}
|
||||||
|
{e.clubLogHasOQRS && chip('var(--success)', 'OQRS')}
|
||||||
|
{e.clubLogLiveStream && (
|
||||||
|
<a href="#" onClick={(ev) => { ev.preventDefault(); void OpenExternalURL(`https://clublog.org/livestream/${e.callsign.replace('*', '')}`); }}
|
||||||
|
className="px-1.5 py-0.5 rounded text-[10px] font-bold border text-info border-info/40 bg-info/10 hover:bg-info/20">Live</a>
|
||||||
|
)}
|
||||||
|
{list.length > 0 && (needed > 0
|
||||||
|
? chip('var(--warning)', e.isContest ? t('wl.nToday', { n: needed }) : t('wl.nNeeded', { n: needed }))
|
||||||
|
: chip('var(--success)', e.isContest ? t('wl.workedToday') : t('wl.allWorked')))}
|
||||||
|
{e.lastSeenStr && e.lastSeenStr !== 'Never' && (
|
||||||
|
<span className="text-[11px] text-muted-foreground">· {e.lastSeenStr}</span>
|
||||||
|
)}
|
||||||
|
{e.spotCount > 0 && (
|
||||||
|
<span className="text-[11px] text-muted-foreground/70">· {t('wl.totalSpots', { n: e.spotCount })}</span>
|
||||||
|
)}
|
||||||
|
<div className="flex-1" />
|
||||||
|
<button type="button" title={t('wl.toggleContest')}
|
||||||
|
onClick={() => void WatchlistSetContest(e.callsign, !e.isContest).then(refresh)}
|
||||||
|
className={cn('p-1 rounded hover:bg-muted', e.isContest ? 'text-warning' : 'text-muted-foreground/40')}>
|
||||||
|
<Trophy className="size-3.5" />
|
||||||
|
</button>
|
||||||
|
<button type="button" title={e.notify ? t('wl.notifyOff') : t('wl.notifyOn')}
|
||||||
|
onClick={() => void WatchlistSetNotify(e.callsign, !e.notify).then(refresh)}
|
||||||
|
className={cn('p-1 rounded hover:bg-muted', e.notify ? 'text-warning' : 'text-muted-foreground/40')}>
|
||||||
|
{e.notify ? <Bell className="size-3.5" /> : <BellOff className="size-3.5" />}
|
||||||
|
</button>
|
||||||
|
<button type="button" title={t('wl.remove')}
|
||||||
|
onClick={() => void remove(e.callsign)}
|
||||||
|
className="p-1 rounded hover:bg-muted text-muted-foreground/40 hover:text-danger">
|
||||||
|
<Trash2 className="size-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{list.length > 0 ? (
|
||||||
|
<div className="mt-2 space-y-1 max-h-52 overflow-y-auto">
|
||||||
|
{list.slice(0, 12).map((s, i) => {
|
||||||
|
const done = workedFor(e, s);
|
||||||
|
const badge = dxccBadge(s);
|
||||||
|
const mode = inferSpotMode(s.comment ?? '', s.freq_hz);
|
||||||
|
return (
|
||||||
|
<button key={i} type="button"
|
||||||
|
onClick={() => onSpotSelect?.(s)}
|
||||||
|
onDoubleClick={() => onSpotClick?.(s)}
|
||||||
|
title={t('wl.spotTip')}
|
||||||
|
className={cn('w-full flex items-center gap-2 px-2 py-1.5 rounded text-[11px] bg-muted/25 hover:bg-muted/70 transition-colors text-left',
|
||||||
|
!done && 'border-l-[3px] border-warning')}>
|
||||||
|
{done && <span className='font-bold shrink-0 text-success'>✓</span>}
|
||||||
|
<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>
|
||||||
|
<span className="px-1.5 rounded bg-muted shrink-0">{s.band}</span>
|
||||||
|
{mode && <span className="px-1.5 rounded shrink-0" style={{ color: 'var(--chart-5)', background: 'color-mix(in srgb, var(--chart-5) 12%, transparent)' }}>{mode}</span>}
|
||||||
|
<span className="font-mono text-muted-foreground shrink-0">{(s.freq_hz / 1e6).toFixed(4)}</span>
|
||||||
|
{badge && chip(badge.color, badge.label)}
|
||||||
|
<div className="flex-1" />
|
||||||
|
{done
|
||||||
|
? chip('var(--success)', e.isContest ? t('wl.todayOk') : t('wl.worked'))
|
||||||
|
: chip('var(--warning)', e.isContest ? t('wl.workToday') : t('wl.needed'))}
|
||||||
|
<span className="text-muted-foreground/70 shrink-0">{s.time_utc ?? ''}</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="mt-2 text-[11px] text-muted-foreground text-center py-1.5 bg-muted/30 rounded">
|
||||||
|
{t('wl.noSpots')}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,555 +0,0 @@
|
|||||||
// Label Designer — QSO labels for QSL cards and address labels for envelopes.
|
|
||||||
//
|
|
||||||
// Same architecture as the QSL card designer, stripped to what a monochrome
|
|
||||||
// sticker needs: saved templates on the left, a mm-true canvas on the right,
|
|
||||||
// click to select, drag to move. The canvas renderer (labelRender) is shared
|
|
||||||
// with the future print path, so what the preview shows is what the PDF gets.
|
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
||||||
import { X, Plus, Trash2, Star, Tag, MapPin } from 'lucide-react';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Input } from '@/components/ui/input';
|
|
||||||
import { Label } from '@/components/ui/label';
|
|
||||||
import { Checkbox } from '@/components/ui/checkbox';
|
|
||||||
import {
|
|
||||||
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
|
|
||||||
} from '@/components/ui/select';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import { useI18n } from '@/lib/i18n';
|
|
||||||
import {
|
|
||||||
LabelListStocks, LabelSaveStock, LabelDeleteStock,
|
|
||||||
LabelListTemplates, LabelGetTemplate, LabelSaveTemplate, LabelDeleteTemplate,
|
|
||||||
LabelSetDefaultTemplate, LabelSampleQSOs, GetActiveProfile,
|
|
||||||
} from '../../../wailsjs/go/main/App';
|
|
||||||
import type { LabelElement, LabelSample, LabelStock, LabelTemplate } from './labelTypes';
|
|
||||||
import { LABEL_VARS, TABLE_FIELDS, starterTemplate } from './labelTypes';
|
|
||||||
import { drawMargins, render, type ElementBox } from './labelRender';
|
|
||||||
|
|
||||||
interface Props { open: boolean; onClose: () => void }
|
|
||||||
|
|
||||||
interface TplInfo {
|
|
||||||
id: number; name: string; kind: string; stock_id: number;
|
|
||||||
is_default: boolean; updated_at: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The preview fills whatever room the centre pane offers — a label cut off at
|
|
||||||
// the edge cannot be judged, and 90 mm across a fixed 720 px wasted half the
|
|
||||||
// window. Measured live so a resize re-fits.
|
|
||||||
const PREVIEW_MIN_SCALE = 2;
|
|
||||||
|
|
||||||
export function LabelDesignerModal({ open, onClose }: Props) {
|
|
||||||
const { t } = useI18n();
|
|
||||||
const [stocks, setStocks] = useState<LabelStock[]>([]);
|
|
||||||
const [saved, setSaved] = useState<TplInfo[]>([]);
|
|
||||||
const [samples, setSamples] = useState<LabelSample[]>([]);
|
|
||||||
const [myVars, setMyVars] = useState<Record<string, string>>({});
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
|
|
||||||
// The design being edited (null = nothing open yet).
|
|
||||||
const [tplId, setTplId] = useState(0);
|
|
||||||
const [tpl, setTpl] = useState<LabelTemplate | null>(null);
|
|
||||||
const [tplName, setTplName] = useState('');
|
|
||||||
const [forProfile, setForProfile] = useState(true);
|
|
||||||
const [sel, setSel] = useState<number | null>(null);
|
|
||||||
const [dirty, setDirty] = useState(false);
|
|
||||||
const [deleteArm, setDeleteArm] = useState(0);
|
|
||||||
|
|
||||||
// Stock editor (collapsed by default — geometry is set once per roll).
|
|
||||||
const [stockOpen, setStockOpen] = useState(false);
|
|
||||||
const [stockDraft, setStockDraft] = useState<LabelStock | null>(null);
|
|
||||||
|
|
||||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
|
||||||
const paneRef = useRef<HTMLDivElement>(null);
|
|
||||||
const [paneSize, setPaneSize] = useState({ w: 720, h: 420 });
|
|
||||||
useEffect(() => {
|
|
||||||
const el = paneRef.current;
|
|
||||||
if (!el) return;
|
|
||||||
const ro = new ResizeObserver(() => {
|
|
||||||
setPaneSize({ w: el.clientWidth, h: el.clientHeight });
|
|
||||||
});
|
|
||||||
ro.observe(el);
|
|
||||||
return () => ro.disconnect();
|
|
||||||
}, [open, tpl != null]);
|
|
||||||
const boxesRef = useRef<ElementBox[]>([]);
|
|
||||||
const dragRef = useRef<{ idx: number; dxMm: number; dyMm: number } | null>(null);
|
|
||||||
|
|
||||||
const stock = useMemo(
|
|
||||||
() => stocks.find((s) => s.id === tpl?.stock_id) ?? stocks[0],
|
|
||||||
[stocks, tpl?.stock_id]);
|
|
||||||
|
|
||||||
const refresh = useCallback(async () => {
|
|
||||||
try {
|
|
||||||
setStocks((await LabelListStocks()) as any as LabelStock[]);
|
|
||||||
setSaved(((await LabelListTemplates()) ?? []) as any as TplInfo[]);
|
|
||||||
} catch (e: any) { setError(String(e?.message ?? e)); }
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!open) return;
|
|
||||||
setError(''); setTpl(null); setTplId(0); setSel(null); setDirty(false);
|
|
||||||
void refresh();
|
|
||||||
LabelSampleQSOs(5).then((r: any) => setSamples(r ?? [])).catch(() => {});
|
|
||||||
// The preview resolves <MY*> from the active profile so the address label
|
|
||||||
// reads like the finished sticker, not like a form.
|
|
||||||
GetActiveProfile().then((p: any) => setMyVars({
|
|
||||||
MYCALL: p?.callsign ?? 'MYCALL', MYNAME: p?.op_name ?? p?.operator ?? '',
|
|
||||||
MYSTREET: p?.my_street ?? '', MYZIP: p?.my_postal_code ?? '', MYCITY: p?.my_city ?? '',
|
|
||||||
MYCOUNTRY: p?.my_country ?? '',
|
|
||||||
})).catch(() => setMyVars({ MYCALL: 'MYCALL' }));
|
|
||||||
}, [open, refresh]);
|
|
||||||
|
|
||||||
// Preview variable values: the first sample QSO plays the DX station.
|
|
||||||
const vars = useMemo(() => {
|
|
||||||
const q = samples[0];
|
|
||||||
return {
|
|
||||||
CALL: q?.callsign ?? 'DL1ABC', NAME: q?.name ?? 'Hans', QTH: q?.qth ?? 'Berlin',
|
|
||||||
COUNTRY: q?.country ?? 'Germany', VIA: 'DJ5XX',
|
|
||||||
STREET: 'Funkerstrasse 12', ZIP: '10115', CITY: q?.qth || 'Berlin', STATE: '',
|
|
||||||
...myVars,
|
|
||||||
} as Record<string, string>;
|
|
||||||
}, [samples, myVars]);
|
|
||||||
|
|
||||||
// ── canvas ────────────────────────────────────────────────────────────
|
|
||||||
const scale = useMemo(() => {
|
|
||||||
if (!stock) return 4;
|
|
||||||
// Leave room for the pane's padding and the two control strips above and
|
|
||||||
// below the canvas; never shrink below a scale where 8 pt is readable.
|
|
||||||
const availW = Math.max(200, paneSize.w - 56);
|
|
||||||
const availH = Math.max(120, paneSize.h - 130);
|
|
||||||
return Math.max(PREVIEW_MIN_SCALE, Math.min(availW / stock.w_mm, availH / stock.h_mm));
|
|
||||||
}, [stock, paneSize]);
|
|
||||||
|
|
||||||
const paint = useCallback(() => {
|
|
||||||
const cv = canvasRef.current;
|
|
||||||
if (!cv || !tpl || !stock) return;
|
|
||||||
const dpr = window.devicePixelRatio || 1;
|
|
||||||
cv.width = Math.round(stock.w_mm * scale * dpr);
|
|
||||||
cv.height = Math.round(stock.h_mm * scale * dpr);
|
|
||||||
cv.style.width = `${stock.w_mm * scale}px`;
|
|
||||||
cv.style.height = `${stock.h_mm * scale}px`;
|
|
||||||
const ctx = cv.getContext('2d');
|
|
||||||
if (!ctx) return;
|
|
||||||
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
|
|
||||||
boxesRef.current = render(ctx, tpl, stock, { vars, qsos: samples }, scale);
|
|
||||||
drawMargins(ctx, stock, scale);
|
|
||||||
// Selection outline, drawn after everything: the editor's own chrome.
|
|
||||||
if (sel != null && boxesRef.current[sel]) {
|
|
||||||
const b = boxesRef.current[sel];
|
|
||||||
ctx.save();
|
|
||||||
ctx.scale(scale, scale);
|
|
||||||
ctx.strokeStyle = 'rgba(255,140,0,0.9)';
|
|
||||||
ctx.lineWidth = 0.3;
|
|
||||||
ctx.setLineDash([1, 0.8]);
|
|
||||||
ctx.strokeRect(b.x - 0.6, b.y - 0.6, b.w + 1.2, b.h + 1.2);
|
|
||||||
ctx.restore();
|
|
||||||
}
|
|
||||||
}, [tpl, stock, vars, samples, scale, sel]);
|
|
||||||
|
|
||||||
useEffect(() => { paint(); }, [paint]);
|
|
||||||
|
|
||||||
const mmFromEvent = (ev: React.MouseEvent): { x: number; y: number } => {
|
|
||||||
const r = canvasRef.current!.getBoundingClientRect();
|
|
||||||
return { x: (ev.clientX - r.left) / scale, y: (ev.clientY - r.top) / scale };
|
|
||||||
};
|
|
||||||
|
|
||||||
const onCanvasDown = (ev: React.MouseEvent) => {
|
|
||||||
if (!tpl) return;
|
|
||||||
const p = mmFromEvent(ev);
|
|
||||||
// Topmost element under the pointer wins — iterate backwards.
|
|
||||||
for (let i = boxesRef.current.length - 1; i >= 0; i--) {
|
|
||||||
const b = boxesRef.current[i];
|
|
||||||
if (p.x >= b.x && p.x <= b.x + b.w && p.y >= b.y && p.y <= b.y + b.h) {
|
|
||||||
setSel(i);
|
|
||||||
dragRef.current = { idx: i, dxMm: p.x - tpl.elements[i].x_mm, dyMm: p.y - tpl.elements[i].y_mm };
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
setSel(null);
|
|
||||||
};
|
|
||||||
const onCanvasMove = (ev: React.MouseEvent) => {
|
|
||||||
const d = dragRef.current;
|
|
||||||
if (!d || !tpl) return;
|
|
||||||
const p = mmFromEvent(ev);
|
|
||||||
// Snapped to 0.5 mm: free pixels look precise on screen and print ragged.
|
|
||||||
const x = Math.round((p.x - d.dxMm) * 2) / 2;
|
|
||||||
const y = Math.round((p.y - d.dyMm) * 2) / 2;
|
|
||||||
patchEl(d.idx, { x_mm: x, y_mm: y });
|
|
||||||
};
|
|
||||||
const onCanvasUp = () => { dragRef.current = null; };
|
|
||||||
|
|
||||||
// ── template edits ────────────────────────────────────────────────────
|
|
||||||
function patchEl(idx: number, patch: Partial<LabelElement>) {
|
|
||||||
setTpl((cur) => {
|
|
||||||
if (!cur) return cur;
|
|
||||||
const elements = cur.elements.map((e, i) => (i === idx ? { ...e, ...patch } : e));
|
|
||||||
return { ...cur, elements };
|
|
||||||
});
|
|
||||||
setDirty(true);
|
|
||||||
}
|
|
||||||
function addElement(e: LabelElement) {
|
|
||||||
setTpl((cur) => (cur ? { ...cur, elements: [...cur.elements, e] } : cur));
|
|
||||||
setSel(tpl ? tpl.elements.length : 0);
|
|
||||||
setDirty(true);
|
|
||||||
}
|
|
||||||
function removeSelected() {
|
|
||||||
if (sel == null) return;
|
|
||||||
setTpl((cur) => (cur ? { ...cur, elements: cur.elements.filter((_, i) => i !== sel) } : cur));
|
|
||||||
setSel(null);
|
|
||||||
setDirty(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
function newTemplate(kind: 'qso' | 'address') {
|
|
||||||
const s = stocks[0];
|
|
||||||
if (!s) { setError(t('lbl.noStock')); return; }
|
|
||||||
setTpl(starterTemplate(kind, s));
|
|
||||||
setTplId(0);
|
|
||||||
setTplName(kind === 'qso' ? t('lbl.newQsoName') : t('lbl.newAddrName'));
|
|
||||||
setSel(null);
|
|
||||||
setDirty(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function openTemplate(info: TplInfo) {
|
|
||||||
try {
|
|
||||||
const doc = await LabelGetTemplate(info.id);
|
|
||||||
setTpl(JSON.parse(doc) as LabelTemplate);
|
|
||||||
setTplId(info.id);
|
|
||||||
setTplName(info.name);
|
|
||||||
setSel(null);
|
|
||||||
setDirty(false);
|
|
||||||
} catch (e: any) { setError(String(e?.message ?? e)); }
|
|
||||||
}
|
|
||||||
|
|
||||||
async function save() {
|
|
||||||
if (!tpl) return;
|
|
||||||
try {
|
|
||||||
const id = await LabelSaveTemplate(tplId, tplName.trim() || 'Label', JSON.stringify(tpl), forProfile);
|
|
||||||
setTplId(id as number);
|
|
||||||
setDirty(false);
|
|
||||||
await refresh();
|
|
||||||
} catch (e: any) { setError(String(e?.message ?? e)); }
|
|
||||||
}
|
|
||||||
|
|
||||||
async function removeTemplate(id: number) {
|
|
||||||
if (deleteArm !== id) { setDeleteArm(id); window.setTimeout(() => setDeleteArm(0), 2500); return; }
|
|
||||||
try {
|
|
||||||
await LabelDeleteTemplate(id);
|
|
||||||
if (id === tplId) { setTpl(null); setTplId(0); }
|
|
||||||
await refresh();
|
|
||||||
} catch (e: any) { setError(String(e?.message ?? e)); }
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── stock editor ──────────────────────────────────────────────────────
|
|
||||||
async function saveStock() {
|
|
||||||
if (!stockDraft) return;
|
|
||||||
try {
|
|
||||||
await LabelSaveStock(stockDraft as any);
|
|
||||||
setStockDraft(null);
|
|
||||||
await refresh();
|
|
||||||
} catch (e: any) { setError(String(e?.message ?? e)); }
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!open) return null;
|
|
||||||
const e = sel != null && tpl ? tpl.elements[sel] : undefined;
|
|
||||||
|
|
||||||
const numField = (label: string, value: number, set: (v: number) => void, step = 0.5, w = 'w-20') => (
|
|
||||||
<div className="space-y-0.5">
|
|
||||||
<Label className="text-[10px] text-muted-foreground">{label}</Label>
|
|
||||||
<Input type="number" step={step} value={value} className={cn('h-7 text-xs font-mono', w)}
|
|
||||||
onChange={(ev) => set(parseFloat(ev.target.value) || 0)} />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="fixed inset-0 z-50 bg-black/60 flex items-center justify-center p-4">
|
|
||||||
<div className="bg-card border border-border rounded-xl shadow-2xl w-full max-w-6xl h-[92vh] flex flex-col overflow-hidden">
|
|
||||||
{/* header */}
|
|
||||||
<div className="flex items-center gap-3 px-4 py-2.5 border-b border-border shrink-0">
|
|
||||||
<Tag className="size-4 text-primary" />
|
|
||||||
<span className="font-semibold text-sm">{t('lbl.title')}</span>
|
|
||||||
<div className="flex-1" />
|
|
||||||
{tpl && (
|
|
||||||
<>
|
|
||||||
<Input className="h-8 w-56 text-sm" value={tplName} onChange={(ev) => { setTplName(ev.target.value); setDirty(true); }}
|
|
||||||
placeholder={t('lbl.namePh')} />
|
|
||||||
<label className="flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer">
|
|
||||||
<Checkbox checked={forProfile} onCheckedChange={(c) => setForProfile(!!c)} />
|
|
||||||
{t('lbl.forProfile')}
|
|
||||||
</label>
|
|
||||||
<Button size="sm" className="h-8" onClick={save} disabled={!dirty && tplId !== 0}>
|
|
||||||
{t('lbl.save')}
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
<Button variant="ghost" size="sm" className="h-8" onClick={onClose}><X className="size-4" /></Button>
|
|
||||||
</div>
|
|
||||||
{error && <div className="px-4 py-1.5 text-xs text-danger border-b border-border/60">{error}</div>}
|
|
||||||
|
|
||||||
<div className="flex-1 min-h-0 flex">
|
|
||||||
{/* left: saved templates + stocks */}
|
|
||||||
<div className="w-64 border-r border-border flex flex-col min-h-0 shrink-0">
|
|
||||||
<div className="p-2 flex gap-1.5">
|
|
||||||
<Button size="sm" variant="outline" className="h-8 flex-1" onClick={() => newTemplate('qso')}>
|
|
||||||
<Plus className="size-3.5" /> {t('lbl.newQso')}
|
|
||||||
</Button>
|
|
||||||
<Button size="sm" variant="outline" className="h-8 flex-1" onClick={() => newTemplate('address')}>
|
|
||||||
<Plus className="size-3.5" /> {t('lbl.newAddr')}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<div className="flex-1 overflow-y-auto px-2 pb-2 space-y-1">
|
|
||||||
{saved.map((s) => (
|
|
||||||
<div key={s.id}
|
|
||||||
className={cn('rounded-md border px-2 py-1.5 cursor-pointer text-xs',
|
|
||||||
s.id === tplId ? 'border-primary bg-primary/5' : 'border-border hover:bg-muted/50')}
|
|
||||||
onClick={() => void openTemplate(s)}>
|
|
||||||
<div className="flex items-center gap-1.5">
|
|
||||||
{s.kind === 'qso' ? <Tag className="size-3 shrink-0 text-muted-foreground" /> : <MapPin className="size-3 shrink-0 text-muted-foreground" />}
|
|
||||||
<span className="font-medium truncate flex-1">{s.name}</span>
|
|
||||||
<button type="button" title={t('lbl.setDefault')}
|
|
||||||
onClick={(ev) => { ev.stopPropagation(); void LabelSetDefaultTemplate(s.id).then(refresh); }}>
|
|
||||||
<Star className={cn('size-3.5', s.is_default ? 'text-warning fill-warning' : 'text-muted-foreground/40')} />
|
|
||||||
</button>
|
|
||||||
<button type="button" title={t('lbl.delete')}
|
|
||||||
onClick={(ev) => { ev.stopPropagation(); void removeTemplate(s.id); }}>
|
|
||||||
<Trash2 className={cn('size-3.5', deleteArm === s.id ? 'text-danger' : 'text-muted-foreground/40')} />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div className="text-[10px] text-muted-foreground pl-4">
|
|
||||||
{s.kind === 'qso' ? t('lbl.kindQso') : t('lbl.kindAddr')} · {s.updated_at}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
{saved.length === 0 && (
|
|
||||||
<div className="text-xs text-muted-foreground px-1 py-3">{t('lbl.empty')}</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{/* stocks */}
|
|
||||||
<div className="border-t border-border p-2 space-y-1.5">
|
|
||||||
<button type="button" className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground"
|
|
||||||
onClick={() => setStockOpen((v) => !v)}>
|
|
||||||
{t('lbl.stocks')} {stockOpen ? '▾' : '▸'}
|
|
||||||
</button>
|
|
||||||
{stockOpen && (
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Select value={String(stockDraft?.id ?? '')} onValueChange={(v) => {
|
|
||||||
const s = stocks.find((x) => String(x.id) === v);
|
|
||||||
if (s) setStockDraft({ ...s });
|
|
||||||
}}>
|
|
||||||
<SelectTrigger className="h-7 text-xs"><SelectValue placeholder={t('lbl.pickStock')} /></SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{stocks.map((s) => <SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>)}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
<div className="flex gap-1.5">
|
|
||||||
<Button size="sm" variant="outline" className="h-7 text-xs flex-1"
|
|
||||||
onClick={() => setStockDraft({ name: t('lbl.customStock'), w_mm: 90, h_mm: 29, margin_top_mm: 1.5, margin_right_mm: 3, margin_bottom_mm: 1.5, margin_left_mm: 3, dpi: 300 })}>
|
|
||||||
<Plus className="size-3" /> {t('lbl.newStock')}
|
|
||||||
</Button>
|
|
||||||
{stockDraft?.id ? (
|
|
||||||
<Button size="sm" variant="ghost" className="h-7 text-xs text-danger"
|
|
||||||
onClick={() => { void LabelDeleteStock(stockDraft.id!).then(() => { setStockDraft(null); return refresh(); }); }}>
|
|
||||||
<Trash2 className="size-3" />
|
|
||||||
</Button>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
{stockDraft && (
|
|
||||||
<div className="space-y-1.5">
|
|
||||||
<Input className="h-7 text-xs" value={stockDraft.name}
|
|
||||||
onChange={(ev) => setStockDraft({ ...stockDraft, name: ev.target.value })} />
|
|
||||||
<div className="grid grid-cols-2 gap-1.5">
|
|
||||||
{numField(t('lbl.widthMm'), stockDraft.w_mm, (v) => setStockDraft({ ...stockDraft, w_mm: v }), 0.5, 'w-full')}
|
|
||||||
{numField(t('lbl.heightMm'), stockDraft.h_mm, (v) => setStockDraft({ ...stockDraft, h_mm: v }), 0.5, 'w-full')}
|
|
||||||
</div>
|
|
||||||
<div className="grid grid-cols-4 gap-1.5">
|
|
||||||
{numField('↑', stockDraft.margin_top_mm, (v) => setStockDraft({ ...stockDraft, margin_top_mm: v }), 0.5, 'w-full')}
|
|
||||||
{numField('→', stockDraft.margin_right_mm, (v) => setStockDraft({ ...stockDraft, margin_right_mm: v }), 0.5, 'w-full')}
|
|
||||||
{numField('↓', stockDraft.margin_bottom_mm, (v) => setStockDraft({ ...stockDraft, margin_bottom_mm: v }), 0.5, 'w-full')}
|
|
||||||
{numField('←', stockDraft.margin_left_mm, (v) => setStockDraft({ ...stockDraft, margin_left_mm: v }), 0.5, 'w-full')}
|
|
||||||
</div>
|
|
||||||
<Button size="sm" className="h-7 text-xs w-full" onClick={() => void saveStock()}>{t('lbl.saveStock')}</Button>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* centre: preview */}
|
|
||||||
<div ref={paneRef} className="flex-1 min-w-0 flex flex-col items-center justify-center bg-muted/30 overflow-auto p-6 gap-3">
|
|
||||||
{tpl && stock ? (
|
|
||||||
<>
|
|
||||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
|
||||||
<span>{t('lbl.stock')}:</span>
|
|
||||||
<Select value={String(tpl.stock_id || stock.id)} onValueChange={(v) => {
|
|
||||||
setTpl({ ...tpl, stock_id: parseInt(v, 10) }); setDirty(true);
|
|
||||||
}}>
|
|
||||||
<SelectTrigger className="h-7 text-xs w-72"><SelectValue /></SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{stocks.map((s) => <SelectItem key={s.id} value={String(s.id)}>{s.name}</SelectItem>)}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
<span className="font-mono">{stock.w_mm}×{stock.h_mm} mm</span>
|
|
||||||
</div>
|
|
||||||
<canvas ref={canvasRef} className="shadow-lg rounded-sm cursor-move"
|
|
||||||
onMouseDown={onCanvasDown} onMouseMove={onCanvasMove}
|
|
||||||
onMouseUp={onCanvasUp} onMouseLeave={onCanvasUp} />
|
|
||||||
<div className="flex items-center gap-1.5">
|
|
||||||
<Button size="sm" variant="outline" className="h-7 text-xs"
|
|
||||||
onClick={() => addElement({ type: 'text', x_mm: stock.margin_left_mm, y_mm: stock.h_mm / 2, text: t('lbl.newText'), size_pt: 9 })}>
|
|
||||||
<Plus className="size-3" /> {t('lbl.addText')}
|
|
||||||
</Button>
|
|
||||||
<Button size="sm" variant="outline" className="h-7 text-xs"
|
|
||||||
onClick={() => addElement({ type: 'line', x_mm: stock.margin_left_mm, y_mm: stock.h_mm / 2, w_mm: stock.w_mm - stock.margin_left_mm - stock.margin_right_mm, thickness_mm: 0.3 })}>
|
|
||||||
<Plus className="size-3" /> {t('lbl.addLine')}
|
|
||||||
</Button>
|
|
||||||
{tpl.kind === 'address' && (
|
|
||||||
<Button size="sm" variant="outline" className="h-7 text-xs"
|
|
||||||
onClick={() => addElement({ type: 'addr_block', x_mm: stock.margin_left_mm + 2, y_mm: stock.margin_top_mm + 2, lines: ['<NAME>', '<STREET>', '<ZIP> <CITY>', '<COUNTRY>'], size_pt: 11, line_gap_mm: 1.6 })}>
|
|
||||||
<Plus className="size-3" /> {t('lbl.addAddr')}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{tpl.kind === 'qso' && !tpl.elements.some((x) => x.type === 'qso_table') && (
|
|
||||||
<Button size="sm" variant="outline" className="h-7 text-xs"
|
|
||||||
onClick={() => addElement({ type: 'qso_table', x_mm: stock.margin_left_mm, y_mm: stock.margin_top_mm + 7, w_mm: stock.w_mm - stock.margin_left_mm - stock.margin_right_mm, rows_max: 4, row_h_mm: 4, header: true, size_pt: 7.5, columns: TABLE_FIELDS.slice(0, 6).map((c) => ({ ...c })) })}>
|
|
||||||
<Plus className="size-3" /> {t('lbl.addTable')}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{sel != null && (
|
|
||||||
<Button size="sm" variant="ghost" className="h-7 text-xs text-danger" onClick={removeSelected}>
|
|
||||||
<Trash2 className="size-3" /> {t('lbl.removeEl')}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<div className="text-sm text-muted-foreground text-center max-w-sm leading-relaxed">
|
|
||||||
{t('lbl.intro')}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* right: properties of the selection */}
|
|
||||||
{tpl && (
|
|
||||||
<div className="w-72 border-l border-border overflow-y-auto p-3 space-y-3 shrink-0">
|
|
||||||
{!e ? (
|
|
||||||
<div className="text-xs text-muted-foreground leading-relaxed">{t('lbl.selectHint')}</div>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<div className="text-[11px] font-semibold uppercase tracking-wider text-muted-foreground">
|
|
||||||
{t(`lbl.el_${e.type}` as any)}
|
|
||||||
</div>
|
|
||||||
<div className="flex gap-2">
|
|
||||||
{numField('X mm', e.x_mm, (v) => patchEl(sel!, { x_mm: v }))}
|
|
||||||
{numField('Y mm', e.y_mm, (v) => patchEl(sel!, { y_mm: v }))}
|
|
||||||
{(e.type === 'text' || e.type === 'line' || e.type === 'qso_table') &&
|
|
||||||
numField('W mm', e.w_mm ?? 0, (v) => patchEl(sel!, { w_mm: v }))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{e.type === 'text' && (
|
|
||||||
<>
|
|
||||||
<div className="space-y-0.5">
|
|
||||||
<Label className="text-[10px] text-muted-foreground">{t('lbl.text')}</Label>
|
|
||||||
<Input className="h-7 text-xs" value={e.text ?? ''} onChange={(ev) => patchEl(sel!, { text: ev.target.value })} />
|
|
||||||
</div>
|
|
||||||
<VarPicker onPick={(v) => patchEl(sel!, { text: `${e.text ?? ''}<${v}>` })} t={t} />
|
|
||||||
<div className="flex gap-2 items-end">
|
|
||||||
{numField('pt', e.size_pt ?? 9, (v) => patchEl(sel!, { size_pt: v }), 0.5, 'w-16')}
|
|
||||||
<label className="flex items-center gap-1 text-xs cursor-pointer pb-1.5">
|
|
||||||
<Checkbox checked={!!e.bold} onCheckedChange={(c) => patchEl(sel!, { bold: !!c })} /> B
|
|
||||||
</label>
|
|
||||||
<label className="flex items-center gap-1 text-xs italic cursor-pointer pb-1.5">
|
|
||||||
<Checkbox checked={!!e.italic} onCheckedChange={(c) => patchEl(sel!, { italic: !!c })} /> I
|
|
||||||
</label>
|
|
||||||
<Select value={e.align ?? 'left'} onValueChange={(v) => patchEl(sel!, { align: v as any })}>
|
|
||||||
<SelectTrigger className="h-7 text-xs w-24"><SelectValue /></SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="left">{t('lbl.alignLeft')}</SelectItem>
|
|
||||||
<SelectItem value="center">{t('lbl.alignCenter')}</SelectItem>
|
|
||||||
<SelectItem value="right">{t('lbl.alignRight')}</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{e.type === 'line' && numField(t('lbl.thickness'), e.thickness_mm ?? 0.3, (v) => patchEl(sel!, { thickness_mm: v }), 0.1)}
|
|
||||||
|
|
||||||
{e.type === 'addr_block' && (
|
|
||||||
<>
|
|
||||||
<div className="space-y-0.5">
|
|
||||||
<Label className="text-[10px] text-muted-foreground">{t('lbl.addrLines')}</Label>
|
|
||||||
<textarea
|
|
||||||
className="w-full h-28 rounded-md border border-input bg-background px-2 py-1 text-xs font-mono"
|
|
||||||
value={(e.lines ?? []).join('\n')}
|
|
||||||
onChange={(ev) => patchEl(sel!, { lines: ev.target.value.split('\n') })} />
|
|
||||||
<div className="text-[10px] text-muted-foreground">{t('lbl.addrHint')}</div>
|
|
||||||
</div>
|
|
||||||
<VarPicker onPick={(v) => patchEl(sel!, { lines: [...(e.lines ?? []), `<${v}>`] })} t={t} />
|
|
||||||
<div className="flex gap-2">
|
|
||||||
{numField('pt', e.size_pt ?? 11, (v) => patchEl(sel!, { size_pt: v }), 0.5, 'w-16')}
|
|
||||||
{numField(t('lbl.lineGap'), e.line_gap_mm ?? 1.5, (v) => patchEl(sel!, { line_gap_mm: v }), 0.1, 'w-20')}
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{e.type === 'qso_table' && (
|
|
||||||
<>
|
|
||||||
<div className="flex gap-2">
|
|
||||||
{numField(t('lbl.rows'), e.rows_max ?? 4, (v) => patchEl(sel!, { rows_max: Math.max(1, Math.round(v)) }), 1, 'w-16')}
|
|
||||||
{numField(t('lbl.rowH'), e.row_h_mm ?? 4, (v) => patchEl(sel!, { row_h_mm: v }), 0.1, 'w-20')}
|
|
||||||
{numField('pt', e.size_pt ?? 7.5, (v) => patchEl(sel!, { size_pt: v }), 0.5, 'w-16')}
|
|
||||||
</div>
|
|
||||||
<label className="flex items-center gap-1.5 text-xs cursor-pointer">
|
|
||||||
<Checkbox checked={!!e.header} onCheckedChange={(c) => patchEl(sel!, { header: !!c })} />
|
|
||||||
{t('lbl.header')}
|
|
||||||
</label>
|
|
||||||
<div className="space-y-1">
|
|
||||||
<Label className="text-[10px] text-muted-foreground">{t('lbl.columns')}</Label>
|
|
||||||
{(e.columns ?? []).map((c, ci) => (
|
|
||||||
<div key={ci} className="flex items-center gap-1">
|
|
||||||
<Select value={c.field} onValueChange={(v) => {
|
|
||||||
const f = TABLE_FIELDS.find((x) => x.field === v);
|
|
||||||
const columns = e.columns!.map((x, i) => (i === ci ? { ...x, field: v, label: f?.label ?? v } : x));
|
|
||||||
patchEl(sel!, { columns });
|
|
||||||
}}>
|
|
||||||
<SelectTrigger className="h-6 text-[11px] flex-1"><SelectValue /></SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{TABLE_FIELDS.map((f) => <SelectItem key={f.field} value={f.field}>{f.label}</SelectItem>)}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
<Input type="number" step={0.5} className="h-6 w-14 text-[11px] font-mono" value={c.w_mm}
|
|
||||||
onChange={(ev) => {
|
|
||||||
const columns = e.columns!.map((x, i) => (i === ci ? { ...x, w_mm: parseFloat(ev.target.value) || 1 } : x));
|
|
||||||
patchEl(sel!, { columns });
|
|
||||||
}} />
|
|
||||||
<button type="button" onClick={() => patchEl(sel!, { columns: e.columns!.filter((_, i) => i !== ci) })}>
|
|
||||||
<Trash2 className="size-3 text-muted-foreground/60" />
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
<Button size="sm" variant="outline" className="h-6 text-[11px] w-full"
|
|
||||||
onClick={() => patchEl(sel!, { columns: [...(e.columns ?? []), { ...TABLE_FIELDS[0] }] })}>
|
|
||||||
<Plus className="size-3" /> {t('lbl.addColumn')}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// VarPicker inserts a <VARIABLE> — a menu beats remembering the exact spelling.
|
|
||||||
function VarPicker({ onPick, t }: { onPick: (v: string) => void; t: (k: string) => string }) {
|
|
||||||
return (
|
|
||||||
<Select value="" onValueChange={(v) => { if (v) onPick(v); }}>
|
|
||||||
<SelectTrigger className="h-7 text-xs"><SelectValue placeholder={t('lbl.insertVar')} /></SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{LABEL_VARS.map((v) => <SelectItem key={v} value={v}>{`<${v}>`}</SelectItem>)}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,502 +0,0 @@
|
|||||||
// Label printing — the paper-QSL labelling session, in three steps:
|
|
||||||
//
|
|
||||||
// 1. PICK the contacts (preloaded with the R/Q paper queue), grouped by
|
|
||||||
// callsign — several QSOs of the same station share one card.
|
|
||||||
// 2. REVIEW each recipient: routing (direct / bureau / via manager), the
|
|
||||||
// address checked and edited by hand, a QRZ fetch to fill it.
|
|
||||||
// 3. PRINT ONE PDF holding every label of the session (each page at its
|
|
||||||
// own physical size), opened straight in the system viewer — the
|
|
||||||
// operator prints from there — then mark the contacts sent
|
|
||||||
// (date + via) in the log.
|
|
||||||
//
|
|
||||||
// The pages are rasterised by the designer's own renderer at the stock's dpi:
|
|
||||||
// what the designer previewed is what the PDF carries.
|
|
||||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
|
||||||
import { X, Printer, RefreshCw, ChevronRight, ChevronLeft, Check, Loader2 } from 'lucide-react';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Input } from '@/components/ui/input';
|
|
||||||
import { Checkbox } from '@/components/ui/checkbox';
|
|
||||||
import {
|
|
||||||
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
|
|
||||||
} from '@/components/ui/select';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import { useI18n } from '@/lib/i18n';
|
|
||||||
import {
|
|
||||||
LabelPaperQueue, LabelListStocks, LabelListTemplates, LabelGetTemplate,
|
|
||||||
LabelOpenPDF, LookupCallsignFresh, BulkUpdateQSL, GetActiveProfile,
|
|
||||||
} from '../../../wailsjs/go/main/App';
|
|
||||||
import type { LabelSample, LabelStock, LabelTemplate } from './labelTypes';
|
|
||||||
import { rasterize } from './labelRender';
|
|
||||||
|
|
||||||
interface Props { open: boolean; onClose: () => void }
|
|
||||||
|
|
||||||
type Routing = 'direct' | 'bureau' | 'via';
|
|
||||||
|
|
||||||
interface Station {
|
|
||||||
call: string;
|
|
||||||
qsos: any[]; // raw QSO rows, newest first
|
|
||||||
checked: boolean;
|
|
||||||
routing: Routing;
|
|
||||||
via: string; // manager callsign when routing = via
|
|
||||||
address: string; // multiline, the text that will be printed — verbatim
|
|
||||||
// Whose address the box holds: the DX's prefill, the manager's fetch, or the
|
|
||||||
// operator's own edit. Routing changes recompute the first two and must never
|
|
||||||
// touch the third — an address typed by hand is not the app's to replace.
|
|
||||||
addrFor: 'dx' | 'mgr' | 'user' | 'none';
|
|
||||||
fetching?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface TplInfo { id: number; name: string; kind: string; stock_id: number; is_default: boolean }
|
|
||||||
|
|
||||||
// One label's worth of QSO rows, in the designer's sample shape.
|
|
||||||
function toSample(q: any): LabelSample {
|
|
||||||
const d = new Date(q.qso_date);
|
|
||||||
const pad = (n: number) => String(n).padStart(2, '0');
|
|
||||||
return {
|
|
||||||
callsign: q.callsign ?? '',
|
|
||||||
qso_date: `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())}`,
|
|
||||||
time_on: `${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}`,
|
|
||||||
band: q.band ?? '', mode: q.mode ?? '',
|
|
||||||
freq: q.freq_hz ? (q.freq_hz / 1e6).toFixed(3) : '',
|
|
||||||
rst_sent: q.rst_sent ?? '', rst_rcvd: q.rst_rcvd ?? '',
|
|
||||||
name: q.name ?? '', qth: q.qth ?? '', country: q.country ?? '',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// dedupeLines drops empties and any line already CONTAINED in an earlier one:
|
|
||||||
// the log often holds "20370 Casablanca Morocco" as the address AND "20370
|
|
||||||
// CASABLANCA" as the QTH AND "Morocco" as the country, and printing all three
|
|
||||||
// stacks the same city three times on the envelope.
|
|
||||||
function dedupeLines(lines: Array<any>): string[] {
|
|
||||||
const out: string[] = [];
|
|
||||||
for (const raw of lines) {
|
|
||||||
const l = String(raw ?? '').trim();
|
|
||||||
if (!l) continue;
|
|
||||||
const low = l.toLowerCase();
|
|
||||||
if (out.some((prev) => prev.toLowerCase().includes(low))) continue;
|
|
||||||
out.push(l);
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
function initialAddress(q: any): string {
|
|
||||||
return dedupeLines([q.name, q.address, q.qth, q.country]).join('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
export function LabelPrintModal({ open, onClose }: Props) {
|
|
||||||
const { t } = useI18n();
|
|
||||||
const [step, setStep] = useState<'pick' | 'review' | 'print'>('pick');
|
|
||||||
const [stations, setStations] = useState<Station[]>([]);
|
|
||||||
const [loading, setLoading] = useState(false);
|
|
||||||
const [error, setError] = useState('');
|
|
||||||
|
|
||||||
const [stocks, setStocks] = useState<LabelStock[]>([]);
|
|
||||||
const [tpls, setTpls] = useState<TplInfo[]>([]);
|
|
||||||
const [doQso, setDoQso] = useState(true);
|
|
||||||
const [doAddr, setDoAddr] = useState(true);
|
|
||||||
const [doReturn, setDoReturn] = useState(false);
|
|
||||||
const [qsoTplId, setQsoTplId] = useState(0);
|
|
||||||
const [addrTplId, setAddrTplId] = useState(0);
|
|
||||||
const [retTplId, setRetTplId] = useState(0);
|
|
||||||
const [myAddress, setMyAddress] = useState('');
|
|
||||||
const [myVars, setMyVars] = useState<Record<string, string>>({});
|
|
||||||
|
|
||||||
// Rasterised pages per kind — kept separate for the previews, concatenated
|
|
||||||
// (with each page's own mm size) into the single PDF.
|
|
||||||
type Page = { png: string; w_mm: number; h_mm: number };
|
|
||||||
const [pages, setPages] = useState<{ qso: Page[]; addr: Page[]; ret: Page[] }>({ qso: [], addr: [], ret: [] });
|
|
||||||
const [building, setBuilding] = useState(false);
|
|
||||||
const [pdfPath, setPdfPath] = useState('');
|
|
||||||
const [markDate, setMarkDate] = useState(() => new Date().toISOString().slice(0, 10));
|
|
||||||
const [marked, setMarked] = useState(0);
|
|
||||||
|
|
||||||
const load = useCallback(async () => {
|
|
||||||
setLoading(true); setError('');
|
|
||||||
try {
|
|
||||||
const rows: any[] = (await LabelPaperQueue()) ?? [];
|
|
||||||
// Group by callsign, newest first inside each group.
|
|
||||||
const by = new Map<string, any[]>();
|
|
||||||
for (const q of rows) {
|
|
||||||
const c = String(q.callsign ?? '').toUpperCase();
|
|
||||||
if (!by.has(c)) by.set(c, []);
|
|
||||||
by.get(c)!.push(q);
|
|
||||||
}
|
|
||||||
setStations([...by.entries()].map(([call, qsos]) => {
|
|
||||||
const via = String(qsos[0]?.qsl_via ?? '').trim();
|
|
||||||
// Via a manager, the DX's own address is exactly the wrong thing to
|
|
||||||
// print on the envelope — start empty and let the QRZ fetch fill in the
|
|
||||||
// MANAGER's.
|
|
||||||
const address = via ? '' : initialAddress(qsos[0]);
|
|
||||||
return {
|
|
||||||
call, qsos, checked: true,
|
|
||||||
routing: via ? 'via' as Routing : (address.split('\n').length >= 3 ? 'direct' as Routing : 'bureau' as Routing),
|
|
||||||
via, address, addrFor: (via ? 'none' : 'dx') as Station['addrFor'],
|
|
||||||
};
|
|
||||||
}));
|
|
||||||
const st = (await LabelListStocks()) as any as LabelStock[];
|
|
||||||
setStocks(st);
|
|
||||||
const tl = ((await LabelListTemplates()) ?? []) as any as TplInfo[];
|
|
||||||
setTpls(tl);
|
|
||||||
const def = (kind: string) => tl.find((x) => x.kind === kind && x.is_default) ?? tl.find((x) => x.kind === kind);
|
|
||||||
setQsoTplId(def('qso')?.id ?? 0);
|
|
||||||
setAddrTplId(def('address')?.id ?? 0);
|
|
||||||
setRetTplId(def('address')?.id ?? 0);
|
|
||||||
const p: any = await GetActiveProfile().catch(() => null);
|
|
||||||
const mv = {
|
|
||||||
MYCALL: p?.callsign ?? '', MYNAME: p?.op_name ?? p?.operator ?? '',
|
|
||||||
MYSTREET: p?.my_street ?? '', MYZIP: p?.my_postal_code ?? '',
|
|
||||||
MYCITY: p?.my_city ?? '', MYCOUNTRY: p?.my_country ?? '',
|
|
||||||
};
|
|
||||||
setMyVars(mv);
|
|
||||||
setMyAddress([mv.MYNAME && `${mv.MYNAME} · ${mv.MYCALL}` || mv.MYCALL, mv.MYSTREET,
|
|
||||||
[mv.MYZIP, mv.MYCITY].filter(Boolean).join(' '), mv.MYCOUNTRY]
|
|
||||||
.map((x) => String(x ?? '').trim()).filter(Boolean).join('\n'));
|
|
||||||
} catch (e: any) { setError(String(e?.message ?? e)); }
|
|
||||||
setLoading(false);
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!open) return;
|
|
||||||
setStep('pick'); setPages({ qso: [], addr: [], ret: [] }); setPdfPath(''); setMarked(0);
|
|
||||||
void load();
|
|
||||||
}, [open, load]);
|
|
||||||
|
|
||||||
const patchStation = (i: number, p: Partial<Station>) =>
|
|
||||||
setStations((l) => l.map((s, j) => (j === i ? { ...s, ...p } : s)));
|
|
||||||
|
|
||||||
async function fetchAddress(i: number) {
|
|
||||||
const s = stations[i];
|
|
||||||
const target = s.routing === 'via' && s.via.trim() ? s.via.trim().toUpperCase() : s.call;
|
|
||||||
patchStation(i, { fetching: true });
|
|
||||||
try {
|
|
||||||
const r: any = await LookupCallsignFresh(target, '');
|
|
||||||
// A postal address needs a STREET (or at least a name and a town). A
|
|
||||||
// lookup that fell back to cty.dat answers with a country alone —
|
|
||||||
// overwriting a reviewed address with a bare country is strictly worse
|
|
||||||
// than saying nothing was found, and losing the address is what was
|
|
||||||
// reported.
|
|
||||||
const street = String(r?.address ?? '').trim();
|
|
||||||
if (!street && !(String(r?.name ?? '').trim() && String(r?.qth ?? '').trim())) {
|
|
||||||
patchStation(i, { fetching: false });
|
|
||||||
setError(t('lpr.noAddress', { call: target }));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const lines = dedupeLines([
|
|
||||||
r?.name, street,
|
|
||||||
[r?.zip, r?.qth].filter(Boolean).join(' '),
|
|
||||||
r?.country,
|
|
||||||
]);
|
|
||||||
patchStation(i, {
|
|
||||||
address: lines.join('\n'), fetching: false,
|
|
||||||
addrFor: target === s.call ? 'dx' : 'mgr',
|
|
||||||
});
|
|
||||||
} catch (e: any) {
|
|
||||||
patchStation(i, { fetching: false });
|
|
||||||
setError(String(e?.message ?? e));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const picked = stations.filter((s) => s.checked);
|
|
||||||
const needAddress = picked.filter((s) => s.routing !== 'bureau');
|
|
||||||
|
|
||||||
// ── step 3: build the pages ───────────────────────────────────────────
|
|
||||||
async function buildPages() {
|
|
||||||
setBuilding(true); setError('');
|
|
||||||
try {
|
|
||||||
const getTpl = async (id: number): Promise<{ tpl: LabelTemplate; stock: LabelStock } | null> => {
|
|
||||||
if (!id) return null;
|
|
||||||
const tpl = JSON.parse(await LabelGetTemplate(id)) as LabelTemplate;
|
|
||||||
const stock = stocks.find((x) => x.id === tpl.stock_id) ?? stocks[0];
|
|
||||||
return stock ? { tpl, stock } : null;
|
|
||||||
};
|
|
||||||
const out = { qso: [] as Page[], addr: [] as Page[], ret: [] as Page[] };
|
|
||||||
const page = (png: string, stock: LabelStock): Page => ({ png, w_mm: stock.w_mm, h_mm: stock.h_mm });
|
|
||||||
if (doQso) {
|
|
||||||
const got = await getTpl(qsoTplId);
|
|
||||||
if (!got) throw new Error(t('lpr.noQsoTpl'));
|
|
||||||
const table = got.tpl.elements.find((e) => e.type === 'qso_table');
|
|
||||||
const per = Math.max(1, table?.rows_max ?? 4);
|
|
||||||
for (const s of picked) {
|
|
||||||
const vars = { CALL: s.call, NAME: s.qsos[0]?.name ?? '', QTH: s.qsos[0]?.qth ?? '', COUNTRY: s.qsos[0]?.country ?? '', VIA: s.via, ...myVars };
|
|
||||||
for (let i = 0; i < s.qsos.length; i += per) {
|
|
||||||
out.qso.push(page(rasterize(got.tpl, got.stock, { vars, qsos: s.qsos.slice(i, i + per).map(toSample) }), got.stock));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (doAddr) {
|
|
||||||
const got = await getTpl(addrTplId);
|
|
||||||
if (!got) throw new Error(t('lpr.noAddrTpl'));
|
|
||||||
for (const s of needAddress) {
|
|
||||||
// The REVIEWED text wins: the template's address block prints these
|
|
||||||
// lines verbatim — that is what "check the address first" means.
|
|
||||||
const tpl: LabelTemplate = {
|
|
||||||
...got.tpl,
|
|
||||||
elements: got.tpl.elements.map((e) =>
|
|
||||||
e.type === 'addr_block' ? { ...e, lines: s.address.split('\n') } : e),
|
|
||||||
};
|
|
||||||
const vars = { CALL: s.call, VIA: s.via, ...myVars };
|
|
||||||
out.addr.push(page(rasterize(tpl, got.stock, { vars, qsos: [] }), got.stock));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (doReturn) {
|
|
||||||
const got = await getTpl(retTplId);
|
|
||||||
if (!got) throw new Error(t('lpr.noAddrTpl'));
|
|
||||||
const tpl: LabelTemplate = {
|
|
||||||
...got.tpl,
|
|
||||||
elements: got.tpl.elements.map((e) =>
|
|
||||||
e.type === 'addr_block' ? { ...e, lines: myAddress.split('\n') } : e),
|
|
||||||
};
|
|
||||||
// One per envelope that needs a return slip — the direct/via ones.
|
|
||||||
const n = Math.max(1, needAddress.length);
|
|
||||||
const one = page(rasterize(tpl, got.stock, { vars: { ...myVars, CALL: myVars.MYCALL }, qsos: [] }), got.stock);
|
|
||||||
for (let i = 0; i < n; i++) out.ret.push(one);
|
|
||||||
}
|
|
||||||
setPages(out);
|
|
||||||
} catch (e: any) { setError(String(e?.message ?? e)); }
|
|
||||||
setBuilding(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
const allPages = [...pages.qso, ...pages.addr, ...pages.ret];
|
|
||||||
|
|
||||||
async function openPdf() {
|
|
||||||
try {
|
|
||||||
const path = await LabelOpenPDF(allPages as any);
|
|
||||||
if (path) setPdfPath(path as string);
|
|
||||||
} catch (e: any) { setError(String(e?.message ?? e)); }
|
|
||||||
}
|
|
||||||
|
|
||||||
async function markSent() {
|
|
||||||
try {
|
|
||||||
const date = markDate.replace(/-/g, '');
|
|
||||||
let n = 0;
|
|
||||||
const groups: Array<[Station[], string]> = [
|
|
||||||
[picked.filter((s) => s.routing === 'bureau'), 'B'],
|
|
||||||
[picked.filter((s) => s.routing !== 'bureau'), 'D'],
|
|
||||||
];
|
|
||||||
for (const [list, via] of groups) {
|
|
||||||
const ids = list.flatMap((s) => s.qsos.map((q) => q.id));
|
|
||||||
if (ids.length === 0) continue;
|
|
||||||
n += (await BulkUpdateQSL(ids, { sent_status: 'Y', sent_date: date, via, rcvd_status: '', rcvd_date: '', rcvd_via: '', notes: '', comment: '' } as any)) as number;
|
|
||||||
}
|
|
||||||
setMarked(n);
|
|
||||||
} catch (e: any) { setError(String(e?.message ?? e)); }
|
|
||||||
}
|
|
||||||
|
|
||||||
const kindBlock = (kind: 'qso' | 'addr' | 'ret', title: string) => {
|
|
||||||
const pg = pages[kind];
|
|
||||||
if (pg.length === 0) return null;
|
|
||||||
return (
|
|
||||||
<div className="rounded-lg border border-border p-3 space-y-2">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<span className="text-sm font-semibold">{title}</span>
|
|
||||||
<span className="text-xs text-muted-foreground">{t('lpr.pageCount', { n: pg.length })}</span>
|
|
||||||
</div>
|
|
||||||
<div className="flex gap-2 overflow-x-auto pb-1">
|
|
||||||
{pg.slice(0, 8).map((p, i) => (
|
|
||||||
<img key={i} src={p.png} className="h-20 border border-border rounded-sm bg-white shrink-0" />
|
|
||||||
))}
|
|
||||||
{pg.length > 8 && <span className="text-xs text-muted-foreground self-center">+{pg.length - 8}</span>}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
if (!open) return null;
|
|
||||||
const sumQsos = picked.reduce((a, s) => a + s.qsos.length, 0);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="fixed inset-0 z-50 bg-black/60 flex items-center justify-center p-4">
|
|
||||||
<div className="bg-card border border-border rounded-xl shadow-2xl w-full max-w-5xl h-[90vh] flex flex-col overflow-hidden">
|
|
||||||
<div className="flex items-center gap-3 px-4 py-2.5 border-b border-border shrink-0">
|
|
||||||
<Printer className="size-4 text-primary" />
|
|
||||||
<span className="font-semibold text-sm">{t('lpr.title')}</span>
|
|
||||||
<span className="text-xs text-muted-foreground">
|
|
||||||
{step === 'pick' ? t('lpr.step1') : step === 'review' ? t('lpr.step2') : t('lpr.step3')}
|
|
||||||
</span>
|
|
||||||
<div className="flex-1" />
|
|
||||||
<Button variant="ghost" size="sm" className="h-8" onClick={onClose}><X className="size-4" /></Button>
|
|
||||||
</div>
|
|
||||||
{error && <div className="px-4 py-1.5 text-xs text-danger border-b border-border/60">{error}</div>}
|
|
||||||
|
|
||||||
<div className="flex-1 min-h-0 overflow-y-auto p-4">
|
|
||||||
{loading ? (
|
|
||||||
<div className="flex items-center justify-center h-full text-muted-foreground gap-2">
|
|
||||||
<Loader2 className="size-4 animate-spin" /> …
|
|
||||||
</div>
|
|
||||||
) : step === 'pick' ? (
|
|
||||||
stations.length === 0 ? (
|
|
||||||
<div className="text-sm text-muted-foreground text-center pt-16 max-w-md mx-auto leading-relaxed">
|
|
||||||
{t('lpr.emptyQueue')}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-1">
|
|
||||||
<div className="flex items-center gap-2 pb-1 text-xs text-muted-foreground">
|
|
||||||
<button type="button" className="underline underline-offset-2" onClick={() => setStations((l) => l.map((s) => ({ ...s, checked: true })))}>{t('lpr.all')}</button>
|
|
||||||
<button type="button" className="underline underline-offset-2" onClick={() => setStations((l) => l.map((s) => ({ ...s, checked: false })))}>{t('lpr.none')}</button>
|
|
||||||
<div className="flex-1" />
|
|
||||||
<span>{t('lpr.pickSummary', { s: picked.length, q: sumQsos })}</span>
|
|
||||||
</div>
|
|
||||||
{stations.map((s, i) => (
|
|
||||||
<label key={s.call} className="flex items-center gap-2.5 rounded-md border border-border/60 px-2.5 py-1.5 text-sm cursor-pointer hover:bg-muted/40">
|
|
||||||
<Checkbox checked={s.checked} onCheckedChange={(c) => patchStation(i, { checked: !!c })} />
|
|
||||||
<span className="font-mono font-bold w-28">{s.call}</span>
|
|
||||||
<span className="text-xs text-muted-foreground w-16">{s.qsos.length} QSO{s.qsos.length > 1 ? 's' : ''}</span>
|
|
||||||
<span className="text-xs text-muted-foreground flex-1 truncate">
|
|
||||||
{s.qsos.map((q) => `${q.band ?? ''} ${q.mode ?? ''}`).slice(0, 5).join(' · ')}
|
|
||||||
</span>
|
|
||||||
<span className="text-xs text-muted-foreground truncate max-w-40">{s.qsos[0]?.country ?? ''}</span>
|
|
||||||
{s.via && <span className="text-[10px] px-1.5 rounded bg-info-muted text-info-muted-foreground">via {s.via}</span>}
|
|
||||||
</label>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
)
|
|
||||||
) : step === 'review' ? (
|
|
||||||
<div className="space-y-2">
|
|
||||||
{picked.map((s) => {
|
|
||||||
const i = stations.indexOf(s);
|
|
||||||
return (
|
|
||||||
<div key={s.call} className="rounded-lg border border-border p-2.5 flex gap-3">
|
|
||||||
<div className="w-64 shrink-0 space-y-1.5">
|
|
||||||
<div className="font-mono font-bold">{s.call}
|
|
||||||
<span className="ml-2 text-xs font-normal text-muted-foreground">{s.qsos.length} QSO{s.qsos.length > 1 ? 's' : ''}</span>
|
|
||||||
</div>
|
|
||||||
<Select value={s.routing} onValueChange={(v) => {
|
|
||||||
const routing = v as Routing;
|
|
||||||
const patch: Partial<Station> = { routing };
|
|
||||||
if (s.addrFor !== 'user') {
|
|
||||||
// The box follows the routing while the operator has
|
|
||||||
// not typed in it: via → empty (fetch the manager),
|
|
||||||
// direct → the DX's own prefill.
|
|
||||||
patch.address = routing === 'via' ? '' : initialAddress(s.qsos[0]);
|
|
||||||
patch.addrFor = routing === 'via' ? 'none' : 'dx';
|
|
||||||
}
|
|
||||||
patchStation(i, patch);
|
|
||||||
}}>
|
|
||||||
<SelectTrigger className="h-7 text-xs"><SelectValue /></SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="direct">{t('lpr.direct')}</SelectItem>
|
|
||||||
<SelectItem value="bureau">{t('lpr.bureau')}</SelectItem>
|
|
||||||
<SelectItem value="via">{t('lpr.viaMgr')}</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
{s.routing === 'via' && (
|
|
||||||
<Input className="h-7 text-xs font-mono uppercase" placeholder={t('lpr.mgrPh')}
|
|
||||||
value={s.via} onChange={(ev) => patchStation(i, { via: ev.target.value })} />
|
|
||||||
)}
|
|
||||||
{s.routing !== 'bureau' && (
|
|
||||||
<Button size="sm" variant="outline" className="h-7 text-xs w-full"
|
|
||||||
disabled={s.fetching}
|
|
||||||
onClick={() => void fetchAddress(i)}>
|
|
||||||
{s.fetching ? <Loader2 className="size-3 animate-spin" /> : <RefreshCw className="size-3" />}
|
|
||||||
{t('lpr.fetchQrz')}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{s.routing === 'bureau' ? (
|
|
||||||
<div className="flex-1 text-xs text-muted-foreground self-center">{t('lpr.bureauHint')}</div>
|
|
||||||
) : (
|
|
||||||
<textarea
|
|
||||||
className={cn('flex-1 rounded-md border bg-background px-2 py-1 text-sm font-mono',
|
|
||||||
s.address.trim() ? 'border-input' : 'border-danger')}
|
|
||||||
rows={4}
|
|
||||||
placeholder={s.routing === 'via' ? t('lpr.mgrAddressPh') : t('lpr.addressPh')}
|
|
||||||
value={s.address}
|
|
||||||
onChange={(ev) => patchStation(i, { address: ev.target.value, addrFor: 'user' })} />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-3">
|
|
||||||
{/* what to print */}
|
|
||||||
<div className="rounded-lg border border-border p-3 space-y-2">
|
|
||||||
<div className="text-sm font-semibold">{t('lpr.whatToPrint')}</div>
|
|
||||||
{([
|
|
||||||
['qso', doQso, setDoQso, qsoTplId, setQsoTplId, 'qso', t('lpr.kQso')],
|
|
||||||
['addr', doAddr, setDoAddr, addrTplId, setAddrTplId, 'address', t('lpr.kAddr')],
|
|
||||||
['ret', doReturn, setDoReturn, retTplId, setRetTplId, 'address', t('lpr.kRet')],
|
|
||||||
] as const).map(([key, on, setOn, tplId, setTplId, kind, label]) => (
|
|
||||||
<div key={key} className="flex items-center gap-2">
|
|
||||||
<label className="flex items-center gap-1.5 text-sm cursor-pointer w-64">
|
|
||||||
<Checkbox checked={on} onCheckedChange={(c) => (setOn as any)(!!c)} /> {label}
|
|
||||||
</label>
|
|
||||||
<Select value={String(tplId || '')} onValueChange={(v) => (setTplId as any)(parseInt(v, 10))}>
|
|
||||||
<SelectTrigger className="h-7 text-xs w-72"><SelectValue placeholder={t('lpr.pickTpl')} /></SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
{tpls.filter((x) => x.kind === kind).map((x) => (
|
|
||||||
<SelectItem key={x.id} value={String(x.id)}>{x.name}</SelectItem>
|
|
||||||
))}
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
{doReturn && (
|
|
||||||
<div className="flex items-start gap-2 pl-6">
|
|
||||||
<span className="text-xs text-muted-foreground pt-1 w-24">{t('lpr.myAddress')}</span>
|
|
||||||
<textarea className="flex-1 max-w-96 rounded-md border border-input bg-background px-2 py-1 text-xs font-mono" rows={4}
|
|
||||||
value={myAddress} onChange={(ev) => setMyAddress(ev.target.value)} />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<Button size="sm" className="h-8" onClick={() => void buildPages()} disabled={building || (!doQso && !doAddr && !doReturn)}>
|
|
||||||
{building ? <Loader2 className="size-3.5 animate-spin" /> : <RefreshCw className="size-3.5" />}
|
|
||||||
{t('lpr.build')}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
{kindBlock('qso', t('lpr.kQso'))}
|
|
||||||
{kindBlock('addr', t('lpr.kAddr'))}
|
|
||||||
{kindBlock('ret', t('lpr.kRet'))}
|
|
||||||
{allPages.length > 0 && (
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<Button size="sm" className="h-8" onClick={() => void openPdf()}>
|
|
||||||
<Printer className="size-3.5" /> {t('lpr.openPdf', { n: allPages.length })}
|
|
||||||
</Button>
|
|
||||||
{pdfPath && <span className="text-xs text-success flex items-center gap-1"><Check className="size-3.5" />{pdfPath}</span>}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{/* mark as sent */}
|
|
||||||
{(pages.qso.length > 0 || pages.addr.length > 0) && (
|
|
||||||
<div className="rounded-lg border border-border p-3 space-y-2">
|
|
||||||
<div className="text-sm font-semibold">{t('lpr.markTitle')}</div>
|
|
||||||
<div className="text-xs text-muted-foreground">{t('lpr.markHint')}</div>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<input type="date" className="h-8 rounded-md border border-input bg-background px-2 text-xs"
|
|
||||||
value={markDate} onChange={(ev) => setMarkDate(ev.target.value)} />
|
|
||||||
<Button size="sm" className="h-8" onClick={() => void markSent()} disabled={marked > 0}>
|
|
||||||
<Check className="size-3.5" /> {t('lpr.markBtn', { n: sumQsos })}
|
|
||||||
</Button>
|
|
||||||
{marked > 0 && <span className="text-xs text-success">{t('lpr.markDone', { n: marked })}</span>}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* footer nav */}
|
|
||||||
<div className="flex items-center gap-2 px-4 py-2.5 border-t border-border shrink-0">
|
|
||||||
{step !== 'pick' && (
|
|
||||||
<Button variant="outline" size="sm" className="h-8"
|
|
||||||
onClick={() => setStep(step === 'print' ? 'review' : 'pick')}>
|
|
||||||
<ChevronLeft className="size-3.5" /> {t('lpr.back')}
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
<div className="flex-1" />
|
|
||||||
{step === 'pick' && (
|
|
||||||
<Button size="sm" className="h-8" disabled={picked.length === 0} onClick={() => setStep('review')}>
|
|
||||||
{t('lpr.next')} <ChevronRight className="size-3.5" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
{step === 'review' && (
|
|
||||||
<Button size="sm" className="h-8"
|
|
||||||
disabled={needAddress.some((s) => !s.address.trim())}
|
|
||||||
title={needAddress.some((s) => !s.address.trim()) ? t('lpr.missingAddr') : undefined}
|
|
||||||
onClick={() => setStep('print')}>
|
|
||||||
{t('lpr.next')} <ChevronRight className="size-3.5" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,190 +0,0 @@
|
|||||||
// labelRender draws a label template onto a canvas. It is THE renderer: the
|
|
||||||
// designer's preview and (later) the pages rasterised into the print PDF both
|
|
||||||
// come through here, which is what makes the preview trustworthy — there is no
|
|
||||||
// second implementation to disagree with it.
|
|
||||||
//
|
|
||||||
// The canvas is scaled so that 1 mm = `scale` px; print passes dpi/25.4, the
|
|
||||||
// preview passes whatever fits its box. All layout maths stays in mm.
|
|
||||||
|
|
||||||
import type { LabelElement, LabelSample, LabelStock, LabelTemplate } from './labelTypes';
|
|
||||||
|
|
||||||
export interface RenderData {
|
|
||||||
// Variable values for text/address elements (<CALL> → value). Missing keys
|
|
||||||
// render as the bare <NAME> so the designer can SEE an unresolved variable.
|
|
||||||
vars: Record<string, string>;
|
|
||||||
// Rows for the qso_table element.
|
|
||||||
qsos: LabelSample[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ElementBox { x: number; y: number; w: number; h: number } // mm
|
|
||||||
|
|
||||||
const PT_TO_MM = 25.4 / 72;
|
|
||||||
|
|
||||||
// resolveVars substitutes <VAR> markers, collapsing to '' only when the value
|
|
||||||
// is known-empty; unknown markers stay visible on purpose.
|
|
||||||
export function resolveVars(text: string, vars: Record<string, string>): string {
|
|
||||||
return text.replace(/<([A-Z_]+)>/g, (m, k) => (k in vars ? vars[k] : m));
|
|
||||||
}
|
|
||||||
|
|
||||||
// render draws the whole label and returns each element's bounding box in mm —
|
|
||||||
// the editor's hit-testing works off these, so a drag grabs exactly what was
|
|
||||||
// painted, table rows included.
|
|
||||||
export function render(
|
|
||||||
ctx: CanvasRenderingContext2D,
|
|
||||||
t: LabelTemplate,
|
|
||||||
stock: LabelStock,
|
|
||||||
data: RenderData,
|
|
||||||
scale: number,
|
|
||||||
): ElementBox[] {
|
|
||||||
const W = stock.w_mm, H = stock.h_mm;
|
|
||||||
ctx.save();
|
|
||||||
ctx.scale(scale, scale);
|
|
||||||
// The physical label: white, whatever the app theme — this is paper.
|
|
||||||
ctx.fillStyle = '#fff';
|
|
||||||
ctx.fillRect(0, 0, W, H);
|
|
||||||
ctx.fillStyle = '#000';
|
|
||||||
|
|
||||||
// The canvas thinks in mm from here on; fonts are set per element in pt and
|
|
||||||
// drawn with an unscaled-pt trick: setTransform back to px for text quality.
|
|
||||||
const boxes: ElementBox[] = [];
|
|
||||||
for (const e of t.elements) {
|
|
||||||
boxes.push(drawElement(ctx, e, t, data, scale));
|
|
||||||
}
|
|
||||||
ctx.restore();
|
|
||||||
return boxes;
|
|
||||||
}
|
|
||||||
|
|
||||||
// drawMargins paints the unprintable border as a dashed guide — editor only,
|
|
||||||
// never part of a print rasterisation.
|
|
||||||
export function drawMargins(ctx: CanvasRenderingContext2D, stock: LabelStock, scale: number): void {
|
|
||||||
ctx.save();
|
|
||||||
ctx.scale(scale, scale);
|
|
||||||
ctx.strokeStyle = 'rgba(80,140,255,0.55)';
|
|
||||||
ctx.lineWidth = 0.15;
|
|
||||||
ctx.setLineDash([1.2, 1.2]);
|
|
||||||
ctx.strokeRect(
|
|
||||||
stock.margin_left_mm, stock.margin_top_mm,
|
|
||||||
stock.w_mm - stock.margin_left_mm - stock.margin_right_mm,
|
|
||||||
stock.h_mm - stock.margin_top_mm - stock.margin_bottom_mm,
|
|
||||||
);
|
|
||||||
ctx.restore();
|
|
||||||
}
|
|
||||||
|
|
||||||
function drawText(
|
|
||||||
ctx: CanvasRenderingContext2D, text: string, xMm: number, yTopMm: number,
|
|
||||||
wMm: number | undefined, sizePt: number, scale: number,
|
|
||||||
opts: { bold?: boolean; italic?: boolean; align?: string; face?: string },
|
|
||||||
): number {
|
|
||||||
// Text is drawn in PX space (resetting the mm scale) so the browser rasterises
|
|
||||||
// the font at device resolution instead of scaling a 1-mm-tall glyph up.
|
|
||||||
const hMm = sizePt * PT_TO_MM;
|
|
||||||
ctx.save();
|
|
||||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
|
||||||
// The font is specified in px = (pt → mm) × scale, so a 10 pt line measures
|
|
||||||
// exactly 10 pt on the printed label whatever the preview zoom is.
|
|
||||||
ctx.font = `${opts.italic ? 'italic ' : ''}${opts.bold ? 'bold ' : ''}${hMm * scale}px ${opts.face && opts.face.trim() ? opts.face : 'Arial, Helvetica, sans-serif'}`;
|
|
||||||
ctx.fillStyle = '#000';
|
|
||||||
ctx.textBaseline = 'top';
|
|
||||||
let x = xMm * scale;
|
|
||||||
if (wMm && opts.align === 'center') {
|
|
||||||
ctx.textAlign = 'center';
|
|
||||||
x = (xMm + wMm / 2) * scale;
|
|
||||||
} else if (wMm && opts.align === 'right') {
|
|
||||||
ctx.textAlign = 'right';
|
|
||||||
x = (xMm + wMm) * scale;
|
|
||||||
} else {
|
|
||||||
ctx.textAlign = 'left';
|
|
||||||
}
|
|
||||||
ctx.fillText(text, x, yTopMm * scale);
|
|
||||||
ctx.restore();
|
|
||||||
return hMm;
|
|
||||||
}
|
|
||||||
|
|
||||||
function drawElement(
|
|
||||||
ctx: CanvasRenderingContext2D, e: LabelElement, t: LabelTemplate,
|
|
||||||
data: RenderData, scale: number,
|
|
||||||
): ElementBox {
|
|
||||||
switch (e.type) {
|
|
||||||
case 'text': {
|
|
||||||
const size = e.size_pt || 9;
|
|
||||||
const text = resolveVars(e.text ?? '', data.vars);
|
|
||||||
drawText(ctx, text, e.x_mm, e.y_mm, e.w_mm, size, scale,
|
|
||||||
{ bold: e.bold, italic: e.italic, align: e.align, face: t.font });
|
|
||||||
const h = size * PT_TO_MM * 1.25;
|
|
||||||
return { x: e.x_mm, y: e.y_mm, w: e.w_mm || Math.max(20, text.length * size * PT_TO_MM * 0.55), h };
|
|
||||||
}
|
|
||||||
case 'line': {
|
|
||||||
const th = e.thickness_mm || 0.3;
|
|
||||||
ctx.fillStyle = '#000';
|
|
||||||
ctx.fillRect(e.x_mm, e.y_mm, e.w_mm || 10, th);
|
|
||||||
// A hairline is a 0.3 mm target nobody can grab; the box pads it.
|
|
||||||
return { x: e.x_mm, y: e.y_mm - 0.8, w: e.w_mm || 10, h: th + 1.6 };
|
|
||||||
}
|
|
||||||
case 'addr_block': {
|
|
||||||
const size = e.size_pt || 11;
|
|
||||||
const gap = e.line_gap_mm ?? 1.5;
|
|
||||||
// Collapse-empty is the point of the block: a missing street must pull
|
|
||||||
// the city UP, not leave a hole in the middle of an address.
|
|
||||||
const lines = (e.lines ?? [])
|
|
||||||
.map((l) => resolveVars(l, data.vars).trim())
|
|
||||||
.filter((l) => l !== '');
|
|
||||||
let y = e.y_mm;
|
|
||||||
let maxW = 0;
|
|
||||||
for (const l of lines) {
|
|
||||||
const h = drawText(ctx, l, e.x_mm, y, undefined, size, scale,
|
|
||||||
{ bold: e.bold, italic: e.italic, face: t.font });
|
|
||||||
y += h + gap;
|
|
||||||
maxW = Math.max(maxW, l.length * size * PT_TO_MM * 0.55);
|
|
||||||
}
|
|
||||||
return { x: e.x_mm, y: e.y_mm, w: Math.max(20, maxW), h: Math.max(4, y - e.y_mm) };
|
|
||||||
}
|
|
||||||
case 'qso_table': {
|
|
||||||
const cols = e.columns ?? [];
|
|
||||||
const size = e.size_pt || 7.5;
|
|
||||||
const rowH = e.row_h_mm || 4;
|
|
||||||
const wTot = cols.reduce((a, c) => a + c.w_mm, 0);
|
|
||||||
let y = e.y_mm;
|
|
||||||
if (e.header) {
|
|
||||||
let x = e.x_mm;
|
|
||||||
for (const c of cols) {
|
|
||||||
drawText(ctx, c.label, x + 0.6, y + (rowH - size * PT_TO_MM) / 2, c.w_mm - 1.2, size, scale,
|
|
||||||
{ bold: true, align: c.align, face: t.font });
|
|
||||||
x += c.w_mm;
|
|
||||||
}
|
|
||||||
// Rule under the header, not a full grid: on a 29 mm label the grid IS
|
|
||||||
// the noise.
|
|
||||||
ctx.fillStyle = '#000';
|
|
||||||
ctx.fillRect(e.x_mm, y + rowH - 0.25, wTot, 0.25);
|
|
||||||
y += rowH;
|
|
||||||
}
|
|
||||||
const rows = data.qsos.slice(0, e.rows_max || 4);
|
|
||||||
for (const q of rows) {
|
|
||||||
let x = e.x_mm;
|
|
||||||
for (const c of cols) {
|
|
||||||
const v = String((q as any)[c.field] ?? '');
|
|
||||||
drawText(ctx, v, x + 0.6, y + (rowH - size * PT_TO_MM) / 2, c.w_mm - 1.2, size, scale,
|
|
||||||
{ align: c.align, face: t.font });
|
|
||||||
x += c.w_mm;
|
|
||||||
}
|
|
||||||
y += rowH;
|
|
||||||
}
|
|
||||||
return { x: e.x_mm, y: e.y_mm, w: wTot, h: y - e.y_mm };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return { x: e.x_mm, y: e.y_mm, w: 10, h: 4 };
|
|
||||||
}
|
|
||||||
|
|
||||||
// rasterize renders one label at the stock's dpi and returns a PNG data URL —
|
|
||||||
// the pages handed to the PDF exporter. Same renderer as the preview, only the
|
|
||||||
// scale changes, which is the whole guarantee of the feature.
|
|
||||||
export function rasterize(
|
|
||||||
t: LabelTemplate, stock: LabelStock, data: RenderData,
|
|
||||||
): string {
|
|
||||||
const scale = (stock.dpi || 300) / 25.4; // px per mm
|
|
||||||
const cv = document.createElement('canvas');
|
|
||||||
cv.width = Math.round(stock.w_mm * scale);
|
|
||||||
cv.height = Math.round(stock.h_mm * scale);
|
|
||||||
const ctx = cv.getContext('2d')!;
|
|
||||||
render(ctx, t, stock, data, scale);
|
|
||||||
return cv.toDataURL('image/png');
|
|
||||||
}
|
|
||||||
@@ -1,118 +0,0 @@
|
|||||||
// TypeScript mirror of the label template schema (v1) defined in
|
|
||||||
// internal/labels/labels.go. Documents cross the Wails boundary as JSON
|
|
||||||
// strings; these types are the frontend's contract with that schema.
|
|
||||||
//
|
|
||||||
// Everything is in MILLIMETRES — pixels only exist inside labelRender, at the
|
|
||||||
// stock's dpi. See the Go package comment for why.
|
|
||||||
|
|
||||||
export interface LabelStock {
|
|
||||||
id?: number;
|
|
||||||
name: string;
|
|
||||||
w_mm: number;
|
|
||||||
h_mm: number;
|
|
||||||
margin_top_mm: number;
|
|
||||||
margin_right_mm: number;
|
|
||||||
margin_bottom_mm: number;
|
|
||||||
margin_left_mm: number;
|
|
||||||
dpi: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LabelColumn {
|
|
||||||
field: string;
|
|
||||||
label: string;
|
|
||||||
w_mm: number;
|
|
||||||
align?: 'left' | 'center' | 'right';
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LabelElement {
|
|
||||||
type: 'text' | 'line' | 'qso_table' | 'addr_block';
|
|
||||||
x_mm: number;
|
|
||||||
y_mm: number;
|
|
||||||
w_mm?: number;
|
|
||||||
// text
|
|
||||||
text?: string;
|
|
||||||
size_pt?: number;
|
|
||||||
bold?: boolean;
|
|
||||||
italic?: boolean;
|
|
||||||
align?: 'left' | 'center' | 'right';
|
|
||||||
// line
|
|
||||||
thickness_mm?: number;
|
|
||||||
// qso_table
|
|
||||||
columns?: LabelColumn[];
|
|
||||||
rows_max?: number;
|
|
||||||
row_h_mm?: number;
|
|
||||||
header?: boolean;
|
|
||||||
// addr_block
|
|
||||||
lines?: string[];
|
|
||||||
line_gap_mm?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LabelTemplate {
|
|
||||||
version: 1;
|
|
||||||
kind: 'qso' | 'address';
|
|
||||||
name?: string;
|
|
||||||
stock_id: number;
|
|
||||||
font?: string;
|
|
||||||
elements: LabelElement[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface LabelSample {
|
|
||||||
callsign: string; qso_date: string; time_on: string; band: string;
|
|
||||||
freq: string; mode: string; rst_sent: string; rst_rcvd: string;
|
|
||||||
name: string; qth: string; country: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The QSO-table columns the designer offers, with default widths that fit their
|
|
||||||
// content at 8 pt — the operator adjusts from there against real data.
|
|
||||||
export const TABLE_FIELDS: { field: string; label: string; w_mm: number }[] = [
|
|
||||||
{ field: 'qso_date', label: 'Date', w_mm: 17 },
|
|
||||||
{ field: 'time_on', label: 'UTC', w_mm: 10 },
|
|
||||||
{ field: 'band', label: 'Band', w_mm: 10 },
|
|
||||||
{ field: 'freq', label: 'MHz', w_mm: 13 },
|
|
||||||
{ field: 'mode', label: 'Mode', w_mm: 11 },
|
|
||||||
{ field: 'rst_sent', label: 'RST', w_mm: 9 },
|
|
||||||
{ field: 'rst_rcvd', label: 'RST rx', w_mm: 9 },
|
|
||||||
];
|
|
||||||
|
|
||||||
// The variables a text or address element may carry. Resolution at PRINT time
|
|
||||||
// uses the real QSO/profile; the designer resolves them against the sample so
|
|
||||||
// the preview reads like a finished label.
|
|
||||||
export const LABEL_VARS = [
|
|
||||||
'CALL', 'NAME', 'QTH', 'COUNTRY', 'VIA',
|
|
||||||
'STREET', 'ZIP', 'CITY', 'STATE',
|
|
||||||
'MYCALL', 'MYNAME', 'MYSTREET', 'MYZIP', 'MYCITY', 'MYCOUNTRY',
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
// Starter documents for a fresh template — a usable label, not a blank page:
|
|
||||||
// an empty canvas asks the operator to invent the feature, a finished-looking
|
|
||||||
// starter only asks them to adjust it.
|
|
||||||
export function starterTemplate(kind: 'qso' | 'address', stock: LabelStock): LabelTemplate {
|
|
||||||
const w = stock.w_mm - stock.margin_left_mm - stock.margin_right_mm;
|
|
||||||
const x = stock.margin_left_mm;
|
|
||||||
if (kind === 'qso') {
|
|
||||||
return {
|
|
||||||
version: 1, kind, stock_id: stock.id ?? 0,
|
|
||||||
elements: [
|
|
||||||
{ type: 'text', x_mm: x, y_mm: stock.margin_top_mm + 1, w_mm: w, text: 'To Radio <CALL>', size_pt: 10, bold: true },
|
|
||||||
{ type: 'line', x_mm: x, y_mm: stock.margin_top_mm + 6.2, w_mm: w, thickness_mm: 0.3 },
|
|
||||||
{
|
|
||||||
type: 'qso_table', x_mm: x, y_mm: stock.margin_top_mm + 7.5, w_mm: w,
|
|
||||||
rows_max: Math.max(1, Math.min(5, Math.floor((stock.h_mm - stock.margin_top_mm - stock.margin_bottom_mm - 12) / 4))),
|
|
||||||
row_h_mm: 4, header: true, size_pt: 7.5,
|
|
||||||
columns: TABLE_FIELDS.slice(0, 6).map((c) => ({ ...c })),
|
|
||||||
} as LabelElement,
|
|
||||||
{ type: 'text', x_mm: x, y_mm: stock.h_mm - stock.margin_bottom_mm - 4, w_mm: w, text: 'PSE QSL · 73 de <MYCALL>', size_pt: 8 },
|
|
||||||
],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
version: 1, kind, stock_id: stock.id ?? 0,
|
|
||||||
elements: [
|
|
||||||
{
|
|
||||||
type: 'addr_block', x_mm: x + 2, y_mm: stock.margin_top_mm + 3,
|
|
||||||
lines: ['<NAME> · <CALL>', '<STREET>', '<ZIP> <CITY>', '<COUNTRY>'],
|
|
||||||
size_pt: 11, line_gap_mm: 1.6,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
// IARU band plans, by region.
|
||||||
|
//
|
||||||
|
// The band maps used to carry one hard-coded table — Region 1's — so a US or
|
||||||
|
// Australian operator saw 40 m stop at 7200 while stations sat spotted at 7250,
|
||||||
|
// and the SSB wash started 25 kHz early. The region is a station-level fact the
|
||||||
|
// operator states once (Settings → General); everything drawing a band edge or
|
||||||
|
// a mode segment reads it from here.
|
||||||
|
//
|
||||||
|
// The tables are deliberately coarse: a band map's wash is CONTEXT, not a
|
||||||
|
// regulatory chart. Only the segments that differ between regions in ways an
|
||||||
|
// operator notices are split out; national fine print (US licence classes,
|
||||||
|
// beacon slots) does not belong in a background tint.
|
||||||
|
import { writeUiPref } from '@/lib/uiPref';
|
||||||
|
|
||||||
|
export type IaruRegion = 1 | 2 | 3;
|
||||||
|
export const KEY_IARU_REGION = 'opslog.iaruRegion';
|
||||||
|
|
||||||
|
export function iaruRegion(): IaruRegion {
|
||||||
|
try {
|
||||||
|
const v = localStorage.getItem(KEY_IARU_REGION);
|
||||||
|
return v === '2' ? 2 : v === '3' ? 3 : 1;
|
||||||
|
} catch { return 1; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setIaruRegion(r: IaruRegion): void {
|
||||||
|
writeUiPref(KEY_IARU_REGION, String(r));
|
||||||
|
listeners.forEach((l) => l());
|
||||||
|
}
|
||||||
|
|
||||||
|
// The band maps capture the plan inside their render, so a change must reach
|
||||||
|
// them the way the distance unit reaches the grids.
|
||||||
|
const listeners = new Set<() => void>();
|
||||||
|
export function subscribeIaruRegion(fn: () => void): () => void {
|
||||||
|
listeners.add(fn);
|
||||||
|
return () => { listeners.delete(fn); };
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SegMode = 'cw' | 'digi' | 'phone';
|
||||||
|
type Seg = [number, number, SegMode];
|
||||||
|
|
||||||
|
interface Plan {
|
||||||
|
ranges: Record<string, [number, number]>;
|
||||||
|
segments: Record<string, Seg[]>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Region 1 — Europe / Africa / Middle East / northern Asia. The baseline the
|
||||||
|
// other two override.
|
||||||
|
const R1: Plan = {
|
||||||
|
ranges: {
|
||||||
|
'160m': [1800, 2000], '80m': [3500, 3800], '60m': [5350, 5450],
|
||||||
|
'40m': [7000, 7200], '30m': [10100, 10150], '20m': [14000, 14350],
|
||||||
|
'17m': [18068, 18168], '15m': [21000, 21450], '12m': [24890, 24990],
|
||||||
|
'10m': [28000, 29700], '6m': [50000, 50500], '4m': [70000, 70500],
|
||||||
|
'2m': [144000, 146000], '70cm': [430000, 440000],
|
||||||
|
},
|
||||||
|
segments: {
|
||||||
|
'160m': [[1800, 1838, 'cw'], [1838, 1840, 'digi'], [1840, 2000, 'phone']],
|
||||||
|
'80m': [[3500, 3580, 'cw'], [3580, 3600, 'digi'], [3600, 3800, 'phone']],
|
||||||
|
'60m': [[5350, 5450, 'phone']],
|
||||||
|
'40m': [[7000, 7040, 'cw'], [7040, 7100, 'digi'], [7100, 7200, 'phone']],
|
||||||
|
'30m': [[10100, 10130, 'cw'], [10130, 10150, 'digi']],
|
||||||
|
'20m': [[14000, 14070, 'cw'], [14070, 14100, 'digi'], [14100, 14350, 'phone']],
|
||||||
|
'17m': [[18068, 18095, 'cw'], [18095, 18110, 'digi'], [18110, 18168, 'phone']],
|
||||||
|
'15m': [[21000, 21070, 'cw'], [21070, 21150, 'digi'], [21150, 21450, 'phone']],
|
||||||
|
'12m': [[24890, 24915, 'cw'], [24915, 24940, 'digi'], [24940, 24990, 'phone']],
|
||||||
|
'10m': [[28000, 28070, 'cw'], [28070, 28300, 'digi'], [28300, 29700, 'phone']],
|
||||||
|
'6m': [[50000, 50100, 'cw'], [50100, 50500, 'phone']],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// Region 2 — the Americas. 80 m runs to 4000 and 40 m to 7300, with phone from
|
||||||
|
// 7125 (the whole point of asking the region: a KP4 ragchew on 7250 must not
|
||||||
|
// hang past the top of the map).
|
||||||
|
const R2: Plan = {
|
||||||
|
ranges: {
|
||||||
|
...R1.ranges,
|
||||||
|
'80m': [3500, 4000], '40m': [7000, 7300],
|
||||||
|
'6m': [50000, 54000], '2m': [144000, 148000], '70cm': [420000, 450000],
|
||||||
|
},
|
||||||
|
segments: {
|
||||||
|
...R1.segments,
|
||||||
|
'80m': [[3500, 3570, 'cw'], [3570, 3600, 'digi'], [3600, 4000, 'phone']],
|
||||||
|
'40m': [[7000, 7040, 'cw'], [7040, 7125, 'digi'], [7125, 7300, 'phone']],
|
||||||
|
'6m': [[50000, 50100, 'cw'], [50100, 54000, 'phone']],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// Region 3 — Asia-Pacific. 80 m to 3900; 40 m as Region 1's shape.
|
||||||
|
const R3: Plan = {
|
||||||
|
ranges: {
|
||||||
|
...R1.ranges,
|
||||||
|
'80m': [3500, 3900],
|
||||||
|
'6m': [50000, 54000], '2m': [144000, 148000], '70cm': [430000, 450000],
|
||||||
|
},
|
||||||
|
segments: {
|
||||||
|
...R1.segments,
|
||||||
|
'80m': [[3500, 3535, 'cw'], [3535, 3600, 'digi'], [3600, 3900, 'phone']],
|
||||||
|
'6m': [[50000, 50100, 'cw'], [50100, 54000, 'phone']],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
function plan(): Plan {
|
||||||
|
const r = iaruRegion();
|
||||||
|
return r === 2 ? R2 : r === 3 ? R3 : R1;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function bandRange(band: string): [number, number] | undefined {
|
||||||
|
return plan().ranges[band];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function bandSegments(band: string): Seg[] {
|
||||||
|
return plan().segments[band] ?? [];
|
||||||
|
}
|
||||||
+55
-105
File diff suppressed because one or more lines are too long
@@ -36,17 +36,17 @@ export function inferSpotMode(comment: string, freqHz: number): string {
|
|||||||
type Seg = [number, number, string];
|
type Seg = [number, number, string];
|
||||||
const segs: Seg[] = [
|
const segs: Seg[] = [
|
||||||
[1.8, 1.838, 'CW'], [1.838, 1.84, 'FT8'], [1.84, 2.0, 'SSB'],
|
[1.8, 1.838, 'CW'], [1.838, 1.84, 'FT8'], [1.84, 2.0, 'SSB'],
|
||||||
[3.5, 3.58, 'CW'], [3.573, 3.576, 'FT8'], [3.58, 3.6, 'DATA'], [3.6, 4.0, 'SSB'],
|
[3.573, 3.575, 'FT8'], [3.575, 3.578, 'FT4'], [3.5, 3.58, 'CW'], [3.58, 3.6, 'DATA'], [3.6, 4.0, 'SSB'],
|
||||||
[5.3, 5.5, 'SSB'],
|
[5.357, 5.36, 'FT8'], [5.3, 5.5, 'SSB'],
|
||||||
[7.0, 7.04, 'CW'], [7.074, 7.077, 'FT8'], [7.0475, 7.0485, 'FT4'],
|
[7.0, 7.04, 'CW'], [7.074, 7.077, 'FT8'], [7.0475, 7.0485, 'FT4'],
|
||||||
[7.04, 7.1, 'DATA'], [7.1, 7.3, 'SSB'],
|
[7.04, 7.1, 'DATA'], [7.1, 7.3, 'SSB'],
|
||||||
[10.1, 10.13, 'CW'], [10.13, 10.15, 'DATA'],
|
[10.136, 10.139, 'FT8'], [10.14, 10.143, 'FT4'], [10.1, 10.13, 'CW'], [10.13, 10.15, 'DATA'],
|
||||||
[14.0, 14.07, 'CW'], [14.074, 14.077, 'FT8'], [14.08, 14.0815, 'FT4'],
|
[14.0, 14.07, 'CW'], [14.074, 14.077, 'FT8'], [14.08, 14.0815, 'FT4'],
|
||||||
[14.07, 14.1, 'DATA'], [14.1, 14.35, 'SSB'],
|
[14.07, 14.1, 'DATA'], [14.1, 14.35, 'SSB'],
|
||||||
[18.068, 18.095, 'CW'], [18.1, 18.103, 'FT8'], [18.095, 18.11, 'DATA'], [18.11, 18.168, 'SSB'],
|
[18.1, 18.103, 'FT8'], [18.104, 18.107, 'FT4'], [18.068, 18.095, 'CW'], [18.095, 18.11, 'DATA'], [18.11, 18.168, 'SSB'],
|
||||||
[21.0, 21.07, 'CW'], [21.074, 21.077, 'FT8'], [21.14, 21.143, 'FT4'],
|
[21.0, 21.07, 'CW'], [21.074, 21.077, 'FT8'], [21.14, 21.143, 'FT4'],
|
||||||
[21.07, 21.15, 'DATA'], [21.15, 21.45, 'SSB'],
|
[21.07, 21.15, 'DATA'], [21.15, 21.45, 'SSB'],
|
||||||
[24.89, 24.915, 'CW'], [24.915, 24.917, 'FT8'], [24.915, 24.94, 'DATA'], [24.94, 24.99, 'SSB'],
|
[24.915, 24.918, 'FT8'], [24.919, 24.922, 'FT4'], [24.89, 24.915, 'CW'], [24.915, 24.94, 'DATA'], [24.94, 24.99, 'SSB'],
|
||||||
[28.0, 28.07, 'CW'], [28.074, 28.077, 'FT8'], [28.18, 28.183, 'FT4'],
|
[28.0, 28.07, 'CW'], [28.074, 28.077, 'FT8'], [28.18, 28.183, 'FT4'],
|
||||||
[28.07, 28.3, 'DATA'], [28.3, 29.7, 'SSB'],
|
[28.07, 28.3, 'DATA'], [28.3, 29.7, 'SSB'],
|
||||||
[50.0, 50.1, 'CW'], [50.313, 50.316, 'FT8'], [50.318, 50.321, 'FT4'],
|
[50.0, 50.1, 'CW'], [50.313, 50.316, 'FT8'], [50.318, 50.321, 'FT4'],
|
||||||
|
|||||||
@@ -11,7 +11,25 @@
|
|||||||
//
|
//
|
||||||
// They compose deliberately: mute what is done, light up what is not.
|
// They compose deliberately: mute what is done, light up what is not.
|
||||||
|
|
||||||
export type SpotDisplayOptions = { muteWorked: boolean; slotHighlight: boolean };
|
export type SpotDisplayOptions = {
|
||||||
|
muteWorked: boolean; slotHighlight: boolean;
|
||||||
|
// Chase switches (Settings → DX Cluster), ON by default. An operator who does
|
||||||
|
// not chase parks does not want NEW POTA shouting from every activator spot:
|
||||||
|
// off, the marker is withdrawn at the display layer — a "new band + new POTA"
|
||||||
|
// spot simply reads NEW BAND — and the reference column goes quiet. The facts
|
||||||
|
// keep being computed; only the telling stops, so ticking the box back on
|
||||||
|
// needs no rescan.
|
||||||
|
chasePota: boolean; chaseSota: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
// chasePota/chaseSota read the switches directly — for the places that show a
|
||||||
|
// REFERENCE rather than a status (the POTA and SOTA columns).
|
||||||
|
export function chasePota(): boolean {
|
||||||
|
try { return localStorage.getItem('opslog.chasePota') !== '0'; } catch { return true; }
|
||||||
|
}
|
||||||
|
export function chaseSota(): boolean {
|
||||||
|
try { return localStorage.getItem('opslog.chaseSota') !== '0'; } catch { return true; }
|
||||||
|
}
|
||||||
|
|
||||||
// Both options are withdrawn from the filter panel for now. The machinery below
|
// Both options are withdrawn from the filter panel for now. The machinery below
|
||||||
// is deliberately kept whole — it is correct and hard-won — so putting the two
|
// is deliberately kept whole — it is correct and hard-won — so putting the two
|
||||||
@@ -23,14 +41,19 @@ export type SpotDisplayOptions = { muteWorked: boolean; slotHighlight: boolean }
|
|||||||
export const SPOT_DISPLAY_OPTIONS_EXPOSED = false;
|
export const SPOT_DISPLAY_OPTIONS_EXPOSED = false;
|
||||||
|
|
||||||
export function readSpotDisplayOptions(): SpotDisplayOptions {
|
export function readSpotDisplayOptions(): SpotDisplayOptions {
|
||||||
if (!SPOT_DISPLAY_OPTIONS_EXPOSED) return { muteWorked: false, slotHighlight: false };
|
// The EXPOSED flag only withdraws the two original switches; the chase
|
||||||
|
// switches are live regardless.
|
||||||
|
if (!SPOT_DISPLAY_OPTIONS_EXPOSED) {
|
||||||
|
return { muteWorked: false, slotHighlight: false, chasePota: chasePota(), chaseSota: chaseSota() };
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
return {
|
return {
|
||||||
muteWorked: localStorage.getItem('opslog.clusterMuteWorked') === '1',
|
muteWorked: localStorage.getItem('opslog.clusterMuteWorked') === '1',
|
||||||
slotHighlight: localStorage.getItem('opslog.clusterSlotHighlight') === '1',
|
slotHighlight: localStorage.getItem('opslog.clusterSlotHighlight') === '1',
|
||||||
|
chasePota: chasePota(), chaseSota: chaseSota(),
|
||||||
};
|
};
|
||||||
} catch {
|
} catch {
|
||||||
return { muteWorked: false, slotHighlight: false };
|
return { muteWorked: false, slotHighlight: false, chasePota: true, chaseSota: true };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,6 +95,9 @@ export function applySpotDisplay<T extends Entry>(s: T, o: SpotDisplayOptions):
|
|||||||
if (o.muteWorked) {
|
if (o.muteWorked) {
|
||||||
e = { ...e, worked_call: false } as NonNullable<T>;
|
e = { ...e, worked_call: false } as NonNullable<T>;
|
||||||
}
|
}
|
||||||
|
if (!o.chasePota && e.new_pota) {
|
||||||
|
e = { ...e, new_pota: false } as NonNullable<T>;
|
||||||
|
}
|
||||||
return e;
|
return e;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -41,6 +41,9 @@ const PORTABLE_KEYS = [
|
|||||||
'opslog.clusterLockBand', 'opslog.clusterLockMode', 'opslog.clusterStatusFilter',
|
'opslog.clusterLockBand', 'opslog.clusterLockMode', 'opslog.clusterStatusFilter',
|
||||||
'opslog.clusterModeFilter', 'opslog.clusterSearch', 'opslog.clusterHideWorked',
|
'opslog.clusterModeFilter', 'opslog.clusterSearch', 'opslog.clusterHideWorked',
|
||||||
'opslog.distanceMiles', // distances shown in statute miles rather than km
|
'opslog.distanceMiles', // distances shown in statute miles rather than km
|
||||||
|
'opslog.iaruRegion', // IARU region (1/2/3) — band edges and segments on the band maps
|
||||||
|
'opslog.chasePota', // show POTA references and the NEW POTA marker on spots
|
||||||
|
'opslog.chaseSota', // show SOTA references on spots
|
||||||
'opslog.activeTab', // last selected tab
|
'opslog.activeTab', // last selected tab
|
||||||
'opslog.mainSplit', // Main tab: width share of the left pane (percent) — legacy, read once to seed mainShares
|
'opslog.mainSplit', // Main tab: width share of the left pane (percent) — legacy, read once to seed mainShares
|
||||||
'opslog.mainShares', // Main tab: column shares per column count, as {2:[..],3:[..],4:[..]}
|
'opslog.mainShares', // Main tab: column shares per column count, as {2:[..],3:[..],4:[..]}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// Single source of truth for the app version shown in the UI (header + About).
|
// Single source of truth for the app version shown in the UI (header + About).
|
||||||
// Bump this on a release (the release script updates it alongside telemetry.go).
|
// Bump this on a release (the release script updates it alongside telemetry.go).
|
||||||
export const APP_VERSION = '0.26.22';
|
export const APP_VERSION = '0.27.2';
|
||||||
|
|
||||||
// Author / credits, shown in Help -> About.
|
// Author / credits, shown in Help -> About.
|
||||||
export const APP_AUTHOR = 'F4BPO';
|
export const APP_AUTHOR = 'F4BPO';
|
||||||
|
|||||||
Vendored
+41
-23
@@ -21,7 +21,6 @@ import {solar} from '../models';
|
|||||||
import {tunergenius} from '../models';
|
import {tunergenius} from '../models';
|
||||||
import {webpub} from '../models';
|
import {webpub} from '../models';
|
||||||
import {winkeyer} from '../models';
|
import {winkeyer} from '../models';
|
||||||
import {labels} from '../models';
|
|
||||||
import {alerts} from '../models';
|
import {alerts} from '../models';
|
||||||
import {audio} from '../models';
|
import {audio} from '../models';
|
||||||
import {contest} from '../models';
|
import {contest} from '../models';
|
||||||
@@ -31,6 +30,7 @@ import {lotwusers} from '../models';
|
|||||||
import {lookup} from '../models';
|
import {lookup} from '../models';
|
||||||
import {netctl} from '../models';
|
import {netctl} from '../models';
|
||||||
import {scp} from '../models';
|
import {scp} from '../models';
|
||||||
|
import {watchlist} from '../models';
|
||||||
|
|
||||||
export function ACOMSetOperate(arg1:boolean):Promise<void>;
|
export function ACOMSetOperate(arg1:boolean):Promise<void>;
|
||||||
|
|
||||||
@@ -46,6 +46,8 @@ export function ActivateProfile(arg1:number):Promise<void>;
|
|||||||
|
|
||||||
export function ActiveRadioID():Promise<string>;
|
export function ActiveRadioID():Promise<string>;
|
||||||
|
|
||||||
|
export function ActiveRadioMyRig():Promise<string>;
|
||||||
|
|
||||||
export function AddQSO(arg1:qso.QSO):Promise<number>;
|
export function AddQSO(arg1:qso.QSO):Promise<number>;
|
||||||
|
|
||||||
export function AmpFanMode(arg1:string,arg2:string):Promise<void>;
|
export function AmpFanMode(arg1:string,arg2:string):Promise<void>;
|
||||||
@@ -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 ComputeStationInfo(arg1:string,arg2:string):Promise<main.StationInfoComputed>;
|
||||||
|
|
||||||
|
export function ConfigureDecoderMode(arg1:string):Promise<void>;
|
||||||
|
|
||||||
export function ConnectAllClusters():Promise<void>;
|
export function ConnectAllClusters():Promise<void>;
|
||||||
|
|
||||||
export function ConnectClusterServer(arg1:number):Promise<void>;
|
export function ConnectClusterServer(arg1:number):Promise<void>;
|
||||||
@@ -404,6 +408,8 @@ export function GetAntGeniusSettings():Promise<main.AntGeniusSettings>;
|
|||||||
|
|
||||||
export function GetAntGeniusStatus():Promise<antgenius.Status>;
|
export function GetAntGeniusStatus():Promise<antgenius.Status>;
|
||||||
|
|
||||||
|
export function GetAudioMonitorPref():Promise<boolean>;
|
||||||
|
|
||||||
export function GetAudioSettings():Promise<main.AudioSettings>;
|
export function GetAudioSettings():Promise<main.AudioSettings>;
|
||||||
|
|
||||||
export function GetAutostartPrograms():Promise<Array<main.AutostartProgram>>;
|
export function GetAutostartPrograms():Promise<Array<main.AutostartProgram>>;
|
||||||
@@ -602,6 +608,8 @@ export function GetUltrabeamSettings():Promise<main.UltrabeamSettings>;
|
|||||||
|
|
||||||
export function GetUltrabeamStatus():Promise<main.UltrabeamStatusInfo>;
|
export function GetUltrabeamStatus():Promise<main.UltrabeamStatusInfo>;
|
||||||
|
|
||||||
|
export function GetWatchlistContestPattern():Promise<string>;
|
||||||
|
|
||||||
export function GetWebPublishConfig():Promise<webpub.Config>;
|
export function GetWebPublishConfig():Promise<webpub.Config>;
|
||||||
|
|
||||||
export function GetWebPublishStatus():Promise<main.WebPublishStatus>;
|
export function GetWebPublishStatus():Promise<main.WebPublishStatus>;
|
||||||
@@ -614,6 +622,10 @@ export function GetWinkeyerStatus():Promise<winkeyer.Status>;
|
|||||||
|
|
||||||
export function GetWorkedCallVariants():Promise<boolean>;
|
export function GetWorkedCallVariants():Promise<boolean>;
|
||||||
|
|
||||||
|
export function GetWsjtFollowMode():Promise<boolean>;
|
||||||
|
|
||||||
|
export function GetWsjtHighlight():Promise<boolean>;
|
||||||
|
|
||||||
export function GetYaesuBandAntennas():Promise<Record<string, number>>;
|
export function GetYaesuBandAntennas():Promise<Record<string, number>>;
|
||||||
|
|
||||||
export function GetYaesuState():Promise<cat.YaesuTXState>;
|
export function GetYaesuState():Promise<cat.YaesuTXState>;
|
||||||
@@ -624,6 +636,8 @@ export function HaltDecodeTx(arg1:string,arg2:boolean):Promise<void>;
|
|||||||
|
|
||||||
export function HasBuiltinReferences(arg1:string):Promise<boolean>;
|
export function HasBuiltinReferences(arg1:string):Promise<boolean>;
|
||||||
|
|
||||||
|
export function IcomConsolePTT(arg1:boolean):Promise<void>;
|
||||||
|
|
||||||
export function IcomRefresh():Promise<void>;
|
export function IcomRefresh():Promise<void>;
|
||||||
|
|
||||||
export function IcomScopeData():Promise<cat.ScopeSweep>;
|
export function IcomScopeData():Promise<cat.ScopeSweep>;
|
||||||
@@ -638,6 +652,8 @@ export function IcomSetANF(arg1:boolean):Promise<void>;
|
|||||||
|
|
||||||
export function IcomSetAPF(arg1:boolean):Promise<void>;
|
export function IcomSetAPF(arg1:boolean):Promise<void>;
|
||||||
|
|
||||||
|
export function IcomSetATU(arg1:boolean):Promise<void>;
|
||||||
|
|
||||||
export function IcomSetAntenna(arg1:number):Promise<void>;
|
export function IcomSetAntenna(arg1:number):Promise<void>;
|
||||||
|
|
||||||
export function IcomSetAntiVOX(arg1:number):Promise<void>;
|
export function IcomSetAntiVOX(arg1:number):Promise<void>;
|
||||||
@@ -698,6 +714,8 @@ export function IcomSetScopeMode(arg1:boolean):Promise<void>;
|
|||||||
|
|
||||||
export function IcomSetSplit(arg1:boolean):Promise<void>;
|
export function IcomSetSplit(arg1:boolean):Promise<void>;
|
||||||
|
|
||||||
|
export function IcomSetSplitOffset(arg1:number):Promise<void>;
|
||||||
|
|
||||||
export function IcomSetSquelch(arg1:number):Promise<void>;
|
export function IcomSetSquelch(arg1:number):Promise<void>;
|
||||||
|
|
||||||
export function IcomSetVOX(arg1:boolean):Promise<void>;
|
export function IcomSetVOX(arg1:boolean):Promise<void>;
|
||||||
@@ -726,28 +744,6 @@ export function KenwoodSendCW(arg1:string):Promise<void>;
|
|||||||
|
|
||||||
export function KenwoodStopCW():Promise<void>;
|
export function KenwoodStopCW():Promise<void>;
|
||||||
|
|
||||||
export function LabelDeleteStock(arg1:number):Promise<void>;
|
|
||||||
|
|
||||||
export function LabelDeleteTemplate(arg1:number):Promise<void>;
|
|
||||||
|
|
||||||
export function LabelGetTemplate(arg1:number):Promise<string>;
|
|
||||||
|
|
||||||
export function LabelListStocks():Promise<Array<labels.Stock>>;
|
|
||||||
|
|
||||||
export function LabelListTemplates():Promise<Array<main.LabelTemplateInfo>>;
|
|
||||||
|
|
||||||
export function LabelOpenPDF(arg1:Array<main.LabelPDFPage>):Promise<string>;
|
|
||||||
|
|
||||||
export function LabelPaperQueue():Promise<Array<qso.QSO>>;
|
|
||||||
|
|
||||||
export function LabelSampleQSOs(arg1:number):Promise<Array<main.LabelSampleQSO>>;
|
|
||||||
|
|
||||||
export function LabelSaveStock(arg1:labels.Stock):Promise<number>;
|
|
||||||
|
|
||||||
export function LabelSaveTemplate(arg1:number,arg2:string,arg3:string,arg4:boolean):Promise<number>;
|
|
||||||
|
|
||||||
export function LabelSetDefaultTemplate(arg1:number):Promise<void>;
|
|
||||||
|
|
||||||
export function LaunchAutostartProgram(arg1:string):Promise<main.AutostartLaunchResult>;
|
export function LaunchAutostartProgram(arg1:string):Promise<main.AutostartLaunchResult>;
|
||||||
|
|
||||||
export function LaunchAutostartPrograms():Promise<Array<main.AutostartLaunchResult>>;
|
export function LaunchAutostartPrograms():Promise<Array<main.AutostartLaunchResult>>;
|
||||||
@@ -1168,6 +1164,8 @@ export function SetKenwoodNB(arg1:boolean):Promise<void>;
|
|||||||
|
|
||||||
export function SetKenwoodNR(arg1:boolean):Promise<void>;
|
export function SetKenwoodNR(arg1:boolean):Promise<void>;
|
||||||
|
|
||||||
|
export function SetKenwoodPanelMode(arg1:string):Promise<void>;
|
||||||
|
|
||||||
export function SetKenwoodPower(arg1:number):Promise<void>;
|
export function SetKenwoodPower(arg1:number):Promise<void>;
|
||||||
|
|
||||||
export function SetKenwoodPreamp(arg1:boolean):Promise<void>;
|
export function SetKenwoodPreamp(arg1:boolean):Promise<void>;
|
||||||
@@ -1176,6 +1174,8 @@ export function SetKenwoodRFGain(arg1:number):Promise<void>;
|
|||||||
|
|
||||||
export function SetKenwoodRIT(arg1:boolean):Promise<void>;
|
export function SetKenwoodRIT(arg1:boolean):Promise<void>;
|
||||||
|
|
||||||
|
export function SetKenwoodRITOffset(arg1:number):Promise<void>;
|
||||||
|
|
||||||
export function SetKenwoodSquelch(arg1:number):Promise<void>;
|
export function SetKenwoodSquelch(arg1:number):Promise<void>;
|
||||||
|
|
||||||
export function SetKenwoodTX(arg1:boolean):Promise<void>;
|
export function SetKenwoodTX(arg1:boolean):Promise<void>;
|
||||||
@@ -1246,10 +1246,16 @@ export function SetUIPref(arg1:string,arg2:string):Promise<void>;
|
|||||||
|
|
||||||
export function SetUltrabeamDirection(arg1:number):Promise<void>;
|
export function SetUltrabeamDirection(arg1:number):Promise<void>;
|
||||||
|
|
||||||
|
export function SetWatchlistContestPattern(arg1:string):Promise<void>;
|
||||||
|
|
||||||
export function SetWinkeyerTrace(arg1:boolean):Promise<void>;
|
export function SetWinkeyerTrace(arg1:boolean):Promise<void>;
|
||||||
|
|
||||||
export function SetWorkedCallVariants(arg1:boolean):Promise<void>;
|
export function SetWorkedCallVariants(arg1:boolean):Promise<void>;
|
||||||
|
|
||||||
|
export function SetWsjtFollowMode(arg1:boolean):Promise<void>;
|
||||||
|
|
||||||
|
export function SetWsjtHighlight(arg1:boolean):Promise<void>;
|
||||||
|
|
||||||
export function SetYaesuAFGain(arg1:number):Promise<void>;
|
export function SetYaesuAFGain(arg1:number):Promise<void>;
|
||||||
|
|
||||||
export function SetYaesuAGC(arg1:string):Promise<void>;
|
export function SetYaesuAGC(arg1:string):Promise<void>;
|
||||||
@@ -1376,6 +1382,18 @@ export function UploadCallsign(arg1:string):Promise<string>;
|
|||||||
|
|
||||||
export function UploadQSOsManual(arg1:string,arg2:Array<number>):Promise<void>;
|
export function UploadQSOsManual(arg1:string,arg2:Array<number>):Promise<void>;
|
||||||
|
|
||||||
|
export function WatchlistAdd(arg1:string,arg2:boolean):Promise<void>;
|
||||||
|
|
||||||
|
export function WatchlistEntries():Promise<Array<watchlist.Entry>>;
|
||||||
|
|
||||||
|
export function WatchlistRemove(arg1:string):Promise<void>;
|
||||||
|
|
||||||
|
export function WatchlistSetContest(arg1:string,arg2:boolean):Promise<void>;
|
||||||
|
|
||||||
|
export function WatchlistSetNotify(arg1:string,arg2:boolean):Promise<void>;
|
||||||
|
|
||||||
|
export function WatchlistWorkedSlots(arg1:Array<main.WatchlistSlotQuery>):Promise<Array<boolean>>;
|
||||||
|
|
||||||
export function WebPublishColumns():Promise<Array<Record<string, string>>>;
|
export function WebPublishColumns():Promise<Array<Record<string, string>>>;
|
||||||
|
|
||||||
export function WinkeyerBackspace():Promise<void>;
|
export function WinkeyerBackspace():Promise<void>;
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ export function ActiveRadioID() {
|
|||||||
return window['go']['main']['App']['ActiveRadioID']();
|
return window['go']['main']['App']['ActiveRadioID']();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function ActiveRadioMyRig() {
|
||||||
|
return window['go']['main']['App']['ActiveRadioMyRig']();
|
||||||
|
}
|
||||||
|
|
||||||
export function AddQSO(arg1) {
|
export function AddQSO(arg1) {
|
||||||
return window['go']['main']['App']['AddQSO'](arg1);
|
return window['go']['main']['App']['AddQSO'](arg1);
|
||||||
}
|
}
|
||||||
@@ -218,6 +222,10 @@ export function ComputeStationInfo(arg1, arg2) {
|
|||||||
return window['go']['main']['App']['ComputeStationInfo'](arg1, arg2);
|
return window['go']['main']['App']['ComputeStationInfo'](arg1, arg2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function ConfigureDecoderMode(arg1) {
|
||||||
|
return window['go']['main']['App']['ConfigureDecoderMode'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
export function ConnectAllClusters() {
|
export function ConnectAllClusters() {
|
||||||
return window['go']['main']['App']['ConnectAllClusters']();
|
return window['go']['main']['App']['ConnectAllClusters']();
|
||||||
}
|
}
|
||||||
@@ -746,6 +754,10 @@ export function GetAntGeniusStatus() {
|
|||||||
return window['go']['main']['App']['GetAntGeniusStatus']();
|
return window['go']['main']['App']['GetAntGeniusStatus']();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function GetAudioMonitorPref() {
|
||||||
|
return window['go']['main']['App']['GetAudioMonitorPref']();
|
||||||
|
}
|
||||||
|
|
||||||
export function GetAudioSettings() {
|
export function GetAudioSettings() {
|
||||||
return window['go']['main']['App']['GetAudioSettings']();
|
return window['go']['main']['App']['GetAudioSettings']();
|
||||||
}
|
}
|
||||||
@@ -1142,6 +1154,10 @@ export function GetUltrabeamStatus() {
|
|||||||
return window['go']['main']['App']['GetUltrabeamStatus']();
|
return window['go']['main']['App']['GetUltrabeamStatus']();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function GetWatchlistContestPattern() {
|
||||||
|
return window['go']['main']['App']['GetWatchlistContestPattern']();
|
||||||
|
}
|
||||||
|
|
||||||
export function GetWebPublishConfig() {
|
export function GetWebPublishConfig() {
|
||||||
return window['go']['main']['App']['GetWebPublishConfig']();
|
return window['go']['main']['App']['GetWebPublishConfig']();
|
||||||
}
|
}
|
||||||
@@ -1166,6 +1182,14 @@ export function GetWorkedCallVariants() {
|
|||||||
return window['go']['main']['App']['GetWorkedCallVariants']();
|
return window['go']['main']['App']['GetWorkedCallVariants']();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function GetWsjtFollowMode() {
|
||||||
|
return window['go']['main']['App']['GetWsjtFollowMode']();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function GetWsjtHighlight() {
|
||||||
|
return window['go']['main']['App']['GetWsjtHighlight']();
|
||||||
|
}
|
||||||
|
|
||||||
export function GetYaesuBandAntennas() {
|
export function GetYaesuBandAntennas() {
|
||||||
return window['go']['main']['App']['GetYaesuBandAntennas']();
|
return window['go']['main']['App']['GetYaesuBandAntennas']();
|
||||||
}
|
}
|
||||||
@@ -1186,6 +1210,10 @@ export function HasBuiltinReferences(arg1) {
|
|||||||
return window['go']['main']['App']['HasBuiltinReferences'](arg1);
|
return window['go']['main']['App']['HasBuiltinReferences'](arg1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function IcomConsolePTT(arg1) {
|
||||||
|
return window['go']['main']['App']['IcomConsolePTT'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
export function IcomRefresh() {
|
export function IcomRefresh() {
|
||||||
return window['go']['main']['App']['IcomRefresh']();
|
return window['go']['main']['App']['IcomRefresh']();
|
||||||
}
|
}
|
||||||
@@ -1214,6 +1242,10 @@ export function IcomSetAPF(arg1) {
|
|||||||
return window['go']['main']['App']['IcomSetAPF'](arg1);
|
return window['go']['main']['App']['IcomSetAPF'](arg1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function IcomSetATU(arg1) {
|
||||||
|
return window['go']['main']['App']['IcomSetATU'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
export function IcomSetAntenna(arg1) {
|
export function IcomSetAntenna(arg1) {
|
||||||
return window['go']['main']['App']['IcomSetAntenna'](arg1);
|
return window['go']['main']['App']['IcomSetAntenna'](arg1);
|
||||||
}
|
}
|
||||||
@@ -1334,6 +1366,10 @@ export function IcomSetSplit(arg1) {
|
|||||||
return window['go']['main']['App']['IcomSetSplit'](arg1);
|
return window['go']['main']['App']['IcomSetSplit'](arg1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function IcomSetSplitOffset(arg1) {
|
||||||
|
return window['go']['main']['App']['IcomSetSplitOffset'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
export function IcomSetSquelch(arg1) {
|
export function IcomSetSquelch(arg1) {
|
||||||
return window['go']['main']['App']['IcomSetSquelch'](arg1);
|
return window['go']['main']['App']['IcomSetSquelch'](arg1);
|
||||||
}
|
}
|
||||||
@@ -1390,50 +1426,6 @@ export function KenwoodStopCW() {
|
|||||||
return window['go']['main']['App']['KenwoodStopCW']();
|
return window['go']['main']['App']['KenwoodStopCW']();
|
||||||
}
|
}
|
||||||
|
|
||||||
export function LabelDeleteStock(arg1) {
|
|
||||||
return window['go']['main']['App']['LabelDeleteStock'](arg1);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function LabelDeleteTemplate(arg1) {
|
|
||||||
return window['go']['main']['App']['LabelDeleteTemplate'](arg1);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function LabelGetTemplate(arg1) {
|
|
||||||
return window['go']['main']['App']['LabelGetTemplate'](arg1);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function LabelListStocks() {
|
|
||||||
return window['go']['main']['App']['LabelListStocks']();
|
|
||||||
}
|
|
||||||
|
|
||||||
export function LabelListTemplates() {
|
|
||||||
return window['go']['main']['App']['LabelListTemplates']();
|
|
||||||
}
|
|
||||||
|
|
||||||
export function LabelOpenPDF(arg1) {
|
|
||||||
return window['go']['main']['App']['LabelOpenPDF'](arg1);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function LabelPaperQueue() {
|
|
||||||
return window['go']['main']['App']['LabelPaperQueue']();
|
|
||||||
}
|
|
||||||
|
|
||||||
export function LabelSampleQSOs(arg1) {
|
|
||||||
return window['go']['main']['App']['LabelSampleQSOs'](arg1);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function LabelSaveStock(arg1) {
|
|
||||||
return window['go']['main']['App']['LabelSaveStock'](arg1);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function LabelSaveTemplate(arg1, arg2, arg3, arg4) {
|
|
||||||
return window['go']['main']['App']['LabelSaveTemplate'](arg1, arg2, arg3, arg4);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function LabelSetDefaultTemplate(arg1) {
|
|
||||||
return window['go']['main']['App']['LabelSetDefaultTemplate'](arg1);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function LaunchAutostartProgram(arg1) {
|
export function LaunchAutostartProgram(arg1) {
|
||||||
return window['go']['main']['App']['LaunchAutostartProgram'](arg1);
|
return window['go']['main']['App']['LaunchAutostartProgram'](arg1);
|
||||||
}
|
}
|
||||||
@@ -2274,6 +2266,10 @@ export function SetKenwoodNR(arg1) {
|
|||||||
return window['go']['main']['App']['SetKenwoodNR'](arg1);
|
return window['go']['main']['App']['SetKenwoodNR'](arg1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function SetKenwoodPanelMode(arg1) {
|
||||||
|
return window['go']['main']['App']['SetKenwoodPanelMode'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
export function SetKenwoodPower(arg1) {
|
export function SetKenwoodPower(arg1) {
|
||||||
return window['go']['main']['App']['SetKenwoodPower'](arg1);
|
return window['go']['main']['App']['SetKenwoodPower'](arg1);
|
||||||
}
|
}
|
||||||
@@ -2290,6 +2286,10 @@ export function SetKenwoodRIT(arg1) {
|
|||||||
return window['go']['main']['App']['SetKenwoodRIT'](arg1);
|
return window['go']['main']['App']['SetKenwoodRIT'](arg1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function SetKenwoodRITOffset(arg1) {
|
||||||
|
return window['go']['main']['App']['SetKenwoodRITOffset'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
export function SetKenwoodSquelch(arg1) {
|
export function SetKenwoodSquelch(arg1) {
|
||||||
return window['go']['main']['App']['SetKenwoodSquelch'](arg1);
|
return window['go']['main']['App']['SetKenwoodSquelch'](arg1);
|
||||||
}
|
}
|
||||||
@@ -2430,6 +2430,10 @@ export function SetUltrabeamDirection(arg1) {
|
|||||||
return window['go']['main']['App']['SetUltrabeamDirection'](arg1);
|
return window['go']['main']['App']['SetUltrabeamDirection'](arg1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function SetWatchlistContestPattern(arg1) {
|
||||||
|
return window['go']['main']['App']['SetWatchlistContestPattern'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
export function SetWinkeyerTrace(arg1) {
|
export function SetWinkeyerTrace(arg1) {
|
||||||
return window['go']['main']['App']['SetWinkeyerTrace'](arg1);
|
return window['go']['main']['App']['SetWinkeyerTrace'](arg1);
|
||||||
}
|
}
|
||||||
@@ -2438,6 +2442,14 @@ export function SetWorkedCallVariants(arg1) {
|
|||||||
return window['go']['main']['App']['SetWorkedCallVariants'](arg1);
|
return window['go']['main']['App']['SetWorkedCallVariants'](arg1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function SetWsjtFollowMode(arg1) {
|
||||||
|
return window['go']['main']['App']['SetWsjtFollowMode'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SetWsjtHighlight(arg1) {
|
||||||
|
return window['go']['main']['App']['SetWsjtHighlight'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
export function SetYaesuAFGain(arg1) {
|
export function SetYaesuAFGain(arg1) {
|
||||||
return window['go']['main']['App']['SetYaesuAFGain'](arg1);
|
return window['go']['main']['App']['SetYaesuAFGain'](arg1);
|
||||||
}
|
}
|
||||||
@@ -2690,6 +2702,30 @@ export function UploadQSOsManual(arg1, arg2) {
|
|||||||
return window['go']['main']['App']['UploadQSOsManual'](arg1, arg2);
|
return window['go']['main']['App']['UploadQSOsManual'](arg1, arg2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function WatchlistAdd(arg1, arg2) {
|
||||||
|
return window['go']['main']['App']['WatchlistAdd'](arg1, arg2);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WatchlistEntries() {
|
||||||
|
return window['go']['main']['App']['WatchlistEntries']();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WatchlistRemove(arg1) {
|
||||||
|
return window['go']['main']['App']['WatchlistRemove'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WatchlistSetContest(arg1, arg2) {
|
||||||
|
return window['go']['main']['App']['WatchlistSetContest'](arg1, arg2);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WatchlistSetNotify(arg1, arg2) {
|
||||||
|
return window['go']['main']['App']['WatchlistSetNotify'](arg1, arg2);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function WatchlistWorkedSlots(arg1) {
|
||||||
|
return window['go']['main']['App']['WatchlistWorkedSlots'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
export function WebPublishColumns() {
|
export function WebPublishColumns() {
|
||||||
return window['go']['main']['App']['WebPublishColumns']();
|
return window['go']['main']['App']['WebPublishColumns']();
|
||||||
}
|
}
|
||||||
|
|||||||
+88
-107
@@ -983,6 +983,7 @@ export namespace cat {
|
|||||||
mode?: string;
|
mode?: string;
|
||||||
transmitting: boolean;
|
transmitting: boolean;
|
||||||
split: boolean;
|
split: boolean;
|
||||||
|
sub_hz: number;
|
||||||
s_meter: number;
|
s_meter: number;
|
||||||
power_meter: number;
|
power_meter: number;
|
||||||
swr_meter: number;
|
swr_meter: number;
|
||||||
@@ -1006,6 +1007,7 @@ export namespace cat {
|
|||||||
att: number;
|
att: number;
|
||||||
filter: number;
|
filter: number;
|
||||||
antenna: number;
|
antenna: number;
|
||||||
|
atu_on: boolean;
|
||||||
pbt_inner: number;
|
pbt_inner: number;
|
||||||
pbt_outer: number;
|
pbt_outer: number;
|
||||||
manual_notch: boolean;
|
manual_notch: boolean;
|
||||||
@@ -1030,6 +1032,7 @@ export namespace cat {
|
|||||||
this.mode = source["mode"];
|
this.mode = source["mode"];
|
||||||
this.transmitting = source["transmitting"];
|
this.transmitting = source["transmitting"];
|
||||||
this.split = source["split"];
|
this.split = source["split"];
|
||||||
|
this.sub_hz = source["sub_hz"];
|
||||||
this.s_meter = source["s_meter"];
|
this.s_meter = source["s_meter"];
|
||||||
this.power_meter = source["power_meter"];
|
this.power_meter = source["power_meter"];
|
||||||
this.swr_meter = source["swr_meter"];
|
this.swr_meter = source["swr_meter"];
|
||||||
@@ -1053,6 +1056,7 @@ export namespace cat {
|
|||||||
this.att = source["att"];
|
this.att = source["att"];
|
||||||
this.filter = source["filter"];
|
this.filter = source["filter"];
|
||||||
this.antenna = source["antenna"];
|
this.antenna = source["antenna"];
|
||||||
|
this.atu_on = source["atu_on"];
|
||||||
this.pbt_inner = source["pbt_inner"];
|
this.pbt_inner = source["pbt_inner"];
|
||||||
this.pbt_outer = source["pbt_outer"];
|
this.pbt_outer = source["pbt_outer"];
|
||||||
this.manual_notch = source["manual_notch"];
|
this.manual_notch = source["manual_notch"];
|
||||||
@@ -1072,12 +1076,14 @@ export namespace cat {
|
|||||||
model?: string;
|
model?: string;
|
||||||
elecraft: boolean;
|
elecraft: boolean;
|
||||||
mode?: string;
|
mode?: string;
|
||||||
|
data_sub?: string;
|
||||||
transmitting: boolean;
|
transmitting: boolean;
|
||||||
split: boolean;
|
split: boolean;
|
||||||
split_tx_hz: number;
|
split_tx_hz: number;
|
||||||
s_meter: number;
|
s_meter: number;
|
||||||
s_meter_raw: number;
|
s_meter_raw: number;
|
||||||
power_meter: number;
|
power_meter: number;
|
||||||
|
power_w: number;
|
||||||
swr: number;
|
swr: number;
|
||||||
swr_raw: number;
|
swr_raw: number;
|
||||||
rf_power: number;
|
rf_power: number;
|
||||||
@@ -1108,12 +1114,14 @@ export namespace cat {
|
|||||||
this.model = source["model"];
|
this.model = source["model"];
|
||||||
this.elecraft = source["elecraft"];
|
this.elecraft = source["elecraft"];
|
||||||
this.mode = source["mode"];
|
this.mode = source["mode"];
|
||||||
|
this.data_sub = source["data_sub"];
|
||||||
this.transmitting = source["transmitting"];
|
this.transmitting = source["transmitting"];
|
||||||
this.split = source["split"];
|
this.split = source["split"];
|
||||||
this.split_tx_hz = source["split_tx_hz"];
|
this.split_tx_hz = source["split_tx_hz"];
|
||||||
this.s_meter = source["s_meter"];
|
this.s_meter = source["s_meter"];
|
||||||
this.s_meter_raw = source["s_meter_raw"];
|
this.s_meter_raw = source["s_meter_raw"];
|
||||||
this.power_meter = source["power_meter"];
|
this.power_meter = source["power_meter"];
|
||||||
|
this.power_w = source["power_w"];
|
||||||
this.swr = source["swr"];
|
this.swr = source["swr"];
|
||||||
this.swr_raw = source["swr_raw"];
|
this.swr_raw = source["swr_raw"];
|
||||||
this.rf_power = source["rf_power"];
|
this.rf_power = source["rf_power"];
|
||||||
@@ -1617,39 +1625,6 @@ export namespace kpa {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export namespace labels {
|
|
||||||
|
|
||||||
export class Stock {
|
|
||||||
id?: number;
|
|
||||||
name: string;
|
|
||||||
w_mm: number;
|
|
||||||
h_mm: number;
|
|
||||||
margin_top_mm: number;
|
|
||||||
margin_right_mm: number;
|
|
||||||
margin_bottom_mm: number;
|
|
||||||
margin_left_mm: number;
|
|
||||||
dpi: number;
|
|
||||||
|
|
||||||
static createFrom(source: any = {}) {
|
|
||||||
return new Stock(source);
|
|
||||||
}
|
|
||||||
|
|
||||||
constructor(source: any = {}) {
|
|
||||||
if ('string' === typeof source) source = JSON.parse(source);
|
|
||||||
this.id = source["id"];
|
|
||||||
this.name = source["name"];
|
|
||||||
this.w_mm = source["w_mm"];
|
|
||||||
this.h_mm = source["h_mm"];
|
|
||||||
this.margin_top_mm = source["margin_top_mm"];
|
|
||||||
this.margin_right_mm = source["margin_right_mm"];
|
|
||||||
this.margin_bottom_mm = source["margin_bottom_mm"];
|
|
||||||
this.margin_left_mm = source["margin_left_mm"];
|
|
||||||
this.dpi = source["dpi"];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
export namespace lookup {
|
export namespace lookup {
|
||||||
|
|
||||||
export class Result {
|
export class Result {
|
||||||
@@ -2969,78 +2944,6 @@ export namespace main {
|
|||||||
this.samples = source["samples"];
|
this.samples = source["samples"];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
export class LabelPDFPage {
|
|
||||||
png: string;
|
|
||||||
w_mm: number;
|
|
||||||
h_mm: number;
|
|
||||||
|
|
||||||
static createFrom(source: any = {}) {
|
|
||||||
return new LabelPDFPage(source);
|
|
||||||
}
|
|
||||||
|
|
||||||
constructor(source: any = {}) {
|
|
||||||
if ('string' === typeof source) source = JSON.parse(source);
|
|
||||||
this.png = source["png"];
|
|
||||||
this.w_mm = source["w_mm"];
|
|
||||||
this.h_mm = source["h_mm"];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
export class LabelSampleQSO {
|
|
||||||
callsign: string;
|
|
||||||
qso_date: string;
|
|
||||||
time_on: string;
|
|
||||||
band: string;
|
|
||||||
freq: string;
|
|
||||||
mode: string;
|
|
||||||
rst_sent: string;
|
|
||||||
rst_rcvd: string;
|
|
||||||
name: string;
|
|
||||||
qth: string;
|
|
||||||
country: string;
|
|
||||||
|
|
||||||
static createFrom(source: any = {}) {
|
|
||||||
return new LabelSampleQSO(source);
|
|
||||||
}
|
|
||||||
|
|
||||||
constructor(source: any = {}) {
|
|
||||||
if ('string' === typeof source) source = JSON.parse(source);
|
|
||||||
this.callsign = source["callsign"];
|
|
||||||
this.qso_date = source["qso_date"];
|
|
||||||
this.time_on = source["time_on"];
|
|
||||||
this.band = source["band"];
|
|
||||||
this.freq = source["freq"];
|
|
||||||
this.mode = source["mode"];
|
|
||||||
this.rst_sent = source["rst_sent"];
|
|
||||||
this.rst_rcvd = source["rst_rcvd"];
|
|
||||||
this.name = source["name"];
|
|
||||||
this.qth = source["qth"];
|
|
||||||
this.country = source["country"];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
export class LabelTemplateInfo {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
kind: string;
|
|
||||||
stock_id: number;
|
|
||||||
profile_id?: number;
|
|
||||||
is_default: boolean;
|
|
||||||
updated_at: string;
|
|
||||||
|
|
||||||
static createFrom(source: any = {}) {
|
|
||||||
return new LabelTemplateInfo(source);
|
|
||||||
}
|
|
||||||
|
|
||||||
constructor(source: any = {}) {
|
|
||||||
if ('string' === typeof source) source = JSON.parse(source);
|
|
||||||
this.id = source["id"];
|
|
||||||
this.name = source["name"];
|
|
||||||
this.kind = source["kind"];
|
|
||||||
this.stock_id = source["stock_id"];
|
|
||||||
this.profile_id = source["profile_id"];
|
|
||||||
this.is_default = source["is_default"];
|
|
||||||
this.updated_at = source["updated_at"];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
export class ModePreset {
|
export class ModePreset {
|
||||||
name: string;
|
name: string;
|
||||||
default_rst_sent?: string;
|
default_rst_sent?: string;
|
||||||
@@ -4404,6 +4307,24 @@ export namespace main {
|
|||||||
this.text = source["text"];
|
this.text = source["text"];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
export class WatchlistSlotQuery {
|
||||||
|
call: string;
|
||||||
|
band: string;
|
||||||
|
mode: string;
|
||||||
|
contest: boolean;
|
||||||
|
|
||||||
|
static createFrom(source: any = {}) {
|
||||||
|
return new WatchlistSlotQuery(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(source: any = {}) {
|
||||||
|
if ('string' === typeof source) source = JSON.parse(source);
|
||||||
|
this.call = source["call"];
|
||||||
|
this.band = source["band"];
|
||||||
|
this.mode = source["mode"];
|
||||||
|
this.contest = source["contest"];
|
||||||
|
}
|
||||||
|
}
|
||||||
export class WebPublishStatus {
|
export class WebPublishStatus {
|
||||||
last_run: string;
|
last_run: string;
|
||||||
last_err: string;
|
last_err: string;
|
||||||
@@ -5243,7 +5164,6 @@ export namespace qso {
|
|||||||
band?: string;
|
band?: string;
|
||||||
mode?: string;
|
mode?: string;
|
||||||
station_callsign?: string;
|
station_callsign?: string;
|
||||||
qsl_sent_in?: string[];
|
|
||||||
limit?: number;
|
limit?: number;
|
||||||
offset?: number;
|
offset?: number;
|
||||||
|
|
||||||
@@ -5257,7 +5177,6 @@ export namespace qso {
|
|||||||
this.band = source["band"];
|
this.band = source["band"];
|
||||||
this.mode = source["mode"];
|
this.mode = source["mode"];
|
||||||
this.station_callsign = source["station_callsign"];
|
this.station_callsign = source["station_callsign"];
|
||||||
this.qsl_sent_in = source["qsl_sent_in"];
|
|
||||||
this.limit = source["limit"];
|
this.limit = source["limit"];
|
||||||
this.offset = source["offset"];
|
this.offset = source["offset"];
|
||||||
}
|
}
|
||||||
@@ -6095,6 +6014,68 @@ export namespace udp {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export namespace watchlist {
|
||||||
|
|
||||||
|
export class Entry {
|
||||||
|
callsign: string;
|
||||||
|
// Go type: time
|
||||||
|
lastSeen: any;
|
||||||
|
lastSeenStr: string;
|
||||||
|
// Go type: time
|
||||||
|
addedAt: any;
|
||||||
|
spotCount: number;
|
||||||
|
isContest: boolean;
|
||||||
|
notify: boolean;
|
||||||
|
isExpedition: boolean;
|
||||||
|
clubLogQSOs24h: number;
|
||||||
|
clubLogTotalQSOs: number;
|
||||||
|
clubLogHasOQRS: boolean;
|
||||||
|
clubLogLiveStream: boolean;
|
||||||
|
// Go type: time
|
||||||
|
clubLogUpdatedAt?: any;
|
||||||
|
|
||||||
|
static createFrom(source: any = {}) {
|
||||||
|
return new Entry(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(source: any = {}) {
|
||||||
|
if ('string' === typeof source) source = JSON.parse(source);
|
||||||
|
this.callsign = source["callsign"];
|
||||||
|
this.lastSeen = this.convertValues(source["lastSeen"], null);
|
||||||
|
this.lastSeenStr = source["lastSeenStr"];
|
||||||
|
this.addedAt = this.convertValues(source["addedAt"], null);
|
||||||
|
this.spotCount = source["spotCount"];
|
||||||
|
this.isContest = source["isContest"];
|
||||||
|
this.notify = source["notify"];
|
||||||
|
this.isExpedition = source["isExpedition"];
|
||||||
|
this.clubLogQSOs24h = source["clubLogQSOs24h"];
|
||||||
|
this.clubLogTotalQSOs = source["clubLogTotalQSOs"];
|
||||||
|
this.clubLogHasOQRS = source["clubLogHasOQRS"];
|
||||||
|
this.clubLogLiveStream = source["clubLogLiveStream"];
|
||||||
|
this.clubLogUpdatedAt = this.convertValues(source["clubLogUpdatedAt"], null);
|
||||||
|
}
|
||||||
|
|
||||||
|
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||||
|
if (!a) {
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
if (a.slice && a.map) {
|
||||||
|
return (a as any[]).map(elem => this.convertValues(elem, classs));
|
||||||
|
} else if ("object" === typeof a) {
|
||||||
|
if (asMap) {
|
||||||
|
for (const key of Object.keys(a)) {
|
||||||
|
a[key] = new classs(a[key]);
|
||||||
|
}
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
return new classs(a);
|
||||||
|
}
|
||||||
|
return a;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
export namespace webpub {
|
export namespace webpub {
|
||||||
|
|
||||||
export class Config {
|
export class Config {
|
||||||
|
|||||||
@@ -27,27 +27,31 @@ type modeSeg struct {
|
|||||||
var bandPlan = []modeSeg{
|
var bandPlan = []modeSeg{
|
||||||
{1_800_000, 1_838_000, "CW"}, {1_838_000, 1_840_000, "FT8"}, {1_840_000, 2_000_000, "SSB"},
|
{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"},
|
{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_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"},
|
{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.
|
// 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"},
|
{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_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"},
|
{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"},
|
{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_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"},
|
{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"},
|
{24_890_000, 24_915_000, "CW"}, {24_915_000, 24_940_000, "DATA"}, {24_940_000, 24_990_000, "SSB"},
|
||||||
|
|
||||||
{28_074_000, 28_077_000, "FT8"}, {28_180_000, 28_183_000, "FT4"},
|
{28_074_000, 28_077_000, "FT8"}, {28_180_000, 28_183_000, "FT4"},
|
||||||
|
|||||||
@@ -356,6 +356,29 @@ func (m *Manager) StartTXAudio(micDev, toRadioDev string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// StartTXAudioNetwork pipes the live microphone into a SEND function instead
|
||||||
|
// of a render device — the talk button when the radio is reached over its own
|
||||||
|
// link. No ring and no pacing goroutine: the microphone delivers in real time,
|
||||||
|
// and the sender re-frames to the rig's cadence, so the capture callback IS
|
||||||
|
// the clock.
|
||||||
|
func (m *Manager) StartTXAudioNetwork(micDev string, send func([]byte) error) error {
|
||||||
|
m.mu.Lock()
|
||||||
|
if m.txStop != nil {
|
||||||
|
m.mu.Unlock()
|
||||||
|
return fmt.Errorf("TX audio already running")
|
||||||
|
}
|
||||||
|
stop := make(chan struct{})
|
||||||
|
m.txStop = stop
|
||||||
|
m.mu.Unlock()
|
||||||
|
go func() {
|
||||||
|
if err := captureStream(micDev, stop, func(chunk []byte) { _ = send(chunk) }); err != nil {
|
||||||
|
LogSink("audio: network TX capture from %q failed: %v", DeviceName(micDev), err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
m.notify()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// StopTXAudio stops the TX mic→rig passthrough.
|
// StopTXAudio stops the TX mic→rig passthrough.
|
||||||
func (m *Manager) StopTXAudio() {
|
func (m *Manager) StopTXAudio() {
|
||||||
m.mu.Lock()
|
m.mu.Lock()
|
||||||
|
|||||||
@@ -64,4 +64,4 @@ func NetworkPlayerReady() bool { return networkPlayer() != nil }
|
|||||||
// comes back with. Named, because "the device could not be opened" would send
|
// comes back with. Named, because "the device could not be opened" would send
|
||||||
// an operator hunting through Windows sound settings for a device that never
|
// an operator hunting through Windows sound settings for a device that never
|
||||||
// existed.
|
// existed.
|
||||||
var errNoNetworkRadio = errors.New("no radio is connected to take the audio — check the CAT link (the radio output only works with a TCI radio)")
|
var errNoNetworkRadio = errors.New("no radio is connected to take the audio — check the CAT link (a TCI radio, or a network Icom with RX audio enabled)")
|
||||||
|
|||||||
+11
-4
@@ -572,9 +572,13 @@ type IcomTXState struct {
|
|||||||
// Transmit + live status (polled).
|
// Transmit + live status (polled).
|
||||||
Transmitting bool `json:"transmitting"`
|
Transmitting bool `json:"transmitting"`
|
||||||
Split bool `json:"split"`
|
Split bool `json:"split"`
|
||||||
SMeter int `json:"s_meter"` // 0-100 (raw 0-255; S9≈120)
|
// SubHz is the unselected VFO / sub receiver's frequency — shown on the
|
||||||
PowerMeter int `json:"power_meter"` // 0-100 (TX Po)
|
// console's SUB display whether or not split is on: a dual-receiver rig
|
||||||
SWRMeter int `json:"swr_meter"` // 0-100 (TX SWR)
|
// (IC-7610/7760) has a second dial worth seeing at all times.
|
||||||
|
SubHz int64 `json:"sub_hz"`
|
||||||
|
SMeter int `json:"s_meter"` // 0-100 (raw 0-255; S9≈120)
|
||||||
|
PowerMeter int `json:"power_meter"` // 0-100 (TX Po)
|
||||||
|
SWRMeter int `json:"swr_meter"` // 0-100 (TX SWR)
|
||||||
// RIT / ΔTX (XIT).
|
// RIT / ΔTX (XIT).
|
||||||
RITHz int `json:"rit_hz"` // RIT/XIT offset, signed Hz
|
RITHz int `json:"rit_hz"` // RIT/XIT offset, signed Hz
|
||||||
RITOn bool `json:"rit_on"`
|
RITOn bool `json:"rit_on"`
|
||||||
@@ -598,7 +602,8 @@ type IcomTXState struct {
|
|||||||
Att int `json:"att"` // dB attenuation, 0=off
|
Att int `json:"att"` // dB attenuation, 0=off
|
||||||
Filter int `json:"filter"` // 1 | 2 | 3 (FIL1/2/3)
|
Filter int `json:"filter"` // 1 | 2 | 3 (FIL1/2/3)
|
||||||
// Antenna (IC-7610 = ANT1/ANT2).
|
// Antenna (IC-7610 = ANT1/ANT2).
|
||||||
Antenna int `json:"antenna"` // 1 | 2 (0 = unknown)
|
Antenna int `json:"antenna"` // 1 | 2 (0 = unknown)
|
||||||
|
ATUOn bool `json:"atu_on"` // internal tuner engaged
|
||||||
// Filter fine controls: Twin PBT + manual notch (0-100, 50 = centre).
|
// Filter fine controls: Twin PBT + manual notch (0-100, 50 = centre).
|
||||||
PBTInner int `json:"pbt_inner"`
|
PBTInner int `json:"pbt_inner"`
|
||||||
PBTOuter int `json:"pbt_outer"`
|
PBTOuter int `json:"pbt_outer"`
|
||||||
@@ -636,6 +641,8 @@ type IcomController interface {
|
|||||||
SetRFPower(int) error
|
SetRFPower(int) error
|
||||||
SetMicGain(int) error
|
SetMicGain(int) error
|
||||||
SetIcomSplit(bool) error
|
SetIcomSplit(bool) error
|
||||||
|
SetIcomSplitOffset(bool, int64) error
|
||||||
|
SetATU(bool) error
|
||||||
TuneATU() error
|
TuneATU() error
|
||||||
SetScope(bool) error // enable/disable the spectrum-scope waveform stream
|
SetScope(bool) error // enable/disable the spectrum-scope waveform stream
|
||||||
SetScopeMode(bool) error // true = fixed span, false = center-on-VFO
|
SetScopeMode(bool) error // true = fixed span, false = center-on-VFO
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ const (
|
|||||||
CmdVfoFreq = 0x25 // read a specific VFO's freq (sub 0x00 selected, 0x01 unselected)
|
CmdVfoFreq = 0x25 // read a specific VFO's freq (sub 0x00 selected, 0x01 unselected)
|
||||||
CmdPTT = 0x1C // sub 0x00 = PTT
|
CmdPTT = 0x1C // sub 0x00 = PTT
|
||||||
CmdExtra = 0x1A // sub 0x06 = data mode on modern Icoms
|
CmdExtra = 0x1A // sub 0x06 = data mode on modern Icoms
|
||||||
|
CmdModeDataFil = 0x26 // sub 0x00 = selected VFO: mode + data flag + filter in one frame
|
||||||
CmdReadID = 0x19 // sub 0x00 = rig's own CI-V address (identifies model)
|
CmdReadID = 0x19 // sub 0x00 = rig's own CI-V address (identifies model)
|
||||||
CmdPower = 0x18 // power on/off (sub 0x01 = on, 0x00 = off; on needs an FE wake preamble)
|
CmdPower = 0x18 // power on/off (sub 0x01 = on, 0x00 = off; on needs an FE wake preamble)
|
||||||
|
|
||||||
@@ -130,6 +131,8 @@ const (
|
|||||||
ModeFM = 0x05
|
ModeFM = 0x05
|
||||||
ModeCWR = 0x07
|
ModeCWR = 0x07
|
||||||
ModeRTTYR = 0x08
|
ModeRTTYR = 0x08
|
||||||
|
ModePSK = 0x12 // native PSK (IC-7610/7760/7851 class; older rigs NAK it)
|
||||||
|
ModePSKR = 0x13
|
||||||
)
|
)
|
||||||
|
|
||||||
// Frame builds a complete CI-V frame (preamble … end) for payload, which is the
|
// Frame builds a complete CI-V frame (preamble … end) for payload, which is the
|
||||||
@@ -305,6 +308,8 @@ func ModeToADIF(m byte, data bool) string {
|
|||||||
return "CW"
|
return "CW"
|
||||||
case ModeRTTY, ModeRTTYR:
|
case ModeRTTY, ModeRTTYR:
|
||||||
return "RTTY"
|
return "RTTY"
|
||||||
|
case ModePSK, ModePSKR:
|
||||||
|
return "PSK31"
|
||||||
case ModeAM:
|
case ModeAM:
|
||||||
return "AM"
|
return "AM"
|
||||||
case ModeFM:
|
case ModeFM:
|
||||||
@@ -357,6 +362,8 @@ func ModelName(addr byte) string {
|
|||||||
return "IC-9700"
|
return "IC-9700"
|
||||||
case 0xA4:
|
case 0xA4:
|
||||||
return "IC-705"
|
return "IC-705"
|
||||||
|
case 0xB2:
|
||||||
|
return "IC-7760"
|
||||||
case 0xB6:
|
case 0xB6:
|
||||||
return "IC-7300MKII"
|
return "IC-7300MKII"
|
||||||
}
|
}
|
||||||
|
|||||||
+132
-11
@@ -22,17 +22,20 @@ package cat
|
|||||||
// audio stream is opt-in and entirely separate from control/CI-V.
|
// audio stream is opt-in and entirely separate from control/CI-V.
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// icaAudioOffset is where the PCM payload begins inside an audio data packet
|
// icaAudioOffset is where the PCM payload begins inside an audio data packet.
|
||||||
// (wfview audio_packet: 16-byte common header + ident@0x10 + datalen@0x12 +
|
// CONFIRMED on a real IC-7760 (2026-08-29): 16-byte common header, ident@0x10,
|
||||||
// sendseq@0x14 → audio@0x16). Isolated as a const so a capture-confirmed change
|
// send seq (BE) @0x12, payload length (BE uint32) @0x14 — 0x500 observed on
|
||||||
// is a one-line edit.
|
// every packet — and the PCM starts at 0x18. The 0x16 first guessed from
|
||||||
const icaAudioOffset = 0x16
|
// wfview's struct swallowed two header bytes into the audio, one broken sample
|
||||||
|
// per packet: a 50 Hz click track under everything.
|
||||||
|
const icaAudioOffset = 0x18
|
||||||
|
|
||||||
// icaDumpFirst is how many initial audio packets to hex-dump to the debug log for
|
// icaDumpFirst is how many initial audio packets to hex-dump to the debug log for
|
||||||
// offset verification. After the layout is confirmed on a real rig this can go to
|
// offset verification. After the layout is confirmed on a real rig this can go to
|
||||||
@@ -54,8 +57,16 @@ type icomAudio struct {
|
|||||||
rxLastSeq uint16
|
rxLastSeq uint16
|
||||||
rxMissing map[uint16]int
|
rxMissing map[uint16]int
|
||||||
|
|
||||||
dumped int // packets hex-dumped so far (≤ icaDumpFirst)
|
dumped int // packets hex-dumped so far (≤ icaDumpFirst)
|
||||||
lastRx atomic.Int64 // UnixNano of last packet (liveness)
|
pingSeq uint16 // client-ping counter — the rig wants OUR pings too (see icnPing)
|
||||||
|
started time.Time
|
||||||
|
|
||||||
|
// Live-TX state — see SendTXChunk.
|
||||||
|
txMu sync.Mutex
|
||||||
|
txRem []byte
|
||||||
|
txOuter uint16
|
||||||
|
txSend uint16
|
||||||
|
lastRx atomic.Int64 // UnixNano of last packet (liveness)
|
||||||
|
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
closeOnce sync.Once
|
closeOnce sync.Once
|
||||||
@@ -100,6 +111,7 @@ func dialIcomAudio(host string, sink func([]byte), cancel <-chan struct{}) (*ico
|
|||||||
_ = conn.SetReadBuffer(1 << 20)
|
_ = conn.SetReadBuffer(1 << 20)
|
||||||
a := &icomAudio{
|
a := &icomAudio{
|
||||||
conn: conn, aID: aID, aRemote: aRemote,
|
conn: conn, aID: aID, aRemote: aRemote,
|
||||||
|
started: time.Now(),
|
||||||
sink: sink,
|
sink: sink,
|
||||||
rxMissing: make(map[uint16]int),
|
rxMissing: make(map[uint16]int),
|
||||||
done: make(chan struct{}),
|
done: make(chan struct{}),
|
||||||
@@ -115,6 +127,7 @@ func dialIcomAudio(host string, sink func([]byte), cancel <-chan struct{}) (*ico
|
|||||||
func (a *icomAudio) audioPump() {
|
func (a *icomAudio) audioPump() {
|
||||||
buf := make([]byte, 8192)
|
buf := make([]byte, 8192)
|
||||||
lastIdle := time.Now()
|
lastIdle := time.Now()
|
||||||
|
lastPing := time.Now()
|
||||||
lastReq := time.Now()
|
lastReq := time.Now()
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
@@ -132,12 +145,19 @@ func (a *icomAudio) audioPump() {
|
|||||||
case typ == 0x05: // rig-initiated disconnect
|
case typ == 0x05: // rig-initiated disconnect
|
||||||
debugLog.Printf("icom audio: rig sent DISCONNECT — audio stream dropped by the rig")
|
debugLog.Printf("icom audio: rig sent DISCONNECT — audio stream dropped by the rig")
|
||||||
case typ == 0x00 && k > icaAudioOffset: // audio data packet
|
case typ == 0x00 && k > icaAudioOffset: // audio data packet
|
||||||
a.trackRxSeq(icnLE.Uint16(buf[6:]))
|
fresh := a.trackRxSeq(icnLE.Uint16(buf[6:]))
|
||||||
if a.dumped < icaDumpFirst {
|
if a.dumped < icaDumpFirst {
|
||||||
a.dumped++
|
a.dumped++
|
||||||
debugLog.Printf("icom audio raw #%d: len=%d head=% X", a.dumped, k, buf[:min(icaAudioOffset+8, k)])
|
debugLog.Printf("icom audio raw #%d: len=%d head=% X", a.dumped, k, buf[:min(icaAudioOffset+8, k)])
|
||||||
}
|
}
|
||||||
if a.sink != nil {
|
// Only a packet that ADVANCES the sequence reaches the sink. A
|
||||||
|
// duplicate or a late retransmit used to be delivered as if it
|
||||||
|
// were the next 20 ms of audio: the monitor's capped ring threw
|
||||||
|
// the surplus away (the speakers stayed clean), but the recorder
|
||||||
|
// keeps every sample it is given — the file grew longer than the
|
||||||
|
// QSO and played back slowed and stuttering, each lost-then-
|
||||||
|
// resent packet heard twice.
|
||||||
|
if fresh && a.sink != nil {
|
||||||
payload := append([]byte(nil), buf[icaAudioOffset:k]...)
|
payload := append([]byte(nil), buf[icaAudioOffset:k]...)
|
||||||
a.sink(payload)
|
a.sink(payload)
|
||||||
}
|
}
|
||||||
@@ -147,6 +167,11 @@ func (a *icomAudio) audioPump() {
|
|||||||
_, _ = a.conn.Write(icnCtrl(0x00, 0, a.aID, a.aRemote))
|
_, _ = a.conn.Write(icnCtrl(0x00, 0, a.aID, a.aRemote))
|
||||||
lastIdle = time.Now()
|
lastIdle = time.Now()
|
||||||
}
|
}
|
||||||
|
if time.Since(lastPing) > 500*time.Millisecond {
|
||||||
|
a.pingSeq++
|
||||||
|
_, _ = a.conn.Write(icnPing(a.pingSeq, a.aID, a.aRemote, uint32(time.Since(a.started).Milliseconds())))
|
||||||
|
lastPing = time.Now()
|
||||||
|
}
|
||||||
if time.Since(lastReq) > 100*time.Millisecond {
|
if time.Since(lastReq) > 100*time.Millisecond {
|
||||||
a.sendRetransmitReq()
|
a.sendRetransmitReq()
|
||||||
lastReq = time.Now()
|
lastReq = time.Now()
|
||||||
@@ -157,26 +182,36 @@ func (a *icomAudio) audioPump() {
|
|||||||
// trackRxSeq / sendRetransmitReq mirror icomNet's receive-side retransmit exactly
|
// trackRxSeq / sendRetransmitReq mirror icomNet's receive-side retransmit exactly
|
||||||
// (audio is as loss-sensitive as the scope stream). Duplicated deliberately so
|
// (audio is as loss-sensitive as the scope stream). Duplicated deliberately so
|
||||||
// the audio stream owns its own seq state with no shared locking.
|
// the audio stream owns its own seq state with no shared locking.
|
||||||
func (a *icomAudio) trackRxSeq(seq uint16) {
|
//
|
||||||
|
// The return value says whether this packet moves the stream FORWARD — the
|
||||||
|
// only kind the sink may hear. A duplicate is the same 20 ms again; a late
|
||||||
|
// retransmit would play old audio in the middle of new. Both are accounted
|
||||||
|
// for here and dropped by the caller.
|
||||||
|
func (a *icomAudio) trackRxSeq(seq uint16) bool {
|
||||||
if !a.rxHaveSeq {
|
if !a.rxHaveSeq {
|
||||||
a.rxHaveSeq = true
|
a.rxHaveSeq = true
|
||||||
a.rxLastSeq = seq
|
a.rxLastSeq = seq
|
||||||
return
|
return true
|
||||||
}
|
}
|
||||||
switch d := int16(seq - a.rxLastSeq); {
|
switch d := int16(seq - a.rxLastSeq); {
|
||||||
case d == 0:
|
case d == 0:
|
||||||
|
return false
|
||||||
case d < 0:
|
case d < 0:
|
||||||
delete(a.rxMissing, seq)
|
delete(a.rxMissing, seq)
|
||||||
|
return false
|
||||||
case d == 1:
|
case d == 1:
|
||||||
a.rxLastSeq = seq
|
a.rxLastSeq = seq
|
||||||
|
return true
|
||||||
case int(d) <= icnMaxMissing:
|
case int(d) <= icnMaxMissing:
|
||||||
for f := a.rxLastSeq + 1; f != seq; f++ {
|
for f := a.rxLastSeq + 1; f != seq; f++ {
|
||||||
a.rxMissing[f] = 0
|
a.rxMissing[f] = 0
|
||||||
}
|
}
|
||||||
a.rxLastSeq = seq
|
a.rxLastSeq = seq
|
||||||
|
return true
|
||||||
default:
|
default:
|
||||||
a.rxMissing = make(map[uint16]int)
|
a.rxMissing = make(map[uint16]int)
|
||||||
a.rxLastSeq = seq
|
a.rxLastSeq = seq
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -217,3 +252,89 @@ func (a *icomAudio) sendRetransmitReq() {
|
|||||||
_, _ = a.conn.Write(b)
|
_, _ = a.conn.Write(b)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PlayTX sends one already-decoded message out over the audio session, paced
|
||||||
|
// at the stream's own 20 ms / 320-sample cadence, and returns when the last
|
||||||
|
// packet has gone or stop is closed.
|
||||||
|
//
|
||||||
|
// The frame mirrors what the rig itself sends on this socket byte for byte —
|
||||||
|
// ident 0x81 0x01 (LPCM mono 16-bit), a big-endian send sequence at 0x12, the
|
||||||
|
// payload length at 0x14, PCM from 0x18 — with the IDs swapped for direction.
|
||||||
|
// PTT is the caller's business, exactly as on the TCI and sound-card paths.
|
||||||
|
func (a *icomAudio) PlayTX(pcm []byte, rate, ch, bits int, stop <-chan struct{}) error {
|
||||||
|
mono := decodeToMono(pcm, ch, bits)
|
||||||
|
if len(mono) == 0 {
|
||||||
|
return fmt.Errorf("the message is empty")
|
||||||
|
}
|
||||||
|
if rate > 0 && rate != 16000 {
|
||||||
|
mono = resampleLinear(mono, rate, 16000)
|
||||||
|
}
|
||||||
|
// Through the SAME framer and counters as the live microphone. Each of the
|
||||||
|
// two used to number its own packets from 1, and a voice-keyer message sent
|
||||||
|
// after a talk session re-used sequence numbers the rig had already seen —
|
||||||
|
// it keyed for the full length of the message and modulated none of it.
|
||||||
|
const frame = 320 // samples per packet: 20 ms at 16 kHz, the rig's own cadence
|
||||||
|
tick := time.NewTicker(20 * time.Millisecond)
|
||||||
|
defer tick.Stop()
|
||||||
|
buf := make([]byte, frame*2)
|
||||||
|
for pos := 0; pos < len(mono); pos += frame {
|
||||||
|
select {
|
||||||
|
case <-stop:
|
||||||
|
return nil
|
||||||
|
case <-a.done:
|
||||||
|
return fmt.Errorf("the audio stream closed mid-message")
|
||||||
|
case <-tick.C:
|
||||||
|
}
|
||||||
|
for i := 0; i < frame; i++ {
|
||||||
|
var v float32
|
||||||
|
if pos+i < len(mono) {
|
||||||
|
v = mono[pos+i] * 32767
|
||||||
|
}
|
||||||
|
if v > 32767 {
|
||||||
|
v = 32767
|
||||||
|
} else if v < -32768 {
|
||||||
|
v = -32768
|
||||||
|
}
|
||||||
|
icnLE.PutUint16(buf[i*2:], uint16(int16(v)))
|
||||||
|
}
|
||||||
|
if err := a.SendTXChunk(buf); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Live TX — the microphone, not a recorded message. Chunks arrive at the
|
||||||
|
// microphone's own real-time pace (16 kHz mono 16-bit, whatever length the
|
||||||
|
// capture delivers) and are re-framed into the rig's 320-sample packets; the
|
||||||
|
// remainder waits for the next chunk. Counters and remainder live on the
|
||||||
|
// stream so a talk session survives across calls.
|
||||||
|
func (a *icomAudio) SendTXChunk(pcm []byte) error {
|
||||||
|
a.txMu.Lock()
|
||||||
|
defer a.txMu.Unlock()
|
||||||
|
a.txRem = append(a.txRem, pcm...)
|
||||||
|
const frameBytes = 640
|
||||||
|
for len(a.txRem) >= frameBytes {
|
||||||
|
select {
|
||||||
|
case <-a.done:
|
||||||
|
return fmt.Errorf("the audio stream closed")
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
pkt := make([]byte, 0x18+frameBytes)
|
||||||
|
icnLE.PutUint32(pkt[0:], uint32(len(pkt)))
|
||||||
|
a.txOuter++
|
||||||
|
icnLE.PutUint16(pkt[6:], a.txOuter)
|
||||||
|
icnLE.PutUint32(pkt[8:], a.aID)
|
||||||
|
icnLE.PutUint32(pkt[12:], a.aRemote)
|
||||||
|
pkt[0x10], pkt[0x11] = 0x81, 0x01
|
||||||
|
icnBE.PutUint16(pkt[0x12:], a.txSend)
|
||||||
|
a.txSend++
|
||||||
|
icnBE.PutUint32(pkt[0x14:], frameBytes)
|
||||||
|
copy(pkt[0x18:], a.txRem[:frameBytes])
|
||||||
|
a.txRem = a.txRem[frameBytes:]
|
||||||
|
if _, err := a.conn.Write(pkt); err != nil {
|
||||||
|
return fmt.Errorf("sending mic audio to the rig: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|||||||
+212
-9
@@ -56,6 +56,15 @@ func NewIcomNet(host, user, pass string, civAddr int, digitalDefault string, aud
|
|||||||
model: "Icom",
|
model: "Icom",
|
||||||
scopeFixed: true,
|
scopeFixed: true,
|
||||||
}
|
}
|
||||||
|
// lastNetConnect is when the previous session came up, and it drives a
|
||||||
|
// deliberate pause: on a real IC-7760 a session sometimes goes deaf on CI-V
|
||||||
|
// while the rig still holds it half-open, and a session dialled straight
|
||||||
|
// back in answers for a second and is then strangled when the rig finally
|
||||||
|
// purges the old one — reconnect, die, reconnect, die, twenty seconds a
|
||||||
|
// lap and no audio the whole time. When the last session died YOUNG, wait
|
||||||
|
// out the rig's cleanup before dialling again; a session that lived long
|
||||||
|
// reconnects immediately, as ever.
|
||||||
|
var lastNetConnect time.Time
|
||||||
b.open = func() (civTransport, error) {
|
b.open = func() (civTransport, error) {
|
||||||
if strings.TrimSpace(host) == "" {
|
if strings.TrimSpace(host) == "" {
|
||||||
return nil, fmt.Errorf("no rig host configured")
|
return nil, fmt.Errorf("no rig host configured")
|
||||||
@@ -63,7 +72,20 @@ func NewIcomNet(host, user, pass string, civAddr int, digitalDefault string, aud
|
|||||||
b.dialMu.Lock()
|
b.dialMu.Lock()
|
||||||
cancel := b.dialCancel
|
cancel := b.dialCancel
|
||||||
b.dialMu.Unlock()
|
b.dialMu.Unlock()
|
||||||
return dialIcomNet(host, user, pass, "OpsLog", b.rigAddr, cancel, audioSink)
|
if !lastNetConnect.IsZero() && time.Since(lastNetConnect) < 90*time.Second {
|
||||||
|
debugLog.Printf("icom net: the last session died young — pausing 20 s before redialling so the rig can purge it first")
|
||||||
|
for i := 0; i < 40; i++ {
|
||||||
|
if icnCanceled(cancel) {
|
||||||
|
return nil, errDialCanceled
|
||||||
|
}
|
||||||
|
time.Sleep(500 * time.Millisecond)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tr, err := dialIcomNet(host, user, pass, "OpsLog", b.rigAddr, cancel, audioSink)
|
||||||
|
if err == nil {
|
||||||
|
lastNetConnect = time.Now()
|
||||||
|
}
|
||||||
|
return tr, err
|
||||||
}
|
}
|
||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
@@ -97,6 +119,19 @@ type icomNet struct {
|
|||||||
// CAT goroutine) and during dial — never by the pump — so no lock is needed.
|
// CAT goroutine) and during dial — never by the pump — so no lock is needed.
|
||||||
vTracked uint16
|
vTracked uint16
|
||||||
vCivSeq uint16
|
vCivSeq uint16
|
||||||
|
seqMu sync.Mutex // guards vTracked/vCivSeq: the command loop AND the pump's quiet-recovery both send
|
||||||
|
// Client-ping sequence counters, one per stream, and the connection's epoch
|
||||||
|
// for the ping timestamps. Owned by their pump goroutines — no locking.
|
||||||
|
civPingSeq uint16
|
||||||
|
ctrlPingSeq uint16
|
||||||
|
started time.Time
|
||||||
|
// txCiv counts CI-V command packets sent, and txAtData snapshots it at the
|
||||||
|
// last received CI-V data. Their difference during a silence answers the
|
||||||
|
// question the reconnects cannot: were we still ASKING when the answers
|
||||||
|
// stopped? Zero writes-since-data would mean the fault is our own poll
|
||||||
|
// loop, not the rig — and RS-BA1 showing no such dropouts points that way.
|
||||||
|
txCiv atomic.Uint32
|
||||||
|
txAtData atomic.Uint32
|
||||||
|
|
||||||
rx chan []byte // CI-V byte chunks from civPump → Read (control replies)
|
rx chan []byte // CI-V byte chunks from civPump → Read (control replies)
|
||||||
scopeRx chan []byte // scope (0x27) frames, kept off rx so the panadapter
|
scopeRx chan []byte // scope (0x27) frames, kept off rx so the panadapter
|
||||||
@@ -227,10 +262,13 @@ func (n *icomNet) Write(p []byte) (int, error) {
|
|||||||
if icnTrace {
|
if icnTrace {
|
||||||
debugLog.Printf("icom net TX: % X", p)
|
debugLog.Printf("icom net TX: % X", p)
|
||||||
}
|
}
|
||||||
seq := n.vTracked
|
n.seqMu.Lock()
|
||||||
pkt := icnCivData(seq, n.vID, n.vRemote, n.vCivSeq, p)
|
seq, civSeq := n.vTracked, n.vCivSeq
|
||||||
n.vTracked++
|
n.vTracked++
|
||||||
n.vCivSeq++
|
n.vCivSeq++
|
||||||
|
n.seqMu.Unlock()
|
||||||
|
n.txCiv.Add(1)
|
||||||
|
pkt := icnCivData(seq, n.vID, n.vRemote, civSeq, p)
|
||||||
n.sentMu.Lock()
|
n.sentMu.Lock()
|
||||||
n.sentBuf[seq] = pkt
|
n.sentBuf[seq] = pkt
|
||||||
delete(n.sentBuf, seq-1024) // keep the buffer bounded (~last 1024 packets) so
|
delete(n.sentBuf, seq-1024) // keep the buffer bounded (~last 1024 packets) so
|
||||||
@@ -281,6 +319,7 @@ func (n *icomNet) Close() error {
|
|||||||
func (n *icomNet) ctrlPump() {
|
func (n *icomNet) ctrlPump() {
|
||||||
buf := make([]byte, 4096)
|
buf := make([]byte, 4096)
|
||||||
lastIdle := time.Now()
|
lastIdle := time.Now()
|
||||||
|
lastCtrlPing := time.Now()
|
||||||
lastToken := time.Now() // token was just granted during dial
|
lastToken := time.Now() // token was just granted during dial
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
@@ -321,6 +360,11 @@ func (n *icomNet) ctrlPump() {
|
|||||||
}
|
}
|
||||||
// Renew well inside the rig's ~2-min token timeout. 30 s (was 45) leaves room
|
// Renew well inside the rig's ~2-min token timeout. 30 s (was 45) leaves room
|
||||||
// for one lost renewal + its retransmit before the token would lapse.
|
// for one lost renewal + its retransmit before the token would lapse.
|
||||||
|
if time.Since(lastCtrlPing) > 500*time.Millisecond {
|
||||||
|
n.ctrlPingSeq++
|
||||||
|
_, _ = n.ctrl.Write(icnPing(n.ctrlPingSeq, n.cID, n.cRemote, uint32(time.Since(n.started).Milliseconds())))
|
||||||
|
lastCtrlPing = time.Now()
|
||||||
|
}
|
||||||
if time.Since(lastToken) > 30*time.Second {
|
if time.Since(lastToken) > 30*time.Second {
|
||||||
n.renewToken()
|
n.renewToken()
|
||||||
lastToken = time.Now()
|
lastToken = time.Now()
|
||||||
@@ -359,6 +403,25 @@ func (n *icomNet) civPump() {
|
|||||||
buf := make([]byte, 8192)
|
buf := make([]byte, 8192)
|
||||||
lastIdle := time.Now()
|
lastIdle := time.Now()
|
||||||
lastReq := time.Now()
|
lastReq := time.Now()
|
||||||
|
// Diagnosis for the recurring 2-3-minute silence a real IC-7760 shows on
|
||||||
|
// this stream while the control link stays alive: when the stream has been
|
||||||
|
// quiet for 10 s, say so ONCE, with the last read error — a socket error
|
||||||
|
// and a rig that stopped talking are different repairs, and the 30 s
|
||||||
|
// watchdog that follows cannot tell them apart from where it sits.
|
||||||
|
debugLog.Printf("icom net: client pings armed on the CI-V stream (every 500 ms)")
|
||||||
|
lastPkt := time.Now()
|
||||||
|
lastPing := time.Now()
|
||||||
|
lastData := time.Now() // CI-V payload packets (replies + transceive)
|
||||||
|
lastScope := time.Time{} // scope frames within those
|
||||||
|
var lastErr error
|
||||||
|
quietSaid := false
|
||||||
|
gaveUp := false
|
||||||
|
// sawData: this session has heard at least one CI-V payload. A radio in
|
||||||
|
// STANDBY is silent on CI-V by design — only the transport chats — and the
|
||||||
|
// quiet-recovery below must not treat that as a fault: it was tearing the
|
||||||
|
// session down every 15 s, and with it the console and its ON button, so a
|
||||||
|
// radio that was off when OpsLog started could never be turned on at all.
|
||||||
|
sawData := false
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-n.done:
|
case <-n.done:
|
||||||
@@ -366,7 +429,14 @@ func (n *icomNet) civPump() {
|
|||||||
default:
|
default:
|
||||||
}
|
}
|
||||||
_ = n.civ.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
|
_ = n.civ.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
|
||||||
if k, err := n.civ.Read(buf); err == nil && k >= 16 {
|
k, err := n.civ.Read(buf)
|
||||||
|
if err != nil {
|
||||||
|
if e, ok := err.(net.Error); !ok || !e.Timeout() {
|
||||||
|
lastErr = err // a REAL socket error, not the read deadline
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err == nil && k >= 16 {
|
||||||
|
lastPkt = time.Now()
|
||||||
n.markRx()
|
n.markRx()
|
||||||
switch typ := icnLE.Uint16(buf[4:]); {
|
switch typ := icnLE.Uint16(buf[4:]); {
|
||||||
case typ == 0x07: // ping
|
case typ == 0x07: // ping
|
||||||
@@ -379,6 +449,13 @@ func (n *icomNet) civPump() {
|
|||||||
n.dead.Store(true) // make Alive() fail now → prompt clean reconnect
|
n.dead.Store(true) // make Alive() fail now → prompt clean reconnect
|
||||||
debugLog.Printf("icom net: rig sent DISCONNECT on CI-V stream — session dropped by the rig")
|
debugLog.Printf("icom net: rig sent DISCONNECT on CI-V stream — session dropped by the rig")
|
||||||
case typ == 0x00 && k > 0x15 && buf[0x10] == 0xc1: // CI-V data
|
case typ == 0x00 && k > 0x15 && buf[0x10] == 0xc1: // CI-V data
|
||||||
|
if quietSaid {
|
||||||
|
debugLog.Printf("icom net: CI-V replies are back after %s", time.Since(lastData).Round(time.Second))
|
||||||
|
quietSaid, gaveUp = false, false
|
||||||
|
}
|
||||||
|
sawData = true
|
||||||
|
lastData = time.Now()
|
||||||
|
n.txAtData.Store(n.txCiv.Load())
|
||||||
n.trackRxSeq(icnLE.Uint16(buf[6:])) // note gaps for retransmit
|
n.trackRxSeq(icnLE.Uint16(buf[6:])) // note gaps for retransmit
|
||||||
civBytes := buf[0x15:k]
|
civBytes := buf[0x15:k]
|
||||||
cp := append([]byte(nil), civBytes...)
|
cp := append([]byte(nil), civBytes...)
|
||||||
@@ -388,6 +465,7 @@ func (n *icomNet) civPump() {
|
|||||||
// feeder in IcomSerial picks them up. Everything else is a control
|
// feeder in IcomSerial picks them up. Everything else is a control
|
||||||
// reply → rx → Read.
|
// reply → rx → Read.
|
||||||
if len(civBytes) >= 5 && civBytes[4] == 0x27 {
|
if len(civBytes) >= 5 && civBytes[4] == 0x27 {
|
||||||
|
lastScope = time.Now()
|
||||||
icnEnqueueDrop(n.scopeRx, cp)
|
icnEnqueueDrop(n.scopeRx, cp)
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -410,14 +488,69 @@ func (n *icomNet) civPump() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if !quietSaid && sawData && time.Since(lastData) > 10*time.Second {
|
||||||
|
quietSaid = true
|
||||||
|
scopeAge := "never"
|
||||||
|
if !lastScope.IsZero() {
|
||||||
|
scopeAge = time.Since(lastScope).Round(time.Second).String()
|
||||||
|
}
|
||||||
|
debugLog.Printf("icom net: no CI-V DATA for 10 s (transport last heard %s ago; last scope frame %s ago; last socket error: %v; missing-seq backlog: %d; CI-V commands SENT since the last answer: %d)",
|
||||||
|
time.Since(lastPkt).Round(time.Second), scopeAge, lastErr, len(n.rxMissing), n.txCiv.Load()-n.txAtData.Load())
|
||||||
|
// And try the gentle repair before the 30 s watchdog tears the whole
|
||||||
|
// session down: if the rig quietly closed the CI-V data flow (the
|
||||||
|
// transport is still chatting, so the session itself stands), saying
|
||||||
|
// "open" again on the same stream is all it should take. Harmless
|
||||||
|
// when the cause is elsewhere — the watchdog still fires at 30 s.
|
||||||
|
n.seqMu.Lock()
|
||||||
|
seq, civSeq := n.vTracked, n.vCivSeq
|
||||||
|
n.vTracked++
|
||||||
|
n.vCivSeq++
|
||||||
|
n.seqMu.Unlock()
|
||||||
|
ocPkt := icnOpenClose(seq, n.vID, n.vRemote, civSeq, 0x04)
|
||||||
|
n.sentMu.Lock()
|
||||||
|
n.sentBuf[seq] = ocPkt
|
||||||
|
n.sentMu.Unlock()
|
||||||
|
_, _ = n.civ.Write(ocPkt)
|
||||||
|
debugLog.Printf("icom net: re-sent the CI-V open on the existing stream")
|
||||||
|
}
|
||||||
|
// The reopen was given five seconds. On a real IC-7760 it never works —
|
||||||
|
// the rig ignores it and only a fresh session brings CI-V back — so
|
||||||
|
// rather than sit out the 30 s watchdog, fail the link NOW and let the
|
||||||
|
// manager rebuild it: the outage drops from ~35 s to ~15.
|
||||||
|
if quietSaid && !gaveUp && time.Since(lastData) > 15*time.Second {
|
||||||
|
gaveUp = true
|
||||||
|
n.dead.Store(true)
|
||||||
|
debugLog.Printf("icom net: the reopen did not bring CI-V back — forcing a fresh session")
|
||||||
|
}
|
||||||
if time.Since(lastIdle) > 150*time.Millisecond {
|
if time.Since(lastIdle) > 150*time.Millisecond {
|
||||||
_, _ = n.civ.Write(icnCtrl(0x00, 0, n.vID, n.vRemote))
|
// Idles carry a REAL sequence number, drawn from the same counter as
|
||||||
|
// the data packets, and sit in the retransmit buffer like them —
|
||||||
|
// which is how RS-BA1 and wfview number theirs. Ours used seq 0 on
|
||||||
|
// every idle, seven a second, interleaved with properly-numbered
|
||||||
|
// data; a rig that follows the sequence tolerates that for a minute
|
||||||
|
// or so and then stops serving CI-V data on the stream — which is
|
||||||
|
// the shape of every dropout this loaner IC-7760 has shown, with
|
||||||
|
// the scope and the TX path both since eliminated.
|
||||||
|
n.seqMu.Lock()
|
||||||
|
iseq := n.vTracked
|
||||||
|
n.vTracked++
|
||||||
|
n.seqMu.Unlock()
|
||||||
|
ipkt := icnCtrl(0x00, iseq, n.vID, n.vRemote)
|
||||||
|
n.sentMu.Lock()
|
||||||
|
n.sentBuf[iseq] = ipkt
|
||||||
|
n.sentMu.Unlock()
|
||||||
|
_, _ = n.civ.Write(ipkt)
|
||||||
lastIdle = time.Now()
|
lastIdle = time.Now()
|
||||||
}
|
}
|
||||||
if time.Since(lastReq) > 100*time.Millisecond {
|
if time.Since(lastReq) > 100*time.Millisecond {
|
||||||
n.sendRetransmitReq()
|
n.sendRetransmitReq()
|
||||||
lastReq = time.Now()
|
lastReq = time.Now()
|
||||||
}
|
}
|
||||||
|
if time.Since(lastPing) > 500*time.Millisecond {
|
||||||
|
n.civPingSeq++
|
||||||
|
_, _ = n.civ.Write(icnPing(n.civPingSeq, n.vID, n.vRemote, uint32(time.Since(n.started).Milliseconds())))
|
||||||
|
lastPing = time.Now()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -661,6 +794,7 @@ func dialIcomNet(host, user, pass, compName string, rigAddr byte, cancel <-chan
|
|||||||
cTracked: cTracked, cAuthSeq: cInner,
|
cTracked: cTracked, cAuthSeq: cInner,
|
||||||
cToken: token, cTokReq: tokReq,
|
cToken: token, cTokReq: tokReq,
|
||||||
cSentBuf: make(map[uint16][]byte),
|
cSentBuf: make(map[uint16][]byte),
|
||||||
|
started: time.Now(),
|
||||||
}
|
}
|
||||||
n.markRx() // the successful handshake counts as initial rig activity
|
n.markRx() // the successful handshake counts as initial rig activity
|
||||||
// openClose(open) starts the CI-V data flow. We intentionally DO NOT power the
|
// openClose(open) starts the CI-V data flow. We intentionally DO NOT power the
|
||||||
@@ -712,6 +846,11 @@ func icnHandshake(c *net.UDPConn, myID uint32, cancel <-chan struct{}) (uint32,
|
|||||||
}
|
}
|
||||||
typ := icnLE.Uint16(p[4:])
|
typ := icnLE.Uint16(p[4:])
|
||||||
sentid := icnLE.Uint32(p[8:])
|
sentid := icnLE.Uint32(p[8:])
|
||||||
|
// Every packet the rig sends during the handshake, verbatim. A radio that
|
||||||
|
// answers SOMETHING unrecognised (a newer model, a different firmware) and
|
||||||
|
// a radio that answers nothing are different faults, and a silent timeout
|
||||||
|
// hides which one this is.
|
||||||
|
icnHandshakeProbe(p)
|
||||||
switch typ {
|
switch typ {
|
||||||
case 0x04: // iAmHere
|
case 0x04: // iAmHere
|
||||||
remoteID = sentid
|
remoteID = sentid
|
||||||
@@ -843,11 +982,20 @@ func icnConnInfo(seq, innerSeq, tokReq uint16, sentid, rcvdid, token uint32, use
|
|||||||
copy(b[0x40:0x60], []byte("IC-7610"))
|
copy(b[0x40:0x60], []byte("IC-7610"))
|
||||||
copy(b[0x60:0x70], icnPasscode(user))
|
copy(b[0x60:0x70], icnPasscode(user))
|
||||||
b[0x70] = rxEnable // rxenable: 1 opens the 50003 RX audio stream, 0 = CI-V only
|
b[0x70] = rxEnable // rxenable: 1 opens the 50003 RX audio stream, 0 = CI-V only
|
||||||
b[0x71] = 0x00 // txenable (Phase 5)
|
// TX rides the same audio session: whenever the operator wants RX audio the
|
||||||
b[0x72] = 0x10 // rxcodec
|
// TX side is opened with it, so the voice keyer can play to the radio with
|
||||||
b[0x73] = 0x04 // txcodec
|
// no cable. Costs nothing when unused — no packets flow until a message is
|
||||||
|
// actually played.
|
||||||
|
b[0x71] = rxEnable // txenable
|
||||||
|
// rxcodec 0x04 = LPCM, ONE channel, 16-BIT — settled by experiment on a
|
||||||
|
// real IC-7760, one wrong guess at a time: 0x10 produced 1280-byte payloads
|
||||||
|
// of interleaved 16-bit stereo, 0x02 produced 320-byte payloads of 8-bit
|
||||||
|
// mono (samples hugging 0x80). 0x04 sits between them in the codec table
|
||||||
|
// (as in wfview): 16-bit mono, the format the 16 kHz playback path plays.
|
||||||
|
b[0x72] = 0x04 // rxcodec
|
||||||
|
b[0x73] = 0x04 // txcodec
|
||||||
icnBE.PutUint32(b[0x74:], 16000)
|
icnBE.PutUint32(b[0x74:], 16000)
|
||||||
icnBE.PutUint32(b[0x78:], 8000)
|
icnBE.PutUint32(b[0x78:], 16000) // TX sample rate — the same 16 kHz everything else here runs at
|
||||||
icnBE.PutUint32(b[0x7c:], uint32(civPort))
|
icnBE.PutUint32(b[0x7c:], uint32(civPort))
|
||||||
icnBE.PutUint32(b[0x80:], uint32(audioPort))
|
icnBE.PutUint32(b[0x80:], uint32(audioPort))
|
||||||
icnBE.PutUint32(b[0x84:], 100)
|
icnBE.PutUint32(b[0x84:], 100)
|
||||||
@@ -855,6 +1003,26 @@ func icnConnInfo(seq, innerSeq, tokReq uint16, sentid, rcvdid, token uint32, use
|
|||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PlayTXAudio plays one voice-keyer message through the 50003 audio session.
|
||||||
|
// On the transport because the transport owns the session; the IcomSerial
|
||||||
|
// controller forwards here after a type assertion, exactly as the TCI path
|
||||||
|
// reaches its radio.
|
||||||
|
func (n *icomNet) PlayTXAudio(pcm []byte, rate, ch, bits int, stop <-chan struct{}) error {
|
||||||
|
if n.audio == nil {
|
||||||
|
return fmt.Errorf("the radio's audio stream is not open — enable RX audio in Settings → CAT first")
|
||||||
|
}
|
||||||
|
return n.audio.PlayTX(pcm, rate, ch, bits, stop)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TXAudioSender returns a function that streams live microphone chunks to the
|
||||||
|
// rig — the talk button's road, where PlayTXAudio is the voice keyer's.
|
||||||
|
func (n *icomNet) TXAudioSender() (func([]byte) error, error) {
|
||||||
|
if n.audio == nil {
|
||||||
|
return nil, fmt.Errorf("the radio's audio stream is not open — enable RX audio in Settings → CAT first")
|
||||||
|
}
|
||||||
|
return n.audio.SendTXChunk, nil
|
||||||
|
}
|
||||||
|
|
||||||
func icnOpenClose(seq uint16, sentid, rcvdid uint32, civSeq uint16, magic byte) []byte {
|
func icnOpenClose(seq uint16, sentid, rcvdid uint32, civSeq uint16, magic byte) []byte {
|
||||||
b := make([]byte, 0x16)
|
b := make([]byte, 0x16)
|
||||||
icnLE.PutUint32(b[0:], 0x16)
|
icnLE.PutUint32(b[0:], 0x16)
|
||||||
@@ -903,3 +1071,38 @@ func icnPasscode(s string) []byte {
|
|||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// icnHandshakeProbe logs the first packets seen during a control handshake —
|
||||||
|
// capped hard, because a working handshake would log for ever.
|
||||||
|
var icnProbeCount int
|
||||||
|
|
||||||
|
func icnHandshakeProbe(p []byte) {
|
||||||
|
if icnProbeCount >= 12 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
icnProbeCount++
|
||||||
|
n := len(p)
|
||||||
|
if n > 32 {
|
||||||
|
n = 32
|
||||||
|
}
|
||||||
|
debugLog.Printf("icom net: handshake rx %d bytes: % X", len(p), p[:n])
|
||||||
|
}
|
||||||
|
|
||||||
|
// icnPing builds a CLIENT ping request (wfview's ping_packet: 0x15 bytes,
|
||||||
|
// type 0x07, reply=0, a monotonic time at 0x11). The rig answers each one —
|
||||||
|
// and, decisively, treats them as the client's sign of life: wfview sends one
|
||||||
|
// every 500 ms on every stream, and OpsLog, which only ever REPLIED to the
|
||||||
|
// rig's pings, watched the IC-7760 stop serving CI-V data about a minute into
|
||||||
|
// every session. Same socket answered, same transport alive: the rig had
|
||||||
|
// simply concluded nobody was listening.
|
||||||
|
func icnPing(seq uint16, sentid, rcvdid uint32, ms uint32) []byte {
|
||||||
|
b := make([]byte, 0x15)
|
||||||
|
icnLE.PutUint32(b[0:], 0x15)
|
||||||
|
icnLE.PutUint16(b[4:], 0x07)
|
||||||
|
icnLE.PutUint16(b[6:], seq)
|
||||||
|
icnLE.PutUint32(b[8:], sentid)
|
||||||
|
icnLE.PutUint32(b[12:], rcvdid)
|
||||||
|
b[0x10] = 0x00
|
||||||
|
icnLE.PutUint32(b[0x11:], ms)
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|||||||
+168
-12
@@ -116,7 +116,13 @@ type IcomSerial struct {
|
|||||||
// "alive but silent" tolerance below, which used to be
|
// "alive but silent" tolerance below, which used to be
|
||||||
// unbounded and left the display frozen for ever
|
// unbounded and left the display frozen for ever
|
||||||
silentGrace time.Duration // current width of that tolerance (backs off, see ReadState)
|
silentGrace time.Duration // current width of that tolerance (backs off, see ReadState)
|
||||||
dspLoaded bool // readDSP has run since the rig became responsive (loads all
|
// Needle inertia for the TX meters — the CI-V meters are point samples, and
|
||||||
|
// between two SSB syllables a poll lands on 0 W and a perfect SWR. See
|
||||||
|
// meterPeak (yaesu_panel.go): power decays like a needle, SWR holds then
|
||||||
|
// snaps back to the live truth.
|
||||||
|
powerPeak meterPeak
|
||||||
|
swrPeak meterPeak
|
||||||
|
dspLoaded bool // readDSP has run since the rig became responsive (loads all
|
||||||
// the panel's set-once controls once the rig actually answers)
|
// the panel's set-once controls once the rig actually answers)
|
||||||
// When the console last asked for the DSP snapshot. The meters and the
|
// When the console last asked for the DSP snapshot. The meters and the
|
||||||
// front-panel rotation are polled ONLY while something is displaying them:
|
// front-panel rotation are polled ONLY while something is displaying them:
|
||||||
@@ -262,6 +268,21 @@ func (b *IcomSerial) Connect() error {
|
|||||||
// non-default address still RENDERS; this flag only drives the SET/read commands
|
// non-default address still RENDERS; this flag only drives the SET/read commands
|
||||||
// (mode, span, edges), which need the 0x00 selector to be accepted on the 7300.
|
// (mode, span, edges), which need the 0x00 selector to be accepted on the 7300.
|
||||||
b.dualScope = idAddr == 0x98 || idAddr == 0xA2 || idAddr == 0x94
|
b.dualScope = idAddr == 0x98 || idAddr == 0xA2 || idAddr == 0x94
|
||||||
|
// Silence any LEFTOVER waveform stream, BLIND, before anything else. The
|
||||||
|
// 0x27 output flag lives in the RADIO and survives sessions; its flood is
|
||||||
|
// what makes the IC-7760 stop answering CI-V — so waiting for CI-V to
|
||||||
|
// answer before sending this (the first attempt did) was the egg asking
|
||||||
|
// the chicken to hatch it. Fire-and-forget: an unanswered set costs one
|
||||||
|
// frame, and the rig acts on what it decodes whether or not we hear the
|
||||||
|
// acknowledgement. The front-panel display is deliberately untouched.
|
||||||
|
// Synchronously: Connect already runs on the CAT goroutine, and a stray
|
||||||
|
// goroutine writing to the shared link would interleave with the command
|
||||||
|
// loop. Two forms, because the selector byte differs by model and a NAK
|
||||||
|
// costs one frame — and the results are LOGGED, because a kill that quietly
|
||||||
|
// fails leaves the flood running and the next dropout unexplained.
|
||||||
|
err1 := b.execScope("waveform output off (leftover)", civ.SubScopeOn, 0)
|
||||||
|
err2 := b.exec(civ.CmdScope, civ.SubScopeOn, 0x00, 0x00) // main-selector form
|
||||||
|
applog.Printf("icom: waveform-off sent at connect (plain: %v, with selector: %v)", err1, err2)
|
||||||
// Defer the DSP snapshot until the rig actually answers CI-V. Over the network
|
// Defer the DSP snapshot until the rig actually answers CI-V. Over the network
|
||||||
// the rig may still be booting (or off) at Connect, so an immediate readDSP
|
// the rig may still be booting (or off) at Connect, so an immediate readDSP
|
||||||
// would time out and leave every control at 0 / off with no retry. ReadState
|
// would time out and leave every control at 0 / off with no retry. ReadState
|
||||||
@@ -347,7 +368,12 @@ func (b *IcomSerial) ReadState() (RigState, error) {
|
|||||||
case readerGone:
|
case readerGone:
|
||||||
debugLog.Printf("icom net: the CI-V reader has exited — the connection is dead however alive the control link looks → reconnecting")
|
debugLog.Printf("icom net: the CI-V reader has exited — the connection is dead however alive the control link looks → reconnecting")
|
||||||
case at.Alive():
|
case at.Alive():
|
||||||
debugLog.Printf("icom net: control link answers but no CI-V reply for %s → reconnecting. Another program (WSJT-X/OmniRig, the Remote Utility) has most likely taken the CI-V session.", silentFor.Round(time.Second))
|
// No verdict on WHY: this fires for a session taken by another
|
||||||
|
// program (WSJT-X, the Remote Utility) AND for a rig that simply
|
||||||
|
// stopped answering — a real IC-7760 did exactly that once with
|
||||||
|
// nothing else on the network. Blaming a hijacker sent that
|
||||||
|
// operator hunting software that was not installed.
|
||||||
|
debugLog.Printf("icom net: control link answers but no CI-V reply for %s → reconnecting. Either another program took the CI-V session (WSJT-X/OmniRig/Remote Utility), or the rig stopped answering on its own.", silentFor.Round(time.Second))
|
||||||
default:
|
default:
|
||||||
debugLog.Printf("icom net: control link went quiet (no rig packets for >6 s) → reconnecting. If this recurs every ~2-3 min, the rig is invalidating the session (token renewal rejected).")
|
debugLog.Printf("icom net: control link went quiet (no rig packets for >6 s) → reconnecting. If this recurs every ~2-3 min, the rig is invalidating the session (token renewal rejected).")
|
||||||
}
|
}
|
||||||
@@ -396,6 +422,19 @@ func (b *IcomSerial) ReadState() (RigState, error) {
|
|||||||
}
|
}
|
||||||
b.dspMu.Lock()
|
b.dspMu.Lock()
|
||||||
b.dsp.Mode = s.Mode
|
b.dsp.Mode = s.Mode
|
||||||
|
// The console says which SIDEBAND, not the ADIF family: "SSB" on 40 m
|
||||||
|
// leaves the operator guessing whether the rig is where convention puts
|
||||||
|
// it. The log keeps SSB; the panel shows what the radio is actually doing.
|
||||||
|
switch b.curModeByte {
|
||||||
|
case civ.ModeUSB:
|
||||||
|
if s.Mode == "SSB" {
|
||||||
|
b.dsp.Mode = "USB"
|
||||||
|
}
|
||||||
|
case civ.ModeLSB:
|
||||||
|
if s.Mode == "SSB" {
|
||||||
|
b.dsp.Mode = "LSB"
|
||||||
|
}
|
||||||
|
}
|
||||||
b.dspMu.Unlock()
|
b.dspMu.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -409,8 +448,13 @@ func (b *IcomSerial) ReadState() (RigState, error) {
|
|||||||
// all, for the user's Set* commands.
|
// all, for the user's Set* commands.
|
||||||
if b.pollN%4 == 1 {
|
if b.pollN%4 == 1 {
|
||||||
b.splitOn, b.splitTXFreq = false, 0
|
b.splitOn, b.splitTXFreq = false, 0
|
||||||
if on, ok := b.readSplit(); ok && on {
|
on, okSplit := b.readSplit()
|
||||||
if txHz, ok2 := b.readTXFreq(); ok2 && txHz > 0 {
|
// The unselected VFO is read split or NOT: on a dual-receiver rig it is
|
||||||
|
// the sub receiver's dial, and the console showed it blank until split
|
||||||
|
// was engaged.
|
||||||
|
if txHz, ok2 := b.readTXFreq(); ok2 && txHz > 0 {
|
||||||
|
b.setCache(func(st *IcomTXState) { st.SubHz = txHz })
|
||||||
|
if okSplit && on {
|
||||||
b.splitOn, b.splitTXFreq = true, txHz
|
b.splitOn, b.splitTXFreq = true, txHz
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -435,12 +479,16 @@ func (b *IcomSerial) ReadState() (RigState, error) {
|
|||||||
sm, _ = b.readMeter(civ.SubMeterS)
|
sm, _ = b.readMeter(civ.SubMeterS)
|
||||||
po, swr = 0, 0
|
po, swr = 0, 0
|
||||||
if tx {
|
if tx {
|
||||||
|
now := time.Now()
|
||||||
if v, ok := b.readMeter(civ.SubMeterPo); ok {
|
if v, ok := b.readMeter(civ.SubMeterPo); ok {
|
||||||
po = v
|
po = b.powerPeak.update(v, now)
|
||||||
}
|
}
|
||||||
if v, ok := b.readMeter(civ.SubMeterSWR); ok {
|
if v, ok := b.readMeter(civ.SubMeterSWR); ok {
|
||||||
swr = v
|
swr = b.swrPeak.updateSnap(v, now)
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
// Cleared with the carrier, so the next transmission starts fresh.
|
||||||
|
b.powerPeak, b.swrPeak = meterPeak{}, meterPeak{}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
b.dspMu.Lock()
|
b.dspMu.Lock()
|
||||||
@@ -509,6 +557,13 @@ func (b *IcomSerial) refreshFrontPanel() {
|
|||||||
b.dsp.Filter = int(f)
|
b.dsp.Filter = int(f)
|
||||||
b.dspMu.Unlock()
|
b.dspMu.Unlock()
|
||||||
}
|
}
|
||||||
|
case 2:
|
||||||
|
// Tuner in/out — the radio's own TUNER button changes it mid-session.
|
||||||
|
if v, ok := b.readSwitchSub(civ.CmdATU, civ.SubATU); ok {
|
||||||
|
b.dspMu.Lock()
|
||||||
|
b.dsp.ATUOn = v == 1
|
||||||
|
b.dspMu.Unlock()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -559,6 +614,18 @@ func (b *IcomSerial) SetMode(mode string) error {
|
|||||||
}
|
}
|
||||||
// Filter 0x01 (FIL1) is the conventional default for the data-mode set.
|
// Filter 0x01 (FIL1) is the conventional default for the data-mode set.
|
||||||
_ = b.execIdempotent("set data mode", civ.CmdExtra, civ.SubDataMode, dataByte, 0x01)
|
_ = b.execIdempotent("set data mode", civ.CmdExtra, civ.SubDataMode, dataByte, 0x01)
|
||||||
|
// Trust, then verify: the IC-7760 acknowledges 1A 06 and stays in USB-D
|
||||||
|
// anyway, which left an operator unable to get back to plain USB at all.
|
||||||
|
// When the readback disagrees, say it again with 0x26 — mode, data flag and
|
||||||
|
// filter in one frame, the command the newer rigs actually honour. Only on
|
||||||
|
// a mismatch, so rigs that predate 0x26 never see it.
|
||||||
|
if got := b.readDataMode(); got != data {
|
||||||
|
if err := b.execIdempotent("set mode+data (0x26)", civ.CmdModeDataFil, 0x00, code, dataByte, 0x01); err != nil {
|
||||||
|
applog.Printf("icom: data flag stuck at %v after mode %s, and 0x26 failed too: %v", got, mode, err)
|
||||||
|
} else {
|
||||||
|
applog.Printf("icom: data flag stuck after 1A06, corrected via 0x26 (mode %s)", mode)
|
||||||
|
}
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1482,6 +1549,12 @@ func (b *IcomSerial) modeCode(mode string) (code byte, data bool, err error) {
|
|||||||
return civ.ModeFM, false, nil
|
return civ.ModeFM, false, nil
|
||||||
case "RTTY", "FSK":
|
case "RTTY", "FSK":
|
||||||
return civ.ModeRTTY, false, nil
|
return civ.ModeRTTY, false, nil
|
||||||
|
case "PSK":
|
||||||
|
// The console button, not the ADIF mode: the rigs that HAVE a native PSK
|
||||||
|
// mode (7610/7760/7851 class) get it; a 7300 NAKs 0x12 and the button
|
||||||
|
// stays dead there, exactly as RS-BA1's does. Soundcard PSK31 stays on
|
||||||
|
// USB-D below, where every rig can do it.
|
||||||
|
return civ.ModePSK, false, nil
|
||||||
case "FT8", "FT4", "PSK31", "MFSK", "JS8", "JT65", "JT9", "OLIVIA", "DATA", "DIGITALVOICE":
|
case "FT8", "FT4", "PSK31", "MFSK", "JS8", "JT65", "JT9", "OLIVIA", "DATA", "DIGITALVOICE":
|
||||||
// Digital data modes ride on USB with the data flag set (FT8 etc.).
|
// Digital data modes ride on USB with the data flag set (FT8 etc.).
|
||||||
return civ.ModeUSB, true, nil
|
return civ.ModeUSB, true, nil
|
||||||
@@ -1832,10 +1905,16 @@ func (b *IcomSerial) SetMicGain(p int) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (b *IcomSerial) SetIcomSplit(on bool) error {
|
func (b *IcomSerial) SetIcomSplit(on bool) error {
|
||||||
|
return b.SetIcomSplitOffset(on, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetIcomSplitOffset enables split with a CHOSEN TX offset in Hz (0 = the
|
||||||
|
// usual convention: +1 kHz on CW, +5 kHz otherwise). The console offers
|
||||||
|
// +1/+5/+10 directly, DXpedition style.
|
||||||
|
func (b *IcomSerial) SetIcomSplitOffset(on bool, offsetHz int64) error {
|
||||||
if on {
|
if on {
|
||||||
// Enable split with the usual "work him up" TX offset: +1 kHz on CW,
|
// Set the unselected (TX) VFO to RX+offset first, then turn split on.
|
||||||
// +5 kHz otherwise (SSB). Set the unselected (TX) VFO to RX+offset first,
|
// 0x25 0x01 + BCD sets the unselected VFO's frequency.
|
||||||
// then turn split on. 0x25 0x01 + BCD sets the unselected VFO's frequency.
|
|
||||||
rx := b.curFreq
|
rx := b.curFreq
|
||||||
if rx <= 0 {
|
if rx <= 0 {
|
||||||
if hz, err := b.readFreq(); err == nil {
|
if hz, err := b.readFreq(); err == nil {
|
||||||
@@ -1843,12 +1922,39 @@ func (b *IcomSerial) SetIcomSplit(on bool) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if rx > 0 {
|
if rx > 0 {
|
||||||
offset := int64(5000)
|
offset := offsetHz
|
||||||
if b.curModeByte == civ.ModeCW || b.curModeByte == civ.ModeCWR {
|
if offset <= 0 {
|
||||||
offset = 1000
|
offset = 5000
|
||||||
|
if b.curModeByte == civ.ModeCW || b.curModeByte == civ.ModeCWR {
|
||||||
|
offset = 1000
|
||||||
|
}
|
||||||
}
|
}
|
||||||
_ = b.exec(append([]byte{civ.CmdVfoFreq, civ.SubVfoUnselected}, civ.FreqToBCD(rx+offset)...)...)
|
_ = b.exec(append([]byte{civ.CmdVfoFreq, civ.SubVfoUnselected}, civ.FreqToBCD(rx+offset)...)...)
|
||||||
}
|
}
|
||||||
|
// And the MODE crosses with it: a split where the TX VFO is still on
|
||||||
|
// yesterday's mode transmits FM into a CW pileup. 0x26 0x01 sets the
|
||||||
|
// unselected VFO's mode + data flag in one frame; rigs that predate
|
||||||
|
// 0x26 NAK it harmlessly and behave as they always did.
|
||||||
|
if b.curModeByte == 0 {
|
||||||
|
// A fresh session may not have read the mode yet — ask, or the copy
|
||||||
|
// below would send mode 0 (LSB) whatever the main is on.
|
||||||
|
if m, ok := b.readMode(); ok {
|
||||||
|
b.curModeByte = m
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if b.curModeByte != 0 {
|
||||||
|
dataByte := byte(0)
|
||||||
|
if got := b.readDataMode(); got {
|
||||||
|
dataByte = 1
|
||||||
|
}
|
||||||
|
// Logged, not discarded: the first version swallowed the error and a
|
||||||
|
// real 7760's sub VFO kept yesterday's mode with nothing to show why.
|
||||||
|
if err := b.exec(civ.CmdModeDataFil, 0x01, b.curModeByte, dataByte, 0x01); err != nil {
|
||||||
|
applog.Printf("icom: split mode-align (26 01 %02X %d) refused: %v", b.curModeByte, dataByte, err)
|
||||||
|
} else {
|
||||||
|
applog.Printf("icom: split mode-align OK (26 01 %02X %d)", b.curModeByte, dataByte)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if err := b.exec(civ.CmdSplit, boolByte(on)); err != nil {
|
if err := b.exec(civ.CmdSplit, boolByte(on)); err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -1982,6 +2088,17 @@ func (b *IcomSerial) TuneATU() error {
|
|||||||
return b.exec(civ.CmdATU, civ.SubATU, 0x02)
|
return b.exec(civ.CmdATU, civ.SubATU, 0x02)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetATU engages or DISENGAGES the internal tuner (0x1C 0x01: 1 = in line,
|
||||||
|
// 0 = through). Tune existed without this, which meant a tuner once engaged
|
||||||
|
// could not be taken out of line again from the console.
|
||||||
|
func (b *IcomSerial) SetATU(on bool) error {
|
||||||
|
if err := b.exec(civ.CmdATU, civ.SubATU, boolByte(on)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
b.setCache(func(s *IcomTXState) { s.ATUOn = on })
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (b *IcomSerial) setCache(fn func(*IcomTXState)) {
|
func (b *IcomSerial) setCache(fn func(*IcomTXState)) {
|
||||||
b.dspMu.Lock()
|
b.dspMu.Lock()
|
||||||
fn(&b.dsp)
|
fn(&b.dsp)
|
||||||
@@ -2024,3 +2141,42 @@ func agcValue(name string) byte {
|
|||||||
}
|
}
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PlayTXAudio hands a voice-keyer message to the network audio session, when
|
||||||
|
// this rig is reached over one. A USB-connected Icom takes its audio through
|
||||||
|
// its own sound card instead, and says so.
|
||||||
|
func (b *IcomSerial) PlayTXAudio(pcm []byte, rate, ch, bits int, stop <-chan struct{}) error {
|
||||||
|
// port is written once per Connect, on the CAT goroutine this is fetched
|
||||||
|
// from (IcomDo); at worst a reconnect leaves this one connection stale, and
|
||||||
|
// a stale transport fails fast on its closed done channel.
|
||||||
|
port := b.port
|
||||||
|
// A nil port fails the assertions below too — and used to fail them with
|
||||||
|
// the sound-card message, sending an operator whose radio was simply OFF
|
||||||
|
// hunting through their audio devices.
|
||||||
|
if port == nil {
|
||||||
|
return fmt.Errorf("not connected to the radio — check the CAT link")
|
||||||
|
}
|
||||||
|
type txPlayer interface {
|
||||||
|
PlayTXAudio(pcm []byte, rate, ch, bits int, stop <-chan struct{}) error
|
||||||
|
}
|
||||||
|
if p, ok := port.(txPlayer); ok {
|
||||||
|
return p.PlayTXAudio(pcm, rate, ch, bits, stop)
|
||||||
|
}
|
||||||
|
return fmt.Errorf("this rig takes transmit audio through its USB sound card, not the CAT link")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TXAudioSender hands back the network transport's live-mic sender, when this
|
||||||
|
// rig is reached over one.
|
||||||
|
func (b *IcomSerial) TXAudioSender() (func([]byte) error, error) {
|
||||||
|
port := b.port
|
||||||
|
if port == nil {
|
||||||
|
return nil, fmt.Errorf("not connected to the radio — check the CAT link")
|
||||||
|
}
|
||||||
|
type sender interface {
|
||||||
|
TXAudioSender() (func([]byte) error, error)
|
||||||
|
}
|
||||||
|
if p, ok := port.(sender); ok {
|
||||||
|
return p.TXAudioSender()
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("this rig takes transmit audio through its USB sound card, not the CAT link")
|
||||||
|
}
|
||||||
|
|||||||
@@ -35,6 +35,11 @@ type KenwoodTXState struct {
|
|||||||
Model string `json:"model,omitempty"`
|
Model string `json:"model,omitempty"`
|
||||||
Elecraft bool `json:"elecraft"` // a K3/K4 rather than a Kenwood
|
Elecraft bool `json:"elecraft"` // a K3/K4 rather than a Kenwood
|
||||||
Mode string `json:"mode,omitempty"`
|
Mode string `json:"mode,omitempty"`
|
||||||
|
// DataSub is the K3/K4 DATA submode while in DATA mode (DT): "DATA A",
|
||||||
|
// "AFSK A", "FSK D" or "PSK D". Empty on a Kenwood, and outside DATA. The
|
||||||
|
// panel's two DATA buttons need it to show WHICH data mode the rig is in —
|
||||||
|
// FT8 wants DATA A, RTTY wants FSK D, and MD6 alone cannot say which.
|
||||||
|
DataSub string `json:"data_sub,omitempty"`
|
||||||
|
|
||||||
Transmitting bool `json:"transmitting"`
|
Transmitting bool `json:"transmitting"`
|
||||||
Split bool `json:"split"`
|
Split bool `json:"split"`
|
||||||
@@ -47,9 +52,15 @@ type KenwoodTXState struct {
|
|||||||
SMeterRaw int `json:"s_meter_raw"`
|
SMeterRaw int `json:"s_meter_raw"`
|
||||||
// PowerMeter is 0-100 while transmitting. SWR is the ratio; 0 means "not
|
// PowerMeter is 0-100 while transmitting. SWR is the ratio; 0 means "not
|
||||||
// measured", NOT a perfect match.
|
// measured", NOT a perfect match.
|
||||||
PowerMeter int `json:"power_meter"`
|
PowerMeter int `json:"power_meter"`
|
||||||
SWR float64 `json:"swr"`
|
// PowerW is the transmit power in WATTS, derived from the bargraph and the
|
||||||
SWRRaw int `json:"swr_raw"`
|
// meter's RANGE. The K3's bar is relative to a range that flips at 12 W —
|
||||||
|
// calibrated against a real one: 10 W showed 83 (10/12), 100 W showed 83
|
||||||
|
// too (100/120). The bar alone never was watts; with the PC setting to
|
||||||
|
// pick the range, it converts. 0 while receiving.
|
||||||
|
PowerW int `json:"power_w"`
|
||||||
|
SWR float64 `json:"swr"`
|
||||||
|
SWRRaw int `json:"swr_raw"`
|
||||||
|
|
||||||
RFPower int `json:"rf_power"` // watts, the PC setting
|
RFPower int `json:"rf_power"` // watts, the PC setting
|
||||||
AFGain int `json:"af_gain"` // 0-100
|
AFGain int `json:"af_gain"` // 0-100
|
||||||
@@ -107,10 +118,12 @@ type KenwoodPanelController interface {
|
|||||||
SetKenwoodRIT(bool) error
|
SetKenwoodRIT(bool) error
|
||||||
SetKenwoodXIT(bool) error
|
SetKenwoodXIT(bool) error
|
||||||
NudgeKenwoodRIT(int) error
|
NudgeKenwoodRIT(int) error
|
||||||
|
SetKenwoodRITOffset(int) error
|
||||||
ClearKenwoodRIT() error
|
ClearKenwoodRIT() error
|
||||||
SetKenwoodTX(bool) error
|
SetKenwoodTX(bool) error
|
||||||
TuneKenwoodATU() error
|
TuneKenwoodATU() error
|
||||||
ToggleKenwoodATU() error
|
ToggleKenwoodATU() error
|
||||||
|
SetKenwoodPanelMode(string) error
|
||||||
}
|
}
|
||||||
|
|
||||||
// kenwoodPanelSlowBeat is how many polls pass between full re-reads of the
|
// kenwoodPanelSlowBeat is how many polls pass between full re-reads of the
|
||||||
@@ -155,6 +168,7 @@ func (k *Kenwood) readPanel(mode string, split bool, txHz int64, txNow bool) {
|
|||||||
// Cleared, not frozen: a power bar left standing after the carrier drops
|
// Cleared, not frozen: a power bar left standing after the carrier drops
|
||||||
// reads as a live transmission.
|
// reads as a live transmission.
|
||||||
k.panel.PowerMeter = 0
|
k.panel.PowerMeter = 0
|
||||||
|
k.panel.PowerW = 0
|
||||||
k.panel.SWR, k.panel.SWRRaw = 0, 0
|
k.panel.SWR, k.panel.SWRRaw = 0, 0
|
||||||
k.powerPeak, k.swrPeak = meterPeak{}, meterPeak{}
|
k.powerPeak, k.swrPeak = meterPeak{}, meterPeak{}
|
||||||
// The S-meter only means anything while receiving.
|
// The S-meter only means anything while receiving.
|
||||||
@@ -212,6 +226,14 @@ func (k *Kenwood) readPanelSettings() {
|
|||||||
if v, ok := k.askNum("NR;", "NR", 1); ok {
|
if v, ok := k.askNum("NR;", "NR", 1); ok {
|
||||||
k.panel.NR = v != 0
|
k.panel.NR = v != 0
|
||||||
}
|
}
|
||||||
|
// The DATA submode, Elecraft only (a plain Kenwood has no DT and would "?;"
|
||||||
|
// it). Read every settings beat: the operator changes it from the rig's own
|
||||||
|
// front panel mid-session, and the two DATA buttons must follow.
|
||||||
|
if k.elecraft {
|
||||||
|
if v, ok := k.askNum("DT;", "DT", 1); ok {
|
||||||
|
k.panel.DataSub = kenwoodDataSubName(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
if v, ok := k.askNum("GT;", "GT", 3); ok {
|
if v, ok := k.askNum("GT;", "GT", 3); ok {
|
||||||
k.panel.AGC = kenwoodAGCName(v)
|
k.panel.AGC = kenwoodAGCName(v)
|
||||||
}
|
}
|
||||||
@@ -326,6 +348,13 @@ func (k *Kenwood) readTXMeters() {
|
|||||||
defer func() { k.noLatch = false }()
|
defer func() { k.noLatch = false }()
|
||||||
if v, ok := k.askNum("BG;", "BG", 2); ok {
|
if v, ok := k.askNum("BG;", "BG", 2); ok {
|
||||||
k.panel.PowerMeter = k.powerPeak.update(kenwoodBargraphPercent(v), now)
|
k.panel.PowerMeter = k.powerPeak.update(kenwoodBargraphPercent(v), now)
|
||||||
|
if k.elecraft {
|
||||||
|
scale := 120
|
||||||
|
if k.panel.RFPower > 0 && k.panel.RFPower <= 12 {
|
||||||
|
scale = 12 // the K3's QRP range
|
||||||
|
}
|
||||||
|
k.panel.PowerW = k.panel.PowerMeter * scale / 100
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// SW; — SETTLED, from Elecraft's own release note: three digits, tenths of a
|
// SW; — SETTLED, from Elecraft's own release note: three digits, tenths of a
|
||||||
// ratio. "SW023;" is 2.3:1, and "SW999;" is the 99.9:1 it reports instead of
|
// ratio. "SW023;" is 2.3:1, and "SW999;" is the 99.9:1 it reports instead of
|
||||||
@@ -334,7 +363,7 @@ func (k *Kenwood) readTXMeters() {
|
|||||||
if v, ok := k.askNum("SW;", "SW", 3); ok {
|
if v, ok := k.askNum("SW;", "SW", 3); ok {
|
||||||
k.panel.SWRRaw = v
|
k.panel.SWRRaw = v
|
||||||
if v > 0 {
|
if v > 0 {
|
||||||
k.panel.SWR = float64(k.swrPeak.update(v, now)) / 10
|
k.panel.SWR = float64(k.swrPeak.updateSnap(v, now)) / 10
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if k.metersLogged >= 20 {
|
if k.metersLogged >= 20 {
|
||||||
@@ -564,6 +593,16 @@ func (k *Kenwood) SetKenwoodXIT(on bool) error {
|
|||||||
|
|
||||||
// ClearKenwoodRIT zeroes the RIT/XIT offset, both at once — which is what RC
|
// ClearKenwoodRIT zeroes the RIT/XIT offset, both at once — which is what RC
|
||||||
// does and what the operator means by "clear it".
|
// does and what the operator means by "clear it".
|
||||||
|
// SetKenwoodRITOffset writes the offset as an ABSOLUTE value — what the shared
|
||||||
|
// ShiftRow control speaks. Nudge stays for the keyboard clarifier; both funnel
|
||||||
|
// into the same RO write.
|
||||||
|
func (k *Kenwood) SetKenwoodRITOffset(hz int) error {
|
||||||
|
k.mu.Lock()
|
||||||
|
cur := k.panel.RITOffset
|
||||||
|
k.mu.Unlock()
|
||||||
|
return k.NudgeKenwoodRIT(hz - cur)
|
||||||
|
}
|
||||||
|
|
||||||
func (k *Kenwood) ClearKenwoodRIT() error {
|
func (k *Kenwood) ClearKenwoodRIT() error {
|
||||||
return k.setPanel("RC;")
|
return k.setPanel("RC;")
|
||||||
}
|
}
|
||||||
@@ -650,3 +689,58 @@ func (k *Kenwood) askNum(cmd, prefix string, digits int) (int, bool) {
|
|||||||
}
|
}
|
||||||
return n, true
|
return n, true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// kenwoodDataSubName decodes DT (K3/K4 programmer's reference).
|
||||||
|
func kenwoodDataSubName(v int) string {
|
||||||
|
switch v {
|
||||||
|
case 0:
|
||||||
|
return "DATA A"
|
||||||
|
case 1:
|
||||||
|
return "AFSK A"
|
||||||
|
case 2:
|
||||||
|
return "FSK D"
|
||||||
|
case 3:
|
||||||
|
return "PSK D"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetKenwoodPanelMode is the panel's mode row: CW / USB / LSB / DATA / RTTY.
|
||||||
|
//
|
||||||
|
// It exists because SetMode is the LOGGER's path — it maps an ADIF mode and
|
||||||
|
// honours the data-mode preference — while a panel button is the operator
|
||||||
|
// saying exactly what the rig should do. The two DATA cases are the point:
|
||||||
|
// "DATA" is MD6 + DT0 (DATA A, the soundcard submode FT8/FT4 modulate through)
|
||||||
|
// and "RTTY" is MD6 + DT2 (FSK D, the K3's direct-keyed RTTY). MD6 alone keeps
|
||||||
|
// whatever submode a prior session left, which is how a K3 "in DATA" transmits
|
||||||
|
// FT8 with no audio — the report behind this row.
|
||||||
|
func (k *Kenwood) SetKenwoodPanelMode(mode string) error {
|
||||||
|
k.mu.Lock()
|
||||||
|
defer k.mu.Unlock()
|
||||||
|
if k.port == nil {
|
||||||
|
return fmt.Errorf("kenwood: not connected")
|
||||||
|
}
|
||||||
|
var cmds []string
|
||||||
|
switch strings.ToUpper(strings.TrimSpace(mode)) {
|
||||||
|
case "CW":
|
||||||
|
cmds = []string{"MD3;"}
|
||||||
|
case "USB":
|
||||||
|
cmds = []string{"MD2;"}
|
||||||
|
case "LSB":
|
||||||
|
cmds = []string{"MD1;"}
|
||||||
|
case "DATA":
|
||||||
|
cmds = []string{"MD6;", "DT0;"}
|
||||||
|
case "RTTY":
|
||||||
|
cmds = []string{"MD6;", "DT2;"}
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("kenwood panel: unknown mode %q", mode)
|
||||||
|
}
|
||||||
|
for _, c := range cmds {
|
||||||
|
if err := k.write(c); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Re-read the settings on the next poll so Mode and DataSub confirm at once.
|
||||||
|
k.panelCycle = kenwoodPanelSlowBeat
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -553,6 +553,13 @@ func (o *OmniRig) SetFrequency(hz int64) error {
|
|||||||
props := []string{prop, "Freq"}
|
props := []string{prop, "Freq"}
|
||||||
if onSubVFO {
|
if onSubVFO {
|
||||||
props = []string{prop}
|
props = []string{prop}
|
||||||
|
} else if isYaesu && split&pmSplitOn != 0 && split&pmSplitOff == 0 {
|
||||||
|
// Yaesu with SPLIT engaged: the generic Freq write lands on the TX
|
||||||
|
// VFO — an FT-2000 moved B and left A (the receiver) behind, so a
|
||||||
|
// spot click QSYed the transmitter and nothing audible changed.
|
||||||
|
// Both VFOs are written: the radio arrives on the spot RX and TX
|
||||||
|
// together, split left as the operator had it.
|
||||||
|
props = []string{"FreqA", "FreqB", "Freq"}
|
||||||
}
|
}
|
||||||
for _, p := range props {
|
for _, p := range props {
|
||||||
if _, e := oleutil.PutProperty(o.rig, p, hz32); e != nil {
|
if _, e := oleutil.PutProperty(o.rig, p, hz32); e != nil {
|
||||||
|
|||||||
+26
-2
@@ -165,8 +165,7 @@ func (t *TCI) Connect() error {
|
|||||||
if t.spotsEnabled {
|
if t.spotsEnabled {
|
||||||
debugLog.Printf("TCI: panorama spots are ON — spots will be sent to the radio")
|
debugLog.Printf("TCI: panorama spots are ON — spots will be sent to the radio")
|
||||||
}
|
}
|
||||||
_ = t.send("rx_sensors_enable:true,200;")
|
t.subscribeSensors("connect")
|
||||||
_ = t.send("tx_sensors_enable:true,200;")
|
|
||||||
if t.spotsEnabled {
|
if t.spotsEnabled {
|
||||||
// Forget what we thought was on the panorama at the same moment the radio
|
// Forget what we thought was on the panorama at the same moment the radio
|
||||||
// is told to drop it. Kept, the memory would suppress the next spot for
|
// is told to drop it. Kept, the memory would suppress the next spot for
|
||||||
@@ -461,6 +460,24 @@ func (t *TCI) SetTXAudioSource(src string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// send writes a command to the WebSocket (one writer at a time).
|
// send writes a command to the WebSocket (one writer at a time).
|
||||||
|
// subscribeSensors asks the radio to push its meters. Nothing measures anything
|
||||||
|
// until this goes out — the S-meter, the transmit power and the SWR are all
|
||||||
|
// subscription-only (TCI §4.4) — and it is sent at connect AND again at every
|
||||||
|
// "ready", because a subscription sent during the server's initial dump can be
|
||||||
|
// dropped. 200 ms is the rate the protocol's own examples use.
|
||||||
|
func (t *TCI) subscribeSensors(when string) {
|
||||||
|
// Both cases, deliberately. Every other command this backend sends works in
|
||||||
|
// lower case, but the meters stayed silent on a real SunSDR through two
|
||||||
|
// rounds of fixes — and the protocol document's own examples are upper case
|
||||||
|
// (TX_SENSORS_ENABLE:true,200;). A server that is case-insensitive ignores
|
||||||
|
// the duplicate; one that is not finally hears the subscription.
|
||||||
|
e1 := t.send("rx_sensors_enable:true,200;")
|
||||||
|
e2 := t.send("tx_sensors_enable:true,200;")
|
||||||
|
_ = t.send("RX_SENSORS_ENABLE:true,200;")
|
||||||
|
_ = t.send("TX_SENSORS_ENABLE:true,200;")
|
||||||
|
debugLog.Printf("TCI: sensor subscription sent (%s, both cases): rx=%v tx=%v", when, e1, e2)
|
||||||
|
}
|
||||||
|
|
||||||
func (t *TCI) send(cmd string) error {
|
func (t *TCI) send(cmd string) error {
|
||||||
t.mu.Lock()
|
t.mu.Lock()
|
||||||
c := t.conn
|
c := t.conn
|
||||||
@@ -567,6 +584,13 @@ func (t *TCI) handle(msg string) {
|
|||||||
}
|
}
|
||||||
case "ready", "start":
|
case "ready", "start":
|
||||||
t.ready = true
|
t.ready = true
|
||||||
|
// (Re)subscribe to the meters HERE, not only at connect. ExpertSDR3
|
||||||
|
// dumps its whole state and then says "ready"; a unidirectional control
|
||||||
|
// command sent while that dump is still in flight can be ignored, and
|
||||||
|
// the report from a real SunSDR — transmit meters still empty after the
|
||||||
|
// connect-time subscription — has exactly that shape. From a goroutine:
|
||||||
|
// send takes t.mu, which this handler holds.
|
||||||
|
go t.subscribeSensors("ready")
|
||||||
case "stop":
|
case "stop":
|
||||||
t.ready = false
|
t.ready = false
|
||||||
case "vfo":
|
case "vfo":
|
||||||
|
|||||||
@@ -113,7 +113,8 @@ func (t *TCI) handlePanel(name string, get func(int) string, args string) bool {
|
|||||||
// it. What the radio actually announces after the command settles whether
|
// it. What the radio actually announces after the command settles whether
|
||||||
// this is our reading or its doing, and no amount of reasoning will.
|
// this is our reading or its doing, and no amount of reasoning will.
|
||||||
switch name {
|
switch name {
|
||||||
case "mute", "sql_enable", "sql_level", "tx_power", "tx_swr", "tune":
|
case "mute", "sql_enable", "sql_level", "tx_power", "tx_swr", "tune",
|
||||||
|
"tx_sensors", "rx_sensors", "rx_channel_sensors":
|
||||||
// Logged on arrival so an ANSWER can be told from a SILENCE: the log
|
// Logged on arrival so an ANSWER can be told from a SILENCE: the log
|
||||||
// showed the transmit meters being asked for and nothing coming back,
|
// showed the transmit meters being asked for and nothing coming back,
|
||||||
// which on its own proves nothing — a reply that arrived and failed to
|
// which on its own proves nothing — a reply that arrived and failed to
|
||||||
|
|||||||
@@ -905,3 +905,22 @@ func yaesuSplitCommand(cmd, vfo string, on bool) string {
|
|||||||
}
|
}
|
||||||
return cmd + "0;"
|
return cmd + "0;"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// updateSnap is update for a meter where lingering is misinformation: the peak
|
||||||
|
// stands for the hold, then the display returns to the live sample AT ONCE.
|
||||||
|
// Made for the K3's SWR — the radio throws a brief SWR spike as an FT8 frame
|
||||||
|
// ends, and the quarter-of-the-gap decay above turned that one bad sample into
|
||||||
|
// twelve seconds of alarming red on the next transmission. A needle's inertia
|
||||||
|
// suits a power meter; an SWR reading is a warning light, and a warning that
|
||||||
|
// fades slowly reads as a fault that is slowly getting better.
|
||||||
|
func (m *meterPeak) updateSnap(sample int, now time.Time) int {
|
||||||
|
if sample >= m.val {
|
||||||
|
m.val, m.at = sample, now
|
||||||
|
return m.val
|
||||||
|
}
|
||||||
|
if now.Sub(m.at) < meterHold {
|
||||||
|
return m.val
|
||||||
|
}
|
||||||
|
m.val, m.at = sample, now
|
||||||
|
return m.val
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,30 +0,0 @@
|
|||||||
-- Label designer: printable labels for paper QSL work.
|
|
||||||
--
|
|
||||||
-- Two tables because the two things have different lifetimes. A STOCK is the
|
|
||||||
-- physical roll in the printer (width, height, margins) — one per label size,
|
|
||||||
-- shared by every design printed on it. A TEMPLATE is one design (what goes on
|
|
||||||
-- the label) and points at the stock it was drawn for. Deleting a design must
|
|
||||||
-- never take the roll definition of the other designs with it.
|
|
||||||
--
|
|
||||||
-- kind separates the two families the operator designs: 'qso' (the label glued
|
|
||||||
-- on the QSL card, with its repeating QSO table) and 'address' (destination or
|
|
||||||
-- return address). is_default is per (kind, profile scope) — printing wants
|
|
||||||
-- "the QSO label" and "the address label" without asking every time.
|
|
||||||
CREATE TABLE label_stocks (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
json TEXT NOT NULL,
|
|
||||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
|
|
||||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
|
||||||
);
|
|
||||||
CREATE TABLE label_templates (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
kind TEXT NOT NULL,
|
|
||||||
profile_id INTEGER REFERENCES station_profiles(id) ON DELETE SET NULL,
|
|
||||||
stock_id INTEGER REFERENCES label_stocks(id) ON DELETE SET NULL,
|
|
||||||
json TEXT NOT NULL,
|
|
||||||
is_default INTEGER NOT NULL DEFAULT 0,
|
|
||||||
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
|
|
||||||
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
|
|
||||||
);
|
|
||||||
@@ -51,8 +51,6 @@ var settingsTables = []string{
|
|||||||
"operating_stations_new",
|
"operating_stations_new",
|
||||||
"award_references",
|
"award_references",
|
||||||
"qsl_templates",
|
"qsl_templates",
|
||||||
"label_stocks",
|
|
||||||
"label_templates",
|
|
||||||
"cluster_servers",
|
"cluster_servers",
|
||||||
"integrations_udp",
|
"integrations_udp",
|
||||||
"callsign_cache",
|
"callsign_cache",
|
||||||
|
|||||||
@@ -156,6 +156,8 @@ type Event struct {
|
|||||||
DecodeModeRaw string
|
DecodeModeRaw string
|
||||||
// DecodeMsgRaw is the message as sent, untrimmed — see DecodeModeRaw.
|
// DecodeMsgRaw is the message as sent, untrimmed — see DecodeModeRaw.
|
||||||
DecodeMsgRaw string
|
DecodeMsgRaw string
|
||||||
|
// DecodeIsNew is false on the history a Replay resends: display-only lines.
|
||||||
|
DecodeIsNew bool
|
||||||
// ProgramID is the sending application's own id ("WSJT-X", "MSHV", or
|
// ProgramID is the sending application's own id ("WSJT-X", "MSHV", or
|
||||||
// "WSJT-X - 2" for a second instance started with --rig-name). It is what
|
// "WSJT-X - 2" for a second instance started with --rig-name). It is what
|
||||||
// tells two receivers apart on one multicast group — and it is the address a
|
// tells two receivers apart on one multicast group — and it is the address a
|
||||||
@@ -212,6 +214,9 @@ type Server struct {
|
|||||||
// lastFrom is the address each program's packets arrive from — where a Reply
|
// lastFrom is the address each program's packets arrive from — where a Reply
|
||||||
// has to be sent. See SendReply.
|
// has to be sent. See SendReply.
|
||||||
lastFrom map[string]*net.UDPAddr
|
lastFrom map[string]*net.UDPAddr
|
||||||
|
// onNewInstance fires (off the read loop) the first time a program id is
|
||||||
|
// heard on this listener — the hook the startup replay hangs from.
|
||||||
|
onNewInstance func(programID string)
|
||||||
// instLabel names each running application, keyed by id AND sending address.
|
// instLabel names each running application, keyed by id AND sending address.
|
||||||
//
|
//
|
||||||
// WSJT-X requires --rig-name for a second instance, so its ids differ. MSHV
|
// WSJT-X requires --rig-name for a second instance, so its ids differ. MSHV
|
||||||
@@ -285,11 +290,12 @@ func describePacket(pkt []byte) string {
|
|||||||
|
|
||||||
func newServer(cfg Config, out chan<- Event, mgr *Manager) *Server {
|
func newServer(cfg Config, out chan<- Event, mgr *Manager) *Server {
|
||||||
return &Server{
|
return &Server{
|
||||||
cfg: cfg,
|
cfg: cfg,
|
||||||
out: out,
|
out: out,
|
||||||
mgr: mgr,
|
mgr: mgr,
|
||||||
stop: make(chan struct{}),
|
onNewInstance: mgr.onNewInstance,
|
||||||
done: make(chan struct{}),
|
stop: make(chan struct{}),
|
||||||
|
done: make(chan struct{}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -515,13 +521,23 @@ func (s *Server) handle(pkt []byte, remote *net.UDPAddr) {
|
|||||||
// must go to the sender's own address, never to the group.
|
// must go to the sender's own address, never to the group.
|
||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
inst := s.instanceLabel(w.ProgramID, remote)
|
inst := s.instanceLabel(w.ProgramID, remote)
|
||||||
|
newInstance := false
|
||||||
if inst != "" && remote != nil {
|
if inst != "" && remote != nil {
|
||||||
if s.lastFrom == nil {
|
if s.lastFrom == nil {
|
||||||
s.lastFrom = map[string]*net.UDPAddr{}
|
s.lastFrom = map[string]*net.UDPAddr{}
|
||||||
}
|
}
|
||||||
|
if _, known := s.lastFrom[inst]; !known {
|
||||||
|
newInstance = true
|
||||||
|
}
|
||||||
s.lastFrom[inst] = remote
|
s.lastFrom[inst] = remote
|
||||||
}
|
}
|
||||||
|
onNew := s.onNewInstance
|
||||||
s.mu.Unlock()
|
s.mu.Unlock()
|
||||||
|
// A program just heard for the first time this session: tell the app, so
|
||||||
|
// it can ask for a replay of the decodes already on that program's screen.
|
||||||
|
if newInstance && onNew != nil {
|
||||||
|
go onNew(inst)
|
||||||
|
}
|
||||||
// Status carries the current dial frequency; remember it so Decode audio
|
// Status carries the current dial frequency; remember it so Decode audio
|
||||||
// offsets can be turned into RF frequencies for the panadapter.
|
// offsets can be turned into RF frequencies for the panadapter.
|
||||||
if w.FreqHz > 0 && !w.IsDecode {
|
if w.FreqHz > 0 && !w.IsDecode {
|
||||||
@@ -580,6 +596,7 @@ func (s *Server) handle(pkt []byte, remote *net.UDPAddr) {
|
|||||||
ev.DecodeModeRaw = w.Mode
|
ev.DecodeModeRaw = w.Mode
|
||||||
ev.DecodeMsg = w.DecodeMsg
|
ev.DecodeMsg = w.DecodeMsg
|
||||||
ev.DecodeMsgRaw = w.DecodeMsgRaw
|
ev.DecodeMsgRaw = w.DecodeMsgRaw
|
||||||
|
ev.DecodeIsNew = w.DecodeIsNew
|
||||||
ev.DecodeAt = decodeTime(w.DecodeMsSinceMidnight)
|
ev.DecodeAt = decodeTime(w.DecodeMsSinceMidnight)
|
||||||
ev.DecodeTRPeriod = tr
|
ev.DecodeTRPeriod = tr
|
||||||
ev.DecodeDial = dial
|
ev.DecodeDial = dial
|
||||||
@@ -803,6 +820,10 @@ type Manager struct {
|
|||||||
repo *Repo
|
repo *Repo
|
||||||
out chan Event
|
out chan Event
|
||||||
|
|
||||||
|
// onNewInstance is copied onto every inbound listener as it starts; see
|
||||||
|
// Server.onNewInstance.
|
||||||
|
onNewInstance func(programID string)
|
||||||
|
|
||||||
// noADIFOnce keeps the "nothing to forward to" note to one line a session
|
// noADIFOnce keeps the "nothing to forward to" note to one line a session
|
||||||
// rather than one per QSO logged.
|
// rather than one per QSO logged.
|
||||||
noADIFOnce sync.Once
|
noADIFOnce sync.Once
|
||||||
@@ -940,3 +961,11 @@ func (m *Manager) StopAll() {
|
|||||||
s.close()
|
s.close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetOnNewInstance installs the first-sighting hook. Call before Reload so
|
||||||
|
// listeners are born with it.
|
||||||
|
func (m *Manager) SetOnNewInstance(fn func(programID string)) {
|
||||||
|
m.mu.Lock()
|
||||||
|
m.onNewInstance = fn
|
||||||
|
m.mu.Unlock()
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
package udp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/binary"
|
||||||
|
|
||||||
|
"hamlog/internal/applog"
|
||||||
|
)
|
||||||
|
|
||||||
|
// WSJT-X Configure (message 15) — change the decoder's settings remotely. Used
|
||||||
|
// for ONE thing here: clicking an FT4 spot while the decoder sits in FT8
|
||||||
|
// switches its mode too, so the operator lands ready to decode instead of
|
||||||
|
// staring at a band of gibberish. Every other field is sent as "no change"
|
||||||
|
// (empty strings, max-quint32), per the protocol.
|
||||||
|
const wsjtMsgConfigure = 15
|
||||||
|
|
||||||
|
// EncodeConfigureMode builds a Configure datagram that changes only the mode.
|
||||||
|
func EncodeConfigureMode(programID, mode string) []byte {
|
||||||
|
const noChange32 = ^uint32(0)
|
||||||
|
var b bytes.Buffer
|
||||||
|
_ = binary.Write(&b, binary.BigEndian, uint32(wsjtMagic))
|
||||||
|
_ = binary.Write(&b, binary.BigEndian, uint32(2))
|
||||||
|
_ = binary.Write(&b, binary.BigEndian, uint32(wsjtMsgConfigure))
|
||||||
|
writeQString(&b, programID)
|
||||||
|
writeQString(&b, mode) // Mode
|
||||||
|
_ = binary.Write(&b, binary.BigEndian, noChange32) // Frequency Tolerance — no change
|
||||||
|
writeQString(&b, "") // Submode — no change
|
||||||
|
_ = binary.Write(&b, binary.BigEndian, uint8(0)) // Fast Mode — off (right for every HF mode)
|
||||||
|
_ = binary.Write(&b, binary.BigEndian, noChange32) // T/R Period — no change
|
||||||
|
_ = binary.Write(&b, binary.BigEndian, noChange32) // Rx DF — no change
|
||||||
|
writeQString(&b, "") // DX Call — no change
|
||||||
|
writeQString(&b, "") // DX Grid — no change
|
||||||
|
_ = binary.Write(&b, binary.BigEndian, uint8(0)) // Generate Messages — no
|
||||||
|
return b.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
// SendConfigureMode asks every decoder heard this session to switch mode.
|
||||||
|
// Sent to all instances rather than one: the spot click does not say which
|
||||||
|
// decoder the operator is looking at, and a second instance already in the
|
||||||
|
// right mode treats the message as a no-op.
|
||||||
|
func (m *Manager) SendConfigureMode(mode string) {
|
||||||
|
for _, inst := range m.Instances() {
|
||||||
|
if err := m.sendToInstance(inst, EncodeConfigureMode(inst, mode), "configure-mode"); err == nil {
|
||||||
|
applog.Printf("udp: asked %q to switch to %s", inst, mode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -1,194 +0,0 @@
|
|||||||
// Package labels holds the label designer's data model: the printable labels
|
|
||||||
// an operator sticks on a QSL card (the QSO table) or an envelope (addresses).
|
|
||||||
//
|
|
||||||
// Everything is measured in MILLIMETRES. Label stock is sold in mm (a Brother
|
|
||||||
// DK-11201 is 29×90), printer margins are quoted in mm, and an operator lining
|
|
||||||
// a design up against a physical label thinks in mm — pixels only exist at
|
|
||||||
// render time, where the frontend rasterises at the stock's dpi. Storing mm
|
|
||||||
// keeps a template meaningful if it is ever printed at another resolution.
|
|
||||||
//
|
|
||||||
// The document is deliberately much simpler than the QSL card designer's: a
|
|
||||||
// label is monochrome text on a small sticker, so there are no photos, no
|
|
||||||
// effects, no presets — four element types and a geometry.
|
|
||||||
package labels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Stock is one physical label size — the roll in the printer. Designs point at
|
|
||||||
// a stock rather than embedding the geometry so that changing "my printer's
|
|
||||||
// margins are actually 2 mm" fixes every design at once.
|
|
||||||
type Stock struct {
|
|
||||||
ID int64 `json:"id,omitempty"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
WMm float64 `json:"w_mm"`
|
|
||||||
HMm float64 `json:"h_mm"`
|
|
||||||
// Margins are the unprintable border, in mm from each edge.
|
|
||||||
MarginTop float64 `json:"margin_top_mm"`
|
|
||||||
MarginRight float64 `json:"margin_right_mm"`
|
|
||||||
MarginBottom float64 `json:"margin_bottom_mm"`
|
|
||||||
MarginLeft float64 `json:"margin_left_mm"`
|
|
||||||
DPI int `json:"dpi"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// BuiltinStocks are the label sizes seeded on first run — the common Brother DK
|
|
||||||
// rolls (the QL family is what prompted the feature) plus a 62 mm continuous
|
|
||||||
// strip. Ordinary rows once seeded: an operator with different margins edits
|
|
||||||
// them like any stock.
|
|
||||||
func BuiltinStocks() []Stock {
|
|
||||||
m := func(name string, w, h float64) Stock {
|
|
||||||
return Stock{Name: name, WMm: w, HMm: h,
|
|
||||||
MarginTop: 1.5, MarginRight: 3, MarginBottom: 1.5, MarginLeft: 3, DPI: 300}
|
|
||||||
}
|
|
||||||
return []Stock{
|
|
||||||
m("Brother DK-11201 · 29×90 mm (address)", 90, 29),
|
|
||||||
m("Brother DK-11202 · 62×100 mm (shipping)", 100, 62),
|
|
||||||
m("Brother DK-11208 · 38×90 mm (large address)", 90, 38),
|
|
||||||
m("Brother DK-22205 · 62 mm continuous (cut 100 mm)", 100, 62),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Element is one thing drawn on the label. Type selects which fields matter:
|
|
||||||
//
|
|
||||||
// text X/Y/W, Text (with <VARIABLES>), Size, Bold, Align
|
|
||||||
// line X/Y/W, Thickness — a horizontal rule
|
|
||||||
// qso_table X/Y/W, Columns, RowsMax, RowH, Header — the repeating QSO block
|
|
||||||
// addr_block X/Y, Lines, Size, Bold, LineGap — address lines, blanks collapsed
|
|
||||||
//
|
|
||||||
// One struct with optional fields rather than a type per element: the document
|
|
||||||
// crosses the Wails boundary as JSON and the frontend edits it in place, and a
|
|
||||||
// closed union would buy safety here at the price of a parallel hierarchy on
|
|
||||||
// both sides of that boundary.
|
|
||||||
type Element struct {
|
|
||||||
Type string `json:"type"`
|
|
||||||
XMm float64 `json:"x_mm"`
|
|
||||||
YMm float64 `json:"y_mm"`
|
|
||||||
WMm float64 `json:"w_mm,omitempty"`
|
|
||||||
|
|
||||||
// text
|
|
||||||
Text string `json:"text,omitempty"`
|
|
||||||
SizePt float64 `json:"size_pt,omitempty"`
|
|
||||||
Bold bool `json:"bold,omitempty"`
|
|
||||||
Italic bool `json:"italic,omitempty"`
|
|
||||||
Align string `json:"align,omitempty"` // left | center | right
|
|
||||||
|
|
||||||
// line
|
|
||||||
ThicknessMm float64 `json:"thickness_mm,omitempty"`
|
|
||||||
|
|
||||||
// qso_table
|
|
||||||
Columns []Column `json:"columns,omitempty"`
|
|
||||||
RowsMax int `json:"rows_max,omitempty"`
|
|
||||||
RowHMm float64 `json:"row_h_mm,omitempty"`
|
|
||||||
Header bool `json:"header,omitempty"`
|
|
||||||
|
|
||||||
// addr_block
|
|
||||||
Lines []string `json:"lines,omitempty"`
|
|
||||||
LineGap float64 `json:"line_gap_mm,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Column is one column of the QSO table. Field names the QSO field (the same
|
|
||||||
// lower-case keys the grids use: qso_date, time_on, band, freq, mode, rst_sent,
|
|
||||||
// rst_rcvd, …); Label is the printed header.
|
|
||||||
type Column struct {
|
|
||||||
Field string `json:"field"`
|
|
||||||
Label string `json:"label"`
|
|
||||||
WMm float64 `json:"w_mm"`
|
|
||||||
Align string `json:"align,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Template is one label design.
|
|
||||||
type Template struct {
|
|
||||||
Version int `json:"version"`
|
|
||||||
Kind string `json:"kind"` // qso | address
|
|
||||||
Name string `json:"name,omitempty"`
|
|
||||||
StockID int64 `json:"stock_id"`
|
|
||||||
FontName string `json:"font,omitempty"` // one face for the whole label; "" = the renderer's default
|
|
||||||
Elements []Element `json:"elements"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse decodes a template document.
|
|
||||||
func Parse(doc []byte) (Template, error) {
|
|
||||||
var t Template
|
|
||||||
if err := json.Unmarshal(doc, &t); err != nil {
|
|
||||||
return t, fmt.Errorf("label template: %w", err)
|
|
||||||
}
|
|
||||||
return t, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Encode is the inverse of Parse.
|
|
||||||
func Encode(t Template) ([]byte, error) { return json.MarshalIndent(t, "", " ") }
|
|
||||||
|
|
||||||
// Validate rejects a document that could not be rendered or printed sensibly.
|
|
||||||
// Geometry beyond the stock is NOT an error — the editor lets an element be
|
|
||||||
// dragged around freely and clips at render time — but nonsense that would make
|
|
||||||
// rendering undefined (unknown types, absurd sizes) is refused at save.
|
|
||||||
func Validate(t Template) error {
|
|
||||||
if t.Version != 1 {
|
|
||||||
return fmt.Errorf("unsupported label template version %d", t.Version)
|
|
||||||
}
|
|
||||||
if t.Kind != "qso" && t.Kind != "address" {
|
|
||||||
return fmt.Errorf("unknown label kind %q", t.Kind)
|
|
||||||
}
|
|
||||||
if len(t.Elements) == 0 {
|
|
||||||
return fmt.Errorf("the label has no elements")
|
|
||||||
}
|
|
||||||
if len(t.Elements) > 64 {
|
|
||||||
return fmt.Errorf("too many elements (%d)", len(t.Elements))
|
|
||||||
}
|
|
||||||
for i, e := range t.Elements {
|
|
||||||
switch e.Type {
|
|
||||||
case "text":
|
|
||||||
if strings.TrimSpace(e.Text) == "" {
|
|
||||||
return fmt.Errorf("element %d: empty text", i+1)
|
|
||||||
}
|
|
||||||
case "line":
|
|
||||||
if e.WMm <= 0 {
|
|
||||||
return fmt.Errorf("element %d: a line needs a width", i+1)
|
|
||||||
}
|
|
||||||
case "qso_table":
|
|
||||||
if len(e.Columns) == 0 {
|
|
||||||
return fmt.Errorf("element %d: the QSO table has no columns", i+1)
|
|
||||||
}
|
|
||||||
if e.RowsMax < 1 || e.RowsMax > 20 {
|
|
||||||
return fmt.Errorf("element %d: rows must be 1-20", i+1)
|
|
||||||
}
|
|
||||||
for _, c := range e.Columns {
|
|
||||||
if strings.TrimSpace(c.Field) == "" || c.WMm <= 0 {
|
|
||||||
return fmt.Errorf("element %d: every column needs a field and a width", i+1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
case "addr_block":
|
|
||||||
if len(e.Lines) == 0 {
|
|
||||||
return fmt.Errorf("element %d: the address block has no lines", i+1)
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
return fmt.Errorf("element %d: unknown type %q", i+1, e.Type)
|
|
||||||
}
|
|
||||||
if e.SizePt < 0 || e.SizePt > 72 {
|
|
||||||
return fmt.Errorf("element %d: font size out of range", i+1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ValidStock rejects geometry no label printer produces.
|
|
||||||
func ValidStock(s Stock) error {
|
|
||||||
if strings.TrimSpace(s.Name) == "" {
|
|
||||||
return fmt.Errorf("the stock needs a name")
|
|
||||||
}
|
|
||||||
if s.WMm < 10 || s.WMm > 300 || s.HMm < 6 || s.HMm > 300 {
|
|
||||||
return fmt.Errorf("label size out of range (10-300 mm wide, 6-300 mm high)")
|
|
||||||
}
|
|
||||||
for _, m := range []float64{s.MarginTop, s.MarginRight, s.MarginBottom, s.MarginLeft} {
|
|
||||||
if m < 0 || m*2 >= s.HMm || m*2 >= s.WMm {
|
|
||||||
return fmt.Errorf("margins leave no printable area")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if s.DPI != 0 && (s.DPI < 72 || s.DPI > 1200) {
|
|
||||||
return fmt.Errorf("dpi out of range")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,252 +0,0 @@
|
|||||||
package labels
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"database/sql"
|
|
||||||
"fmt"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Record is one stored template row; JSON holds the Template document.
|
|
||||||
type Record struct {
|
|
||||||
ID int64 `json:"id"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Kind string `json:"kind"`
|
|
||||||
ProfileID *int64 `json:"profile_id,omitempty"`
|
|
||||||
StockID *int64 `json:"stock_id,omitempty"`
|
|
||||||
JSON string `json:"json"`
|
|
||||||
IsDefault bool `json:"is_default"`
|
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Repo accesses the label_stocks and label_templates tables. Same shape as the
|
|
||||||
// QSL template repo it is modelled on — the label designer is that feature's
|
|
||||||
// smaller sibling and the storage questions were settled there.
|
|
||||||
type Repo struct{ db *sql.DB }
|
|
||||||
|
|
||||||
func NewRepo(db *sql.DB) *Repo { return &Repo{db: db} }
|
|
||||||
|
|
||||||
// ── stocks ──────────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
// Stocks lists every stored label stock, oldest first (the seeded Brother rolls
|
|
||||||
// keep their familiar order at the top).
|
|
||||||
func (r *Repo) Stocks(ctx context.Context) ([]Stock, error) {
|
|
||||||
rows, err := r.db.QueryContext(ctx, `SELECT id, json FROM label_stocks ORDER BY id`)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
var out []Stock
|
|
||||||
for rows.Next() {
|
|
||||||
var id int64
|
|
||||||
var doc string
|
|
||||||
if err := rows.Scan(&id, &doc); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var s Stock
|
|
||||||
if err := parseStock(doc, &s); err != nil {
|
|
||||||
continue // one corrupt row must not hide the rest
|
|
||||||
}
|
|
||||||
s.ID = id
|
|
||||||
out = append(out, s)
|
|
||||||
}
|
|
||||||
return out, rows.Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
// SaveStock upserts one stock (ID 0 creates) and writes the id back.
|
|
||||||
func (r *Repo) SaveStock(ctx context.Context, s *Stock) error {
|
|
||||||
if err := ValidStock(*s); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
doc, err := encodeStock(*s)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
now := time.Now().UTC().Format("2006-01-02T15:04:05.000Z")
|
|
||||||
if s.ID == 0 {
|
|
||||||
res, err := r.db.ExecContext(ctx,
|
|
||||||
`INSERT INTO label_stocks (name, json, created_at, updated_at) VALUES (?,?,?,?)`,
|
|
||||||
s.Name, doc, now, now)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("insert stock: %w", err)
|
|
||||||
}
|
|
||||||
s.ID, _ = res.LastInsertId()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
_, err = r.db.ExecContext(ctx,
|
|
||||||
`UPDATE label_stocks SET name = ?, json = ?, updated_at = ? WHERE id = ?`,
|
|
||||||
s.Name, doc, now, s.ID)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteStock removes a stock. Templates pointing at it keep their design and
|
|
||||||
// fall back to "pick a stock" in the editor (the FK nulls the reference).
|
|
||||||
func (r *Repo) DeleteStock(ctx context.Context, id int64) error {
|
|
||||||
_, err := r.db.ExecContext(ctx, `DELETE FROM label_stocks WHERE id = ?`, id)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// SeedStocks inserts the builtin rolls when the table is empty — first run, or
|
|
||||||
// an operator who deleted everything and wants the presets back gets them by
|
|
||||||
// emptying the table.
|
|
||||||
func (r *Repo) SeedStocks(ctx context.Context) error {
|
|
||||||
var n int
|
|
||||||
if err := r.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM label_stocks`).Scan(&n); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if n > 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
for _, s := range BuiltinStocks() {
|
|
||||||
st := s
|
|
||||||
if err := r.SaveStock(ctx, &st); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── templates ───────────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
const tplCols = `id, name, kind, profile_id, stock_id, json, is_default, updated_at`
|
|
||||||
|
|
||||||
// ListFor returns the templates visible to a profile (its own plus shared),
|
|
||||||
// defaults first.
|
|
||||||
func (r *Repo) ListFor(ctx context.Context, profileID int64) ([]Record, error) {
|
|
||||||
rows, err := r.db.QueryContext(ctx, `SELECT `+tplCols+` FROM label_templates
|
|
||||||
WHERE profile_id = ? OR profile_id IS NULL
|
|
||||||
ORDER BY is_default DESC, id DESC`, profileID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return scanRecords(rows)
|
|
||||||
}
|
|
||||||
|
|
||||||
// List returns every template (no active profile yet).
|
|
||||||
func (r *Repo) List(ctx context.Context) ([]Record, error) {
|
|
||||||
rows, err := r.db.QueryContext(ctx,
|
|
||||||
`SELECT `+tplCols+` FROM label_templates ORDER BY is_default DESC, id DESC`)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return scanRecords(rows)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get returns one template.
|
|
||||||
func (r *Repo) Get(ctx context.Context, id int64) (Record, error) {
|
|
||||||
row := r.db.QueryRowContext(ctx, `SELECT `+tplCols+` FROM label_templates WHERE id = ?`, id)
|
|
||||||
return scanRecord(row)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Save upserts a template (ID 0 creates); the id is written back.
|
|
||||||
func (r *Repo) Save(ctx context.Context, rec *Record) error {
|
|
||||||
if rec.Name == "" {
|
|
||||||
return fmt.Errorf("template name required")
|
|
||||||
}
|
|
||||||
now := time.Now().UTC().Format("2006-01-02T15:04:05.000Z")
|
|
||||||
if rec.ID == 0 {
|
|
||||||
res, err := r.db.ExecContext(ctx, `INSERT INTO label_templates
|
|
||||||
(name, kind, profile_id, stock_id, json, is_default, created_at, updated_at)
|
|
||||||
VALUES (?,?,?,?,?,?,?,?)`,
|
|
||||||
rec.Name, rec.Kind, nullID(rec.ProfileID), nullID(rec.StockID), rec.JSON,
|
|
||||||
boolInt(rec.IsDefault), now, now)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("insert label template: %w", err)
|
|
||||||
}
|
|
||||||
rec.ID, _ = res.LastInsertId()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
_, err := r.db.ExecContext(ctx, `UPDATE label_templates
|
|
||||||
SET name = ?, kind = ?, profile_id = ?, stock_id = ?, json = ?, updated_at = ?
|
|
||||||
WHERE id = ?`,
|
|
||||||
rec.Name, rec.Kind, nullID(rec.ProfileID), nullID(rec.StockID), rec.JSON, now, rec.ID)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete removes a template.
|
|
||||||
func (r *Repo) Delete(ctx context.Context, id int64) error {
|
|
||||||
_, err := r.db.ExecContext(ctx, `DELETE FROM label_templates WHERE id = ?`, id)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetDefault marks one template as the default FOR ITS KIND within its profile
|
|
||||||
// scope: printing asks for "the QSO label" and "the address label" separately,
|
|
||||||
// so the two defaults must not compete.
|
|
||||||
func (r *Repo) SetDefault(ctx context.Context, id int64) error {
|
|
||||||
tx, err := r.db.BeginTx(ctx, nil)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer tx.Rollback() //nolint:errcheck
|
|
||||||
var kind string
|
|
||||||
var profileID sql.NullInt64
|
|
||||||
if err := tx.QueryRowContext(ctx,
|
|
||||||
`SELECT kind, profile_id FROM label_templates WHERE id = ?`, id).Scan(&kind, &profileID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if profileID.Valid {
|
|
||||||
_, err = tx.ExecContext(ctx, `UPDATE label_templates SET is_default = 0
|
|
||||||
WHERE kind = ? AND (profile_id = ? OR profile_id IS NULL)`, kind, profileID.Int64)
|
|
||||||
} else {
|
|
||||||
_, err = tx.ExecContext(ctx, `UPDATE label_templates SET is_default = 0 WHERE kind = ?`, kind)
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if _, err = tx.ExecContext(ctx, `UPDATE label_templates SET is_default = 1 WHERE id = ?`, id); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return tx.Commit()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── scanning helpers ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
type rowScanner interface{ Scan(dest ...any) error }
|
|
||||||
|
|
||||||
func scanRecord(row rowScanner) (Record, error) {
|
|
||||||
var rec Record
|
|
||||||
var pid, sid sql.NullInt64
|
|
||||||
var def int
|
|
||||||
var updated string
|
|
||||||
if err := row.Scan(&rec.ID, &rec.Name, &rec.Kind, &pid, &sid, &rec.JSON, &def, &updated); err != nil {
|
|
||||||
return rec, err
|
|
||||||
}
|
|
||||||
if pid.Valid {
|
|
||||||
v := pid.Int64
|
|
||||||
rec.ProfileID = &v
|
|
||||||
}
|
|
||||||
if sid.Valid {
|
|
||||||
v := sid.Int64
|
|
||||||
rec.StockID = &v
|
|
||||||
}
|
|
||||||
rec.IsDefault = def != 0
|
|
||||||
rec.UpdatedAt, _ = time.Parse(time.RFC3339, updated)
|
|
||||||
return rec, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func scanRecords(rows *sql.Rows) ([]Record, error) {
|
|
||||||
defer rows.Close()
|
|
||||||
var out []Record
|
|
||||||
for rows.Next() {
|
|
||||||
rec, err := scanRecord(rows)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
out = append(out, rec)
|
|
||||||
}
|
|
||||||
return out, rows.Err()
|
|
||||||
}
|
|
||||||
|
|
||||||
func nullID(p *int64) any {
|
|
||||||
if p == nil || *p == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return *p
|
|
||||||
}
|
|
||||||
|
|
||||||
func boolInt(b bool) int {
|
|
||||||
if b {
|
|
||||||
return 1
|
|
||||||
}
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
package labels
|
|
||||||
|
|
||||||
import "encoding/json"
|
|
||||||
|
|
||||||
// The stock row stores its geometry as JSON so adding a field never needs a
|
|
||||||
// migration; the name is duplicated into its own column for listing.
|
|
||||||
func parseStock(doc string, s *Stock) error { return json.Unmarshal([]byte(doc), s) }
|
|
||||||
|
|
||||||
func encodeStock(s Stock) (string, error) {
|
|
||||||
s.ID = 0 // the row id is authoritative; never persist a stale copy inside the blob
|
|
||||||
b, err := json.Marshal(s)
|
|
||||||
return string(b), err
|
|
||||||
}
|
|
||||||
@@ -1,131 +0,0 @@
|
|||||||
// Package pdf writes the one kind of PDF the label printer needs: a document
|
|
||||||
// whose every page is a single full-bleed image at an exact physical size.
|
|
||||||
//
|
|
||||||
// Written by hand rather than through a library for two reasons. The build is
|
|
||||||
// pure Go with no room for cgo, and the need is tiny: the pages arrive as
|
|
||||||
// PNGs rasterised by the SAME canvas renderer the designer's preview uses, so
|
|
||||||
// this file only has to carry pixels to paper without touching them. Fonts,
|
|
||||||
// vectors, compression profiles — all already decided upstream.
|
|
||||||
//
|
|
||||||
// The images are stored as 8-bit DeviceGray with FlateDecode: labels are
|
|
||||||
// monochrome, grey keeps antialiased text edges smooth on a 300 dpi thermal
|
|
||||||
// head, and flate is lossless — JPEG artefacts around small print are exactly
|
|
||||||
// what a QSL label cannot afford.
|
|
||||||
package pdf
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"compress/zlib"
|
|
||||||
"fmt"
|
|
||||||
"image/png"
|
|
||||||
)
|
|
||||||
|
|
||||||
const mmToPt = 72.0 / 25.4
|
|
||||||
|
|
||||||
// Doc accumulates pages; Bytes() renders the file.
|
|
||||||
type Doc struct {
|
|
||||||
pages []pageData
|
|
||||||
}
|
|
||||||
|
|
||||||
type pageData struct {
|
|
||||||
wPt, hPt float64
|
|
||||||
imgW int
|
|
||||||
imgH int
|
|
||||||
gray []byte // zlib-compressed 8-bit samples
|
|
||||||
}
|
|
||||||
|
|
||||||
// AddImagePage appends one page of wMm×hMm entirely covered by the PNG.
|
|
||||||
// The PNG's aspect ratio is not checked against the page's: the caller
|
|
||||||
// rasterised it AT this size, and a mismatch would be its bug to see.
|
|
||||||
func (d *Doc) AddImagePage(pngBytes []byte, wMm, hMm float64) error {
|
|
||||||
img, err := png.Decode(bytes.NewReader(pngBytes))
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("page image: %w", err)
|
|
||||||
}
|
|
||||||
b := img.Bounds()
|
|
||||||
w, h := b.Dx(), b.Dy()
|
|
||||||
if w <= 0 || h <= 0 {
|
|
||||||
return fmt.Errorf("page image is empty")
|
|
||||||
}
|
|
||||||
// To 8-bit grey. Luminance weights, not an average: blue text on a designer
|
|
||||||
// screen should darken the way a photocopier would darken it.
|
|
||||||
gray := make([]byte, w*h)
|
|
||||||
i := 0
|
|
||||||
for y := b.Min.Y; y < b.Max.Y; y++ {
|
|
||||||
for x := b.Min.X; x < b.Max.X; x++ {
|
|
||||||
r, g, bb, _ := img.At(x, y).RGBA()
|
|
||||||
gray[i] = byte((299*r + 587*g + 114*bb) / 1000 >> 8)
|
|
||||||
i++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var buf bytes.Buffer
|
|
||||||
zw := zlib.NewWriter(&buf)
|
|
||||||
if _, err := zw.Write(gray); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := zw.Close(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
d.pages = append(d.pages, pageData{
|
|
||||||
wPt: wMm * mmToPt, hPt: hMm * mmToPt,
|
|
||||||
imgW: w, imgH: h, gray: buf.Bytes(),
|
|
||||||
})
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Bytes renders the whole document.
|
|
||||||
func (d *Doc) Bytes() ([]byte, error) {
|
|
||||||
if len(d.pages) == 0 {
|
|
||||||
return nil, fmt.Errorf("no pages")
|
|
||||||
}
|
|
||||||
var out bytes.Buffer
|
|
||||||
offsets := []int{0} // object 0 is the free-list head
|
|
||||||
obj := func(body func()) int {
|
|
||||||
offsets = append(offsets, out.Len())
|
|
||||||
n := len(offsets) - 1
|
|
||||||
fmt.Fprintf(&out, "%d 0 obj\n", n)
|
|
||||||
body()
|
|
||||||
out.WriteString("endobj\n")
|
|
||||||
return n
|
|
||||||
}
|
|
||||||
|
|
||||||
out.WriteString("%PDF-1.4\n%\xe2\xe3\xcf\xd3\n")
|
|
||||||
|
|
||||||
// Objects 1 (catalog) and 2 (pages) reference their children by number, so
|
|
||||||
// the numbering is laid out first: 3 objects per page after the two roots.
|
|
||||||
nPages := len(d.pages)
|
|
||||||
pageObj := func(i int) int { return 3 + i*3 }
|
|
||||||
|
|
||||||
obj(func() { out.WriteString("<< /Type /Catalog /Pages 2 0 R >>\n") }) // 1
|
|
||||||
obj(func() { // 2
|
|
||||||
out.WriteString("<< /Type /Pages /Kids [")
|
|
||||||
for i := 0; i < nPages; i++ {
|
|
||||||
fmt.Fprintf(&out, "%d 0 R ", pageObj(i))
|
|
||||||
}
|
|
||||||
fmt.Fprintf(&out, "] /Count %d >>\n", nPages)
|
|
||||||
})
|
|
||||||
for i, p := range d.pages {
|
|
||||||
content := fmt.Sprintf("q %.4f 0 0 %.4f 0 0 cm /Im0 Do Q", p.wPt, p.hPt)
|
|
||||||
obj(func() { // page
|
|
||||||
fmt.Fprintf(&out, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 %.4f %.4f] /Contents %d 0 R /Resources << /XObject << /Im0 %d 0 R >> >> >>\n",
|
|
||||||
p.wPt, p.hPt, pageObj(i)+1, pageObj(i)+2)
|
|
||||||
})
|
|
||||||
obj(func() { // contents
|
|
||||||
fmt.Fprintf(&out, "<< /Length %d >>\nstream\n%s\nendstream\n", len(content), content)
|
|
||||||
})
|
|
||||||
obj(func() { // image
|
|
||||||
fmt.Fprintf(&out, "<< /Type /XObject /Subtype /Image /Width %d /Height %d /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /FlateDecode /Length %d >>\nstream\n",
|
|
||||||
p.imgW, p.imgH, len(p.gray))
|
|
||||||
out.Write(p.gray)
|
|
||||||
out.WriteString("\nendstream\n")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
xref := out.Len()
|
|
||||||
fmt.Fprintf(&out, "xref\n0 %d\n0000000000 65535 f \n", len(offsets))
|
|
||||||
for _, off := range offsets[1:] {
|
|
||||||
fmt.Fprintf(&out, "%010d 00000 n \n", off)
|
|
||||||
}
|
|
||||||
fmt.Fprintf(&out, "trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n", len(offsets), xref)
|
|
||||||
return out.Bytes(), nil
|
|
||||||
}
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
package pdf
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"image"
|
|
||||||
"image/color"
|
|
||||||
"image/png"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func testPNG(t *testing.T, w, h int) []byte {
|
|
||||||
t.Helper()
|
|
||||||
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
|
||||||
for x := 0; x < w; x++ {
|
|
||||||
img.Set(x, h/2, color.Black)
|
|
||||||
}
|
|
||||||
var buf bytes.Buffer
|
|
||||||
if err := png.Encode(&buf, img); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return buf.Bytes()
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDocShape(t *testing.T) {
|
|
||||||
var d Doc
|
|
||||||
// A 90×29 mm label at 300 dpi is 1063×343 px.
|
|
||||||
if err := d.AddImagePage(testPNG(t, 1063, 343), 90, 29); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := d.AddImagePage(testPNG(t, 1063, 343), 90, 29); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
b, err := d.Bytes()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
// Not a PDF parser — the shape a viewer needs to find its way in.
|
|
||||||
for _, want := range []string{"%PDF-1.4", "/Count 2", "/DeviceGray", "startxref", "%%EOF"} {
|
|
||||||
if !bytes.Contains(b, []byte(want)) {
|
|
||||||
t.Errorf("missing %q in output", want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 90 mm = 255.118 pt — the page size a driver prints 1:1 on the roll.
|
|
||||||
if !bytes.Contains(b, []byte("/MediaBox [0 0 255.1181 82.2047]")) {
|
|
||||||
t.Errorf("media box is not the label size")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestEmptyDocRefused(t *testing.T) {
|
|
||||||
var d Doc
|
|
||||||
if _, err := d.Bytes(); err == nil {
|
|
||||||
t.Fatal("an empty document should refuse to render")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+181
-79
@@ -232,11 +232,8 @@ type ListFilter struct {
|
|||||||
Band string `json:"band,omitempty"`
|
Band string `json:"band,omitempty"`
|
||||||
Mode string `json:"mode,omitempty"`
|
Mode string `json:"mode,omitempty"`
|
||||||
StationCallsign string `json:"station_callsign,omitempty"`
|
StationCallsign string `json:"station_callsign,omitempty"`
|
||||||
// QSLSentIn keeps only rows whose paper-QSL sent status is one of these
|
Limit int `json:"limit,omitempty"`
|
||||||
// values — 'R' (requested) and 'Q' (queued) are the label printer's queue.
|
Offset int `json:"offset,omitempty"`
|
||||||
QSLSentIn []string `json:"qsl_sent_in,omitempty"`
|
|
||||||
Limit int `json:"limit,omitempty"`
|
|
||||||
Offset int `json:"offset,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Repo accesses the qso table.
|
// Repo accesses the qso table.
|
||||||
@@ -725,15 +722,14 @@ func (r *Repo) MarkUploadedBatch(ctx context.Context, statusCol, dateCol, date s
|
|||||||
if len(ids) == 0 {
|
if len(ids) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
ph := strings.TrimSuffix(strings.Repeat("?,", len(ids)), ",")
|
now := db.NowISO()
|
||||||
args := make([]any, 0, len(ids)+2)
|
_, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
|
||||||
args = append(args, date, db.NowISO())
|
args := append([]any{date, now}, idArgs...)
|
||||||
for _, id := range ids {
|
_, err := r.db.ExecContext(ctx,
|
||||||
args = append(args, id)
|
`UPDATE qso SET `+statusCol+` = 'Y', `+dateCol+` = ?, updated_at = ? WHERE id IN (`+ph+`)`,
|
||||||
}
|
args...)
|
||||||
_, err := r.db.ExecContext(ctx,
|
return 0, err
|
||||||
`UPDATE qso SET `+statusCol+` = 'Y', `+dateCol+` = ?, updated_at = ? WHERE id IN (`+ph+`)`,
|
})
|
||||||
args...)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("mark uploaded batch (%d): %w", len(ids), err)
|
return fmt.Errorf("mark uploaded batch (%d): %w", len(ids), err)
|
||||||
}
|
}
|
||||||
@@ -871,6 +867,73 @@ var bulkEditableCols = map[string]bool{
|
|||||||
|
|
||||||
// BulkSetField sets one whitelisted column to value on every listed QSO in a
|
// BulkSetField sets one whitelisted column to value on every listed QSO in a
|
||||||
// single statement. value "" clears the field. Returns rows affected.
|
// single statement. value "" clears the field. Returns rows affected.
|
||||||
|
// bulkEditableIntCols are the NUMERIC columns the bulk editor may touch. Their
|
||||||
|
// own path, not the text one: the columns are nullable integers, and while
|
||||||
|
// SQLite would coerce "14" quietly, a shared MySQL logbook would not — and an
|
||||||
|
// empty string is NULL here, never "".
|
||||||
|
// bulkByIDChunks runs one UPDATE per slice of ids, small enough for SQLite's
|
||||||
|
// bound-variable cap: the single IN (…) with one placeholder per id worked at
|
||||||
|
// 10 000 QSOs and failed at 168 000 with "too many SQL variables". Each call
|
||||||
|
// gets the placeholder string and the id arguments for its slice; affected
|
||||||
|
// rows are summed. 500 per statement keeps every backend far from any limit
|
||||||
|
// while costing a few hundred statements on the largest logs.
|
||||||
|
func bulkByIDChunks(ctx context.Context, ids []int64, run func(ph string, idArgs []any) (int64, error)) (int64, error) {
|
||||||
|
const chunk = 500
|
||||||
|
var total int64
|
||||||
|
for start := 0; start < len(ids); start += chunk {
|
||||||
|
end := start + chunk
|
||||||
|
if end > len(ids) {
|
||||||
|
end = len(ids)
|
||||||
|
}
|
||||||
|
part := ids[start:end]
|
||||||
|
ph := strings.Repeat("?,", len(part)-1) + "?"
|
||||||
|
args := make([]any, len(part))
|
||||||
|
for i, id := range part {
|
||||||
|
args[i] = id
|
||||||
|
}
|
||||||
|
n, err := run(ph, args)
|
||||||
|
if err != nil {
|
||||||
|
return total, err
|
||||||
|
}
|
||||||
|
total += n
|
||||||
|
}
|
||||||
|
return total, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var bulkEditableIntCols = map[string]bool{
|
||||||
|
"my_dxcc": true,
|
||||||
|
"my_cq_zone": true,
|
||||||
|
"my_itu_zone": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// BulkSetIntField sets one integer column across the ids; v nil clears it.
|
||||||
|
func (r *Repo) BulkSetIntField(ctx context.Context, ids []int64, column string, v *int) (int64, error) {
|
||||||
|
if !bulkEditableIntCols[column] {
|
||||||
|
return 0, fmt.Errorf("field %q is not bulk-editable", column)
|
||||||
|
}
|
||||||
|
if len(ids) == 0 {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
var val any
|
||||||
|
if v != nil {
|
||||||
|
val = *v
|
||||||
|
}
|
||||||
|
now := db.NowISO()
|
||||||
|
n, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
|
||||||
|
args := append([]any{val, now}, idArgs...)
|
||||||
|
res, err := r.db.ExecContext(ctx,
|
||||||
|
"UPDATE qso SET "+column+" = ?, updated_at = ? WHERE id IN ("+ph+")", args...)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return res.RowsAffected()
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return n, fmt.Errorf("bulk set %s: %w", column, err)
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (r *Repo) BulkSetField(ctx context.Context, ids []int64, column, value string) (int64, error) {
|
func (r *Repo) BulkSetField(ctx context.Context, ids []int64, column, value string) (int64, error) {
|
||||||
if !bulkEditableCols[column] {
|
if !bulkEditableCols[column] {
|
||||||
return 0, fmt.Errorf("field %q is not bulk-editable", column)
|
return 0, fmt.Errorf("field %q is not bulk-editable", column)
|
||||||
@@ -878,13 +941,6 @@ func (r *Repo) BulkSetField(ctx context.Context, ids []int64, column, value stri
|
|||||||
if len(ids) == 0 {
|
if len(ids) == 0 {
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
ph := make([]string, len(ids))
|
|
||||||
args := make([]any, 0, len(ids)+2)
|
|
||||||
args = append(args, value, db.NowISO())
|
|
||||||
for i, id := range ids {
|
|
||||||
ph[i] = "?"
|
|
||||||
args = append(args, id)
|
|
||||||
}
|
|
||||||
set := column + " = ?, updated_at = ?"
|
set := column + " = ?, updated_at = ?"
|
||||||
if column == "mode" {
|
if column == "mode" {
|
||||||
// A submode belongs to the mode it was recorded under. Left behind, it
|
// A submode belongs to the mode it was recorded under. Left behind, it
|
||||||
@@ -893,13 +949,19 @@ func (r *Repo) BulkSetField(ctx context.Context, ids []int64, column, value stri
|
|||||||
// only outcome that leaves the row meaning what the operator asked for.
|
// only outcome that leaves the row meaning what the operator asked for.
|
||||||
set += ", submode = ''"
|
set += ", submode = ''"
|
||||||
}
|
}
|
||||||
res, err := r.db.ExecContext(ctx,
|
now := db.NowISO()
|
||||||
`UPDATE qso SET `+set+` WHERE id IN (`+strings.Join(ph, ",")+`)`,
|
n, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
|
||||||
args...)
|
args := append([]any{value, now}, idArgs...)
|
||||||
|
res, err := r.db.ExecContext(ctx,
|
||||||
|
`UPDATE qso SET `+set+` WHERE id IN (`+ph+`)`, args...)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return res.RowsAffected()
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, fmt.Errorf("bulk set %s: %w", column, err)
|
return n, fmt.Errorf("bulk set %s: %w", column, err)
|
||||||
}
|
}
|
||||||
n, _ := res.RowsAffected()
|
|
||||||
return n, nil
|
return n, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -960,26 +1022,26 @@ func (r *Repo) BulkSetExtra(ctx context.Context, ids []int64, adifKey, value str
|
|||||||
if len(ids) == 0 {
|
if len(ids) == 0 {
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
ph := make([]string, len(ids))
|
head := []any{}
|
||||||
args := make([]any, 0, len(ids)+2)
|
|
||||||
expr := `json_set(COALESCE(extras_json, '{}'), '$.` + adifKey + `', ?)`
|
expr := `json_set(COALESCE(extras_json, '{}'), '$.` + adifKey + `', ?)`
|
||||||
if value == "" {
|
if value == "" {
|
||||||
expr = `json_remove(COALESCE(extras_json, '{}'), '$.` + adifKey + `')`
|
expr = `json_remove(COALESCE(extras_json, '{}'), '$.` + adifKey + `')`
|
||||||
} else {
|
} else {
|
||||||
args = append(args, value)
|
head = append(head, value)
|
||||||
}
|
}
|
||||||
args = append(args, db.NowISO())
|
head = append(head, db.NowISO())
|
||||||
for i, id := range ids {
|
n, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
|
||||||
ph[i] = "?"
|
args := append(append([]any{}, head...), idArgs...)
|
||||||
args = append(args, id)
|
res, err := r.db.ExecContext(ctx,
|
||||||
}
|
`UPDATE qso SET extras_json = `+expr+`, updated_at = ? WHERE id IN (`+ph+`)`, args...)
|
||||||
res, err := r.db.ExecContext(ctx,
|
if err != nil {
|
||||||
`UPDATE qso SET extras_json = `+expr+`, updated_at = ? WHERE id IN (`+strings.Join(ph, ",")+`)`,
|
return 0, err
|
||||||
args...)
|
}
|
||||||
|
return res.RowsAffected()
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, fmt.Errorf("bulk set extra %s: %w", adifKey, err)
|
return n, fmt.Errorf("bulk set extra %s: %w", adifKey, err)
|
||||||
}
|
}
|
||||||
n, _ := res.RowsAffected()
|
|
||||||
return n, nil
|
return n, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -991,20 +1053,19 @@ func (r *Repo) BulkSetFrequency(ctx context.Context, ids []int64, freqHz int64,
|
|||||||
if len(ids) == 0 {
|
if len(ids) == 0 {
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
ph := make([]string, len(ids))
|
now := db.NowISO()
|
||||||
args := make([]any, 0, len(ids)+3)
|
n, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
|
||||||
args = append(args, freqHz, band, db.NowISO())
|
args := append([]any{freqHz, band, now}, idArgs...)
|
||||||
for i, id := range ids {
|
res, err := r.db.ExecContext(ctx,
|
||||||
ph[i] = "?"
|
`UPDATE qso SET freq_hz = ?, band = ?, updated_at = ? WHERE id IN (`+ph+`)`, args...)
|
||||||
args = append(args, id)
|
if err != nil {
|
||||||
}
|
return 0, err
|
||||||
res, err := r.db.ExecContext(ctx,
|
}
|
||||||
`UPDATE qso SET freq_hz = ?, band = ?, updated_at = ? WHERE id IN (`+strings.Join(ph, ",")+`)`,
|
return res.RowsAffected()
|
||||||
args...)
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, fmt.Errorf("bulk set frequency: %w", err)
|
return n, fmt.Errorf("bulk set frequency: %w", err)
|
||||||
}
|
}
|
||||||
n, _ := res.RowsAffected()
|
|
||||||
return n, nil
|
return n, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1166,17 +1227,16 @@ func (r *Repo) DeleteMany(ctx context.Context, ids []int64) (int64, error) {
|
|||||||
if len(ids) == 0 {
|
if len(ids) == 0 {
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
ph := make([]string, len(ids))
|
n, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
|
||||||
args := make([]any, len(ids))
|
res, err := r.db.ExecContext(ctx, `DELETE FROM qso WHERE id IN (`+ph+`)`, idArgs...)
|
||||||
for i, id := range ids {
|
if err != nil {
|
||||||
ph[i] = "?"
|
return 0, err
|
||||||
args[i] = id
|
}
|
||||||
}
|
return res.RowsAffected()
|
||||||
res, err := r.db.ExecContext(ctx, `DELETE FROM qso WHERE id IN (`+strings.Join(ph, ",")+`)`, args...)
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, fmt.Errorf("delete qsos: %w", err)
|
return n, fmt.Errorf("delete qsos: %w", err)
|
||||||
}
|
}
|
||||||
n, _ := res.RowsAffected()
|
|
||||||
return n, nil
|
return n, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1214,12 +1274,6 @@ func (r *Repo) List(ctx context.Context, f ListFilter) ([]QSO, error) {
|
|||||||
q += " AND station_callsign = ?"
|
q += " AND station_callsign = ?"
|
||||||
args = append(args, f.StationCallsign)
|
args = append(args, f.StationCallsign)
|
||||||
}
|
}
|
||||||
if len(f.QSLSentIn) > 0 {
|
|
||||||
q += " AND qsl_sent IN (?" + strings.Repeat(",?", len(f.QSLSentIn)-1) + ")"
|
|
||||||
for _, v := range f.QSLSentIn {
|
|
||||||
args = append(args, v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
q += " ORDER BY qso_date DESC, id DESC"
|
q += " ORDER BY qso_date DESC, id DESC"
|
||||||
if f.Limit <= 0 {
|
if f.Limit <= 0 {
|
||||||
f.Limit = 500
|
f.Limit = 500
|
||||||
@@ -1672,27 +1726,42 @@ func (r *Repo) IterateByIDs(ctx context.Context, ids []int64, fn func(QSO) error
|
|||||||
if len(ids) == 0 {
|
if len(ids) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
ph := strings.TrimSuffix(strings.Repeat("?,", len(ids)), ",")
|
// Chunked like every other by-ids statement (the one-placeholder-per-id IN
|
||||||
args := make([]any, len(ids))
|
// died at 168k with "too many SQL variables") — and because each chunk is
|
||||||
for i, id := range ids {
|
// only locally ordered, the rows are collected and sorted once at the end
|
||||||
args[i] = id
|
// so the chronological contract holds across chunks.
|
||||||
}
|
var all []QSO
|
||||||
rows, err := r.db.QueryContext(ctx,
|
_, err := bulkByIDChunks(ctx, ids, func(ph string, idArgs []any) (int64, error) {
|
||||||
`SELECT `+selectCols+` FROM qso WHERE id IN (`+ph+`) ORDER BY qso_date ASC, id ASC`, args...)
|
rows, err := r.db.QueryContext(ctx,
|
||||||
|
`SELECT `+selectCols+` FROM qso WHERE id IN (`+ph+`)`, idArgs...)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
for rows.Next() {
|
||||||
|
q, err := scanQSO(rows)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
all = append(all, q)
|
||||||
|
}
|
||||||
|
return 0, rows.Err()
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("query qso: %w", err)
|
return fmt.Errorf("query qso: %w", err)
|
||||||
}
|
}
|
||||||
defer rows.Close()
|
sort.Slice(all, func(i, j int) bool {
|
||||||
for rows.Next() {
|
if !all[i].QSODate.Equal(all[j].QSODate) {
|
||||||
q, err := scanQSO(rows)
|
return all[i].QSODate.Before(all[j].QSODate)
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
|
return all[i].ID < all[j].ID
|
||||||
|
})
|
||||||
|
for _, q := range all {
|
||||||
if err := fn(q); err != nil {
|
if err := fn(q); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return rows.Err()
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GridKey builds the lookup key for the worked-grid index.
|
// GridKey builds the lookup key for the worked-grid index.
|
||||||
@@ -1974,6 +2043,39 @@ func bandStatusCode(callWorked, callConfirmed, entityConfirmed bool) int {
|
|||||||
|
|
||||||
// modeClass collapses ADIF modes into the three buckets DXers care about.
|
// modeClass collapses ADIF modes into the three buckets DXers care about.
|
||||||
// Anything not voice and not CW is treated as digital.
|
// Anything not voice and not CW is treated as digital.
|
||||||
|
// ModeClass is modeClass for callers outside the package — the watchlist
|
||||||
|
// judges slots at the same grain the cluster does.
|
||||||
|
func ModeClass(mode string) string { return modeClass(mode) }
|
||||||
|
|
||||||
|
// SlotRow is one (callsign, band, mode) triple from SlotsSince.
|
||||||
|
type SlotRow struct {
|
||||||
|
Callsign string
|
||||||
|
Band string
|
||||||
|
Mode string
|
||||||
|
}
|
||||||
|
|
||||||
|
// SlotsSince lists the slots of every contact made since the given instant —
|
||||||
|
// the contest watchlist's "worked today", where the day boundary lives in this
|
||||||
|
// query's bound and nowhere else.
|
||||||
|
func (r *Repo) SlotsSince(ctx context.Context, since time.Time) ([]SlotRow, error) {
|
||||||
|
rows, err := r.db.QueryContext(ctx,
|
||||||
|
"SELECT callsign, band, mode FROM qso WHERE qso_date >= ?",
|
||||||
|
since.UTC().Format(isoMillis))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
var out []SlotRow
|
||||||
|
for rows.Next() {
|
||||||
|
var sr SlotRow
|
||||||
|
if err := rows.Scan(&sr.Callsign, &sr.Band, &sr.Mode); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out = append(out, sr)
|
||||||
|
}
|
||||||
|
return out, rows.Err()
|
||||||
|
}
|
||||||
|
|
||||||
func modeClass(mode string) string {
|
func modeClass(mode string) string {
|
||||||
switch strings.ToUpper(mode) {
|
switch strings.ToUpper(mode) {
|
||||||
case "SSB", "USB", "LSB", "AM", "FM", "DIGITALVOICE", "PHONE":
|
case "SSB", "USB", "LSB", "AM", "FM", "DIGITALVOICE", "PHONE":
|
||||||
|
|||||||
@@ -246,6 +246,11 @@ func (s *Server) serve(c net.Conn) {
|
|||||||
s.releasePTT(fmt.Sprintf("client %s left", c.RemoteAddr()))
|
s.releasePTT(fmt.Sprintf("client %s left", c.RemoteAddr()))
|
||||||
}()
|
}()
|
||||||
s.log("rigctld: client connected from %s", c.RemoteAddr())
|
s.log("rigctld: client connected from %s", c.RemoteAddr())
|
||||||
|
// The HANDSHAKE is always traced — the first few commands are where a
|
||||||
|
// client decides to stay or hang up, and a connect that lasted 50 ms left
|
||||||
|
// nothing in the log to say which answer it disliked. Steady-state polling
|
||||||
|
// stays behind the CAT trace switch.
|
||||||
|
traced := 0
|
||||||
r := bufio.NewReader(c)
|
r := bufio.NewReader(c)
|
||||||
w := bufio.NewWriter(c)
|
w := bufio.NewWriter(c)
|
||||||
for {
|
for {
|
||||||
@@ -265,7 +270,8 @@ func (s *Server) serve(c net.Conn) {
|
|||||||
// that preceded it — the one thing needed to tell whether OpsLog answered
|
// that preceded it — the one thing needed to tell whether OpsLog answered
|
||||||
// something the client could not accept. Behind the same switch as the CAT
|
// something the client could not accept. Behind the same switch as the CAT
|
||||||
// wire trace: this is one line per poll and would drown an ordinary log.
|
// wire trace: this is one line per poll and would drown an ordinary log.
|
||||||
if req != "" && cat.CIVTraceEnabled() {
|
if req != "" && (traced < 6 || cat.CIVTraceEnabled()) {
|
||||||
|
traced++
|
||||||
s.log("rigctld: %s → %q ⇒ %q", c.RemoteAddr(), req, strings.TrimRight(resp, "\r\n"))
|
s.log("rigctld: %s → %q ⇒ %q", c.RemoteAddr(), req, strings.TrimRight(resp, "\r\n"))
|
||||||
}
|
}
|
||||||
if resp != "" {
|
if resp != "" {
|
||||||
|
|||||||
@@ -0,0 +1,131 @@
|
|||||||
|
package watchlist
|
||||||
|
|
||||||
|
// ClubLog enrichment — phase 2 of the DXHunter port. clublog.org/watch.php
|
||||||
|
// answers, per callsign: is this an expedition, does it run OQRS, is there a
|
||||||
|
// LiveStream, the log's QSO total and the last 24 hours' rate. That block has
|
||||||
|
// been in the Entry schema since phase 1 (the file round-trips DXHunter's);
|
||||||
|
// this file finally fills it.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// WatchData is clublog.org/watch.php's answer, reduced to what the tab shows.
|
||||||
|
type WatchData struct {
|
||||||
|
IsExpedition bool `json:"is_expedition"`
|
||||||
|
HasOQRS bool `json:"has_oqrs"`
|
||||||
|
LiveStream bool `json:"livestream"`
|
||||||
|
ClubLogInfo *struct {
|
||||||
|
TotalQSOs int `json:"total_qsos"`
|
||||||
|
} `json:"clublog_info"`
|
||||||
|
// {} when populated, [] when empty — RawMessage swallows both shapes.
|
||||||
|
QSOsPerBand json.RawMessage `json:"24h_qsos_per_band_mode"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// QSOs24h sums the per-band/per-mode counts.
|
||||||
|
func (d *WatchData) QSOs24h() int {
|
||||||
|
if len(d.QSOsPerBand) == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
var parsed map[string]map[string]int
|
||||||
|
if err := json.Unmarshal(d.QSOsPerBand, &parsed); err != nil {
|
||||||
|
return 0 // "[]" for an empty answer lands here, which is the right zero
|
||||||
|
}
|
||||||
|
n := 0
|
||||||
|
for _, modes := range parsed {
|
||||||
|
for _, c := range modes {
|
||||||
|
n += c
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// FetchWatch asks ClubLog about one callsign. A 404 is "ClubLog has no log for
|
||||||
|
// this call" — an ordinary answer, not an error.
|
||||||
|
func FetchWatch(ctx context.Context, client *http.Client, apiKey, callsign string) (*WatchData, error) {
|
||||||
|
url := fmt.Sprintf("https://clublog.org/watch.php?call=%s&api=%s",
|
||||||
|
strings.ToUpper(strings.TrimSpace(callsign)), apiKey)
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req.Header.Set("User-Agent", "OpsLog")
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
if resp.StatusCode == http.StatusNotFound {
|
||||||
|
return &WatchData{}, nil
|
||||||
|
}
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return nil, fmt.Errorf("clublog watch %s: HTTP %d", callsign, resp.StatusCode)
|
||||||
|
}
|
||||||
|
body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(strings.TrimSpace(string(body))) == 0 {
|
||||||
|
return &WatchData{}, nil
|
||||||
|
}
|
||||||
|
var data WatchData
|
||||||
|
if err := json.Unmarshal(body, &data); err != nil {
|
||||||
|
return nil, fmt.Errorf("clublog watch %s: %w", callsign, err)
|
||||||
|
}
|
||||||
|
return &data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ApplyClubLog writes one answer into the entry and reports whether anything
|
||||||
|
// the tab shows actually changed — the caller only broadcasts on true.
|
||||||
|
func (s *Store) ApplyClubLog(callsign string, d *WatchData) bool {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
e, ok := s.entries[strings.ToUpper(strings.TrimSpace(callsign))]
|
||||||
|
if !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
total := e.ClubLogTotalQSOs
|
||||||
|
if d.ClubLogInfo != nil {
|
||||||
|
total = d.ClubLogInfo.TotalQSOs
|
||||||
|
}
|
||||||
|
q24 := d.QSOs24h()
|
||||||
|
changed := e.IsExpedition != d.IsExpedition || e.ClubLogHasOQRS != d.HasOQRS ||
|
||||||
|
e.ClubLogLiveStream != d.LiveStream || e.ClubLogTotalQSOs != total ||
|
||||||
|
e.ClubLogQSOs24h != q24
|
||||||
|
e.IsExpedition = d.IsExpedition
|
||||||
|
e.ClubLogHasOQRS = d.HasOQRS
|
||||||
|
e.ClubLogLiveStream = d.LiveStream
|
||||||
|
e.ClubLogTotalQSOs = total
|
||||||
|
e.ClubLogQSOs24h = q24
|
||||||
|
e.ClubLogUpdatedAt = time.Now()
|
||||||
|
s.scheduleSave()
|
||||||
|
return changed
|
||||||
|
}
|
||||||
|
|
||||||
|
// StaleEntries lists the callsigns whose ClubLog block is due a refresh.
|
||||||
|
// Expeditions age faster — their totals are the interesting number and move by
|
||||||
|
// the hour; a quiet call is asked about four times a day at most.
|
||||||
|
func (s *Store) StaleEntries(expTTL, otherTTL time.Duration) []string {
|
||||||
|
s.mu.RLock()
|
||||||
|
defer s.mu.RUnlock()
|
||||||
|
now := time.Now()
|
||||||
|
var out []string
|
||||||
|
for call, e := range s.entries {
|
||||||
|
// A starred pattern is a family, not a station — ClubLog has no log
|
||||||
|
// for "VK9*". The base (star stripped) is what gets asked about.
|
||||||
|
ttl := otherTTL
|
||||||
|
if e.IsExpedition {
|
||||||
|
ttl = expTTL
|
||||||
|
}
|
||||||
|
if now.Sub(e.ClubLogUpdatedAt) >= ttl {
|
||||||
|
out = append(out, call)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -0,0 +1,268 @@
|
|||||||
|
// Package watchlist is the DXHunter watchlist, transplanted: a list of
|
||||||
|
// callsigns (or prefixes) the operator is hunting, matched against the live
|
||||||
|
// spot stream, with per-entry state that survives restarts.
|
||||||
|
//
|
||||||
|
// The JSON file is DXHunter's OWN schema, field for field — including the
|
||||||
|
// ClubLog expedition block this phase does not fill yet. Deliberate: the
|
||||||
|
// operator asked to carry their watchlist.json across, and a file that
|
||||||
|
// round-trips unchanged is the whole of "same format". The file is GLOBAL
|
||||||
|
// (dataDir, beside nets.json), not per profile: a DXpedition worth hunting is
|
||||||
|
// worth hunting whichever station is on.
|
||||||
|
//
|
||||||
|
// The CONTEST idea is per entry, not a global mode as in DXHunter: an entry
|
||||||
|
// marked contest is judged against the CURRENT UTC DAY — at midnight UTC
|
||||||
|
// yesterday's contacts stop counting and every slot reads "work today" again.
|
||||||
|
// Nothing resets and nothing is stored for it: the day boundary lives in the
|
||||||
|
// query, which is why it cannot drift or need a timer.
|
||||||
|
package watchlist
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Entry is one watched callsign. JSON tags match DXHunter's watchlist.json
|
||||||
|
// exactly — see the package comment before renaming anything.
|
||||||
|
type Entry struct {
|
||||||
|
Callsign string `json:"callsign"`
|
||||||
|
LastSeen time.Time `json:"lastSeen"`
|
||||||
|
LastSeenStr string `json:"lastSeenStr"`
|
||||||
|
AddedAt time.Time `json:"addedAt"`
|
||||||
|
SpotCount int `json:"spotCount"`
|
||||||
|
IsContest bool `json:"isContest"`
|
||||||
|
Notify bool `json:"notify"`
|
||||||
|
// ClubLog expedition enrichment — phase 2. Carried so a DXHunter file
|
||||||
|
// round-trips; not filled by OpsLog yet.
|
||||||
|
IsExpedition bool `json:"isExpedition"`
|
||||||
|
ClubLogQSOs24h int `json:"clubLogQSOs24h"`
|
||||||
|
ClubLogTotalQSOs int `json:"clubLogTotalQSOs"`
|
||||||
|
ClubLogHasOQRS bool `json:"clubLogHasOQRS"`
|
||||||
|
ClubLogLiveStream bool `json:"clubLogLiveStream"`
|
||||||
|
ClubLogUpdatedAt time.Time `json:"clubLogUpdatedAt,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store owns the file. All methods are safe for concurrent use; writes are
|
||||||
|
// debounced so a burst of MarkSeen calls costs one disk write.
|
||||||
|
type Store struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
entries map[string]*Entry
|
||||||
|
path string
|
||||||
|
|
||||||
|
saveMu sync.Mutex
|
||||||
|
saveTimer *time.Timer
|
||||||
|
ioMu sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(path string) *Store {
|
||||||
|
s := &Store{entries: map[string]*Entry{}, path: path}
|
||||||
|
s.load()
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) load() {
|
||||||
|
data, err := os.ReadFile(s.path)
|
||||||
|
if err != nil {
|
||||||
|
return // absent on first run — created on first save
|
||||||
|
}
|
||||||
|
var list []Entry
|
||||||
|
if err := json.Unmarshal(data, &list); err != nil {
|
||||||
|
return // a corrupt file must not take the app down; it is left for repair
|
||||||
|
}
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
for i := range list {
|
||||||
|
e := list[i]
|
||||||
|
e.Callsign = strings.ToUpper(strings.TrimSpace(e.Callsign))
|
||||||
|
if e.Callsign == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
s.entries[e.Callsign] = &e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entries returns a snapshot, watched-first ordering left to the UI.
|
||||||
|
func (s *Store) Entries() []Entry {
|
||||||
|
s.mu.RLock()
|
||||||
|
defer s.mu.RUnlock()
|
||||||
|
out := make([]Entry, 0, len(s.entries))
|
||||||
|
for _, e := range s.entries {
|
||||||
|
c := *e
|
||||||
|
c.LastSeenStr = lastSeenLabel(c.LastSeen)
|
||||||
|
out = append(out, c)
|
||||||
|
}
|
||||||
|
sort.Slice(out, func(i, j int) bool { return out[i].Callsign < out[j].Callsign })
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add creates an entry; contest marks it as re-workable every UTC day. A
|
||||||
|
// trailing * makes the entry a prefix (VK9* catches every VK9…); anywhere else
|
||||||
|
// the star is refused rather than silently matching nothing.
|
||||||
|
func (s *Store) Add(callsign string, contest bool) error {
|
||||||
|
call := strings.ToUpper(strings.TrimSpace(callsign))
|
||||||
|
if call == "" {
|
||||||
|
return fmt.Errorf("callsign required")
|
||||||
|
}
|
||||||
|
if i := strings.Index(call, "*"); i >= 0 && i != len(call)-1 {
|
||||||
|
return fmt.Errorf("* is only allowed at the end (VK9*)")
|
||||||
|
}
|
||||||
|
if call == "*" {
|
||||||
|
return fmt.Errorf("a bare * would match every spot")
|
||||||
|
}
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
if _, ok := s.entries[call]; ok {
|
||||||
|
return fmt.Errorf("%s is already on the watchlist", call)
|
||||||
|
}
|
||||||
|
s.entries[call] = &Entry{Callsign: call, AddedAt: time.Now(), IsContest: contest}
|
||||||
|
s.scheduleSave()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove deletes an entry.
|
||||||
|
func (s *Store) Remove(callsign string) error {
|
||||||
|
call := strings.ToUpper(strings.TrimSpace(callsign))
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
if _, ok := s.entries[call]; !ok {
|
||||||
|
return fmt.Errorf("%s is not on the watchlist", call)
|
||||||
|
}
|
||||||
|
delete(s.entries, call)
|
||||||
|
s.scheduleSave()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetNotify arms or disarms the alert for one entry.
|
||||||
|
func (s *Store) SetNotify(callsign string, on bool) error {
|
||||||
|
return s.patch(callsign, func(e *Entry) { e.Notify = on })
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetContest flips the per-entry contest rule.
|
||||||
|
func (s *Store) SetContest(callsign string, on bool) error {
|
||||||
|
return s.patch(callsign, func(e *Entry) { e.IsContest = on })
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) patch(callsign string, fn func(*Entry)) error {
|
||||||
|
call := strings.ToUpper(strings.TrimSpace(callsign))
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
e, ok := s.entries[call]
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("%s is not on the watchlist", call)
|
||||||
|
}
|
||||||
|
fn(e)
|
||||||
|
s.scheduleSave()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Match returns the entry a spotted callsign belongs to, or "".
|
||||||
|
//
|
||||||
|
// EXACT unless the entry says otherwise: N8W matches only N8W, and it takes
|
||||||
|
// N8W* to catch N8WCR. The first version prefix-matched everything, DXHunter
|
||||||
|
// style, and a three-letter special-event call swallowed every longer call
|
||||||
|
// sharing its start — N8W lit up for N8WCR, which is a different station
|
||||||
|
// entirely. The operator writes the star when they MEAN a family (VK9*, an
|
||||||
|
// expedition's portable forms via RI0SP*); a bare entry means that call.
|
||||||
|
func (s *Store) Match(callsign string) (string, bool) {
|
||||||
|
call := strings.ToUpper(strings.TrimSpace(callsign))
|
||||||
|
if call == "" {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
s.mu.RLock()
|
||||||
|
defer s.mu.RUnlock()
|
||||||
|
for pattern := range s.entries {
|
||||||
|
if PatternMatches(pattern, call) {
|
||||||
|
return pattern, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
// PatternMatches reports whether one watchlist pattern covers a callsign:
|
||||||
|
// exact equality, or — with a trailing * — a prefix.
|
||||||
|
func PatternMatches(pattern, call string) bool {
|
||||||
|
if p, ok := strings.CutSuffix(pattern, "*"); ok {
|
||||||
|
return p != "" && strings.HasPrefix(call, p)
|
||||||
|
}
|
||||||
|
return call == pattern
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarkSeen records a spot against the matching entry and reports whether the
|
||||||
|
// entry wants an alert.
|
||||||
|
func (s *Store) MarkSeen(callsign string) (entry string, notify bool, ok bool) {
|
||||||
|
pattern, found := s.Match(callsign)
|
||||||
|
if !found {
|
||||||
|
return "", false, false
|
||||||
|
}
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
e := s.entries[pattern]
|
||||||
|
if e == nil {
|
||||||
|
return "", false, false
|
||||||
|
}
|
||||||
|
e.LastSeen = time.Now()
|
||||||
|
e.SpotCount++
|
||||||
|
s.scheduleSave()
|
||||||
|
return e.Callsign, e.Notify, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// scheduleSave debounces the write: a burst of spots costs one file write two
|
||||||
|
// seconds after the last of them. Callers hold s.mu.
|
||||||
|
func (s *Store) scheduleSave() {
|
||||||
|
s.saveMu.Lock()
|
||||||
|
defer s.saveMu.Unlock()
|
||||||
|
if s.saveTimer != nil {
|
||||||
|
s.saveTimer.Stop()
|
||||||
|
}
|
||||||
|
s.saveTimer = time.AfterFunc(2*time.Second, func() { s.persist() })
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) persist() {
|
||||||
|
list := s.Entries()
|
||||||
|
data, err := json.MarshalIndent(list, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.ioMu.Lock()
|
||||||
|
defer s.ioMu.Unlock()
|
||||||
|
_ = os.WriteFile(s.path, data, 0o644)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Flush writes now — for shutdown, where the two-second debounce would lose
|
||||||
|
// the last edits.
|
||||||
|
func (s *Store) Flush() { s.persist() }
|
||||||
|
|
||||||
|
// lastSeenLabel is DXHunter's "Just now / 5m ago / 3h ago / 2d ago" string,
|
||||||
|
// computed at read time so it never goes stale in the file.
|
||||||
|
func lastSeenLabel(t time.Time) string {
|
||||||
|
if t.IsZero() {
|
||||||
|
return "Never"
|
||||||
|
}
|
||||||
|
d := time.Since(t)
|
||||||
|
switch {
|
||||||
|
case d < time.Minute:
|
||||||
|
return "Just now"
|
||||||
|
case d < time.Hour:
|
||||||
|
return fmt.Sprintf("%dm ago", int(d.Minutes()))
|
||||||
|
case d < 24*time.Hour:
|
||||||
|
return fmt.Sprintf("%dh ago", int(d.Hours()))
|
||||||
|
default:
|
||||||
|
return fmt.Sprintf("%dd ago", int(d.Hours()/24))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get returns one entry by its exact name — the alert path needs its contest
|
||||||
|
// flag after MarkSeen named it.
|
||||||
|
func (s *Store) Get(callsign string) (Entry, bool) {
|
||||||
|
s.mu.RLock()
|
||||||
|
defer s.mu.RUnlock()
|
||||||
|
e, ok := s.entries[strings.ToUpper(strings.TrimSpace(callsign))]
|
||||||
|
if !ok {
|
||||||
|
return Entry{}, false
|
||||||
|
}
|
||||||
|
return *e, true
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
package watchlist
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGlobMatch(t *testing.T) {
|
||||||
|
s := New(filepath.Join(t.TempDir(), "watchlist.json"))
|
||||||
|
if err := s.Add("RI0SP*", false); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := s.Add("N8W", false); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// A starred entry is a family: the expedition's portable forms.
|
||||||
|
for _, call := range []string{"RI0SP", "RI0SP/MM", "RI0SP/P"} {
|
||||||
|
if _, ok := s.Match(call); !ok {
|
||||||
|
t.Errorf("Match(%q) = false, want true", call)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A bare entry is THAT call — the reported bug was N8W lighting up for
|
||||||
|
// N8WCR, a different station entirely.
|
||||||
|
if _, ok := s.Match("N8W"); !ok {
|
||||||
|
t.Error("exact entry must match its own call")
|
||||||
|
}
|
||||||
|
if _, ok := s.Match("N8WCR"); ok {
|
||||||
|
t.Error("exact entry must NOT match a longer call")
|
||||||
|
}
|
||||||
|
if _, ok := s.Match("RI0S"); ok {
|
||||||
|
t.Error("a SHORTER call must not match a starred entry")
|
||||||
|
}
|
||||||
|
if err := s.Add("VK*9", false); err == nil {
|
||||||
|
t.Error("a mid-string star must be refused")
|
||||||
|
}
|
||||||
|
if err := s.Add("*", false); err == nil {
|
||||||
|
t.Error("a bare star must be refused")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDXHunterFileRoundTrips(t *testing.T) {
|
||||||
|
// A real DXHunter entry, ClubLog block included. It must survive
|
||||||
|
// load → save byte-meaningfully: same keys, values preserved.
|
||||||
|
src := `[{"callsign":"C5SP","lastSeen":"0001-01-01T00:00:00Z","lastSeenStr":"Never",
|
||||||
|
"addedAt":"2026-01-17T00:18:43.89Z","spotCount":7,"isContest":true,"notify":true,
|
||||||
|
"isExpedition":true,"clubLogQSOs24h":120,"clubLogTotalQSOs":30500,
|
||||||
|
"clubLogHasOQRS":true,"clubLogLiveStream":true,"clubLogUpdatedAt":"2026-08-28T22:32:18Z"}]`
|
||||||
|
dir := t.TempDir()
|
||||||
|
path := filepath.Join(dir, "watchlist.json")
|
||||||
|
if err := os.WriteFile(path, []byte(src), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
s := New(path)
|
||||||
|
s.Flush()
|
||||||
|
out, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var list []map[string]any
|
||||||
|
if err := json.Unmarshal(out, &list); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(list) != 1 {
|
||||||
|
t.Fatalf("got %d entries", len(list))
|
||||||
|
}
|
||||||
|
e := list[0]
|
||||||
|
for k, want := range map[string]any{
|
||||||
|
"callsign": "C5SP", "isContest": true, "notify": true,
|
||||||
|
"isExpedition": true, "clubLogQSOs24h": float64(120),
|
||||||
|
"clubLogTotalQSOs": float64(30500), "clubLogHasOQRS": true,
|
||||||
|
} {
|
||||||
|
if e[k] != want {
|
||||||
|
t.Errorf("%s = %v, want %v", k, e[k], want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMarkSeenAndNotify(t *testing.T) {
|
||||||
|
s := New(filepath.Join(t.TempDir(), "watchlist.json"))
|
||||||
|
_ = s.Add("HB040A", false)
|
||||||
|
_ = s.SetNotify("HB040A", true)
|
||||||
|
entry, notify, ok := s.MarkSeen("HB040A")
|
||||||
|
if !ok || !notify || entry != "HB040A" {
|
||||||
|
t.Fatalf("MarkSeen = %q %v %v", entry, notify, ok)
|
||||||
|
}
|
||||||
|
list := s.Entries()
|
||||||
|
if list[0].SpotCount != 1 || list[0].LastSeenStr != "Just now" {
|
||||||
|
t.Errorf("entry after MarkSeen: %+v", list[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -21,7 +21,7 @@ import (
|
|||||||
|
|
||||||
const (
|
const (
|
||||||
// appVersion is stamped on every heartbeat (and could feed the About box).
|
// appVersion is stamped on every heartbeat (and could feed the About box).
|
||||||
appVersion = "0.26.22"
|
appVersion = "0.27.2"
|
||||||
|
|
||||||
// posthogHost is the PostHog ingestion endpoint. EU cloud by default; change
|
// posthogHost is the PostHog ingestion endpoint. EU cloud by default; change
|
||||||
// to https://us.i.posthog.com for a US project.
|
// to https://us.i.posthog.com for a US project.
|
||||||
|
|||||||
Reference in New Issue
Block a user