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
|
#
# This file is part of the PyMeasure package.
#
# Copyright (c) 2013-2024 PyMeasure Developers
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import logging
import time
from warnings import warn
from .common_base import CommonBase
from ..adapters.visa import VISAAdapter
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())
class Instrument(CommonBase):
""" The base class for all Instrument definitions.
It makes use of one of the :py:class:`~pymeasure.adapters.Adapter` classes for communication
with the connected hardware device. This decouples the instrument/command definition from the
specific communication interface used.
When ``adapter`` is a string, this is taken as an appropriate resource name. Depending on your
installed VISA library, this can be something simple like ``COM1`` or ``ASRL2``, or a more
complicated
`VISA resource name <https://pyvisa.readthedocs.io/en/latest/introduction/names.html>`__
defining the target of your connection.
When ``adapter`` is an integer, a GPIB resource name is created based on that.
In either case a :py:class:`~pymeasure.adapters.VISAAdapter` is constructed based on that
resource name.
Keyword arguments can be used to further configure the connection.
Otherwise, the passed :py:class:`~pymeasure.adapters.Adapter` object is used and any keyword
arguments are discarded.
This class defines basic SCPI commands by default. This can be disabled with
:code:`includeSCPI` for instruments not compatible with the standard SCPI commands.
:param adapter: A string, integer, or :py:class:`~pymeasure.adapters.Adapter` subclass object
:param string name: The name of the instrument. Often the model designation by default.
:param includeSCPI: An obligatory boolean, which toggles the inclusion of standard SCPI commands
.. deprecated:: 0.14
If True, inherit the :class:`~pymeasure.instruments.generic_types.SCPIMixin` class
instead.
:param preprocess_reply: An optional callable used to preprocess
strings received from the instrument. The callable returns the
processed string.
.. deprecated:: 0.11
Implement it in the instrument's `read` method instead.
:param \\**kwargs: In case ``adapter`` is a string or integer, additional arguments passed on
to :py:class:`~pymeasure.adapters.VISAAdapter` (check there for details).
Discarded otherwise.
"""
# noinspection PyPep8Naming
def __init__(self, adapter, name, includeSCPI=None,
preprocess_reply=None,
**kwargs):
# Setup communication before possible children require the adapter.
if isinstance(adapter, (int, str)):
try:
adapter = VISAAdapter(adapter, **kwargs)
except ImportError:
raise Exception("Invalid Adapter provided for Instrument since"
" PyVISA is not present")
self.adapter = adapter
if includeSCPI is True:
warn("Defining SCPI base functionality with `includeSCPI=True` is deprecated, inherit "
"the `SCPIMixin` class instead.", FutureWarning)
elif includeSCPI is None:
warn("It is deprecated to specify `includeSCPI` implicitly, use "
"`includeSCPI=False` or inherit the `SCPIMixin` class instead.", FutureWarning)
includeSCPI = True
self.SCPI = includeSCPI
self.isShutdown = False
self.name = name
super().__init__(preprocess_reply=preprocess_reply)
log.info("Initializing %s." % self.name)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.shutdown()
# SCPI default properties
@property
def complete(self):
"""Get the synchronization bit.
This property allows synchronization between a controller and a device. The Operation
Complete query places an ASCII character 1 into the device's Output Queue when all pending
selected device operations have been finished.
"""
if self.SCPI:
return self.ask("*OPC?").strip()
else:
raise NotImplementedError("Non SCPI instruments require implementation in subclasses")
@property
def status(self):
""" Get the status byte and Master Summary Status bit. """
if self.SCPI:
return self.ask("*STB?").strip()
else:
raise NotImplementedError("Non SCPI instruments require implementation in subclasses")
@property
def options(self):
""" Get the device options installed. """
if self.SCPI:
return self.ask("*OPT?").strip()
else:
raise NotImplementedError("Non SCPI instruments require implementation in subclasses")
@property
def id(self):
""" Get the identification of the instrument. """
if self.SCPI:
return self.ask("*IDN?").strip()
else:
raise NotImplementedError("Non SCPI instruments require implementation in subclasses")
@property
def next_error(self):
"""Get the next error of the instrument (tuple of code and message)."""
if self.SCPI:
return self.values("SYST:ERR?")
else:
raise NotImplementedError("Non SCPI instruments require implementation in subclasses")
# Wrapper functions for the Adapter object
def write(self, command, **kwargs):
"""Write a string command to the instrument appending `write_termination`.
:param command: command string to be sent to the instrument
:param kwargs: Keyword arguments for the adapter.
"""
self.adapter.write(command, **kwargs)
def write_bytes(self, content, **kwargs):
"""Write the bytes `content` to the instrument."""
self.adapter.write_bytes(content, **kwargs)
def read(self, **kwargs):
"""Read up to (excluding) `read_termination` or the whole read buffer."""
return self.adapter.read(**kwargs)
def read_bytes(self, count, **kwargs):
"""Read a certain number of bytes from the instrument.
:param int count: Number of bytes to read. A value of -1 indicates to
read the whole read buffer.
:param kwargs: Keyword arguments for the adapter.
:returns bytes: Bytes response of the instrument (including termination).
"""
return self.adapter.read_bytes(count, **kwargs)
def write_binary_values(self, command, values, *args, **kwargs):
"""Write binary values to the device.
:param command: Command to send.
:param values: The values to transmit.
:param \\*args, \\**kwargs: Further arguments to hand to the Adapter.
"""
self.adapter.write_binary_values(command, values, *args, **kwargs)
def read_binary_values(self, **kwargs):
"""Read binary values from the device."""
return self.adapter.read_binary_values(**kwargs)
# Communication functions
def wait_for(self, query_delay=None):
"""Wait for some time. Used by 'ask' to wait before reading.
:param query_delay: Delay between writing and reading in seconds. None is default delay.
"""
if query_delay:
time.sleep(query_delay)
# SCPI default methods
def clear(self):
""" Clears the instrument status byte
"""
if self.SCPI:
self.write("*CLS")
else:
raise NotImplementedError("Non SCPI instruments require implementation in subclasses")
def reset(self):
""" Resets the instrument. """
if self.SCPI:
self.write("*RST")
else:
raise NotImplementedError("Non SCPI instruments require implementation in subclasses")
def shutdown(self):
"""Brings the instrument to a safe and stable state"""
self.isShutdown = True
log.info(f"Finished shutting down {self.name}")
def check_errors(self):
"""Read all errors from the instrument and log them.
:return: List of error entries.
"""
if self.SCPI:
errors = []
while True:
err = self.next_error
if int(err[0]) != 0:
log.error(f"{self.name}: {err[0]}, {err[1]}")
errors.append(err)
else:
break
return errors
else:
raise NotImplementedError("Non SCPI instruments require implementation in subclasses")
def check_get_errors(self):
"""Check for errors after having gotten a property and log them.
Called if :code:`check_get_errors=True` is set for that property.
If you override this method, you may choose to raise an Exception for certain errors.
:return: List of error entries.
"""
return self.check_errors()
def check_set_errors(self):
"""Check for errors after having set a property and log them.
Called if :code:`check_set_errors=True` is set for that property.
If you override this method, you may choose to raise an Exception for certain errors.
:return: List of error entries.
"""
return self.check_errors()
|