-
Notifications
You must be signed in to change notification settings - Fork 12
/
JanVNA2_comms.cpp
3190 lines (2815 loc) · 91.1 KB
/
JanVNA2_comms.cpp
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
#pragma hdrstop
#include "JanVNA2_comms.h"
#include "CommsUnit.h"
#include "DataUnit.h"
#include "Unit1.h"
#include "SettingsUnit.h"
#pragma package(smart_init)
#define CDBM_SCALE 100
// *******************************
// protocol
const int EP_Data_Out_Addr = 0x01;
const int EP_Data_In_Addr = 0x81;
const int EP_Log_In_Addr = 0x82;
const uint8_t header_magic = 0x5A;
const uint16_t Version = 1;
// *******************************
class Encoder
{
public:
Encoder(uint8_t *buf, uint16_t size) :
buf(buf),
bufSize(size),
usedSize(0),
bitpos(0)
{
memset(buf, 0, size);
};
template<typename T> bool add(T data)
{
if (bitpos != 0)
{
// add padding to next byte boundary
bitpos = 0;
usedSize++;
}
if (bufSize - usedSize < (long) sizeof(T))
{
// not enough space left
return false;
}
memcpy(&buf[usedSize], &data, sizeof(T));
usedSize += sizeof(T);
return true;
}
bool addBits(uint8_t value, uint8_t bits)
{
if (bits >= 8 || usedSize >= bufSize)
{
return false;
}
buf[usedSize] |= (value << bitpos) & 0xFF;
bitpos += bits;
if (bitpos > 8)
{
// the value did not fit completely into the current byte
if (usedSize >= bufSize - 1)
{
// already at maximum limit, not enough space for remaining bits
return false;
}
// move access to next byte
bitpos -= 8;
usedSize++;
// add remaining bytes
buf[usedSize] = value >> (bits - bitpos);
}
else
if (bitpos == 8)
{
bitpos = 0;
usedSize++;
}
return true;
}
uint16_t getSize() const
{
if (bitpos == 0)
{
return usedSize;
}
else
{
return usedSize + 1;
}
};
private:
uint8_t *buf;
uint16_t bufSize;
uint16_t usedSize;
uint8_t bitpos;
};
class Decoder
{
public:
Decoder(const uint8_t *buf) :
buf(buf),
usedSize(0),
bitpos(0)
{
};
template<typename T> void get(T &t)
{
if (bitpos != 0)
{
// add padding to next byte boundary
bitpos = 0;
usedSize++;
}
// still enough bytes available
memcpy(&t, &buf[usedSize], sizeof(T));
usedSize += sizeof(T);
}
uint8_t getBits(uint8_t bits)
{
if (bits >= 8)
{
return 0;
}
uint8_t mask = 0x00;
for(uint8_t i=0;i<bits;i++)
{
mask <<= 1;
mask |= 0x01;
}
uint8_t value = (buf[usedSize] >> bitpos) & mask;
bitpos += bits;
if (bitpos > 8)
{
// the current byte did not contain the complete value
// move access to next byte
bitpos -= 8;
usedSize++;
// get remaining bits
value |= (buf[usedSize] << (bits - bitpos)) & mask;
}
else
if (bitpos == 8)
{
bitpos = 0;
usedSize++;
}
return value;
}
private:
const uint8_t *buf;
uint16_t usedSize;
uint8_t bitpos;
};
/*
uint16_t Protocol::EncodePacket(const PacketInfo &packet, uint8_t *dest, uint16_t destsize)
{
int16_t payload_size = 0;
switch (packet.type)
{
case PacketType::Datapoint:
payload_size = EncodeDatapoint(packet.datapoint, &dest[4], destsize - 8);
break;
case PacketType::SweepSettings:
payload_size = EncodeSweepSettings(packet.settings, &dest[4], destsize - 8);
break;
case PacketType::Reference:
payload_size = EncodeReferenceSettings(packet.reference, &dest[4], destsize - 8);
break;
case PacketType::DeviceInfo:
payload_size = EncodeDeviceInfo(packet.info, &dest[4], destsize - 8);
break;
case PacketType::Status:
payload_size = EncodeStatus(packet.status, &dest[4], destsize - 8);
break;
case PacketType::ManualControl:
payload_size = EncodeManualControl(packet.manual, &dest[4], destsize - 8);
break;
case PacketType::FirmwarePacket:
payload_size = EncodeFirmwarePacket(packet.firmware, &dest[4], destsize - 8);
break;
case PacketType::Generator:
payload_size = EncodeGeneratorSettings(packet.generator, &dest[4], destsize - 8);
break;
case PacketType::SpectrumAnalyzerSettings:
payload_size = EncodeSpectrumAnalyzerSettings(packet.spectrumSettings, &dest[4], destsize - 8);
break;
case PacketType::SpectrumAnalyzerResult:
payload_size = EncodeSpectrumAnalyzerResult(packet.spectrumResult, &dest[4], destsize - 8);
break;
case PacketType::Ack:
case PacketType::PerformFirmwareUpdate:
case PacketType::ClearFlash:
case PacketType::Nack:
case PacketType::RequestDeviceInfo:
// no payload, nothing to do
break;
case PacketType::None:
break;
}
if (payload_size < 0 || payload_size + 8 > destsize)
{
// encoding failed, buffer too small
return 0;
}
// Write header
dest[0] = header;
uint16_t overall_size = payload_size + 8;
memcpy(&dest[1], &overall_size, 2);
dest[3] = (int)packet.type;
// Calculate checksum
uint32_t crc = 0x00000000;
if (packet.type == PacketType::Datapoint)
{
// CRC calculation takes about 18us which is the bulk of the time required to encode and transmit a datapoint.
// Skip CRC for data points to optimize throughput
crc = 0x00000000;
}
else
{
crc = CRC32(0, dest, overall_size - 4);
}
memcpy(&dest[overall_size - 4], &crc, 4);
return overall_size;
}
*/
// *******************************
CUSBRx::CUSBRx(libusb_context *ctx, libusb_device_handle *handle, const uint8_t end_point, const int buffer_size, t_usb_in_data_callback on_data_cb)
{
int res = 0;
m_event = CreateEvent(NULL, TRUE, FALSE, NULL);
m_ctx = ctx;
m_handle = handle;
m_on_data_callback = on_data_cb;
m_data_buffer_wr = 0;
int num_iso_pack = 0;
// int num_iso_pack = 16;
m_transfer_buffer.resize(4096);
if (buffer_size > 0)
m_data_buffer.resize(buffer_size);
try
{
m_transfer = libusb_alloc_transfer(num_iso_pack);
if (m_transfer)
{
if (num_iso_pack > 0)
{
libusb_fill_iso_transfer(m_transfer, m_handle, end_point, &m_transfer_buffer[0], m_transfer_buffer.size(), num_iso_pack, callback, this, 100);
libusb_set_iso_packet_lengths(m_transfer, m_transfer_buffer.size() / num_iso_pack);
}
else
{
libusb_fill_bulk_transfer(m_transfer, m_handle, end_point, &m_transfer_buffer[0], m_transfer_buffer.size(), callback, this, 100);
}
res = libusb_submit_transfer(m_transfer);
if (res < 0)
libusb_free_transfer(m_transfer);
}
}
catch (Exception &exception)
{
//exception.ToString());
}
if (res < 0 && Form1)
{
const char *str = libusb_strerror(res);
String s = "rx: usb rx transfer submit error";
if (str != NULL)
s += ": " + String(str);
Form1->pushCommMessage(s);
}
}
CUSBRx::~CUSBRx()
{
if (m_transfer)
{
int res;
// clear event flag
if (m_event)
ResetEvent(m_event);
// cancel transfers
try
{
res = libusb_cancel_transfer(m_transfer);
}
catch (...)
{
}
if (res < 0 && Form1)
{
const char *str = libusb_strerror(res);
String s = "rx: usb rx transfer cancel error";
if (str != NULL)
s += ": " + String(str);
Form1->pushCommMessage(s);
}
// wait for cancellation to complete
if (m_event)
{
res = 0;
DWORD ret = WAIT_OBJECT_0;
for (int i = 0; i < 50; i++)
{
int completed = 0;
struct timeval tv = {0, 1000};
res = libusb_handle_events_timeout_completed(m_ctx, &tv, &completed);
if (res < 0)
break;
ret = WaitForSingleObject(m_event, 1);
//if (ret == WAIT_OBJECT_0 || completed != 0)
if (ret == WAIT_OBJECT_0)
break;
}
if (Form1)
{
if (res < 0)
{
const char *str = libusb_strerror(res);
String s = "rx: usb rx transfer handle error";
if (str != NULL)
s += ": " + String(str);
Form1->pushCommMessage(s);
}
if (ret != WAIT_OBJECT_0)
Form1->pushCommMessage("rx: usb rx transfer cancel timed out");
}
}
}
HANDLE event = m_event;
m_event = NULL;
m_transfer = NULL;
m_ctx = NULL;
m_handle = NULL;
m_on_data_callback = NULL;
if (event)
CloseHandle(event);
}
void __fastcall CUSBRx::addTransferData(libusb_transfer *transfer)
{
if (transfer == NULL)
return;
const uint8_t *buf = (uint8_t *)transfer->buffer;
const int len = transfer->actual_length;
if (buf && len > 0)
{ // copy the data into our buffer
memcpy(&m_data_buffer[m_data_buffer_wr], buf, len);
m_data_buffer_wr += len;
if (m_data_buffer_wr >= ((int)m_data_buffer.size() / 2) && Form1)
{
String s;
s.printf(L"rx: usb rx transfer more than half full %d/%u", m_data_buffer_wr, m_data_buffer.size());
Form1->pushCommMessage(s);
}
#if 0
// TEST ONLY
String s;
s.printf(L"transfer cb %d\n", len);
common.logFileAppend(s + "\n");
#endif
}
if (len >= (transfer->length / 2))
{ // the buffer is quite full .. double it's size
m_transfer_buffer.resize(m_transfer_buffer.size() * 2);
transfer->buffer = &m_transfer_buffer[0];
transfer->length = m_transfer_buffer.size();
if (Form1)
{
String s;
s.printf(L"rx: usb rx transfer buffer was more than half full %d, increased size to %u", len, m_transfer_buffer.size());
Form1->pushCommMessage(s);
}
}
int res = 0;
try
{
res = libusb_submit_transfer(transfer);
if (res < 0)
libusb_free_transfer(transfer);
}
catch (...)
{
}
if (res < 0)
{
const char *str = libusb_strerror(res);
if (Form1 && str != NULL)
Form1->pushCommMessage("rx: usb buffer submit error: " + String(str));
}
if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT)
{
if (Form1 && len != 0)
{
String s;
s.printf(L"rx: usb buffer timed out .. ep %02X act-len %d flags %02X", transfer->endpoint, len, transfer->flags);
Form1->pushCommMessage(s);
}
}
}
void __fastcall CUSBRx::processCallback(libusb_transfer *transfer)
{
int res;
if (transfer == NULL)
return;
switch (transfer->type)
{
case LIBUSB_TRANSFER_TYPE_CONTROL:
if (Form1)
Form1->pushCommMessage("rx: usb rx transfer type control");
break;
case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
if (Form1)
Form1->pushCommMessage("rx: usb rx transfer type iso");
for (int packet = 0; packet < transfer->num_iso_packets; packet++)
{
struct libusb_iso_packet_descriptor *pack = &transfer->iso_packet_desc[packet];
if (pack->status != LIBUSB_TRANSFER_COMPLETED)
{
String s;
s.printf(L"rx: usb rx transfer iso error .. pack %d status %d", packet, pack->status);
if (Form1)
Form1->pushCommMessage(s);
}
else
{
// const uint8_t *buf = libusb_get_iso_packet_buffer(transfer, packet);
// if (buf && len > 0)
// { // copy the data into our buffer
// memcpy(&m_data_buffer[m_data_buffer_wr], buf, len);
// m_data_buffer_wr += len;
//
// if (m_data_buffer_wr >= ((int)m_data_buffer.size() / 2) && Form1)
// Form1->pushCommMessage("rx: usb rx transfer half full");
// }
if (Form1)
{
String s;
s.printf(L"rx: usb rx transfer .. pack %d length %u actual_length %u", packet, pack->length, pack->actual_length);
Form1->pushCommMessage(s);
}
}
}
break;
case LIBUSB_TRANSFER_TYPE_BULK:
// if (Form1)
// Form1->pushCommMessage("rx: usb rx transfer type bulk");
if (transfer->status == LIBUSB_TRANSFER_COMPLETED || transfer->status == LIBUSB_TRANSFER_TIMED_OUT)
{
addTransferData(transfer);
#if 0
// TEST ONLY
if (transfer->endpoint == EP_Data_In_Addr)
common.dataFileAppend(transfer->buffer, transfer->actual_length);
#endif
}
break;
case LIBUSB_TRANSFER_TYPE_INTERRUPT:
// if (Form1)
// Form1->pushCommMessage("rx: usb rx transfer type interrupt");
break;
case LIBUSB_TRANSFER_TYPE_BULK_STREAM:
if (Form1)
Form1->pushCommMessage("rx: usb rx transfer type bulk stream");
break;
}
switch (transfer->status)
{
case LIBUSB_TRANSFER_COMPLETED:
break;
case LIBUSB_TRANSFER_NO_DEVICE:
if (Form1)
Form1->pushCommMessage("rx: usb rx transfer no device");
if ((transfer->flags & LIBUSB_TRANSFER_FREE_TRANSFER) == 0)
{
try
{
libusb_free_transfer(transfer);
}
catch (...)
{
}
}
transfer = NULL;
break;
case LIBUSB_TRANSFER_ERROR:
case LIBUSB_TRANSFER_OVERFLOW:
case LIBUSB_TRANSFER_STALL:
if (Form1)
Form1->pushCommMessage("rx: usb rx transfer error [" + IntToStr(transfer->status) + "]");
if ((transfer->flags & LIBUSB_TRANSFER_FREE_TRANSFER) == 0)
{
try
{
libusb_free_transfer(transfer);
}
catch (...)
{
}
}
transfer = NULL;
break;
case LIBUSB_TRANSFER_CANCELLED:
//if (Form1)
// Form1->pushCommMessage("rx: usb rx transfer cancelled");
if ((transfer->flags & LIBUSB_TRANSFER_FREE_TRANSFER) == 0)
{
try
{
libusb_free_transfer(transfer);
}
catch (...)
{
}
}
if (m_event)
SetEvent(m_event); // let the owner know we have cancelled the transfers
transfer = NULL;
break;
case LIBUSB_TRANSFER_TIMED_OUT:
if (Form1 && transfer->actual_length != 0)
{
String s;
s.printf(L"rx: usb rx transfer timed out .. ep %02X act-len %d flags %02X", transfer->endpoint, transfer->actual_length, transfer->flags);
Form1->pushCommMessage(s);
}
break;
default:
if (Form1)
Form1->pushCommMessage("rx: usb rx transfer unknown status [" + UIntToStr((uint32_t)transfer->status) + "]");
break;
}
if (m_on_data_callback && m_data_buffer_wr > 0)
{
const int bytes_used = m_on_data_callback((TObject *)this, m_data_buffer, m_data_buffer_wr);
// remove the used bytes
if (bytes_used >= m_data_buffer_wr)
{
m_data_buffer_wr = 0;
}
else
if (bytes_used > 0)
{
memmove(&m_data_buffer[0], &m_data_buffer[bytes_used], m_data_buffer_wr - bytes_used);
m_data_buffer_wr -= bytes_used;
}
}
}
// *******************************
CJanVNA2_comms janvna2_comms;
CJanVNA2_comms::CJanVNA2_comms()
{
m_usb_rx_data = NULL;
m_usb_in_log = NULL;
m_device.hdev = NULL;
// m_events_thread_priority = tpTimeCritical; // tpIdle tpLowest tpNormal tpHighest tpTimeCritical
m_events_thread_priority = tpNormal; // tpIdle tpLowest tpNormal tpHighest tpTimeCritical
m_events_thread = NULL;
m_thread = NULL;
m_data_tx.buffer.resize(4096);
m_data_tx.index_wr = 0;
m_rx_packets.packet_rd = 0;
m_rx_packets.packet_wr = 0;
reset(false);
}
CJanVNA2_comms::~CJanVNA2_comms()
{
stopThread();
closeDevice();
}
bool __fastcall CJanVNA2_comms::startThread()
{
if (m_events_thread == NULL)
m_events_thread = new CJanVNA2EventsThread(&threadEventsProcess, true, &m_events_thread);
if (m_events_thread == NULL)
{
stopThread();
return false;
}
if (m_thread == NULL)
m_thread = new CJanVNA2Thread(&threadProcess, true, &m_thread);
if (m_thread == NULL)
{
stopThread();
return false;
}
return true;
}
void __fastcall CJanVNA2_comms::stopThread(const bool local)
{
CJanVNA2EventsThread *events_thread = m_events_thread;
m_events_thread = NULL;
CJanVNA2Thread *thread = m_thread;
m_thread = NULL;
// HANDLE handle = GetCurrentProcess();
// HANDLE thread_handle = GetCurrentThread();
if (events_thread != NULL)
{
events_thread->m_process = NULL;
events_thread->Terminate();
}
if (thread != NULL)
{
thread->m_process = NULL;
thread->Terminate();
}
}
void __fastcall CJanVNA2_comms::reset(const bool reset_vna)
{
m_mode = MODE_NONE;
m_new_mode = MODE_NONE;
m_max_retries = 4;
m_retries = 0;
m_pause_comms = false;
m_ack_timeout_ms = 800;
m_poll_ms = DEFAULT_POLL_JANVNAV2_MS;
m_device_info_ok = false;
m_ack = false;
m_nack = false;
m_data_tx.index_wr = 0;
m_update_sweep_settings = false;
m_update_generator_settings = false;
m_output_power = IROUND(DEFAULT_JANVNAV2_MAX_CDBM * CDBM_SCALE);
// default sweep settings
m_own_sweep_settings.f_start = data_unit.m_freq_start_Hz;
m_own_sweep_settings.f_stop = data_unit.m_freq_stop_Hz;
m_own_sweep_settings.points = data_unit.m_points;
m_own_sweep_settings.if_bandwidth = data_unit.m_bandwidth_Hz;
m_own_sweep_settings.cdbm_excitation = m_output_power;
m_own_sweep_settings.excitePort1 = 1;
m_own_sweep_settings.excitePort2 = 0;
m_own_sweep_settings.suppressPeaks = 1;
// default generator settings
m_own_generator_settings.frequency = data_unit.m_freq_cw_Hz;
m_own_generator_settings.cdbm_level = m_output_power;
m_own_generator_settings.activePort = 1; // 0 = off, 1 = port 1, 2 = port 2
//CCriticalSection cs(m_rx_packets.cs);
m_rx_packets.packet_rd = 0;
m_rx_packets.packet_wr = 0;
}
void __fastcall CJanVNA2_comms::setSweepSettings(const bool update)
{
if (update)
{
m_own_sweep_settings.f_start = data_unit.m_freq_start_Hz;
m_own_sweep_settings.f_stop = data_unit.m_freq_stop_Hz;
m_own_sweep_settings.points = data_unit.m_points;
m_own_sweep_settings.if_bandwidth = data_unit.m_bandwidth_Hz;
m_own_sweep_settings.cdbm_excitation = m_output_power;
m_own_sweep_settings.excitePort1 = 1;
m_own_sweep_settings.excitePort2 = 0;
m_own_sweep_settings.suppressPeaks = 1;
}
m_update_sweep_settings = true;
}
void __fastcall CJanVNA2_comms::setGeneratorSettings(const bool update)
{
if (update)
{
m_own_generator_settings.frequency = data_unit.m_freq_cw_Hz;
m_own_generator_settings.cdbm_level = m_output_power;
m_own_generator_settings.activePort = 1; // 0 = off, 1 = port 1, 2 = port 2
}
m_update_generator_settings = true;
}
float __fastcall CJanVNA2_comms::minOutputPowerdBm()
{
return m_device_info_ok ? (float)m_device_info.limits_cdbm_min / CDBM_SCALE : DEFAULT_JANVNAV2_MIN_CDBM;
}
float __fastcall CJanVNA2_comms::maxOutputPowerdBm()
{
return m_device_info_ok ? (float)m_device_info.limits_cdbm_max / CDBM_SCALE : DEFAULT_JANVNAV2_MAX_CDBM;
}
void __fastcall CJanVNA2_comms::setOutputPower(const float dBm)
{
const int cdBm_max = m_device_info_ok ? m_device_info.limits_cdbm_max : IROUND(DEFAULT_JANVNAV2_MAX_CDBM * CDBM_SCALE);
const int cdBm_min = m_device_info_ok ? m_device_info.limits_cdbm_min : IROUND(DEFAULT_JANVNAV2_MIN_CDBM * CDBM_SCALE);
int power = IROUND(dBm * CDBM_SCALE);
if (power < cdBm_min) power = cdBm_min;
else
if (power > cdBm_max) power = cdBm_max;
m_output_power = power;
m_own_sweep_settings.cdbm_excitation = m_output_power;
m_own_generator_settings.cdbm_level = m_output_power;
if (connected)
{
switch (m_mode)
{
case MODE_INIT1:
case MODE_INIT2:
case MODE_IDLE:
case MODE_POLL:
case MODE_SINGLE_SCAN:
case MODE_SCAN:
m_update_sweep_settings = true;
break;
case MODE_GENERATOR:
m_update_generator_settings = true;
break;
default:
break;
}
}
}
String __fastcall CJanVNA2_comms::packetTypeToStr(const PacketType packet_type)
{
switch (packet_type)
{
case PacketType::None: return "None";
case PacketType::Datapoint: return "Datapoint";
case PacketType::SweepSettings: return "SweepSettings";
case PacketType::Status: return "Status";
case PacketType::ManualControl: return "ManualControl";
case PacketType::DeviceInfo: return "DeviceInfo";
case PacketType::FirmwarePacket: return "FirmwarePacket";
case PacketType::Ack: return "Ack";
case PacketType::ClearFlash: return "ClearFlash";
case PacketType::PerformFirmwareUpdate: return "PerformFirmwareUpdate";
case PacketType::Nack: return "Nack";
case PacketType::Reference: return "Reference";
case PacketType::Generator: return "Generator";
case PacketType::SpectrumAnalyzerSettings: return "SpectrumAnalyzerSettings";
case PacketType::SpectrumAnalyzerResult: return "SpectrumAnalyzerResult";
case PacketType::RequestDeviceInfo: return "RequestDeviceInfo";
default: return "Unknown " + IntToStr((int)packet_type);
};
}
String __fastcall CJanVNA2_comms::usbSpeedToStr(const int usb_speed)
{
switch (usb_speed)
{
default:
case LIBUSB_SPEED_UNKNOWN: return "USB-Unknown";
case LIBUSB_SPEED_LOW: return "USB2.0_Low";
case LIBUSB_SPEED_FULL: return "USB2.0_Full";
case LIBUSB_SPEED_HIGH: return "USB2.0_High";
case LIBUSB_SPEED_SUPER: return "USB3.0";
case LIBUSB_SPEED_SUPER_PLUS: return "USB3.0+";
}
}
String __fastcall CJanVNA2_comms::usbClassToStr(const uint8_t usb_class)
{
switch (usb_class)
{
case LIBUSB_CLASS_PER_INTERFACE: return "CLASS_PER_INTERFACE";
case LIBUSB_CLASS_AUDIO: return "CLASS_AUDIO";
case LIBUSB_CLASS_COMM: return "CLASS_COMM";
case LIBUSB_CLASS_HID: return "CLASS_HID";
case LIBUSB_CLASS_PHYSICAL: return "CLASS_PHYSICAL";
case LIBUSB_CLASS_PRINTER: return "CLASS_PRINTER";
// case LIBUSB_CLASS_PTP: return "CLASS_PTP";
case LIBUSB_CLASS_IMAGE: return "CLASS_PTP/IMAGE";
case LIBUSB_CLASS_MASS_STORAGE: return "CLASS_MASS_STORAGE";
case LIBUSB_CLASS_HUB: return "CLASS_HUB";
case LIBUSB_CLASS_DATA: return "CLASS_DATA";
case LIBUSB_CLASS_SMART_CARD: return "CLASS_SMART_CARD";
case LIBUSB_CLASS_CONTENT_SECURITY: return "CLASS_CONTENT_SECURITY";
case LIBUSB_CLASS_VIDEO: return "CLASS_VIDEO";
case LIBUSB_CLASS_PERSONAL_HEALTHCARE: return "CLASS_PERSONAL_HEALTHCARE";
case LIBUSB_CLASS_DIAGNOSTIC_DEVICE: return "CLASS_DIAGNOSTIC_DEVICE";
case LIBUSB_CLASS_WIRELESS: return "CLASS_WIRELESS";
case LIBUSB_CLASS_APPLICATION: return "CLASS_APPLICATION";
case LIBUSB_CLASS_VENDOR_SPEC: return "CLASS_VENDOR_SPEC";
default: return "CLASS_UNKNOWN";
}
}
bool __fastcall CJanVNA2_comms::queueTxPacket(const PacketType packet_type, const void *data, const int data_size)
{
if (m_device.hdev == NULL)
return false;
if (data_size < 0)
return false;
if (data_size > 0 && !data)
return false;
const int size = sizeof(t_janvna2_header) + data_size + sizeof(uint32_t);
const int space = m_data_tx.buffer.size() - m_data_tx.index_wr;
if (space < size)
{
if (Form1)
Form1->pushCommMessage("tx: not enough buffer space");
return false;
}
std::vector <uint8_t> packet(size);
t_janvna2_header *p_header = (t_janvna2_header *)&packet[0];
uint8_t *p_data = &packet[sizeof(t_janvna2_header)];
uint32_t *p_crc = (uint32_t *)&packet[sizeof(t_janvna2_header) + data_size];
p_header->magic = header_magic;
p_header->total_length = size;
p_header->packet_type = (uint8_t)packet_type;
if (data_size > 0)
memcpy(p_data, data, data_size);
*p_crc = crc32(0x00000000, &packet[0], size - sizeof(uint32_t));
m_ack_timer.mark();
m_ack = false;
m_nack = false;
memcpy(&m_data_tx.buffer[m_data_tx.index_wr], &packet[0], size);
m_data_tx.index_wr += size;
#if 1
if (Form1)
{
String s;
s.printf(L"tx: [%s] %d %08X %d/%u {", packetTypeToStr((PacketType)p_header->packet_type).c_str(), size, *p_crc, m_data_tx.index_wr, m_data_tx.buffer.size());
for (unsigned int i = 0; i < packet.size(); i++)
s += IntToHex(packet[i], 2) + " ";
s = s.Trim() + "}";
Form1->pushCommMessage(s);
}
#endif
return true;
}
void __fastcall CJanVNA2_comms::sendRequestDeviceInfo()
{
queueTxPacket(PacketType::RequestDeviceInfo, NULL, 0);
}
void __fastcall CJanVNA2_comms::sendSweepSettings(const bool idle)
{
t_janvna2_sweepSettings sweep_settings;
const uint64_t maxFreq = m_device_info_ok ? m_device_info.limits_maxFreq : MAX_VNA_JANVNAV2_FREQ_HZ;
const uint64_t minFreq = m_device_info_ok ? m_device_info.limits_minFreq : MIN_VNA_JANVNAV2_FREQ_HZ;
if (m_own_sweep_settings.f_start > maxFreq) m_own_sweep_settings.f_start = maxFreq;
else
if (m_own_sweep_settings.f_start < minFreq) m_own_sweep_settings.f_start = minFreq;
if (m_own_sweep_settings.f_stop > maxFreq) m_own_sweep_settings.f_stop = maxFreq;
else
if (m_own_sweep_settings.f_stop < minFreq) m_own_sweep_settings.f_stop = minFreq;
const int maxPoints = m_device_info_ok ? m_device_info.limits_maxPoints : DEFAULT_JANVNAV2_MAX_POINTS;
const int minPoints = 2;
if (m_own_sweep_settings.points > maxPoints) m_own_sweep_settings.points = maxPoints;
else
if (m_own_sweep_settings.points < minPoints) m_own_sweep_settings.points = minPoints;
const uint32_t maxIFBW = m_device_info_ok ? m_device_info.limits_maxIFBW : DEFAULT_JANVNAV2_MAX_IF_BW;
const uint32_t minIFBW = m_device_info_ok ? m_device_info.limits_minIFBW : DEFAULT_JANVNAV2_MIN_IF_BW;
if (m_own_sweep_settings.if_bandwidth > maxIFBW) m_own_sweep_settings.if_bandwidth = maxIFBW;
else
if (m_own_sweep_settings.if_bandwidth < minIFBW) m_own_sweep_settings.if_bandwidth = minIFBW;
const int cdBm_max = m_device_info_ok ? m_device_info.limits_cdbm_max : IROUND(DEFAULT_JANVNAV2_MAX_CDBM * CDBM_SCALE);
const int cdBm_min = m_device_info_ok ? m_device_info.limits_cdbm_min : IROUND(DEFAULT_JANVNAV2_MIN_CDBM * CDBM_SCALE);
if (m_own_sweep_settings.cdbm_excitation > cdBm_max) m_own_sweep_settings.cdbm_excitation = cdBm_max;
else
if (m_own_sweep_settings.cdbm_excitation < cdBm_min) m_own_sweep_settings.cdbm_excitation = cdBm_min;
sweep_settings.f_start = m_own_sweep_settings.f_start;
sweep_settings.f_stop = m_own_sweep_settings.f_stop;
sweep_settings.points = m_own_sweep_settings.points;
sweep_settings.if_bandwidth = m_own_sweep_settings.if_bandwidth;
sweep_settings.cdbm_excitation = m_own_sweep_settings.cdbm_excitation;
sweep_settings.excitePort1 = idle ? 0 : m_own_sweep_settings.excitePort1; // '0' stops it sweeping
sweep_settings.excitePort2 = idle ? 0 : m_own_sweep_settings.excitePort2; // '0' stops it sweeping
sweep_settings.suppressPeaks = m_own_sweep_settings.suppressPeaks;
if (temp_buf.size() < sizeof(t_janvna2_sweepSettings))
temp_buf.resize(sizeof(t_janvna2_sweepSettings)); // just need to ensure the buffer is big enough to hold the final packet
Encoder e(&temp_buf[0], temp_buf.size());
e.add <uint64_t> (sweep_settings.f_start);
e.add <uint64_t> (sweep_settings.f_stop);
e.add <uint16_t> (sweep_settings.points);
e.add <uint32_t> (sweep_settings.if_bandwidth);
e.add <int16_t> (sweep_settings.cdbm_excitation);
e.addBits(sweep_settings.excitePort1, 1);
e.addBits(sweep_settings.excitePort2, 1);
e.addBits(sweep_settings.suppressPeaks, 1);
const int data_size = e.getSize();
queueTxPacket(PacketType::SweepSettings, &temp_buf[0], data_size);
data_unit.m_bandwidth_Hz = sweep_settings.if_bandwidth;
if (Form1)
{
String s;
s = "tx: start " + common.freqToStr1(sweep_settings.f_start, true, true, 6, false) + "Hz";
Form1->pushCommMessage(s);
s = "tx: stop " + common.freqToStr1(sweep_settings.f_stop, true, true, 6, false) + "Hz";
Form1->pushCommMessage(s);
Form1->printfCommMessage("tx: points %u", sweep_settings.points);
Form1->printfCommMessage("tx: if_bandwidth %u", sweep_settings.if_bandwidth);
Form1->printfCommMessage("tx: cdbm_excitation %d", sweep_settings.cdbm_excitation);
Form1->printfCommMessage("tx: excitePort1 %u", sweep_settings.excitePort1);
Form1->printfCommMessage("tx: excitePort2 %u", sweep_settings.excitePort2);