/
app.py
694 lines (493 loc) · 23.6 KB
/
app.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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
#sys.path.append('/Adafruit_Python_GPIO')
import os
import sys
import cgi, cgitb
# Import SPI library (for hardware SPI) and MCP3008 library.
import lib.Adafruit_GPIO.SPI as SPI
import lib.Adafruit_MCP3008 as MCP
import lib.Adafruit_MAX31855.MAX31855 as MAX31855
import time
import glob
from flask import Flask, render_template, request, json
from flask_socketio import SocketIO, emit
from random import random
from threading import Thread, Event
from sqlalchemy import event, DDL
base_dir = '/sys/bus/w1/devices/'
project_dir = os.path.dirname(os.path.abspath(__file__))
database_file = "sqlite:///{}".format(os.path.join(project_dir,"yachtbraindatabase.db"))
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = database_file
#turn the flask app into a socketio app
socketio = SocketIO(app, async_mode=None, logger=True, engineio_logger=True)
#random number Generator Thread
thread = Thread()
thread_stop_event = Event()
from shared import db
db.init_app(app)
x=0
#import our data models
from models import RPIPins, Sensors, SensorLocations, SensorTypes
# Define a function to convert celsius to fahrenheit.
def c_to_f(c):
return c * 9.0 / 5.0 + 32.0
#used for 1Wire
def read_temp_raw(device_file):
f = open(device_file, 'r')
lines = f.readlines()
f.close()
return lines
#used for 1Wire
def read_temp(sensor_id):
print(sensor_id)
import os.path
if os.path.exists(base_dir + sensor_id):
device_folder = glob.glob(base_dir + sensor_id)[0]
device_file = device_folder + '/w1_slave'
lines = read_temp_raw(device_file)
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw(device_file)
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
data = {"temp_c": round(temp_c), "temp_f": round(temp_f)}
return data
else:
data = {"temp_c": "9999", "temp_f": "9999"}
return data
#used for 1Wire
def read_temp_return_list(sensor_id):
print(sensor_id)
import os.path
if os.path.exists(base_dir + sensor_id):
device_folder = glob.glob(base_dir + sensor_id)[0]
device_file = device_folder + '/w1_slave'
lines = read_temp_raw(device_file)
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw(device_file)
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
data = {"temp_c": round(temp_c), "temp_f": round(temp_f)}
#data = {}
#data.temp_c = round(temp_c)
#data.temp_f = round(temp_f)
return data
else:
#data = {}
#data.temp_c = round(999)
#data.temp_f = round(888)
data = {"temp_c": round(999), "temp_f": round(888)}
return data
def left(s, amount):
return s[:amount]
def right(s, amount):
return s[-amount:]
# - PAGE Functions
@app.route('/')
def index():
print('starting index')
return render_template("index.html")
@app.route('/create_database')
def create_database():
from database_create import insert_initial_values_sensor_locations, insert_initial_values_sensor_types, insert_initial_RPIValues
db.create_all()
insert_initial_values_sensor_locations()
insert_initial_values_sensor_types()
insert_initial_RPIValues()
return render_template("index.html")
@app.route('/sensors', methods=["GET", "POST"])
def sensors():
print('Reading Sensors from DB')
#get all sensors stored in the database
sensors = Sensors.query.order_by(Sensors.title).all()
#print(type(sensors))
print('Load DB Sensors into Array')
#loop through all sensors saved in db and create an array of the sensor id's
sensors_in_database = []
for sensor in sensors:
sensors_in_database.append(sensor.sensor_id)
#if a form is posted we look for changes, and insert, update or delete
if request.form:
print('form was posted')
sensor_db_id = request.form.get("sensor_db_id")
# , sensor_id = request.form.get("sensor_id") - removed this so they cant overwrite it - used for sensor reads
# read values from form
sensor = Sensors(title = request.form.get("title")
, sensor_db_id = request.form.get("sensor_db_id")
, sensor_location = request.form.get("sensor_location")
, sensor_type = request.form.get("sensor_type")
, warning_low = request.form.get("warning_low")
, warning_hi = request.form.get("warning_hi")
, alarm_low = request.form.get("alarm_low")
, alarm_hi = request.form.get("alarm_hi")
, mapping_a_reading = request.form.get("mapping_a_reading")
, mapping_a_value = request.form.get("mapping_a_value")
, mapping_b_reading = request.form.get("mapping_b_reading")
, mapping_b_value = request.form.get("mapping_b_value")
, is_one_wire = request.form.get("is_one_wire")
, is_analog_sensor = request.form.get("is_analog_sensor"))
# if this sensor already exists in the db we update
if sensor_db_id is not '':
#update record
if request.form.get("delete"):
#delete record
Sensors.query.filter_by(sensor_db_id=request.form.get("sensor_db_id")).delete()
db.session.commit()
else:
#update the changes
db.session.merge(sensor)
db.session.commit()
elif request.form.get("sensor_id") not in sensors_in_database:
#its a new one, insert record
db.session.add(sensor)
db.session.commit()
sensors_in_database.append(sensor.sensor_id)
#here we have the normal behavior of the page
#get all the sensors in database
#get all sensors on the bus
#compare the list of each against each other, place the non-assigned sensors at the top of the page maybe?
#Load the sensor locations lookups & types lookups
sensor_locations = SensorLocations.query.order_by(SensorLocations.sensor_location_value).all()
sensor_types = SensorTypes.query.order_by(SensorTypes.sensor_type_value).all()
rpipins = RPIPins.query.order_by(RPIPins.rpipins_id).all()
#Now, sense all 1 Wires and Add them to DB
from lib import OneWireSensors
#get all sensors off the onewire bus
sensor_ids_onewire = OneWireSensors.get_all_onewire_ids()
for sensor_id in sensor_ids_onewire:
if sensor_id not in sensors_in_database:
sensor = Sensors(sensor_id = sensor_id)
#insert record
db.session.add(sensor)
db.session.commit()
#Now, sense any data on the Analog Sensors and Add them to DB
for rpipin in rpipins:
if rpipin.rpipins_type == "Analog" and rpipin.rpipins_clk is not None and rpipin.rpipins_clk != 'None':
BoardNum = rpipin.rpipins_number
CLK = int(rpipin.rpipins_clk)
MISO = int(rpipin.rpipins_miso)
MOSI = int(rpipin.rpipins_mosi)
CS = int(rpipin.rpipins_cs)
mcp = MCP.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)
print('Inspecting Analog for data')
# Read all the ADC channel values in a list.
values = [0]*8
for i in range(8):
print('looping analog')
# The read_adc function will get the value of the specified channel (0-7).
values[i] = mcp.read_adc(i)
voltage = (values[i]*5)/1024.0;
print('voltage' + str(voltage))
if voltage > 0.2:
sensor = Sensors(sensor_id = 'A' + str(i) + '-' + str(BoardNum))
#print('SensorID: ' + sensor)
if sensor.sensor_id not in sensors_in_database:
#insert record
db.session.add(sensor)
db.session.commit()
#Now check for any MAX31855 Sensors
x = 0
for rpipin in rpipins:
if rpipin.rpipins_type == "MAX31855" and rpipin.rpipins_clk is not None and rpipin.rpipins_clk != 'None':
x = x + 1
# Raspberry Pi software SPI configuration.
CLK = int(rpipin.rpipins_clk)
DO = int(rpipin.rpipins_miso)
CS = int(rpipin.rpipins_cs)
maxsensor = MAX31855.MAX31855(CLK, CS, DO)
sensor = Sensors(sensor_id = 'MAX31855-' + str(x))
if sensor.sensor_id not in sensors_in_database:
#insert record
db.session.add(sensor)
db.session.commit()
#example code on reading from sensor
## temp = maxsensor.readTempC()
## internal = maxsensor.readInternalC()
## print('Thermocouple Temperature: {0:0.3F}*C / {1:0.3F}*F'.format(temp, c_to_f(temp)))
## print(' Internal Temperature: {0:0.3F}*C / {1:0.3F}*F'.format(internal, c_to_f(internal)))
#Finished finding all sensors. Reload the Sensors object from the DB to pickup the new changes from above
#pick up the changes before returning to page
sensors = Sensors.query.order_by(Sensors.title).all()
import pprint
pprint.pprint(sensors)
return render_template("sensors.html", sensors = sensors, sensor_locations=sensor_locations,sensor_types=sensor_types)
@app.route('/tables', methods=["GET", "POST"])
def rpipins():
rpipins = RPIPins.query.order_by(RPIPins.rpipins_title).all()
#loop through all sensors saved in db and create an array of the sensor id's
for rpipin in rpipins:
#sensors_in_database.append(sensor.sensor_id)
print('instantiated rpipin')
if request.form:
rpipins_title = str(request.form.get("rpipins_title"))
if rpipins_title != '':
#do the update.
print('updating values')
rpipin = RPIPins(rpipins_title = rpipins_title
, rpipins_id = request.form.get("rpipins_id")
, rpipins_type = request.form.get("rpipins_type")
, rpipins_number = request.form.get("rpipins_number")
, rpipins_clk = request.form.get("rpipins_clk")
, rpipins_cs = request.form.get("rpipins_cs")
, rpipins_miso = request.form.get("rpipins_miso")
, rpipins_mosi = request.form.get("rpipins_mosi"))
print('rpi pin values set')
db.session.merge(rpipin)
db.session.commit()
return render_template("tables.html", rpipins = rpipins)
##import cgi, cgitb
##print "Content-type: text/html\n\n" #for showing print on HTML
##data = cgi.FieldStorage()
##argument = data["webArguments"].value #argument = name of PLC i need to fetch
###some script for connecting to PLC and reading current value of
###variable with name "argument", in this example "aiTemperature"
##print plcVar
#ajax function to retrieve sensor values based on sensor id
@app.route('/getSensorValue', methods=["GET", "POST"])
def getSensorValue():
print('sensor value')
#sensor_id = request.GET['sensor_id']
sensor_id = request.values['sensor_id']
sensor_value = read_temp(sensor_id)
#print(sensor_value)
import json
#data = json.loads(sensor_value)
#print(data)
return json.dumps(sensor_value)
#ajax function to retrieve sensor values based on sensor id
def getSensorValueForSocket(sensor):
print('sensor value')
#sensor_id = request.GET['sensor_id']
#if 'sensor_id' in locals():
#sensor_id = request.values['sensor_id']
return read_temp_return_list(sensor.sensor_id)
#print(sensor_value)
#import json
#data = json.loads(sensor_value)
#print(data)
#return sensor_value
#return json.dumps(sensor_value)
@app.route('/UpdateGauges', methods=['POST'])
def UpdateGauges():
#get all sensors stored in the database
sensors = Sensors.query.order_by(Sensors.title).all()
ScreenText = []
#loop through all sensors saved in db and create an array of the sensor id's
for sensor in sensors:
#Display them all now to screen
if sensor.is_one_wire == 1:
#1 Wire
device_folder = glob.glob(base_dir + '*')[0]
device_file = device_folder + '/w1_slave'
#print(sensor.title + ' : ' + str(read_temp(sensor.sensor_id)) + 'F')
ScreenText.append(str(int(read_temp(sensor.sensor_id))) + '°F')
elif sensor.is_analog_sensor == 1:
#which board is this, and find right pins for it
BoardNum = right(sensor.sensor_id,1)
#now do a lookup from rpipins to find Analog pins for that board
rpipins = RPIPins.query.order_by(RPIPins.rpipins_id).all()
for rpipin in rpipins:
if rpipin.rpipins_type == 'Analog' and rpipin.rpipins_number == str(BoardNum):
# Software SPI configuration:
pCLK = int(rpipin.rpipins_clk)
MISO = int(rpipin.rpipins_miso)
MOSI = int(rpipin.rpipins_mosi)
CS = int(rpipin.rpipins_cs)
mcp = MCP.MCP3008(clk=pCLK, cs=CS, miso=MISO, mosi=MOSI)
# The read_adc function will get the value of the specified channel (0-7).
voltage = mcp.read_adc(int(right(left(sensor.sensor_id,2),1)))
#hook up 5v to first slot to read true 5.0 v
voltage = (voltage*5)/1024.0;
#if voltage > 0.25:
pressure = 0
if voltage > .5:
# example multiplier for 150psi sensor
pressure = voltage * 30
#print(sensor.title + ' : ' + str(pressure) + 'psi');
ScreenText.append(str(pressure) + 'psi')
#need to look up the other sensor settings to determine voltage scale still
# Print the ADC values.
# for 150 psi .5 = 0psi 2.5v=75psi 4.5v=150psi
# for 300 psi .5 = 0psi 2.5v=150psi 4.5v=300psi
elif left(sensor.sensor_id,8) == 'MAX31855':
#which board is this, and find right pins for it
BoardNum = right(sensor.sensor_id,1)
#now do a lookup from rpipins to find Analog pins for that board
rpipins = RPIPins.query.order_by(RPIPins.rpipins_id).all()
for rpipin in rpipins:
if rpipin.rpipins_type == 'MAX31855' and rpipin.rpipins_number == str(BoardNum):
# Raspberry Pi software SPI configuration.
CLK = int(rpipin.rpipins_clk)
DO = int(rpipin.rpipins_miso)
CS = int(rpipin.rpipins_cs)
maxsensor = MAX31855.MAX31855(CLK, CS, DO)
#example code on reading from sensor
temp = maxsensor.readTempC()
internal = maxsensor.readInternalC()
#print(sensor.title + ' Probe Temp: ' + str(c_to_f(temp)))
#print(sensor.title + ' Board Temp: ' + str(c_to_f(internal)))
if temp != temp:
#checking for Nan (not a number)
temp = 0
if internal != internal:
#checking for Nan (not a number)
internal = 0
ScreenText.append(str(int(c_to_f(temp))) + '°F')
ScreenText.append(str(int(c_to_f(internal))) + '°F')
return json.dumps({'GaugeValues':ScreenText})
# return json.dumps({'GaugeValues':ScreenText,'Temp2':str(c_to_f(temp))})
@app.route('/display_twin_engine')
def display_twin_engine():
#get all sensors stored in the database
sensors = Sensors.query.order_by(Sensors.title).all()
sensor_locations = SensorLocations.query.order_by(SensorLocations.sensor_location_value).all()
sensor_types = SensorTypes.query.order_by(SensorTypes.sensor_type_value).all()
rpipins = RPIPins.query.order_by(RPIPins.rpipins_id).all()
return render_template("display_twin_engine.html", sensors=sensors, sensor_types=sensor_types)
@app.route('/display')
def display():
#get all sensors stored in the database
sensors = Sensors.query.order_by(Sensors.title).all()
ScreenText = []
#loop through all sensors saved in db and create an array of the sensor id's
for sensor in sensors:
#Display them all now to screen
if sensor.is_one_wire == 1:
#1 Wire
device_folder = glob.glob(base_dir + '*')[0]
device_file = device_folder + '/w1_slave'
#print(sensor.title + ' : ' + str(read_temp(sensor.sensor_id)) + 'F')
ScreenText.append(sensor.title)
elif sensor.is_analog_sensor == 1:
#which board is this, and find right pins for it
BoardNum = right(sensor.sensor_id,1)
#now do a lookup from rpipins to find Analog pins for that board
rpipins = RPIPins.query.order_by(RPIPins.rpipins_id).all()
for rpipin in rpipins:
if rpipin.rpipins_type == 'Analog' and rpipin.rpipins_number == str(BoardNum):
# Software SPI configuration:
pCLK = int(rpipin.rpipins_clk)
MISO = int(rpipin.rpipins_miso)
MOSI = int(rpipin.rpipins_mosi)
CS = int(rpipin.rpipins_cs)
mcp = MCP.MCP3008(clk=pCLK, cs=CS, miso=MISO, mosi=MOSI)
# The read_adc function will get the value of the specified channel (0-7).
voltage = mcp.read_adc(int(right(left(sensor.sensor_id,2),1)))
#hook up 5v to first slot to read true 5.0 v
voltage = (voltage*5)/1024.0;
#if voltage > 0.25:
pressure = 0
if voltage > .5:
# example multiplier for 150psi sensor
pressure = voltage * 30
#print(sensor.title + ' : ' + str(pressure) + 'psi');
ScreenText.append(sensor.title)
#need to look up the other sensor settings to determine voltage scale still
# Print the ADC values.
# for 150 psi .5 = 0psi 2.5v=75psi 4.5v=150psi
# for 300 psi .5 = 0psi 2.5v=150psi 4.5v=300psi
elif left(sensor.sensor_id,8) == 'MAX31855':
#which board is this, and find right pins for it
BoardNum = right(sensor.sensor_id,1)
#now do a lookup from rpipins to find Analog pins for that board
rpipins = RPIPins.query.order_by(RPIPins.rpipins_id).all()
for rpipin in rpipins:
if rpipin.rpipins_type == 'MAX31855' and rpipin.rpipins_number == str(BoardNum):
# Raspberry Pi software SPI configuration.
CLK = int(rpipin.rpipins_clk)
DO = int(rpipin.rpipins_miso)
CS = int(rpipin.rpipins_cs)
maxsensor = MAX31855.MAX31855(CLK, CS, DO)
#example code on reading from sensor
temp = maxsensor.readTempC()
internal = maxsensor.readInternalC()
#print(sensor.title + ' Probe Temp: ' + str(c_to_f(temp)))
#print(sensor.title + ' Board Temp: ' + str(c_to_f(internal)))
ScreenText.append(sensor.title + ' Probe Temp')
ScreenText.append(sensor.title + ' Board Temp')
return render_template("display.html", ScreenText = ScreenText)
#sockets test script
def sensorReadValueToSocket(sensors):
"""
continually loop through sensors and take readings
push the values to the web socket to update any clients
"""
#print('getting sensors')
# get all the sensors in the database
#with app.app_context():
#sensors = Sensors.query.order_by(Sensors.title).all()
#from pprint import pprint
#type(sensors)
#print('got sensors')
#infinite loop of magical random numbers
#print("checkign sensors")
import json
while not thread_stop_event.isSet():
for i in range(len(sensors)):
#print(type(sensors[i]))
#print(sensors[i].sensor_id)
#print('sensor for')
#sensor_data = sensors[i]
#data = json.dumps(sensors[i])
#sensors[i].sensorValues = getSensorValueForSocket(sensors[i])
#sensor_data.sensorValue = 132
#print(sensors[i].sensor_id)
#print('got endfor sensors')
sensor_json = {
"sensor_id": sensors[i].sensor_id
, "sensor_values": getSensorValueForSocket(sensors[i])
, "sensor_db_id": sensors[i].sensor_db_id
, "title": sensors[i].title
, "sensor_location": sensors[i].sensor_location
, "sensor_type": sensors[i].sensor_type
, "warning_low": sensors[i].warning_low
, "warning_hi": sensors[i].warning_hi
, "alarm_low": sensors[i].alarm_low
, "alarm_hi": sensors[i].alarm_hi
, "mapping_a_reading": sensors[i].mapping_a_reading
, "mapping_a_value": sensors[i].mapping_a_value
, "mapping_b_reading": sensors[i].mapping_b_reading
, "is_one_wire": sensors[i].is_one_wire
, "is_analog_sensor": sensors[i].is_analog_sensor
}
socketio.emit('newnumber', sensor_json, namespace='/test')
#sensor_data.sensorValue = 321
#socketio.emit('newnumber', {'number': sensor_data.sensorValue}, namespace='/test')
socketio.sleep(5)
def randomNumberGenerator():
"""
Generate a random number every 1 second and emit to a socketio instance (broadcast)
Ideally to be run in a separate thread?
"""
#infinite loop of magical random numbers
print("Making random numbers")
with app.app_context():
sensors = Sensors.query.order_by(Sensors.title).all()
print("Mxxxxxs")
while not thread_stop_event.isSet():
number = round(random()*10, 3)
print(number)
socketio.emit('newnumber', {'number': number}, namespace='/test')
socketio.sleep(2)
@socketio.on('connect', namespace='/test')
def test_connect():
# need visibility of the global thread object
global thread
print('Client connected')
#Start the random number generator thread only if the thread has not been started before.
if not thread.isAlive():
print("Starting Thread")
sensors = Sensors.query.order_by(Sensors.title).all()
thread = socketio.start_background_task(sensorReadValueToSocket, sensors)
@socketio.on('disconnect', namespace='/test')
def test_disconnect():
print('Client disconnected')
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0', port=5000)