Debian Codegraph @

pymeasure/instruments/toptica/ibeamsmart.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 re
27 import time
28 from warnings import warn
29
30 from pyvisa.errors import VisaIOError
31
32 from pymeasure.instruments import Channel, Instrument
33 from pymeasure.instruments.validators import strict_discrete_set, strict_range
34
35 log = logging.getLogger(__name__)
36 log.addHandler(logging.NullHandler())
37
38
39 def _deprecation_warning(text):
40 def func(x):
41 warn(text, FutureWarning)
42 return x
43
44 return func
45
46
47 def _deprecation_warning_channels(property_name):
48 def func(x):
49 warn(f'Deprecated property name "{property_name}", use the channels '
50 '"enabled" property instead.', FutureWarning)
51 return x
52
53 return func
54
55
56 def deprecated_strict_discrete_set(value, values):
57 warn("This property is deprecated, use channels instead.", FutureWarning)
58 return strict_discrete_set(value, values)
59
60
61 class DriverChannel(Channel):
62 """A laser diode driver channel for the IBeam Smart laser."""
63
64 power = Channel.setting(
65 "ch {ch} pow %f mic",
66 """Set the output power in µW (float up to 200000).""",
67 check_set_errors=True,
68 validator=strict_range,
69 values=[0, 200000],
70 )
71
72 enabled = Channel.control(
73 "sta ch {ch}",
74 "%s {ch}",
75 """Control the enabled state of the driver channel.""",
76 validator=strict_discrete_set,
77 values=[True, False],
78 get_process=lambda s: True if s == 'ON' else False,
79 set_process=lambda v: "en" if v else "di",
80 check_set_errors=True,
81 )
82
83
84 class IBeamSmart(Instrument):
85 """ IBeam Smart laser diode
86
87 For the usage of the different diode driver channels, see the manual
88
89 .. code::
90
91 laser = IBeamSmart("SomeResourceString")
92 laser.emission = True
93 laser.ch_2.power = 1000 # µW
94 laser.ch_2.enabled = True
95 laser.shutdown()
96
97 :param adapter: pyvisa resource name or adapter instance.
98 :param baud_rate: The baud rate you have set in the instrument.
99 :param \\**kwargs: Any valid key-word argument for VISAAdapter.
100 """
101 _reg_value = re.compile(r"\w+\s+=\s+(\w+)")
102
103 ch_1 = Instrument.ChannelCreator(DriverChannel, 1)
104
105 ch_2 = Instrument.ChannelCreator(DriverChannel, 2)
106
107 ch_3 = Instrument.ChannelCreator(DriverChannel, 3)
108
109 ch_4 = Instrument.ChannelCreator(DriverChannel, 4)
110
111 ch_5 = Instrument.ChannelCreator(DriverChannel, 5)
112
113 def __init__(self, adapter, name="Toptica IBeam Smart laser diode",
114 baud_rate=115200,
115 **kwargs):
116 super().__init__(
117 adapter,
118 name,
119 includeSCPI=False,
120 read_termination='\r\n',
121 write_termination='\r\n',
122 asrl={'baud_rate': baud_rate},
123 **kwargs
124 )
125 # configure communication mode: no repeating and no command prompt
126 self.write('echo off')
127 self.write('prom off')
128 time.sleep(0.04)
129 # clear the initial messages from the controller
130 try:
131 self.adapter.flush_read_buffer()
132 except AttributeError:
133 log.warning("Adapter does not have 'flush_read_buffer' method.")
134 self.ask('talk usual')
135
136 def read(self):
137 """Read a reply of the instrument and extract the values, if possible.
138
139 Reads a reply of the instrument which consists of at least two
140 lines. The initial ones are the reply to the command while the last one
141 should be '[OK]' which acknowledges that the device is ready to receive
142 more commands.
143
144 Note: '[OK]' is always returned as last message even in case of an
145 invalid command, where a message indicating the error is returned
146 before the '[OK]'
147
148 Value extraction: extract <value> from 'name = <value> [unit]'.
149 If <value> can not be identified the original string is returned.
150
151 :return: string containing the ASCII response of the instrument (without '[OK]').
152 """
153 reply = super().read() # read back the LF+CR which is always sent back
154 if reply != "":
155 raise ValueError(
156 f"Error, no empty line at begin of message, instead '{reply}'")
157 msg = []
158 try:
159 while True:
160 line = super().read()
161 if line == '[OK]':
162 break
163 msg.append(line)
164 except VisaIOError:
165 reply = '\n'.join(msg)
166 try:
167 self.adapter.flush_read_buffer()
168 except AttributeError:
169 log.warning("Adapter does not have 'flush_read_buffer' method.")
170 raise ValueError(f"Flush buffer failed after '{reply}'")
171 reply = '\n'.join(msg)
172 r = self._reg_value.search(reply)
173 if r:
174 return r.groups()[0]
175 else:
176 return reply
177
178 def check_set_errors(self):
179 """Check for errors after having gotten a property and log them.
180
181 Checks if the last reply is only '[OK]', otherwise a ValueError is
182 raised and the read buffer is flushed because one has to assume that
183 some communication is out of sync.
184 """
185 reply = self.read()
186 if reply:
187 # anything else than '[OK]'.
188 self.adapter.flush_read_buffer()
189 log.error(f"Setting a property failed with reply '{reply}'.")
190 raise ValueError(f"Setting a property failed with reply '{reply}'.")
191 return []
192
193 version = Instrument.measurement(
194 "ver", """Get Firmware version number.""",
195 )
196
197 serial = Instrument.measurement(
198 "serial", """Get Serial number of the laser system.""",
199 )
200
201 temp = Instrument.measurement(
202 "sh temp",
203 """Measure the temperature of the laser diode in degree centigrade.""",
204 )
205
206 system_temp = Instrument.measurement(
207 "sh temp sys",
208 """Measure base plate (heatsink) temperature in degree centigrade.""",
209 )
210
211 current = Instrument.measurement(
212 "sh cur",
213 """Measure the laser diode current in mA.""",
214 )
215
216 emission = Instrument.control(
217 "sta la", "la %s",
218 """Control emission status of the laser diode driver (bool).""",
219 validator=strict_discrete_set,
220 values=[True, False],
221 get_process=lambda s: True if s == 'ON' else False,
222 set_process=lambda v: "on" if v else "off",
223 check_set_errors=True,
224 )
225
226 laser_enabled = Instrument.control(
227 "sta la", "la %s",
228 """Control emission status of the laser diode driver (bool).
229
230 .. deprecated:: 0.12 Use attr:`emission` instead.
231 """,
232 validator=deprecated_strict_discrete_set,
233 values=[True, False],
234 get_process=lambda s: True if s == 'ON' else False,
235 set_process=lambda v: "on" if v else "off",
236 check_set_errors=True,
237 preprocess_reply=_deprecation_warning(
238 "Property `laser_enabled` is deprecated, use `emission` instead."),
239 )
240
241 channel1_enabled = Instrument.control(
242 "sta ch 1", "%s",
243 """Control status of Channel 1 of the laser (bool).
244
245 .. deprecated:: 0.12 Use :attr:`ch_1.enabled` instead.
246 """,
247 validator=deprecated_strict_discrete_set,
248 values=[True, False],
249 get_process=lambda s: True if s == 'ON' else False,
250 set_process=lambda v: "en 1" if v else "di 1",
251 check_set_errors=True,
252 preprocess_reply=_deprecation_warning_channels("channel1_enabled"),
253 )
254
255 channel2_enabled = Instrument.control(
256 "sta ch 2", "%s",
257 """Control status of Channel 2 of the laser (bool).
258
259 .. deprecated:: 0.12 Use :attr:`ch_2.enabled` instead.""",
260 validator=deprecated_strict_discrete_set,
261 values=[True, False],
262 get_process=lambda s: True if s == 'ON' else False,
263 set_process=lambda v: "en 2" if v else "di 2",
264 check_set_errors=True,
265 preprocess_reply=_deprecation_warning_channels("channel2_enabled"),
266 )
267
268 power = Instrument.control(
269 "sh pow", "ch pow %f mic",
270 """Control actual output power in µW of the laser system. In pulse mode
271 this means that the set value might not correspond to the readback
272 one (float up to 200000).""",
273 validator=strict_range,
274 values=[0, 200000],
275 check_set_errors=True,
276 )
277
278 def enable_continous(self):
279 """Enable countinous emmission mode."""
280 self.write('di ext')
281 self.check_set_errors()
282 self.emission = True
283 self.ch_2.enabled = True
284
285 def enable_pulsing(self):
286 """Enable pulsing mode.
287
288 The optical output is controlled by a digital
289 input signal on a dedicated connnector on the device."""
290 self.emission = True
291 self.ch_2.enabled = True
292 self.write('en ext')
293 self.check_set_errors()
294
295 def disable(self):
296 """Shutdown all laser operation."""
297 self.write('di 0')
298 self.check_set_errors()
299 self.emission = False
300
301 def shutdown(self):
302 """Brings the instrument to a safe and stable state."""
303 self.disable()
304 super().shutdown()