-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathFlexRadioDriver.cs
More file actions
619 lines (533 loc) · 20.3 KB
/
Copy pathFlexRadioDriver.cs
File metadata and controls
619 lines (533 loc) · 20.3 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
using OscarWatch.Core.Models;
using OscarWatch.Core.Radio;
using Serilog;
namespace OscarWatch.Rig;
/// <summary>
/// FlexRadio SmartSDR driver for full-duplex satellite tracking (Main = RX slice, Sub = TX slice).
/// </summary>
public sealed class FlexRadioDriver : IRigDriver
{
private static readonly ILogger Log = Serilog.Log.ForContext<FlexRadioDriver>();
private readonly FlexSmartSdrClient _client;
private readonly bool _ownsClient;
private RigVfo _currentVfo = RigVfo.Main;
private int _rxSliceIndex = 0;
private int _txSliceIndex = 1;
private bool _satelliteMode;
private long _lastMainHz;
private long _lastSubHz;
private long _lastMainStatusRevision;
private long _lastMainObservedHz;
private bool _hasMainStatusObservation;
private bool _toneOn;
private bool _toneApplied;
private double _toneHz = 67.0;
private RigSettings _antennaPortSettings = new();
public FlexRadioDriver(string host, int port, int catDelayMs = 50)
: this(new FlexSmartSdrClient(host, port, ResolveTimeoutMs(catDelayMs)), ownsClient: true)
{
}
internal FlexRadioDriver(FlexSmartSdrClient client, bool ownsClient = false)
{
_client = client;
_ownsClient = ownsClient;
}
public RigType RigType => RigType.FlexSmartSdr;
public bool IsConnected => _client.IsConnected;
public bool SupportsTracking => true;
public bool SupportsVfoExchange => false;
public bool IsSatelliteModeActive => _satelliteMode;
/// <summary>RX (downlink) slice index after satellite setup.</summary>
public int RxSliceIndex => _rxSliceIndex;
/// <summary>TX (uplink) slice index after satellite setup.</summary>
public int TxSliceIndex => _txSliceIndex;
public void Open() => _client.Open();
public long? ReadFrequencyHz(RigVfo vfo)
{
var slice = SliceFor(vfo);
var cached = CachedFrequencyHz(vfo);
if (!_client.IsConnected)
return cached > 0 ? cached : null;
long? hz;
if (vfo is RigVfo.Main or RigVfo.VfoA)
{
var observation = _client.GetSliceFrequencyObservation(slice);
hz = observation?.FrequencyHz;
if (observation is { } observed)
{
_lastMainStatusRevision = observed.StatusRevision;
_lastMainObservedHz = observed.FrequencyHz;
_hasMainStatusObservation = true;
}
}
else
{
hz = _client.GetSliceFrequencyHz(slice);
}
if (hz is > 0)
{
StoreFrequencyHz(vfo, hz.Value);
return hz;
}
return cached > 0 ? cached : null;
}
public bool SetFrequencyHz(long hz)
{
if (hz <= 0)
return false;
if (!_client.IsConnected)
{
StoreFrequencyHz(_currentVfo, hz);
return true;
}
var isReceive = _currentVfo is RigVfo.Main or RigVfo.VfoA;
var tuned = isReceive && _hasMainStatusObservation
? _client.TuneSliceIfStatusUnchanged(
SliceFor(_currentVfo),
hz,
_lastMainStatusRevision,
_lastMainObservedHz)
: _client.TuneSlice(SliceFor(_currentVfo), hz);
if (tuned)
StoreFrequencyHz(_currentVfo, hz);
return tuned;
}
public void SelectVfo(RigVfo vfo, bool force = false) => _currentVfo = vfo;
public void SetMode(string mode)
{
var smart = FlexModeMapper.ToSmartSdrMode(mode);
if (smart is null || !_client.IsConnected)
return;
var sliceIndex = SliceFor(_currentVfo);
if (!_client.SetSliceMode(sliceIndex, smart))
{
Log.Warning(
"FlexRadio failed to set mode on slice {SliceIndex}: mode={Mode}",
sliceIndex,
smart);
}
}
public void SetSplitOn(bool on)
{
// Full duplex uses two slices; classic split is not used.
}
public void SetSatelliteMode(bool on)
{
if (!_client.IsConnected)
return;
if (!on)
{
var disabled = _client.SetFullDuplex(false);
_satelliteMode = false;
Log.Information("FlexRadio satellite mode disabled; full duplex command succeeded={Succeeded}", disabled);
return;
}
if (!_client.SetFullDuplex(true))
{
_satelliteMode = false;
throw new FlexSatelliteSetupException("SmartSDR did not enable full duplex.");
}
if (!EnsureDuplexSlicesWithRetry())
{
DisableFullDuplexAfterSetupFailure();
throw new FlexSatelliteSetupException("SmartSDR could not establish separate RX and TX slices.");
}
if (!_client.SetSliceTx(_txSliceIndex, true))
{
DisableFullDuplexAfterSetupFailure();
throw new FlexSatelliteSetupException($"SmartSDR did not mark slice {_txSliceIndex} as the TX slice.");
}
_satelliteMode = true;
Log.Information(
"FlexRadio satellite mode enabled; full duplex=true, RX slice={RxSliceIndex}, TX slice={TxSliceIndex}",
_rxSliceIndex,
_txSliceIndex);
}
/// <summary>
/// Queries the radio for available antenna ports (<c>ant list</c>).
/// Returns null if disconnected or the query fails.
/// </summary>
public IReadOnlyList<string>? QueryAntennaList() =>
_client.IsConnected ? _client.QueryAntennaList() : null;
/// <summary>
/// Stores band→port settings used when creating slices and applying antenna ports.
/// </summary>
public void ConfigureAntennaPorts(RigSettings settings) =>
_antennaPortSettings = settings;
/// <summary>
/// Applies configured VHF/UHF RX and TX antenna ports for the current duplex slices.
/// Empty settings leave SmartSDR ports unchanged.
/// </summary>
public void ApplyBandAntennaPorts(RigSettings settings, long downlinkHz, long uplinkHz)
{
_antennaPortSettings = settings;
if (!_client.IsConnected)
return;
var rxAnt = FlexAntennaPortResolver.ResolveRxPort(settings, downlinkHz);
if (rxAnt is not null)
{
if (!_client.SetSliceRxAnt(_rxSliceIndex, rxAnt, out var rxFailure))
{
Log.Warning(
"FlexRadio failed to set RX antenna on slice {SliceIndex}: port={Port}, downlinkHz={DownlinkHz}, detail={Detail}",
_rxSliceIndex,
rxAnt,
downlinkHz,
rxFailure);
}
}
if (!_satelliteMode || uplinkHz <= 0)
return;
var txAnt = FlexAntennaPortResolver.ResolveTxPort(settings, uplinkHz);
if (txAnt is not null && !_client.SetSliceTxAnt(_txSliceIndex, txAnt, out var txFailure))
{
Log.Warning(
"FlexRadio failed to set TX antenna on slice {SliceIndex}: port={Port}, uplinkHz={UplinkHz}, detail={Detail}",
_txSliceIndex,
txAnt,
uplinkHz,
txFailure);
}
}
/// <summary>
/// Binds RX/TX slices to locked VHF/UHF panadapters before initial tune on band changes.
/// </summary>
/// <param name="forceRebind">
/// When true (V/U↔U/V layout flip), recreate even if cached pan IDs look plausible.
/// </param>
public void BindDuplexSlicesToBandPans(long downlinkHz, long uplinkHz, bool forceRebind = false)
{
if (!_client.IsConnected || !_satelliteMode)
return;
_client.ResolveDuplexSliceRoles(ref _rxSliceIndex, ref _txSliceIndex);
const int maxAttempts = 2;
const int retryDelayMs = 100;
for (var attempt = 1; attempt <= maxAttempts; attempt++)
{
if (_client.BindDuplexSlicesToBandPans(
ref _rxSliceIndex,
ref _txSliceIndex,
downlinkHz,
uplinkHz,
_satelliteMode,
forceRebind))
return;
if (attempt < maxAttempts)
{
Log.Debug(
"FlexRadio slice-to-pan bind attempt {Attempt}/{MaxAttempts} failed; retrying",
attempt,
maxAttempts);
Thread.Sleep(retryDelayMs);
}
}
Log.Warning(
"FlexRadio failed to bind duplex slices to band panadapters: downlinkHz={DownlinkHz}, uplinkHz={UplinkHz}, forceRebind={ForceRebind}",
downlinkHz,
uplinkHz,
forceRebind);
}
/// <summary>
/// One-shot: centre each band panadapter (VHF SCU / UHF SCU) after pass init.
/// Uses pan display band, not slice pan association, so U/V after V/U still splits correctly.
/// Continuous Doppler uses autopan=0 so these pans are not yanked again.
/// </summary>
public void CenterBandPanadapters(long downlinkHz, long uplinkHz)
{
if (!_client.IsConnected)
return;
FlexPanBandResolver.ResolveTargetFrequencies(
downlinkHz,
uplinkHz,
_satelliteMode,
out var vhfHz,
out var uhfHz);
var centred = _client.CenterBandPans(downlinkHz, uplinkHz, _satelliteMode);
_client.GetLockedBandPanStreamIds(out var lockedVhf, out var lockedUhf);
if (!centred)
{
Log.Warning(
"FlexRadio failed to centre one or more band panadapters: downlinkHz={DownlinkHz}, uplinkHz={UplinkHz}, vhfPan={VhfPan}, uhfPan={UhfPan}",
downlinkHz,
uplinkHz,
lockedVhf ?? "(none)",
lockedUhf ?? "(none)");
}
else
{
if (vhfHz > 0)
{
Log.Information(
"FlexRadio centred VHF pan {PanStreamId} at {CenterMhz:0.###} MHz",
lockedVhf ?? "(unresolved)",
FlexSmartSdrCodec.HzToMhz(vhfHz));
}
if (_satelliteMode && uhfHz > 0)
{
Log.Information(
"FlexRadio centred UHF pan {PanStreamId} at {CenterMhz:0.###} MHz",
lockedUhf ?? "(unresolved)",
FlexSmartSdrCodec.HzToMhz(uhfHz));
}
}
var rxPan = _client.GetSlicePanStreamId(_rxSliceIndex);
var txPan = _client.GetSlicePanStreamId(_txSliceIndex);
if (!string.IsNullOrWhiteSpace(rxPan)
&& !string.IsNullOrWhiteSpace(txPan)
&& string.Equals(rxPan, txPan, StringComparison.OrdinalIgnoreCase)
&& downlinkHz > 0
&& uplinkHz > 0)
{
Log.Warning(
"FlexRadio RX and TX slices share pan {PanStreamId}; both bands cannot stay on screen until each slice has its own panadapter",
rxPan);
}
}
/// <summary>
/// After bind/tune/centre/modes, confirm live RX/TX layout. Retune and re-apply modes, and if needed
/// clear pan locks and force-rebind, when the radio did not land on the commanded pass.
/// </summary>
public void EnsureDuplexPassFrequencies(
long downlinkHz,
long uplinkHz,
string? expectedRxMode = null,
string? expectedTxMode = null)
{
if (!_client.IsConnected || !_satelliteMode)
return;
_client.ResolveDuplexSliceRoles(ref _rxSliceIndex, ref _txSliceIndex);
if (DuplexFrequenciesVerified(downlinkHz, uplinkHz, out var mismatch, expectedRxMode, expectedTxMode))
return;
Log.Warning(
"FlexRadio pass layout mismatch after init: {Detail}; retuning, recentring, and reapplying modes",
mismatch);
ApplyDuplexLightRepair(downlinkHz, uplinkHz, expectedRxMode, expectedTxMode);
if (DuplexFrequenciesVerified(downlinkHz, uplinkHz, out _, expectedRxMode, expectedTxMode))
{
Log.Information(
"FlexRadio pass layout repaired without rebind: RX={RxHz} Hz, TX={TxHz} Hz",
downlinkHz,
uplinkHz);
return;
}
DuplexFrequenciesVerified(downlinkHz, uplinkHz, out var afterRetune, expectedRxMode, expectedTxMode);
Log.Warning(
"FlexRadio pass layout still wrong after light repair: {Detail}; force-rebinding while preserving band pan locks",
afterRetune);
// Never clear sticky locks while both pans may sit on one band — re-resolve only if VHF+UHF are both live.
_client.TryRelockBandPansFromLiveCentres();
BindDuplexSlicesToBandPans(downlinkHz, uplinkHz, forceRebind: true);
ApplyDuplexLightRepair(downlinkHz, uplinkHz, expectedRxMode, expectedTxMode);
if (DuplexFrequenciesVerified(downlinkHz, uplinkHz, out var stillWrong, expectedRxMode, expectedTxMode))
{
Log.Information(
"FlexRadio pass layout repaired by force rebind: RX={RxHz} Hz, TX={TxHz} Hz",
downlinkHz,
uplinkHz);
}
else
{
Log.Warning(
"FlexRadio pass layout still incorrect after force rebind: {Detail}. If both panadapters are stuck on one band, load a SmartSDR Global Profile that restores separate VHF and UHF pans, then re-select the satellite in OscarWatch.",
stillWrong);
}
}
private bool DuplexFrequenciesVerified(
long downlinkHz,
long uplinkHz,
out string detail,
string? expectedRxMode = null,
string? expectedTxMode = null) =>
_client.VerifyDuplexSliceFrequencies(
_rxSliceIndex,
_txSliceIndex,
downlinkHz,
uplinkHz,
_satelliteMode,
out detail,
expectedRxMode,
expectedTxMode);
private void ApplyDuplexLightRepair(
long downlinkHz,
long uplinkHz,
string? expectedRxMode,
string? expectedTxMode)
{
// Centre pans onto the target bands first, then tune slices, then centre again so a stale
// pan centre cannot leave both displays on one band after a layout flip.
CenterBandPanadapters(downlinkHz, uplinkHz);
RetuneDuplexSlices(downlinkHz, uplinkHz);
CenterBandPanadapters(downlinkHz, uplinkHz);
if (!string.IsNullOrWhiteSpace(expectedRxMode))
_client.SetSliceMode(_rxSliceIndex, expectedRxMode);
if (!string.IsNullOrWhiteSpace(expectedTxMode))
_client.SetSliceMode(_txSliceIndex, expectedTxMode);
if (_satelliteMode && uplinkHz > 0)
_client.SetSliceTx(_txSliceIndex, tx: true);
}
private void RetuneDuplexSlices(long downlinkHz, long uplinkHz)
{
if (downlinkHz > 0)
_client.TuneSlice(_rxSliceIndex, downlinkHz);
if (_satelliteMode && uplinkHz > 0)
_client.TuneSlice(_txSliceIndex, uplinkHz);
}
public void ExchangeVfos()
{
// Slice roles stay RX/TX; front-panel / SmartSDR swap is not mirrored.
(_rxSliceIndex, _txSliceIndex) = (_txSliceIndex, _rxSliceIndex);
(_lastMainHz, _lastSubHz) = (_lastSubHz, _lastMainHz);
_hasMainStatusObservation = false;
}
public void SetToneOn(bool on)
{
_toneOn = on;
ApplyTone();
}
public void SetToneSquelchOn(bool on)
{
// SmartSDR FM encode tone; squelch tone is not separately modelled in v1.
_toneOn = on;
ApplyTone();
}
public void SetToneHz(double hz, bool squelchTone)
{
if (hz > 0)
_toneHz = hz;
_toneOn = true;
ApplyTone();
}
public void Dispose()
{
if (_ownsClient)
_client.Dispose();
}
private void ApplyTone()
{
if (!_client.IsConnected)
return;
if (!_toneOn)
{
if (!_toneApplied)
return;
_toneApplied = false;
}
if (!_client.SetSliceTone(_txSliceIndex, _toneOn, _toneHz))
{
Log.Warning(
"FlexRadio failed to confirm CTCSS on TX slice {SliceIndex}: enabled={Enabled}, toneHz={ToneHz}",
_txSliceIndex,
_toneOn,
_toneHz);
return;
}
if (_toneOn)
_toneApplied = true;
}
private void DisableFullDuplexAfterSetupFailure()
{
_satelliteMode = false;
try
{
_client.SetFullDuplex(false);
}
catch (Exception ex)
{
Log.Debug(ex, "FlexRadio full duplex cleanup after setup failure failed");
}
}
/// <summary>
/// After reconnect SmartSDR sometimes reports zero slices briefly; create/status can lag.
/// Retry a few times before failing pass init (matches field recovery on immediate re-init).
/// </summary>
private bool EnsureDuplexSlicesWithRetry()
{
const int maxAttempts = 5;
const int retryDelayMs = 100;
for (var attempt = 1; attempt <= maxAttempts; attempt++)
{
if (TryEnsureDuplexSlices())
return true;
if (attempt < maxAttempts)
{
Log.Debug(
"FlexRadio duplex slice setup attempt {Attempt}/{MaxAttempts} failed; retrying",
attempt,
maxAttempts);
Thread.Sleep(retryDelayMs);
}
}
return false;
}
private bool TryEnsureDuplexSlices()
{
var slices = _client.GetInUseSlices();
var tx = slices.FirstOrDefault(s => s.IsTransmit);
if (slices.Count >= 2)
{
if (tx is not null)
{
_txSliceIndex = tx.Index;
_rxSliceIndex = slices.FirstOrDefault(s => s.Index != tx.Index)?.Index ?? (tx.Index == 0 ? 1 : 0);
}
else
{
_rxSliceIndex = slices[0].Index;
_txSliceIndex = slices[1].Index;
}
return _rxSliceIndex != _txSliceIndex;
}
if (slices.Count == 1)
{
_rxSliceIndex = slices[0].Index;
var createHz = _lastSubHz > 0 ? _lastSubHz : 435_000_000;
var created = _client.CreateSlice(
createHz,
"USB",
FlexAntennaPortResolver.ResolveTxPort(_antennaPortSettings, createHz));
if (created is null || created.Value == _rxSliceIndex)
return false;
_txSliceIndex = created.Value;
return _client.GetInUseSlices().Select(s => s.Index).Distinct().Count() >= 2;
}
var rxCreateHz = _lastMainHz > 0 ? _lastMainHz : 145_900_000;
var txCreateHz = _lastSubHz > 0 ? _lastSubHz : 435_000_000;
var rxCreated = _client.CreateSlice(
rxCreateHz,
"USB",
FlexAntennaPortResolver.ResolveRxPort(_antennaPortSettings, rxCreateHz));
var txCreated = _client.CreateSlice(
txCreateHz,
"USB",
FlexAntennaPortResolver.ResolveTxPort(_antennaPortSettings, txCreateHz));
if (rxCreated is null || txCreated is null || rxCreated.Value == txCreated.Value)
return false;
_rxSliceIndex = rxCreated.Value;
_txSliceIndex = txCreated.Value;
return _client.GetInUseSlices().Select(s => s.Index).Distinct().Count() >= 2;
}
private int SliceFor(RigVfo vfo) =>
vfo is RigVfo.Sub or RigVfo.VfoB ? _txSliceIndex : _rxSliceIndex;
private long CachedFrequencyHz(RigVfo vfo) =>
vfo is RigVfo.Sub or RigVfo.VfoB ? _lastSubHz : _lastMainHz;
private void StoreFrequencyHz(RigVfo vfo, long hz)
{
if (vfo is RigVfo.Sub or RigVfo.VfoB)
_lastSubHz = hz;
else
_lastMainHz = hz;
}
/// <summary>
/// SmartSDR command wait budget. Floor matches <see cref="FlexSmartSdrClient"/>'s 2s default so
/// Open's multi-subscribe handshake is not starved when CatDelayMs is the Doppler default (50).
/// </summary>
private static int ResolveTimeoutMs(int catDelayMs) =>
Math.Max(2000, Math.Max(0, catDelayMs) * 20);
}
public sealed class FlexSatelliteSetupException : InvalidOperationException
{
public FlexSatelliteSetupException(string message)
: base(message)
{
}
}