-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHvController.py
378 lines (311 loc) · 11 KB
/
HvController.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# -*- coding: utf-8 -*-
#
# This file is part of the HvControllerGUI software.
# The HvController class contains methods to operate the HV device.
# It was developped for a FJ model +40kV 3.0 mA
#
# Copyright 2018-2019 Aurélie Vancraeyenest
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import serial
import time
import logging
import checksum
class HvController():
'''
Class for controlling HV power supply Glassman FJ model +40kV 3.0 mA
Modify constants according to specifications of the device:
MAX_VOLTAGE = 40.0
MAX_CURENT = 3.0
MAX_HEX_VAL_RECEIVE = 0x3FF
MAX_HEX_VAL_SENT = 0xFFF
'''
MAX_VOLTAGE = 40.0
MAX_CURENT = 3.0
MAX_HEX_VAL_RECEIVE = 0x3FF
MAX_HEX_VAL_SENT = 0xFFF
def __init__(self):
self.device = serial.Serial()
self.voltage = 0
self.current = 0
self.hvOn = False
self.fault = False
self.ctrlMode = 'voltage'
self.logger = logging.getLogger('hvController')
def openPortHV(self, port, defaultTI=2):
'''
Open the port for communication with HV supply
Parameters
----------
portname : str
Port name (default 'COM4')
defaultTI : float
default time out (default 2 sec)
'''
self.device.port = port
self.device.timeout = defaultTI
self.device.open()
def closePortHV(self):
'''
Close the HV port and check if correctly closed
Returns
-------
output : str
Succesful or still open
'''
self.resetHV()
self.device.close()
if self.device.is_open is False:
return ("Device on port {} has been closed succesfully"
.format(self.device.name))
else:
return ("The close command has failed: port {} is still open!"
.format(self.device.name))
# TODO: handle closing error
def queryHV(self, verbosity=False):
'''
HV controller method to query the HV (Q command)
Parameters
----------
verbosity : bool
Set to True for verbose output
Returns
-------
Status : str
return str of the status if verbosity set to True
Updated values
--------------
hvOn : bool
True if HV is on
fault : bool
True if HV is faulty
ctrlMode : str
'voltage' or 'current'
voltage : float
Voltage value in kV
current : float
Current value in mA
'''
self.device.read_all()
queryCmd = self._encodeCommand('Q')
answer = self._sendCommand(queryCmd)
checksum.checkChecksum(answer)
controlMode = {'0': 'voltage', '1': 'current'}
faultStatus = {'0': False, '1': True}
hvOnStatus = {'0': False, '1': True}
# First extract the HV status and update the status
statusBits = bin(int(answer[10:11], 16)).lstrip('0b').zfill(3)
self.hvOn = hvOnStatus[statusBits[0]]
self.fault = faultStatus[statusBits[1]]
self.ctrlMode = controlMode[statusBits[2]]
# Then extract the HV voltage and current values
voltageByte = answer[1:4]
curentByte = answer[4:7]
self.voltage = round(int(voltageByte, 16)
* self.MAX_VOLTAGE / self.MAX_HEX_VAL_RECEIVE, 1)
self.current = round(int(curentByte, 16)
* self.MAX_CURENT / self.MAX_HEX_VAL_RECEIVE, 1)
if verbosity:
return ('HV status: \n V = {v} \n I = {A}'
'\n HV mode : {mode} \n HV fault: {f} \n HV on: {on}'
.format(v=self.voltage, A=self.current, mode=self.ctrlMode,
f=self.fault, on=self.hvOn))
def setHV(self, voltToSet, curToSet, digitContr='on', verbosity=False):
'''
HV controller method to send a set HV command (S command)
Parameters
----------
voltToSet : float
Voltage in kV rounded to 0.01 precision
curToSet : float
Current in mA rounded to 0.01 precision
digitContr : str
'on' 'off' or 'reset'
verbosity : bool
Set to True for verbose output
Returns
-------
Output : str
return str succes or failed if verbosity set to True
Updated values by a query after the execution:
----------------------------------------------
hvOn : bool
True if HV is on
fault : bool
True if HV is faulty
ctrlMode : str
'voltage' or 'current'
voltage : float
Voltage value in kV
current : float
Current value in mA
'''
# Construct the S commmand
# Voltage and current are given in % of MAX_VALUE
voltHex = round(voltToSet * self.MAX_HEX_VAL_SENT / self.MAX_VOLTAGE)
curHex = round(curToSet * self.MAX_HEX_VAL_SENT / self.MAX_CURENT)
# "%0.3X" % voltHex for 3 digit uppercase hex value
if digitContr == 'off':
cmd = 'S' + "%0.3X" % voltHex + "%0.3X" % curHex + '0000001'
elif digitContr == 'on':
cmd = 'S' + "%0.3X" % voltHex + "%0.3X" % curHex + '0000002'
elif digitContr == 'reset':
cmd = 'S' + "%0.3X" % 0 + "%0.3X" % 0 + '0000004'
cmdToSend = self._encodeCommand(cmd)
answer = self._sendCommand(cmdToSend, readTI=0.5)
# Handle the answer
if verbosity:
if answer == b'A':
return ("The set command sent succesfully: {} V, {} mA "
.format(voltToSet, curToSet))
else:
return ("Set command has failed \n Returned answer: {}"
.format(answer))
# update of the HV status values
self.queryHV()
def version(self):
'''
HV controller method to ask the Version number (V command)
The version number is encoded on bytes 1-2
Returns
-------
Output : str
Return version number
'''
cmdToSend = self._encodeCommand('V')
answer = self._sendCommand(cmdToSend)
checksum.checkChecksum(answer)
return ("The firmware version is: {}"
.format(answer[1:-2].decode()))
def resetHV(self, verbosity=False):
'''
HV controller method to send a reset HV command (S command)
Send a set HV method with digitContr = 'reset' so output is the
same as setHV() method. Refer to it for details.
Parameters
----------
verbosity : bool
Set to True for verbose output
Returns
-------
Output : str
Return str succes or failed if verbosity set to True
Updated values by a query after the execution
---------------------------------------------
hvOn : bool
True if HV is on
fault : bool
True if HV is faulty
ctrlMode : str
'voltage' or 'current'
voltage : float
Voltage value in kV
current : float
Current value in mA
'''
output = self.setHV(0.0, 0.0, 'reset', verbosity)
return output
def _configureHV(self, timeoutMode="enable"):
'''
HV controller method to switch timeout mode ('enable' or 'disable')
WARNING
-------
The timeout mode should always be enabled when the power
supply is in normal use !!!
Disable the timeout only for software debugging purposes!!!
Parameters
----------
timeoutMode : str
'enable' or 'disable'
Returns
-------
console output : str
prints to the console : enabled or disabled
'''
if timeoutMode == "enable":
configCmd = self._encodeCommand('C0')
answer = self._sendCommand(configCmd)
if answer is b'A':
print("The timeout has been enabled")
else:
print(answer)
elif timeoutMode == "disable":
configCmd = self._encodeCommand('C1')
answer = self._sendCommand(configCmd)
if answer is b'A':
print("The timeout has been disabled")
else:
print(answer)
def _sendCommand(self, cmdToSend, readTI=0.1):
'''
HV controller method to send command to HV
Parameters
----------
cmdToSend : bytes
Format b'\\\\x01XXXXXXX\\\\x0D'
readTI : float
Timeout for read method (default 0.1 s)
Returns
-------
Answer : bytes
return the answer received in bytes
'''
self.device.read_all()
self.device.write(cmdToSend)
time.sleep(readTI)
answer = self.device.read_all().strip(b'\r')
if answer.startswith(b'E'):
self._handleError(answer)
else:
return answer
def _encodeCommand(self, cmd):
'''
HV controller method to encode command from string to bytes
Convert the string command into a bytes object, prepend the
SOH character and append the checksum as well as the
CR character
Parameters
----------
cmd : str
String part of the command (e.g. Q051) including checksum
Returns
-------
Command : bytes
Return the command bytes (e.g. b'\\\\x01Q051\\\\x0D')
'''
csum = checksum.calculateChksum(cmd)
cmdToSend = b'\x01' + bytes(cmd, 'ascii') + csum + b'\x0D'
return cmdToSend
def _handleErrors(self, errorMes):
'''
HV controller method to decode received error message
Parameters
----------
errorMes : bytes
Error message stripped for b'\\\\r'
Returns
-------
message : str
Return the error message
Note
----
Not in use in the current version
'''
errorKey = int(errorMes.lstrip(b'E').decode('ascii')[0])
errorDict = {1: "Undefined Command Code",
2: "Checksum Error",
3: "Extra Byte(s) received",
4: "Illegal Digital Control Byte In Set Command",
5: "Illegal Set Command Received While a Fault is Active",
6: "Processing Error"}
return ("An error has occured: {}".format(errorDict[errorKey]))