Debian Codegraph @

pymeasure/instruments/instrument.py

raw
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 import time
27 from warnings import warn
28
29 from .common_base import CommonBase
30 from ..adapters.visa import VISAAdapter
31
32 log = logging.getLogger(__name__)
33 log.addHandler(logging.NullHandler())
34
35
36 class Instrument(CommonBase):
37 """ The base class for all Instrument definitions.
38
39 It makes use of one of the :py:class:`~pymeasure.adapters.Adapter` classes for communication
40 with the connected hardware device. This decouples the instrument/command definition from the
41 specific communication interface used.
42
43 When ``adapter`` is a string, this is taken as an appropriate resource name. Depending on your
44 installed VISA library, this can be something simple like ``COM1`` or ``ASRL2``, or a more
45 complicated
46 `VISA resource name <https://pyvisa.readthedocs.io/en/latest/introduction/names.html>`__
47 defining the target of your connection.
48
49 When ``adapter`` is an integer, a GPIB resource name is created based on that.
50 In either case a :py:class:`~pymeasure.adapters.VISAAdapter` is constructed based on that
51 resource name.
52 Keyword arguments can be used to further configure the connection.
53
54 Otherwise, the passed :py:class:`~pymeasure.adapters.Adapter` object is used and any keyword
55 arguments are discarded.
56
57 This class defines basic SCPI commands by default. This can be disabled with
58 :code:`includeSCPI` for instruments not compatible with the standard SCPI commands.
59
60 :param adapter: A string, integer, or :py:class:`~pymeasure.adapters.Adapter` subclass object
61 :param string name: The name of the instrument. Often the model designation by default.
62 :param includeSCPI: An obligatory boolean, which toggles the inclusion of standard SCPI commands
63
64 .. deprecated:: 0.14
65 If True, inherit the :class:`~pymeasure.instruments.generic_types.SCPIMixin` class
66 instead.
67
68 :param preprocess_reply: An optional callable used to preprocess
69 strings received from the instrument. The callable returns the
70 processed string.
71
72 .. deprecated:: 0.11
73 Implement it in the instrument's `read` method instead.
74 :param \\**kwargs: In case ``adapter`` is a string or integer, additional arguments passed on
75 to :py:class:`~pymeasure.adapters.VISAAdapter` (check there for details).
76 Discarded otherwise.
77 """
78
79 # noinspection PyPep8Naming
80 def __init__(self, adapter, name, includeSCPI=None,
81 preprocess_reply=None,
82 **kwargs):
83 # Setup communication before possible children require the adapter.
84 if isinstance(adapter, (int, str)):
85 try:
86 adapter = VISAAdapter(adapter, **kwargs)
87 except ImportError:
88 raise Exception("Invalid Adapter provided for Instrument since"
89 " PyVISA is not present")
90 self.adapter = adapter
91 if includeSCPI is True:
92 warn("Defining SCPI base functionality with `includeSCPI=True` is deprecated, inherit "
93 "the `SCPIMixin` class instead.", FutureWarning)
94 elif includeSCPI is None:
95 warn("It is deprecated to specify `includeSCPI` implicitly, use "
96 "`includeSCPI=False` or inherit the `SCPIMixin` class instead.", FutureWarning)
97 includeSCPI = True
98 self.SCPI = includeSCPI
99 self.isShutdown = False
100 self.name = name
101
102 super().__init__(preprocess_reply=preprocess_reply)
103
104 log.info("Initializing %s." % self.name)
105
106 def __enter__(self):
107 return self
108
109 def __exit__(self, exc_type, exc_val, exc_tb):
110 self.shutdown()
111
112 # SCPI default properties
113 @property
114 def complete(self):
115 """Get the synchronization bit.
116
117 This property allows synchronization between a controller and a device. The Operation
118 Complete query places an ASCII character 1 into the device's Output Queue when all pending
119 selected device operations have been finished.
120 """
121 if self.SCPI:
122 return self.ask("*OPC?").strip()
123 else:
124 raise NotImplementedError("Non SCPI instruments require implementation in subclasses")
125
126 @property
127 def status(self):
128 """ Get the status byte and Master Summary Status bit. """
129 if self.SCPI:
130 return self.ask("*STB?").strip()
131 else:
132 raise NotImplementedError("Non SCPI instruments require implementation in subclasses")
133
134 @property
135 def options(self):
136 """ Get the device options installed. """
137 if self.SCPI:
138 return self.ask("*OPT?").strip()
139 else:
140 raise NotImplementedError("Non SCPI instruments require implementation in subclasses")
141
142 @property
143 def id(self):
144 """ Get the identification of the instrument. """
145 if self.SCPI:
146 return self.ask("*IDN?").strip()
147 else:
148 raise NotImplementedError("Non SCPI instruments require implementation in subclasses")
149
150 @property
151 def next_error(self):
152 """Get the next error of the instrument (tuple of code and message)."""
153 if self.SCPI:
154 return self.values("SYST:ERR?")
155 else:
156 raise NotImplementedError("Non SCPI instruments require implementation in subclasses")
157
158 # Wrapper functions for the Adapter object
159 def write(self, command, **kwargs):
160 """Write a string command to the instrument appending `write_termination`.
161
162 :param command: command string to be sent to the instrument
163 :param kwargs: Keyword arguments for the adapter.
164 """
165 self.adapter.write(command, **kwargs)
166
167 def write_bytes(self, content, **kwargs):
168 """Write the bytes `content` to the instrument."""
169 self.adapter.write_bytes(content, **kwargs)
170
171 def read(self, **kwargs):
172 """Read up to (excluding) `read_termination` or the whole read buffer."""
173 return self.adapter.read(**kwargs)
174
175 def read_bytes(self, count, **kwargs):
176 """Read a certain number of bytes from the instrument.
177
178 :param int count: Number of bytes to read. A value of -1 indicates to
179 read the whole read buffer.
180 :param kwargs: Keyword arguments for the adapter.
181 :returns bytes: Bytes response of the instrument (including termination).
182 """
183 return self.adapter.read_bytes(count, **kwargs)
184
185 def write_binary_values(self, command, values, *args, **kwargs):
186 """Write binary values to the device.
187
188 :param command: Command to send.
189 :param values: The values to transmit.
190 :param \\*args, \\**kwargs: Further arguments to hand to the Adapter.
191 """
192 self.adapter.write_binary_values(command, values, *args, **kwargs)
193
194 def read_binary_values(self, **kwargs):
195 """Read binary values from the device."""
196 return self.adapter.read_binary_values(**kwargs)
197
198 # Communication functions
199 def wait_for(self, query_delay=None):
200 """Wait for some time. Used by 'ask' to wait before reading.
201
202 :param query_delay: Delay between writing and reading in seconds. None is default delay.
203 """
204 if query_delay:
205 time.sleep(query_delay)
206
207 # SCPI default methods
208 def clear(self):
209 """ Clears the instrument status byte
210 """
211 if self.SCPI:
212 self.write("*CLS")
213 else:
214 raise NotImplementedError("Non SCPI instruments require implementation in subclasses")
215
216 def reset(self):
217 """ Resets the instrument. """
218 if self.SCPI:
219 self.write("*RST")
220 else:
221 raise NotImplementedError("Non SCPI instruments require implementation in subclasses")
222
223 def shutdown(self):
224 """Brings the instrument to a safe and stable state"""
225 self.isShutdown = True
226 log.info(f"Finished shutting down {self.name}")
227
228 def check_errors(self):
229 """Read all errors from the instrument and log them.
230
231 :return: List of error entries.
232 """
233 if self.SCPI:
234 errors = []
235 while True:
236 err = self.next_error
237 if int(err[0]) != 0:
238 log.error(f"{self.name}: {err[0]}, {err[1]}")
239 errors.append(err)
240 else:
241 break
242 return errors
243 else:
244 raise NotImplementedError("Non SCPI instruments require implementation in subclasses")
245
246 def check_get_errors(self):
247 """Check for errors after having gotten a property and log them.
248
249 Called if :code:`check_get_errors=True` is set for that property.
250
251 If you override this method, you may choose to raise an Exception for certain errors.
252
253 :return: List of error entries.
254 """
255 return self.check_errors()
256
257 def check_set_errors(self):
258 """Check for errors after having set a property and log them.
259
260 Called if :code:`check_set_errors=True` is set for that property.
261
262 If you override this method, you may choose to raise an Exception for certain errors.
263
264 :return: List of error entries.
265 """
266 return self.check_errors()