Debian Codegraph @

pymeasure/adapters/adapter.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 from warnings import warn
27
28 import numpy as np
29 from copy import copy
30 from pyvisa.util import to_ieee_block, to_hp_block, to_binary_block
31
32
33 class Adapter:
34 """ Base class for Adapter child classes, which adapt between the Instrument
35 object and the connection, to allow flexible use of different connection
36 techniques.
37
38 This class should only be inherited from.
39
40 :param preprocess_reply: An optional callable used to preprocess
41 strings received from the instrument. The callable returns the
42 processed string.
43
44 .. deprecated:: 0.11
45 Implement it in the instrument's `read` method instead.
46
47 :param log: Parent logger of the 'Adapter' logger.
48 :param \\**kwargs: Keyword arguments just to be cooperative.
49 """
50
51 def __init__(self, preprocess_reply=None, log=None, **kwargs):
52 super().__init__(**kwargs)
53 self.preprocess_reply = preprocess_reply
54 self.connection = None
55 if log is None:
56 self.log = logging.getLogger("Adapter")
57 else:
58 self.log = log.getChild("Adapter")
59 self.log.addHandler(logging.NullHandler())
60 if preprocess_reply is not None:
61 warn(("Parameter `preprocess_reply` is deprecated in Adapter. "
62 "Implement it in the instrument instead."),
63 FutureWarning)
64
65 def __del__(self):
66 """Close connection upon garbage collection of the device."""
67 self.close()
68
69 def close(self):
70 """Close the connection."""
71 if self.connection is not None:
72 self.connection.close()
73
74 # Directly called methods, which ensure proper logging of the communication
75 # without the termination characters added by the particular adapters.
76 # DO NOT OVERRIDE IN SUBCLASS!
77 def write(self, command, **kwargs):
78 """Write a string command to the instrument appending `write_termination`.
79
80 Do not override in a subclass!
81
82 :param str command: Command string to be sent to the instrument
83 (without termination).
84 :param \\**kwargs: Keyword arguments for the connection itself.
85 """
86 self.log.debug("WRITE:%s", command)
87 self._write(command, **kwargs)
88
89 def write_bytes(self, content, **kwargs):
90 """Write the bytes `content` to the instrument.
91
92 Do not override in a subclass!
93
94 :param bytes content: The bytes to write to the instrument.
95 :param \\**kwargs: Keyword arguments for the connection itself.
96 """
97 self.log.debug("WRITE:%s", content)
98 self._write_bytes(content, **kwargs)
99
100 def read(self, **kwargs):
101 """Read up to (excluding) `read_termination` or the whole read buffer.
102
103 Do not override in a subclass!
104
105 :param \\**kwargs: Keyword arguments for the connection itself.
106 :returns str: ASCII response of the instrument (excluding read_termination).
107 """
108 read = self._read(**kwargs)
109 self.log.debug("READ:%s", read)
110 return read
111
112 def read_bytes(self, count=-1, break_on_termchar=False, **kwargs):
113 """Read a certain number of bytes from the instrument.
114
115 Do not override in a subclass!
116
117 :param int count: Number of bytes to read. A value of -1 indicates to
118 read from the whole read buffer.
119 :param bool break_on_termchar: Stop reading at a termination character.
120 :param \\**kwargs: Keyword arguments for the connection itself.
121 :returns bytes: Bytes response of the instrument (including termination).
122 """
123 read = self._read_bytes(count, break_on_termchar, **kwargs)
124 self.log.debug("READ:%s", read)
125 return read
126
127 # Methods to implement in the subclasses.
128 def _write(self, command, **kwargs):
129 """Write string to the instrument. Implement in subclass."""
130 raise NotImplementedError("Adapter class has not implemented writing.")
131
132 def _write_bytes(self, content, **kwargs):
133 """Write bytes to the instrument. Implement in subclass."""
134 raise NotImplementedError("Adapter class has not implemented writing bytes.")
135
136 def _read(self, **kwargs):
137 """Read string from the instrument. Implement in subclass."""
138 raise NotImplementedError("Adapter class has not implemented reading.")
139
140 def _read_bytes(self, count, break_on_termchar, **kwargs):
141 """Read bytes from the instrument. Implement in subclass."""
142 raise NotImplementedError("Adapter class has not implemented reading bytes.")
143
144 def flush_read_buffer(self):
145 """Flush and discard the input buffer. Implement in subclass."""
146 raise NotImplementedError("Adapter class has not implemented input flush.")
147
148 # Deprecated methods.
149 def ask(self, command):
150 """ Write the command to the instrument and returns the resulting
151 ASCII response.
152
153 .. deprecated:: 0.11
154 Call `Instrument.ask` instead.
155
156 :param command: SCPI command string to be sent to the instrument
157 :returns: String ASCII response of the instrument
158 """
159 warn("`Adapter.ask` is deprecated, call `Instrument.ask` instead.", FutureWarning)
160 self.write(command)
161 return self.read()
162
163 def values(self, command, separator=',', cast=float, preprocess_reply=None):
164 """ Write a command to the instrument and returns a list of formatted
165 values from the result.
166
167 .. deprecated:: 0.11
168 Call `Instrument.values` instead.
169
170 :param command: SCPI command to be sent to the instrument
171 :param separator: A separator character to split the string into a list
172 :param cast: A type to cast the result
173 :param preprocess_reply: optional callable used to preprocess values
174 received from the instrument. The callable returns the processed string.
175 If not specified, the Adapter default is used if available, otherwise no
176 preprocessing is done.
177 :returns: A list of the desired type, or strings where the casting fails
178 """
179 warn("`Adapter.values` is deprecated, call `Instrument.values` instead.",
180 FutureWarning)
181 results = str(self.ask(command)).strip()
182 if callable(preprocess_reply):
183 results = preprocess_reply(results)
184 elif callable(self.preprocess_reply):
185 results = self.preprocess_reply(results)
186 results = results.split(separator)
187 for i, result in enumerate(results):
188 try:
189 if cast == bool:
190 # Need to cast to float first since results are usually
191 # strings and bool of a non-empty string is always True
192 results[i] = bool(float(result))
193 else:
194 results[i] = cast(result)
195 except Exception:
196 pass # Keep as string
197 return results
198
199 def binary_values(self, command, header_bytes=0, dtype=np.float32):
200 """ Returns a numpy array from a query for binary data
201
202 .. deprecated:: 0.11
203 Call `Instrument.binary_values` instead.
204
205 :param command: SCPI command to be sent to the instrument
206 :param header_bytes: Integer number of bytes to ignore in header
207 :param dtype: The NumPy data type to format the values with
208 :returns: NumPy array of values
209 """
210 warn("`Adapter.binary_values` is deprecated, call `Instrument.binary_values` instead.",
211 FutureWarning)
212 self.write(command)
213 binary = self.read()
214 # header = binary[:header_bytes]
215 data = binary[header_bytes:]
216 return np.fromstring(data, dtype=dtype)
217
218 # Binary format methods
219 def read_binary_values(self, header_bytes=0, termination_bytes=None,
220 dtype=np.float32, **kwargs):
221 """ Returns a numpy array from a query for binary data
222
223 :param int header_bytes: Number of bytes to ignore in header.
224 :param int termination_bytes: Number of bytes to strip at end of message or None.
225 :param dtype: The NumPy data type to format the values with.
226 :param \\**kwargs: Further arguments for the NumPy fromstring method.
227 :returns: NumPy array of values
228 """
229 binary = self.read_bytes(-1)
230 # header = binary[:header_bytes]
231 data = binary[header_bytes:termination_bytes]
232 return np.fromstring(data, dtype=dtype, **kwargs)
233
234 def _format_binary_values(self, values, datatype='f', is_big_endian=False, header_fmt="ieee"):
235 """Format values in binary format, used internally in :meth:`Adapter.write_binary_values`.
236
237 :param values: data to be written to the device.
238 :param datatype: the format string for a single element. See struct module.
239 :param is_big_endian: boolean indicating endianess.
240 :param header_fmt: Format of the header prefixing the data ("ieee", "hp", "empty").
241 :return: binary string.
242 :rtype: bytes
243 """
244 if header_fmt == "ieee":
245 block = to_ieee_block(values, datatype, is_big_endian)
246 elif header_fmt == "hp":
247 block = to_hp_block(values, datatype, is_big_endian)
248 elif header_fmt == "empty":
249 block = to_binary_block(values, b"", datatype, is_big_endian)
250 else:
251 raise ValueError("Unsupported header_fmt: %s" % header_fmt)
252 return block
253
254 def write_binary_values(self, command, values, termination="", **kwargs):
255 """ Write binary data to the instrument, e.g. waveform for signal generators
256
257 :param command: command string to be sent to the instrument
258 :param values: iterable representing the binary values
259 :param termination: String added afterwards to terminate the message.
260 :param \\**kwargs: Key-word arguments to pass onto :meth:`Adapter._format_binary_values`
261 :returns: number of bytes written
262 """
263 block = self._format_binary_values(values, **kwargs)
264 return self.write_bytes(command.encode() + block + termination.encode())
265
266
267 class FakeAdapter(Adapter):
268 """Provides a fake adapter for debugging purposes,
269 which bounces back the command so that arbitrary values
270 testing is possible.
271
272 .. code-block:: python
273
274 a = FakeAdapter()
275 assert a.read() == ""
276 a.write("5")
277 assert a.read() == "5"
278 assert a.read() == ""
279 assert a.ask("10") == "10"
280 assert a.values("10") == [10]
281
282 """
283
284 _buffer = ""
285
286 def _read(self):
287 """ Return the last commands given after the
288 last read call.
289 """
290 result = copy(self._buffer)
291 # Reset the buffer
292 self._buffer = ""
293 return result
294
295 def _read_bytes(self, count, break_on_termchar):
296 """ Return the last commands given after the
297 last read call.
298 """
299 result = copy(self._buffer)
300 # Reset the buffer
301 self._buffer = ""
302 return result[:count].encode()
303
304 def _write(self, command):
305 """ Write the command to a buffer, so that it can
306 be read back.
307 """
308 self._buffer += command
309
310 def _write_bytes(self, command):
311 """ Write the command to a buffer, so that it can
312 be read back.
313 """
314 self._buffer += command.decode()
315
316 def __repr__(self):
317 return "<FakeAdapter>"