Debian Codegraph @

pymeasure/instruments/hcp/tc038d.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
27 from enum import IntEnum
28
29 from pymeasure.instruments import Instrument
30
31
32 log = logging.getLogger(__name__)
33 log.addHandler(logging.NullHandler())
34
35
36 def CRC16(data):
37 """Calculate the CRC16 checksum for the data byte array."""
38 CRC = 0xFFFF
39 for octet in data:
40 CRC ^= octet
41 for j in range(8):
42 lsb = CRC & 0x1 # least significant bit
43 CRC = CRC >> 1
44 if lsb:
45 CRC ^= 0xA001
46 return [CRC & 0xFF, CRC >> 8]
47
48
49 class Functions(IntEnum):
50 R = 0x03
51 WRITESINGLE = 0x06
52 ECHO = 0x08 # register address has to be 0
53 W = 0x10 # writing multiple variables
54
55
56 class TC038D(Instrument):
57 """
58 Communication with the HCP TC038D oven.
59
60 This is the newer version with DC heating.
61
62 The oven expects raw bytes written, no ascii code, and sends raw bytes.
63 For the variables are two or four-byte modes available. We use the
64 four-byte mode addresses. In that case element count has to be
65 double the variables read.
66 """
67
68 byteMode = 4
69
70 def __init__(self, adapter, name="TC038D", address=1, timeout=1000,
71 **kwargs):
72 """Initialize the device."""
73 super().__init__(adapter, name, timeout=timeout,
74 includeSCPI=False,
75 **kwargs)
76 self.address = address
77
78 def write(self, command):
79 """Write a command to the device.
80
81 :param str command: comma separated string of:
82 - the function: read ('R') or write ('W') or 'echo',
83 - the address to write to (e.g. '0x106' or '262'),
84 - the values (comma separated) to write
85 - or the number of elements to read (defaults to 1).
86 """
87 function, address, *values = command.split(",")
88 function = Functions[function]
89 data = [self.address] # 1B device address
90 data.append(function) # 1B function code
91 address = int(address, 16) if "x" in address else int(address)
92 data.extend(address.to_bytes(2, "big")) # 2B register address
93 if function == Functions.W:
94 elements = len(values) * self.byteMode // 2
95 data.extend(elements.to_bytes(2, "big")) # 2B number of elements
96 data.append(elements * 2) # 1B number of bytes to write
97 for element in values:
98 data.extend(int(element).to_bytes(self.byteMode, "big", signed=True))
99 elif function == Functions.R:
100 count = int(values[0]) * self.byteMode // 2 if values else self.byteMode // 2
101 data.extend(count.to_bytes(2, "big")) # 2B number of elements to read
102 elif function == Functions.ECHO:
103 data[-2:] = [0, 0]
104 if values:
105 data.extend(int(values[0]).to_bytes(2, "big")) # 2B test data
106 data += CRC16(data)
107 self.write_bytes(bytes(data))
108
109 def read(self):
110 """Read response and interpret the number, returning it as a string."""
111 # Slave address, function
112 got = self.read_bytes(2)
113 if got[1] == Functions.R:
114 # length of data to follow
115 length = self.read_bytes(1)
116 # data length, 2 Byte CRC
117 read = self.read_bytes(length[0] + 2)
118 if read[-2:] != bytes(CRC16(got + length + read[:-2])):
119 raise ConnectionError("Response CRC does not match.")
120 return str(int.from_bytes(read[:-2], byteorder="big", signed=True))
121 elif got[1] == Functions.W:
122 # start address, number elements, CRC; each 2 Bytes long
123 got += self.read_bytes(2 + 2 + 2)
124 if got[-2:] != bytes(CRC16(got[:-2])):
125 raise ConnectionError("Response CRC does not match.")
126 elif got[1] == Functions.ECHO:
127 # start address 0, data, CRC; each 2B
128 got += self.read_bytes(2 + 2 + 2)
129 if got[-2:] != bytes(CRC16(got[:-2])):
130 raise ConnectionError("Response CRC does not match.")
131 return str(int.from_bytes(got[-4:-2], "big"))
132 else: # an error occurred
133 # got[1] is functioncode + 0x80
134 end = self.read_bytes(3) # error code and CRC
135 errors = {0x02: "Wrong start address.",
136 0x03: "Variable data error.",
137 0x04: "Operation error."}
138 if end[0] in errors.keys():
139 raise ValueError(errors[end[0]])
140 else:
141 raise ConnectionError(f"Unknown read error. Received: {got} {end}")
142
143 def check_set_errors(self):
144 """Check for errors after having set a property.
145
146 Called if :code:`check_set_errors=True` is set for that property.
147 """
148 try:
149 self.read()
150 except Exception as exc:
151 log.exception("Setting a property failed.", exc_info=exc)
152 raise
153 else:
154 return []
155
156 def ping(self, test_data=0):
157 """Test the connection sending an integer up to 65535, checks the response."""
158 assert int(self.ask(f"ECHO,0,{test_data}")) == test_data
159
160 setpoint = Instrument.control(
161 "R,0x106", "W,0x106,%i",
162 """Control the setpoint of the oven in °C.""",
163 check_set_errors=True,
164 get_process=lambda v: v / 10,
165 set_process=lambda v: int(round(v * 10)),
166 )
167
168 temperature = Instrument.measurement(
169 "R,0x0",
170 """Measure the current oven temperature in °C.""",
171 get_process=lambda v: v / 10,
172 )