| 1 |
# |
| 2 |
# This file is part of the PyMeasure package. |
| 3 |
# |
| 4 |
# Copyright (c) 2013-2024 PyMeasure Developers |
| 5 |
# |
| 6 |
# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 7 |
# of this software and associated documentation files (the "Software"), to deal |
| 8 |
# in the Software without restriction, including without limitation the rights |
| 9 |
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 10 |
# copies of the Software, and to permit persons to whom the Software is |
| 11 |
# furnished to do so, subject to the following conditions: |
| 12 |
# |
| 13 |
# The above copyright notice and this permission notice shall be included in |
| 14 |
# all copies or substantial portions of the Software. |
| 15 |
# |
| 16 |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 22 |
# THE SOFTWARE. |
| 23 |
# |
| 24 |
|
| 25 |
import logging |
| 26 |
from warnings import warn |
| 27 |
|
| 28 |
import pyvisa |
| 29 |
import numpy as np |
| 30 |
|
| 31 |
from .adapter import Adapter |
| 32 |
from .protocol import ProtocolAdapter |
| 33 |
|
| 34 |
log = logging.getLogger(__name__) |
| 35 |
log.addHandler(logging.NullHandler()) |
| 36 |
|
| 37 |
|
| 38 |
# noinspection PyPep8Naming,PyUnresolvedReferences |
| 39 |
class VISAAdapter(Adapter): |
| 40 |
""" Adapter class for the VISA library, using PyVISA to communicate with instruments. |
| 41 |
|
| 42 |
The workhorse of our library, used by most instruments. |
| 43 |
|
| 44 |
:param resource_name: A |
| 45 |
`VISA resource string <https://pyvisa.readthedocs.io/en/latest/introduction/names.html>`__ |
| 46 |
or GPIB address integer that identifies the target of the connection |
| 47 |
:param visa_library: PyVISA VisaLibrary Instance, path of the VISA library or VisaLibrary spec |
| 48 |
string (``@py`` or ``@ivi``). If not given, the default for the platform will be used. |
| 49 |
:param preprocess_reply: An optional callable used to preprocess strings |
| 50 |
received from the instrument. The callable returns the processed string. |
| 51 |
|
| 52 |
.. deprecated:: 0.11 |
| 53 |
Implement it in the instrument's `read` method instead. |
| 54 |
|
| 55 |
:param float query_delay: Time in s to wait after writing and before reading. |
| 56 |
|
| 57 |
.. deprecated:: 0.11 |
| 58 |
Implement it in the instrument's `wait_for` method instead. |
| 59 |
|
| 60 |
:param log: Parent logger of the 'Adapter' logger. |
| 61 |
:param \\**kwargs: Keyword arguments for configuring the PyVISA connection. |
| 62 |
|
| 63 |
:Kwargs: |
| 64 |
Keyword arguments are used to configure the connection created by PyVISA. This is |
| 65 |
complicated by the fact that *which* arguments are valid depends on the interface (e.g. |
| 66 |
serial, GPIB, TCPI/IP, USB) determined by the current ``resource_name``. |
| 67 |
|
| 68 |
A flexible process is used to easily define reasonable *default values* for |
| 69 |
different instrument interfaces, but also enable the instrument user to *override any |
| 70 |
setting* if their situation demands it. |
| 71 |
|
| 72 |
A kwarg that names a pyVISA interface type (most commonly ``asrl``, ``gpib``, ``tcpip``, or |
| 73 |
``usb``) is a dictionary with keyword arguments defining defaults specific to that |
| 74 |
interface. Example: ``asrl={'baud_rate': 4200}``. |
| 75 |
|
| 76 |
All other kwargs are either generally valid (e.g. ``timeout=500``) or override any default |
| 77 |
settings from the interface-specific entries above. For example, passing |
| 78 |
``baud_rate=115200`` when connecting via a resource name ``ASRL1`` would override a |
| 79 |
default of 4200 defined as above. |
| 80 |
|
| 81 |
See :ref:`connection_settings` for how to tweak settings when *connecting* to an instrument. |
| 82 |
See :ref:`default_connection_settings` for how to best define default settings when |
| 83 |
*implementing an instrument*. |
| 84 |
""" |
| 85 |
|
| 86 |
def __init__(self, resource_name, visa_library='', preprocess_reply=None, |
| 87 |
query_delay=0, log=None, **kwargs): |
| 88 |
super().__init__(preprocess_reply=preprocess_reply, log=log) |
| 89 |
if query_delay: |
| 90 |
warn(("Parameter `query_delay` is deprecated. " |
| 91 |
"Implement in Instrument's `wait_for` instead."), |
| 92 |
FutureWarning) |
| 93 |
kwargs.setdefault("query_delay", query_delay) |
| 94 |
self.query_delay = query_delay |
| 95 |
if isinstance(resource_name, ProtocolAdapter): |
| 96 |
self.connection = resource_name |
| 97 |
self.connection.write_raw = self.connection.write_bytes |
| 98 |
self.read_bytes = self.connection.read_bytes |
| 99 |
return |
| 100 |
elif isinstance(resource_name, VISAAdapter): |
| 101 |
# Allow to reuse the connection. |
| 102 |
self.resource_name = getattr(resource_name, "resource_name", None) |
| 103 |
self.connection = resource_name.connection |
| 104 |
self.manager = resource_name.manager |
| 105 |
self.query_delay = resource_name.query_delay |
| 106 |
return |
| 107 |
elif isinstance(resource_name, int): |
| 108 |
resource_name = "GPIB0::%d::INSTR" % resource_name |
| 109 |
|
| 110 |
self.resource_name = resource_name |
| 111 |
self.manager = pyvisa.ResourceManager(visa_library) |
| 112 |
|
| 113 |
# Clean up kwargs considering the interface type matching resource_name |
| 114 |
if_type = self.manager.resource_info(self.resource_name).interface_type |
| 115 |
for key in list(kwargs.keys()): # iterate over a copy of the keys as we modify kwargs |
| 116 |
# Remove all interface-specific kwargs: |
| 117 |
if key in pyvisa.constants.InterfaceType.__members__: |
| 118 |
if getattr(pyvisa.constants.InterfaceType, key) is if_type: |
| 119 |
# For the present interface, dump contents into kwargs first if they are not |
| 120 |
# present already. This way, it is possible to override default values with |
| 121 |
# kwargs passed to Instrument.__init__() |
| 122 |
for k, v in kwargs[key].items(): |
| 123 |
kwargs.setdefault(k, v) |
| 124 |
del kwargs[key] |
| 125 |
|
| 126 |
self.connection = self.manager.open_resource( |
| 127 |
resource_name, |
| 128 |
**kwargs |
| 129 |
) |
| 130 |
|
| 131 |
def close(self): |
| 132 |
"""Close the connection. |
| 133 |
|
| 134 |
.. note:: |
| 135 |
|
| 136 |
This closes the connection to the resource for all adapters using |
| 137 |
it currently (e.g. different adapters using the same GPIB line). |
| 138 |
""" |
| 139 |
super().close() |
| 140 |
try: |
| 141 |
if self.manager.visalib.library_path == "unset": |
| 142 |
# if using the pyvisa-sim library the manager has to be also closed. |
| 143 |
# this works around https://github.com/pyvisa/pyvisa-sim/issues/82 |
| 144 |
self.manager.close() |
| 145 |
except AttributeError: |
| 146 |
# AttributeError can occur during __del__ calling close |
| 147 |
pass |
| 148 |
|
| 149 |
def _write(self, command, **kwargs): |
| 150 |
"""Write a string command to the instrument appending `write_termination`. |
| 151 |
|
| 152 |
:param str command: Command string to be sent to the instrument |
| 153 |
(without termination). |
| 154 |
:param \\**kwargs: Keyword arguments for the connection itself. |
| 155 |
""" |
| 156 |
self.connection.write(command, **kwargs) |
| 157 |
|
| 158 |
def _write_bytes(self, content, **kwargs): |
| 159 |
"""Write the bytes `content` to the instrument. |
| 160 |
|
| 161 |
:param bytes content: The bytes to write to the instrument. |
| 162 |
:param \\**kwargs: Keyword arguments for the connection itself. |
| 163 |
""" |
| 164 |
self.connection.write_raw(content, **kwargs) |
| 165 |
|
| 166 |
def _read(self, **kwargs): |
| 167 |
"""Read up to (excluding) `read_termination` or the whole read buffer. |
| 168 |
|
| 169 |
:param \\**kwargs: Keyword arguments for the connection itself. |
| 170 |
:returns str: ASCII response of the instrument (excluding read_termination). |
| 171 |
""" |
| 172 |
return self.connection.read(**kwargs) |
| 173 |
|
| 174 |
def _read_bytes(self, count, break_on_termchar=False, **kwargs): |
| 175 |
"""Read a certain number of bytes from the instrument. |
| 176 |
|
| 177 |
:param int count: Number of bytes to read. A value of -1 indicates to |
| 178 |
read from the whole read buffer until timeout. |
| 179 |
:param bool break_on_termchar: Stop reading at a termination character. |
| 180 |
:param \\**kwargs: Keyword arguments for the connection itself. |
| 181 |
:returns bytes: Bytes response of the instrument (including termination). |
| 182 |
""" |
| 183 |
if count >= 0: |
| 184 |
return self.connection.read_bytes(count, break_on_termchar=break_on_termchar, **kwargs) |
| 185 |
elif break_on_termchar: |
| 186 |
return self.connection.read_raw(None, **kwargs) |
| 187 |
else: |
| 188 |
# pyvisa's `read_raw` reads until newline, if no termination_character defined |
| 189 |
# and if not configured to stop at a termination lane etc. |
| 190 |
# see https://github.com/pyvisa/pyvisa/issues/728 |
| 191 |
result = bytearray() |
| 192 |
while True: |
| 193 |
try: |
| 194 |
result.extend(self.connection.read_bytes(1)) |
| 195 |
except pyvisa.errors.VisaIOError as exc: |
| 196 |
if exc.error_code == pyvisa.constants.StatusCode.error_timeout: |
| 197 |
return bytes(result) |
| 198 |
raise |
| 199 |
|
| 200 |
def ask(self, command): |
| 201 |
""" Writes the command to the instrument and returns the resulting |
| 202 |
ASCII response |
| 203 |
|
| 204 |
.. deprecated:: 0.11 |
| 205 |
Call `Instrument.ask` instead. |
| 206 |
|
| 207 |
:param command: SCPI command string to be sent to the instrument |
| 208 |
:returns: String ASCII response of the instrument |
| 209 |
""" |
| 210 |
warn("`Adapter.ask` is deprecated, call `Instrument.ask` instead.", FutureWarning) |
| 211 |
return self.connection.query(command) |
| 212 |
|
| 213 |
def ask_values(self, command, **kwargs): |
| 214 |
""" Writes a command to the instrument and returns a list of formatted |
| 215 |
values from the result. This leverages the `query_ascii_values` method |
| 216 |
in PyVISA. |
| 217 |
|
| 218 |
.. deprecated:: 0.11 |
| 219 |
Call `Instrument.values` instead. |
| 220 |
|
| 221 |
:param command: SCPI command to be sent to the instrument |
| 222 |
:param \\**kwargs: Key-word arguments to pass onto `query_ascii_values` |
| 223 |
:returns: Formatted response of the instrument. |
| 224 |
""" |
| 225 |
warn("`Adapter.ask_values` is deprecated, call `Instrument.values` instead.", |
| 226 |
FutureWarning) |
| 227 |
|
| 228 |
return self.connection.query_ascii_values(command, **kwargs) |
| 229 |
|
| 230 |
def binary_values(self, command, header_bytes=0, dtype=np.float32): |
| 231 |
""" Returns a numpy array from a query for binary data |
| 232 |
|
| 233 |
.. deprecated:: 0.11 |
| 234 |
Call `Instrument.binary_values` instead. |
| 235 |
|
| 236 |
:param command: SCPI command to be sent to the instrument |
| 237 |
:param header_bytes: Integer number of bytes to ignore in header |
| 238 |
:param dtype: The NumPy data type to format the values with |
| 239 |
:returns: NumPy array of values |
| 240 |
""" |
| 241 |
warn("`Adapter.binary_values` is deprecated, call `Instrument.binary_values` instead.", |
| 242 |
FutureWarning) |
| 243 |
self.connection.write(command) |
| 244 |
binary = self.connection.read_raw() |
| 245 |
# header = binary[:header_bytes] |
| 246 |
data = binary[header_bytes:] |
| 247 |
return np.fromstring(data, dtype=dtype) |
| 248 |
|
| 249 |
def wait_for_srq(self, timeout=25, delay=0.1): |
| 250 |
""" Block until a SRQ, and leave the bit high |
| 251 |
|
| 252 |
:param timeout: Timeout duration in seconds |
| 253 |
:param delay: Time delay between checking SRQ in seconds |
| 254 |
""" |
| 255 |
self.connection.wait_for_srq(timeout * 1000) |
| 256 |
|
| 257 |
def flush_read_buffer(self): |
| 258 |
""" Flush and discard the input buffer |
| 259 |
|
| 260 |
As detailed by pyvisa, discard the read and receivee buffer contents |
| 261 |
and if data was present in the read buffer and no END-indicator was present, |
| 262 |
read from the device until encountering an END indicator (which causes loss of data). |
| 263 |
""" |
| 264 |
try: |
| 265 |
self.connection.flush(pyvisa.constants.BufferOperation.discard_read_buffer) |
| 266 |
self.connection.flush(pyvisa.constants.BufferOperation.discard_receive_buffer) |
| 267 |
except NotImplementedError: |
| 268 |
# NotImplementedError is raised when using resource types other than `asrl` |
| 269 |
# in conjunction with pyvisa-py. |
| 270 |
# Upstream issue: https://github.com/pyvisa/pyvisa-py/issues/348 |
| 271 |
# fake discarding the read buffer by reading all available messages. |
| 272 |
timeout = self.connection.timeout |
| 273 |
self.connection.timeout = 0 |
| 274 |
try: |
| 275 |
self.read_bytes(-1) |
| 276 |
except pyvisa.errors.VisaIOError: |
| 277 |
pass |
| 278 |
finally: |
| 279 |
self.connection.timeout = timeout |
| 280 |
|
| 281 |
def __repr__(self): |
| 282 |
return "<VISAAdapter(resource='%s')>" % self.connection.resource_name |