This repository has been archived by the owner on Jun 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
secretary.py
418 lines (329 loc) · 11.2 KB
/
secretary.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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
from Managers import FileManager
from Managers.LoggerManager import Logger
from Managers.FileManager import Process
from multiprocessing import Queue
from queue import Empty
from enum import Enum
import time
import configparser
import os
import sys, traceback
# Secretary is meants as a main hub for the entire software.
# It mediates communication between the processes.
#
# Commands between processes are lists, not strings.
# If the list has 1 element it is always assumed to be an
# error, otherwise, it is process specific.
def read_config():
config = configparser.ConfigParser()
with open('file.cfg') as f:
config.read_file(f)
return config['FILE']
# Read the the stdin/boss and prepares the data to be ran in the loop
# Commands from the CMD are expected to have the
# following form:
# 1) One word. General command that is expected to do
# one single thing for the entire software. Ex.
# "close" prepares and closes all processes.
# 2) Two words. Command aimed at a specific process.
# Ex. "ARDUINO retrieveErrors" sends the command
# "retrieveErrors" to the arduinoer process.
# 3) Three words. Same as two words command with the
# addition of a value parameter. Ex. "ARDUINO setTemperature 10"
def listen_to_boss(*, queue, err):
response = { \
'process' : Process.NONE, \
'close' : False, \
'cmd' : '', \
'value' : ''}
try:
cmd = queue.get_nowait()
if len(cmd) == 1:
response['cmd'] = cmd[0]
elif len(cmd) == 2:
response['process'] = Process[cmd[0]]
response['cmd'] = cmd[1]
elif len(cmd) >= 3:
response['process'] = Process[cmd[0]]
response['cmd'] = cmd[1]
response['value'] = cmd[2]
response['close'] = (response['cmd'] == 'close')
return (response, err)
except Empty as error:
return (None, err)
except Exception as error:
raise error
def listen_to_queue(*, queue, err):
if queue is None:
return (None, err)
try:
items = queue.get_nowait()
return (items, err)
except Empty as error:
return (None, err)
except Exception as error:
raise error
# Grabs the response or command and relays to the
# other processes.
def relay_message(*, response, queues):
ardOutQueue = queues['ArduinoOut']
ivOutQueue = queues['ElectrometerOut']
graQueue = queues['Grapher']
if response is not None:
if response['process'] == Process.ARDUINO:
if ardOutQueue is not None:
ardOutQueue.put(response)
elif response['process'] == Process.IV:
if ivOutQueue is not None:
ivOutQueue.put(response)
elif response['process'] == Process.GRAPHER:
graQueue.put(response)
elif response['process'] == Process.SECRETARY:
pass # What to do here
elif response['process'] == Process.ALL:
graQueue.put(response)
if ardOutQueue is not None:
ardOutQueue.put(response)
if ivOutQueue is not None:
ivOutQueue.put(response)
def loop(file, graQueue, bossQueue, ardOutQueue, ardInQueue, ivOutQueue, \
ivInQueue, commErr):
### Saving data to file while-loop ###
print('[File] Starting listening.')
onGoing = True
isRunning = False
# Loop config bits
config = read_config()
endRunByTime = config.getboolean('EndRunTimeCondition')
startTime = time.time()
endTime = float(config['EndRunTime'])
while onGoing:
# Run at ~100 Hz
time.sleep(1.0/100)
# BOSS LOOP #
# Listens to CMD, parses the command, and sends it around.
response, commErr = listen_to_boss(queue=bossQueue, err=commErr)
# If the command is specifically formatted, it will relay.
relay_message(response = response, queues = { \
'ArduinoOut' : ardOutQueue, \
'ElectrometerOut' : ivOutQueue, \
'Grapher' : graQueue })
# If commands are single words, we build the command.
if response is not None:
if response['close']:
close(file, \
graQueue, bossQueue, ardOutQueue, ardInQueue, ivOutQueue, \
ivInQueue, commErr)
# Only way to stop the while loop
onGoing = False
# One word commands
# Restarts the system in case of an error.
if response['cmd'] == 'restart':
commErr = restart(file, \
graQueue, bossQueue, ardOutQueue, ardInQueue, ivOutQueue, \
ivInQueue, commErr)
# Sets the arduino and electrometer in standby mode.
elif response['cmd'] == 'standby':
standbyCMD = { \
'process' : Process.ALL, \
'close' : False, \
'cmd' : 'setState', \
'value' : 'STANDBY'}
if ardOutQueue is not None:
ardOutQueue.put(standbyCMD)
if ivOutQueue is not None:
ivOutQueue.put(standbyCMD)
# Starts the system.
elif response['cmd'] == 'run':
isRunning = True
runCMD = { \
'process' : Process.ALL, \
'close' : False, \
'cmd' : 'setState', \
'value' : 'RUNNING'}
if ardOutQueue is not None:
ardOutQueue.put(runCMD)
if ivOutQueue is not None:
ivOutQueue.put(runCMD)
elif response['cmd'] == 'next':
cmd = { \
'process' : Process.IV, \
'close' : False, \
'cmd' : 'next', \
'value' : ''}
if ivOutQueue is not None:
ivOutQueue.put(cmd)
# # Debug command to let the arduino know we are done with the
# # measurements.
# elif response['cmd'] == 'done':
# cmd = { \
# 'process' : Process.ARDUINO, \
# 'close' : False, \
# 'cmd' : 'done', \
# 'value' : ''}
# if ardOutQueue is not None:
# ardOutQueue.put(cmd)
################
# IV LOOP #
items, commErr = listen_to_queue(queue=ivInQueue, err=commErr)
if items is not None:
if items['Data'] is not None:
data = items['Data']
# data[0] = time
# data[1] = voltage
# data[2] = current
file.add_IV(data[0:3], numSiPM=data[3])
graQueue.put([data[0], None, data[1], data[2], None, None])
if items['Error'] is not None:
commErr = f'{commErr} Electrometer returned error: {items["Error"]}'
if items['FatalError'] is not None:
if items['FatalError']:
# If a fatal error is present in any of the
# other threads. We close.
raise Exception('Electrometer returned with a fatal error.')
if items['CMD'] is not None:
cmd = items['CMD']
relay_message(response = cmd, queues = { \
'ArduinoOut' : ardOutQueue, \
'ElectrometerOut' : ivOutQueue, \
'Grapher' : graQueue })
################
# ARDUINO LOOP #
items, commErr = listen_to_queue(queue=ardInQueue, err=commErr)
if items is not None:
if items['Data'] is not None:
data = items['Data']
file.add_HT(data)
graQueue.put([None, data[0], None, None, data[1], data[2]])
if items['Error'] is not None:
commErr = f'{commErr} Arduino returned error: {items["Error"]}'
if items['FatalError'] is not None:
if items['FatalError']:
# If a fatal error is present in any of the
# other threads. We close.
raise Exception('Arduino returned with a fatal error.')
if items['CMD'] is not None:
cmd = items['CMD']
relay_message(response = cmd, queues = { \
'ArduinoOut' : ardOutQueue, \
'ElectrometerOut' : ivOutQueue, \
'Grapher' : graQueue })
################
# RUNNING LOOP #
################ Things done in the loop of secretary.
# Nothing to see for now.
################
# Sends a command and listens for a reply from the arduino and
# electrometer.
def send_and_listen(cmd, graQueue, bossQueue, ardOutQueue, ardInQueue, \
ivOutQueue, ivInQueue, commErr):
if ardOutQueue is not None:
ardOutQueue.put(cmd)
try:
response = ardInQueue.get(timeout=10)
if response is not None:
if response['Error'] is not None:
commErr = f'{commErr} {response["Error"]}'
except Empty:
commErr = f'{commErr} Arduino did not return a response.'
except Exception as err:
commErr = f'{commErr} {err}.'
print(f'[File] Error while listening to Arduino: {err}.')
if ivOutQueue is not None:
ivOutQueue.put(cmd)
try:
response = ivInQueue.get(timeout=10)
if response is not None:
if response['Error'] is not None:
commErr = f'{commErr} {response["Error"]}'
except Empty:
commErr = f'{commErr} Electrometer did not return a response.'
except Exception as err:
commErr = f'{commErr} {err}.'
print(f'[File] Error while listening to Electroemeter: {err}.')
if graQueue is not None:
graQueue.put(cmd)
return commErr
# Important commands that needs their own function. #
# Command -> 'close'
# Send a command to retrieve all the cumulated errors, and close
# all the processes.
def close(file, graQueue, bossQueue, ardOutQueue, ardInQueue, ivOutQueue, \
ivInQueue, commErr):
print('[File] Closing everything.')
closeResponse = { \
'process' : Process.ALL, \
'close' : True, \
'cmd' : 'close', \
'value' : '' }
commErr = send_and_listen(closeResponse, \
graQueue, bossQueue, ardOutQueue, ardInQueue, ivOutQueue, ivInQueue, commErr)
# Finally, add any errors that were
# present in the run.
if file is not None:
file.add_attribute('Error', commErr)
return commErr
# Command -> 'restart'
# Restarts the software by cleaning the error, and opening a new database
# under the same name as the last one.
def restart(file, graQueue, bossQueue, ardOutQueue, ardInQueue, ivOutQueue, \
ivInQueue, commErr):
print('[File] Restarting everything.')
restartResponse = { \
'process' : Process.ALL, \
'close' : False, \
'cmd' : 'restart', \
'value' : '' }
# Retrieve the errors from all the processes.
commErr = send_and_listen(restartResponse, \
graQueue, bossQueue, ardOutQueue, ardInQueue, ivOutQueue, ivInQueue, commErr)
# Save errors to file.
if file is not None:
file.add_attribute('Error', commErr)
# Reset the error as it was saved to previous 'run'.
commErr = ''
# 'resets' file but in reality it starts another run.
if file is not None:
file.reset()
# Should be empty but we are keeping a standard.
return commErr
######################################
def file_process_main(*, bossQueue, graQueue, ardOutQueue=None, ardInQueue=None, \
ivOutQueue=None, ivInQueue=None):
# Makes sure all output gets written to a log and console.
sys.stdout = Logger()
file = None
commulativeError = ''
# Only three config for now. Database name, file name and comment
# Maybe expand to include number of data points, time, etc
configs = read_config()
db_name = configs['DBName']
name_of_measurements = configs['FileName']
comment = configs['Comment']
NUM_SIPMS = int(configs['NumSiPMsToTest'])
try:
# File creation/initialization
print('[File] Setting up database.')
file = FileManager.sipmFileManager(db_name, numSiPMs=NUM_SIPMS)
file.create_dataset(name_of_measurements)
file.add_attribute('Comment', comment)
loop(file, graQueue, bossQueue, ardOutQueue, ardInQueue, ivOutQueue, \
ivInQueue, commulativeError)
# If an error occurred during secretary, the best thing to do
# is to delete everything and restart the software.
# Before closing, we retrieve all the errors if possible.
except Exception as err:
print('[File] Error with the file manager. Deleting previous data base.')
print(f'[File] Error: {err}.')
commulativeError = f'{commulativeError} {err}.'
# If the file broke the error will not be saved.
# In fact, nothing will.
close(file, graQueue, bossQueue, ardOutQueue, ardInQueue, ivOutQueue, \
ivInQueue, commulativeError)
if file is not None:
file.delete_dataset()
traceback.print_exc(file=sys.stdout)
# Open resources.
finally:
if file is not None:
file.close()