Debian Codegraph @

pymeasure/instruments/tcpowerconversion/tccxn.py

raw
1 #
2 # This file is part of the PyMeasure package.
3 #
4 # Copyright (c) 2013-2022 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 enum
26 import struct
27
28 from pymeasure.instruments.validators import strict_discrete_set
29 from pymeasure.instruments import Channel, Instrument
30
31
32 def values(self, command, cast=int, separator=',', preprocess_reply=None, **kwargs):
33 """Write a command to the instrument and return a list of formatted
34 values from the result.
35
36 This is derived from CommonBase.values and adapted here for use with bytes
37 communication messages (no str conversion and strip). It is implemented as a
38 general method to allow using it equally in PresetChannel and CXN. See
39 Github issue #784 for details.
40
41 :param command: SCPI command to be sent to the instrument
42 :param separator: A separator character to split the string into a list
43 :param cast: A type to cast the result
44 :param preprocess_reply: optional callable used to preprocess values
45 received from the instrument. The callable returns the processed
46 string.
47 :returns: A list of the desired type, or strings where the casting fails
48 """
49 results = self.ask(command)
50 if callable(preprocess_reply):
51 results = preprocess_reply(results)
52 for i, result in enumerate(results):
53 try:
54 if cast == bool:
55 # Need to cast to float first since results are usually
56 # strings and bool of a non-empty string is always True
57 results[i] = bool(float(result))
58 else:
59 results[i] = cast(result)
60 except Exception:
61 pass # Keep as bytes
62 return results
63
64
65 def int2char(value):
66 """Convert an 16-bit unsigned integer to a tuple of two representing characters."""
67 return tuple(int(b) for b in value.to_bytes(2, "big"))
68
69
70 class PresetChannel(Channel):
71 values = values
72
73 load_capacity = Instrument.control(
74 "GU\x00{ch:c}\x00\x00", "TD{ch:c}\x01\x00%c",
75 """Control the percentage of full-scale value of the load capacity preset.""",
76 preprocess_reply=lambda d: struct.unpack(">H", d[2:4]),
77 validator=strict_discrete_set,
78 values=range(101),
79 )
80
81 tune_capacity = Instrument.control(
82 "GU\x00{ch:c}\x00\x00", "TD{ch:c}\x02\x00%c",
83 """Control the percentage of full-scale value of the tune capacity preset.""",
84 preprocess_reply=lambda d: struct.unpack(">H", d[4:6]),
85 validator=strict_discrete_set,
86 values=range(101),
87 )
88
89
90 class CXN(Instrument):
91 """T&C Power Conversion AG Series Plasma Generator CXN
92 (also rebranded by AJA International Inc as 0113 GTC or 0313 GTC)
93
94 Connection to the device is made through an RS232 serial connection.
95 The communication settings are fixed in the device at 38400, stopbit one,
96 parity none. The device uses a command response system where every receipt
97 of a command is acknowledged by returning a '*'. A '?' is returned to
98 indicates the command was not recognized by the device.
99
100 A command messages always consists of the following bytes (B):
101 1B - header (always 'C'),
102 1B - address (ignored),
103 2B - command id,
104 2B - parameter 1,
105 2B - parameter,
106 2B - checksum
107
108 A response message always consists of:
109 1B - header (always 'R'),
110 1B - address of the device,
111 2B - length of the data package,
112 variable length data,
113 2B - checksum
114 response messages are received after the acknowledge byte.
115
116 :param adapter: pyvisa resource name of the instrument or adapter instance
117 :param string name: Name of the instrument.
118 :param kwargs: Any valid key-word argument for Instrument
119
120 .. Note::
121
122 In order to enable setting any parameters one has to request control
123 and periodically (at least once per 2s) poll any value from the device.
124 Failure to do so will mean loss of control and the device will reset
125 certain parameters (setpoint, disable RF, ...). If no value should be polled
126 but control should remain active one can also use the ping method.
127 """
128 # use predefined values method to allow reusing in the Channels
129 values = values
130
131 preset_1 = Instrument.ChannelCreator(PresetChannel, 1)
132
133 preset_2 = Instrument.ChannelCreator(PresetChannel, 2)
134
135 preset_3 = Instrument.ChannelCreator(PresetChannel, 3)
136
137 preset_4 = Instrument.ChannelCreator(PresetChannel, 4)
138
139 preset_5 = Instrument.ChannelCreator(PresetChannel, 5)
140
141 preset_6 = Instrument.ChannelCreator(PresetChannel, 6)
142
143 preset_7 = Instrument.ChannelCreator(PresetChannel, 7)
144
145 preset_8 = Instrument.ChannelCreator(PresetChannel, 8)
146
147 preset_9 = Instrument.ChannelCreator(PresetChannel, 9)
148
149 def __init__(self, adapter, name="T&C RF sputtering power supply", address=0, **kwargs):
150 self.address = address
151 super().__init__(adapter,
152 name,
153 includeSCPI=False,
154 write_termination="",
155 read_termination="",
156 asrl=dict(baud_rate=38400),
157 **kwargs)
158
159 @staticmethod
160 def _checksum(msg):
161 """Calculate a 2 bytes checksum calculated by a bytewise sum of the message.
162
163 :param bytes msg: message content
164 :returns: calculated checksum
165 :rtype: bytes
166 """
167 return struct.pack(">H", sum(msg))
168
169 def _prepend_cmdheader(self, cmd):
170 """Prepends command start byte and address to the command.
171
172 :param bytes msg: command message
173 """
174 return b"C" + self.address.to_bytes(1, "big") + cmd
175
176 def _check_acknowledgment(self):
177 """Check reply string for acknowledgement byte.
178
179 :raises ValueError: if an invalid an invalid byte is read from the instrument
180 """
181 ret = super().read_bytes(1)
182 if ret == b"*":
183 return
184 # no valid acknowledgement message found
185 raise ValueError(
186 f"invalid reply '{ret}' found in acknowledgement check")
187
188 def read(self):
189 """Reads a response message from the instrument.
190
191 This method determines the length of the message from the automatically
192 by reading the message header and also checks for a correct checksum.
193
194 :returns: the data fields
195 :rtype: bytes
196 :raises ValueError: if a checksum error is detected
197 """
198 header = super().read_bytes(4)
199 # check valid header
200 if header[0] != 82:
201 raise ValueError(f"invalid header start byte '{header[0]}' received")
202 if header[1] != self.address:
203 raise ValueError(f"invalid address byte '{header[1]}' received; "
204 f"should be {self.address.to_bytes(1, 'big')}")
205 datalength = int.from_bytes(header[2:], "big")
206 data = super().read_bytes(datalength)
207 chksum = super().read_bytes(2)
208 if chksum == self._checksum(header + data):
209 return data
210 else:
211 raise ValueError(
212 f"checksum error in received message {header + data} "
213 f"with checksum {self._checksum(header + data)} "
214 f"but received {chksum}")
215
216 def write(self, command):
217 """Writes a command to the instrument and includes needed required
218 header and address.
219
220 :param str command: command to be sent to the instrument
221 """
222 fullcmd = self._prepend_cmdheader(command.encode())
223 super().write_bytes(fullcmd + self._checksum(fullcmd))
224 self._check_acknowledgment()
225
226 class Status(enum.IntFlag):
227 """IntFlag type used to represent the CXN status.
228
229 The used bits correspond to:
230 bit 14: Analog interface enabled,
231 bit 11: Interlock open,
232 bit 10: Over temperature,
233 bit 9: Reverse power limit,
234 bit 8: Forward power limit,
235 bit 6: MCG mode active,
236 bit 5: load power leveling active,
237 bit 4, External RF source active,
238 bit 0: RF power on.
239
240 """
241 RF_ENABLED = 1
242 EXTERNAL_RFSOURCE = 16
243 LOAD_POWER_LEVELING = 32
244 MCG_MODE = 64
245 FORWARD_POWER_LIMIT = 256
246 REVERSE_POWER_LIMIT = 512
247 OVER_TEMPERATURE = 1024
248 INTERLOCK_OPEN = 2048
249 ANALOG_INTERFACE = 16384
250
251 id = Instrument.measurement(
252 "Gi\x00\x01\x00\x00",
253 """Get the device identification string.""",
254 cast=str,
255 get_process=lambda d: d.decode()[2:-1].strip(),
256 )
257
258 serial = Instrument.measurement(
259 "Gi\x00\x02\x00\x00",
260 """Get the serial number of the instrument.""",
261 cast=str,
262 get_process=lambda d: d.decode()[2:-1].strip(),
263 )
264
265 firmware_version = Instrument.measurement(
266 "Gf\x00\x00\x00\x00",
267 """Get the UI-processor and RF-processor firmware version numbers.""",
268 preprocess_reply=lambda d: struct.unpack("BBBB", d),
269 get_process=lambda v: str.format("UI {}.{}, RF {}.{}", *v)
270 )
271
272 pulse_params = Instrument.measurement(
273 "GE\x00\x00\x00\x00",
274 """Get pulse on/off time of the pulse waveform.""",
275 preprocess_reply=lambda d: struct.unpack(">HH", d),
276 )
277
278 frequency = Instrument.measurement(
279 "GF\x00\x00\x00\x00",
280 """Get operating frequency in Hz.""",
281 preprocess_reply=lambda d: struct.unpack(">L", d),
282 )
283
284 power = Instrument.measurement(
285 "GP\x00\x00\x00\x00",
286 """Get power readings for forward/reverse/load power in watts.""",
287 preprocess_reply=lambda d: struct.unpack(">HHH", d),
288 get_process=lambda d: (float(d[0]) / 10, float(d[1]) / 10, float(d[2]) / 10),
289 )
290
291 status = Instrument.measurement(
292 "GS\x00\x00\x00\x00",
293 """Get status field. The return value is represented by the IntFlag
294 type Status.""",
295 preprocess_reply=lambda d: struct.unpack(">H", d[:2]),
296 get_process=lambda d: CXN.Status(d),
297 )
298
299 temperature = Instrument.measurement(
300 "GS\x00\x00\x00\x00",
301 """Get heat sink temperature in deg Celsius.""",
302 preprocess_reply=lambda d: struct.unpack(">H", d[2:4]),
303 get_process=lambda d: float(d) / 10,
304 )
305
306 tuner = Instrument.measurement(
307 "GS\x00\x00\x00\x00",
308 """Get type of the used tuner.""",
309 preprocess_reply=lambda d: struct.unpack(">H", d[6:]),
310 values={"none": 1, "AFT generator": 2,
311 "analog tuner": 3, "digital tuner": 4},
312 map_values=True,
313 )
314
315 power_limit = Instrument.measurement(
316 "Gp\x00\x00\x00\x00",
317 """Get maximum power of the power supply.""",
318 preprocess_reply=lambda d: struct.unpack(">H", d[2:4]),
319 get_process=lambda d: float(d) / 10,
320 )
321
322 reverse_power_limit = Instrument.measurement(
323 "Gp\x00\x00\x00\x00",
324 """Get maximum reverse power.""",
325 preprocess_reply=lambda d: struct.unpack(">H", d[18:20]),
326 get_process=lambda d: float(d) / 10,
327 )
328
329 dc_voltage = Instrument.measurement(
330 "GT\x00\x00\x00\x00",
331 """Get the DC voltage in volts.""",
332 preprocess_reply=lambda d: struct.unpack(">H", d[6:8]),
333 )
334
335 operation_mode = Instrument.control(
336 "GS\x00\x00\x00\x00", "SO\x00%c\x00\x00",
337 """Control the operation mode.""",
338 preprocess_reply=lambda d: struct.unpack(">H", d[4:6]),
339 values={"normal": 1, "<invalid>": 2, "pulse": 3, "ramp": 4},
340 map_values=True,
341 )
342
343 setpoint = Instrument.control(
344 "GL\x00\x00\x00\x00", "SA%c%c\x00\x00",
345 """Control the setpoint power level in watts.""",
346 preprocess_reply=lambda d: struct.unpack(">H", d),
347 get_process=lambda d: float(d) / 10,
348 set_process=int2char,
349 validator=strict_discrete_set,
350 values=range(4001),
351 )
352
353 ramp_start_power = Instrument.control(
354 "GR\x00\x00\x00\x00", "RP%c%c\x00\x00",
355 """Control the ramp starting power in watts.""",
356 preprocess_reply=lambda d: struct.unpack(">H", d[:2]),
357 set_process=int2char,
358 validator=strict_discrete_set,
359 values=range(1, 4001),
360 )
361
362 ramp_rate = Instrument.control(
363 "GR\x00\x00\x00\x00", "RR%c%c\x00\x00",
364 """Control the ramp rate in watts/second.""",
365 preprocess_reply=lambda d: struct.unpack(">H", d[2:]),
366 set_process=int2char,
367 validator=strict_discrete_set,
368 values=range(1, 99),
369 )
370
371 manual_mode = Instrument.control(
372 "GT\x00\x00\x00\x00", "TM\x00%c\x00\x00",
373 """Control the manual tuner mode.""",
374 preprocess_reply=lambda d: struct.unpack(">H", d[:2]),
375 get_process=lambda v: bool(v & 1),
376 set_process=lambda v: 2 if v else 1,
377 validator=strict_discrete_set,
378 values=(True, False),
379 )
380
381 load_capacity = Instrument.control(
382 "GT\x00\x00\x00\x00", "TC\x00\x01\x00%c",
383 """Control the percentage of full-scale value of the load capacity.
384 It can be set only when manual_mode is True.""",
385 preprocess_reply=lambda d: struct.unpack(">H", d[2:4]),
386 get_process=lambda d: float(d) / 10,
387 validator=strict_discrete_set,
388 values=range(101),
389 )
390
391 tune_capacity = Instrument.control(
392 "GT\x00\x00\x00\x00", "TC\x00\x02\x00%c",
393 """Control the percentage of full-scale value of the tune capacity.
394 It can be set only when manual_mode is True.""",
395 preprocess_reply=lambda d: struct.unpack(">H", d[4:6]),
396 get_process=lambda d: float(d) / 10,
397 validator=strict_discrete_set,
398 values=range(101),
399 )
400
401 preset_slot = Instrument.control(
402 "GT\x00\x00\x00\x00", "TP\x00%c\x00\x00",
403 """Control which preset slot will be used for auto-tune mode.
404 Valid values are 0 to 9. 0 means no preset will be used""",
405 preprocess_reply=lambda d: struct.unpack(">H", d[8:10]),
406 validator=strict_discrete_set,
407 values=range(10),
408 )
409
410 rf_enabled = Instrument.control(
411 "GS\x00\x00\x00\x00", "BR%c%c\x00\x00",
412 """Control the RF output.""",
413 preprocess_reply=lambda d: struct.unpack(">H", d[:2]),
414 get_process=lambda v: bool(v & 1),
415 set_process=lambda v: (85, 85) if v else (0, 0),
416 validator=strict_discrete_set,
417 values=(True, False),
418 )
419
420 def request_control(self):
421 """Request control of the instrument.
422
423 This is required to be able to set any properties.
424 """
425 self.write("BC\x55\x55\x00\x00")
426 status = int(struct.unpack(">H", self.read())[0])
427 if status != 1:
428 print("error(CXN): control request denied!")
429
430 def release_control(self):
431 """Release instrument control.
432
433 This will reset certain properties to safe defaults and disable the RF
434 output.
435 """
436 self.write("BC\x00\x00\x00\x00")
437 status = int(struct.unpack(">H", self.read())[0])
438 if status != 0:
439 print("error(CXN): release of control unsuccessful!")
440
441 def ping(self):
442 """Send a ping to the instrument."""
443 self.write("BP\x00\x00\x00\x00")