Debian Codegraph @

pymeasure/instruments/thyracont/smartline_v2.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 from enum import IntEnum
26
27 from pymeasure.instruments import Instrument, Channel, validators
28 from pyvisa.constants import Parity, StopBits
29
30 from .smartline_v1 import calculate_checksum
31
32
33 def compose_data(value):
34 """Generate a string with the length of `value` and the `value` itself afterwards.
35
36 :param value: Value to send to the device.
37 """
38 value = f"{value}"
39 return f"{len(value):02}{value}"
40
41
42 class Sources(IntEnum):
43 COMBINATION = 0
44 PIRANI = 1
45 PIEZO = 2
46 HOT_CATHODE = 3
47 COLD_CATHODE = 4
48 AMBIENT = 6
49 RELATIVE = 7
50
51
52 def str_to_source(source_string):
53 """Turn a string with a source number to a `Sources` enum. Useful for `cast` parameter."""
54 return Sources(int(source_string))
55
56
57 gas_factor = Channel.control(
58 "0C{ch}00", "0C{ch}%s", "Control the gas correction factor.",
59 values=(0.2, 8),
60 validator=validators.strict_range,
61 set_process=compose_data,
62 )
63
64
65 class SensorChannel(Channel):
66 """Generic channel for individual pressure sensors of a Transmitter."""
67
68 _id = -1 # obligatory channel number, define in channel types
69
70 def __init__(self, parent, id=None, **kwargs):
71 # id parameter is necessary for usage with `ChannelCreator`.
72 if id is None or id == self._id:
73 super().__init__(parent, id=self._id, **kwargs)
74 else:
75 raise ValueError(f"Pirani ID has to be {self._id} for that channel type.")
76
77 pressure = Channel.measurement(
78 "0M{ch}00", """Get the current pressure in mbar.""",
79 preprocess_reply=lambda r: r.replace("UR", "0").replace("OR", "inf"),
80 )
81
82
83 class Pirani(SensorChannel):
84 """Pirani sensor channel.
85
86 A Pirani sensor measures the heat transfer in the gas. The reading depends on the gas type.
87 The sensor reading is linear to the real pressure below some threshold, around 1 mbar.
88 You may control a gas factor with :attr:`gas_factor`.
89 """
90
91 _id = Sources.PIRANI
92
93 gas_factor = gas_factor
94
95 statistics = Channel.measurement(
96 "0PM011",
97 """Get the sensor statistics as a tuple: wear in percent (negative: corrosion,
98 positive: contamination), time since last adjustment in hours.""",
99 preprocess_reply=lambda msg: msg.strip("W"),
100 separator="A",
101 cast=int,
102 get_process=lambda vals: (vals[0], vals[1] / 4),
103 )
104
105
106 class Piezo(SensorChannel):
107 """Piezo sensor channel. A piezo sensor is independent of the gas present."""
108
109 _id = Sources.PIEZO
110
111
112 class HotCathode(SensorChannel):
113 """Hot cathode sensor channel."""
114
115 _id = Sources.HOT_CATHODE
116
117 filament_mode = Instrument.control(
118 "0FC00", "2FC01%i",
119 docs="""Control which hot cathode filament to use.
120 ("2 if 1 defect", "Filament1", "Filament2", "toggle>1mbar")
121 """,
122 values={"2 if 1 defect": 0,
123 "Filament1": 1,
124 "Filament2": 2,
125 "toggle>1mbar": 3},
126 validator=validators.strict_discrete_set,
127 map_values=True,
128 cast=int,
129 check_set_errors=True,
130 )
131
132 degas = Instrument.control(
133 "0DG00", "2DG01%i",
134 """Control the degas mode.""",
135 values={True: 1, False: 0},
136 map_values=True,
137 validator=validators.strict_discrete_set,
138 check_set_errors=True,
139 )
140
141 sensor_enabled = Instrument.control(
142 "0CC00", "2CC01%i",
143 """Control the state of the cathode.""",
144 values={True: 1, False: 0},
145 map_values=True,
146 validator=validators.strict_discrete_set,
147 check_set_errors=True,
148 )
149 active_filament = Instrument.measurement(
150 "0FN00", "Get the current filament number.",
151 cast=int,
152 )
153
154 filament_status = Instrument.measurement(
155 "0FS00", """Get the status of the hot cathode filaments.""",
156 values=["Filament 1 and 2 ok",
157 "Filament 1 defective",
158 "Filament 2 defective",
159 "Filament 1 and 2 defective"],
160 map_values=True,
161 )
162
163 gas_factor = gas_factor
164
165 statistics = Channel.measurement(
166 "0PM013",
167 """Get the wear levels in percent as a tuple: filament 1, filament 2.""",
168 preprocess_reply=lambda msg: msg.strip("F"),
169 separator="S",
170 cast=int,
171 )
172
173 # cathode status CA, cathode control mode CM
174
175
176 class ColdCathode(SensorChannel):
177 """Cold cathode sensor channel."""
178
179 _id = Sources.COLD_CATHODE
180
181 gas_factor = gas_factor
182
183
184 class Ambient(SensorChannel):
185
186 _id = Sources.AMBIENT
187
188
189 class Relative(SensorChannel):
190
191 _id = Sources.RELATIVE
192
193
194 class SmartlineV2(Instrument):
195 """
196 A Thyracont vacuum sensor transmitter of the Smartline V2 series.
197
198 You may subclass this Instrument and add the appropriate channels, see the following example.
199
200 .. doctest::
201
202 from pymeasure.instruments import Instrument
203 from pymeasure.instruments.thyractont import SmartlineV2
204
205 PiezoAndPiraniInstrument(SmartlineV2):
206 piezo = Instrument.ChannelCreator(Piezo)
207 pirani = Instrument.ChannelCreator(Pirani)
208
209 Communication Protocol v2 via RS485:
210 - Everything is sent as ASCII characters
211 - Package (bytes and usage):
212 - 0-2 address, 3 access code, 4-5 command, 6-7 data length.
213 - if data: 8-n data to be sent, n+1 checksum, n+2 carriage return
214 - if no data: 8 checksum, 9 carriage return
215 - Access codes (request: master->transmitter, response: transmitter->master):
216 - read: 0, 1
217 - write: 2, 3
218 - factory default: 4,5
219 - error: -, 7
220 - binary 8, 9
221 - Data length is number of data in bytes (padding with zeroes on left)
222 - Checksum: Add the decimal numbers of the characters before, mod 64, add 64, show as ASCII.
223
224 :param adress: The device address in the range 1-16.
225 """
226
227 Sources = Sources
228
229 errors = {'NO_DEF': "Invalid command for this device.",
230 '_LOGIC': "Access Code is invalid or illogical command.",
231 '_RANGE': "Value sent is out of range.",
232 'ERROR1': "Sensor defect or stacked out.",
233 'SYNTAX': "Wrong syntax or mode in data is invalid for this device.",
234 'LENGTH': "Length of data is out of expected range.",
235 '_CD_RE': "Calibration Data Read Error.",
236 '_EP_RE': "EEPROM Read Error.",
237 '_UNSUP': "Unsupported Data for that command.",
238 '_SEDIS': "Sensor element disabled."}
239
240 def __init__(self, adapter, name="Thyracont SmartlineV2 Transmitter", baud_rate=115200,
241 address=1, timeout=250,
242 **kwargs):
243 super().__init__(adapter, name=name, includeSCPI=False,
244 write_termination="\r",
245 read_termination="\r",
246 timeout=timeout,
247 asrl={'baud_rate': baud_rate,
248 'parity': Parity.none,
249 'stop_bits': StopBits.one,
250 },
251 **kwargs
252 )
253 self.address = address # 1-16
254
255 def write(self, command):
256 """Write a command to the device."""
257 message = f"{self.address:03}{command}"
258 super().write(f"{message}{calculate_checksum(message)}")
259
260 def write_composition(self, accessCode, command, data=""):
261 """Write a command with an accessCode and optional data to the device.
262
263 :param accessCode: How to access the device.
264 :param command: Two char command string to send to the device.
265 :param data: Data for the command.
266 """
267 self.write(f"{accessCode}{command}{compose_data(data)}")
268
269 def ask(self, command_message, query_delay=None):
270 """Ask for some value and check that the response matches the original command.
271
272 :param str command_message: Access code, command, length, and content.
273 The command sent is compared to the response command.
274 """
275 self.write(command_message)
276 self.wait_for(query_delay)
277 return self.read(command_message[1:3])
278
279 def ask_manually(self, accessCode, command, data="", query_delay=None):
280 """
281 Send a message to the transmitter and return its answer.
282
283 :param accessCode: How to access the device.
284 :param command: Command to send to the device.
285 :param data: Data for the command.
286 :param float query_delay: Time to wait between writing and reading in seconds.
287 :return str: Response from the device after error checking.
288 """
289 self.write(f"{accessCode}{command}{compose_data(data)}")
290 self.wait_for(query_delay)
291 return self.read(command)
292
293 def read(self, command=None):
294 """Read from the device and do error checking.
295
296 :param str command: Original command sent to the device to compare it with the response.
297 None deactivates the check.
298 """
299 # Sometimes the answer contains 0x00 or values above 127, such that
300 # decoding fails.
301 response = self.read_bytes(-1, break_on_termchar=True)
302 response = response.replace(b"\x00", b"")
303
304 # b"\r" is the termination character
305 got = response.rstrip(b"\r").decode('ascii', errors="ignore")
306 # Error checking
307 if got[3] == "7":
308 raise ConnectionError(self.errors[got[8:-1]])
309 if command is not None and got[4:6] != command:
310 raise ConnectionError(f"Wrong response to {command}: '{got}'.")
311 if calculate_checksum(got[:-1]) != got[-1]:
312 raise ConnectionError("Response checksum is wrong.")
313 return got[8:-1]
314
315 def check_set_errors(self):
316 """Check the errors after setting a property."""
317 self.read()
318 return [] # no error happened
319
320 " Main commands"
321
322 range = Instrument.measurement(
323 "0MR00", """Get the measurement range in mbar.""",
324 preprocess_reply=lambda r: r[1:], separator="L")
325
326 pressure = Instrument.measurement(
327 "0MV00", """Get the current pressure of the default sensor in mbar""",
328 preprocess_reply=lambda r: r.replace("UR", "0").replace("OR", "inf"),
329 )
330
331 # def Relays
332
333 display_unit = Instrument.control(
334 get_command="0DU00",
335 set_command="2DU%s",
336 docs="""Control the unit shown in the display. ('mbar', 'Torr', 'hPa')""",
337 values=['mbar', 'Torr', 'hPa'],
338 validator=validators.strict_discrete_set,
339 set_process=compose_data,
340 check_set_errors=True,
341 )
342
343 display_orientation = Instrument.control(
344 "0DO00", "2DO01%i",
345 """Control the orientation of the display in relation to the pipe ('top', 'bottom').""",
346 values={"top": 0, "bottom": 1},
347 map_values=True,
348 validator=validators.strict_discrete_set,
349 check_set_errors=True,
350 )
351
352 display_data = Instrument.control(
353 "0DD00", "2DD01%i",
354 """Control the display data source (strict SOURCES).""",
355 values=Sources,
356 cast=str_to_source,
357 validator=validators.strict_discrete_set,
358 check_set_errors=True,
359 )
360
361 def set_high(self, high=""):
362 """Set the high pressure to `high` pressure in mbar."""
363 self.ask_manually(2, "AH", high)
364
365 def set_low(self, low=""):
366 """Set the low pressure to `low` pressure in mbar."""
367 self.ask_manually(2, "AL", low)
368
369 " Sensor parameters"
370
371 def get_sensor_transition(self):
372 """
373 Get the current sensor transition between sensors.
374
375 return interpretation:
376 - direct
377 switch at 1 mbar.
378 - continuous
379 switch between 5 and 15 mbar.
380 - F[float]T[float]
381 switch between low and high value.
382 - D[float]
383 switch at value.
384 """
385 got = self.ask_manually(0, "ST")
386 # VSR/VSL: 0 direct switch at 1 mbar, 1 continuous between 5 to 15 mbar
387 # VSH: 0 direct switch at 4e-4 mbar, 1 continuous between 1e-3 to 2e-3 mbar,
388 # 2 continuous between 2e-3 to 5e-3 mbar
389 mapping = {
390 "0": "direct",
391 "1": "continuous",
392 "2": "continuous 2",
393 }
394 return mapping.get(got, got)
395
396 def set_default_sensor_transition(self):
397 """Set the senstor transition mode to the default value, depends on the device."""
398 self.ask_manually(2, "ST", "1")
399
400 def set_continuous_sensor_transition(self, low, high):
401 """Set the sensor transition mode to "continuous" mode between `low` and `high` (floats)."""
402 self.ask_manually(2, "ST", f"F{low}T{high}")
403
404 def set_direct_sensor_transition(self, transition_point):
405 """Set the sensor transition to "direct" mode.
406
407 :param float transition_point: Switch between the sensors at that value.
408 """
409 self.ask_manually(2, "ST", f"D{transition_point}")
410
411 " Device Information"
412 # def response delay
413
414 device_type = Instrument.measurement(
415 "0TD00", """Get the device type, like 'VSR205'.""", cast=str)
416
417 product_name = Instrument.measurement(
418 "0PN00", """Get the product name (article number).""", cast=str)
419
420 device_serial = Instrument.measurement(
421 "0SD00", """Get the transmitter device serial number.""", cast=str)
422
423 sensor_serial = Instrument.measurement(
424 "0SH00", """Get the sensor head serial number.""", cast=str)
425
426 baud_rate = Instrument.setting(
427 "2BR%s", """Set the device baud rate.""",
428 set_process=compose_data,
429 check_set_errors=True,
430 )
431
432 device_address = Instrument.setting(
433 "2DA%s", "Set the device address.",
434 set_process=compose_data,
435 check_set_errors=True,
436 )
437
438 device_version = Instrument.measurement(
439 "0VD00", """Get the device hardware version.""", cast=str)
440
441 firmware_version = Instrument.measurement(
442 "0VF00", """Get the firmware version.""", cast=str)
443
444 bootloader_version = Instrument.measurement(
445 "0VB00", """Get the bootloader version.""", cast=str)
446
447 analog_output_setting = Instrument.measurement(
448 "0OC00", "Get current analog output setting. See manual.", cast=str)
449
450 operating_hours = Instrument.measurement(
451 "0OH00", "Measure the operating hours.",
452 separator="C",
453 cast=int,
454 get_process=lambda vals: vals / 4 if isinstance(vals, int) else [v / 4 for v in vals],
455 # TODO simplify once #740 is merged.
456 )
457
458
459 class VSH(SmartlineV2):
460 """Vacuum transmitter of VSH series with both a pirani and a hot cathode sensor."""
461
462 pirani = Instrument.ChannelCreator(Pirani)
463 hotcathode = Instrument.ChannelCreator(HotCathode)
464
465
466 class VSR(SmartlineV2):
467 """Vacuum transmitter of VSR/VCR series with both a piezo and a pirani sensor."""
468
469 piezo = Instrument.ChannelCreator(Piezo)
470 pirani = Instrument.ChannelCreator(Pirani)