-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtekscope.py
executable file
·734 lines (627 loc) · 24.6 KB
/
tekscope.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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
#!/usr/bin/python
# tds-2024.py
# Python interface to the TDS20xx Tektronix oscilloscope
#
# Les Schaffer Designspring, Inc. http://designspring.com
#
# Licensed under the GPL version 2 or later; see the file LICENSE
# included with this distribution.
#
# Current status:
# Version 0.1 -- 6/7 Feb 2015 first version, uses serial interface, will do USB and GPIB later.
# starting with TDS 2024, probably useful for many others
# Version 0.2 -- 10 Feb 2015 many improvements to code, in good working order, ready to be extended as needed.
# Version 0.3 -- 15 Feb 2015 added a TriggerControl class, could use some ugly-code-->gorgeous-code adjustments
# started tracking the trigger position in the plots.
# Adding a HORizontal control. CH, DAT, and DIS to follow
# Version 0.4 -- Added in a USB scope via linux kernel module usbtmc
#
#
# adapated from : http://www.febo.com/geekworks/data-capture/tds-2012.html cf. https://gist.github.com/pklaus/320584
# i think the previous line handles my responsibilities under GPL. am newcomer to licensing, please let me know if
# otherwise
#
# see also: https://github.com/python-ivi
import datetime
from math import log10, ceil
from string import split, upper
from time import sleep
from struct import unpack
from serial import Serial # we don't need no steenkin' VISA
from numpy import array
import os
from plotter import ScopeDisplay
# how long to sleep after issuing a write
sleeptime = 0.01
mNAN = 9.9e+37 # Tektronix "not a number"
class Measurement(object):
"""
Given a list of measurement requests on a channel, and a function for obtaining them, acquire the measurements when call()ed and
set appropriate attributes to store these values. Also store appropriate stringified versions, for later display.
Acquired measurements can be retrieved by attribute, or can be returned as a list or a dictionary.
possible measurements:
MEASUrement:IMMed:TYPe { FREQuency | MEAN | PERIod |PHAse | PK2pk | CRMs | MINImum | MAXImum | RISe | FALL | PWIdth | NWIdth }
TODO:
1. do we want immediate measurements or regular?
2. get the associated unit, for display (why bother, here they are:)
"""
mtypeT = ('FREQ', 'MEAN', 'PERI', 'PHAS', 'PK2P', 'CRMS', 'MINI', 'MAXI', 'RISE', 'FALL', 'PWID', 'NWID')
munitsT = ('Hz', 'V ', 's ', '', 'V ', 'V ', 'V ', 'V ', 's ', 's ', 's ', 's ')
mtypeD = {meas: unit for meas, unit in zip(mtypeT, munitsT)}
sufD = {0:' ', 3:'m', 6:'u', 9:'n', 12:'p', -3: 'k', -6:'M'}
def __init__(self, mreader):
self._immed=mreader
self.isReset=False
self.measL=()
self.reset()
def getMeasStrLD(self):
return {m: getattr(self, m.lower()+'Str') for m in self.measL}
def getMeasStrLL(self):
return [getattr(self, m.lower()+'Str') for m in self.measL]
def __call__(self, keyL):
# this acquires the actual reading
# we are not doiing the units, for now
self.reset() # might not want to reset if we have new vals!!!
self.measL = tuple( map(upper, keyL) )
for key in self.measL:
if key not in self.mtypeT:
raise ValueError('Channel does not support %s IMMed TYPe'%key)
val = self._immed(key)
# we make nice strings for later retrieval
# means data is acquired throu call() and retrived via attribute
attrN = key.lower()+'Str'
setattr(self, attrN, self.val_to_string(val, key))
# store raw as attr
setattr(self, key.lower(), val)
self.isReset=False # we have readings
def val_to_string(self, val, meas):
tmpl = '{:4s}: {:> 8.3f} '
if val == 0.0:
return tmpl.format(meas, val) + ' ' + self.mtypeD[meas]
aval = abs(val)
if aval > 10.0e9: return '%4s: ** ? ** '%meas
if aval<1.0 or aval>=1000.:
mulmod =3 * ceil( log10(1.0/aval) / 3)
scaled = val*10**mulmod
suf = self.sufD[mulmod]
else:
scaled = val
suf=' '
return tmpl.format(meas,scaled) + suf + self.mtypeD[meas]
def reset(self):
# clear the previous readings.
if not self.isReset:
# reset all values
for typ in self.mtypeT:
setattr(self, typ.lower(), mNAN)
setattr(self, typ.lower()+'_Str', '********')
self.isReset=True
def _strip(strBuf):
return strBuf.replace('"', '')
class Channel(object):
wfmFuncD = {'BYT_NR':int,
'BIT_NR': int,
'ENCDG': None, # ASC | BIN
'BN_FMT': None,
'BYT_OR': None,
'NR_PT': int,
'WFID': _strip, # "Ch3, DC coupling, 1.0E0 V/div, 1.0E-1 s/div, 2500 points, Sample mode"
'PT_FMT': None,
'XINCR': float, # 4.0E-4
'PT_OFF': int, # 0
'XZERO': float, # -1.0E-1
'XUNIT': _strip, # "s"
'YMULT': float, # 4.0E-2
'YZERO': float, # 0.0E0
'YOFF': float, # -4.5E1
'YUNIT': _strip #"Volts"
}
wfmT = wfmFuncD.keys()
chFuncD = { 'BAN': None,
'COUP': None,
'INV': None,
'POS': float,
'PROBE': int,
'SCA': float,
'YUNIT': None
}
chT = chFuncD.keys()
# :WFMPRE:BYT_NR 1;BIT_NR 8;ENCDG BIN;BN_FMT RI;BYT_OR LSB;NR_PT
# 2500;WFID "Ch3, DC coupling, 5.0E-1 V/div, 1.0E-1 s/div, 2500
# points, Sample mode";PT_FMT Y;XINCR 4.0E-4;PT_OFF 0;XZERO
# -1.0E-1;XUNIT "s";YMULT 2.0E-2;YZERO 0.0E0;YOFF -1.69E2;YUNIT
# "Volts"
def __init__(self, chN, instr):
self._channel = 'CH%1d'%chN
self._instr = instr
self._msmnt = Measurement(self.getImmed)
self.wfmD = {}
def getVerticalSetting(self):
# 2,5,10,20,50, 100,200,500 mV/div 1,2,5 V/div
# get instrument settings
voltsdiv=self._instr.query_float('%3s:scale?'%self._channel)
if voltsdiv >= 1:
volt_string = '%i\nV/DIV' % (voltsdiv)
else:
volt_string = '%i\nmV/DIV' % (voltsdiv * 1000)
self.voltStr = volt_string
self.voltsdiv = voltsdiv
def __setitem__(self, key, val):
self._instr.cmd('CH%d:%s %s'%(self._channel, key, val))
def __getitem__(self, key):
ret = self._instr.query('CH%d:%s?'%(self._channel, key))
return map(self.chFuncD[key], (ret,))[0]
def getImmed(self, typ):
self._instr.cmd('measu:imm:typ %s;:measu:imm:sou %3s'%(typ,self._channel))
return self._instr.query_float('measu:imm:val?')
def acqMeas(self, mL):
# acquire some measurements, available later as self.getMeasurements()
self._msmnt(mL)
def getMeasStrD(self):
return self._msmnt.getMeasStrLD()
def getMeasStrL(self):
return self._msmnt.getMeasStrLL()
def wfmpreQ(self):
tmp=self._instr.query('wfmpre?')[0:-1] # strip CR
# strip header :WFMPRE:
preamble = split(tmp[8:],';')
for resp in preamble:
name, val = resp.split(' ',1)
if name in self.wfmT:
func = self.wfmFuncD[name]
if func:
self.wfmD[name]= func(val)
else:
self.wfmD[name] = val
# number of points in trace
self.points = self.wfmD['NR_PT']
if self._instr._debug: print self.wfmD
def acquire(self, prepare):
# for ASCII read, use 'self.read(16384)' instead of the above, and
# delete the next two lines. You'll need to use 'split' to convert the
# comma-delimited values returned in 'tmp' to a list of values called
# 'tmplist', and you may need to adjust the offsets used in the 'for' loop
# to end up with the proper number of points
self._instr.cmd('DATA:SOURCE %3s'%self._channel)
if prepare: self.wfmpreQ()
tmp = self._instr.query('curv?', nBytes=9)
# header: :CURVE #42500
numChr = int(tmp[8]) # 4
tmp=self._instr.read(numChr)
points = int(tmp)
if self._instr._debug: print 'Acquiring %d points'%points
tmp=self._instr.read(self.wfmD['BYT_NR']*points+1) #newline at end???
formatstring = '%ib' % (len(tmp)) # does this assume BYT_NR==1???
tmplist = unpack(formatstring,tmp)[:-1] # there's a newline at the end of the data, thus the strange slice
yoff = self.wfmD['YOFF']
ymult = self.wfmD['YMULT']
yzero = self.wfmD['YZERO']
points = self.wfmD['NR_PT']
tmp = array( map(int, tmplist) )
self.trace = (tmp - yoff) * ymult + yzero
self.trace_undisplaced = tmp*ymult/self.voltsdiv
if self._instr._debug: print self.trace
class HorizontalControl(object):
horFuncD = { 'HOR:VIEW': None,
'HOR:MAIN:POS': float,
'HOR:MAIN:SCA': float
}
horT = horFuncD.keys()
def __init__(self, instr):
self._instr = instr
self._horD = {}
def __getitem__(self, key): # upwards
val= self._instr.query_val(key)
func = self.horFuncD[val]
if func:
val = func(val)
return val
def __setitem__(self, key, val): # downwards
if not val: return
if key not in self.horT: raise ValueError('%s not in trigger dictionary'%key)
self._instr.cmd('%s %s'%(key, val)) # in instrument
class TriggerControl(object):
trigFuncD = {'STATE': None, # No MAIN: prepended, shrug
'MODE': None,
'TYPE': None,
'LEVEL': float,
'HOLDO': float,
'EDGE:SOU': None,
'EDGE:COUP': None,
'EDGE:SLO': None,
'PULS:SOU': None ,
'PULS:WIDTH:POL': None,
'PULS:WIDTH:WHEN': None,
'PULS:WIDTH:WIDTH': float,
'VID:SOU': None,
'VID:LINE': int,
'VID:POL': None,
'VID:STAND': None,
'VID:SYNC': None
}
trigT = trigFuncD.keys()
# no comment, must be a simpler way, have no time to figure it out!!!!!:
mainD = {}
edgeD = {}
pulsD = {}
vidD = {}
for key in ('MODE', 'TYPE', 'LEVEL', 'HOLDO'):
mainD[key] = trigFuncD[key]
for key in ('SOU', 'COUP', 'SLO'):
edgeD[key] = trigFuncD['EDGE:%s'%key]
for key in ('WIDTH:POL', 'WIDTH:WHEN', 'WIDTH:WIDTH', 'SOU'):
pulsD[key] = trigFuncD['PULS:%s'%key]
for key in ('SOU', 'LINE', 'POL', 'STAND', 'SYNC'):
vidD[key] = trigFuncD['VID:%s'%key]
trigTypesD={'MAIN':mainD, 'EDGE':edgeD, 'PULS':pulsD, 'VID':vidD}
def __init__(self, instr):
self._instr = instr
self._trigD = {}
def acqState(self):
# first update from scope
self._trigD['STATE'] = self._instr.query_val('TRIG:STATE?')
return self._trigD['STATE']
def _acqD(self, typ):
query=self._instr.query_val
theD = self.trigTypesD[typ]
name = 'TRIGGER:MAIN:'
key=''
pref=typ
if pref != 'MAIN':
name=name + pref + ':'
key=pref+':'
for s, func in theD.items():
val = query(name+'%s?'%s)
if func:
val = func(val)
self._trigD[key+s]=val
def _setD(self, typ, kwD):
query=self._instr.cmd
setT = self.trigTypesD[typ].keys()
name = '%s:'%typ
for key, val in kwD.items():
if key not in setT: raise IndexError('%s not in (%s)'%(key,setT))
self[name+key] = val
def setTrigger(self, level, mode, holdo, typ, trigD):
self['LEVEL'] = level
self['MODE'] = mode
self['HOLDO'] = holdo
if typ:
if typ not in self.trigTypesD.keys(): raise TypeError('%s is not a trigger type'%typ)
self._setD(typ, trigD)
self['TYPE'] = typ
def getTrigger(self, forceAcq = False):
if forceAcq: self.acqSettings()
# get the type of trigger:
trigD = {key: self[key] for key in ('LEVEL', 'HOLDO', 'MODE', 'TYPE', 'STATE') }
typ = trigD['TYPE']
for key in self.trigTypesD[typ].keys():
trigD[key]= self[typ+':'+ key]
return trigD
def acqSettings(self):
self.acqState()
self._acqD('MAIN')
self._acqD(self._trigD['TYPE'])
def __getitem__(self, key): # upwards
return self._trigD[key]
def __setitem__(self, key, val): # downwards
if not val: return
if key not in self.trigT: raise ValueError('%s not in trigger dictionary'%key)
self._instr.cmd('TRIGGER:MAIN:%s %s'%(key, val)) # in instrument
# now store local
self._trigD[key]=val
class TektronixScope(object):
"""
TODO ideas:
1. could have a channels class, and add four to this device
2. channels could have a set of measurements and a unique trace
3. could handle various kinds of trigger and setup condx to satisfy grabbing data
4. could autostore data (tables best for this)
"""
def __init__(self, debug=False, horScale=None, horPos=None):
self._debug = debug
self.connect()
self.clear()
self.identify()
self._channelL=[]
self._channelAcqL=[]
for i in (1,2,3,4):
self._channelL.append( Channel(i,self) )
self._triggerCtl = TriggerControl(self)
self._horCtl = HorizontalControl(self)
if horScale: self._horCtl['HOR:MAIN:SCA']=horScale
if horPos: self._horCtl['HOR:MAIN:POS']=horPos
def identify(self):
sleep(sleeptime)
self.write('*IDN?'+'\n')
sleep(sleeptime)
resp=self.readline()
if resp.strip() == self._idStr:
print resp.strip()
else:
raise ValueError('Failed to get instrument id (%s)'%resp)
def getChannel(self, chN):
return self._channelL[chN-1]
def channelWasAcq(self, chN):
return chN in self._chanAcqL
def getacqTag(self):
return self._acqtag
def setTrigger(self, level, mode, holdo, typ, trigD ):
self._triggerCtl.setTrigger(level, mode, holdo, typ, trigD )
def getTrigger(self, forceAcq):
return self._triggerCtl.getTrigger(forceAcq)
def query(self, req, nBytes=None):
if self._debug:
print "send to Serial: ", req
self.write(req+'\n')
sleep(sleeptime)
if nBytes:
resp=self.read(nBytes)
else:
resp=self.readline()
if self._debug:
print "got from Serial: ", resp,
return resp # for dog's sake, remove the CR once and for all
def setAcqState(self, state, stopAfter='RUNSTOP'):
if state not in ('STOP', 'RUN', 'ON', 'OFF'):
raise ValueError('Not an acquisition state: %s'%state)
self.cmd('ACQ:STATE %s'%state)
self.cmd('ACQ:STOPA %s'%stopAfter)
def query_val(self, req):
resp = self.query(req)
return resp.strip().split()[-1]
def query_float(self, req):
resp = self.query(req)
resp=float( resp.split()[1] )
if self._debug: print 'query_float:%s'%resp
return resp
def cmd(self, cmdS):
if self._debug:
print "send to Serial: ", cmdS
self.write(cmdS+'\n')
sleep(sleeptime)
def prepare(self):
self.cmd('acquire:state on')
raw_input('Press ENTER when ready to acquire triggered data: ')
def complete(self):
self.cmd('acquire:state off')
# should catch SIGINT/SIGKILL and call __del__ and clean up buffers
__del__ = complete
def acquire(self, chmD, prepChannels=True):
self._triggerCtl.acqSettings()
self.prepare()
self.getSweepSetting()
self._chanAcqL=chmD.keys()
for ch,m in chmD.items():
chan = self.getChannel(ch)
chan.getVerticalSetting()
chan.acqMeas(m)
chan.acquire(prepChannels)
self.complete()
def measLoop(self, chmD):
debug=self._debug
self._debug=False
while 1:
for ch,m in chmD.items():
chan = self.getChannel(ch)
chan.acqMeas(m)
print chan.getMeasStrD()
x = raw_input('Enter to continue, anything to quit: ')
if x: break
self._debug=debug
def load(self):
pass
def dump(self):
dfp = open('scope.dat', 'w')
dfp.close()
def getSweepSetting(self):
sufD = {3:'m', 6:'u', 9:'n'}
scaled=self.query_float('hor:mai:sca?')
if scaled >= 1:
suf = ' s'
if scaled < 1:
mulmod =3 * ceil( log10(1.0/scaled) / 3)
scaled = scaled*10**mulmod
suf = sufD[mulmod]+'s'
sweepStr= '%.f' % scaled
self.sweepStr = sweepStr + '\n' + (suf) + "/DIV"
self.sweep=scaled
def showFileSystem(self):
print self.query('FILES:DIR?')
class TDS2024(TektronixScope):
_idStr = 'TEKTRONIX,TDS 2024,0,CF:91.1CT FV:v4.12 TDS2CM:CMV:v1.04'
def __init__(self, port='/dev/ttyS0', **kwD):
self._port = port
super(TDS2024, self).__init__(kwD)
def connect(self):
self.serial = Serial(self._port, 9600, timeout=None)
self.read = self.serial.read
self.readline = self.serial.readline
self.write = self.serial.write
def clear(self):
cnt=10
self.serial.timeout=1
while 1:
self.serial.sendBreak() # doesnt seem to handle if other stuff in the queue
sleep(sleeptime)
resp=self.readline()
if resp == 'DCL\0\n': # should see: [68, 67, 76, 0, 10]
# we may have another DCL in the queue because we've repeated
if cnt==9:
resp=self.readline() # hangs here sometimes. put a timeout on it???
self.serial.flushInput()
self.serial.flushOutput()
if self._debug: print map(ord,resp)
print
break
if self._debug:
print 'X',
print map(ord, resp)
cnt=cnt-1
if cnt==0: raise ValueError('Serial port did not return DCL! (%s)'%resp )
self.serial.timeout=None
class USBScope(TektronixScope):
"""
Bus 006 Device 003: ID 0699:03a6 Tektronix, Inc.
Device Descriptor:
bLength 18
bDescriptorType 1
bcdUSB 2.00
bDeviceClass 0 (Defined at Interface level)
bDeviceSubClass 0
bDeviceProtocol 0
bMaxPacketSize0 64
idVendor 0x0699 Tektronix, Inc.
idProduct 0x03a6
bcdDevice 0.42
iManufacturer 1 Tektronix, Inc.
iProduct 2 Tektronix TDS2024C
iSerial 3 C016676
bNumConfigurations 1
Configuration Descriptor:
bLength 9
bDescriptorType 2
wTotalLength 39
bNumInterfaces 1
bConfigurationValue 1
iConfiguration 0
bmAttributes 0xc0
Self Powered
MaxPower 100mA
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 0
bAlternateSetting 0
bNumEndpoints 3
bInterfaceClass 254 Application Specific Interface
bInterfaceSubClass 3 Test and Measurement
bInterfaceProtocol 1 TMC
iInterface 0
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x85 EP 5 IN
bmAttributes 2
Transfer Type Bulk
Synch Type None
Usage Type Data
wMaxPacketSize 0x0040 1x 64 bytes
bInterval 0
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x06 EP 6 OUT
bmAttributes 2
Transfer Type Bulk
Synch Type None
Usage Type Data
wMaxPacketSize 0x0040 1x 64 bytes
bInterval 0
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x87 EP 7 IN
bmAttributes 3
Transfer Type Interrupt
Synch Type None
Usage Type Data
wMaxPacketSize 0x0040 1x 64 bytes
bInterval 8
Device Status: 0x0000
(Bus Powered)
"""
_idStr = 'TEKTRONIX,TDS 2024C,C016676,CF:91.1CT FV:v24.17'
def __init__(self, port='/dev/usbtmc0', **kwD):
self._port = port
super(USBScope, self).__init__(kwD)
def connect(self):
self.usbtmc = os.open(self._port, os.O_RDWR)
#instr = usbtmc.Instrument(idVendor=0x0699, idProduct=0x03a6)
self.write('HEADER on\n')
def write(self, data):
os.write(self.usbtmc, data)
def read(self, length = 4000):
return os.read(self.usbtmc, length)
def readline(self):
return self.read() #.strip()
def _readline(self):
buf = ''
new = self.read(1)
while new != '\n':
buf = buf+new
new=self.read(1)
return buf
def usb(self):
"""
USB End of Message (EOM) Terminators. The EOM bit must be set in
the USB header of the last transfer of a command message. See the
USB Test and Measurement Class Specification (USBTMC) section
3.2.1 for details. The oscilloscope terminates messages by setting
the EOM bit in the USB header of the last transfer of a message to
the host (USBTMC Specification section 3.3.1), and by terminating
messages with a LF. White space is allowed before the terminator;
for example, CR LF is acceptable.
"""
try:
import usb.core
import usb.util
except:
print 'No PyUSB'
raise
# find our device
dev = usb.core.find(idVendor=0x0699, idProduct=0x03a6)
# was it found?
if dev is None:
raise ValueError('Device not found')
# set the active configuration. With no arguments, the first
# configuration will be the active one
dev.set_configuration()
# get an endpoint instance
cfg = dev.get_active_configuration()
intf = cfg[(0,0)]
ep = usb.util.find_descriptor(
intf,
# match the first OUT endpoint
custom_match = lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_OUT
)
assert ep is not None
self.read = ep.read
self.readline = self._readline
self.write = ep.write
def clear(self):
"""
From a USB host, send an INITIATE_CLEAR followed by a
CHECK_CLEAR_STATUS. The USB interface responds to
CHECK_CLEAR_STATUS with STATUS_SUCCESS when it is
finished clearing the output queue.
"""
print "Clear() not implemented"
if __name__ == '__main__':
TimeStamp = datetime.datetime.now().isoformat().replace(':', '-').split('.')[0]
if 0:
tds2024 = TDS2024(debug=True)
else:
tds2024=USBScope(port='/dev/usbtmc0', debug=True)
if 0:
from pickle import dump, load
# can't pickle the instance. have to try grabbing only attributed ....
acqD = {3:('FALL', 'RISE', 'PK2P', 'MAXI'), 2: ('FALL', 'RISE', 'MAXI'), 1: ('FALL', 'RISE', 'MAXI') }
tds2024.acquire(acqD )
tds2024.dump()
if 1:
mT = ('FALL', 'RISE', 'PK2P', 'CRMS')
mT= ('FALL', 'RISE', 'MINI', 'MAXI')
#mT=('MEAN', )
tds2024.setTrigger(level=4.40, holdo=None, mode='NORMAL', typ='EDGE', trigD={'SOU':'CH2', 'SLO':'FAL'})
tds2024.setAcqState('RUN', stopAfter='RUNST')
print tds2024.getTrigger(forceAcq=True)
#acqD = {4:mT, 3: mT, 2:mT, 1: mT}
acqD = {1: mT}
tds2024.acquire(acqD )
ScopeDisplay(tds2024, idStr=TimeStamp, disp=True, save=True)
if 0: # options please!!!!
tds2024.showFileSystem()
if 0:
acqD = {2: ('MEAN',)}
tds2024.measLoop(acqD)