-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAcquisitionControllerLineDetect.cpp
More file actions
2518 lines (2339 loc) · 103 KB
/
AcquisitionControllerLineDetect.cpp
File metadata and controls
2518 lines (2339 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//#include "AcquisitionControllerLineDetect.h"
//#include <stdio.h>
//#include <iostream>
//#include <sstream>
//#include <cmath>
//#include <algorithm>
//#include <cstring> // For memset, memmove
//
//// --- Windows/Linux Compatibility ---
//#ifdef _WIN32
//#include <conio.h>
//#include <direct.h>
//#define GetCurrentDir _getcwd
//#else
//#include <unistd.h>
//#define GetCurrentDir getcwd
//#endif
//
//// ============================================================================
//// HELPER FUNCTIONS
//// ============================================================================
//
//int AcquisitionController::FindLagByXCorr(const std::vector<float>& x, const std::vector<float>& y, int maxLag)
//{
// int N = (int)x.size();
// if (N == 0 || (int)y.size() != N) return 0;
//
// float mean_x = 0.f, mean_y = 0.f;
// for (int i = 0; i < N; ++i) { mean_x += x[i]; mean_y += y[i]; }
// mean_x /= N; mean_y /= N;
//
// std::vector<float> xc(N), yc(N);
// for (int i = 0; i < N; ++i) { xc[i] = x[i] - mean_x; yc[i] = y[i] - mean_y; }
//
// int bestLag = 0;
// double bestScore = -1e308;
//
// for (int lag = -maxLag; lag <= maxLag; ++lag) {
// double num = 0.0, denom_x = 0.0, denom_y = 0.0;
// for (int i = 0; i < N; ++i) {
// int j = i + lag;
// if (j < 0 || j >= N) continue;
// num += (double)xc[i] * (double)yc[j];
// denom_x += (double)xc[i] * (double)xc[i];
// denom_y += (double)yc[j] * (double)yc[j];
// }
// double denom = sqrt(denom_x * denom_y) + 1e-20;
// double score = num / denom;
// if (score > bestScore) { bestScore = score; bestLag = lag; }
// }
// return bestLag;
//}
//
//// ============================================================================
//// CONSTRUCTOR & DESTRUCTOR
//// ============================================================================
//
//AcquisitionController::AcquisitionController() :
// m_isAcquiring(false),
// m_syncBoardHandle(nullptr),
// m_keepProcessing(true),
// // Algorithm Init
// m_linesReady(false),
// m_cb_write_head(0),
// m_lp_cb_lr_w(0),
// m_lp_cb_ud_r(0),
// m_lp_line_r(0),
// m_s_m1_cb_lp_r(0),
// m_top_peak_found(false),
// m_bot_peak_found(false),
// m_first_buffer(true),
// m_lastCalculatedLag(0)
//{
// // 1. Allocate Algorithm Buffers
// m_cb_M1.resize(CIRC_BUFFER_SIZE, 0.0);
// m_cb_M2.resize(CIRC_BUFFER_SIZE, 0.0);
// m_cb_Img.resize(CIRC_BUFFER_SIZE, 0.0);
//
// memset(m_lineParams.leftright, -1, sizeof(m_lineParams.leftright));
// memset(m_lineParams.updown, -1, sizeof(m_lineParams.updown));
// memset(m_lineParams.mean_m2, 0, sizeof(m_lineParams.mean_m2));
//
// // 2. Start Threads
// m_saveThread = std::thread(&AcquisitionController::SaveThreadLoop, this);
// m_detectorThread = std::thread(&AcquisitionController::DetectorThreadLoop, this);
// m_generatorThread = std::thread(&AcquisitionController::GeneratorThreadLoop, this);
//}
//
//AcquisitionController::~AcquisitionController()
//{
// m_isAcquiring = false;
// StopAcquisition();
//
// // Signal Threads to Die
// m_keepProcessing = false;
// m_saveQueueCV.notify_all();
// m_procQueueCV.notify_all();
// m_lineCV.notify_all();
//
// if (m_saveThread.joinable()) m_saveThread.join();
// if (m_detectorThread.joinable()) m_detectorThread.join();
// if (m_generatorThread.joinable()) m_generatorThread.join();
//
// if (m_syncBoardHandle) {
// sb_device_close(m_syncBoardHandle);
// m_syncBoardHandle = nullptr;
// }
//
// for (AlazarDigitizer* board : m_boards) delete board;
// m_boards.clear();
//}
//
//// ============================================================================
//// HARDWARE DISCOVERY & CONFIG
//// ============================================================================
//
//bool AcquisitionController::DiscoverBoards()
//{
// Log("Finding hardware...");
//
// // 1. SyncBoard
// if (m_syncBoardHandle == nullptr) {
// size_t count = 0;
// sb_get_device_count(&count);
// if (count > 0) {
// if (sb_device_open(0, &m_syncBoardHandle) == sb_rc_success)
// Log("Found and opened ATS Sync 4X1G.");
// else
// Log("Error: Failed to open ATS Sync 4X1G.");
// }
// else {
// Log("Warning: No ATS Sync 4X1G detected.");
// }
// }
//
// // 2. Digitizers
// U32 systemCount = AlazarNumOfSystems();
// if (systemCount < 1) {
// Log("Error: No AlazarTech systems found.");
// return false;
// }
//
// // CLEAN UP OLD BOARDS
// for (AlazarDigitizer* board : m_boards) delete board;
// m_boards.clear();
//
// U32 uniqueLogicalId = 1;
// for (U32 systemId = 1; systemId <= systemCount; systemId++) {
// U32 boardsInThisSystem = AlazarBoardsInSystemBySystemID(systemId);
// for (U32 boardId = 1; boardId <= boardsInThisSystem; boardId++) {
// HANDLE handle = AlazarGetBoardBySystemID(systemId, boardId);
// if (handle == NULL) continue;
// AlazarDigitizer* pBoard = new AlazarDigitizer(handle, systemId, uniqueLogicalId++);
// if (pBoard->QueryBoardInfo()) m_boards.push_back(pBoard);
// else delete pBoard;
// }
// }
//
// std::stringstream ss;
// ss << "Found " << m_boards.size() << " digitizer(s).";
// Log(ss.str());
// return m_boards.size() > 0;
//}
//
//bool AcquisitionController::ConfigureAllBoards(const BoardConfig& config)
//{
// if (m_boards.empty()) {
// Log("Error: No boards to configure.");
// return false;
// }
// m_currentConfig = config;
//
// // Configure Digitizers
// for (AlazarDigitizer* board : m_boards) {
// if (!board->ConfigureBoard(config)) return false;
// }
//
// // Configure SyncBoard
// if (m_syncBoardHandle) {
// sb_device_set_trigger_status(m_syncBoardHandle, sb_trigger_status_disabled);
// sb_clock_conf_t clock_conf;
//
// if (config.sampleRateId == SAMPLE_RATE_USER_DEF) {
// clock_conf.source = sb_clock_source_external;
// clock_conf.sample_rate_hz = 0;
// std::cout << "SyncBoard: External Clock" << std::endl;
// }
// else {
// clock_conf.source = sb_clock_source_internal;
// clock_conf.sample_rate_hz = (int64_t)config.sampleRateHz;
// }
//
// if (sb_device_set_clock(m_syncBoardHandle, clock_conf) != sb_rc_success) {
// Log("Error: Failed to configure SyncBoard clock.");
// return false;
// }
// }
// return true;
//}
//
//// ============================================================================
//// ACQUISITION LOOP (PRODUCER)
//// ============================================================================
//
//bool AcquisitionController::RunAcquisition(const AcquisitionConfig& config)
//{
// if (m_isAcquiring) { Log("Error: Acquisition already in progress."); return false; }
// m_isAcquiring = true;
// m_currentAcqConfig = config;
//
// // 1. Close Gate
// if (m_syncBoardHandle) sb_device_set_trigger_status(m_syncBoardHandle, sb_trigger_status_disabled);
//
// // 2. Setup Buffers
// U32 recordsPerBuffer = (config.admaMode == ADMA_CONTINUOUS_MODE) ? 1 : config.recordsPerBuffer;
// U32 samplesPerChannel = (config.admaMode == ADMA_CONTINUOUS_MODE) ? (config.samplesPerRecord / 4) : config.samplesPerRecord;
// U32 bytesPerBuffer = samplesPerChannel * 4 * 2 * recordsPerBuffer;
//
// if (config.saveData && !OpenDataFiles((U32)m_boards.size())) { m_isAcquiring = false; return false; }
//
// for (AlazarDigitizer* board : m_boards) {
// if (!board->AllocateBuffers(bytesPerBuffer)) { StopAcquisition(); return false; }
// if (!board->PrepareForAcquisition(config, CHANNEL_A | CHANNEL_B | CHANNEL_C | CHANNEL_D)) { StopAcquisition(); return false; }
// for (U32 i = 0; i < BUFFER_COUNT; i++) board->PostBuffer(i);
// if (!board->StartCapture()) { StopAcquisition(); return false; }
// }
//
// // 3. Open Gate
// if (m_syncBoardHandle) {
// Log("Enabling SyncBoard Trigger...");
// sb_device_set_trigger_status(m_syncBoardHandle, sb_trigger_status_enabled);
// }
//
// // 4. Acquisition Loop
// U32 buffersCompleted = 0;
// bool success = true;
//
// while (buffersCompleted < config.buffersPerAcquisition && success && m_isAcquiring)
// {
// U32 bufferIndex = buffersCompleted % BUFFER_COUNT;
//
// for (AlazarDigitizer* board : m_boards) {
// if (!board->WaitFordBuffer(bufferIndex, m_currentConfig.triggerTimeoutMS + 1000)) {
// success = false; break;
// }
//
// IO_BUFFER* pIoBuffer = board->GetBuffer(bufferIndex);
// if (!ProcessBufferData(board, (U16*)pIoBuffer->pBuffer, config)) {
// success = false; break;
// }
//
// if (!board->PostBuffer(bufferIndex)) {
// success = false; break;
// }
// }
//
// if (!success) break;
// buffersCompleted++;
// if (buffersCompleted % config.logInterval == 0) {
// std::stringstream ss; ss << "Captured " << buffersCompleted; Log(ss.str());
// }
// }
//
// Log("Acquisition complete.");
// StopAcquisition();
// return success;
//}
//
//// ============================================================================
//// DATA PROCESSING (Buffer -> Deinterleave -> Queues)
//// ============================================================================
//
//bool AcquisitionController::ProcessBufferData(AlazarDigitizer* board, U16* buffer, const AcquisitionConfig& config)
//{
// U32 recordsPerBuffer = (config.admaMode == ADMA_CONTINUOUS_MODE) ? 1 : config.recordsPerBuffer;
// U32 samplesPerChannel = (config.admaMode == ADMA_CONTINUOUS_MODE) ? (config.samplesPerRecord / 4) : config.samplesPerRecord;
// size_t totalSamples = samplesPerChannel * recordsPerBuffer;
//
// DataChunk chunk;
// chunk.boardId = board->GetBoardId();
// chunk.chA.resize(totalSamples);
// chunk.chB.resize(totalSamples);
// chunk.chC.resize(totalSamples);
// chunk.chD.resize(totalSamples);
//
// // De-interleave
// for (U32 r = 0; r < recordsPerBuffer; r++) {
// for (U32 s = 0; s < samplesPerChannel; s++) {
// U32 interleaved_index = (r * (samplesPerChannel * 4)) + (s * 4);
// U32 flat_index = r * samplesPerChannel + s;
// chunk.chA[flat_index] = buffer[interleaved_index + 0];
// chunk.chB[flat_index] = buffer[interleaved_index + 1];
// chunk.chC[flat_index] = buffer[interleaved_index + 2];
// chunk.chD[flat_index] = buffer[interleaved_index + 3];
// }
// }
//
// // Update GUI Scope (Map)
// if (config.processData) {
// std::lock_guard<std::mutex> lock(m_guiDataMutex);
// std::vector<float>& scope = m_latestScopeData[chunk.boardId];
// if (scope.size() != totalSamples) scope.resize(totalSamples);
//
// for (size_t i = 0; i < totalSamples; i++) {
// double code = chunk.chA[i] >> 2;
// scope[i] = (float)((code - 8191.5) / 8191.5);
// }
// }
//
// // Push to Save Queue
// if (config.saveData) {
// std::lock_guard<std::mutex> lock(m_saveQueueMutex);
// if (m_saveQueue.size() < 500) {
// m_saveQueue.push(chunk);
// m_saveQueueCV.notify_one();
// }
// }
//
// // Push to Processing Queue (New Peak Detection)
// if (config.processData) {
// std::lock_guard<std::mutex> lock(m_procQueueMutex);
// if (m_procQueue.size() < PROCESSING_QUEUE_MAX_SIZE) {
// m_procQueue.push(std::move(chunk));
// m_procQueueCV.notify_one();
// }
// }
//
// return true;
//}
//
//// ============================================================================
//// SYNC TEST (Blocking Manual Capture)
//// ============================================================================
//
//bool AcquisitionController::RunSyncTest(const BoardConfig& config)
//{
// if (m_isAcquiring) { Log("Busy."); return false; }
// if (m_boards.size() < 2) { Log("Error: Need 2 boards."); return false; }
// m_isAcquiring = true;
// Log("--- Starting Sync Test ---");
//
// // 1. Config SyncBoard
// if (m_syncBoardHandle) {
// sb_device_set_trigger_status(m_syncBoardHandle, sb_trigger_status_disabled);
// sb_clock_conf_t clock_conf;
// if (config.sampleRateId == SAMPLE_RATE_USER_DEF) {
// clock_conf.source = sb_clock_source_external;
// clock_conf.sample_rate_hz = 0;
// }
// else {
// clock_conf.source = sb_clock_source_internal;
// clock_conf.sample_rate_hz = (int64_t)config.sampleRateHz;
// }
// sb_device_set_clock(m_syncBoardHandle, clock_conf);
// }
//
// // 2. Config Digitizers
// for (AlazarDigitizer* board : m_boards) {
// if (!board->ConfigureBoard(config)) { StopAcquisition(); return false; }
// }
//
// // 3. One-Shot Setup
// AcquisitionConfig acqConfig = {};
// acqConfig.admaMode = ADMA_NPT;
// acqConfig.samplesPerRecord = 4096;
// acqConfig.recordsPerBuffer = 1;
// acqConfig.buffersPerAcquisition = 1;
//
// U32 bytesPerBuffer = 4096 * 4 * 2;
// for (AlazarDigitizer* board : m_boards) {
// board->AllocateBuffers(bytesPerBuffer);
// board->PrepareForAcquisition(acqConfig, CHANNEL_A | CHANNEL_B | CHANNEL_C | CHANNEL_D);
// board->PostBuffer(0);
// board->StartCapture();
// }
//
// Log("Waiting for trigger...");
// if (m_syncBoardHandle) sb_device_set_trigger_status(m_syncBoardHandle, sb_trigger_status_enabled);
//
// bool success = true;
// std::vector<std::vector<float>> snapshots;
//
// for (AlazarDigitizer* board : m_boards) {
// if (!board->WaitFordBuffer(0, config.triggerTimeoutMS + 1000)) {
// Log("Timeout Board " + std::to_string(board->GetBoardId()));
// success = false;
// }
// else {
// IO_BUFFER* pIoBuffer = board->GetBuffer(0);
// U16* buffer = (U16*)pIoBuffer->pBuffer;
// std::vector<float> chA_float(4096);
// for (int i = 0; i < 4096; i++) {
// double code = buffer[i * 4] >> 2;
// chA_float[i] = (float)((code - 8191.5) / 8191.5);
// }
// snapshots.push_back(chA_float);
// }
// }
//
// if (success && snapshots.size() >= 2) {
// m_syncSnapshot1 = snapshots[0];
// m_syncSnapshot2 = snapshots[1];
// m_lastCalculatedLag = FindLagByXCorr(m_syncSnapshot1, m_syncSnapshot2, 50);
// std::stringstream ss; ss << "Sync Test Complete. Lag: " << m_lastCalculatedLag;
// Log(ss.str());
// }
//
// StopAcquisition();
// return success;
//}
//
//// ============================================================================
//// THREAD 2: DETECTOR LOOP
//// ============================================================================
//
//void AcquisitionController::DetectorThreadLoop()
//{
// const int LR_SEARCH_AREA = 10;
// static double temp_ld_sig_m1[2 * LR_SEARCH_AREA + NUMBER_OF_SEGMENTS_PER_BUFFER];
// memset(temp_ld_sig_m1, 0, sizeof(temp_ld_sig_m1));
//
// while (m_keepProcessing)
// {
// DataChunk chunk;
// {
// std::unique_lock<std::mutex> lock(m_procQueueMutex);
// m_procQueueCV.wait(lock, [this] { return !m_procQueue.empty() || !m_keepProcessing; });
// if (!m_keepProcessing && m_procQueue.empty()) return;
// chunk = std::move(m_procQueue.front());
// m_procQueue.pop();
// }
//
// // Fill Circular Buffers
// size_t samples = chunk.chA.size();
// for (size_t i = 0; i < samples; i++) {
// size_t idx = (m_cb_write_head + i) % CIRC_BUFFER_SIZE;
// m_cb_Img[idx] = (double)chunk.chA[i];
// m_cb_M1[idx] = (double)chunk.chB[i];
// m_cb_M2[idx] = (double)chunk.chC[i];
// }
// m_cb_write_head = (m_cb_write_head + samples) % CIRC_BUFFER_SIZE;
//
// // Run Peak Detection
// memmove(&temp_ld_sig_m1, &temp_ld_sig_m1[NUMBER_OF_SEGMENTS_PER_BUFFER], sizeof(double) * (2 * LR_SEARCH_AREA));
//
// // Copy NEW data safely (handling wrap)
// size_t read_start = (m_s_m1_cb_lp_r * NUMBER_OF_SEGMENTS_PER_BUFFER);
// if (read_start + NUMBER_OF_SEGMENTS_PER_BUFFER <= CIRC_BUFFER_SIZE) {
// memcpy(&temp_ld_sig_m1[2 * LR_SEARCH_AREA], &m_cb_M1[read_start], sizeof(double) * NUMBER_OF_SEGMENTS_PER_BUFFER);
// }
// else {
// size_t p1 = CIRC_BUFFER_SIZE - read_start;
// size_t p2 = NUMBER_OF_SEGMENTS_PER_BUFFER - p1;
// memcpy(&temp_ld_sig_m1[2 * LR_SEARCH_AREA], &m_cb_M1[read_start], sizeof(double) * p1);
// memcpy(&temp_ld_sig_m1[2 * LR_SEARCH_AREA + p1], &m_cb_M1[0], sizeof(double) * p2);
// }
//
// bool new_lines = false;
// bool peak_detected;
//
// for (int i = LR_SEARCH_AREA; i < NUMBER_OF_SEGMENTS_PER_BUFFER + LR_SEARCH_AREA; i++) {
// if (m_first_buffer) { i += (2 * LR_SEARCH_AREA); m_first_buffer = false; }
//
// peak_detected = true;
// if (!m_top_peak_found) {
// // Find Max
// for (int j = -LR_SEARCH_AREA; j < LR_SEARCH_AREA + 1; j++) {
// if (temp_ld_sig_m1[i] < temp_ld_sig_m1[i + j]) { peak_detected = false; break; }
// }
// if (peak_detected) {
// m_top_peak_pos = i + m_s_m1_cb_lp_r * NUMBER_OF_SEGMENTS_PER_BUFFER - (2 * LR_SEARCH_AREA);
// if (m_top_peak_pos < 0) m_top_peak_pos += CIRC_BUFFER_SIZE;
// m_top_peak_found = true;
// if (m_bot_peak_found) {
// m_lineParams.start[m_lp_cb_lr_w] = m_bot_peak_pos;
// m_lineParams.end[m_lp_cb_lr_w] = m_top_peak_pos;
// m_lineParams.leftright[m_lp_cb_lr_w] = 0; // Forward
// m_lp_cb_lr_w = (m_lp_cb_lr_w + 1) % NUMBER_OF_LINE_PARAMS;
// }
// m_bot_peak_found = false;
// }
// }
// else {
// // Find Min
// for (int j = -LR_SEARCH_AREA; j < LR_SEARCH_AREA + 1; j++) {
// if (temp_ld_sig_m1[i] > temp_ld_sig_m1[i + j]) { peak_detected = false; break; }
// }
// if (peak_detected) {
// m_bot_peak_pos = i + m_s_m1_cb_lp_r * NUMBER_OF_SEGMENTS_PER_BUFFER - (2 * LR_SEARCH_AREA);
// if (m_bot_peak_pos < 0) m_bot_peak_pos += CIRC_BUFFER_SIZE;
// m_bot_peak_found = true;
// m_lineParams.start[m_lp_cb_lr_w] = m_top_peak_pos;
// m_lineParams.end[m_lp_cb_lr_w] = m_bot_peak_pos;
// m_lineParams.leftright[m_lp_cb_lr_w] = 1; // Backward
// m_lp_cb_lr_w = (m_lp_cb_lr_w + 1) % NUMBER_OF_LINE_PARAMS;
// m_top_peak_found = false;
// }
// }
// }
// m_s_m1_cb_lp_r = (m_s_m1_cb_lp_r + 1) % NUMBER_OF_SEGBUFFERS_IN_CIRCBUFFER;
//
// // Calc M2 Average
// int temp_w = m_lp_cb_lr_w;
// if (m_lp_cb_ud_r > temp_w) temp_w += NUMBER_OF_LINE_PARAMS;
// if (m_lp_cb_ud_r < temp_w) new_lines = true;
//
// for (int i = m_lp_cb_ud_r; i < temp_w; i++) {
// int imod = i % NUMBER_OF_LINE_PARAMS;
// int len = (m_lineParams.end[imod] >= m_lineParams.start[imod])
// ? (m_lineParams.end[imod] - m_lineParams.start[imod])
// : (m_lineParams.end[imod] + CIRC_BUFFER_SIZE - m_lineParams.start[imod]);
//
// double sum_m2 = 0;
// for (int k = 0; k < len; k++) {
// int idx = (m_lineParams.start[imod] + k) % CIRC_BUFFER_SIZE;
// sum_m2 += m_cb_M2[idx];
// }
// if (len > 0) m_lineParams.mean_m2[imod] = sum_m2 / len;
//
// // Up/Down logic
// int prev = (imod - 1 + NUMBER_OF_LINE_PARAMS) % NUMBER_OF_LINE_PARAMS;
// m_lineParams.updown[imod] = (m_lineParams.mean_m2[imod] > m_lineParams.mean_m2[prev]) ? 0 : 1;
// m_lp_cb_ud_r = (m_lp_cb_ud_r + 1) % NUMBER_OF_LINE_PARAMS;
// }
//
// if (new_lines) {
// std::unique_lock<std::mutex> ul(m_lineMutex);
// m_linesReady = true;
// m_lineCV.notify_one();
// }
// }
//}
//
//// ============================================================================
//// THREAD 3: GENERATOR LOOP
//// ============================================================================
//
//void AcquisitionController::GeneratorThreadLoop()
//{
// static std::vector<double> temp_line_data(NUMBER_OF_POINTS_PER_LINE);
//
// while (m_keepProcessing)
// {
// std::unique_lock<std::mutex> ul(m_lineMutex);
// m_lineCV.wait(ul, [this] { return m_linesReady || !m_keepProcessing; });
// m_linesReady = false;
// ul.unlock();
// if (!m_keepProcessing) return;
//
// long temp_w = m_lp_cb_lr_w;
// if (temp_w < m_lp_line_r) temp_w += NUMBER_OF_LINE_PARAMS;
//
// for (int i = m_lp_line_r; i < temp_w; i++) {
// int imod = i % NUMBER_OF_LINE_PARAMS;
// int len = (m_lineParams.end[imod] >= m_lineParams.start[imod])
// ? (m_lineParams.end[imod] - m_lineParams.start[imod])
// : (m_lineParams.end[imod] + CIRC_BUFFER_SIZE - m_lineParams.start[imod]);
//
// int copy_len = (len > NUMBER_OF_POINTS_PER_LINE) ? NUMBER_OF_POINTS_PER_LINE : len;
// if (copy_len <= 0) continue;
//
// temp_line_data.assign(NUMBER_OF_POINTS_PER_LINE, 0.0);
//
// // Fetch and Reverse if needed
// for (int k = 0; k < copy_len; k++) {
// int idx = (m_lineParams.start[imod] + k) % CIRC_BUFFER_SIZE;
// temp_line_data[k] = m_cb_Img[idx];
// }
// if (m_lineParams.leftright[imod] == 1) { // Backward
// std::reverse(temp_line_data.begin(), temp_line_data.begin() + copy_len);
// }
//
// // Map to Y
// static double m2_max = 38500;
// static double m2_min = 28500;
// double y_norm = (m_lineParams.mean_m2[imod] - m2_min) / (m2_max - m2_min);
// int y_idx = (int)(ceil(y_norm * NUMBER_OF_POINTS_PER_LINE) - 1);
// if (y_idx < 0) y_idx = 0;
// if (y_idx >= NUMBER_OF_POINTS_PER_LINE) y_idx = NUMBER_OF_POINTS_PER_LINE - 1;
//
// // Write to Image
// {
// std::lock_guard<std::mutex> lock(m_guiDataMutex);
// for (int x = 0; x < NUMBER_OF_POINTS_PER_LINE; x++) {
// m_finalImage[y_idx][x] = temp_line_data[x];
// }
// }
// }
// m_lp_line_r = temp_w % NUMBER_OF_LINE_PARAMS;
// }
//}
//
//// ============================================================================
//// PUBLIC GETTERS
//// ============================================================================
//
//void AcquisitionController::GetLatestImage(std::vector<std::vector<double>>& outImage) {
// std::lock_guard<std::mutex> lock(m_guiDataMutex);
// if (outImage.size() != NUMBER_OF_POINTS_PER_LINE)
// outImage.resize(NUMBER_OF_POINTS_PER_LINE, std::vector<double>(NUMBER_OF_POINTS_PER_LINE));
// for (int y = 0; y < NUMBER_OF_POINTS_PER_LINE; y++)
// for (int x = 0; x < NUMBER_OF_POINTS_PER_LINE; x++)
// outImage[y][x] = m_finalImage[y][x];
//}
//
//void AcquisitionController::GetLatestScopeData(std::vector<float>& data, U32 boardId) {
// std::lock_guard<std::mutex> lock(m_guiDataMutex);
// if (m_latestScopeData.count(boardId)) data = m_latestScopeData[boardId];
// else data.clear();
//}
//
//std::vector<std::string> AcquisitionController::GetLogMessages() { return m_logMessages; }
//void AcquisitionController::GetSyncSnapshot(std::vector<float>& b1, std::vector<float>& b2) { b1 = m_syncSnapshot1; b2 = m_syncSnapshot2; }
//
//// ============================================================================
//// CLEANUP & SAVING
//// ============================================================================
//
//void AcquisitionController::StopAcquisition() {
// if (m_syncBoardHandle) sb_device_set_trigger_status(m_syncBoardHandle, sb_trigger_status_disabled);
// for (auto b : m_boards) { b->AbortAcquisition(); b->FreeBuffers(); }
// CloseDataFiles();
// m_isAcquiring = false;
//}
//
//void AcquisitionController::SaveThreadLoop() {
// while (m_keepProcessing) {
// DataChunk chunk;
// {
// std::unique_lock<std::mutex> lock(m_saveQueueMutex);
// m_saveQueueCV.wait(lock, [this] { return !m_saveQueue.empty() || !m_keepProcessing; });
// if (!m_keepProcessing && m_saveQueue.empty()) return;
// chunk = std::move(m_saveQueue.front());
// m_saveQueue.pop();
// }
// int boardIdx = -1;
// if (chunk.boardId == 1) boardIdx = 0; else if (chunk.boardId == 2) boardIdx = 1;
//
// if (boardIdx >= 0) {
// int f = boardIdx * 4;
// if (f + 3 < m_fileStreams.size()) {
// if (!chunk.chA.empty() && m_fileStreams[f].is_open()) m_fileStreams[f].write((char*)chunk.chA.data(), chunk.chA.size() * 2);
// if (!chunk.chB.empty() && m_fileStreams[f + 1].is_open()) m_fileStreams[f + 1].write((char*)chunk.chB.data(), chunk.chB.size() * 2);
// if (!chunk.chC.empty() && m_fileStreams[f + 2].is_open()) m_fileStreams[f + 2].write((char*)chunk.chC.data(), chunk.chC.size() * 2);
// if (!chunk.chD.empty() && m_fileStreams[f + 3].is_open()) m_fileStreams[f + 3].write((char*)chunk.chD.data(), chunk.chD.size() * 2);
// }
// }
// }
//}
//
//bool AcquisitionController::OpenDataFiles(U32 boardCount) {
// char cwd[MAX_PATH]; if (!_getcwd(cwd, MAX_PATH)) return false; m_savePath = cwd;
// m_fileStreams.resize(boardCount * 4);
// char chs[] = { 'A','B','C','D' };
// for (U32 i = 0; i < boardCount; i++) {
// for (int c = 0; c < 4; c++) {
// std::stringstream ss; ss << m_savePath << "\\board" << m_boards[i]->GetBoardId() << "_ch" << chs[c] << ".bin";
// m_fileStreams[i * 4 + c].open(ss.str(), std::ios::binary);
// }
// }
// return true;
//}
//bool AcquisitionController::IsAcquiring() { return m_isAcquiring; }
//void AcquisitionController::CloseDataFiles() { for (auto& f : m_fileStreams) if (f.is_open()) f.close(); m_fileStreams.clear(); }
//void AcquisitionController::Log(std::string m) { std::cout << m << std::endl; m_logMessages.push_back(m); if (m_logMessages.size() > 100) m_logMessages.erase(m_logMessages.begin());
#include "AcquisitionControllerLineDetect.h"
#include <stdio.h>
#include <iostream>
#include <sstream>
#include <cmath>
#include <algorithm>
#include <cstring> // For memset, memmove
// --- Windows/Linux Compatibility ---
#ifdef _WIN32
#include <conio.h>
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
// ============================================================================
// HELPER: Cross Correlation (For Sync Test)
// ============================================================================
int AcquisitionController::FindLagByXCorr(const std::vector<float>& x, const std::vector<float>& y, int maxLag)
{
int N = (int)x.size();
if (N == 0 || (int)y.size() != N) return 0;
float mean_x = 0.f, mean_y = 0.f;
for (float f : x) mean_x += f; mean_x /= N;
for (float f : y) mean_y += f; mean_y /= N;
std::vector<float> xc(N), yc(N);
for (int i = 0; i < N; ++i) { xc[i] = x[i] - mean_x; yc[i] = y[i] - mean_y; }
int bestLag = 0;
double bestScore = -1e9;
for (int lag = -maxLag; lag <= maxLag; ++lag) {
double num = 0.0, denom_x = 0.0, denom_y = 0.0;
for (int i = 0; i < N; ++i) {
int j = i + lag;
if (j >= 0 && j < N) {
num += (double)xc[i] * (double)yc[j];
denom_x += (double)xc[i] * (double)xc[i];
denom_y += (double)yc[j] * (double)yc[j];
}
}
double denom = sqrt(denom_x * denom_y) + 1e-20;
double score = num / denom;
if (score > bestScore) { bestScore = score; bestLag = lag; }
}
return bestLag;
}
// ============================================================================
// CONSTRUCTOR & DESTRUCTOR
// ============================================================================
AcquisitionController::AcquisitionController() :
m_isAcquiring(false),
m_syncBoardHandle(nullptr),
m_keepProcessing(true),
// Algorithm Init
m_linesReady(false),
m_cb_write_head(0),
m_lp_cb_lr_w(0),
m_lp_cb_ud_r(0),
m_lp_line_r(0),
m_s_m1_cb_lp_r(0),
m_top_peak_found(false),
m_bot_peak_found(false),
m_first_buffer(true),
m_lastCalculatedLag(0)
{
// 1. Allocate Large Circular Buffers
m_cb_M1.resize(CIRC_BUFFER_SIZE, 0.0);
m_cb_M2.resize(CIRC_BUFFER_SIZE, 0.0);
m_cb_Img.resize(CIRC_BUFFER_SIZE, 0.0);
m_cb_D.resize(CIRC_BUFFER_SIZE, 0.0);
memset(m_lineParams.leftright, -1, sizeof(m_lineParams.leftright));
memset(m_lineParams.updown, -1, sizeof(m_lineParams.updown));
memset(m_lineParams.mean_m2, 0, sizeof(m_lineParams.mean_m2));
// 2. Start Threads
m_saveThread = std::thread(&AcquisitionController::SaveThreadLoop, this);
m_detectorThread = std::thread(&AcquisitionController::DetectorThreadLoop, this);
m_generatorThread = std::thread(&AcquisitionController::GeneratorThreadLoop, this);
}
AcquisitionController::~AcquisitionController()
{
m_isAcquiring = false;
StopAcquisition();
// Signal Threads to Die
m_keepProcessing = false;
m_saveQueueCV.notify_all();
m_procQueueCV.notify_all();
m_lineCV.notify_all();
// Join Threads
if (m_saveThread.joinable()) m_saveThread.join();
if (m_detectorThread.joinable()) m_detectorThread.join();
if (m_generatorThread.joinable()) m_generatorThread.join();
// Close Hardware
if (m_syncBoardHandle) {
sb_device_close(m_syncBoardHandle);
m_syncBoardHandle = nullptr;
}
for (AlazarDigitizer* board : m_boards) delete board;
m_boards.clear();
}
// ============================================================================
// HARDWARE DISCOVERY & CONFIG
// ============================================================================
bool AcquisitionController::DiscoverBoards()
{
Log("Finding hardware...");
// 1. SyncBoard Discovery
if (m_syncBoardHandle == nullptr) {
size_t count = 0;
sb_get_device_count(&count);
if (count > 0) {
if (sb_device_open(0, &m_syncBoardHandle) == sb_rc_success)
Log("Found and opened ATS Sync 4X1G.");
else
Log("Error: Failed to open ATS Sync 4X1G.");
}
else {
Log("Warning: No ATS Sync 4X1G detected.");
}
}
// 2. Digitizer Discovery
U32 systemCount = AlazarNumOfSystems();
if (systemCount < 1) {
Log("Error: No AlazarTech systems found.");
return false;
}
// Clean up old handles
for (AlazarDigitizer* board : m_boards) delete board;
m_boards.clear();
U32 uniqueLogicalId = 1;
for (U32 systemId = 1; systemId <= systemCount; systemId++) {
U32 boardsInThisSystem = AlazarBoardsInSystemBySystemID(systemId);
for (U32 boardId = 1; boardId <= boardsInThisSystem; boardId++) {
HANDLE handle = AlazarGetBoardBySystemID(systemId, boardId);
if (handle == NULL) continue;
AlazarDigitizer* pBoard = new AlazarDigitizer(handle, systemId, uniqueLogicalId++);
if (pBoard->QueryBoardInfo()) m_boards.push_back(pBoard);
else delete pBoard;
}
}
std::stringstream ss;
ss << "Found " << m_boards.size() << " digitizer(s).";
Log(ss.str());
return m_boards.size() > 0;
}
bool AcquisitionController::ConfigureAllBoards(const BoardConfig& config)
{
if (m_boards.empty()) {
Log("Error: No boards to configure.");
return false;
}
m_currentConfig = config;
// Configure Digitizers
for (AlazarDigitizer* board : m_boards) {
if (!board->ConfigureBoard(config)) return false;
}
// Configure SyncBoard Clock
if (m_syncBoardHandle) {
sb_device_set_trigger_status(m_syncBoardHandle, sb_trigger_status_disabled);
sb_clock_conf_t clock_conf;
if (config.sampleRateId == SAMPLE_RATE_USER_DEF) {
clock_conf.source = sb_clock_source_external;
clock_conf.sample_rate_hz = 0;
std::cout << "SyncBoard: External Clock Mode" << std::endl;
}
else {
clock_conf.source = sb_clock_source_internal;
clock_conf.sample_rate_hz = (int64_t)config.sampleRateHz;
}
if (sb_device_set_clock(m_syncBoardHandle, clock_conf) != sb_rc_success) {
Log("Error: Failed to configure SyncBoard clock.");
return false;
}
}
return true;
}
// ============================================================================
// ACQUISITION LOOP (PRODUCER)
// ============================================================================
bool AcquisitionController::RunAcquisition(const AcquisitionConfig& config)
{
if (m_isAcquiring) { Log("Error: Acquisition already in progress."); return false; }
m_isAcquiring = true;
m_currentAcqConfig = config;
// 1. Close Gate
if (m_syncBoardHandle) sb_device_set_trigger_status(m_syncBoardHandle, sb_trigger_status_disabled);
// 2. Setup Buffers
U32 recordsPerBuffer = (config.admaMode == ADMA_CONTINUOUS_MODE) ? 1 : config.recordsPerBuffer;
U32 samplesPerChannel = (config.admaMode == ADMA_CONTINUOUS_MODE) ? (config.samplesPerRecord / 4) : config.samplesPerRecord;
U32 bytesPerBuffer = samplesPerChannel * 4 * 2 * recordsPerBuffer;
if (config.saveData && !OpenDataFiles((U32)m_boards.size())) { m_isAcquiring = false; return false; }
for (AlazarDigitizer* board : m_boards) {
if (!board->AllocateBuffers(bytesPerBuffer)) { StopAcquisition(); return false; }
if (!board->PrepareForAcquisition(config, CHANNEL_A | CHANNEL_B | CHANNEL_C | CHANNEL_D)) { StopAcquisition(); return false; }
for (U32 i = 0; i < BUFFER_COUNT; i++) board->PostBuffer(i);
if (!board->StartCapture()) { StopAcquisition(); return false; }
}
// 3. Open Gate
if (m_syncBoardHandle) {
Log("Enabling SyncBoard Trigger...");
sb_device_set_trigger_status(m_syncBoardHandle, sb_trigger_status_enabled);
}
// 4. Acquisition Loop
U32 buffersCompleted = 0;
bool success = true;
while (buffersCompleted < config.buffersPerAcquisition && success && m_isAcquiring)
{
U32 bufferIndex = buffersCompleted % BUFFER_COUNT;
for (AlazarDigitizer* board : m_boards) {
if (!board->WaitFordBuffer(bufferIndex, m_currentConfig.triggerTimeoutMS + 1000)) {
success = false; break;
}
IO_BUFFER* pIoBuffer = board->GetBuffer(bufferIndex);
if (!ProcessBufferData(board, (U16*)pIoBuffer->pBuffer, config)) {
success = false; break;
}
if (!board->PostBuffer(bufferIndex)) {
success = false; break;
}
}
if (!success) break;
buffersCompleted++;
if (buffersCompleted % config.logInterval == 0) {
std::stringstream ss; ss << "Captured " << buffersCompleted; Log(ss.str());
}
}
Log("Acquisition complete.");
StopAcquisition();
return success;
}
// ============================================================================
// DATA PROCESSING (Buffer -> Deinterleave -> Queues)
//
//
// This function, ProcessBufferData, is the "engine room" of your acquisition software.
// It takes a raw block of memory filled with data from the Alazar card,
// organizes it into separate channels, and then dispatches it to three different destinations:
// the GUI display, the Disk Saver, and the Processing algorithm.
//
// ============================================================================
bool AcquisitionController::ProcessBufferData(AlazarDigitizer* board, U16* buffer, const AcquisitionConfig& config)
{
// if the data acquisition is continuous just treat it as one buffer else use the cofiguration that is given in the setting
U32 recordsPerBuffer = (config.admaMode == ADMA_CONTINUOUS_MODE) ? 1 : config.recordsPerBuffer;
U32 samplesPerChannel = (config.admaMode == ADMA_CONTINUOUS_MODE) ? (config.samplesPerRecord / 4) : config.samplesPerRecord;
size_t totalSamples = samplesPerChannel * recordsPerBuffer;
// assign memory space for each of the channels of the board
DataChunk chunk;
chunk.boardId = board->GetBoardId();
chunk.chA.resize(totalSamples);
chunk.chB.resize(totalSamples);
chunk.chC.resize(totalSamples);
chunk.chD.resize(totalSamples);
// De-interleave Logic
/*
interleaved_index: Calculates where the current sample lives in the raw buffer.
s * 4: Since data is packed as groups of 4 (A,B,C,D), we jump 4 spots to find the next sample for the same channel.
+ 0, + 1, etc.: Offsets to pick A, B, C, or D from that group.
flat_index: Calculates where to put the sample in the clean chunk vector (0, 1, 2, 3...)
*/
for (U32 r = 0; r < recordsPerBuffer; r++) {
for (U32 s = 0; s < samplesPerChannel; s++) {
U32 interleaved_index = (r * (samplesPerChannel * 4)) + (s * 4);
U32 flat_index = r * samplesPerChannel + s;
chunk.chA[flat_index] = buffer[interleaved_index + 0];
chunk.chB[flat_index] = buffer[interleaved_index + 1];
chunk.chC[flat_index] = buffer[interleaved_index + 2];
chunk.chD[flat_index] = buffer[interleaved_index + 3];
}
}
// --- UPDATE GUI SCOPE (MULTI-CHANNEL) ---
/*
std::lock_guard: This is Thread Safety. It prevents the GUI from reading the data while this function is writing to it,
which would cause the program to crash.BIT_SHIFT = 2: The ATS9440 is a 14-bit card,
but data is stored in a 16-bit container.The data is often "left-aligned" or padded.
This shift corrects the integer value.(codeA - 8191.5) / 8191.5: This converts the raw integer "code" into Volts
(normalized float between -1.0 and 1.0).
2^14 = 16384.Half of that is approx 8192.
This formula centers the data so 0V is roughly 0.0 in the float array.
*/
if (config.processData) {
std::lock_guard<std::mutex> lock(m_guiDataMutex);