forked from w5xd/Digi-Rite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainForm.cs
2467 lines (2274 loc) · 107 KB
/
MainForm.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace DigiRite
{
public enum ExchangeTypes { GRID_SQUARE, DB_REPORT, ARRL_FIELD_DAY, ARRL_RTTY, GRID_SQUARE_PLUS_REPORT};
public enum VfoControl { VFO_NONE, VFO_SPLIT, VFO_SHIFT };
public partial class MainForm : Form, QsoQueue.IQsoQueueCallBacks, Qso2MessageExchange.IQsoQueueCallBacks
{
public static String[] DefaultAcknowledgements = { "73", "RR73", "RRR" };
public enum DigiMode { FT8, FT4 };
// These are the objects needed to receive and send FT8.
private XDft.Demodulator demodulator;
private XDft.WsjtSharedMemory wsjtSharedMem;
private XDft.WsjtExe wsjtExe;
private XD.WaveDevicePlayer waveDevicePlayer;
private XD.WaveDeviceTx deviceTx = null; // to modulate
private XDft.GeneratorContext genContext;
private DigiMode digiMode = DigiMode.FT8;
private RcvrForm rxForm;
private String myCall;
private String myBaseCall; // in case myCall is nonstandard
private int instanceNumber;
private String instanceRegKeyName;
private uint RxInDevice = 0;
private uint TxOutDevice = 0;
private bool SetupMaySelectDevices = true;
private bool SetupMaySelectLR = true;
private IQsoQueue qsoQueue;
private LogFile logFile;
private LogFile conversationLogFile;
private bool sendInProgress = false;
private AltMessageShortcuts altMessageShortcuts;
// what we put in listToMe and cqlist
private CallPresentation cqListOdd;
private CallPresentation cqListEven;
private CallPresentation toMe;
private QsosPanel qsosPanel;
private VfoControl controlVFOsplit = VfoControl.VFO_NONE;
private bool forceRigUsb = false;
private int TxHighFreqLimit = 0;
#if DEBUG
List<string> simulatorLines;
int simulatorTimeOrigin = -1;
DateTime simulatorStart;
int simulatorNext = 0;
#endif
public MainForm(int instanceNumber)
{
this.instanceNumber = instanceNumber;
instanceRegKeyName = String.Format("Software\\W5XD\\WriteLog\\DigiRite-{0}", instanceNumber);
InitializeComponent();
labelPtt.Text = "";
}
#region Logger customization
private DigiRiteLogger.IDigiRiteLogger logger;
// currentBand is only used to distinguish messages from a CALL
// that are part of different QSOs because they are on a different band.
// Even that distinction rarely happens because DigiRite typically
// discards old messages from old QSOs over time. But if you happen to
// work a CALL on one band, changes bands, and immediately work the same
// CALL, you want currentBand to be different when you change bands, else
// the new messages from CALL will be assigned to the QSO on the old band.
private short currentBand = 0;
public void SetWlEntry(object e)
{ // WriteLog is the only logger that calls here.
var wl = new DigiRiteLogger.WriteLog(instanceNumber);
labelPtt.Text = wl.SetWlEntry(e);
logger = wl;
}
#endregion
public static uint StringToIndex(string MySetting, List<string> available)
{
uint ret = 0;
string cmp = MySetting.ToUpper();
for (ret = 0; ret < available.Count; ret++)
{
if (available[(int)ret].ToUpper().Contains(cmp))
break;
}
return ret;
}
private string LogFilePath { get { return wsjtExe.AppDirectoryPath + "DigiRite.log"; } }
const double AUDIO_SLIDER_SCALE = 12;
private bool InitSoundInAndOut()
{
// The objects implement IDisposable. Failing to
// dispose of one after quitting using it
// leaves its Windows resources
// allocated until garbage collection.
rxForm.demodParams = null;
timerFt8Clock.Enabled = false;
timerSpectrum.Enabled = false;
timerCleanup.Enabled = false;
if (null != demodulator)
demodulator.Dispose();
demodulator = null;
if (null != wsjtSharedMem)
wsjtSharedMem.Dispose();
wsjtSharedMem = null;
if (null != wsjtExe)
wsjtExe.Dispose();
wsjtExe = null;
if (null != waveDevicePlayer)
waveDevicePlayer.Dispose();
waveDevicePlayer = null;
if (null != deviceTx)
deviceTx.Dispose();
deviceTx = null;
if (null != logFile)
logFile.Dispose();
logFile = null;
if (null != conversationLogFile)
conversationLogFile.Dispose();
conversationLogFile = null;
// The demodulator invokes the wsjtx decoder
demodulator = new XDft.Demodulator();
// the names of its parameters are verbatim from the wsjt-x source code.
// Don't ask this author what they mean.
demodulator.nftx = 1500;
demodulator.nfqso = 1500;
demodulator.nfa = 200;
demodulator.nfb = 6000;
if (Properties.Settings.Default.Decode_ndepth < 1)
Properties.Settings.Default.Decode_ndepth = 1;
if (Properties.Settings.Default.Decode_ndepth > 3)
Properties.Settings.Default.Decode_ndepth = 1;
demodulator.ndepth = Properties.Settings.Default.Decode_ndepth;
demodulator.lft8apon = Properties.Settings.Default.Decode_lft8apon;
demodulator.nQSOProgress = 5;
demodulator.digiMode = digiMode == DigiMode.FT8 ? XDft.DigiMode.DIGI_FT8 : XDft.DigiMode.DIGI_FT4;
// When the decoder finds an FT8 message, it calls us back...
// ...on a foreign thread. Call BeginInvoke to get back on this one. See below.
demodulator.DemodulatorResultCallback = new XDft.DemodResult(Decoded);
string sharedMemoryKey = "DigiRite-" + instanceNumber.ToString();
wsjtSharedMem = new XDft.WsjtSharedMemory(sharedMemoryKey, false);
if (!wsjtSharedMem.CreateWsjtSharedMem())
{
MessageBox.Show("Failed to create Shared Memory from " + sharedMemoryKey);
return false;
}
// The subprocess itself is managed by the XDft
wsjtExe = new XDft.WsjtExe();
wsjtExe.AppDataName = "DigiRite-" + instanceNumber.ToString();
if (!wsjtExe.CreateWsjtProcess(wsjtSharedMem))
{
MessageBox.Show("Failed to launch wsjt exe");
demodulator.Dispose();
wsjtExe.Dispose();
wsjtExe = null;
wsjtSharedMem.Dispose();
wsjtSharedMem = null;
demodulator = null;
return false;
}
logFile = new LogFile(LogFilePath);
String conversationLog = wsjtExe.AppDirectoryPath + "Conversation.log";
conversationLogFile = new LogFile(conversationLog, false);
rxForm.logFile = logFile;
uint channel = (uint)Properties.Settings.Default["AudioInputChannel_" + instanceNumber.ToString()];
if (waveDevicePlayer != null)
waveDevicePlayer.Dispose();
waveDevicePlayer = new XD.WaveDevicePlayer();
if (!waveDevicePlayer.Open(RxInDevice, channel, demodulator.GetRealTimeRxSink()))
{
MessageBox.Show("Failed to open wave input");
waveDevicePlayer.Dispose();
waveDevicePlayer = null;
return false;
}
else
{
rxForm.demodParams = demodulator;
waveDevicePlayer.Resume();
rxForm.Player = waveDevicePlayer;
}
deviceTx = new XD.WaveDeviceTx();
channel = (uint)Properties.Settings.Default["AudioOutputChannel_" + instanceNumber.ToString()];
if (!deviceTx.Open(TxOutDevice, channel))
{
MessageBox.Show("Failed to open wave output");
deviceTx.Dispose();
deviceTx = null;
return false;
}
deviceTx.SoundSyncCallback = new XD.SoundBeginEnd(AudioBeginEnd);
float gain = deviceTx.Gain;
bool gainOK = gain >= 0;
labelTxValue.Text = "";
if (gainOK)
{ // not sure why the windows volume slider don't
// really work with linear commands, but here we go:
double g = trackBarTxGain.Maximum + Math.Log(gain) * AUDIO_SLIDER_SCALE / Math.Log(2);
int v = (int)g;
if (v < trackBarTxGain.Minimum)
v = trackBarTxGain.Minimum;
trackBarTxGain.Value = v;
labelTxValue.Text = trackBarTxGain.Value.ToString();
}
trackBarTxGain.Enabled = gainOK;
timerFt8Clock.Enabled = true;
timerSpectrum.Enabled = true;
timerCleanup.Enabled = true;
return true;
}
#region received message interactions
private List<XDpack77.Pack77Message.ReceivedMessage> recentMessages =
new List<XDpack77.Pack77Message.ReceivedMessage>();
private DateTime watchDogTime; // the dog sleeps only for so long
private const int MAX_NUMBER_OF_PACK77_CHARS = 36; // truncate decoder strings
private string DECODE_SEPARATOR = "~ ";
private char MESSAGE_SEPARATOR;
private void OnReceived(String s, int cycle)
{ // When the FT8 decoder is invoked, it may find
// multiple signals in the stream. Each is notified by
// a separate string here. An empty string is sent
// at the end of the decoding session.
if (!String.IsNullOrEmpty(s))
{
OneAtATime(new OneAtATimeDel(() =>
{
int v = s.IndexOf(DECODE_SEPARATOR);
// "020000 -9 0.4 500 ~ CQ RU W5XD EM10 "
if (v >= 0)
{
logFile.SendToLog(s);
string msg = s.Substring(v + 3);
if (msg.Length > MAX_NUMBER_OF_PACK77_CHARS)
msg = msg.Substring(0, MAX_NUMBER_OF_PACK77_CHARS);
int i3 = 0; int n3 = 0;
bool[] c77 = null;
XDft.Generator.pack77(msg, ref i3, ref n3, ref c77);
// kludge...see if pack failed cuz of hashed call
// This works around a bug in wsjtx's pack77 routine.
// If/when that bug is fixed, this code may be removed
if ((i3 == 0) && (n3 == 0))
{ // free text...see if removing <> makes it parse
string changedMessage = msg;
bool changed = false;
for (; ; )
{
int idx = changedMessage.IndexOfAny(new char[] { '<', '>' });
if (idx >= 0)
{
changed = true;
changedMessage = changedMessage.Substring(0, idx)
+ changedMessage.Substring(idx + 1);
}
else
break;
}
if (changed)
XDft.Generator.pack77(changedMessage, ref i3, ref n3, ref c77);
// END kludge.
}
// have a look at the packing type. i3 and n3
XDpack77.Pack77Message.ReceivedMessage rm =
XDpack77.Pack77Message.ReceivedMessage.CreateFromReceived(i3, n3, s.Substring(0, v), msg, cycle, MESSAGE_SEPARATOR, ft4MsecOffset);
if (rm == null)
return; // FIXME. some messages we can't parse
// recentMessages retains only matching TimeTag's
if (recentMessages.Any() && recentMessages.First().TimeTag != rm.TimeTag)
recentMessages.Clear();
// discard message decodes that we already have
foreach (var m in recentMessages)
if (m.Match(rm)) return;
rxForm.OnReceived(rm);
recentMessages.Add(rm);
// certain kinds of messages are promoted to the checkbox lists
XDpack77.Pack77Message.ToFromCall toFromCall = rm.Pack77Message as XDpack77.Pack77Message.ToFromCall;
String toCall = toFromCall?.ToCall;
bool directlyToMe = (toCall != null) && ((toCall == myCall) || (toCall == myBaseCall));
if (directlyToMe)
watchDogTime = DateTime.UtcNow;
short mult = 0;
bool dupe = false;
String fromCall = toFromCall?.FromCall;
RecentMessage recentMessage;
if (fromCall != null && null != logger)
{ // dupe check if we can
logger.CheckDupeAndMult(fromCall, digiMode == DigiMode.FT8 ? "FT8" : "FT4", rm.Pack77Message, out dupe, out mult);
}
recentMessage = new RecentMessage(rm, dupe, mult > 0);
bool isConversation = false;
string callQsled = (rm.Pack77Message as XDpack77.Pack77Message.QSL)?.CallQSLed;
if (!String.IsNullOrEmpty(toCall))
qsoQueue.MessageForMycall(recentMessage, directlyToMe,
callQsled, currentBand,
checkBoxRespondAny.Checked && !dupe,
new IsConversationMessage((origin) =>
{ // qsoQueue liked this message. log it
isConversation = true;
string toLog = s.Substring(0, v + 3) + msg;
listBoxConversation.Items.Add(new ListBoxConversationItem(toLog, origin));
conversationLogFile.SendToLog(toLog);
ScrollListBoxToBottom(listBoxConversation);
}));
if (!isConversation)
{ // nobody above claimed this message
if (directlyToMe)
toMe.Add(new RecentMessage(rm, dupe, mult > 0), (CheckState x) => { return true; });
else if ((fromCall != null) &&
!String.Equals(fromCall, myCall) && // decoder is hearing our own
!String.Equals(fromCall, myBaseCall) && // transmissions
String.Equals("ALL", callQsled))
{
CallPresentation cqList = (cycle & 1) == 0 ? cqListEven : cqListOdd;
cqList.Add(recentMessage, (CheckState cqOnly) => {
// enable the checkbox if: its a CQ, or if CheckState is Unchecked
if (cqOnly == CheckState.Unchecked) return true; // everything shows in this mode
// else if its not a CQ , return false
else return null != toCall && toCall.Length >= 2 && toCall.Substring(0, 2) == "CQ"; }
);
}
}
}
}));
}
else
{
if (digiMode == DigiMode.FT4)
{
ft4DecodeOffsetIdx += 1;
if (ft4DecodeOffsetIdx < ft4DecodeOffsetMsec.Length)
{
ft4MsecOffset = 1e-3f * (float)((int)ft4DecodeOffsetMsec[ft4DecodeOffsetIdx] - (int)FT4_DECODER_CENTER_OFFSET_MSEC);
bool started = demodulator.DecodeAgain(wsjtExe, cycleNumber, ft4DecodeOffsetMsec[ft4DecodeOffsetIdx]);
}
}
}
}
private void ScrollListBoxToBottom(ListBox lb)
{
int visibleItems = lb.ClientSize.Height / lb.ItemHeight;
lb.TopIndex = Math.Max(1 + lb.Items.Count - visibleItems, 0);
}
#endregion
#region transmit management
private int MAX_MESSAGES_PER_CYCLE { get { return (int)numericUpDownStreams.Value; } }
// empirically determined to "center" in the time slot
private const int FT8_TX_AFTER_ZERO_MSEC = 210;
private const int FT4_TX_AFTER_ZERO_MSEC = 210;
private const ushort FT4_MULTIPLE_DECODE_OFFSET_MSEC = 400;
private const int FT4_MULTIPLE_DECODE_COUNT = 1; // don't bother with sliding decode window with wsjtx-2.1.0-rc5
private const short DEFAULT_DECODER_LOOKBACK_MSEC = 100;
private const ushort FT4_DECODER_CENTER_OFFSET_MSEC = (FT4_MULTIPLE_DECODE_OFFSET_MSEC * (FT4_MULTIPLE_DECODE_COUNT / 2));
private int UserVfoSplitToPtt = 550;
private int UserPttToSound = 20;
private int VfoSetToTxMsec = 550;
private int FT_CYCLE_TENTHS = 150;
private int FT_GAP_HZ = 60;
private const int MAX_MULTI_STREAM_INCREMENT = 3;
private void AfterNmsec(Action d, int msec)
{
var timer = new Timer { Interval = msec };
timer.Tick += new EventHandler((o, e) =>
{
timer.Enabled = false;
d();
timer.Dispose();
});
timer.Enabled = true;
}
private delegate void GenMessage(string msg, ref string msgSent, ref int[] itone, ref bool[] ftbits);
private GenMessage genMessage;
private bool[] transmittedForQSOLastCycle = new bool[2];
private delegate DateTime GetNowTime();
private void transmitAtZero(bool allowLate = false, GetNowTime getNowTime = null)
{ // right now we're at zero second in the cycle.
if ((digiMode == DigiMode.FT4) && allowLate)
return;
if (null == genMessage)
return;
DateTime toSend = getNowTime == null ? DateTime.UtcNow : getNowTime();
int nowTenths = toSend.Second * 10 + toSend.Millisecond / 100;
int cyclePosTenths = nowTenths % FT_CYCLE_TENTHS;
bool nowOdd = ((nowTenths / FT_CYCLE_TENTHS) & 1) != 0;
int seconds = nowTenths;
seconds /= FT_CYCLE_TENTHS;
seconds *= FT_CYCLE_TENTHS; // round back to nearest
seconds /= TENTHS_IN_SECOND;
int lastCycleIndex = nowOdd ? 0 : 1;
// can't transmit two consecutive cycles, one odd and one even
bool onUserSelectedCycle = nowOdd == radioButtonOdd.Checked;
if ((transmittedForQSOLastCycle[lastCycleIndex])
&& !onUserSelectedCycle)
return;
List<QueuedToSendListItem> toSendList = new List<QueuedToSendListItem>();
// scan the checkboxes and decide what to send
if (checkBoxManualEntry.Checked && onUserSelectedCycle)
{ // the manual entry is not associated with a QSO
String ts = textBoxMessageEdit.Text.ToUpper();
if (!String.IsNullOrEmpty(ts))
{ // if there is typed in text, send it
checkBoxManualEntry.Checked = false;
toSendList.Add(new QueuedToSendListItem(ts, null));
}
}
for (int i = 0; i < listBoxAlternatives.Items.Count; i++)
{ // alternative messages are next on priority list after manual
if (toSendList.Count >= MAX_MESSAGES_PER_CYCLE)
break;
if (listBoxAlternatives.GetItemChecked(i))
{
QueuedToSendListItem li = listBoxAlternatives.Items[i] as QueuedToSendListItem;
bool sendOdd = ((li.q.Message.CycleNumber + 1) & 1) != 0;
if (sendOdd == nowOdd)
{
toSendList.Add(li);
listBoxAlternatives.SetItemChecked(i, false);
li.q.OnSentAlternativeMessage();
}
break;
}
}
// double list search is to maintain the priority order in listBoxInProgress.
// the order things appear in checkedListBoxToSend is irrelevant.
List<QueuedToSendListItem> inToSend = new List<QueuedToSendListItem>();
var inProgress = qsosPanel.QsosInProgress;
for (int i = 0; i < inProgress.Count; i++)
{ // first entries are highest priority
QsoInProgress q = inProgress[i];
if (null == q)
continue; // manual entry goes this way
if (!q.Active)
continue;
bool sendOdd = ((q.Message.CycleNumber + 1) & 1) != 0;
if (sendOdd != nowOdd)
continue; // can't send this one cuz we're on wrong cycle
for (int j = 0; j < checkedlbNextToSend.Items.Count; j++)
{
if (!checkedlbNextToSend.GetItemChecked(j))
continue; // present, but marked to skip
QueuedToSendListItem qli = checkedlbNextToSend.Items[j] as QueuedToSendListItem;
if ((null != qli) && Object.ReferenceEquals(qli.q, q))
inToSend.Add(qli);
}
}
foreach (QueuedToSendListItem qli in inToSend)
{
if (toSendList.Count >= MAX_MESSAGES_PER_CYCLE)
break;
checkedlbNextToSend.Items.Remove(qli);
if (toSendList.Any((qalready) => {
if (null != qalready && null != qalready.q && null != qli.q)
return String.Equals(qli.q.HisCall, qalready.q.HisCall);
return false; }
))
continue; // already a send to this callsign. don't allow another
toSendList.Add(qli);
}
bool anyToSend = toSendList.Any();
int thisCycleIndex = nowOdd ? 1 : 0;
transmittedForQSOLastCycle[thisCycleIndex] = anyToSend;
int cqMode = comboBoxCQ.SelectedIndex;
if (onUserSelectedCycle && toSendList.Count < MAX_MESSAGES_PER_CYCLE &&
((cqMode == 1 && !toSendList.Any()) || cqMode == 2))
{ // only CQ if we have nothing else to send
string cq = "CQ";
/* 77-bit pack is special w.r.t. CQ. can't sent directed CQ
** with call that won't fit in 28 of those bits. */
bool fullcallok = (myBaseCall == myCall);
if (fullcallok)
cq = Properties.Settings.Default.CQmessage;
cq += " " + myCall;
if (fullcallok)
cq += " " + MyGrid4;
toSendList.Add(new QueuedToSendListItem(cq, null));
if (!checkBoxAutoXmit.Checked)
comboBoxCQ.SelectedIndex = 0;
}
List<XDft.Tone> itonesToSend = new List<XDft.Tone>();
List<int> freqsUsed = new List<int>();
int freqRange = FT_GAP_HZ + 1;
int freqIncrement = freqRange + 1;
bool doingMultiStream = toSendList.Count > 1;
foreach (var item in toSendList)
{
QsoInProgress q = item.q;
int freq = TxFrequency;
if (null != q)
{
uint assigned = q.TransmitFrequency;
if (assigned != 0)
{
freq = (int)assigned;
if (doingMultiStream)
{
int fdiff = freq - TxFrequency;
if (fdiff < 0)
fdiff = -fdiff;
if (fdiff > freqIncrement * MAX_MULTI_STREAM_INCREMENT)
freq = TxFrequency; // don't allow multi-streaming that far apart
}
}
}
// prohibit overlapping send frequencies
for (int i = 0; i < freqsUsed.Count;)
{
int f = freqsUsed[i];
if ((freq <= f + freqRange) && (freq >= f - freqRange))
{ // overlaps
freq += freqIncrement;
i = 0;
if (freqIncrement > 0)
freqIncrement = -freqIncrement;
else
{
freqIncrement = -freqIncrement;
freqIncrement += freqRange + 1;
}
}
else
i++;
}
if ((null != q) && q.TransmitFrequency != (uint)freq)
{ // always transmit to this guy on one frequency
q.TransmitFrequency = (uint)freq;
}
freqsUsed.Add(freq);
String asSent = null;
int[] itones = null;
bool[] ftbits = null;
genMessage(item.MessageText, ref asSent, ref itones, ref ftbits);
const float RELATIVE_POWER_THIS_QSO = 1.0f;
itonesToSend.Add(new XDft.Tone(itones, RELATIVE_POWER_THIS_QSO, freq, 0));
string conversationItem = String.Format("{2:00}{3:00}{4:00} transmit {1,4} {0}",
asSent,
freq, toSend.Hour, toSend.Minute, seconds);
listBoxConversation.Items.Add(new ListBoxConversationItem(conversationItem, Conversation.Origin.TRANSMIT));
conversationLogFile.SendToLog(conversationItem);
ScrollListBoxToBottom(listBoxConversation);
logFile.SendToLog("TX: " + item.MessageText);
asSent = asSent.Trim();
if (asSent != item.MessageText)
logFile.SendToLog("TX error sent \"" + asSent + "\" instead of \"" + item.MessageText + "\"");
}
const int MAX_CONVERSATION_LISTBOX_ITEMS = 1000;
if (listBoxConversation.Items.Count >= MAX_CONVERSATION_LISTBOX_ITEMS)
{
while (listBoxConversation.Items.Count >= MAX_CONVERSATION_LISTBOX_ITEMS - 100)
listBoxConversation.Items.RemoveAt(0);
ScrollListBoxToBottom(listBoxConversation);
}
const int ALLOW_LATE_MSEC = 1800; // ft8 decoder only allows so much lateness.This is OK unless our clock is slow.
if (itonesToSend.Any())
{
SetTxCycle(nowOdd ? 1 : 0);
deviceTx.TransmitCycle = XD.Transmit_Cycle.PLAY_NOW;
if (itonesToSend.Count == 1)
{ // single set of tones is sent slightly differently than multiple
int[] itones = itonesToSend[0].itone;
if (allowLate)
{
if (cyclePosTenths > 0)
{
int msecToTruncate = toSend.Millisecond + 100 * cyclePosTenths; // how late we are
msecToTruncate -= ALLOW_LATE_MSEC; // full itones don't last a full 15 seconds
int itonesToLose = msecToTruncate / 160;
if (itonesToLose > 0)
{
int[] truncated = new int[itones.Length - itonesToLose];
Array.Copy(itones, itonesToLose, truncated, 0, truncated.Length);
itones = truncated;
}
}
}
int freq = itonesToSend[0].frequency;
freq = RigVfoSplitForTx(freq, freq + FT_GAP_HZ);
sendInProgress = true;
AfterNmsec(new Action(() =>
XDft.Generator.Play(genContext, itones,
freq, deviceTx.GetRealTimeAudioSink())), VfoSetToTxMsec);
}
else
{ // multiple to send
int minFreq = 99999;
int maxFreq = 0;
foreach (var itones in itonesToSend)
{
if (itones.frequency > maxFreq)
maxFreq = itones.frequency;
if (itones.frequency < minFreq)
minFreq = itones.frequency;
}
int deltaFreq = 0;
if (minFreq < rxForm.MinDecodeFrequency)
deltaFreq = rxForm.MinDecodeFrequency - minFreq;
else if (maxFreq > rxForm.MaxDecodeFrequency + FT_GAP_HZ)
deltaFreq = rxForm.MaxDecodeFrequency + FT_GAP_HZ - maxFreq; // negative
List<XDft.Tone> tones = new List<XDft.Tone>();
foreach (var itones in itonesToSend)
{
int[] nextTones = itones.itone;
if (allowLate)
{
if (cyclePosTenths > 0)
{
int msecToTruncate = toSend.Millisecond + 100 * cyclePosTenths; // how late we are
msecToTruncate -= ALLOW_LATE_MSEC; // full itones don't last a full 15 seconds
int itonesToLose = msecToTruncate / 160;
if (itonesToLose > 0)
{
int[] truncated = new int[nextTones.Length - itonesToLose];
Array.Copy(nextTones, itonesToLose, truncated, 0, truncated.Length);
nextTones = truncated;
}
}
}
XDft.Tone thisSignal = new XDft.Tone(nextTones, 1.0f, itones.frequency + deltaFreq, 0);
tones.Add(thisSignal);
}
RigVfoSplitForTx(minFreq, maxFreq + FT_GAP_HZ, tones);
sendInProgress = true;
AfterNmsec(new Action(() =>
XDft.Generator.Play(genContext, tones.ToArray(), deviceTx.GetRealTimeAudioSink())), VfoSetToTxMsec);
}
}
// clear out checkedlbNextToSend of anything from a QSO no longer in QSO(s) in Progress
for (int j = 0; j < checkedlbNextToSend.Items.Count;)
{
QueuedToSendListItem qli = checkedlbNextToSend.Items[j] as QueuedToSendListItem;
QsoInProgress qp;
if (null != qli && (null != (qp = qli.q)) && inProgress.Any((q) => Object.ReferenceEquals(q, qp) && q.Active))
{ // if the QSO remains active in progress, but still in this list, it didn't get sent,
// mark it unchecked so user can see that.
checkedlbNextToSend.SetItemChecked(j, false);
j += 1;
}
else
checkedlbNextToSend.Items.RemoveAt(j);
}
foreach (var item in toSendList)
{
var cb = item.MessageSent;
if (null != cb)
cb();
}
}
delegate void VfoOnTxEnd();
private VfoOnTxEnd vfoOnTxEnd;
private int RigVfoSplitForTx(int minAudioTx, int maxAudioTx, List<XDft.Tone> tones = null)
{
if (logger == null)
return minAudioTx; // can't do rig control
logger.SetTransmitFocus();
if (controlVFOsplit == VfoControl.VFO_NONE)
return minAudioTx;
bool split;
double txKHz; double rxKHz;
logger.GetRigFrequency(out rxKHz, out txKHz, out split);
// want all outputs below TxHighFreqLimit
// ...and, more importantly, above half that.
int minFreq = TxHighFreqLimit / 2;
int maxFreq = TxHighFreqLimit;
int offset = 0; // try to offset
if (minAudioTx < minFreq)
{
offset = minFreq - minAudioTx; // positive. always
offset /= 100;
offset += 1;
offset *= 100;
}
else if (maxAudioTx > maxFreq)
{
offset = maxFreq - maxAudioTx; // negative
offset /= 100;
offset -= 1;
offset *= 100;
}
// proposed split in offset
if (((maxAudioTx - minAudioTx) >= (maxFreq - minFreq))
|| (offset == 0))
{ //un-split the rig if the needed range is beyond
// the setup parameters, or no offset is needed
if (split)
logger.SetRigFrequency(rxKHz, rxKHz, false);
return minAudioTx;
}
bool rigIsAlreadyOk = false; // check if the rig has an acceptable split already
if (split)
{
int currentOffset = (int)(1000 * (rxKHz - txKHz));
if ((minAudioTx + currentOffset >= minFreq) &&
maxAudioTx + currentOffset <= maxFreq)
{ // the rig's state is OK already
offset = currentOffset;
rigIsAlreadyOk = // OK only if we're really supposed to be in split mode
controlVFOsplit != VfoControl.VFO_SHIFT;
}
}
// offset is what we'll set
if (!rigIsAlreadyOk)
{
double rxDuringTx = rxKHz;
double txDuringTx = rxKHz - .001f * offset;
if (controlVFOsplit == VfoControl.VFO_SPLIT)
logger.SetRigFrequency(rxDuringTx, txDuringTx, true);
else if (controlVFOsplit == VfoControl.VFO_SHIFT)
{
rxDuringTx = txDuringTx;
logger.SetRigFrequency(rxDuringTx, txDuringTx, false);
vfoOnTxEnd = () =>
{
logger.SetRigFrequency(rxKHz, rxKHz, false);
};
}
}
if (null != tones)
foreach (var t in tones)
t.frequency += offset;
return minAudioTx + offset;
}
private void RigVfoSplitForTxOff()
{
if (null != vfoOnTxEnd)
vfoOnTxEnd();
vfoOnTxEnd = null; // only run it once
}
private void SetTxCycle(int cycle)
{
if ((cycle & 1) == 0)
radioButtonEven.Checked = true;
else
radioButtonOdd.Checked = true;
}
private void InitiateQsoFromMessage(RecentMessage rm, bool onHisFrequency)
{
if (!qsoQueue.InitiateQso(rm, currentBand, onHisFrequency,
() =>
{
string s = rm.Message.ToString();
// log the message
listBoxConversation.Items.Add(new ListBoxConversationItem(s, Conversation.Origin.INITIATE));
conversationLogFile.SendToLog(s);
ScrollListBoxToBottom(listBoxConversation);
})
)
return;
// turn its check box ON since this is an interactive click
for (int i = 0; i < checkedlbNextToSend.Items.Count; i++)
{
QueuedToSendListItem qli = checkedlbNextToSend.Items[i] as QueuedToSendListItem;
if (null != qli)
{
if (Object.ReferenceEquals(qli.q.Message, rm.Message))
{
checkedlbNextToSend.SetItemChecked(i, true);
break;
}
}
}
RxFrequency = (int)rm.Message.Hz;
watchDogTime = DateTime.UtcNow;
if (!sendInProgress && (
(rm.Message.CycleNumber & 1) != (cycleNumber & 1))
&& intervalTenths <= START_LATE_MESSAGES_THROUGH_TENTHS)
{ // start late if we can
transmitAtZero(true);
}
}
int MAX_UNANSWERED_MINUTES = 5;
#endregion
#region IQsoQueueCallBacks
private const string BracketFormat = "<{0}>";
private bool needBrackets(string call)
{
int n22=0;
return XDft.Generator.pack28(call, ref n22);
}
public string GetExchangeMessage(QsoInProgress q, bool addAck)
{
var excSet = Properties.Settings.Default.ContestExchange;
return GetExchangeMessage(q, addAck, (ExchangeTypes)excSet);
}
public string MyGrid4 {
get {
string ret = Properties.Settings.Default.MyGrid;
if (ret.Length > 4)
ret = ret.Substring(0, 4);
return ret;
}
}
public string GetExchangeMessage(QsoInProgress q, bool addAck, ExchangeTypes excSet)
{
string hiscall = q.HisCall;
bool hiscallNeedsBrackets = needBrackets(hiscall);
string mycall = myCall;
bool mycallNeedsBrackets = !String.Equals(myCall, myBaseCall);
// 77-bit pack allows only one callsign to be bracketed.
if (hiscallNeedsBrackets && mycallNeedsBrackets)
{
// reduce his call to his base cuz both cannot be hashed
XDft.Generator.checkCall(hiscall, ref hiscall);
mycall = String.Format(BracketFormat, myCall);
}
else if (hiscallNeedsBrackets)
hiscall = String.Format(BracketFormat, hiscall);
else if (mycallNeedsBrackets)
mycall = String.Format(BracketFormat, mycall);
if (null != logger)
{
// fill in from logger if we can
if (q.SentSerialNumber == 0)
{ // assign a serial number even if contest doesn't need it
uint serialToSend = logger.GetSendSerialNumber(q.HisCall);
// logger may give us the same serial number since we're just one radio
Dictionary<uint, uint> serialsInProgress = new Dictionary<uint, uint>();
var inProgress = qsosPanel.QsosInProgress;
for (int i = 0; i < inProgress.Count; i++)
{ // first entries are highest priority
QsoInProgress qp = inProgress[i];
if (null == qp)
continue; // manual entry goes this way
uint qps = qp.SentSerialNumber;
if (qps != 0)
serialsInProgress.Add(qps, qps);
}
uint ignore;
while (serialsInProgress.TryGetValue(serialToSend, out ignore))
serialToSend += 1;
q.SentSerialNumber = serialToSend;
}
switch (excSet)
{
case ExchangeTypes.ARRL_FIELD_DAY:
string entryclass = "";
var fdsplit = Properties.Settings.Default.ContestMessageToSend.Split((char[])null,
StringSplitOptions.RemoveEmptyEntries);
bool founddigit = false;
foreach (string w in fdsplit)
{
if (!founddigit)
{
if (Char.IsDigit(w[0]))
{
founddigit = true;
entryclass = w;
}
}
else if (w.All(Char.IsLetter))
return String.Format("{0} {1} {2}{3} {4}", q.HisCall, myCall,
addAck ? "R " : "", entryclass, w);
}
break;
case ExchangeTypes.ARRL_RTTY:
string part = null;
String percentSearch = Properties.Settings.Default.ContestMessageToSend;
String percentsRemoved = "";
for (; ; )
{ // is there a serial number in the message?
int percentPos = percentSearch.IndexOf('%');
if (percentPos < 0)
{
percentsRemoved += percentSearch;
break; // no serial number
}
if ((percentPos < percentSearch.Length - 1) &&
Char.IsLetter(percentSearch[percentPos + 1]))
{
percentsRemoved += percentSearch.Substring(0, percentPos);
percentSearch = percentSearch.Substring(percentPos + 2);
continue; // this one is not a serial number
}
part = String.Format("{0:0000}", q.SentSerialNumber);
break;
}
if (String.IsNullOrEmpty(part))
{
var rttysplit = percentsRemoved.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
foreach (string w in rttysplit)
if (w.All(Char.IsLetter))
{
part = w.ToUpper();
break;
}
}
return String.Format("{0} {1} {2}{3} {4}", q.HisCall, myCall,
addAck ? "R " : "", q.Message.RST, part);
case ExchangeTypes.GRID_SQUARE:
{
string sentgrid = logger.GridSquareSendingOverride();
if (sentgrid.Length >= 4)
{
q.SentGrid = sentgrid;
return String.Format("{0} {1} {2} {3}",
hiscall, mycall,
addAck ? "R" : "", sentgrid);
}
}
break;
case ExchangeTypes.DB_REPORT:
break; // handle below
}
}
// if logger is not running, or doesn't handle the exchange.
switch (excSet)
{
case ExchangeTypes.DB_REPORT:
int dB = q.Message.SignalDB;
return String.Format("{0} {1} {2}{3:+00;-00;+00}",
hiscall,
mycall,
addAck ? "R" : "", dB);
}
return String.Format("{0} {1} {2}{3}",
hiscall,
mycall,
addAck ? "R " : "", MyGrid4);
}
private string GetAckMessage(QsoInProgress q, bool ofAnAck, int whichAck)
{
// this one does non standard calls backwards from above.
// The standard call is the one that gets hashed.