-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstrument_controller.py
More file actions
381 lines (272 loc) · 8.96 KB
/
instrument_controller.py
File metadata and controls
381 lines (272 loc) · 8.96 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
#!/usr/bin/env python
# coding: utf-8
# # Instrument Controller
# Parent class for instrument control
# ## API
# ### SCPI Commands
# Generic SCPI commands can be executed by transforming the SCPI code in to attributes iva the hierarchy relationship, then calling it. Instrument properties can be queried by passing no arguments to the call. Commands with no arguments are run by passing an empty string to the call.
#
# #### Examples
# `inst = Instrument()`
#
#
# ### Methods
# **Instrument(port, timeout)** Creates an instance of an instrument
#
# **connect()** Connects the program to the instrument
#
# **disconnect()** Disconnects the instrument from the program, closing the port
#
# **write( msg )** Sends **msg** to the instrument
#
# **read()** Gets the most recent response from the instrument
#
# **query( msg )** Sends **msg** to the instrument and returns its response
#
# **reset()** Sets the instruemnt to its default state
#
# **init()** Initializes the instrument for a measurement
#
# ### Properties
# **port** The communication port
#
# **rid** The resource id associated with the instrument [Read Only]
#
# **timeout** The communication timeout of the instrument [Read Only]
#
# **id** The manufacturer id of the instrument [Read Only]
#
# **value** The current value of the instrument [Read Only]
#
# **connected** Whether the instrument is connected or not [Read Only]
# In[4]:
# standard imports
import os
import sys
import serial
import re
from enum import Enum
from aenum import MultiValueEnum
# import logging
# logging.basicConfig( level = logging.DEBUG )
# SCPI imports
import visa
# In[5]:
class Property( object ):
"""
Represents a scpi property of the instrument
"""
#--- static variables ---
ON = 'ON'
OFF = 'OFF'
#--- class methods ---
def __init__( self, inst, name ):
self.__inst = inst # the instrument
self.name = name.upper()
def __getattr__( self, name ):
return Property(
self.__inst,
':'.join( ( self.name, name.upper() ) )
)
def __call__( self, value = None ):
if value is None:
# get property
return self.__inst.query( self.name + '?')
else:
# set value
if isinstance( value, Enum ):
# get value from enum
value = value.value
if not isinstance( value, str ):
# try to convert value to string
value = str( value )
return self.__inst.write( self.name + ' ' + value )
#--- static methods ---
@staticmethod
def val2bool( val ):
"""
Converts standard input to boolean values
True: 'on', '1', 1, True
False: 'off', '0', 0, False
"""
if isinstance( val, str ):
# parse string input
val = val.lower()
if val == 'on' or val == '1':
return True
elif val == 'off' or val == '0':
return False
else:
raise ValueError( 'Invalid input' )
return bool( val )
@staticmethod
def val2state( val ):
"""
Converts standard input to scpi state
ON: True, '1', 1, 'on', 'ON'
OFF: False, '0', 0, 'off', 'OFF'
"""
state = Property.val2bool( val )
if state:
return 'ON'
else:
return 'OFF'
# In[6]:
class Instrument():
"""
Represents an instrument
Arbitrary SCPI commands can be performed
treating the hieracrchy of the command as attributes.
To read an property: inst.p1.p2.p3()
To call a function: inst.p1.p2( 'value' )
To execute a command: inst.p1.p2.p3( '' )
"""
#--- methods ---
def __getattr__( self, name ):
return Property( self, name )
def __init__( self, port = None, timeout = 10, read_terminator = None, write_terminator = None, backend = '' ):
#--- private instance vairables ---
self.__rm = visa.ResourceManager( backend ) # the VISA resource manager
self.__inst = None # the ammeter
self.__port = None
self.__rid = None # the resource id of the instrument
self.__timeout = timeout* 1000
self.__read_terminator = read_terminator
self.__write_terminator = write_terminator
# init connection
self.port = port
def __del__( self ):
if self.connected:
self.disconnect()
del self.__inst
del self.__rm
#--- private methods ---
#--- public methods ---
@property
def instrument( self ):
return self.__inst
@property
def port( self ):
return self.__port
@port.setter
def port( self, port ):
"""
Disconnects from current connection and updates port and id.
Does not reconnect.
"""
if self.__inst is not None:
self.disconnect()
self.__port = port
if port is not None:
self.__rid = 'ASRL{}::INSTR'.format( port )
else:
self.__rid = None
@property
def rid( self ):
"""
Return the resource id of the instrument
"""
return self.__rid
@rid.setter
def rid( self, rid ):
self.__rid = rid
@property
def timeout( self ):
return self.__timeout
@property
def id( self ):
"""
Returns the id of the ammeter
"""
return self.query( '*IDN?' )
@property
def value( self ):
"""
Get current value
"""
return self.query( 'READ?' )
@property
def connected( self ):
"""
Returns if the instrument is connected
"""
if self.__inst is None:
return False
try:
# session throws excpetion if not connected
self.__inst.session
return True
except visa.InvalidSession:
return False
def connect( self ):
"""
Connects to the instrument on the given port
"""
if self.__inst is None:
self.__inst = self.__rm.open_resource( self.rid )
self.__inst.timeout = self.__timeout
# set terminators
if self.__read_terminator is not None:
self.__inst.read_termination = self.__read_terminator
if self.__write_terminator is not None:
self.__inst.write_termination = self.__write_terminator
else:
self.__inst.open()
self.id # place instrument in remote control
def disconnect( self ):
"""
Disconnects from the instrument, and returns local control
"""
if self.__inst is not None:
self.syst.loc( '' )
self.__inst.close()
def write( self, msg ):
"""
Delegates write to resource
"""
if self.__inst is None:
raise Exception( 'Can not write, instrument not connected.' )
return
return self.__inst.write( msg )
def read( self ):
"""
Delegates read to resource
"""
if self.__inst is None:
raise Exception( 'Can not read, instrument not connected' )
return
return self.__inst.read()
def query( self, msg ):
"""
Delegates query to resource
"""
if self.__inst is None:
raise Exception( 'Can not query, instrument not connected' )
return self.__inst.query( msg )
def reset( self ):
"""
Resets the meter to inital state
"""
return self.write( '*RST' )
def init( self ):
"""
Initialize the instrument
"""
return self.write( 'INIT' )
# # CLI
# In[1]:
if __name__ == '__main__':
import getopt
#--- helper functions ---
def print_help():
print( """
Instrument Controller CLI
Use:
python instrument_controller.py [port=<COM>] <function> [arguments]
<COM> is the port to connect to [Default: COM14]
<function> is the ammeter command to run
[arguments] is a space separated list of the arguments the function takes
API:
+ write()
+ query()
""")