forked from bernardokyotoku/pyniscope
-
Notifications
You must be signed in to change notification settings - Fork 0
/
niScope.py
720 lines (640 loc) · 26.6 KB
/
niScope.py
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
from __future__ import print_function
__all__ = []
import six
if six.PY2:
from ordered_symbols import *
else:
from ordered_symbols_3 import *
import os
import sys
import textwrap
import numpy
from numpy import ctypeslib,zeros,float64
from ctypes import create_string_buffer,byref,util
import ctypes
import ctypes.util
import warnings
if six.PY2:
from niScopeTypes import *
from niScopeTypes import ViInt32
else:
from niScopeTypes_3 import *
from niScopeTypes_3 import ViInt32
import platform
arch = platform.architecture()[0]
if arch.startswith('64'):
libname = 'niScope_64'
else:
libname = 'niScope_32'
# include_niScope_h = os.environ['NIIVIPATH']+'Include\\niScope.h'
lib = util.find_library(libname)
if lib is None:
if os.name=='posix':
print(libname + '.so not found, is NI-SCOPE installed?')
raise ImportError
if os.name=='nt':
print(libname + '.dll not found')
raise ImportError
if os.name=='posix':
libniScope = ctypes.cdll.LoadLibrary(lib)
if os.name=='nt':
libniScope = ctypes.windll.LoadLibrary(lib)
class ScopeException(Exception):
pass
class Scope(ViSession):
def CALL(self,name, *args):
"""
Calls libniScope function "name" and arguments "args".
"""
funcname = 'niScope_' + name
func = getattr(libniScope, funcname)
new_args = []
for a in args:
if six.PY2:
if isinstance (a, unicode):
print(name, 'argument',a, 'is unicode')
new_args.append (str (a))
else:
new_args.append (a)
else:
if isinstance(a, str):
new_args.append(a.encode('ascii'))
else:
new_args.append(a)
status = func(*new_args)
if status is not 0:
message = self.errorHandler(status)
raise ScopeException(message)
return status
def __init__(self,resourceName="Dev1",IDQuery=False,resetDevice=False):
if six.PY3:
if isinstance(resourceName, str):
resourceName = resourceName.encode('ascii')
self.info = wfmInfo()
ViSession.__init__(self,0)
status = self.CALL('init',
ViRsrc(resourceName),
ViBoolean(IDQuery),
ViBoolean(resetDevice),
byref(self))
return None
def AutoSetup(self):
"""
Automatically configures the instrument. When you call this
function, the digitizer senses the input signal and automati-
cally configures many of the instrument settings. If no signal
is found on any analog input channel, a warning is returned, and
all channels are enabled. A channel is considered to have a
signal present if the signal is at least 10% of the smallest
vertical range available for that channel.
"""
status = self.CALL("AutoSetup",self)
return status
def ConfigureAcquisition(self,acqType=VAL.NORMAL):
"""
Configures how the digitizer acquires data and fills the wave-
form record.
"""
acquisitionType = ViInt32(acqType)
status = self.CALL("ConfigureAcquisition",self,acquisitionType)
def ConfigureHorizontalTiming(self,
sampleRate = 20000000,
numPts = 1000,
refPosition = 0.5,
numRecords = 1,
enforceRealtime = True):
"""
Configures the common properties of the horizontal subsystem for
a multirecord acquisition in terms of minimum sample rate.
"""
self.RecordLength = numPts
status = self.CALL('ConfigureHorizontalTiming',self,
ViReal64(sampleRate),
ViInt32(numPts),
ViReal64(refPosition),
ViInt32(numRecords),
ViBoolean(enforceRealtime))
return
def ConfigureChanCharacteristics(self,chanList,impedance,maxFrequency):
"""
Configures the attributes that control the electrical character-
istics of the channel the input impedance and the bandwidth.
"""
status = self.CALL("ConfigureChanCharacteristics",self,
ViConstString(chanList),
ViReal64(impedance),
ViReal64(maxFrequency))
return status
def ConfigureClock(self, inputClockSource, outputClockSource, clockSyncPulseSource, masterEnabled):
"""
Configures the attributes for synchronizing the digitizer to a reference
or sending the digitizer's reference clock output to be used as a
synchronizing clock for other digitizers.
Input clock source
==================
'VAL_NO_SOURCE'
'VAL_PFI_1'
'VAL_PFI_2'
'VAL_EXTERNAL'
'VAL_CLK_IN'
'VAL_PXI_CLOCK'
'VAL_RTSI_CLOCK'
Output clock source
===================
'VAL_NO_SOURCE'
'VAL_RTSI_CLOCK'
'VAL_PFI_0'
'VAL_PFI_1'
'VAL_PFI_2'
'VAL_CLK_OUT'
Sync pulse source
=================
For the NI 5102, specifies the line on which the
sample clock is sent or received. For the NI 5112/5620/5621/5911,
specifies the line on which the one-time sync pulse is sent or
received. This line should be the same for all devices to be
synchronized.
Possible values:
'VAL_NO_SOURCE'
'VAL_RTSI_0'
'VAL_RTSI_1'
'VAL_RTSI_2'
'VAL_RTSI_3'
'VAL_RTSI_4'
'VAL_RTSI_5'
'VAL_RTSI_6'
'VAL_PFI_1'
'VAL_PFI_2'
"""
if inputClockSource not in ('VAL_NO_SOURCE', 'VAL_PFI_1', 'VAL_PFI_2',
'VAL_EXTERNAL', 'VAL_CLK_IN', 'VAL_PXI_CLOCK',
'VAL_RTSI_CLOCK'):
raise ValueError('Wrong input clock source.')
if outputClockSource not in ('VAL_NO_SOURCE', 'VAL_RTSI_CLOCK', 'VAL_PFI_0',
'VAL_PFI_1', 'VAL_PFI_2', 'VAL_CLK_OUT'):
raise ValueError('Wrong output clock source.')
if clockSyncPulseSource not in ('VAL_NO_SOURCE', 'VAL_RTSI_0', 'VAL_RTSI_1',
'VAL_RTSI_2', 'VAL_RTSI_3', 'VAL_RTSI_4',
'VAL_RTSI_5', 'VAL_RTSI_6', 'VAL_PFI_1',
'VAL_PFI_2'):
raise ValueError('Wrong sync pulse source.')
status = self.CALL("ConfigureClock", self,
ViConstString(inputClockSource),
ViConstString(outputClockSource),
ViConstString(clockSyncPulseSource),
ViBoolean(masterEnabled))
return status
def ConfigureVertical(self,
channelList="0",
voltageRange=10,
offset=0,
coupling=COUPLING.DC,
probeAttenuation=1,
enabled=True):
"""
Configures the most commonly configured attributes of the digi-
tizer vertical subsystem, such as the range, offset, coupling,
probe attenuation, and the channel.
"""
if six.PY3:
if isinstance(channelList, str):
channelList = channelList.encode('ascii')
status = self.CALL("ConfigureVertical",self,
ViConstString(channelList),
ViReal64(voltageRange),
ViReal64(offset),
ViInt32(coupling),
ViReal64(probeAttenuation),
ViBoolean(enabled))
return status
def ConfigureTrigger(self,trigger_type='Immediate',**settings):
"""
Configures scope trigger type and settings. For each trigger
type distinct settings must be defined.
Parameter Valid Values
trigger_type 'Edge'
'Hysteresis'
'Window'
'Window'
'Software'
'Immediate'
'Digital'
'Video'
Trigger Type Settings Default Value
'Immediate' N/A
'Edge' triggerSource TRIGGER_SOURCE.EXTERNAL
level 0
slope SLOPE.POSITIVE
triggerCoupling COUPLING.DC
holdoff 0
delay 0
'Hysteresis' triggerSource '0'
level 0
hysteresis 0.05
slope SLOPE.POSITIVE
triggerCoupling COUPLING.DC
holdoff 0
delay 0
'Window' triggerSource '0'
lowLevel 0
highLevel 0.1 windowMode TRIGGER_WINDOW.ENTERING_WINDOW
triggerCoupling COUPLING.DC
holdoff 0
delay 0
'Software' holdoff 0
delay 0
'Digital' triggerSource '0'
slope SLOPE.POSITIVE
holdoff 0
delay 0
'Video' triggerSource '0'
enableDCRestore False signalFormat TV_TRIGGER_SIGNAL_FORMAT.VAL_PAL event TV_TRIGGER_EVENT.FIELD1
lineNumber 0
polarity TV_TRIGGER_POLARITY.TV_POSITIVE
triggerCoupling COUPLING.DC
holdoff 0
delay 0
"""
args = {
'Edge':lambda
triggerSource = TRIGGER_SOURCE.EXTERNAL ,
level = 0 ,
slope = SLOPE.POSITIVE ,
triggerCoupling = COUPLING.DC ,
holdoff = 0 ,
delay = 0
:(
ViConstString (triggerSource ),
ViReal64 (level ),
ViInt32 (slope ),
ViInt32 (triggerCoupling),
ViReal64 (holdoff ),
ViReal64 (delay )
),
'Hysteresis':lambda
triggerSource = '0' ,
level = 0 ,
hysteresis = 0.05 ,
slope = SLOPE.POSITIVE ,
triggerCoupling = COUPLING.DC ,
holdoff = 0 ,
delay = 0
:(
ViConstString (triggerSource ),
ViReal64 (level ),
ViReal64 (hysteresis ),
ViInt32 (slope ),
ViInt32 (triggerCoupling),
ViReal64 (holdoff ),
ViReal64 (delay )
),
'Window':lambda
triggerSource = '0' ,
lowLevel = 0 ,
highLevel = 0.1 ,
windowMode = TRIGGER_WINDOW.ENTERING_WINDOW,
triggerCoupling = COUPLING.DC ,
holdoff = 0 ,
delay = 0
:(
ViConstString (triggerSource ),
ViReal64 (lowLevel ),
ViReal64 (highLevel ),
ViInt32 (windowMode ),
ViInt32 (triggerCoupling ),
ViReal64 (holdoff ),
ViReal64 (delay )
),
'Software':lambda
holdoff = 0,
delay = 0
:(
ViReal64 (holdoff ),
ViReal64 (delay )
),
'Immediate':lambda:(),
'Digital':lambda
triggerSource = '0' ,
slope = SLOPE.POSITIVE,
holdoff = 0 ,
delay = 0
:(
ViConstString (triggerSource ),
ViInt32 (slope ),
ViReal64 (holdoff ),
ViReal64 (delay )
),
'Video':lambda
triggerSource = '0' ,
enableDCRestore = False ,
signalFormat = TV_TRIGGER_SIGNAL_FORMAT.VAL_PAL,
event = TV_TRIGGER_EVENT.FIELD1 ,
lineNumber = 0 ,
polarity = TV_TRIGGER_POLARITY.POSITIVE ,
triggerCoupling = COUPLING.DC ,
holdoff = 0 ,
delay = 0
:(
ViConstString (triggerSource ),
ViBoolean (enableDCestore ),
ATTR_TV_TRIGGER_SIGNAL_FORMAT (signalFormat ),
ViInt32 (event ),
ViInt32 (lineNumber ),
ViInt32 (polarity ),
ViInt32 (triggerCoupling ),
ViReal64 (holdoff ),
ViReal64 (delay )
),
}[trigger_type](**settings)
status = self.CALL("ConfigureTrigger"+trigger_type,self,*args)
def ExportSignal(self,signal=NISCOPE_VAL_REF_TRIGGER
,outputTerminal=NISCOPE_VAL_RTSI_0
,signalIdentifier=""):
"""
Configures the digitizer to generate a signal that other devices can detect when
configured for digital triggering or sharing clocks. The signal parameter speci-
fies what condition causes the digitizer to generate the signal. The
outputTerminal parameter specifies where to send the signal on the hardware
(such as a PFI connector or RTSI line).
In cases where multiple instances of a particular signal exist, use the
signalIdentifier input to specify which instance to control. For normal signals,
only one instance exists and you should leave this parameter set to the empty
string. You can call this function multiple times and set each available line to
a different signal.
To unprogram a specific line on device, call this function with the signal you
no longer want to export and set outputTerminal to NISCOPE_VAL_NONE.
"""
status = self.CALL("ExportSignal",self,
ViInt32(signal),
ViConstString(signalIdentifier),
ViConstString(outputTerminal))
return status
def InitiateAcquisition(self):
"""
Initiates a waveform acquisition.
After calling this function, the digitizer leaves the Idle state
and waits for a trigger. The digitizer acquires a waveform for
each channel you enable with ConfigureVertical.
"""
status = self.CALL("InitiateAcquisition",self)
return Acquisition()
def Abort(self):
"""
Aborts an acquisition and returns the digitizer to the Idle
state. Call this function if the digitizer times out waiting for
a trigger.
"""
status = self.CALL("Abort",self)
return status
def AcquisitionStatus(self):
"""
Returns status information about the acquisition to the status
output parameter.
"""
acq_status = ViInt32()
status = self.CALL("AcquisitionStatus",self,
byref(acq_status))
return acq_status.value
def Commit(self):
"""
Commits to hardware all the parameter settings associated with
the task. Use this function if you want a parameter change to be
immediately reflected in the hardware. This function is support-
ed for the NI 5122/5124 only.
"""
status = self.CALL("Commit",self)
def GetAttribute(self, attribute, attrType, channelList=""):
"""
Queries the value of an attribute. You can use this
function to get the values of instrument-specific attributes and
inherent IVI attributes. If the attribute represents an instru-
ment state, this function performs instrument I/O in the follow-
ing cases:
State caching is disabled for the entire session or for the par-
ticular attribute.
State caching is enabled and the currently cached value is inva-
lid.
"""
if six.PY3:
if isinstance(channelList, str):
channelList = channelList.encode('ascii')
var = attrType()
self.CALL("GetAttribute"+attrType.__name__,
self,
ViConstString(channelList),
ViAttr(attribute),
byref(var))
return var.value
def SetAttribute(self, attribute, value, channelList=""):
"""
Sets the value an attribute. This is a low-level function that
you can use to set the values of instrument-specific attributes
and inherent IVI attributes. If the attribute represents an
instrument state, this function performs instrument I/O in the
following cases:
State caching is disabled for the entire session or for the par-
ticular attribute.
State caching is enabled and the currently cached value is inva
lid or is different than the value you specify.
"""
if six.PY2:
attrType = { float:ViReal64,
int:ViInt32,
long:ViInt32,
bool:ViBoolean,
Scope:ViSession,
str:ViString,
} [type(value)]
else:
attrType = { float:ViReal64,
int:ViInt32,
bool:ViBoolean,
Scope:ViSession,
bytes:ViString,
} [type(value)]
if isinstance(channelList, str):
channelList = channelList.encode('ascii')
status = self.CALL("SetAttribute"+attrType.__name__,
self,
ViConstString(channelList),
ViAttr(attribute),
attrType(value))
return status
def CheckAttribute(self, channelList, attribute, value):
"""
Verifies the validity of a value you specify for an attribute.
"""
attrType = { float:ViReal64,
int:ViInt32,
long:ViInt32,
bool:ViBoolean,
Scope:ViSession,
str:ViString,
} [type(value)]
status = self.CALL("CheckAttribute"+attrType.__name__,
self,
ViConstString(channelList),
ViAttr(attribute),
attrType(value))
return status
def Fetch(self, channelList="0", buf = None, timeout=1,):
"""
Returns the waveform from a previously initiated acquisition
that the digitizer acquires for the specified channel.
numpy array needs to be Fortran ordered.
"""
if six.PY3:
if isinstance(channelList, str):
channelList = channelList.encode('ascii')
numAcquiredWaveforms = self.ActualNumWfms(channelList)
numberOfChannels = len(b','.split(channelList))
if buf is None:
buf = zeros([self.RecordLength,
numberOfChannels*numAcquiredWaveforms],order="F"
,dtype=numpy.float64)
samplesPerRecord = buf.shape[0]
numberOfRecords = buf.shape[1]
else:
samplesPerRecord = buf.shape[0]
numberOfRecords = buf.shape[1]
if numberOfRecords < numAcquiredWaveforms*numberOfChannels:
self.FetchNumberRecords = numberOfRecords/numberOfChannels
assert numAcquiredWaveforms == numberOfRecords
assert self.RecordLength >= samplesPerRecord
data_type = {
numpy.float64 :'' ,
numpy.int8 :'Binary8' ,
numpy.int16 :'Binary16' ,
numpy.int32 :'Binary32' }[buf.dtype.type]
wfmInfoArray = wfmInfo*numAcquiredWaveforms
self.info = wfmInfoArray()
# Enclosing CALL into try except because the exception
# that is likely to be raised is overflow warnings.
# Without the try-except, no data will be returned at all.
try:
status = self.CALL("Fetch"+data_type,self,
ViConstString(channelList),
ViReal64(timeout),
ViInt32(samplesPerRecord),
buf.ctypes.data,
byref(self.info)
)
except Exception as e:
message = e.args[0]
if six.PY3:
message = message.decode('ascii')
if message.startswith('Warning'):
warnings.warn(message)
else:
raise
return buf
@property
def FetchRecordNumber(self):
return self.GetAttribute(
NISCOPE_ATTR_FETCH_RECORD_NUMBER,
int)
@FetchRecordNumber.setter
def FetchRecordNumber(self,value):
return self.SetAttribute(
NISCOPE_ATTR_FETCH_RECORD_NUMBER,
int(value))
@property
def FetchNumberRecords(self):
return self.GetAttribute(
NISCOPE_ATTR_FETCH_NUM_RECORDS,
int)
@FetchNumberRecords.setter
def FetchNumberRecords(self,value):
return self.SetAttribute(
NISCOPE_ATTR_FETCH_NUM_RECORDS,
int(value))
@property
def AllowMoreRecordsThanMemory(self):
return self.GetAttribute(
NISCOPE_ATTR_ALLOW_MORE_RECORDS_THAN_MEMORY,
bool)
@AllowMoreRecordsThanMemory.setter
def AllowMoreRecordsThanMemory(self,value):
self.SetAttribute(NISCOPE_ATTR_ALLOW_MORE_RECORDS_THAN_MEMORY,
bool(value))
@property
def NumRecords(self):
"""
Specifies the number of records to acquire. Can be used for multirecord acquisi-
tions and single record acquisitions. Setting this attribute to 1 indicates a
single record acquisition.
"""
return self.GetAttribute(NISCOPE_ATTR_HORZ_NUM_RECORDS, ViInt32)
@NumRecords.setter
def NumRecords(self,value):
self.SetAttribute(NISCOPE_ATTR_HORZ_NUM_RECORDS, int(value))
@property
def ActualRecordLength(self):
"""
Returns the actual number of points the digitizer acquires for
each channel. After configuring the digitizer for an acquisition
, call this function to determine the size of the waveforms that
the digitizer acquires. The value is equal to or greater than
the minimum number of points specified in any of the Configure
Horizontal functions.
Allocate a ViReal64 array of this size or greater to pass as the
waveformArray of the ReadWaveform and FetchWaveform functions.
"""
record = ViInt32()
self.CALL("ActualRecordLength",self,byref(record))
return record.value
def ActualNumWfms(self,channelList = "0"):
"""
Helps you to declare appropriately sized waveforms. NI-SCOPE
handles the channel list parsing for you.
"""
if six.PY3:
if isinstance(channelList, str):
channelList = channelList.encode('ascii')
chan = ViConstString(channelList)
numWfms = ViInt32()
self.CALL("ActualNumWfms",self,chan,byref(numWfms))
return numWfms.value
@property
def ActualSamplingRate(self):
return self.GetAttribute(NISCOPE_ATTR_HORZ_SAMPLE_RATE,ViReal64)
def ActualVoltageRange(self, channelList):
return self.GetAttribute(NISCOPE_ATTR_VERTICAL_RANGE, ViReal64, channelList=channelList)
@property
def OnboardMemory(self):
return self.GetAttribute(NISCOPE_ATTR_ONBOARD_MEMORY_SIZE, ViInt32)
def read(self):
self.ConfigureHorizontalTiming()
self.ConfigureVertical()
self.ConfigureTrigger()
self.InitiateAcquisition()
data = self.Fetch()
self.close()
return data
def close(self):
"""
When you are finished using an instrument driver session, you
must call this function to perform the following actions:
"""
status = self.CALL("close",self)
def errorHandler (self,errorCode):
MAX_FUNCTION_NAME_SIZE = 55
IVI_MAX_MESSAGE_LEN = 255
IVI_MAX_MESSAGE_BUF_SIZE = IVI_MAX_MESSAGE_LEN + 1
MAX_ERROR_DESCRIPTION = (IVI_MAX_MESSAGE_BUF_SIZE * 2 + MAX_FUNCTION_NAME_SIZE + 75)
errorSource = create_string_buffer(MAX_FUNCTION_NAME_SIZE)
errorDescription = create_string_buffer(MAX_ERROR_DESCRIPTION )
self.CALL("errorHandler",self,
ViInt32(errorCode),
errorSource,
errorDescription)
return errorDescription.value
def error_message (self,errorCode):
IVI_MAX_MESSAGE_LEN = 255
class Acquisition(object):
def __iter__(self):
class iterator:
def __iter__(self):
pass
def next(self):
return self.scope.Fetch()