-
Notifications
You must be signed in to change notification settings - Fork 0
/
wsgi.py
471 lines (425 loc) · 18.4 KB
/
wsgi.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
import logging
from logging.handlers import TimedRotatingFileHandler
from flask import Flask
from flask import render_template
from flask import jsonify
from flask import request
from flask import send_from_directory
from flask import Response
import os
from IPy import IP
from subprocess import Popen, PIPE
import requests
from collections import Iterable
from sleekxmpp import ClientXMPP
from sleekxmpp.exceptions import IqError, IqTimeout
import configparser
import helium_compressor
import temperature_controller
import vacuum_pump
import pressure_gauge
import relay_module
import xmpp_bot
import tcp_emul
import redirector
import autostart
def csv(data, sep = '\t'):
s = ""
if isinstance(data, Iterable):
for line in data:
l = ""
if isinstance(line, dict):
for key, value in line.items():
l += repr(value) + sep
elif isinstance(line, Iterable):
for item in data:
l += repr(item) + sep
else:
l = repr(item)
s += l.strip() + '\n'
return s
def get_mac(ip):
mac = None
try:
cmd = "arping -f -I wlan0 " + ip
result = Popen(cmd, stdout=PIPE, shell=True)
mac = result.stdout.readlines()[1].decode('ascii').split()[-2][1:-1]
print(mac)
except:
pass
return mac
config = configparser.ConfigParser()
config.read('/cryolab/python/wsgi.ini')
masters_list = [mac.split('#')[0].strip() for mac in config['masters']['MACs'].splitlines()]
cmpr = helium_compressor.worker()
tmpr = temperature_controller.worker()
relay = relay_module.worker()
pump = vacuum_pump.worker()
gauge = pressure_gauge.worker()
tmpr_rtm = temperature_controller.worker_rtm(temperature_controller=tmpr)
tcp_emul = tcp_emul.worker(temperature_controller = tmpr)
redirector = redirector.worker()
autostarter = autostart.worker(relay=relay, pump=pump, compressor=cmpr)
# xmpp = xmpp_bot.bot(config['XMPP']['jid'], config['XMPP']['pass'])
# # xmpp.register_plugin('xep_0030') # Service Discovery
# # xmpp.register_plugin('xep_0004') # Data Forms
# # xmpp.register_plugin('xep_0060') # PubSub
# # xmpp.register_plugin('xep_0199') # XMPP Ping
#
# xmpp.use_proxy = True
# xmpp.proxy_config = {
# 'host': config['proxy']['host'],
# 'port': int(config['proxy']['port']),
# 'username': config['proxy']['username'],
# 'password': config['proxy']['password']
# }
#
# xmpp.trusted_senders = [login.split('#')[0].strip() for login in config['masters']['jabbers'].splitlines()]
# xmpp.helium_compressor = cmpr
# xmpp.temperature_controller = tmpr
print("Starting")
app = Flask(__name__)
app.url_map.strict_slashes = False
# app.debug = True
if not app.debug:
formatter = logging.Formatter("[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s")
handler = TimedRotatingFileHandler('/cryolab/python/logs/wsgi.log', when='midnight', interval=1, backupCount=5)
handler.setLevel(logging.WARNING)
handler.setFormatter(formatter)
log = logging.getLogger('werkzeug')
log.setLevel(logging.WARNING)
log.addHandler(handler)
app.logger.addHandler(handler)
else:
logging.basicConfig(level=logging.DEBUG)
# if xmpp.connect((config['XMPP']['server'], int(config['XMPP']['port']))):
# print("XMPP connected")
# else:
# print("XMPP connection failed")
# xmpp.process(block=False)
relay.start()
cmpr.start()
tmpr.start()
tcp_emul.start()
tmpr_rtm.start()
pump.start()
gauge.start()
autostarter.start()
@app.errorhandler(404)
def page_not_found(error):
print('This route does not exist {}'.format(request.url))
print(error)
return 'This route does not exist {}'.format(request.url), 404
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'),
'favicon.ico', mimetype='image/vnd.microsoft.icon')
@app.route('/', methods=['GET', 'POST'])
def index():
if temperature_controller.is_realtime_measurement_running:
return "Please wait 'till a measurement is over"
return render_template('status.html',
master_mind = (get_mac(request.remote_addr) in masters_list),
cmpr_pressures = cmpr.pressures,
cmpr_temperatures = cmpr.temperatures,
cmpr_config_mode = cmpr.config_mode,
cmpr_local_on = cmpr.local_on,
cmpr_cold_head_run = cmpr.cold_head_run,
cmpr_cold_head_pause = cmpr.cold_head_pause,
cmpr_fault_off = cmpr.fault_off,
cmpr_oil_fault_off = cmpr.oil_fault_off,
cmpr_solenoid_on = cmpr.solenoid_on,
cmpr_pressure_off = cmpr.pressure_off,
cmpr_oil_level_alarm = cmpr.oil_level_alarm,
cmpr_water_flow_alarm = cmpr.water_flow_alarm,
cmpr_water_temperature_alarm = cmpr.water_temperature_alarm,
cmpr_helium_temperature_off = cmpr.helium_temperature_off,
cmpr_mains_off = cmpr.mains_off,
cmpr_motor_temperature_off = cmpr.motor_temperature_off,
cmpr_system_on = cmpr.system_on,
tmpr_temperatures = tmpr.temperatures,
tmpr_output = tmpr.output)
@app.route('/json', methods= ['GET'])
def stuff():
if temperature_controller.is_realtime_measurement_running:
return "Please wait 'till a measurement is over"
return jsonify(cmpr_pressures = cmpr.pressures,
cmpr_temperatures = cmpr.temperatures,
cmpr_config_mode = cmpr.config_mode,
cmpr_local_on = cmpr.local_on,
cmpr_cold_head_run = cmpr.cold_head_run,
cmpr_cold_head_pause = cmpr.cold_head_pause,
cmpr_fault_off = cmpr.fault_off,
cmpr_oil_fault_off = cmpr.oil_fault_off,
cmpr_solenoid_on = cmpr.solenoid_on,
cmpr_pressure_off = cmpr.pressure_off,
cmpr_oil_level_alarm = cmpr.oil_level_alarm,
cmpr_water_flow_alarm = cmpr.water_flow_alarm,
cmpr_water_temperature_alarm = cmpr.water_temperature_alarm,
cmpr_helium_temperature_off = cmpr.helium_temperature_off,
cmpr_mains_off = cmpr.mains_off,
cmpr_motor_temperature_off = cmpr.motor_temperature_off,
cmpr_system_on = cmpr.system_on,
tmpr_temperatures = tmpr.temperatures,
tmpr_output = tmpr.output)
@app.route('/helium_compressor')
def cmpr_index():
if temperature_controller.is_realtime_measurement_running:
return "Please wait 'till a measurement is over"
return render_template('cmpr.html',
master_mind = (get_mac(request.remote_addr) in masters_list),
pressures = cmpr.pressures,
temperatures = cmpr.temperatures,
config_mode = cmpr.config_mode,
local_on = cmpr.local_on,
cold_head_run = cmpr.cold_head_run,
cold_head_pause = cmpr.cold_head_pause,
fault_off = cmpr.fault_off,
oil_fault_off = cmpr.oil_fault_off,
solenoid_on = cmpr.solenoid_on,
pressure_off = cmpr.pressure_off,
oil_level_alarm = cmpr.oil_level_alarm,
water_flow_alarm = cmpr.water_flow_alarm,
water_temperature_alarm = cmpr.water_temperature_alarm,
helium_temperature_off = cmpr.helium_temperature_off,
mains_off = cmpr.mains_off,
motor_temperature_off = cmpr.motor_temperature_off,
system_on = cmpr.system_on)
@app.route('/helium_compressor/json', methods= ['GET'])
def cmpr_json():
return jsonify(pressures = cmpr.pressures,
temperatures = cmpr.temperatures,
config_mode = cmpr.config_mode,
local_on = cmpr.local_on,
cold_head_run = cmpr.cold_head_run,
cold_head_pause = cmpr.cold_head_pause,
fault_off = cmpr.fault_off,
oil_fault_off = cmpr.oil_fault_off,
solenoid_on = cmpr.solenoid_on,
pressure_off = cmpr.pressure_off,
oil_level_alarm = cmpr.oil_level_alarm,
water_flow_alarm = cmpr.water_flow_alarm,
water_temperature_alarm = cmpr.water_temperature_alarm,
helium_temperature_off = cmpr.helium_temperature_off,
mains_off = cmpr.mains_off,
motor_temperature_off = cmpr.motor_temperature_off,
system_on = cmpr.system_on)
@app.route('/helium_compressor/do', methods = ['POST'])
def cmpr_do():
if temperature_controller.is_realtime_measurement_running:
return "Please wait 'till a measurement is over"
mac = get_mac(request.remote_addr)
if mac in masters_list:
try:
if cmpr.turn(request.json['action']):
return "Command succeeded"
else:
app.logger.warning("compressor failed to process " + repr(request.json))
return "Command failed"
except:
app.logger.error("an error occured while processing " + repr(request.json))
return "Command failed with an error"
app.logger.info("someone %s tried to manipulate the compressor", mac)
return "Permission denied"
@app.route('/relay_module')
def relay_index():
if temperature_controller.is_realtime_measurement_running:
return "Please wait 'till a measurement is over"
return render_template('relay.html',
master_mind = (get_mac(request.remote_addr) in masters_list),
relay_on = relay.is_on)
@app.route('/relay_module/json', methods=['GET'])
def relay_json():
return jsonify(relay_on=relay.is_on)
@app.route('/relay_module/do', methods=['POST'])
def relay_do():
if temperature_controller.is_realtime_measurement_running:
return "Please wait 'till a measurement is over"
mac = get_mac(request.remote_addr)
if mac in masters_list:
try:
relay.is_on = (request.json['action'] not in [0, False])
return "Command succeeded"
except:
app.logger.error("an error occured while processing " + repr(request.json))
return "Command failed with an error"
app.logger.info("someone %s tried to manipulate the relay", mac)
return "Permission denied"
@app.route('/autostart')
def autostart_index():
if temperature_controller.is_realtime_measurement_running:
return "Please wait 'till a measurement is over"
return render_template('autostart.html',
master_mind = (get_mac(request.remote_addr) in masters_list),
autostart_on = autostarter.is_running(),
relay_on = autostarter.relay_on,
water_is_cold = autostarter.water_cold,
pump_on = autostarter.pump_on,
pump_is_ready = autostarter.pump_ready,
compressor_on = autostarter.compressor_on
)
@app.route('/autostart/json', methods=['GET'])
def autostart_json():
return jsonify(
autostart_on = autostarter.is_running(),
relay_on = autostarter.relay_on,
water_is_cold = autostarter.water_cold,
pump_on = autostarter.pump_on,
pump_is_ready = autostarter.pump_ready,
compressor_on = autostarter.compressor_on
)
@app.route('/autostart/do', methods=['POST'])
def autostart_do():
if temperature_controller.is_realtime_measurement_running:
return "Please wait 'till a measurement is over"
mac = get_mac(request.remote_addr)
if mac in masters_list:
try:
autostarter.set_running(request.json['action'] not in [0, False])
return "Command succeeded"
except:
app.logger.error("an error occured while processing " + repr(request.json))
return "Command failed with an error"
app.logger.info("someone %s tried to manipulate the autostart module", mac)
return "Permission denied"
@app.route('/vacuum_pump')
def pump_index():
if temperature_controller.is_realtime_measurement_running:
return "Please wait 'till a measurement is over"
return render_template('pump.html',
master_mind = (get_mac(request.remote_addr) in masters_list),
pumping_on = pump.pumping,
speed = pump.speed)
@app.route('/vacuum_pump/json', methods= ['GET'])
def pump_json():
return jsonify(pumping_on = pump.pumping,
speed = pump.speed)
@app.route('/vacuum_pump/do', methods = ['POST'])
def pump_do():
if temperature_controller.is_realtime_measurement_running:
return "Please wait 'till a measurement is over"
mac = get_mac(request.remote_addr)
if mac in masters_list:
try:
if pump.turn(request.json['action']):
return "Command succeeded"
else:
app.logger.warning("pump failed to process " + repr(request.json))
return "Command failed"
except:
app.logger.error("an error occured while processing " + repr(request.json))
return "Command failed with an error"
app.logger.info("someone %s tried to manipulate the pump", mac)
return "Permission denied"
@app.route('/pressure_gauge')
def gauge_index():
if temperature_controller.is_realtime_measurement_running:
return "Please wait 'till a measurement is over"
return render_template('gauge.html',
pressure = gauge.pressure)
@app.route('/pressure_gauge/json', methods= ['GET'])
def gauge_json():
return jsonify(pressure = gauge.pressure)
@app.route('/temperature_controller')
def tmpr_index():
if temperature_controller.is_realtime_measurement_running:
return "Please wait 'till a measurement is over"
return render_template('tmpr.html',
master_mind = (get_mac(request.remote_addr) in masters_list),
temperatures = tmpr.temperatures,
output = tmpr.output,
rtm = temperature_controller.is_realtime_measurement_running)
@app.route('/temperature_controller/json', methods= ['GET'])
def tmpr_json():
error = ""
for index in range(2):
if len(tmpr.error_in[index]) > 0:
if len(error) > 0:
error += '\n'
error = tmpr.error_in[index]
if len(tmpr.error_out[index]) > 0:
if len(error) > 0:
error += '\n'
error += tmpr.error_out[index]
pid_data = {1: {}, 2: {}}
for output in [1, 2]:
if 'mode' in tmpr.pid_data[output] and tmpr.pid_data[output]['mode'] != None:
pid_data[output] = tmpr.pid_data[output]
else:
for item in ['input', 'mode', 'powerup_enable', 'range', 'value', 'P', 'I', 'D', 'manual']:
pid_data[output][item] = None
return jsonify(temperatures = tmpr.temperatures,
output = tmpr.output,
pid = pid_data,
error = error,
rtm = temperature_controller.is_realtime_measurement_running)
@app.route('/temperature_controller/temperature/A')
def tmpr_tmpr1():
if tmpr.temperatures[0] != None:
return repr(tmpr.temperatures[0])
else:
return repr(-1)
@app.route('/temperature_controller/temperature/B')
def tmpr_tmpr2():
if tmpr.temperatures[1] != None:
return repr(tmpr.temperatures[1])
else:
return repr(-1)
@app.route('/temperature_controller/pid/do', methods = ['POST'])
def tmpr_do():
if temperature_controller.is_realtime_measurement_running:
return "Please wait 'till a measurement is over"
if get_mac(request.remote_addr) in masters_list:
data = request.json;
if tmpr.pid_turn(data):
return "Command succeeded"
else:
return "Command failed"
return "Permission denied"
@app.route('/jokes', methods = ['GET'])
def joke():
if temperature_controller.is_realtime_measurement_running:
return ""
url = 'http://www.laughfactory.com/joke/loadmorejokes'
proxies = {"http": "{host}:{port}".format(host=config['proxy']['host'], port=config['proxy']['port'])}
auth = requests.auth.HTTPProxyAuth(config['proxy']['username'], config['proxy']['password'])
try:
r = requests.get(url, params=request.args, timeout=1, proxies=proxies, auth=auth)
return r.text
except:
return '''{"jokes":[{"joke_text":"I'm not in the mood of joking :("}]}'''
@app.route('/temperature_controller/rtm/do', methods = ['POST'])
def rtm_tmpr():
if temperature_controller.is_realtime_measurement_running:
return "Please wait 'till a measurement is over"
if get_mac(request.remote_addr) in masters_list:
try:
tmpr_rtm.label = request.json.get('label')
tmpr_rtm.count = int(request.json.get('count'))
except:
tmpr_rtm.letter = ''
tmpr_rtm.count = 0
return "Measurement failed to start"
else:
tmpr_rtm.fire()
return "Measurement started"
app.logger.warning('someone tried to start RTM')
return "Permission denied"
@app.route('/temperature_controller/rtm/json')
def rtm_tmpr_json():
return jsonify(data = tmpr_rtm.res)
@app.route('/temperature_controller/rtm/csv')
def rtm_tmpr_csv():
# print(csv(tmpr_rtm.res))
return Response(csv(tmpr_rtm.res), mimetype="text/plain")
if __name__ == '__main__':
print("Running")
# app.config.update(APPLICATION_ROOT='/')
try:
redirector.start()
app.run(host='0.0.0.0', port=80, threaded=True)
except (KeyboardInterrupt, SystemExit):
print('caught ctrl+c')
except:
redirector.stop()
app.run(host='0.0.0.0', threaded=True)