~ubuntu-branches/ubuntu/utopic/fldigi/utopic

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
// ----------------------------------------------------------------------------
// rigio.cxx
//
// Copyright (C) 2007-2009
//		Dave Freese, W1HKJ
//
// This file is part of fldigi.
//
// Fldigi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Fldigi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with fldigi.  If not, see <http://www.gnu.org/licenses/>.
// ----------------------------------------------------------------------------

#include <config.h>

#include <ctime>
#include <sys/time.h>
#include <iostream>
#include <list>
#include <vector>
#include <string>

#ifdef RIGCATTEST
	#include "rigCAT.h"
#else
	#include "fl_digi.h"
	#include "misc.h"
	#include "configuration.h"
#endif

#include "rigsupport.h"
#include "rigxml.h"
#include "trx.h"
#include "serial.h"
#include "rigio.h"
#include "debug.h"
#include "threads.h"
#include "qrunner.h"
#include "confdialog.h"
#include "status.h"

LOG_FILE_SOURCE(debug::LOG_RIGCONTROL);

using namespace std;

Cserial rigio;
static pthread_mutex_t  rigCAT_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_t		*rigCAT_thread = 0;

static bool			 rigCAT_exit = false;
static bool			 rigCAT_open = false;
static bool			 rigCAT_bypass = false;

static string		sRigWidth = "";
static string		sRigMode = "";
static long long	llFreq = 0;

static bool nonCATrig = false;

static void *rigCAT_loop(void *args);

#define RXBUFFSIZE 2000
static unsigned char replybuff[RXBUFFSIZE+1];
static unsigned char retbuf[3];

bool sendCommand (string s, int retnbr)
{
	int numwrite = (int)s.length();
	int readafter = progdefaults.RigCatWait;
	int numread;
	int retval;
	numread = retnbr;
	if (progdefaults.RigCatECHO) numread += numwrite;
	readafter =
		progdefaults.RigCatWait + (int) ceilf (
			numread * (9 + progdefaults.RigCatStopbits) *
			1000.0 / rigio.Baud() );

	LOG_DEBUG("%s", str2hex(s.data(), s.length()));

	retval = rigio.WriteBuffer((unsigned char *)s.c_str(), numwrite);
	if (retval <= 0)
		LOG_VERBOSE("Write error %d", retval);

	memset(replybuff, 0, RXBUFFSIZE + 1);
	numread = 0;
	MilliSleep( readafter );
	while (numread < RXBUFFSIZE) {
		memset(retbuf, 0, 2);
		if (rigio.ReadBuffer(retbuf, 1) == 0) break;
		replybuff[numread] = retbuf[0];
		numread++;
	}
	LOG_DEBUG("reply %s", str2hex(replybuff, numread));
	if (numread > retnbr) {
		memmove(replybuff, replybuff + numread - retnbr, retnbr);
		numread = retnbr;
	}

	return (numread == retnbr);
}

string to_bcd_be(long long freq, int len)
{
	string bcd = "";
	unsigned char a;
	int numchars = len / 2;
	if (len & 1) numchars ++;
	for (int i = 0; i < numchars; i++) {
		a = 0;
		a |= freq%10;
		freq /= 10;
		a |= (freq%10)<<4;
		freq /= 10;
		bcd += a;
	}
	return bcd;
}

string to_bcd(long long freq, int len)
{
	string bcd = "";
	string bcd_be = to_bcd_be(freq, len);
	int bcdlen = bcd_be.size();
	for (int i = bcdlen - 1; i >= 0; i--)
		bcd += bcd_be[i];
	return bcd;
}

long long fm_bcd (size_t p, int len)
{
	int i;
	long long f = 0;
	int numchars = len/2;
	if (len & 1) numchars ++;
	for (i = 0; i < numchars; i++) {
		f *=10;
		f += (replybuff[p + i] >> 4) & 0x0F;
		f *= 10;
		f += replybuff[p + i] & 0x0F;
	}
	return f;
}


long long fm_bcd_be(size_t p, int len)
{
	unsigned char temp;
	int numchars = len/2;
	if (len & 1) numchars++;
	for (int i = 0; i < numchars / 2; i++) {
		temp = replybuff[p + i];
		replybuff[p + i] = replybuff[p + numchars -1 - i];
		replybuff[p + numchars -1 - i] = temp;
	}
	return fm_bcd(p, len);
}

string to_binary_be(long long freq, int len)
{
	string bin = "";
	for (int i = 0; i < len; i++) {
		bin += freq & 0xFF;
		freq >>= 8;
	}
	return bin;
}

string to_binary(long long freq, int len)
{
	string bin = "";
	string bin_be = to_binary_be(freq, len);
	int binlen = bin_be.size();
	for (int i = binlen - 1; i >= 0; i--)
		bin += bin_be[i];
	return bin;
}

long long fm_binary(size_t p, int len)
{
	int i;
	long long f = 0;
	for (i = 0; i < len; i++) {
		f *= 256;
		f += replybuff[p + i];
	}
	return f;
}

long long fm_binary_be(size_t p, int len)
{
	unsigned char temp;
	int numchars = len/2;
	if (len & 1) numchars++;
	for (int i = 0; i < numchars / 2; i++) {
		temp = replybuff[p + i];
		replybuff[p + i] = replybuff[p + numchars -1 - i];
		replybuff[p + numchars -1 - i] = temp;
	}
	return fm_binary(p, len);
}

string to_decimal_be(long long d, int len)
{
	string sdec_be = "";
	for (int i = 0; i < len; i++) {
		sdec_be += (char)((d % 10) + '0');
		d /= 10;
	}
	return sdec_be;
}

string to_decimal(long long d, int len)
{
	string sdec = "";
	string sdec_be = to_decimal_be(d, len);
	int bcdlen = sdec_be.size();
	for (int i = bcdlen - 1; i >= 0; i--)
		sdec += sdec_be[i];
	return sdec;
}

long long fm_decimal(size_t p, int len)
{
	long long d = 0;
	for (int i = 0; i < len; i++) {
		d *= 10;
		d += replybuff[p + i] - '0';
	}
	return d;
}

long long fm_decimal_be(size_t p, int len)
{
	unsigned char temp;
	int numchars = len/2;
	if (len & 1) numchars++;
	for (int i = 0; i < numchars / 2; i++) {
		temp = replybuff[p + i];
		replybuff[p + i] = replybuff[p + numchars -1 - i];
		replybuff[p + numchars -1 - i] = temp;
	}
	return fm_decimal(p, len);
}

string to_freqdata(DATA d, long long f)
{
	int num, den;
	num = 100;
	den = (int)(d.resolution * 100);
	if (d.size == 0) return "";
	if (d.dtype == "BCD") {
		if (d.reverse == true)
			return to_bcd_be((long long int)(f * num / den), d.size);
		else
			return to_bcd((long long int)(f * num / den), d.size);
	} else if (d.dtype == "BINARY") {
		if (d.reverse == true)
			return to_binary_be((long long int)(f * num / den), d.size);
		else
			return to_binary((long long int)(f * num / den), d.size);
	} else if (d.dtype == "DECIMAL") {
		if (d.reverse == true)
			return to_decimal_be((long long int)(f * num / den), d.size);
		else
			return to_decimal((long long int)(f * num / den), d.size);
	}
	return "";
}

long long fm_freqdata(DATA d, size_t p)
{
	int num, den;
	num = (int)(d.resolution * 100);
	den = 100;
	long long fret = 0;
	if (d.dtype == "BCD") {
		if (d.reverse == true)
			fret = (long long int)(fm_bcd_be(p, d.size) * num / den);
		else
			fret = (long long int)(fm_bcd(p, d.size)  * num / den);
	} else if (d.dtype == "BINARY") {
		if (d.reverse == true)
			fret = (long long int)(fm_binary_be(p, d.size)  * num / den);
		else
			fret = (long long int)(fm_binary(p, d.size)  * num / den);
	} else if (d.dtype == "DECIMAL") {
		if (d.reverse == true)
			fret = (long long int)(fm_decimal_be(p, d.size)  * num / den);
		else
			fret = (long long int)(fm_decimal(p, d.size)  * num / den);
	}
	return fret;
}

long long rigCAT_getfreq(int retries, bool &failed)
{
	XMLIOS modeCmd;
	list<XMLIOS>::iterator itrCmd;
	string strCmd;
	size_t p = 0, len1 = 0, len2 = 0, pData = 0;
	long long f = 0;

	failed = false;
	if (nonCATrig) {
		failed = true;
		return progStatus.noCATfreq;
	}

	itrCmd = commands.begin();
	while (itrCmd != commands.end()) {
		if ((*itrCmd).SYMBOL == "GETFREQ")
			break;
		++itrCmd;
	}

	if (itrCmd == commands.end()) {
		failed = true;
		return progStatus.noCATfreq; // get_freq command is not defined!
	}

	modeCmd = *itrCmd;

	if ( modeCmd.str1.empty() == false)
		strCmd.append(modeCmd.str1);

	if (modeCmd.str2.empty() == false)
		strCmd.append(modeCmd.str2);

	if ( !modeCmd.info.size() ) {
		failed = true;
		return 0;
	}

	for (list<XMLIOS>::iterator preply = reply.begin(); preply != reply.end(); ++preply) {
		if (preply->SYMBOL != modeCmd.info)
			continue;

		XMLIOS  rTemp = *preply;
		len1 = rTemp.str1.size();
		len2 = rTemp.str2.size();

//		for (int n = 0; n < progdefaults.RigCatRetries; n++) {
		for (int n = 0; n < retries; n++) {
			if (n && progdefaults.RigCatTimeout > 0)
				MilliSleep(progdefaults.RigCatTimeout);
// send the command
			if ( !sendCommand(strCmd, rTemp.size) ) {
				LOG_VERBOSE("sendCommand failed");
				goto retry_get_freq;
			}
// check the pre data string
			p = 0;
			pData = 0;
			if (len1) {
				for (size_t i = 0; i < len1; i++) {
					if ((char)rTemp.str1[i] != (char)replybuff[i]) {
						LOG_VERBOSE("failed pre data string test @ %" PRIuSZ, i);
						goto retry_get_freq;
					}
				}
				p = len1;
			}
			if (rTemp.fill1) p += rTemp.fill1;
			pData = p;
			if (rTemp.data.dtype == "BCD") {
				p += rTemp.data.size / 2;
				if (rTemp.data.size & 1) p++;
			} else
				p += rTemp.data.size;
// check the post data string
			if (rTemp.fill2) p += rTemp.fill2;

			if (len2) {
				for (size_t i = 0; i < len2; i++)
					if ((char)rTemp.str2[i] != (char)replybuff[p + i]) {
						LOG_VERBOSE("failed post data string test @ %" PRIuSZ, i);
						goto retry_get_freq;
					}
			}
// convert the data field
			f = fm_freqdata(rTemp.data, pData);
			if ( f >= rTemp.data.min && f <= rTemp.data.max)
				return f;
			LOG_VERBOSE("freq: %lld", f);
retry_get_freq: ;
		}
	}
	if (progdefaults.RigCatVSP == false)
		LOG_VERBOSE("Retries failed");
	failed = true;
	return 0;
}

void rigCAT_setfreq(long long f)
{
	XMLIOS modeCmd;
	list<XMLIOS>::iterator itrCmd;
	string strCmd;

	progStatus.noCATfreq = f;

	if (nonCATrig) {
		return;
	}

//	LOG_DEBUG("set frequency %lld", f);

	itrCmd = commands.begin();
	while (itrCmd != commands.end()) {
		if ((*itrCmd).SYMBOL == "SETFREQ")
			break;
		++itrCmd;
	}
	if (itrCmd == commands.end()) {
		LOG_VERBOSE("SET_FREQ not defined");
		return;
	}

	modeCmd = *itrCmd;

	if ( modeCmd.str1.empty() == false)
		strCmd.append(modeCmd.str1);

	strCmd.append( to_freqdata(modeCmd.data, f) );

	if (modeCmd.str2.empty() == false)
		strCmd.append(modeCmd.str2);

	if (modeCmd.ok.size()) {
		list<XMLIOS>::iterator preply = reply.begin();
		while (preply != reply.end()) {
			if (preply->SYMBOL == modeCmd.ok) {
				XMLIOS  rTemp = *preply;
// send the command
				bool ok = false;
				for (int n = 0; n < progdefaults.RigCatRetries; n++) {
					pthread_mutex_lock(&rigCAT_mutex);
					ok = sendCommand(strCmd, rTemp.size);
					pthread_mutex_unlock(&rigCAT_mutex);
					if (ok) return;
				}
				return;
			}
			preply++;
		}
	} else {
		bool ok = false;
		for (int n = 0; n < progdefaults.RigCatRetries; n++) {
			pthread_mutex_lock(&rigCAT_mutex);
			ok = sendCommand(strCmd, 0);
			pthread_mutex_unlock(&rigCAT_mutex);
			if (ok) return;
		}
	}
	if (progdefaults.RigCatVSP == false)
		LOG_VERBOSE("Retries failed");
}

string rigCAT_getmode()
{
	XMLIOS modeCmd;
	list<XMLIOS>::iterator itrCmd;
	list<MODE>::iterator mode;
	list<MODE> *pmode;
	string strCmd, mData;
	size_t len;

	if (nonCATrig)
		return progStatus.noCATmode;

	itrCmd = commands.begin();
	while (itrCmd != commands.end()) {
		if ((*itrCmd).SYMBOL == "GETMODE")
			break;
		++itrCmd;
	}
	if (itrCmd == commands.end())
		return progStatus.noCATmode;

	modeCmd = *itrCmd;

	if ( modeCmd.str1.empty() == false)
		strCmd.append(modeCmd.str1);

	if (modeCmd.str2.empty() == false)
		strCmd.append(modeCmd.str2);

	if (!modeCmd.info.size()) return "";

	for (list<XMLIOS>::iterator preply = reply.begin(); preply != reply.end(); ++preply) {
		if (preply->SYMBOL != modeCmd.info)
			continue;

		XMLIOS  rTemp = *preply;

		for (int n = 0; n < progdefaults.RigCatRetries; n++) {
			if (n && progdefaults.RigCatTimeout > 0)
				MilliSleep(progdefaults.RigCatTimeout);
			size_t p = 0, pData = 0;
// send the command
			if (!sendCommand(strCmd, rTemp.size)) goto retry_get_mode;
// check the pre data string
			len = rTemp.str1.size();
			if (len) {
				for (size_t i = 0; i < len; i++)
					if ((char)rTemp.str1[i] != (char)replybuff[i]) {
						LOG_VERBOSE("failed pre data string test @ %" PRIuSZ, i);
						goto retry_get_mode;
					}
				p = len;
			}
			if (rTemp.fill1) p += rTemp.fill1;
			pData = p;
// check the post data string
			p += rTemp.data.size;
			len = rTemp.str2.size();
			if (rTemp.fill2) p += rTemp.fill2;
			if (len) {
				for (size_t i = 0; i < len; i++)
					if ((char)rTemp.str2[i] != (char)replybuff[p + i])
						goto retry_get_mode;
			}
// convert the data field
			mData = "";
			for (int i = 0; i < rTemp.data.size; i++)
				mData += (char)replybuff[pData + i];
// for FT100 and the ilk that use bit fields
			if (rTemp.data.size == 1) {
				unsigned char d = mData[0];
				if (rTemp.data.shiftbits)
					d >>= rTemp.data.shiftbits;
				d &= rTemp.data.andmask;
				mData[0] = d;
			}
			if (lmodes.empty() == false)
					pmode = &lmodes;
			else if (lmodeREPLY.empty() == false)
				pmode = &lmodeREPLY;
			else
				goto retry_get_mode;
			mode = pmode->begin();
			while (mode != pmode->end()) {
				if ((*mode).BYTES == mData)
					break;
				mode++;
			}
			if (mode != pmode->end())
				return ((*mode).SYMBOL);
retry_get_mode: ;
		}
	}
	if (progdefaults.RigCatVSP == false)
		LOG_VERBOSE("Retries failed");
	return "";
}

void rigCAT_setmode(const string& md)
{
	XMLIOS modeCmd;
	list<XMLIOS>::iterator itrCmd;
	string strCmd;

	progStatus.noCATmode = md;

	if (nonCATrig) {
		return;
	}

	itrCmd = commands.begin();
	while (itrCmd != commands.end()) {
		if ((*itrCmd).SYMBOL == "SETMODE")
			break;
		++itrCmd;
	}
	modeCmd = *itrCmd;

	if ( modeCmd.str1.empty() == false)
		strCmd.append(modeCmd.str1);

	if ( modeCmd.data.size > 0 ) {
		list<MODE>::iterator mode;
		list<MODE> *pmode;
		if (lmodes.empty() == false)
			pmode = &lmodes;
		else if (lmodeCMD.empty() == false)
			pmode = &lmodeCMD;
		else
			return;
		mode = pmode->begin();
		while (mode != pmode->end()) {
			if ((*mode).SYMBOL == md)
				break;
			mode++;
		}
		if (mode != pmode->end())
			strCmd.append( (*mode).BYTES );
	}
	if (modeCmd.str2.empty() == false)
		strCmd.append(modeCmd.str2);

	if (modeCmd.ok.size()) {
		list<XMLIOS>::iterator preply = reply.begin();
		while (preply != reply.end()) {
			if (preply->SYMBOL == modeCmd.ok) {
				XMLIOS  rTemp = *preply;
// send the command
				bool ok = false;
				for (int n = 0; n < progdefaults.RigCatRetries; n++) {
					pthread_mutex_lock(&rigCAT_mutex);
					ok = sendCommand(strCmd, rTemp.size);
					pthread_mutex_unlock(&rigCAT_mutex);
					if (ok) return;
				}
				return;
			}
			preply++;
		}
	} else {
		bool ok = false;
		for (int n = 0; n < progdefaults.RigCatRetries; n++) {
			pthread_mutex_lock(&rigCAT_mutex);
			ok = sendCommand(strCmd, 0);
			pthread_mutex_unlock(&rigCAT_mutex);
			if (ok) return;
		}
	}
	if (progdefaults.RigCatVSP == false)
		LOG_VERBOSE("Retries failed");
}

string rigCAT_getwidth()
{
	XMLIOS modeCmd;
	list<XMLIOS>::iterator itrCmd;
	list<BW>::iterator bw;
	list<BW> *pbw;
	string strCmd, mData;
	size_t len = 0, p = 0, pData = 0;

	if (nonCATrig)
		return progStatus.noCATwidth;

	itrCmd = commands.begin();
	while (itrCmd != commands.end()) {
		if ((*itrCmd).SYMBOL == "GETBW")
			break;
		++itrCmd;
	}
	if (itrCmd == commands.end())
		return "";
	modeCmd = *itrCmd;

	if ( modeCmd.str1.empty() == false)
		strCmd.append(modeCmd.str1);

	if (modeCmd.str2.empty() == false)
		strCmd.append(modeCmd.str2);

	if (!modeCmd.info.size()) return "";

	for (list<XMLIOS>::iterator preply = reply.begin(); preply != reply.end(); ++preply) {
		if (preply->SYMBOL != modeCmd.info)
			continue;

		XMLIOS  rTemp = *preply;
		for (int n = 0; n < progdefaults.RigCatRetries; n++) {
			if (n && progdefaults.RigCatTimeout > 0)
				MilliSleep(progdefaults.RigCatTimeout);

			p = 0;
			pData = 0;
// send the command
			if ( !sendCommand(strCmd, rTemp.size) ) goto retry_get_width;
// check the pre data string
			len = rTemp.str1.size();
			if (len) {
				for (size_t i = 0; i < len; i++)
					if ((char)rTemp.str1[i] != (char)replybuff[i]) {
						LOG_VERBOSE("failed pre data string test @ %" PRIuSZ, i);
						goto retry_get_width;
					}
				p = pData = len;
			}
			if (rTemp.fill1) p += rTemp.fill1;
			pData = p;
			p += rTemp.data.size;
// check the post data string
			if (rTemp.fill2) p += rTemp.fill2;
			len = rTemp.str2.size();
			if (len) {
				for (size_t i = 0; i < len; i++)
					if ((char)rTemp.str2[i] != (char)replybuff[p + i])
						goto retry_get_width;
			}
// convert the data field
			mData = "";
			for (int i = 0; i < rTemp.data.size; i++)
				mData += (char)replybuff[pData + i];
// new for FT100 and the ilk that use bit fields
			if (rTemp.data.size == 1) {
				unsigned char d = mData[0];
				if (rTemp.data.shiftbits)
					d >>= rTemp.data.shiftbits;
				d &= rTemp.data.andmask;
				mData[0] = d;
			}
			if (lbws.empty() == false)
				pbw = &lbws;
			else if (lbwREPLY.empty() == false)
				pbw = &lbwREPLY;
			else
				goto retry_get_width;
			bw = pbw->begin();
			while (bw != pbw->end()) {
				if ((*bw).BYTES == mData)
					break;
				bw++;
			}
			if (bw != pbw->end())
				return ((*bw).SYMBOL);
retry_get_width: ;
		}
	}
	if (progdefaults.RigCatVSP == false)
		LOG_VERBOSE("Retries failed");
	return "";
}

void rigCAT_setwidth(const string& w)
{
	XMLIOS modeCmd;
	list<XMLIOS>::iterator itrCmd;
	string strCmd;

	if (nonCATrig) {
		progStatus.noCATwidth = w;
		return;
	}

	itrCmd = commands.begin();
	while (itrCmd != commands.end()) {
		if ((*itrCmd).SYMBOL == "SETBW")
			break;
		++itrCmd;
	}
	if (itrCmd == commands.end()) {
		progStatus.noCATwidth = w;
		return;
	}
	modeCmd = *itrCmd;

	if ( modeCmd.str1.empty() == false)
		strCmd.append(modeCmd.str1);

	if ( modeCmd.data.size > 0 ) {

		list<BW>::iterator bw;
		list<BW> *pbw;
		if (lbws.empty() == false)
			pbw = &lbws;
		else if (lbwCMD.empty() == false)
			pbw = &lbwCMD;
		else
			return;
		bw = pbw->begin();
		while (bw != pbw->end()) {
			if ((*bw).SYMBOL == w)
				break;
			bw++;
		}
		if (bw != pbw->end())
			strCmd.append( (*bw).BYTES );
	}
	if (modeCmd.str2.empty() == false)
		strCmd.append(modeCmd.str2);

	if (modeCmd.ok.size()) {
		list<XMLIOS>::iterator preply = reply.begin();
		while (preply != reply.end()) {
			if (preply->SYMBOL == modeCmd.ok) {
				XMLIOS  rTemp = *preply;
// send the command
				bool ok = false;
				for (int n = 0; n < progdefaults.RigCatRetries; n++) {
					pthread_mutex_lock(&rigCAT_mutex);
					ok = sendCommand(strCmd, rTemp.size);
					pthread_mutex_unlock(&rigCAT_mutex);
					if (ok) return;
				}
			}
			preply++;
		}
	} else {
		bool ok = false;
		for (int n = 0; n < progdefaults.RigCatRetries; n++) {
			pthread_mutex_lock(&rigCAT_mutex);
			ok = sendCommand(strCmd, 0);
			pthread_mutex_unlock(&rigCAT_mutex);
			if (ok) return;
		}
	}
	LOG_VERBOSE("Retries failed");
}

void rigCAT_pttON()
{
	XMLIOS modeCmd;
	list<XMLIOS>::iterator itrCmd;
	string strCmd;

	rigio.SetPTT(1); // always execute the h/w ptt if enabled

	if (nonCATrig) return;

	itrCmd = commands.begin();
	while (itrCmd != commands.end()) {
		if ((*itrCmd).SYMBOL == "PTTON")
			break;
		++itrCmd;
	}
	if (itrCmd == commands.end())
		return;
	modeCmd = *itrCmd;

	if ( modeCmd.str1.empty() == false)
		strCmd.append(modeCmd.str1);
	if (modeCmd.str2.empty() == false)
		strCmd.append(modeCmd.str2);

	if (modeCmd.ok.size()) {
		list<XMLIOS>::iterator preply = reply.begin();
		while (preply != reply.end()) {
			if (preply->SYMBOL == modeCmd.ok) {
				XMLIOS  rTemp = *preply;
// send the command
				bool ok = false;
				for (int n = 0; n < progdefaults.RigCatRetries; n++) {
					pthread_mutex_lock(&rigCAT_mutex);
					ok = sendCommand(strCmd, rTemp.size);
					pthread_mutex_unlock(&rigCAT_mutex);
					if (ok) return;
				}
				return;
			}
			preply++;
		}
	} else {
		bool ok = false;
		for (int n = 0; n < progdefaults.RigCatRetries; n++) {
			pthread_mutex_lock(&rigCAT_mutex);
			ok = sendCommand(strCmd, 0);
			pthread_mutex_unlock(&rigCAT_mutex);
			if (ok) return;
		}
	}
	LOG_VERBOSE("Retries failed");
}

void rigCAT_pttOFF()
{
	XMLIOS modeCmd;
	list<XMLIOS>::iterator itrCmd;
	string strCmd;

	rigio.SetPTT(0); // always execute the h/w ptt if enabled
	if (nonCATrig) return;

	itrCmd = commands.begin();
	while (itrCmd != commands.end()) {
		if ((*itrCmd).SYMBOL == "PTTOFF")
			break;
		++itrCmd;
	}
	if (itrCmd == commands.end())
		return;
	modeCmd = *itrCmd;

	if ( modeCmd.str1.empty() == false)
		strCmd.append(modeCmd.str1);
	if (modeCmd.str2.empty() == false)
		strCmd.append(modeCmd.str2);

	if (modeCmd.ok.size()) {
		list<XMLIOS>::iterator preply = reply.begin();
		while (preply != reply.end()) {
			if (preply->SYMBOL == modeCmd.ok) {
				XMLIOS  rTemp = *preply;
// send the command
				bool ok = false;
				for (int n = 0; n < progdefaults.RigCatRetries; n++) {
					pthread_mutex_lock(&rigCAT_mutex);
					ok = sendCommand(strCmd, rTemp.size);
					pthread_mutex_unlock(&rigCAT_mutex);
					if (ok) return;
				}
				return;
			}
			preply++;
		}
	} else {
		bool ok = false;
		for (int n = 0; n < progdefaults.RigCatRetries; n++) {
			pthread_mutex_lock(&rigCAT_mutex);
			ok = sendCommand(strCmd, 0);
			pthread_mutex_unlock(&rigCAT_mutex);
			if (ok) return;
		}
	}
	LOG_VERBOSE("Retries failed");
}

void rigCAT_sendINIT(const string& icmd){
	XMLIOS modeCmd;
	list<XMLIOS>::iterator itrCmd;
	string strCmd;

	if (nonCATrig)
		return;

	itrCmd = commands.begin();
	while (itrCmd != commands.end()) {
		if ((*itrCmd).SYMBOL == icmd)
			break;
		++itrCmd;
	}
	if (itrCmd == commands.end())
		return;
	modeCmd = *itrCmd;

	if ( modeCmd.str1.empty() == false)
		strCmd.append(modeCmd.str1);
	if (modeCmd.str2.empty() == false)
		strCmd.append(modeCmd.str2);

	if (modeCmd.ok.size()) {
		list<XMLIOS>::iterator preply = reply.begin();
		while (preply != reply.end()) {
			if (preply->SYMBOL == modeCmd.ok) {
				XMLIOS  rTemp = *preply;
// send the command
				bool ok = false;
				for (int n = 0; n < progdefaults.RigCatRetries; n++) {
					pthread_mutex_lock(&rigCAT_mutex);
					ok = sendCommand(strCmd, rTemp.size);
					pthread_mutex_unlock(&rigCAT_mutex);
					if (ok) return;
				}
				return;
			}
			preply++;
		}
	} else {
		bool ok = false;
		for (int n = 0; n < progdefaults.RigCatRetries; n++) {
			pthread_mutex_lock(&rigCAT_mutex);
			ok = sendCommand(strCmd, 0);
			pthread_mutex_unlock(&rigCAT_mutex);
			if (ok) return;
		}
	}
	LOG_VERBOSE("Retries failed");
}

void rigCAT_defaults()
{
	mnuXmlRigBaudrate->value(xmlrig.baud);
	valRigCatStopbits->value(xmlrig.stopbits);
	btnRigCatRTSplus->value(xmlrig.rts);
	btnRigCatDTRplus->value(xmlrig.dtr);
	btnRigCatRTSptt->value(xmlrig.rtsptt);
	btnRigCatDTRptt->value(xmlrig.dtrptt);
	chk_restore_tio->value(xmlrig.restore_tio);
	chkRigCatRTSCTSflow->value(xmlrig.rtscts);
	cntRigCatRetries->value(xmlrig.retries);
	cntRigCatTimeout->value(xmlrig.timeout);
	cntRigCatWait->value(xmlrig.write_delay);
	btnRigCatEcho->value(xmlrig.echo);
	btnRigCatCMDptt->value(xmlrig.cmdptt);
	chkRigCatVSP->value(xmlrig.vsp);
}

void rigCAT_restore_defaults()
{
	inpXmlRigDevice->value(progdefaults.XmlRigDevice.c_str());
	mnuXmlRigBaudrate->value(progdefaults.XmlRigBaudrate);
	valRigCatStopbits->value(progdefaults.RigCatStopbits);
	btnRigCatRTSplus->value(progdefaults.RigCatRTSplus);
	btnRigCatDTRplus->value(progdefaults.RigCatDTRplus);
	btnRigCatRTSptt->value(progdefaults.RigCatRTSptt);
	btnRigCatDTRptt->value(progdefaults.RigCatDTRptt);
	chk_restore_tio->value(progdefaults.RigCatRestoreTIO);
	chkRigCatRTSCTSflow->value(progdefaults.RigCatRTSCTSflow);
	cntRigCatRetries->value(progdefaults.RigCatRetries);
	cntRigCatTimeout->value(progdefaults.RigCatTimeout);
	cntRigCatWait->value(progdefaults.RigCatWait);
	btnRigCatEcho->value(progdefaults.RigCatECHO);
	btnRigCatCMDptt->value(progdefaults.RigCatCMDptt);
	chkRigCatVSP->value(progdefaults.RigCatVSP);

	btnInitRIGCAT->labelcolor(FL_FOREGROUND_COLOR);
	btnRevertRIGCAT->deactivate();
	dlgConfig->redraw();
}

void rigCAT_init_defaults()
{
	progdefaults.XmlRigDevice = inpXmlRigDevice->value();
	progdefaults.XmlRigBaudrate = mnuXmlRigBaudrate->value();
	progdefaults.RigCatStopbits = static_cast<int>(valRigCatStopbits->value());
	progdefaults.RigCatRTSplus = btnRigCatRTSplus->value();
	progdefaults.RigCatDTRplus = btnRigCatDTRplus->value();
	progdefaults.RigCatRTSptt = btnRigCatRTSptt->value();
	progdefaults.RigCatDTRptt = btnRigCatDTRptt->value();
	progdefaults.RigCatRestoreTIO = chk_restore_tio->value();
	progdefaults.RigCatRTSCTSflow = chkRigCatRTSCTSflow->value();
	progdefaults.RigCatRetries = static_cast<int>(cntRigCatRetries->value());
	progdefaults.RigCatTimeout = static_cast<int>(cntRigCatTimeout->value());
	progdefaults.RigCatWait = static_cast<int>(cntRigCatWait->value());
	progdefaults.RigCatECHO = btnRigCatEcho->value();
	progdefaults.RigCatCMDptt = btnRigCatCMDptt->value();
	progdefaults.RigCatVSP = chkRigCatVSP->value();
}

bool rigCAT_init(bool useXML)
{

	if (rigCAT_open == true) {
		LOG_ERROR("RigCAT already open");
		return false;
	}

	sRigMode = "";
	sRigWidth = "";

	if (useXML == true) {
		rigCAT_init_defaults();
		rigio.Device(progdefaults.XmlRigDevice);
		rigio.Baud(progdefaults.BaudRate(progdefaults.XmlRigBaudrate));
		rigio.RTS(progdefaults.RigCatRTSplus);
		rigio.DTR(progdefaults.RigCatDTRplus);
		rigio.RTSptt(progdefaults.RigCatRTSptt);
		rigio.DTRptt(progdefaults.RigCatDTRptt);
		rigio.RestoreTIO(progdefaults.RigCatRestoreTIO);
		rigio.RTSCTS(progdefaults.RigCatRTSCTSflow);
		rigio.Stopbits(progdefaults.RigCatStopbits);

		LOG_VERBOSE("\n\
Serial port parameters:\n\
device	 : %s\n\
baudrate   : %d\n\
stopbits   : %d\n\
retries	: %d\n\
timeout	: %d\n\
wait	   : %d\n\
initial rts: %+d\n\
use rts ptt: %c\n\
initial dtr: %+d\n\
use dtr ptt: %c\n\
restore tio: %c\n\
flowcontrol: %c\n\
echo	   : %c\n",
		rigio.Device().c_str(),
		rigio.Baud(),
		rigio.Stopbits(),
		progdefaults.RigCatRetries,
		progdefaults.RigCatTimeout,
		progdefaults.RigCatWait,
			(rigio.RTS() ? +12 : -12), (rigio.RTSptt() ? 'T' : 'F'),
			(rigio.DTR() ? +12 : -12), (rigio.DTRptt() ? 'T' : 'F'),
			(rigio.RestoreTIO() ? 'T' : 'F'),
			(rigio.RTSCTS() ? 'T' : 'F'),
			progdefaults.RigCatECHO ? 'T' : 'F');

		if (rigio.OpenPort() == false) {
			LOG_VERBOSE("Cannot open serial port %s", rigio.Device().c_str());
			nonCATrig = true;
			init_NoRig_RigDialog();
			return false;
		}
		sRigMode = "";
		sRigWidth = "";

		nonCATrig = false;
		rigCAT_sendINIT("INIT");

// must be able to get frequency 3 times in sequence or serial port might
// be shared with another application (flrig)
		bool failed = false;
		for (int i = 1; i <= 5; i++) {
			rigCAT_getfreq(1, failed);
			if (failed) break;
			LOG_INFO("Passed serial port test # %d", i);
//			MilliSleep(50);
		}

		if (failed) {
			LOG_INFO("Failed serial port test");
			rigio.ClosePort();
			nonCATrig = true;
			init_NoRig_RigDialog();
			return false;
		} else {
			nonCATrig = false;
			init_Xml_RigDialog();
		}
	} else {
		nonCATrig = true;
		init_NoRig_RigDialog();
	}

	llFreq = 0;
	rigCAT_bypass = false;
	rigCAT_exit = false;

	rigCAT_thread = new pthread_t;

	if (pthread_create(rigCAT_thread, NULL, rigCAT_loop, NULL) < 0) {
		LOG_ERROR("pthread_create failed");
		rigio.ClosePort();
		return false;
	}
	LOG_VERBOSE("New thread %p", rigCAT_thread);

	rigCAT_open = true;

	return true;
}

void rigCAT_close(void)
{
	if (rigCAT_open == false || rigCAT_exit)
		return;

	if (rigCAT_thread == 0) return;

	rigCAT_sendINIT("CLOSE");

	pthread_mutex_lock(&rigCAT_mutex);
		rigCAT_exit = true;
	pthread_mutex_unlock(&rigCAT_mutex);

	if (!rigCAT_thread) return;

	pthread_join(*rigCAT_thread, NULL);

	LOG_VERBOSE("Deleting thread %p", rigCAT_thread);
	delete rigCAT_thread;
	rigCAT_thread = 0;

	wf->USB(true);
	rigCAT_open = false;
}

bool rigCAT_active(void)
{
	return (rigCAT_open);
}

void rigCAT_set_ptt(int ptt)
{
	if (rigCAT_open == false)
		return;
	if (ptt) {
		rigCAT_pttON();
		rigCAT_bypass = true;
	} else{
		rigCAT_pttOFF();
		rigCAT_bypass = false;
	}
}

#ifndef RIGCATTEST
void rigCAT_set_qsy(long long f)
{
	if (rigCAT_open == false)
		return;

	// send new freq to rig
	rigCAT_setfreq(f);
	wf->rfcarrier(f);
	wf->movetocenter();
}
#endif

bool ModeIsLSB(const string& s)
{
	if (nonCATrig) {
		if (s == "LSB" || s == "PKTLSB" || s == "CW" || s == "RTTY")
			return true;
		return false;
	}
	list<string>::iterator pM = LSBmodes.begin();
	while (pM != LSBmodes.end() ) {
		if (*pM == s)
			return true;
		pM++;
	}
	return false;
}

static void *rigCAT_loop(void *args)
{
	SET_THREAD_ID(RIGCTL_TID);

	long long freq = 0L;
	string sWidth, sMode;
	bool failed;

	for (;;) {
		MilliSleep(200);

		if (rigCAT_exit == true)
			break;

		if (rigCAT_bypass == true)
			continue;

		pthread_mutex_lock(&rigCAT_mutex);
			freq = rigCAT_getfreq(progdefaults.RigCatRetries, failed);
		pthread_mutex_unlock(&rigCAT_mutex);

		pthread_mutex_lock(&rigCAT_mutex);
			sWidth = rigCAT_getwidth();
		pthread_mutex_unlock(&rigCAT_mutex);

		pthread_mutex_lock(&rigCAT_mutex);
			sMode = rigCAT_getmode();
		pthread_mutex_unlock(&rigCAT_mutex);

		if ((freq > 0) && (freq != llFreq)) {
			llFreq = freq;
			show_frequency(freq);
			wf->rfcarrier(freq);
		}

		if (sWidth.size() && sWidth != sRigWidth) {
			sRigWidth = sWidth;
			show_bw(sWidth);
		}

		if (sMode.size() && sMode != sRigMode) {
			sRigMode = sMode;
			if (ModeIsLSB(sMode))
				wf->USB(false);
			else
				wf->USB(true);
			show_mode(sMode);
		}
	}

	wf->USB(true);

	pthread_mutex_lock(&rigCAT_mutex);
		LOG_DEBUG("Exiting rigCAT loop, closing serial port");
		rigio.ClosePort();
	pthread_mutex_unlock(&rigCAT_mutex);

	rigCAT_open = false;
	rigCAT_exit = false;
	rigCAT_bypass = false;

	return NULL;
}