forked from cculianu/SpikeGL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DAQ.cpp
executable file
·3241 lines (2943 loc) · 159 KB
/
DAQ.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
#include "SpikeGL.h"
#include "DAQ.h"
#ifdef HAVE_NIDAQmx
# include "NI/NIDAQmx.h"
# include "AOWriteThread.h"
#else
# ifndef FAKEDAQ
# define FAKEDAQ
# endif
# warning Not a real NI platform. All acquisition related functions are emulated!
#endif
#include <string.h>
#include <QString>
#include <QFile>
#include <QDir>
#include <QMessageBox>
#include <QApplication>
#include <QRegExp>
#include <QThread>
#include <QPair>
#include <QSet>
#include <QMutexLocker>
#include <QProcess>
#include <QProcessEnvironment>
#include <math.h>
#include "SampleBufQ.h"
#include "MainApp.h"
#include "FrameGrabber/FG_SpikeGL/FG_SpikeGL/XtCmd.h"
#define DAQmxErrChk(functionCall) do { if( DAQmxFailed(error=(functionCall)) ) { callStr = STR(functionCall); goto Error_Out; } } while (0)
#define DAQmxErrChkNoJump(functionCall) ( DAQmxFailed(error=(functionCall)) && (callStr = STR(functionCall)) )
bool excessiveDebug = false; /* from SpikeGL.h */
namespace DAQ
{
static bool noDaqErrPrint = false;
const unsigned ModeNumChansPerIntan[N_Modes] = {
15, 0, 15, 16, 16, 32, 16, 16, 32
};
const unsigned ModeNumIntans[N_Modes] = {
4, 0, 8, 2, 8, 8, 4, 6, 4
};
/// if empty map returned, no devices with AI!
DeviceRangeMap ProbeAllAIRanges()
{
DeviceRangeMap ret;
Range r;
#ifdef HAVE_NIDAQmx
double myDoubleArray[512];
for (int devnum = 1; devnum <= 16; ++devnum) {
memset(myDoubleArray, 0, sizeof(myDoubleArray));
QString dev( QString("Dev%1").arg(devnum) );
if (!DAQmxFailed(DAQmxGetDevAIVoltageRngs(dev.toUtf8().constData(), myDoubleArray, 512))) {
for (int i=0; i<512; i=i+2) {
r.min = myDoubleArray[i];
r.max = myDoubleArray[i+1];
if (r.min == r.max) break;
ret.insert(dev, r);
}
}
}
#else // !WINDOWS, emulate
r.min = -2.5;
r.max = 2.5;
ret.insert("Dev1", r);
r.min = -5.;
r.max = 5.;
ret.insert("Dev1", r);
r.min = -2.5;
r.max = 2.5;
ret.insert("Dev2", r);
r.min = -5.;
r.max = 5.;
ret.insert("Dev2", r);
#endif
return ret;
}
/// if empty map returned, no devices with AO!
DeviceRangeMap ProbeAllAORanges()
{
DeviceRangeMap ret;
Range r;
#ifdef HAVE_NIDAQmx
double myDoubleArray[512];
for (int devnum = 1; devnum <= 16; ++devnum) {
memset(myDoubleArray, 0, sizeof(myDoubleArray));
QString dev( QString("Dev%1").arg(devnum) );
if (!DAQmxFailed(DAQmxGetDevAOVoltageRngs(dev.toUtf8().constData(), myDoubleArray, 512))) {
for (int i=0; i<512; i=i+2) {
r.min = myDoubleArray[i];
r.max = myDoubleArray[i+1];
if (r.min == r.max) break;
ret.insert(dev, r);
}
}
}
#else // !WINDOWS, emulate
r.min = -2.5;
r.max = 2.5;
ret.insert("Dev1", r);
r.min = -5.;
r.max = 5.;
ret.insert("Dev1", r);
r.min = -2.5;
r.max = 2.5;
ret.insert("Dev2", r);
r.min = -5.;
r.max = 5.;
ret.insert("Dev2", r);
#endif
return ret;
}
DeviceChanMap ProbeAllAIChannels() {
bool savedPrt = noDaqErrPrint;
noDaqErrPrint = true;
DeviceChanMap ret;
for (int devnum = 1; devnum <= 16; ++devnum) {
QString dev( QString("Dev%1").arg(devnum) );
QStringList l = GetAIChans(dev);
if (!l.empty()) {
ret[dev] = l;
}
}
noDaqErrPrint = savedPrt;
return ret;
}
DeviceChanMap ProbeAllAOChannels() {
bool savedPrt = noDaqErrPrint;
noDaqErrPrint = true;
DeviceChanMap ret;
for (int devnum = 1; devnum <= 16; ++devnum) {
QString dev( QString("Dev%1").arg(devnum) );
QStringList l = GetAOChans(dev);
if (!l.empty()) {
ret[dev] = l;
}
}
noDaqErrPrint = savedPrt;
return ret;
}
#if HAVE_NIDAQmx
typedef int32 (__CFUNC *QueryFunc_t)(const char [], char *, uInt32);
static QStringList GetPhysChans(const QString &devname, QueryFunc_t queryFunc, const QString & fn = "")
{
int error;
const char *callStr = "";
char errBuff[2048];
char buf[65536] = "";
QString funcName = fn;
if (!funcName.length()) {
funcName = "??";
}
DAQmxErrChk(queryFunc(devname.toUtf8().constData(), buf, sizeof(buf)));
return QString(buf).split(QRegExp("\\s*,\\s*"), QString::SkipEmptyParts);
Error_Out:
if( DAQmxFailed(error) )
DAQmxGetExtendedErrorInfo(errBuff,2048);
if( DAQmxFailed(error) ) {
if (!noDaqErrPrint) {
Error() << "DAQmx Error: " << errBuff;
Error() << "DAQMxBase Call: " << funcName << "(" << devname << ",buf," << sizeof(buf) << ")";
}
}
return QStringList();
}
#endif
QStringList GetDOChans(const QString & devname)
{
#ifdef HAVE_NIDAQmx
return GetPhysChans(devname, DAQmxGetDevDOLines, "DAQmxGetDevDOLines");
#else // !HAVE_NIDAQmx, emulated, 1 chan
return QStringList(QString("%1/port0/line0").arg(devname));
#endif
}
QStringList GetAIChans(const QString & devname)
{
#ifdef HAVE_NIDAQmx
return GetPhysChans(devname, DAQmxGetDevAIPhysicalChans, "DAQmxGetDevAIPhysicalChans");
#else // !HAVE_NIDAQmx, emulated, 60 chans
QStringList ret;
if (devname == "Dev1") {
for (int i = 0; i < 60; ++i) {
ret.push_back(QString("%1/ai%2").arg(devname).arg(i));
}
}
if (devname == "Dev2") { // new "massive-channel" dev 2, for testing..
for (int i = 0; i < 4096; ++i) {
ret.push_back(QString("%1/ai%2").arg(devname).arg(i));
}
}
return ret;
#endif
}
QStringList GetAOChans(const QString & devname)
{
#ifdef HAVE_NIDAQmx
return GetPhysChans(devname, DAQmxGetDevAOPhysicalChans, "DAQmxGetDevAOPhysicalChans");
#else // !HAVE_NIDAQmx, emulated, 2 chans
QStringList ret;
if (devname == "Dev1" || devname == "Dev2") {
for (int i = 0; i < 2; ++i) {
ret.push_back(QString("%1/ao%2").arg(devname).arg(i));
}
}
return ret;
#endif
}
/// returns the number of physical channels in the AI subdevice for this device, or 0 if AI not supported on this device
unsigned GetNAIChans(const QString & devname)
{
return GetAIChans(devname).count();
}
/// returns the number of physical channels in the AO subdevice for this device, or 0 if AO not supported on this device
unsigned GetNAOChans(const QString & devname)
{
return GetAOChans(devname).count();
}
/// returns true iff the device supports AI simultaneous sampling
bool SupportsAISimultaneousSampling(const QString & devname)
{
#ifdef HAVE_NIDAQmx
bool32 ret = false;
if (DAQmxFailed(DAQmxGetDevAISimultaneousSamplingSupported(devname.toUtf8().constData(), &ret))) {
Error() << "Failed to query whether dev " << devname << " AI supports simultaneous sampling.";
}
return ret;
#else // !HAVE_NIDAQmx, emulated
(void)devname;
return true;
#endif
}
double MaximumSampleRate(const QString & dev, int nChans)
{
double ret = 1e6;
(void)dev; (void)nChans;
#ifdef HAVE_NIDAQmx
float64 val;
int32 e;
if (nChans <= 0) nChans = 1;
if (nChans == 1)
e = DAQmxGetDevAIMaxSingleChanRate(dev.toUtf8().constData(), &val);
else
e = DAQmxGetDevAIMaxMultiChanRate(dev.toUtf8().constData(), &val);
if (DAQmxFailed(e)) {
Error() << "Failed to query maximum sample rate for dev " << dev << ".";
} else {
ret = val;
if (nChans > 1 && !SupportsAISimultaneousSampling(dev)) {
ret = ret / nChans;
}
}
#endif
return ret;
}
double MinimumSampleRate(const QString & dev)
{
double ret = 10.;
(void)dev;
#ifdef HAVE_NIDAQmx
float64 val;
if (DAQmxFailed(DAQmxGetDevAIMinRate(dev.toUtf8().constData(), &val))) {
Error() << "Failed to query minimum sample rate for dev " << dev << ".";
} else {
ret = val;
}
#endif
return ret;
}
QString GetProductName(const QString &dev)
{
if (dev.compare("USB_Bug3", Qt::CaseInsensitive)==0) return "Intan USB Telemetry Receiver (Bug3)";
if (dev.compare("Framegrabber", Qt::CaseInsensitive)==0) return "XtiumCL PX4 + Camerialink to Intan";
#ifdef HAVE_NIDAQmx
char buf[65536] = "Unknown";
if (DAQmxFailed(DAQmxGetDevProductType(dev.toUtf8().constData(), buf, sizeof(buf)))) {
Error() << "Failed to query product name for dev " << dev << ".";
}
// else..
return buf;
#else
(void)dev;
return dev == "Dev2" ? "FakeDAQMassiveTest" : "FakeDAQ";
#endif
}
NITask::NITask(const Params & acqParams, QObject *p, const PagedScanReader &psr, const QString & taskDescriptiveName)
: Task(p,taskDescriptiveName, psr), pleaseStop(false), params(acqParams),
fast_settle(0), muxMode(false), aoWriteThr(0),
#ifdef HAVE_NIDAQmx
taskHandle(0), taskHandle2(0),
#endif
clockSource(0), error(0), callStr(0)
{
errBuff[0] = 0;
setDO(false); // assert DO is low when stopped...
}
NITask::~NITask() {
stop();
if (numChans() > 0)
Debug() << "NITask `" << objectName() << "' deleted after processing " << totalRead/u64(numChans()) << " scans.";
}
void NITask::stop()
{
if (isRunning() && !pleaseStop) {
pleaseStop = true;
wait();
pleaseStop = false;
}
setDO(false); // assert DO low when stopped...
}
void NITask::overflowWarning()
{
Warning() << "DAQ Task sample buffer overflow! Dropping a buffer!";
emit(bufferOverrun());
#ifdef FAKEDAQ
static int overflowct = 0;
if (++overflowct == 5) {
emit(taskError("Overflow limit exceeded"));
}
#endif
}
/* static */
int NITask::computeTaskReadFreq(double srate_in) {
int srate = ceil(srate_in); (void)srate;
return DEF_TASK_READ_FREQ_HZ;
//if (ll) return DEF_TASK_READ_FREQ_HZ_ * 3;
//return DEF_TASK_READ_FREQ_HZ_;
}
#ifdef FAKEDAQ
}// end namespace DAQ
#include <stdlib.h>
namespace DAQ
{
void NITask::daqThr()
{
static QString fname(":/fakedaq/fakedaqdata.bin");
char *e;
if ((e=getenv("FAKEDAQ"))) {
fname = e;
} else {
Warning() << "FAKEDAQ env var not found, using " << fname << " as filename instead";
}
QFile f(fname);
if (!f.open(QIODevice::ReadOnly)) {
QString err = QString("Could not open %1!").arg(fname);
Error() << err;
emit taskError(err);
return;
}
std::vector<int16> data;
const double onePd = writer.scansPerPage()/params.srate;
while (!pleaseStop) {
double ts = getTime();
data.resize(unsigned(params.nVAIChans*writer.scansPerPage()));
qint64 nread = f.read((char *)&data[0], data.size()*sizeof(int16));
if (nread != qint64(data.size()*sizeof(int16))) {
f.seek(0);
} else if (nread > 0) {
nread /= sizeof(int16);
data.resize(nread);
if (!totalRead) emit(gotFirstScan());
doFinalDemuxAndEnqueue(data);
totalReadMut.lock();
totalRead += nread;
totalReadMut.unlock();
}
int sleeptime = int(onePd*1e6) - int((getTime()-ts)*1e6);
if (sleeptime > 0)
usleep(sleeptime);
else
Warning() << "FakeDAQ NITask::daqThr(). sleeptime (" << sleeptime << ") is less than 0!";
}
}
void NITask::setDO(bool onoff)
{
Warning() << "setDO(" << (onoff ? "on" : "off") << ") called (unimplemented in FAKEDAQ mode)";
}
void NITask::requestFastSettle()
{
Warning() << "requestFastSettle() unimplemented for FAKEDAQ mode!";
emit(fastSettleCompleted());
}
#else // !FAKEDAQ
void AOWriteThread::run()
{
if (old2Delete) {
delete old2Delete;
old2Delete = 0;
}
const Params & p(params);
TaskHandle taskHandle(0);
int32 error = 0;
char errBuff[2048]={'\0'};
const char *callStr = "";
unsigned bufferSizeCS = p.aoBufferSizeCS;
if (p.aoBufferSizeCS < p.aiBufferSizeCS) {
Warning() << "AOWrite thread AO buf=" << (p.aoBufferSizeCS*10.) << " is less than AI buf=" << (p.aiBufferSizeCS*10.) << ", this is unsupported. Forcing AO buffer size to " << (p.aiBufferSizeCS*10.);
bufferSizeCS = p.aiBufferSizeCS;
}
int32 aoSamplesPerChan( ceil(ceil(p.aoSrate) * ((bufferSizeCS/100.0)+0.005/*<--ugly fudge to make sure AO buffer size is always 5ms bigger than AI! Argh!*/)) );
while (aoSamplesPerChan % 2)
++aoSamplesPerChan; // force aoSamplesPerChan to be multiple of 2? I forget why!!!!
const int32 aoChansSize = p.aoChannels.size();
unsigned aoBufferSize(aoSamplesPerChan * aoChansSize);
const float64 aoMin = p.aoRange.min;
const float64 aoMax = p.aoRange.max;
const float64 aoTimeout = DAQ_TIMEOUT*2.;
unsigned aoWriteCt = 0;
pleaseStop = false;
//std::vector<int16> leftOver;
// XXX diags..
int nWritesAvg = 0, nWritesAvgMax = 10;
double writeSpeedAvg = 0.;
double tLastData = -1.0, inpDataRate=0., outDataRate=0.;
std::vector<int16> sampsOrig, samps;
Util::Resampler resampler(double(p.aoSrate) / double(p.srate) /* HACK FIXME * 2.0*/, aoChansSize);
int nodatact = 0;
int daqerrct = 0;
while (daqerrct < 3 && !pleaseStop) {
bool break2 = false;
DAQmxErrChk (DAQmxCreateTask("",&taskHandle));
DAQmxErrChk (DAQmxCreateAOVoltageChan(taskHandle,aoChanString.toUtf8().constData(),"",aoMin,aoMax,DAQmx_Val_Volts,NULL));
DAQmxErrChk (DAQmxCfgSampClkTiming(taskHandle,p.aoClock.toUtf8().constData(),p.aoSrate,DAQmx_Val_Rising,DAQmx_Val_ContSamps,/*aoBufferSize*/aoSamplesPerChan/*0*/));
DAQmxErrChk (DAQmxCfgOutputBuffer(taskHandle,aoSamplesPerChan));
DAQmxSetWriteRegenMode(taskHandle, DAQmx_Val_DoNotAllowRegen);
DAQmxSetImplicitUnderflowBehavior(taskHandle, DAQmx_Val_PauseUntilDataAvailable);
Debug() << "AOWrite thread started.";
while (!pleaseStop && !break2) {
u64 sampCount;
if (!dequeueBuffer(sampsOrig, sampCount) || !sampsOrig.size()) {
if (dequeueWarnThresh > 0 && ++nodatact > dequeueWarnThresh) {
nodatact = 0;
if (aoWriteCt) Warning() << "AOWrite thread failed to dequeue any sample data " << dequeueWarnThresh << " times in a row. Clocks drifting?";
// failed to dequeue data, insert silence to keep ao writer going otherwise we get underruns!
/* sampsOrig.clear();
samps.clear();
samps.resize(p.aoSrate * 0.002 * aoChansSize, lastSamp); // insert 2ms of silence?
*/
} else {
msleep(2);
continue;
}
} else { // normal operation..
double now = getTime();
nodatact = 0;
QString err = resampler.resample(sampsOrig, samps);
if (tLastData > 0.0) {
inpDataRate = (double(sampsOrig.size())/aoChansSize)/(now-tLastData);
outDataRate = (double(samps.size())/aoChansSize)/(now-tLastData);
}
tLastData = now;
if (err.length()) {
Error() << "AOWrite thread resampler error: " << err;
continue;
}
}
//if (leftOver.size()) samps.insert(samps.begin(), leftOver.begin(), leftOver.end());
//leftOver.clear();
unsigned sampsSize = (unsigned)samps.size(), rem = sampsSize % aoChansSize;
if (rem) {
Warning() << "AOWrite thread got scan data that has invalid size.. throwing away last " << rem << " chans (writect " << aoWriteCt << ")";
//sampsSize -= rem;
//leftOver.reserve(rem);
//leftOver.insert(leftOver.begin(), samps.begin()+sampsSize, samps.end());
}
unsigned sampIdx = 0;
while (sampIdx < sampsSize && !pleaseStop) {
int32 nScansToWrite = (sampsSize-sampIdx)/aoChansSize;
int32 nScansWritten = 0;
if (nScansToWrite > aoSamplesPerChan) {
Warning() << "AOWrite thread got " << nScansToWrite << " input scans but AO Buffer size is only " << aoSamplesPerChan << " scans.. increase AO buffer size in UI!";
}
/*if (nScansToWrite > aoSamplesPerChan)
nScansToWrite = aoSamplesPerChan;
else if (!aoWriteCt && nScansToWrite < aoSamplesPerChan) { leftOver.insert(leftOver.end(), samps.begin()+sampIdx, samps.end());
break;
}*/
double t0 = getTime();
if ( DAQmxErrChkNoJump(DAQmxWriteBinaryI16(taskHandle, nScansToWrite, 1, aoTimeout, DAQmx_Val_GroupByScanNumber, &samps[sampIdx], &nScansWritten, NULL)) )
{
break2 = true;
if (++daqerrct < 3) {
DAQmxGetExtendedErrorInfo(errBuff,2048);
Debug() << "AOWrite thread error on write: \"" << errBuff << "\". AOWrite retrying since errct < 3.";
DAQmxStopTask(taskHandle);
DAQmxClearTask(taskHandle);
taskHandle = 0;
} else {
Debug() << "AOWrite error on write and not retrying since errct >= 3!";
}
break;
} else if (daqerrct > 0) --daqerrct;
// test code to test AI->AO delay in software, in a very rough way.. remove if you want.
if (excessiveDebug) {
u64 scanCt = (sampsOrig.size() + sampCount)/aoChansSize,
gScanCt = mainApp()->currentDAQScan();
Debug() << "AO got scan:" << scanCt << " (global scan: " << gScanCt << "). delay=~" << int32( (gScanCt-scanCt) / double(p.srate) * 1000.) << "ms";
}
const double tWrite(getTime()-t0);
if (nScansWritten >= 0 && nScansWritten < nScansToWrite) {
rem = (nScansToWrite - nScansWritten) * aoChansSize;
Debug() << "Partial write: nScansWritten=" << nScansWritten << " nScansToWrite=" << nScansToWrite << ", queueing for next write..";
//leftOver.insert(leftOver.end(), samps.begin()+sampIdx+nScansWritten, samps.end());
break;
} else if (nScansWritten != nScansToWrite) {
Error() << "nScansWritten (" << nScansWritten << ") != nScansToWrite (" << nScansToWrite << ")";
break;
}
if (++nWritesAvg > nWritesAvgMax) nWritesAvg = nWritesAvgMax;
writeSpeedAvg -= writeSpeedAvg/nWritesAvg;
double spd;
writeSpeedAvg += (spd = double(nScansWritten)/tWrite ) / double(nWritesAvg);
if (tWrite > 0.250) {
Debug() << "AOWrite #" << aoWriteCt << " " << nScansWritten << " scans " << aoChansSize << " chans" << " (bufsize=" << aoBufferSize << ") took: " << tWrite << " secs";
}
if (excessiveDebug) Debug() << "AOWrite speed " << spd << " Hz avg speed " << writeSpeedAvg << " Hz" << " (" << nScansWritten << " scans) buffer fill " << ((dataQueueSize()/double(dataQueueMaxSize))*100.0) << "% inprate->outrate:" << inpDataRate << "->" << outDataRate << "(?) Hz";
++aoWriteCt;
sampIdx += nScansWritten*aoChansSize;
}
}
}
Error_Out:
if ( DAQmxFailed(error) )
DAQmxGetExtendedErrorInfo(errBuff,2048);
if ( taskHandle != 0) {
DAQmxStopTask(taskHandle);
DAQmxClearTask(taskHandle);
taskHandle = 0;
}
if( DAQmxFailed(error) ) {
QString e;
e.sprintf("DAQmx Error: %s\nDAQMxBase Call: %s",errBuff, callStr);
if (!noDaqErrPrint) {
Error() << e;
}
emit daqError(e);
}
Debug() << "AOWrite thread ended after " << aoWriteCt << " chunks written.";
}
/* static */
void NITask::recomputeAOAITab(QVector<QPair<int, int> > & aoAITab, QString & aoChan, const Params & p)
{
aoAITab.clear();
aoChan.clear();
if (p.aoPassthru) {
const QVector<QString> aoChanStrings ((ProbeAllAOChannels()[p.aoDev]).toVector());
const int aoNChans = aoChanStrings.size();
QSet<int> seenAO;
aoAITab.reserve(aoNChans > 0 ? aoNChans : 0); ///< map of AO chan id to virtual AI chan id
for (int i = 0; i < aoNChans; ++i) {
if (p.aoPassthruMap.contains(i) && !seenAO.contains(i)) {
aoAITab.push_back(QPair<int, int>(i,p.aoPassthruMap[i]));
seenAO.insert(i);
//build chanspec string for AI
aoChan.append(QString("%1%2").arg(aoChan.length() ? ", " : "").arg(aoChanStrings[i]));
}
}
}
}
static inline int mapNewChanIdToPreJuly2011ChanId(int c, DAQ::Mode m, bool dualDevMode) {
const int intan = c/DAQ::ModeNumChansPerIntan[m], chan = c % DAQ::ModeNumChansPerIntan[m];
return chan*(DAQ::ModeNumIntans[m] * (dualDevMode ? 2 : 1)) + intan;
}
bool NITask::createAITasks()
{
const DAQ::Params & p(params);
if ( DAQmxErrChkNoJump (DAQmxCreateTask("",&taskHandle))
|| DAQmxErrChkNoJump (DAQmxCreateAIVoltageChan(taskHandle,chan.toUtf8().constData(),"",(int)p.aiTerm,min,max,DAQmx_Val_Volts,NULL))
|| DAQmxErrChkNoJump (DAQmxCfgSampClkTiming(taskHandle,clockSource,sampleRate,DAQmx_Val_Rising,DAQmx_Val_ContSamps,bufferSize))
|| DAQmxErrChkNoJump (DAQmxTaskControl(taskHandle, DAQmx_Val_Task_Commit)) )
return false;
if ( DAQmxErrChkNoJump(DAQmxSetAIMax(taskHandle,chan.toUtf8().constData(),max)) )
return false;
if ( DAQmxErrChkNoJump(DAQmxSetAIMin(taskHandle,chan.toUtf8().constData(),min)) )
return false;
//DAQmxErrChk (DAQmxCfgInputBuffer(taskHandle,dmaBufSize)); //use a 1,000,000 sample DMA buffer per channel
//DAQmxErrChk (DAQmxRegisterEveryNSamplesEvent (taskHandle, DAQmx_Val_Acquired_Into_Buffer, everyNSamples, 0, DAQPvt::everyNSamples_func, this));
if (p.dualDevMode) {
const char * clockSource2 = clockSource;//*/"PFI2";
//#ifdef DEBUG
// clockSource2 = clockSource;
//#endif
if ( DAQmxErrChkNoJump (DAQmxCreateTask((QString("")+QString::number(qrand())).toUtf8(),&taskHandle2))
|| DAQmxErrChkNoJump (DAQmxCreateAIVoltageChan(taskHandle2,chan2.toUtf8().constData(),"",(int)p.aiTerm,min,max,DAQmx_Val_Volts,NULL))
|| DAQmxErrChkNoJump (DAQmxCfgSampClkTiming(taskHandle2,clockSource2,sampleRate,DAQmx_Val_Rising,DAQmx_Val_ContSamps,bufferSize2))
|| DAQmxErrChkNoJump (DAQmxTaskControl(taskHandle2, DAQmx_Val_Task_Commit)) )
return false;
}
return true;
}
bool NITask::startAITasks()
{
const DAQ::Params & p(params);
if ( DAQmxErrChkNoJump(DAQmxStartTask(taskHandle)) )
return false;
if (p.dualDevMode) {
if ( DAQmxErrChkNoJump(DAQmxStartTask(taskHandle2)) )
return false;
}
return true;
}
void NITask::destroyAITasks()
{
if ( taskHandle != 0) {
DAQmxStopTask (taskHandle);
DAQmxClearTask (taskHandle);
taskHandle = 0;
}
if ( taskHandle2 != 0) {
DAQmxStopTask (taskHandle2);
DAQmxClearTask (taskHandle2);
taskHandle2 = 0;
}
}
// returns 0 if all ok, -1 if unrecoverable error, 1 if had "buffer overflow error" and tried did acq restart..
int NITask::doAIRead(TaskHandle th, u64 samplesPerChan, std::vector<int16> & data, unsigned long oldS, int32 pointsToRead, int32 & pointsRead)
{
const DAQ::Params & p(params);
if (DAQmxErrChkNoJump (DAQmxReadBinaryI16(th,samplesPerChan,timeout,DAQmx_Val_GroupByScanNumber,&data[oldS],pointsToRead,&pointsRead,NULL))) {
Debug() << "Got error number on AI read: " << error;
if (p.autoRetryOnAIOverrun && acceptableRetryErrors.contains(error)) {
if (nReadRetries > 2) {
Error() << "Auto-Retry of AI read failed due to too many consecutive overrun errors!";
return -1;
}
Debug() << "Error ok? Ignoring/Retrying read.. ";
double t0 = Util::getTime();
static const double fixedRestartTime = 0.050;
destroyAITasks();
// XXX TODO FIXME -- figure out if we need to settle here for some time to restart the task
if (muxMode) { setDO(false); /*QThread::msleep(100);*/ }
if ( !createAITasks() || !startAITasks() )
return -1;
const double tleft = fixedRestartTime - (Util::getTime()-t0);
if (tleft > 0.0) QThread::usleep(tleft*1e6);
if (muxMode) setDO(true);
Debug() << "Restart elapsed time: " << ((Util::getTime()-t0)*1000.0) << "ms";
++nReadRetries;
fudgeDataDueToReadRetry();
return 1;
} else
return -1;
}
nReadRetries = 0;
return 0;
}
void NITask::fudgeDataDueToReadRetry()
{
const DAQ::Params & p (params);
const double tNow = Util::getTime();
const double tFudge = tNow - lastEnq;
u64 samps2Fudge = static_cast<u64>(p.srate * tFudge) * static_cast<u64>(p.nVAIChans);
Debug() << "Fudging " << (tFudge*1e3) << "ms worth of data (" << samps2Fudge << " samples)..";
std::vector<int16> dummy(p.nVAIChans,0x7fff);
while (samps2Fudge) {
if (!writer.write(&dummy[0],1))
Error() << "PagedScanWriter::write() returned false in NITask::fudgeDataDueToReadRetry()! Fixme!";
samps2Fudge -= p.nVAIChans;
}
if (aoWriteThr) {
dummy.clear();
u64 aosamps2fudge = static_cast<u64>(p.srate * tFudge) * static_cast<u64>(aoAITab.size());
Debug() << "Fudging " << (tFudge*1e3) << "ms worth of AO data as well (" << aosamps2fudge << " samples)..";
aoWriteThr->enqueueBuffer(dummy, aoSampCount, true, aosamps2fudge);
aoSampCount += aosamps2fudge;
}
totalRead += samps2Fudge;
lastEnq = tNow;
}
void NITask::daqThr()
{
// Task parameters
error = 0;
taskHandle = 0, taskHandle2 = 0;
errBuff[0]='\0';
callStr = "";
double startTime, lastReadTime;
const Params & p (params);
// used for auto-retry code .. the following status codes are accepted for auto-retry, if p.autoRetryOnAIOverrun is true
acceptableRetryErrors.clear(); acceptableRetryErrors << -200279 << -200284;
nReadRetries = 0;
// Channel spec string for NI driver
chan = "", chan2 = "";
QString aoChan = "";
{
const QVector<QString> aiChanStrings ((ProbeAllAIChannels()[p.dev]).toVector());
//build chanspec string for aiChanStrings..
for (QVector<unsigned>::const_iterator it = p.aiChannels.begin(); it != p.aiChannels.end(); ++it)
{
chan.append(QString("%1%2").arg(chan.length() ? ", " : "").arg(aiChanStrings[*it]));
}
}
if (p.dualDevMode) {
const QVector<QString> aiChanStrings2 ((ProbeAllAIChannels()[p.dev2]).toVector());
//build chanspec string for aiChanStrings..
for (QVector<unsigned>::const_iterator it = p.aiChannels2.begin(); it != p.aiChannels2.end(); ++it)
{
chan2.append(QString("%1%2").arg(chan2.length() ? ", " : "").arg(aiChanStrings2[*it]));
}
}
const int nChans = p.aiChannels.size(), nChans2 = p.dualDevMode ? p.aiChannels2.size() : 0;
min = p.range.min;
max = p.range.max;
const int nExtraChans1 = p.nExtraChans1, nExtraChans2 = p.dualDevMode ? p.nExtraChans2 : 0;
// Params dependent on mode and DAQ::Params, etc
clockSource = p.extClock ? "PFI2" : "OnboardClock"; ///< TODO: make extClock possibly be something other than PFI2
sampleRate = p.srate;
timeout = DAQ_TIMEOUT;
const int NCHANS1 = p.nVAIChans1, NCHANS2 = p.dualDevMode ? p.nVAIChans2 : 0;
muxMode = (p.mode != AIRegular);
int nscans_per_mux_scan = 1;
aoWriteThr = 0;
if (muxMode) {
const int mux_chans_per_phys = ModeNumChansPerIntan[p.mode];
sampleRate *= double(mux_chans_per_phys);
nscans_per_mux_scan = mux_chans_per_phys;
/*if (!p.extClock) {
/// Aieeeee! Need ext clock for demux mode!
QString e("Aieeeee! Need to use an EXTERNAL clock for DEMUX mode!");
Error() << e;
emit taskError(e);
return;
}
*/
}
recomputeAOAITab(aoAITab, aoChan, p);
const int task_read_freq_hz = computeTaskReadFreq(p.srate);
int fudged_srate = ceil(sampleRate);
while ((fudged_srate/task_read_freq_hz) % 2) // samples per chan needs to be a multiple of 2
++fudged_srate;
bufferSize = u64(fudged_srate*nChans);
bufferSize2 = u64(fudged_srate*nChans2);
if (p.lowLatency)
bufferSize /= (task_read_freq_hz); ///< 1/10th sec per read
else
bufferSize *= double(p.aiBufferSizeCS) / 100.0; ///< otherwise just use user spec..
if (p.dualDevMode) {
if (p.lowLatency)
bufferSize2 /= (task_read_freq_hz); ///< 1/10th sec per read
else
bufferSize2 *= double(p.aiBufferSizeCS) / 100.0; ///< otherwise just use user spec..
}
if (bufferSize < NCHANS1) bufferSize = NCHANS1;
if (bufferSize2 < NCHANS2) bufferSize2 = NCHANS2;
/* if (bufferSize * task_read_freq_hz != u64(fudged_srate*nChans)) // make sure buffersize is on scan boundary?
bufferSize += task_read_freq_hz - u64(fudged_srate*nChans)%task_read_freq_hz; */
if (bufferSize % nChans) // make sure buffer is on a scan boundary!
bufferSize += nChans - (bufferSize%nChans);
if (p.dualDevMode && bufferSize2 % nChans2) // make sure buffer is on a scan boundary!
bufferSize2 += nChans2 - (bufferSize2%nChans2);
//const u64 dmaBufSize = p.lowLatency ? u64(100000) : u64(1000000); /// 1000000 sample DMA buffer per chan?
const u64 samplesPerChan = bufferSize/nChans, samplesPerChan2 = (nChans2 ? bufferSize2/nChans2 : 0);
// Timing parameters
int32 pointsRead=0, pointsRead2=0;
const int32 pointsToRead = bufferSize, pointsToRead2 = bufferSize2;
std::vector<int16> data, data2, leftOver, leftOver2, aoData;
QMap<unsigned, unsigned> saved_aoPassthruMap = p.aoPassthruMap;
QString saved_aoDev = p.aoDev;
Range saved_aoRange = p.aoRange;
QString saved_aoClock = p.aoClock;
double saved_aoSrate = p.aoSrate;
unsigned saved_aoBufferSizeCS = p.aoBufferSizeCS;
if (muxMode) {
setDO(false);// set DO line low to reset external MUX
msleep(1000); // keep it low for 1 second
}
if ( !createAITasks() ) goto Error_Out;
if (p.aoPassthru && aoAITab.size()) {
aoWriteThr = new AOWriteThread(0, aoChan, p);
Connect(aoWriteThr, SIGNAL(daqError(const QString &)), this, SIGNAL(taskError(const QString &)));
aoWriteThr->start();
}
if ( !startAITasks() ) goto Error_Out;
if (muxMode) {
setDO(true); // now set DO line high to start external MUX and clock on PFI2
}
lastEnq = lastReadTime = startTime = getTime();
aoSampCount = 0;
double hzAvg = 0.;
int nHz = 0, nHzMax = 20;
while( !pleaseStop ) {
data.clear(); // should already be cleared, but enforce...
data2.clear();
if (leftOver.size()) data.swap(leftOver);
if (leftOver2.size()) data2.swap(leftOver2);
unsigned long oldS = (unsigned long)data.size(), oldS2 = (unsigned long)data2.size();
data.reserve(pointsToRead+oldS);
data.resize(pointsToRead+oldS);
double tr0 = getTime();
// XXX DEBUG HACK.. test DAQ retry mechanism
/*static int ctr = 0;
if (++ctr >= 10) {
QThread::msleep(1000);
ctr = 0;
}*/
//DAQmxErrChk (DAQmxReadBinaryI16(taskHandle,samplesPerChan,timeout,DAQmx_Val_GroupByScanNumber,&data[oldS],pointsToRead,&pointsRead,NULL));
int retVal = doAIRead(taskHandle, samplesPerChan, data, oldS, pointsToRead, pointsRead);
if (retVal < 0) goto Error_Out; // fatal
else if (retVal > 0) continue; // retry
// else retval == 0, all ok
double hz = pointsRead/(getTime()-tr0);
hzAvg = ((hzAvg*nHz) + hz) / (nHz+1);
if (++nHz >= nHzMax) nHz = nHzMax-1;
if (excessiveDebug) Debug() << "read rate: " << hz << " Hz, avg " << hzAvg << " Hz";
if (p.dualDevMode) {
data2.reserve(pointsToRead2+oldS2);
data2.resize(pointsToRead2+oldS2);
//DAQmxErrChk (DAQmxReadBinaryI16(taskHandle2,samplesPerChan2,timeout,DAQmx_Val_GroupByScanNumber,&data2[oldS2],pointsToRead2,&pointsRead2,NULL));
retVal = doAIRead(taskHandle2, samplesPerChan2, data2, oldS2, pointsToRead2, pointsRead2);
if (retVal < 0) goto Error_Out; // fatal
else if (retVal > 0) continue; // retry
// else retval == 0, all ok
// TODO FIXME XXX -- *use* this data.. for now we are just testing
//Debug() << "Read " << pointsRead2 << " samples from second dev.\n";
}
lastReadTime = getTime();
u64 sampCount = totalRead;
if (!sampCount) emit(gotFirstScan());
int32 nRead = pointsRead * nChans + oldS, nRead2 = pointsRead2 * nChans2 + oldS2;
int nDemuxScans = nRead/nChans/nscans_per_mux_scan, nDemuxScans2 = 1;
if ( nDemuxScans*nscans_per_mux_scan*nChans != nRead ) {// not on 60 (or 75 if have interwoven PD and in PD mode) channel boundary, so save extra channels and enqueue them next time around..
nRead = nDemuxScans*nscans_per_mux_scan*nChans;
leftOver.insert(leftOver.end(), data.begin()+nRead, data.end());
data.erase(data.begin()+nRead, data.end());
}
if (p.dualDevMode && nChans2) {
nDemuxScans2 = nRead2 / nChans2 / nscans_per_mux_scan;
if (nDemuxScans2 * nscans_per_mux_scan * nChans2 != nRead2) {
nRead2 = nDemuxScans2*nscans_per_mux_scan*nChans2;
leftOver2.insert(leftOver2.end(), data2.begin()+nRead2, data2.end());
data2.erase(data2.begin()+nRead2, data2.end());
}
} else
nRead2 = 0;
if (p.dualDevMode && nDemuxScans != nDemuxScans2) { // ensure same exact number of scans
if (nDemuxScans > nDemuxScans2) {
const int diff = nDemuxScans-nDemuxScans2;
nRead = (nDemuxScans-diff)*nscans_per_mux_scan*nChans;
leftOver.insert(leftOver.end(), data.begin()+nRead, data.end());
data.erase(data.begin()+nRead, data.end());
nDemuxScans -= diff;
} else if (nDemuxScans2 > nDemuxScans) {
const int diff = nDemuxScans2-nDemuxScans;
nRead2 = (nDemuxScans2-diff)*nscans_per_mux_scan*nChans2;
leftOver2.insert(leftOver2.end(), data2.begin()+nRead2, data2.end());
data2.erase(data2.begin()+nRead2, data2.end());
nDemuxScans2 -= diff;
}
}
// at this point we have scans of size 60 (or 75) channels (or 32 in JFRCIntan32)
// in the 75-channel case we need to throw away 14 of those channels since they are interwoven PD-channels!
data.resize(nRead);
data2.resize(nRead2);
if (!nRead) {
Warning() << "Read less than a full scan from DAQ hardware! FIXME on line:" << __LINE__ << " in " << __FILE__ << "!";
continue;
}
//Debug() << "Acquired " << nRead << " samples. Total " << totalRead;
if (muxMode && (nExtraChans1 || nExtraChans2)) {
/*
NB: at this point data contains scans of the form:
| 0 | 1 | 2 | 3 | Extra 1 | Extra 2 | PD | ...
| 4 | 5 | 6 | 7 | Extra 1 | Extra 2 | PD | ...
| 56| 57| 58| 59| Extra 1 | Extra 2 | PD |
---------------------------------------------------------------
Notice how the Extra channels are interwoven into the
0:3 (or 0:7 if in 120 channel mode) AI channels.
We need to remove them!
We want to turn that into 1 (or more) demuxed VIRTUAL scans
of either form:
Pre-July 2011 ordering, which was INTAN_Channel major:
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | ... | 58 | 59 | Extra 1 | Extra 2| PD |
-------------------------------------------------------------------------
Or, the current ordering, which is INTAN major:
| 0 | 4 | 8 | 12 | 16 | 20 | 24 | 28 | ... | 55 | 59 | Extra 1 | Extra 2| PD |
------------------------------------------------------------------------------
Where we remove every `nChans' extraChans except for when
we have (NCHANS-extraChans) samples, then we add the extraChans,
effectively downsampling the extra channels from 444kHz to
29.630 kHz.
Capisce?
NB: nChans = Number of physical channels per physical scan
NCHANS = Number of virtual channels per virtual scan
*/
std::vector<int16> tmp, tmp2;
const int datasz = int(data.size()), datasz2 = int(data2.size());
tmp.reserve(datasz);
tmp2.reserve(datasz2);
const int nMx = nChans-nExtraChans1, nMx2 = nChans2-nExtraChans2;
if (nMx > 0) {
for (int i = nMx; nExtraChans1 && i <= datasz; i += nChans) {