-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasp_cmnd.py
executable file
·582 lines (467 loc) · 23.4 KB
/
asp_cmnd.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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
#!/usr/bin/env python3
"""
asp_cmnd - Software for controlling ASP within the guidelines of the ASP and
MCS ICDs.
"""
import os
import git
import sys
import json
import time
import signal
import socket
import string
import struct
import logging
import argparse
import json_minify
try:
from logging.handlers import WatchedFileHandler
except ImportError:
from logging import FileHandler as WatchedFileHandler
import traceback
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
from MCS import *
from aspFunctions import AnalogProcessor
__version__ = '0.4'
__all__ = ['DEFAULTS_FILENAME', 'MCSCommunicate']
#
# Default Configuration File
#
DEFAULTS_FILENAME = '/lwa/software/defaults.json'
class MCSCommunicate(Communicate):
"""
Class to deal with the communcating with MCS.
"""
def __init__(self, SubSystemInstance, config, opts):
super(MCSCommunicate, self).__init__(SubSystemInstance, config, opts)
def processCommand(self, data):
"""
Interperate the data of a UDP packet as a SHL MCS command.
"""
destination, sender, command, reference, datalen, mjd, mpm, data = self.parsePacket(data)
self.logger.debug('Got command %s from %s with ref# %i', command, sender, reference)
# check destination and sender
if destination in (self.SubSystemInstance.subSystem, 'ALL'):
# PNG
if command == 'PNG':
status = True
packed_data = ''
# Report various MIB entries
elif command == 'RPT':
status = True
packed_data = ''
## General Info.
if data == 'SUMMARY':
summary = self.SubSystemInstance.currentState['status'][:7]
self.logger.debug('summary = %s', summary)
packed_data = summary
elif data == 'INFO':
### Trim down as needed
if len(self.SubSystemInstance.currentState['info']) > 256:
infoMessage = "%s..." % self.SubSystemInstance.currentState['info'][:253]
else:
infoMessage = self.SubSystemInstance.currentState['info'][:256]
self.logger.debug('info = %s', infoMessage)
packed_data = infoMessage
elif data == 'LASTLOG':
### Trim down as needed
if len(self.SubSystemInstance.currentState['lastLog']) > 256:
lastLogEntry = "%s..." % self.SubSystemInstance.currentState['lastLog'][:253]
else:
lastLogEntry = self.SubSystemInstance.currentState['lastLog'][:256]
if len(lastLogEntry) == 0:
lastLogEntry = 'no log entry'
self.logger.debug('lastlog = %s', lastLogEntry)
packed_data = lastLogEntry
elif data == 'SUBSYSTEM':
self.logger.debug('subsystem = %s', self.SubSystemInstance.subSystem)
packed_data = self.SubSystemInstance.subSystem
elif data == 'SERIALNO':
self.logger.debug('serialno = %s', self.SubSystemInstance.serialNumber)
packed_data = self.SubSystemInstance.serialNumber
elif data == 'VERSION':
self.logger.debug('version = %s', self.SubSystemInstance.version)
packed_data = self.SubSystemInstance.version
## Analog chain state - Filter
elif data[0:7] == 'FILTER_':
stand = int(data[7:])
status, filt = self.SubSystemInstance.getFilter(stand)
if status:
packed_data = str(filt)
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = exited with status %s', data, str(status))
## Analog chain state - Attenuators
elif data[0:4] == 'AT1_':
stand = int(data[4:])
status, attens = self.SubSystemInstance.getAttenuators(stand)
if status:
packed_data = str(attens[0])
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = exited with status %s', data, str(status))
elif data[0:4] == 'AT2_':
stand = int(data[4:])
status, attens = self.SubSystemInstance.getAttenuators(stand)
if status:
packed_data = str(attens[1])
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = exited with status %s', data, str(status))
elif data[0:8] == 'ATSPLIT_':
stand = int(data[8:])
status, attens = self.SubSystemInstance.getAttenuators(stand)
if status:
packed_data = str(attens[2])
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = exited with status %s', data, str(status))
## Analog gain state - FEE power
elif data[0:11] == 'FEEPOL1PWR_':
stand = int(data[11:])
status, power = self.SubSystemInstance.getFEEPowerState(stand)
if status:
if power[0]:
packed_data = 'ON '
else:
packed_data = 'OFF'
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = exited with status %s', data, str(status))
elif data[0:11] == 'FEEPOL2PWR_':
stand = int(data[11:])
status, power = self.SubSystemInstance.getFEEPowerState(stand)
if status:
if power[1]:
packed_data = 'ON '
else:
packed_data = 'OFF'
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = exited with status %s', data, str(status))
## ARX power supplies
elif data == 'ARXSUPPLY':
status, value = self.SubSystemInstance.getARXPowerSupplyStatus()
if status:
packed_data = value
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = exited with status %s', data, str(status))
elif data == 'ARXSUPPLY-NO':
status, value = self.SubSystemInstance.getARXPowerSupplyCount()
if status:
packed_data = (str(value))[:2]
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = %s' % (data, packed_data))
elif data[0:11] == 'ARXPWRUNIT_':
psNumb = int(data[11:])
status, value = self.SubSystemInstance.getARXPowerSupplyInfo(psNumb)
if status:
packed_data = value[:256]
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = exited with status %s', data, str(status))
elif data == 'ARXCURR':
status, value = self.SubSystemInstance.getARXCurrentDraw()
if status:
packed_data = "%-7i" % value
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = exited with status %s', data, str(status))
elif data == 'ARXVOLT':
status, value = self.SubSystemInstance.getARXVoltage()
if status:
packed_data = "%-7.3f" % value
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = exited with status %s', data, str(status))
## FEE power supplies
elif data == 'FEESUPPLY':
status, value = self.SubSystemInstance.getFEEPowerSupplyStatus()
if status:
packed_data = value
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = exited with status %s', data, str(status))
elif data == 'FEESUPPLY-NO':
status, value = self.SubSystemInstance.getFEEPowerSupplyCount()
if status:
packed_data = (str(value))[:2]
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = %s' % (data, packed_data))
elif data[0:11] == 'FEEPWRUNIT_':
psNumb = int(data[11:])
status, value = self.SubSystemInstance.getFEEPowerSupplyInfo(psNumb)
if status:
packed_data = value[:256]
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = exited with status %s', data, str(status))
elif data == 'FEECURR':
status, value = self.SubSystemInstance.getFEECurrentDraw()
if status:
packed_data = "%-7i" % value
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = exited with status %s', data, str(status))
elif data == 'FEEVOLT':
status, value = self.SubSystemInstance.getFEEVoltage()
if status:
packed_data = "%-7.3f" % value
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = exited with status %s', data, str(status))
## Temperatue sensors
elif data == 'TEMP-STATUS':
status, value = self.SubSystemInstance.getTemperatureStatus()
if status:
packed_data = value[:256]
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = exited with status %s', data, str(status))
elif data == 'TEMP-SENSE-NO':
status, value = self.SubSystemInstance.getTempSensorCount()
if status:
packed_data = (str(value))[:3]
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = %s' % (data, packed_data))
elif data[0:12] == 'SENSOR-NAME-':
sensorNumb = int(data[12:])
status, value = self.SubSystemInstance.getTempSensorInfo(sensorNumb)
if status:
packed_data = value[:256]
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = exited with status %s', data, str(status))
elif data[0:12] == 'SENSOR-DATA-':
sensorNumb = int(data[12:])
status, value = self.SubSystemInstance.getTempSensorData(sensorNumb)
if status:
packed_data = "%-10.3f" % value
else:
packed_data = self.SubSystemInstance.currentState['lastLog']
self.logger.debug('%s = exited with status %s', data, str(status))
else:
status = False
packed_data = 'Unknown MIB entry: %s' % data
self.logger.debug('%s = exited with status %s', data, str(status))
#
# Control Commands
#
# INI
elif command == 'INI':
# Re-read in the configuration file
with open(self.opts.config, 'r') as ch:
config = json.loads(json_minify.json_minify(ch.read()))
# Refresh the configuration for the communicator and ASP
self.updateConfig(config)
self.SubSystemInstance.updateConfig(config)
# Go
nBoards = int(data)
status, exitCode = self.SubSystemInstance.ini(nBoards)
if status:
packed_data = ''
else:
packed_data = "0x%02X! %s" % (exitCode, self.SubSystemInstance.currentState['lastLog'])
# SHT
elif command == 'SHT':
status, exitCode = self.SubSystemInstance.sht(mode=data)
if status:
packed_data = ''
else:
packed_data = "0x%02X! %s" % (exitCode, self.SubSystemInstance.currentState['lastLog'])
# FIL
elif command == 'FIL':
stand = int(data[:-2])
filterCode = int(data[-2:])
status, exitCode = self.SubSystemInstance.setFilter(stand, filterCode)
if status:
packed_data = ''
else:
packed_data = "0x%02X! %s" % (exitCode, self.SubSystemInstance.currentState['lastLog'])
# AT1
elif command == 'AT1':
mode = 1
stand = int(data[:-2])
attenSetting = int(data[-2:])
status, exitCode = self.SubSystemInstance.setAttenuator(mode, stand, attenSetting)
if status:
packed_data = ''
else:
packed_data = "0x%02X! %s" % (exitCode, self.SubSystemInstance.currentState['lastLog'])
# AT2
elif command == 'AT2':
mode = 2
stand = int(data[:-2])
attenSetting = int(data[-2:])
status, exitCode = self.SubSystemInstance.setAttenuator(mode, stand, attenSetting)
if status:
packed_data = ''
else:
packed_data = "0x%02X! %s" % (exitCode, self.SubSystemInstance.currentState['lastLog'])
# ATS
elif command == 'ATS':
mode = 3
stand = int(data[:-2])
attenSetting = int(data[-2:])
status, exitCode = self.SubSystemInstance.setAttenuator(mode, stand, attenSetting)
if status:
packed_data = ''
else:
packed_data = "0x%02X! %s" % (exitCode, self.SubSystemInstance.currentState['lastLog'])
# FPW
elif command == 'FPW':
stand = int(data[:-3])
pol = int(data[-3])
state = int(data[-2:])
status, exitCode = self.SubSystemInstance.setFEEPowerState(stand, pol, state)
if status:
packed_data = ''
else:
packed_data = "0x%02X! %s" % (exitCode, self.SubSystemInstance.currentState['lastLog'])
# RXP
elif command == 'RXP':
state = int(data)
status, exitCode = self.SubSystemInstance.setARXPowerState(state)
if status:
packed_data = ''
else:
packed_data = "0x%02X! %s" % (exitCode, self.SubSystemInstance.currentState['lastLog'])
elif command == 'FEP':
state = int(data)
status, exitCode = self.SubSystemInstance.setFPWPowerState(state)
if status:
packed_data = ''
else:
packed_data = "0x%02X! %s" % (exitCode, self.SubSystemInstance.currentState['lastLog'])
#
# Unknown command catch
#
else:
status = False
self.logger.debug('%s = error, unknown command', command)
packed_data = 'Unknown command: %s' % command
# Return status, command, reference, and the result
return sender, status, command, reference, packed_data
def main(args):
"""
Main function of asp_cmnd.py. This sets up the various configuation options
and start the UDP command handler.
"""
# Setup logging
logger = logging.getLogger(__name__)
logFormat = logging.Formatter('%(asctime)s [%(levelname)-8s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logFormat.converter = time.gmtime
if args.log is None:
logHandler = logging.StreamHandler(sys.stdout)
else:
logHandler = WatchedFileHandler(args.log)
logHandler.setFormatter(logFormat)
logger.addHandler(logHandler)
if args.debug:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
# Get current MJD and MPM
mjd, mpm = getTime()
# Git information
try:
repo = git.Repo(os.path.basename(os.path.abspath(__file__)))
branch = repo.active_branch.name
hexsha = repo.active_branch.commit.hexsha
shortsha = hexsha[-7:]
dirty = ' (dirty)' if repo.is_dirty() else ''
except git.exc.GitError:
branch = 'unknown'
hexsha = 'unknown'
shortsha = 'unknown'
dirty = ''
# Report on who we are
logger.info('Starting asp_cmnd.py with PID %i', os.getpid())
logger.info('Version: %s', __version__)
logger.info('Revision: %s.%s%s', branch, shortsha, dirty)
logger.info('Current MJD: %i', mjd)
logger.info('Current MPM: %i', mpm)
logger.info('All dates and times are in UTC except where noted')
# Read in the configuration file
with open(args.config, 'r') as ch:
config = json.loads(json_minify.json_minify(ch.read()))
# Setup ASP control
lwaASP = AnalogProcessor(config)
# Setup the communications channels
mcsComms = MCSCommunicate(lwaASP, config, args)
mcsComms.start()
# Setup handler for SIGTERM so that we aren't left in a funny state
def HandleSignalExit(signum, frame, logger=logger, MCSInstance=mcsComms):
logger.info('Exiting on signal %i', signum)
# Shutdown ASP and close the communications channels
tStop = time.time()
logger.info('Shutting down ASP, please wait...')
MCSInstance.SubSystemInstance.sht(mode='SCRAM')
while MCSInstance.SubSystemInstance.currentState['info'] != 'System has been shut down':
time.sleep(5)
MCSInstance.SubSystemInstance.sht(mode='SCRAM')
logger.info('Shutdown completed in %.3f seconds', time.time() - tStop)
MCSInstance.stop()
# Exit
logger.info('Finished')
logging.shutdown()
sys.exit(0)
# Hook in the signal handler - SIGTERM
signal.signal(signal.SIGTERM, HandleSignalExit)
# Loop and process the MCS data packets as they come in - exit if ctrl-c is
# received
logger.info('Ready to communicate')
while True:
try:
mcsComms.receiveCommand()
except KeyboardInterrupt:
logger.info('Exiting on ctrl-c')
break
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
logger.error("asp_cmnd.py failed with: %s at line %i", str(e), exc_traceback.tb_lineno)
## Grab the full traceback and save it to a string via StringIO
fileObject = StringIO()
traceback.print_tb(exc_traceback, file=fileObject)
tbString = fileObject.getvalue()
fileObject.close()
## Print the traceback to the logger as a series of DEBUG messages
for line in tbString.split('\n'):
logger.debug("%s", line)
# If we've made it this far, we have finished so shutdown ASP and close the
# communications channels
tStop = time.time()
print('\nShutting down ASP, please wait...')
logger.info('Shutting down ASP, please wait...')
for attempt in range(5):
lwaASP.sht()
time.sleep(5)
if lwaASP.currentState['info'] == 'System has been shut down':
break
logger.info('Shutdown completed in %.3f seconds', time.time() - tStop)
mcsComms.stop()
# Exit
logger.info('Finished')
logging.shutdown()
sys.exit(0)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='control the ASP sub-system within the guidelines of the ASP and MCS ICDs',
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument('-c', '--config', type=str, default=DEFAULTS_FILENAME,
help='name of the ASP configuration file to use')
parser.add_argument('-l', '--log', type=str,
help='name of the logfile to write logging information to')
parser.add_argument('-d', '--debug', action='store_true',
help='print debug messages as well as info and higher')
args = parser.parse_args()
main(args)