Debian Codegraph @

pymeasure/instruments/oxfordinstruments/base.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
26 from pymeasure.instruments import Instrument
27 from pyvisa.errors import VisaIOError
28 from pyvisa import constants as vconst
29 import re
30 import logging
31
32
33 log = logging.getLogger(__name__)
34 log.addHandler(logging.NullHandler())
35
36
37 class OxfordVISAError(Exception):
38 pass
39
40
41 class OxfordInstrumentsBase(Instrument):
42 """Base instrument for devices from Oxford Instruments.
43
44 Checks the replies from instruments for validity.
45
46 :param adapter: A string, integer, or :py:class:`~pymeasure.adapters.Adapter` subclass object
47 :param string name: The name of the instrument. Often the model designation by default.
48 :param max_attempts: Integer that sets how many attempts at getting a
49 valid response to a query can be made
50 :param \\**kwargs: In case ``adapter`` is a string or integer, additional arguments passed on
51 to :py:class:`~pymeasure.adapters.VISAAdapter` (check there for details).
52 Discarded otherwise.
53 """
54
55 timeoutError = VisaIOError(-1073807339)
56
57 regex_pattern = r"^([a-zA-Z])[\d.+-]*$"
58
59 def __init__(self, adapter, name="OxfordInstruments Base", max_attempts=5, **kwargs):
60 kwargs.setdefault('read_termination', '\r')
61
62 super().__init__(adapter,
63 name=name,
64 includeSCPI=False,
65 asrl={
66 'baud_rate': 9600,
67 'data_bits': 8,
68 'parity': vconst.Parity.none,
69 'stop_bits': vconst.StopBits.two,
70 },
71 **kwargs)
72 self.max_attempts = max_attempts
73
74 def ask(self, command):
75 """Write the command to the instrument and return the resulting ASCII response. Also check
76 the validity of the response before returning it; if the response is not valid, another
77 attempt is made at getting a valid response, until the maximum amount of attempts is
78 reached.
79
80 :param command: ASCII command string to be sent to the instrument
81
82 :returns: String ASCII response of the instrument
83
84 :raises: :class:`~.OxfordVISAError` if the maximum number of attempts is surpassed without
85 getting a valid response
86 """
87
88 for attempt in range(self.max_attempts):
89 # Skip the checks in "write", because we explicitly want to get an answer here
90 super().write(command)
91 self.wait_for()
92 response = self.read()
93
94 if self.is_valid_response(response, command):
95 if command.startswith("R"):
96 # Remove the leading R of the response
97 return response.strip("R")
98 return response
99
100 log.debug("Received invalid response to '%s': %s", command, response)
101
102 # Clear the buffer and try again
103 try:
104 self.read()
105 except VisaIOError as e_visa:
106 if e_visa.args == self.timeoutError.args:
107 pass
108 else:
109 raise e_visa
110
111 # No valid response has been received within the maximum allowed number of attempts
112 raise OxfordVISAError(f"Retried {self.max_attempts} times without getting a valid "
113 "response, maybe there is something worse at hand.")
114
115 def write(self, command):
116 """Write command to instrument and check whether the reply indicates that the given command
117 was not understood.
118 The devices from Oxford Instruments reply with '?xxx' to a command 'xxx' if this command is
119 not known, and replies with 'x' if the command is understood.
120 If the command starts with an "$" the instrument will not reply at all; hence in that case
121 there will be done no checking for a reply.
122
123 :raises: :class:`~.OxfordVISAError` if the instrument does not recognise the supplied
124 command or if the response of the instrument is not understood
125 """
126 super().write(command)
127
128 if not command[0] == "$":
129 response = self.read()
130
131 log.debug(
132 "Wrote '%s' to instrument; instrument responded with: '%s'",
133 command,
134 response,
135 )
136 if not self.is_valid_response(response, command):
137 if response[0] == "?":
138 raise OxfordVISAError("The instrument did not understand this command: "
139 f"{command}")
140 else:
141 raise OxfordVISAError(f"The response of the instrument to command '{command}' "
142 f"is not valid: '{response}'")
143
144 def is_valid_response(self, response, command):
145 """Check if the response received from the instrument after a command is valid and
146 understood by the instrument.
147
148 :param response: String ASCII response of the device
149 :param command: command used in the initial query
150
151 :returns: True if the response is valid and the response indicates the instrument
152 recognised the command
153 """
154
155 # Handle special cases
156 # Check if the response indicates that the command is not recognized
157 if response[0] == "?":
158 log.debug("The instrument did not understand this command: %s", command)
159 return False
160
161 # Handle a special case for when the status is queried
162 if command[0] == "X" and response[0] == "X":
163 return True
164
165 # Handle a special case for when the version is queried
166 if command[0] == "V":
167 return True
168
169 # Handle the other, standard cases
170 try:
171 match = re.match(self.regex_pattern, response)
172 except TypeError:
173 match = False
174
175 if match and not match.groups()[0] == command[0]:
176 match = False
177
178 return bool(match)
179
180 def __repr__(self):
181 return "<OxfordInstrumentsAdapter(adapter='%s')>" % self.adapter.connection.resource_name