0
# Core Backend Functionality
1
2
The PyVisaLibrary class provides the main VISA backend implementation for PyVISA-py, managing sessions, dispatching operations to appropriate session classes, and maintaining VISA compliance. This is the core component that users interact with through PyVISA's resource manager.
3
4
## Capabilities
5
6
### PyVisaLibrary Class
7
8
Main backend implementation that serves as a dispatcher for VISA operations, managing sessions and providing the interface between PyVISA and the protocol-specific session implementations.
9
10
```python { .api }
11
class PyVisaLibrary:
12
"""Pure Python backend for PyVISA."""
13
14
def get_library_paths():
15
"""
16
List library paths for backend identification.
17
18
Returns:
19
Iterable[LibraryPath]: Dummy library path tuple
20
"""
21
22
def get_debug_info():
23
"""
24
Return backend debugging information.
25
26
Returns:
27
DebugInfo: Dictionary with version and session class status
28
"""
29
30
def open(self, session, resource_name, access_mode=constants.AccessModes.no_lock, open_timeout=constants.VI_TMO_IMMEDIATE):
31
"""
32
Open a session to the specified resource.
33
34
Args:
35
session (VISARMSession): Resource Manager session handle
36
resource_name (str): Unique symbolic name of resource
37
access_mode (constants.AccessModes): Resource access mode
38
open_timeout (int): Maximum wait time in milliseconds
39
40
Returns:
41
Tuple[VISASession, StatusCode]: Session handle and status
42
"""
43
44
def close(self, session):
45
"""
46
Close the specified session, event, or resource manager.
47
48
Args:
49
session (Union[VISASession, VISAEventContext, VISARMSession]): Session handle
50
51
Returns:
52
StatusCode: Operation result
53
"""
54
55
def read(self, session, count):
56
"""
57
Read data from device synchronously.
58
59
Args:
60
session (VISASession): Session handle
61
count (int): Number of bytes to read
62
63
Returns:
64
Tuple[bytes, StatusCode]: Data read and status
65
"""
66
67
def write(self, session, data):
68
"""
69
Write data to device synchronously.
70
71
Args:
72
session (VISASession): Session handle
73
data (bytes): Data to write
74
75
Returns:
76
Tuple[int, StatusCode]: Bytes written and status
77
"""
78
79
def buffer_read(self, session, count):
80
"""
81
Read data through formatted I/O buffer.
82
83
Args:
84
session (VISASession): Session handle
85
count (int): Number of bytes to read
86
87
Returns:
88
Tuple[bytes, StatusCode]: Data read and status
89
"""
90
91
def buffer_write(self, session, data):
92
"""
93
Write data to formatted I/O buffer.
94
95
Args:
96
session (VISASession): Session handle
97
data (bytes): Data to write
98
99
Returns:
100
Tuple[int, StatusCode]: Bytes written and status
101
"""
102
103
def list_resources(self, session, query="?*::INSTR"):
104
"""
105
Return tuple of all connected devices matching query.
106
107
Args:
108
session (VISARMSession): Resource manager session handle
109
query (str): Regular expression to match devices
110
111
Returns:
112
Tuple[str, ...]: Resource names matching query
113
"""
114
115
def open_default_resource_manager(self):
116
"""
117
Return session to Default Resource Manager.
118
119
Returns:
120
Tuple[VISARMSession, StatusCode]: RM session handle and status
121
"""
122
```
123
124
### Device Control Operations
125
126
Operations for controlling instrument behavior, clearing buffers, and managing device state.
127
128
```python { .api }
129
def clear(self, session):
130
"""
131
Clear a device.
132
133
Args:
134
session (VISASession): Session handle
135
136
Returns:
137
StatusCode: Operation result
138
"""
139
140
def flush(self, session, mask):
141
"""
142
Flush specified buffers.
143
144
Args:
145
session (VISASession): Session handle
146
mask (constants.BufferOperation): Buffer flush operation
147
148
Returns:
149
StatusCode: Operation result
150
"""
151
152
def assert_trigger(self, session, protocol):
153
"""
154
Assert software or hardware trigger.
155
156
Args:
157
session (VISASession): Session handle
158
protocol (constants.TriggerProtocol): Trigger protocol
159
160
Returns:
161
StatusCode: Operation result
162
"""
163
164
def read_stb(self, session):
165
"""
166
Read service request status byte.
167
168
Args:
169
session (VISASession): Session handle
170
171
Returns:
172
Tuple[int, StatusCode]: Status byte and operation result
173
"""
174
```
175
176
### Attribute Management
177
178
VISA attribute getting and setting for configuring session behavior and communication parameters.
179
180
```python { .api }
181
def get_attribute(self, session, attribute):
182
"""
183
Retrieve the state of a VISA attribute.
184
185
Args:
186
session (Union[VISASession, VISAEventContext, VISARMSession]): Session handle
187
attribute (Union[constants.ResourceAttribute, constants.EventAttribute]): Attribute to query
188
189
Returns:
190
Tuple[Any, StatusCode]: Attribute value and status
191
"""
192
193
def set_attribute(self, session, attribute, attribute_state):
194
"""
195
Set the state of a VISA attribute.
196
197
Args:
198
session (VISASession): Session handle
199
attribute (constants.ResourceAttribute): Attribute to modify
200
attribute_state (Any): New attribute value
201
202
Returns:
203
StatusCode: Operation result
204
"""
205
```
206
207
### Resource Locking
208
209
VISA-compliant resource locking for exclusive and shared access to instruments.
210
211
```python { .api }
212
def lock(self, session, lock_type, timeout, requested_key=None):
213
"""
214
Establish access mode to specified resource.
215
216
Args:
217
session (VISASession): Session handle
218
lock_type (constants.Lock): Type of lock requested
219
timeout (int): Lock timeout in milliseconds
220
requested_key (Optional[str]): Key for shared locks
221
222
Returns:
223
Tuple[str, StatusCode]: Lock key and status
224
"""
225
226
def unlock(self, session):
227
"""
228
Relinquish lock for specified resource.
229
230
Args:
231
session (VISASession): Session handle
232
233
Returns:
234
StatusCode: Operation result
235
"""
236
```
237
238
### GPIB Control Operations
239
240
Specialized operations for GPIB bus control and instrument management.
241
242
```python { .api }
243
def gpib_command(self, session, command_byte):
244
"""
245
Write GPIB command bytes on the bus.
246
247
Args:
248
session (VISASession): Session handle
249
command_byte (bytes): Command data to write
250
251
Returns:
252
Tuple[int, StatusCode]: Bytes written and status
253
"""
254
255
def gpib_send_ifc(self, session):
256
"""
257
Pulse interface clear line (IFC) for at least 100 microseconds.
258
259
Args:
260
session (VISASession): Session handle
261
262
Returns:
263
StatusCode: Operation result
264
"""
265
266
def gpib_control_ren(self, session, mode):
267
"""
268
Control state of GPIB Remote Enable (REN) interface line.
269
270
Args:
271
session (VISASession): Session handle
272
mode (constants.RENLineOperation): REN line state
273
274
Returns:
275
StatusCode: Operation result
276
"""
277
278
def gpib_control_atn(self, session, mode):
279
"""
280
Control state of ATN line and local active controller state.
281
282
Args:
283
session (VISASession): Session handle
284
mode (constants.ATNLineOperation): ATN line state
285
286
Returns:
287
StatusCode: Operation result
288
"""
289
290
def gpib_pass_control(self, session, primary_address, secondary_address):
291
"""
292
Tell GPIB device to become controller in charge (CIC).
293
294
Args:
295
session (VISASession): Session handle
296
primary_address (int): Primary GPIB address
297
secondary_address (int): Secondary GPIB address
298
299
Returns:
300
StatusCode: Operation result
301
"""
302
```
303
304
## Usage Examples
305
306
### Basic Backend Usage
307
308
```python
309
from pyvisa_py import PyVisaLibrary
310
from pyvisa.constants import StatusCode
311
312
# Create backend instance
313
backend = PyVisaLibrary()
314
315
# Open default resource manager
316
rm_session, status = backend.open_default_resource_manager()
317
if status != StatusCode.success:
318
raise RuntimeError("Failed to open resource manager")
319
320
# List available resources
321
resources = backend.list_resources(rm_session)
322
print("Available resources:", resources)
323
324
# Open resource session
325
if resources:
326
session, status = backend.open(rm_session, resources[0])
327
if status == StatusCode.success:
328
# Perform operations
329
data, status = backend.read(session, 1024)
330
if status == StatusCode.success:
331
print("Read data:", data)
332
333
# Close session
334
backend.close(session)
335
336
# Close resource manager
337
backend.close(rm_session)
338
```
339
340
### Attribute Configuration
341
342
```python
343
# Set timeout attribute
344
status = backend.set_attribute(session, constants.VI_ATTR_TMO_VALUE, 5000)
345
346
# Get current timeout
347
timeout, status = backend.get_attribute(session, constants.VI_ATTR_TMO_VALUE)
348
print(f"Current timeout: {timeout} ms")
349
350
# Set read termination character
351
status = backend.set_attribute(session, constants.VI_ATTR_TERMCHAR, ord('\\n'))
352
```
353
354
### Resource Locking
355
356
```python
357
# Acquire exclusive lock
358
key, status = backend.lock(session, constants.Lock.exclusive, 1000)
359
if status == StatusCode.success:
360
try:
361
# Perform exclusive operations
362
backend.write(session, b"*RST\\n")
363
response, status = backend.read(session, 1024)
364
finally:
365
# Always release lock
366
backend.unlock(session)
367
```
368
369
## Error Handling
370
371
The backend properly handles and translates errors from underlying session implementations:
372
373
```python
374
try:
375
session, status = backend.open(rm_session, "INVALID::RESOURCE")
376
if status != StatusCode.success:
377
print(f"Failed to open resource: {status}")
378
except Exception as e:
379
print(f"Unexpected error: {e}")
380
```
381
382
## Session Management
383
384
The backend maintains a registry of active sessions with unique random identifiers:
385
386
- Sessions are automatically created and registered when resources are opened
387
- Each session maps to a protocol-specific session class (SerialSession, USBSession, etc.)
388
- Session cleanup is handled when sessions are closed
389
- Invalid session handles return appropriate VISA error codes