-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathRadioModel.cpp
More file actions
4556 lines (4116 loc) · 187 KB
/
RadioModel.cpp
File metadata and controls
4556 lines (4116 loc) · 187 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "RadioModel.h"
#include "core/CommandParser.h"
#include "core/AppSettings.h"
#include "core/CwTrace.h"
#include "core/LogManager.h"
#include "core/StreamStatus.h"
#include "core/UdpRegistrationPolicy.h"
#include "RadioStatusOwnership.h"
#include <QCoreApplication>
#include <QDebug>
#include <QJsonArray>
#include <QJsonObject>
#include <QRegularExpression>
#include <QDateTime>
#include <QSysInfo>
#include <QtEndian>
#include <algorithm>
#include <cmath>
#include <memory>
namespace AetherSDR {
namespace {
QJsonArray toJsonArray(const QStringList& values)
{
QJsonArray array;
for (const QString& value : values)
array.append(value);
return array;
}
QJsonArray toJsonArray(const QVector<int>& values)
{
QJsonArray array;
for (int value : values)
array.append(value);
return array;
}
QJsonArray toJsonArray(const QSet<int>& values)
{
QList<int> sorted = values.values();
std::sort(sorted.begin(), sorted.end());
QJsonArray array;
for (int value : sorted)
array.append(value);
return array;
}
QString atuStatusToString(ATUStatus status)
{
switch (status) {
case ATUStatus::None: return "None";
case ATUStatus::NotStarted: return "NotStarted";
case ATUStatus::InProgress: return "InProgress";
case ATUStatus::Bypass: return "Bypass";
case ATUStatus::Successful: return "Successful";
case ATUStatus::OK: return "OK";
case ATUStatus::FailBypass: return "FailBypass";
case ATUStatus::Fail: return "Fail";
case ATUStatus::Aborted: return "Aborted";
case ATUStatus::ManualBypass: return "ManualBypass";
}
return "Unknown";
}
bool statusFlagSet(const QMap<QString, QString>& kvs, const QString& key)
{
const QString value = kvs.value(key).trimmed();
return value == QStringLiteral("1")
|| value.compare(QStringLiteral("true"), Qt::CaseInsensitive) == 0;
}
QString cleanClientText(QString value)
{
value.replace(QChar(0x7f), QLatin1Char(' '));
return value.trimmed();
}
quint32 parseClientHandle(QString text)
{
text = text.trimmed();
if (text.startsWith(QStringLiteral("0x"), Qt::CaseInsensitive))
text = text.mid(2);
bool ok = false;
const quint32 handle = text.toUInt(&ok, 16);
return ok ? handle : 0;
}
// parseStreamToken — identical to parseStatusHandle; use the shared version.
inline quint32 parseStreamToken(QString text) { return parseStatusHandle(std::move(text)); }
QString hexId(quint32 value)
{
return QStringLiteral("0x%1")
.arg(QString::number(value, 16).rightJustified(8, QLatin1Char('0')));
}
QString hexCode(int value)
{
return QStringLiteral("0x%1")
.arg(QString::number(static_cast<quint32>(value), 16).rightJustified(8, QLatin1Char('0')));
}
QString normalizePanadapterId(QString text)
{
text = text.trimmed();
if (text.isEmpty())
return QString();
if (text.startsWith(QStringLiteral("0x"), Qt::CaseInsensitive))
text = text.mid(2);
bool ok = false;
const quint32 id = text.toUInt(&ok, 16);
return ok ? hexId(id) : text;
}
QString parsePanadapterCreateId(const QString& body)
{
const QMap<QString, QString> kvs = CommandParser::parseKVs(body);
if (kvs.contains(QStringLiteral("pan")))
return normalizePanadapterId(kvs.value(QStringLiteral("pan")));
if (kvs.contains(QStringLiteral("id")))
return normalizePanadapterId(kvs.value(QStringLiteral("id")));
return normalizePanadapterId(body);
}
struct StreamObjectParts {
bool valid{false};
quint32 streamId{0};
QString action;
};
StreamObjectParts parseStreamObject(const QString& object, const QString& prefix)
{
if (!object.startsWith(prefix + QLatin1Char(' ')))
return {};
const QString rest = object.mid(prefix.size() + 1).trimmed();
const int firstSpace = rest.indexOf(QLatin1Char(' '));
const QString idText = firstSpace >= 0 ? rest.left(firstSpace) : rest;
StreamObjectParts parts;
parts.streamId = parseStreamToken(idText);
parts.valid = parts.streamId != 0;
if (firstSpace >= 0)
parts.action = rest.mid(firstSpace + 1).trimmed();
return parts;
}
bool isDaxStreamType(const QString& type)
{
return type == QStringLiteral("dax_rx")
|| type == QStringLiteral("dax_tx")
|| type == QStringLiteral("dax_mic")
|| type == QStringLiteral("dax_iq");
}
bool streamStatusRemoved(const StreamObjectParts& stream,
const QMap<QString, QString>& kvs)
{
return stream.action == QStringLiteral("removed")
|| kvs.contains(QStringLiteral("removed"))
|| kvs.value(QStringLiteral("in_use")) == QStringLiteral("0");
}
bool looksLikeClientId(const QString& value)
{
static const QRegularExpression guidRe(
QStringLiteral(R"(^\{?[0-9A-Fa-f]{8}-?[0-9A-Fa-f]{4}-?[0-9A-Fa-f]{4}-?[0-9A-Fa-f]{4}-?[0-9A-Fa-f]{12}\}?$)"));
return guidRe.match(value.trimmed()).hasMatch();
}
QString clientConnectionSource(const QMap<QString, QString>& kvs)
{
const QStringList keys = {
QStringLiteral("ip"),
QStringLiteral("client_ip"),
QStringLiteral("remote_ip"),
QStringLiteral("name")
};
for (const QString& key : keys) {
const QString value = cleanClientText(kvs.value(key));
if (!value.isEmpty() && !looksLikeClientId(value))
return value;
}
return {};
}
QJsonObject panToJson(const PanadapterModel* pan, const QString& activePanId)
{
QJsonObject obj;
obj["pan_id"] = pan->panId();
obj["active"] = pan->panId() == activePanId;
obj["waterfall_id"] = pan->waterfallId();
obj["center_mhz"] = pan->centerMhz();
obj["bandwidth_mhz"] = pan->bandwidthMhz();
obj["min_dbm"] = pan->minDbm();
obj["max_dbm"] = pan->maxDbm();
obj["antennas"] = toJsonArray(pan->antList());
obj["rf_gain"] = pan->rfGain();
obj["rf_gain_low"] = pan->rfGainLow();
obj["rf_gain_high"] = pan->rfGainHigh();
obj["rf_gain_step"] = pan->rfGainStep();
obj["preamp"] = pan->preamp();
obj["wnb_active"] = pan->wnbActive();
obj["wnb_level"] = pan->wnbLevel();
obj["resized"] = pan->isResized();
obj["waterfall_configured"] = pan->isWaterfallConfigured();
return obj;
}
QJsonObject xvtrToJson(const RadioModel::XvtrInfo& xvtr)
{
QJsonObject obj;
obj["index"] = xvtr.index;
obj["order"] = xvtr.order;
obj["name"] = xvtr.name;
obj["rf_freq_mhz"] = xvtr.rfFreq;
obj["if_freq_mhz"] = xvtr.ifFreq;
obj["offset_mhz"] = xvtr.rfFreq - xvtr.ifFreq;
obj["lo_error"] = xvtr.loError;
obj["rx_gain"] = xvtr.rxGain;
obj["max_power"] = xvtr.maxPower;
obj["rx_only"] = xvtr.rxOnly;
obj["is_valid"] = xvtr.isValid;
obj["has_is_valid"] = xvtr.hasIsValid;
return obj;
}
QJsonObject clientInfoToJson(quint32 handle,
quint32 ourHandle,
quint32 txHandle,
const RadioModel::ClientInfo& info)
{
QJsonObject obj;
obj["role"] = (handle == ourHandle) ? "current_app" : "other_client";
obj["owns_tx"] = (txHandle != 0 && handle == txHandle);
obj["program"] = info.program;
obj["source"] = info.source;
obj["local_ptt"] = info.localPtt;
obj["tx_antenna"] = info.txAntenna;
obj["tx_freq_mhz"] = info.txFreqMhz;
return obj;
}
} // namespace
RadioModel::RadioModel(QObject* parent)
: QObject(parent)
{
// PanadapterStream runs on its own network thread (#502)
m_networkThread = new QThread(this);
m_networkThread->setObjectName("PanadapterStream");
m_panStream = new PanadapterStream; // no parent — will be moved to thread
m_panStream->moveToThread(m_networkThread);
connect(m_networkThread, &QThread::started, m_panStream, &PanadapterStream::init);
m_networkThread->start();
// RadioConnection runs on its own worker thread (#502) so TCP I/O
// (including ping RTT measurement) is never blocked by paintEvent.
m_connThread = new QThread(this);
m_connThread->setObjectName("RadioConnection");
m_connection = new RadioConnection; // no parent — will be moved to thread
m_connection->moveToThread(m_connThread);
connect(m_connThread, &QThread::started, m_connection, &RadioConnection::init);
m_connThread->start();
// Signals from RadioConnection auto-queue to main thread (#502)
connect(m_connection, &RadioConnection::statusReceived,
this, &RadioModel::onStatusReceived);
connect(m_connection, &RadioConnection::messageReceived,
this, &RadioModel::onMessageReceived);
connect(m_connection, &RadioConnection::connected,
this, &RadioModel::onConnected);
connect(m_connection, &RadioConnection::disconnected,
this, &RadioModel::onDisconnected);
connect(m_connection, &RadioConnection::errorOccurred,
this, &RadioModel::onConnectionError);
connect(m_connection, &RadioConnection::versionReceived,
this, &RadioModel::onVersionReceived);
// Response callbacks: RadioConnection emits commandResponse on worker thread,
// we dispatch to the matching callback on the main thread. (#502)
connect(m_connection, &RadioConnection::commandResponse,
this, [this](quint32 seq, int code, const QString& body) {
auto it = m_pendingCallbacks.find(seq);
if (it != m_pendingCallbacks.end()) {
it.value()(code, body);
m_pendingCallbacks.erase(it);
}
});
// Forward VITA-49 meter packets to MeterModel (cross-thread, auto-queued)
connect(m_panStream, &PanadapterStream::meterDataReady,
&m_meterModel, &MeterModel::updateValues);
// Forward tuner commands to the radio — route through tune inhibit check
connect(&m_tunerModel, &TunerModel::commandReady, this, [this](const QString& cmd){
if (cmd.startsWith("tgxl autotune"))
applyTuneInhibit();
sendCmd(cmd);
});
// Forward DAX IQ commands to the radio
connect(&m_daxIqModel, &DaxIqModel::commandReady, this, [this](const QString& cmd){
sendCmd(cmd);
});
// Forward transmit model commands to the radio
connect(&m_transmitModel, &TransmitModel::commandReady, this, [this](const QString& cmd){
static const QRegularExpression xmitRe(R"(^xmit\s+([01])\s*$)", QRegularExpression::CaseInsensitiveOption);
const auto match = xmitRe.match(cmd.trimmed());
if (match.hasMatch()) {
const bool tx = (match.captured(1) == "1");
m_txRequested = tx;
if (!tx && m_txAudioGate) {
m_txAudioGate = false;
emit txAudioGateChanged(false);
}
}
if (cmd == "transmit tune 1" || cmd == "atu start")
applyTuneInhibit();
sendCmd(cmd);
});
// Forward equalizer model commands to the radio
connect(&m_equalizerModel, &EqualizerModel::commandReady, this, [this](const QString& cmd){
sendCmd(cmd);
});
// Forward TNF model commands to the radio
connect(&m_tnfModel, &TnfModel::commandReady, this, [this](const QString& cmd){
sendCmd(cmd);
});
connect(&m_cwxModel, &CwxModel::commandReady, this, [this](const QString& cmd){
// Track CWX send state so the interlock handler recognises local
// CWX TX and doesn't force the audio gate off. (#2047, #2097)
if (cmd.startsWith("cwx send") || cmd.startsWith("cwx macro send"))
m_cwxActive = true;
else if (cmd.startsWith("cwx clear"))
m_cwxActive = false;
sendCmd(cmd);
});
connect(&m_dvkModel, &DvkModel::commandReady, this, [this](const QString& cmd){
sendCmd(cmd);
});
connect(&m_navtexModel, &NavtexModel::commandReady, this, [this](const QString& cmd){
sendCmd(cmd);
});
connect(&m_navtexModel, &NavtexModel::replyCommandReady, this, [this](const QString& cmd, int seq){
sendCmd(cmd, [this, seq](int respVal, const QString& body){
m_navtexModel.handleSendResponse(seq, static_cast<uint>(respVal), body);
});
});
connect(&m_usbCableModel, &UsbCableModel::commandReady, this, [this](const QString& cmd){
sendCmd(cmd);
});
// Tune PA inhibit: restore TX outputs when tune completes
connect(&m_transmitModel, &TransmitModel::tuneChanged, this, [this](bool tuning) {
if (!tuning && m_tuneInhibitActive && m_tuneInhibitBandId >= 0)
restoreTuneInhibit();
});
m_reconnectTimer.setInterval(5000);
connect(&m_reconnectTimer, &QTimer::timeout, this, [this]() {
if (!m_intentionalDisconnect && !m_lastInfo.address.isNull()) {
qCDebug(lcProtocol) << "RadioModel: auto-reconnecting to" << m_lastInfo.address.toString();
QMetaObject::invokeMethod(m_connection, [this] {
m_connection->connectToRadio(m_lastInfo);
});
} else {
m_reconnectTimer.stop();
}
});
}
RadioModel::~RadioModel()
{
// Disconnect all signals BEFORE member destruction to prevent
// use-after-free (ASAN). (#502)
QObject::disconnect(m_connection, nullptr, this, nullptr);
QObject::disconnect(m_panStream, nullptr, this, nullptr);
// Stop connection thread (#502)
if (m_connection && m_connThread && m_connThread->isRunning()) {
RadioConnection* connection = m_connection;
QMetaObject::invokeMethod(connection, &RadioConnection::disconnectFromRadio,
Qt::BlockingQueuedConnection);
connection->deleteLater();
m_connThread->quit();
m_connThread->wait(3000);
} else {
delete m_connection;
}
if (m_connThread && m_connThread->isRunning()) {
m_connThread->quit();
m_connThread->wait(3000);
}
m_connection = nullptr;
// Stop network thread (#502)
if (m_panStream && m_networkThread && m_networkThread->isRunning()) {
PanadapterStream* panStream = m_panStream;
QMetaObject::invokeMethod(panStream, &PanadapterStream::stop,
Qt::BlockingQueuedConnection);
panStream->deleteLater();
m_networkThread->quit();
m_networkThread->wait(3000);
} else {
delete m_panStream;
}
if (m_networkThread && m_networkThread->isRunning()) {
m_networkThread->quit();
m_networkThread->wait(3000);
}
m_panStream = nullptr;
}
bool RadioModel::isConnected() const
{
return m_connection->isConnected() || (m_wanConn && m_wanConn->isConnected());
}
int RadioModel::maxSlicesForModel(const QString& model)
{
const QString normalized = model.toUpper();
// FlexRadio lists slice capacity as independent receivers per model family.
if (normalized.contains("6700"))
return 8;
if (normalized.contains("6600") || normalized.contains("6500")
|| normalized.contains("8600") || normalized.contains("AU-520"))
return 4;
if (normalized.contains("6300") || normalized.contains("6400")
|| normalized.contains("8400") || normalized.contains("AU-510"))
return 2;
return 4;
}
SliceModel* RadioModel::slice(int id) const
{
for (auto* s : m_slices)
if (s->sliceId() == id) return s;
return nullptr;
}
int RadioModel::activeTxSliceNum() const
{
for (auto* s : m_slices) {
if (s && s->isTxSlice())
return s->sliceId();
}
return -1;
}
// ─── Actions ──────────────────────────────────────────────────────────────────
void RadioModel::connectToRadio(const RadioInfo& info)
{
m_wanConn = nullptr; // LAN mode
m_lastInfo = info;
m_intentionalDisconnect = false;
m_forcedDisconnectInProgress = false;
m_announcedClientConnections.clear();
m_reconnectTimer.stop();
m_name = info.name;
m_model = info.model;
m_version = info.version;
m_maxSlices = maxSlicesForModel(m_model);
setKnownGuiClients(info.guiClientHandles,
info.guiClientPrograms,
info.guiClientStations,
info.guiClientIps,
info.guiClientHosts);
QMetaObject::invokeMethod(m_connection, [conn = m_connection, info] {
conn->connectToRadio(info);
});
}
void RadioModel::connectViaWan(WanConnection* wan, const QString& publicIp, quint16 udpPort)
{
qCDebug(lcProtocol) << "RadioModel: connectViaWan publicIp=" << publicIp
<< "udpPort=" << udpPort
<< "wanHandle=0x" << QString::number(wan->clientHandle(), 16);
// Disconnect any stale signal connections from a previous WAN session
if (m_wanConn)
m_wanConn->disconnect(this);
m_wanConn = wan;
m_wanPublicIp = publicIp;
m_wanUdpPort = udpPort;
m_intentionalDisconnect = false;
m_forcedDisconnectInProgress = false;
m_announcedClientConnections.clear();
m_reconnectTimer.stop();
// Wire WAN connection signals (same as RadioConnection)
connect(wan, &WanConnection::connected, this, &RadioModel::onConnected);
connect(wan, &WanConnection::disconnected, this, &RadioModel::onDisconnected);
connect(wan, &WanConnection::errorOccurred, this, &RadioModel::onConnectionError);
connect(wan, &WanConnection::versionReceived, this, &RadioModel::onVersionReceived);
connect(wan, &WanConnection::messageReceived, this, &RadioModel::onMessageReceived);
connect(wan, &WanConnection::statusReceived, this, &RadioModel::onStatusReceived);
connect(wan, &WanConnection::pingRttMeasured, this, [this](int ms) {
m_pingMissCount = 0;
m_lastPingRtt = ms;
evaluateNetworkQuality();
emit pingReceived();
});
// The WAN connection is already established (TLS + wan validate done)
// and has already received V/H. Trigger onConnected manually.
if (wan->isConnected()) {
qCDebug(lcProtocol) << "RadioModel: WAN already connected, triggering onConnected";
onConnected();
} else {
qCDebug(lcProtocol) << "RadioModel: WAN not yet connected, waiting for connected signal";
}
}
void RadioModel::setPendingClientDisconnects(const QList<quint32>& handles)
{
m_pendingClientDisconnects.clear();
for (quint32 handle : handles) {
if (handle != 0 && !m_pendingClientDisconnects.contains(handle))
m_pendingClientDisconnects.append(handle);
}
}
void RadioModel::setKnownGuiClients(const QStringList& handles,
const QStringList& programs,
const QStringList& stations,
const QStringList& ips,
const QStringList& hosts)
{
applyKnownGuiClients(handles, programs, stations, ips, hosts, true);
}
void RadioModel::mergeKnownGuiClients(const QStringList& handles,
const QStringList& programs,
const QStringList& stations,
const QStringList& ips,
const QStringList& hosts)
{
applyKnownGuiClients(handles, programs, stations, ips, hosts, false);
}
void RadioModel::applyKnownGuiClients(const QStringList& handles,
const QStringList& programs,
const QStringList& stations,
const QStringList& ips,
const QStringList& hosts,
bool replaceExisting)
{
if (replaceExisting) {
m_clientStations.clear();
m_clientInfoMap.clear();
m_startupClientConnections.clear();
}
for (int i = 0; i < handles.size(); ++i) {
const quint32 handle = parseClientHandle(handles[i]);
if (handle == 0)
continue;
if (replaceExisting)
m_startupClientConnections.insert(handle);
const QString program = i < programs.size()
? cleanClientText(programs[i])
: QStringLiteral("Unknown");
const QString station = i < stations.size()
? cleanClientText(stations[i])
: program;
QString source = i < ips.size()
? cleanClientText(ips[i])
: QString();
if (source.isEmpty() && i < hosts.size())
source = cleanClientText(hosts[i]);
ClientInfo client = m_clientInfoMap.value(handle);
if (!station.isEmpty())
client.station = station;
if (!program.isEmpty() && program != QStringLiteral("Unknown"))
client.program = program;
if (!source.isEmpty())
client.source = source;
m_clientStations[handle] = client.station.isEmpty() ? client.program : client.station;
m_clientInfoMap[handle] = client;
}
}
bool RadioModel::shouldSuppressClientConnectionNotice(quint32 handle)
{
if (handle == 0 || handle == clientHandle())
return true;
if (m_startupClientConnections.remove(handle)) {
m_announcedClientConnections.insert(handle);
return true;
}
if (m_clientConnectionNoticeTimer.isValid()
&& m_clientConnectionNoticeTimer.elapsed() < CLIENT_CONNECTION_STARTUP_SUPPRESS_MS) {
m_announcedClientConnections.insert(handle);
return true;
}
return false;
}
void RadioModel::announceClientConnection(quint32 handle,
const QString& source,
const QString& station,
const QString& program)
{
if (handle == clientHandle() || m_announcedClientConnections.contains(handle))
return;
m_announcedClientConnections.insert(handle);
QTimer::singleShot(750, this, [this, handle, source, station, program] {
if (!m_clientInfoMap.contains(handle))
return;
const auto client = m_clientInfoMap.value(handle);
QString latestSource = client.source.isEmpty() ? source : client.source;
QString latestStation = client.station.isEmpty() ? station : client.station;
QString latestProgram = client.program.isEmpty() ? program : client.program;
if (m_wanConn && (latestSource.isEmpty() || latestSource == QStringLiteral("SmartLink"))) {
QTimer::singleShot(1250, this, [this, handle, latestSource, latestStation, latestProgram] {
if (!m_clientInfoMap.contains(handle))
return;
const auto client = m_clientInfoMap.value(handle);
emit clientConnected(handle,
client.source.isEmpty() ? latestSource : client.source,
client.station.isEmpty() ? latestStation : client.station,
client.program.isEmpty() ? latestProgram : client.program);
});
return;
}
emit clientConnected(handle, latestSource, latestStation, latestProgram);
});
}
void RadioModel::disconnectFromRadio()
{
m_intentionalDisconnect = true;
m_reconnectTimer.stop();
m_pingTimer.stop();
if (m_wanConn) {
WanConnection* wan = m_wanConn;
wan->disconnect(this); // remove stale signal connections before adding the one-shot teardown (#224)
connect(wan, &WanConnection::disconnected, this, [this, wan]() {
if (m_wanConn == wan) {
onDisconnected();
}
}, Qt::SingleShotConnection);
wan->disconnectFromRadio();
if (wan->isSocketIdle() && m_wanConn == wan) {
onDisconnected();
}
} else if (m_connection->isConnected()) {
// Graceful disconnect: remove our stream and wait for the radio reply
// before closing. Self "client disconnect" is rejected by the radio.
quint32 handle = clientHandle();
QString streamId = RadioStatusOwnership::streamCommandId(m_rxAudio.streamId);
const quint32 streamRemoveSeq = streamId.isEmpty() ? 0 : m_seqCounter.fetch_add(1);
QMetaObject::invokeMethod(m_connection, [this, handle, streamId,
streamRemoveSeq]() {
m_connection->gracefulDisconnect(handle, streamId, streamRemoveSeq);
}, Qt::BlockingQueuedConnection);
} else {
QMetaObject::invokeMethod(m_connection, &RadioConnection::disconnectFromRadio,
Qt::BlockingQueuedConnection);
}
}
void RadioModel::forceDisconnect()
{
// Close TCP/TLS without setting m_intentionalDisconnect so the UI can
// start the normal unexpected-disconnect reconnect path.
if (m_wanConn) {
m_wanConn->disconnectFromRadio();
} else if (m_connection->isConnected()) {
quint32 handle = clientHandle();
QMetaObject::invokeMethod(m_connection, [conn = m_connection, handle]() {
conn->gracefulDisconnect(handle, QString(), 0);
});
} else {
QMetaObject::invokeMethod(m_connection, &RadioConnection::disconnectFromRadio);
}
}
void RadioModel::setTransmit(bool tx)
{
// Track local intent so we can keep TX gating aligned with user/PTT edges
// while radio interlock transitions through intermediate states.
m_txRequested = tx;
// Optimistic edge gating:
// - TX on: start immediately to keep modem waveform aligned with PTT edge.
// - TX off: stop immediately to avoid "stuck TX tail" during UNKEY_REQUESTED.
m_transmitModel.setTransmitting(tx);
if (!tx && m_txAudioGate) {
m_txAudioGate = false;
emit txAudioGateChanged(false);
}
sendCmd(QString("xmit %1").arg(tx ? 1 : 0));
}
QString RadioModel::audioCompressionParam() const
{
QString setting = AppSettings::instance().value("AudioCompression", "None").toString();
if (setting == "Opus") return "opus";
if (setting == "None") return "none";
// Auto: use Opus on WAN, uncompressed on LAN
return isWan() ? "opus" : "none";
}
void RadioModel::sendCwKey(bool down, const QString& debugSource,
quint64 debugTraceId, quint64 debugSourceMs)
{
const bool prev = m_cwKeyActive;
m_cwKeyActive = down;
// Send only the key edge — the radio's break-in setting decides whether
// it transmits. With break_in=1 (QSK), `cw key 1` triggers TX and
// break_in_delay holds the relay between elements. With break_in=0,
// the radio queues the key but doesn't transmit until the operator
// explicitly asserts CW PTT (Space PTT, MOX, or hardware PTT) — the
// standard semi-break-in workflow per FlexLib Radio.cs:8890–8965.
sendNetCwCommand(QString("cw key %1").arg(down ? 1 : 0),
debugSource, debugTraceId, debugSourceMs);
if (prev != down)
emit cwKeyDownChanged(down);
}
void RadioModel::sendCwPaddle(bool dit, bool dah, const QString& debugSource,
quint64 debugTraceId, quint64 debugSourceMs)
{
// The radio's CW protocol does NOT accept a 2-arg paddle form like
// `cw key dit dah` — FlexLib only ever sends `cw key 1` or `cw key 0`
// (single state) and expects the client to do iambic timing locally.
// Treat any paddle press as a straight-key down so this path still
// works when the local iambic keyer is disabled. When the keyer IS
// running it intercepts upstream and uses sendCwPtt + sendCwKeyEdge
// directly, bypassing this method.
sendCwKey(dit || dah, debugSource, debugTraceId, debugSourceMs);
}
void RadioModel::sendCwPtt(bool on, const QString& debugSource,
quint64 debugTraceId, quint64 debugSourceMs)
{
sendNetCwCommand(on ? QStringLiteral("cw ptt 1") : QStringLiteral("cw ptt 0"),
debugSource, debugTraceId, debugSourceMs);
}
void RadioModel::sendCwKeyEdge(bool down, const QString& debugSource,
quint64 debugTraceId, quint64 debugSourceMs)
{
const bool prev = m_cwKeyActive;
m_cwKeyActive = down;
sendNetCwCommand(QString("cw key %1").arg(down ? 1 : 0),
debugSource, debugTraceId, debugSourceMs);
if (prev != down)
emit cwKeyDownChanged(down);
}
// ── NetCW stream — VITA-49 UDP delivery with redundant sends ────────────────
QByteArray RadioModel::buildNetCwPacket(const QByteArray& payload)
{
// VITA-49 header (28 bytes) + ASCII command payload. Working Maestro
// captures show the payload null-padded to a 32-bit word boundary; keep
// the datagram length consistent with the VRT packet_size field.
const int payloadBytes = payload.size();
const int paddedPayloadBytes = (payloadBytes + 3) & ~3;
const int packetWords = static_cast<int>(std::ceil(payloadBytes / 4.0) + 7); // 7 header words
const int packetBytes = 28 + paddedPayloadBytes;
QByteArray pkt(packetBytes, '\0');
auto* w = reinterpret_cast<quint32*>(pkt.data());
// Word 0: ExtDataWithStream, C=1, T=0, TSI=3(Other), TSF=1(SampleCount)
static int pktCount = 0;
quint32 hdr = (0x3u << 28) // pkt_type = ExtDataWithStream
| (1u << 27) // C = 1 (class ID present)
| (0x3u << 22) // TSI = 3 (Other)
| (0x1u << 20) // TSF = 1 (SampleCount)
| ((pktCount & 0x0F) << 16)
| (packetWords & 0xFFFF);
pktCount = (pktCount + 1) & 0x0F;
w[0] = qToBigEndian(hdr);
w[1] = qToBigEndian(m_netCwStreamId);
w[2] = qToBigEndian<quint32>(0x00001C2D); // OUI (FlexRadio)
w[3] = qToBigEndian<quint32>(0x534C03E3); // ICC=0x534C, PCC=0x03E3
w[4] = 0; w[5] = 0; w[6] = 0; // timestamps
// Payload: ASCII command string
memcpy(pkt.data() + 28, payload.constData(), payloadBytes);
return pkt;
}
void RadioModel::sendNetCwCommand(const QString& baseCmd, const QString& debugSource,
quint64 debugTraceId, quint64 debugSourceMs)
{
if (m_netCwStreamId == 0) {
// No netcw stream — fall back to TCP immediate
const QString fallbackCmd = baseCmd.contains("cw key")
? QString(baseCmd).replace("cw key", "cw key immediate")
: baseCmd;
if (lcCw().isDebugEnabled()) {
const quint64 now = cwTraceNowMs();
qCDebug(lcCw).noquote().nospace()
<< "CW netcw fallback trace=" << debugTraceId
<< " t=" << now << "ms"
<< " sinceSourceMs=" << (debugSourceMs ? static_cast<qint64>(now - debugSourceMs) : -1)
<< " source=" << (debugSource.isEmpty() ? QStringLiteral("unknown") : debugSource)
<< " cmd=\"" << fallbackCmd << "\"";
}
sendCmd(fallbackCmd);
return;
}
// Build the full command with timing metadata and dedup index
// FlexLib format: "cw key 1 time=0x<hex_ms> index=<N> client_handle=0x<handle>".
// The time value is a 16-bit relative millisecond counter, not an epoch
// timestamp. Flex clients reset it after a short idle gap; the radio
// accepts 0x0000 as a timing resync marker.
constexpr qint64 kNetCwIdleResetMs = 3000;
quint16 timeMs = 0;
if (!m_netCwClock.isValid()
|| m_netCwLastSendMs < 0
|| (m_netCwClock.elapsed() - m_netCwLastSendMs) > kNetCwIdleResetMs) {
if (m_netCwClock.isValid())
m_netCwClock.restart();
else
m_netCwClock.start();
m_netCwLastSendMs = 0;
} else {
const qint64 elapsed = m_netCwClock.elapsed();
timeMs = static_cast<quint16>(elapsed & 0xFFFF);
m_netCwLastSendMs = elapsed;
}
int index = m_netCwIndex++;
// FlexLib formats hex values UPPERCASE (C# ToString("X")), and the
// radio's status messages do too (e.g. `S23A59BDF|...`) — the netcw
// parser appears to be case-sensitive on `client_handle`. Match that
// by formatting both hex values uppercase explicitly.
const QString tsHex = QString("%1").arg(timeMs, 4, 16, QChar('0')).toUpper();
const QString chHex = QString("%1").arg(clientHandle(), 0, 16).toUpper();
QString fullCmd = QString("%1 time=0x%2 index=%3 client_handle=0x%4")
.arg(baseCmd, tsHex, QString::number(index), chHex);
QByteArray payload = fullCmd.toLatin1();
// Redundant sends via UDP: 0ms, 5ms, 10ms, 15ms. The radio dedupes by the
// ASCII `index=N` field, but each datagram needs a UNIQUE VITA-49
// packet_count — FlexLib's NetCWStream.AddTXData increments packet_count
// after each ToBytesTX(), so the four redundant copies arrive with counts
// N, N+1, N+2, N+3. Reusing a single buffer (same packet_count on all
// four) makes the radio's VITA stream layer drop them as duplicates.
QByteArray packet0 = buildNetCwPacket(payload);
QByteArray packet1 = buildNetCwPacket(payload);
QByteArray packet2 = buildNetCwPacket(payload);
QByteArray packet3 = buildNetCwPacket(payload);
const quint64 scheduledMs = cwTraceNowMs();
const QString source = debugSource.isEmpty() ? QStringLiteral("unknown") : debugSource;
if (lcCw().isDebugEnabled()) {
qCDebug(lcCw).noquote().nospace()
<< "CW netcw schedule trace=" << debugTraceId
<< " t=" << scheduledMs << "ms"
<< " sinceSourceMs=" << (debugSourceMs ? static_cast<qint64>(scheduledMs - debugSourceMs) : -1)
<< " source=" << source
<< " stream=0x" << QString::number(m_netCwStreamId, 16).toUpper()
<< " index=" << index
<< " time=0x" << tsHex
<< " cmd=\"" << baseCmd << "\""
<< " payloadBytes=" << payload.size()
<< " packetBytes=" << packet0.size()
<< " udpCopies=4 tcpBackstop=1";
}
auto logUdpSend = [debugTraceId, scheduledMs, source](int copy, int delayMs, int bytes) {
if (!lcCw().isDebugEnabled())
return;
const quint64 now = cwTraceNowMs();
qCDebug(lcCw).noquote().nospace()
<< "CW netcw udp-send trace=" << debugTraceId
<< " t=" << now << "ms"
<< " source=" << source
<< " copy=" << copy
<< " delayMs=" << delayMs
<< " actualDelayMs=" << static_cast<qint64>(now - scheduledMs)
<< " timerSlipMs=" << (static_cast<qint64>(now - scheduledMs) - delayMs)
<< " bytes=" << bytes;
};
QMetaObject::invokeMethod(m_panStream, [this, packet0, logUdpSend]() {
logUdpSend(0, 0, packet0.size());
m_panStream->sendToRadio(packet0);
}, Qt::QueuedConnection);
QTimer::singleShot(5, this, [this, packet1, logUdpSend]() {
QMetaObject::invokeMethod(m_panStream, [this, packet1, logUdpSend]() {
logUdpSend(1, 5, packet1.size());
m_panStream->sendToRadio(packet1);
}, Qt::QueuedConnection);
});
QTimer::singleShot(10, this, [this, packet2, logUdpSend]() {
QMetaObject::invokeMethod(m_panStream, [this, packet2, logUdpSend]() {
logUdpSend(2, 10, packet2.size());
m_panStream->sendToRadio(packet2);
}, Qt::QueuedConnection);
});
QTimer::singleShot(15, this, [this, packet3, logUdpSend]() {
QMetaObject::invokeMethod(m_panStream, [this, packet3, logUdpSend]() {
logUdpSend(3, 15, packet3.size());
m_panStream->sendToRadio(packet3);
}, Qt::QueuedConnection);
});
// FlexLib sends the same decorated netcw command over TCP after the UDP
// copies. With the 16-bit timestamp format above, the radio can dedupe
// by index=N and the TCP path provides a reliable delivery backstop.
sendCmd(fullCmd);
}
void RadioModel::cwAutoTune(int sliceId, bool intermittent)
{
if (intermittent) {
sendCmd(QString("slice auto_tune %1 int=1").arg(sliceId));
} else {
// int=0 stops the autotune engine (FlexLib: isIntermittent=false)
sendCmd(QString("slice auto_tune %1 int=0").arg(sliceId));
}
}
void RadioModel::cwAutoTuneOnce(int sliceId)
{
// One-shot autotune (FlexLib: isIntermittent=null)
sendCmd(QString("slice auto_tune %1").arg(sliceId));
}
void RadioModel::addSlice()
{
if (m_activePanId.isEmpty()) {
qCWarning(lcProtocol) << "RadioModel::addSlice: no panadapter, cannot create slice";
return;
}
// Create a new slice offset from existing slices so VFO flags deconflict.
// Use pan center, but if an existing slice is within 5 kHz, offset by
// 20% of the visible bandwidth.
auto* pan = activePanadapter();
double newFreq = pan ? pan->centerMhz() : 14.1;
const double offsetMhz = (pan ? pan->bandwidthMhz() : 0.2) * 0.2; // 20% of visible BW
for (auto* s : m_slices) {
if (std::abs(s->frequency() - newFreq) < 0.005) { // within 5 kHz
newFreq += offsetMhz;
break;
}
}
const QString freq = QString::number(newFreq, 'f', 6);
const QString cmd = QString("slice create pan=%1 freq=%2").arg(m_activePanId, freq);
qCDebug(lcProtocol) << "RadioModel::addSlice:" << cmd;
sendCmd(cmd, [this](int code, const QString& body) {
if (code != 0) {
qCWarning(lcProtocol) << "RadioModel: slice create failed, code"
<< Qt::hex << code << "body:" << body;
emit sliceCreateFailed(maxSlices(), m_model);
} else {
qCDebug(lcProtocol) << "RadioModel: new slice created, index =" << body;
}
});
}
void RadioModel::addSliceOnPan(const QString& panId)
{
if (panId.isEmpty()) { addSlice(); return; }
auto* pan = panadapter(panId);
double newFreq = pan ? pan->centerMhz() : 14.1;