Pure Python implementation of a VISA library for instrument communication.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
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.
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.
class PyVisaLibrary:
"""Pure Python backend for PyVISA."""
def get_library_paths():
"""
List library paths for backend identification.
Returns:
Iterable[LibraryPath]: Dummy library path tuple
"""
def get_debug_info():
"""
Return backend debugging information.
Returns:
DebugInfo: Dictionary with version and session class status
"""
def open(self, session, resource_name, access_mode=constants.AccessModes.no_lock, open_timeout=constants.VI_TMO_IMMEDIATE):
"""
Open a session to the specified resource.
Args:
session (VISARMSession): Resource Manager session handle
resource_name (str): Unique symbolic name of resource
access_mode (constants.AccessModes): Resource access mode
open_timeout (int): Maximum wait time in milliseconds
Returns:
Tuple[VISASession, StatusCode]: Session handle and status
"""
def close(self, session):
"""
Close the specified session, event, or resource manager.
Args:
session (Union[VISASession, VISAEventContext, VISARMSession]): Session handle
Returns:
StatusCode: Operation result
"""
def read(self, session, count):
"""
Read data from device synchronously.
Args:
session (VISASession): Session handle
count (int): Number of bytes to read
Returns:
Tuple[bytes, StatusCode]: Data read and status
"""
def write(self, session, data):
"""
Write data to device synchronously.
Args:
session (VISASession): Session handle
data (bytes): Data to write
Returns:
Tuple[int, StatusCode]: Bytes written and status
"""
def buffer_read(self, session, count):
"""
Read data through formatted I/O buffer.
Args:
session (VISASession): Session handle
count (int): Number of bytes to read
Returns:
Tuple[bytes, StatusCode]: Data read and status
"""
def buffer_write(self, session, data):
"""
Write data to formatted I/O buffer.
Args:
session (VISASession): Session handle
data (bytes): Data to write
Returns:
Tuple[int, StatusCode]: Bytes written and status
"""
def list_resources(self, session, query="?*::INSTR"):
"""
Return tuple of all connected devices matching query.
Args:
session (VISARMSession): Resource manager session handle
query (str): Regular expression to match devices
Returns:
Tuple[str, ...]: Resource names matching query
"""
def open_default_resource_manager(self):
"""
Return session to Default Resource Manager.
Returns:
Tuple[VISARMSession, StatusCode]: RM session handle and status
"""Operations for controlling instrument behavior, clearing buffers, and managing device state.
def clear(self, session):
"""
Clear a device.
Args:
session (VISASession): Session handle
Returns:
StatusCode: Operation result
"""
def flush(self, session, mask):
"""
Flush specified buffers.
Args:
session (VISASession): Session handle
mask (constants.BufferOperation): Buffer flush operation
Returns:
StatusCode: Operation result
"""
def assert_trigger(self, session, protocol):
"""
Assert software or hardware trigger.
Args:
session (VISASession): Session handle
protocol (constants.TriggerProtocol): Trigger protocol
Returns:
StatusCode: Operation result
"""
def read_stb(self, session):
"""
Read service request status byte.
Args:
session (VISASession): Session handle
Returns:
Tuple[int, StatusCode]: Status byte and operation result
"""VISA attribute getting and setting for configuring session behavior and communication parameters.
def get_attribute(self, session, attribute):
"""
Retrieve the state of a VISA attribute.
Args:
session (Union[VISASession, VISAEventContext, VISARMSession]): Session handle
attribute (Union[constants.ResourceAttribute, constants.EventAttribute]): Attribute to query
Returns:
Tuple[Any, StatusCode]: Attribute value and status
"""
def set_attribute(self, session, attribute, attribute_state):
"""
Set the state of a VISA attribute.
Args:
session (VISASession): Session handle
attribute (constants.ResourceAttribute): Attribute to modify
attribute_state (Any): New attribute value
Returns:
StatusCode: Operation result
"""VISA-compliant resource locking for exclusive and shared access to instruments.
def lock(self, session, lock_type, timeout, requested_key=None):
"""
Establish access mode to specified resource.
Args:
session (VISASession): Session handle
lock_type (constants.Lock): Type of lock requested
timeout (int): Lock timeout in milliseconds
requested_key (Optional[str]): Key for shared locks
Returns:
Tuple[str, StatusCode]: Lock key and status
"""
def unlock(self, session):
"""
Relinquish lock for specified resource.
Args:
session (VISASession): Session handle
Returns:
StatusCode: Operation result
"""Specialized operations for GPIB bus control and instrument management.
def gpib_command(self, session, command_byte):
"""
Write GPIB command bytes on the bus.
Args:
session (VISASession): Session handle
command_byte (bytes): Command data to write
Returns:
Tuple[int, StatusCode]: Bytes written and status
"""
def gpib_send_ifc(self, session):
"""
Pulse interface clear line (IFC) for at least 100 microseconds.
Args:
session (VISASession): Session handle
Returns:
StatusCode: Operation result
"""
def gpib_control_ren(self, session, mode):
"""
Control state of GPIB Remote Enable (REN) interface line.
Args:
session (VISASession): Session handle
mode (constants.RENLineOperation): REN line state
Returns:
StatusCode: Operation result
"""
def gpib_control_atn(self, session, mode):
"""
Control state of ATN line and local active controller state.
Args:
session (VISASession): Session handle
mode (constants.ATNLineOperation): ATN line state
Returns:
StatusCode: Operation result
"""
def gpib_pass_control(self, session, primary_address, secondary_address):
"""
Tell GPIB device to become controller in charge (CIC).
Args:
session (VISASession): Session handle
primary_address (int): Primary GPIB address
secondary_address (int): Secondary GPIB address
Returns:
StatusCode: Operation result
"""from pyvisa_py import PyVisaLibrary
from pyvisa.constants import StatusCode
# Create backend instance
backend = PyVisaLibrary()
# Open default resource manager
rm_session, status = backend.open_default_resource_manager()
if status != StatusCode.success:
raise RuntimeError("Failed to open resource manager")
# List available resources
resources = backend.list_resources(rm_session)
print("Available resources:", resources)
# Open resource session
if resources:
session, status = backend.open(rm_session, resources[0])
if status == StatusCode.success:
# Perform operations
data, status = backend.read(session, 1024)
if status == StatusCode.success:
print("Read data:", data)
# Close session
backend.close(session)
# Close resource manager
backend.close(rm_session)# Set timeout attribute
status = backend.set_attribute(session, constants.VI_ATTR_TMO_VALUE, 5000)
# Get current timeout
timeout, status = backend.get_attribute(session, constants.VI_ATTR_TMO_VALUE)
print(f"Current timeout: {timeout} ms")
# Set read termination character
status = backend.set_attribute(session, constants.VI_ATTR_TERMCHAR, ord('\\n'))# Acquire exclusive lock
key, status = backend.lock(session, constants.Lock.exclusive, 1000)
if status == StatusCode.success:
try:
# Perform exclusive operations
backend.write(session, b"*RST\\n")
response, status = backend.read(session, 1024)
finally:
# Always release lock
backend.unlock(session)The backend properly handles and translates errors from underlying session implementations:
try:
session, status = backend.open(rm_session, "INVALID::RESOURCE")
if status != StatusCode.success:
print(f"Failed to open resource: {status}")
except Exception as e:
print(f"Unexpected error: {e}")The backend maintains a registry of active sessions with unique random identifiers:
Install with Tessl CLI
npx tessl i tessl/pypi-pyvisa-py