-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
executable file
·2279 lines (1984 loc) · 83.5 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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# *****************************************
# PiFire Web UI (Flask App)
# *****************************************
#
# Description: This script will start at boot, and start up the web user
# interface.
#
# This script runs as a separate process from the control program
# implementation which handles interfacing and running I2C devices & GPIOs.
#
# *****************************************
from flask import Flask, request, abort, render_template, make_response, send_file, jsonify, redirect
from flask_mobility import Mobility
from flask_socketio import SocketIO
from flask_qrcode import QRcode
from io import BytesIO
from werkzeug.utils import secure_filename
from collections.abc import Mapping
import threading
import zipfile
from threading import Thread
from datetime import timedelta
from datetime import datetime
import time
import os
import json
import datetime
import math
from common import * # Common Library for WebUI and Control Program
from updater import * # Library for doing project updates from GitHub
BACKUPPATH = './backups/' # Path to backups of settings.json, pelletdb.json
UPLOAD_FOLDER = BACKUPPATH # Point uploads to the backup path
ALLOWED_EXTENSIONS = {'json'}
app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="*")
QRcode(app)
Mobility(app)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
@app.route('/')
def index():
global settings
if settings['globals']['first_time_setup']:
return redirect('/wizard/welcome')
else:
return redirect('/dash')
@app.route('/dash')
def dash():
global settings
control = ReadControl()
errors = ReadErrors()
return render_template('dash.html', set_points=control['setpoints'], notify_req=control['notify_req'], probes_enabled=settings['probe_settings']['probes_enabled'], control=control, page_theme=settings['globals']['page_theme'], grill_name=settings['globals']['grill_name'], units=settings['globals']['units'], errors=errors)
@app.route('/dashdata')
def dashdata():
global settings
control = ReadControl()
probes_enabled = settings['probe_settings']['probes_enabled']
cur_probe_temps = []
cur_probe_temps = ReadCurrent()
return jsonify({ 'cur_probe_temps' : cur_probe_temps, 'probes_enabled' : probes_enabled, 'current_mode' : control['mode'], 'set_points' : control['setpoints'], 'notify_req' : control['notify_req'], 'splus' : control['s_plus'], 'splus_default' : settings['smoke_plus']['enabled'] })
@app.route('/hopperlevel')
def hopper_level():
pelletdb = ReadPelletDB()
cur_pellets_string = pelletdb['archive'][pelletdb['current']['pelletid']]['brand'] + ' ' + pelletdb['archive'][pelletdb['current']['pelletid']]['wood']
return jsonify({ 'hopper_level' : pelletdb['current']['hopper_level'], 'cur_pellets' : cur_pellets_string })
@app.route('/timer', methods=['POST','GET'])
def timer():
global settings
control = ReadControl()
if request.method == "GET":
return jsonify({ 'start' : control['timer']['start'], 'paused' : control['timer']['paused'], 'end' : control['timer']['end'], 'shutdown': control['timer']['shutdown']})
elif request.method == "POST":
if 'input' in request.form:
if 'timer_start' == request.form['input']:
control['notify_req']['timer'] = True
# If starting new timer
if control['timer']['paused'] == 0:
now = time.time()
control['timer']['start'] = now
if(('hoursInputRange' in request.form) and ('minsInputRange' in request.form)):
seconds = int(request.form['hoursInputRange']) * 60 * 60
seconds = seconds + int(request.form['minsInputRange']) * 60
control['timer']['end'] = now + seconds
else:
control['timer']['end'] = now + 60
if('shutdownTimer' in request.form):
if(request.form['shutdownTimer'] == 'true'):
control['notify_data']['timer_shutdown'] = True
else:
control['notify_data']['timer_shutdown'] = False
if('keepWarmTimer' in request.form):
if(request.form['keepWarmTimer'] == 'true'):
control['notify_data']['timer_keep_warm'] = True
else:
control['notify_data']['timer_keep_warm'] = False
WriteLog('Timer started. Ends at: ' + epoch_to_time(control['timer']['end']))
WriteControl(control)
else: # If Timer was paused, restart with new end time.
now = time.time()
control['timer']['end'] = (control['timer']['end'] - control['timer']['paused']) + now
control['timer']['paused'] = 0
WriteLog('Timer unpaused. Ends at: ' + epoch_to_time(control['timer']['end']))
WriteControl(control)
elif 'timer_pause' == request.form['input']:
if control['timer']['start'] != 0:
control['notify_req']['timer'] = False
now = time.time()
control['timer']['paused'] = now
WriteLog('Timer paused.')
WriteControl(control)
else:
control['notify_req']['timer'] = False
control['timer']['start'] = 0
control['timer']['end'] = 0
control['timer']['paused'] = 0
control['notify_data']['timer_shutdown'] = False
control['notify_data']['timer_keep_warm'] = False
WriteLog('Timer cleared.')
WriteControl(control)
elif 'timer_stop' == request.form['input']:
control['notify_req']['timer'] = False
control['timer']['start'] = 0
control['timer']['end'] = 0
control['timer']['paused'] = 0
control['notify_data']['timer_shutdown'] = False
control['notify_data']['timer_keep_warm'] = False
WriteLog('Timer stopped.')
WriteControl(control)
return jsonify({'result':'success'})
@app.route('/history/<action>', methods=['POST','GET'])
@app.route('/history', methods=['POST','GET'])
def historypage(action=None):
global settings
control = ReadControl()
if (request.method == 'POST'):
response = request.form
if(action == 'setmins'):
if('minutes' in response):
if(response['minutes'] != ''):
num_items = int(response['minutes']) * 20
settings['history_page']['minutes'] = int(response['minutes'])
WriteSettings(settings)
elif(action == 'clear'):
if('clearhistory' in response):
if(response['clearhistory'] == 'true'):
WriteLog('Clearing History Log.')
ReadHistory(0, flushhistory=True)
elif (request.method == 'GET') and (action == 'export'):
data_list = ReadHistory((settings['history_page']['minutes'] * 20))
exportfilename = "export.csv"
csvfile = open('/tmp/'+exportfilename, "w")
list_length = len(data_list) # Length of list
if(list_length > 0):
# Build Time_List, Settemp_List, Probe_List, cur_probe_temps
writeline = 'Time,Grill Temp,Grill SetTemp,Probe 1 Temp,Probe 1 SetTemp,Probe 2 Temp, Probe 2 SetTemp\n'
csvfile.write(writeline)
last = -1
for index in range(0, list_length):
if (int((index/list_length)*100) > last):
#print('Generating Data: ' + str(int((index/list_length)*100)) + "%")
last = int((index/list_length)*100)
# Convert time data to datetime format
converted_dt = datetime.datetime.fromtimestamp(int(data_list[index][0]) / 1000)
data_list[index][0] = converted_dt.strftime('%Y-%m-%d %H:%M:%S')
writeline = ','.join(data_list[index])
csvfile.write(writeline + '\n')
else:
writeline = 'No Data\n'
csvfile.write(writeline)
csvfile.close()
return send_file('/tmp/'+exportfilename, as_attachment=True, max_age=0)
num_items = settings['history_page']['minutes'] * 20
probes_enabled = settings['probe_settings']['probes_enabled']
data_blob = {}
data_blob = prepare_data(num_items, True, settings['history_page']['datapoints'])
autorefresh = settings['history_page']['autorefresh']
if control['mode'] == 'Stop':
autorefresh = 'off'
return render_template('history.html', control=control, grill_temp_list=data_blob['grill_temp_list'], grill_settemp_list=data_blob['grill_settemp_list'], probe1_temp_list=data_blob['probe1_temp_list'], probe1_settemp_list=data_blob['probe1_settemp_list'], probe2_temp_list=data_blob['probe2_temp_list'], probe2_settemp_list=data_blob['probe2_settemp_list'], label_time_list=data_blob['label_time_list'], probes_enabled=probes_enabled, num_mins=settings['history_page']['minutes'], num_datapoints=settings['history_page']['datapoints'], autorefresh=autorefresh, page_theme=settings['globals']['page_theme'], grill_name=settings['globals']['grill_name'])
@app.route('/historyupdate/<action>', methods=['POST','GET'])
@app.route('/historyupdate')
def historyupdate(action=None):
global settings
if(action == 'stream'):
# GET - Read current temperatures and set points for history streaming
control = ReadControl()
if control['mode'] == 'Stop':
set_temps = [0,0,0]
cur_probe_temps = [0,0,0]
else:
set_temps = control['setpoints']
set_temps[0] = control['setpoints']['grill']
set_temps[1] = control['setpoints']['probe1']
set_temps[2] = control['setpoints']['probe2']
cur_probe_temps = []
cur_probe_temps = ReadCurrent()
return jsonify({ 'probe0_temp' : int(float(cur_probe_temps[0])), 'probe0_settemp' : set_temps[0], 'probe1_temp' : int(float(cur_probe_temps[1])), 'probe1_settemp' : set_temps[1], 'probe2_temp' : int(float(cur_probe_temps[2])), 'probe2_settemp' : set_temps[2]})
elif(action == 'refresh'):
# POST - Get number of minutes into the history to refresh the history chart
requestjson = request.json
if('num_mins' in requestjson):
data_blob = {}
num_items = int(requestjson['num_mins']) * 20 # Calculate number of items requested
data_blob = prepare_data(num_items, True, settings['history_page']['datapoints'])
return jsonify({ 'grill_temp_list' : data_blob['grill_temp_list'], 'grill_settemp_list' : data_blob['grill_settemp_list'], 'probe1_temp_list' : data_blob['probe1_temp_list'], 'probe1_settemp_list' : data_blob['probe1_settemp_list'], 'probe2_temp_list' : data_blob['probe2_temp_list'], 'probe2_settemp_list' : data_blob['probe2_settemp_list'], 'label_time_list' : data_blob['label_time_list'] })
# Legacy Flow - Which may eventually be retired
data_blob = {}
num_items = settings['history_page']['minutes'] * 20
data_blob = prepare_data(num_items, True, settings['history_page']['datapoints'])
for index in range(0, len(data_blob['label_time_list'])):
data_blob['label_time_list'][index] = datetime.datetime.fromtimestamp(int(data_blob['label_time_list'][index]) / 1000).strftime('%H:%M:%S')
return jsonify({ 'grill_temp_list' : data_blob['grill_temp_list'], 'grill_settemp_list' : data_blob['grill_settemp_list'], 'probe1_temp_list' : data_blob['probe1_temp_list'], 'probe1_settemp_list' : data_blob['probe1_settemp_list'], 'probe2_temp_list' : data_blob['probe2_temp_list'], 'probe2_settemp_list' : data_blob['probe2_settemp_list'], 'label_time_list' : data_blob['label_time_list'] })
@app.route('/tuning/<action>', methods=['POST','GET'])
@app.route('/tuning', methods=['POST','GET'])
def tuningpage(action=None):
global settings
control = ReadControl()
if(control['mode'] == 'Stop'):
alert = 'Warning! Grill must be in an active mode to perform tuning (i.e. Monitor Mode, Smoke Mode, Hold Mode, etc.)'
else:
alert = ''
pagectrl = {}
pagectrl['refresh'] = 'off'
pagectrl['selected'] = 'none'
pagectrl['showcalc'] = 'false'
pagectrl['low_trvalue'] = ''
pagectrl['med_trvalue'] = ''
pagectrl['high_trvalue'] = ''
pagectrl['low_tempvalue'] = ''
pagectrl['med_tempvalue'] = ''
pagectrl['high_tempvalue'] = ''
if (request.method == 'POST'):
response = request.form
if('probe_select' in response):
pagectrl['selected'] = response['probe_select']
pagectrl['refresh'] = 'on'
control['tuning_mode'] = True # Enable tuning mode
WriteControl(control)
if(('pause' in response)):
if(response['low_trvalue'] != ''):
pagectrl['low_trvalue'] = response['low_trvalue']
if(response['med_trvalue'] != ''):
pagectrl['med_trvalue'] = response['med_trvalue']
if(response['high_trvalue'] != ''):
pagectrl['high_trvalue'] = response['high_trvalue']
if(response['low_tempvalue'] != ''):
pagectrl['low_tempvalue'] = response['low_tempvalue']
if(response['med_tempvalue'] != ''):
pagectrl['med_tempvalue'] = response['med_tempvalue']
if(response['high_tempvalue'] != ''):
pagectrl['high_tempvalue'] = response['high_tempvalue']
pagectrl['refresh'] = 'off'
control['tuning_mode'] = False # Disable tuning mode while paused
WriteControl(control)
elif(('save' in response)):
if(response['low_trvalue'] != ''):
pagectrl['low_trvalue'] = response['low_trvalue']
if(response['med_trvalue'] != ''):
pagectrl['med_trvalue'] = response['med_trvalue']
if(response['high_trvalue'] != ''):
pagectrl['high_trvalue'] = response['high_trvalue']
if(response['low_tempvalue'] != ''):
pagectrl['low_tempvalue'] = response['low_tempvalue']
if(response['med_tempvalue'] != ''):
pagectrl['med_tempvalue'] = response['med_tempvalue']
if(response['high_tempvalue'] != ''):
pagectrl['high_tempvalue'] = response['high_tempvalue']
if(pagectrl['low_tempvalue'] != '') and (pagectrl['med_tempvalue'] != '') and (pagectrl['high_tempvalue'] != ''):
pagectrl['refresh'] = 'off'
control['tuning_mode'] = False # Disable tuning mode when complete
WriteControl(control)
pagectrl['showcalc'] = 'true'
a, b, c = calc_shh_coefficients(int(pagectrl['low_tempvalue']), int(pagectrl['med_tempvalue']), int(pagectrl['high_tempvalue']), int(pagectrl['low_trvalue']), int(pagectrl['med_trvalue']), int(pagectrl['high_trvalue']))
pagectrl['a'] = a
pagectrl['b'] = b
pagectrl['c'] = c
pagectrl['templist'] = ''
pagectrl['trlist'] = ''
range_size = abs(int(pagectrl['low_trvalue']) - int(pagectrl['high_trvalue']))
range_step = int(range_size / 20)
if(int(pagectrl['low_trvalue']) < int(pagectrl['high_trvalue'])):
low_tr_range = int(int(pagectrl['low_trvalue']) - (range_size * 0.05)) # Add 5% to the resistance at the low temperature side
high_tr_range = int(int(pagectrl['high_trvalue']) + (range_size * 0.05)) # Add 5% to the resistance at the high temperature side
high_tr_range, low_tr_range = low_tr_range, high_tr_range # Swap Tr values for the loop below, so that we start with a low value and go high
# Swapped Value Case (i.e. Low Temp = Low Resistance)
for index in range(high_tr_range, low_tr_range, range_step):
if(index == high_tr_range):
pagectrl['trlist'] = str(index)
pagectrl['templist'] = str(tr_to_temp(index, a, b, c))
else:
pagectrl['trlist'] = str(index) + ', ' + pagectrl['trlist']
pagectrl['templist'] = str(tr_to_temp(index, a, b, c)) + ', ' + pagectrl['templist']
else:
low_tr_range = int(int(pagectrl['low_trvalue']) + (range_size * 0.05)) # Add 5% to the resistance at the low temperature side
high_tr_range = int(int(pagectrl['high_trvalue']) - (range_size * 0.05)) # Add 5% to the resistance at the high temperature side
# Normal Value Case (i.e. Low Temp = High Resistance)
for index in range(high_tr_range, low_tr_range, range_step):
if(index == high_tr_range):
pagectrl['trlist'] = str(index)
pagectrl['templist'] = str(tr_to_temp(index, a, b, c))
else:
pagectrl['trlist'] += ', ' + str(index)
pagectrl['templist'] += ', ' + str(tr_to_temp(index, a, b, c))
else:
pagectrl['refresh'] = 'on'
control['tuning_mode'] = True # Enaable tuning mode
WriteControl(control)
return render_template('tuning.html', control=control, settings=settings, pagectrl=pagectrl, page_theme=settings['globals']['page_theme'], grill_name=settings['globals']['grill_name'], alert=alert)
@app.route('/_grilltr', methods = ['GET'])
def grilltr():
cur_probe_tr = ReadTr()
tr = {}
tr['trohms'] = cur_probe_tr[0]
return json.dumps(tr)
@app.route('/_probe1tr', methods = ['GET'])
def probe1tr():
cur_probe_tr = ReadTr()
tr = {}
tr['trohms'] = cur_probe_tr[1]
return json.dumps(tr)
@app.route('/_probe2tr', methods = ['GET'])
def probe2tr():
cur_probe_tr = ReadTr()
tr = {}
tr['trohms'] = cur_probe_tr[2]
return json.dumps(tr)
@app.route('/events/<action>', methods=['POST','GET'])
@app.route('/events', methods=['POST','GET'])
def eventspage(action=None):
# Show list of logged events and debug event list
event_list, num_events = ReadLog()
global settings
return render_template('events.html', event_list=event_list, num_events=num_events, page_theme=settings['globals']['page_theme'], grill_name=settings['globals']['grill_name'])
@app.route('/pellets/<action>', methods=['POST','GET'])
@app.route('/pellets', methods=['POST','GET'])
def pelletsspage(action=None):
# Pellet Management page
global settings
pelletdb = ReadPelletDB()
event = {}
event = {
'type' : 'none',
'text' : ''
}
if (request.method == 'POST' and action == 'loadprofile'):
response = request.form
if('load_profile' in response):
if(response['load_profile'] == 'true'):
pelletdb['current']['pelletid'] = response['load_id']
# TODO: Implement Hopper Level Check
pelletdb['current']['hopper_level'] = 100
now = str(datetime.datetime.now())
now = now[0:19] # Truncate the microseconds
pelletdb['current']['date_loaded'] = now
pelletdb['log'][now] = response['load_id']
WritePelletDB(pelletdb)
event['type'] = 'updated'
event['text'] = 'Successfully loaded profile and logged.'
elif (request.method == 'GET' and action == 'hopperlevel'):
control = ReadControl()
control['hopper_check'] = True
WriteControl(control)
elif (request.method == 'POST' and action == 'editbrands'):
response = request.form
if('delBrand' in response):
delBrand = response['delBrand']
if(delBrand in pelletdb['brands']):
pelletdb['brands'].remove(delBrand)
WritePelletDB(pelletdb)
event['type'] = 'updated'
event['text'] = delBrand + ' successfully deleted.'
else:
event['type'] = 'error'
event['text'] = delBrand + ' not found in pellet brands.'
elif('newBrand' in response):
newBrand = response['newBrand']
if(newBrand in pelletdb['brands']):
event['type'] = 'error'
event['text'] = newBrand + ' already in pellet brands list.'
else:
pelletdb['brands'].append(newBrand)
WritePelletDB(pelletdb)
event['type'] = 'updated'
event['text'] = newBrand + ' successfully added.'
elif (request.method == 'POST' and action == 'editwoods'):
response = request.form
if('delWood' in response):
delWood = response['delWood']
if(delWood in pelletdb['woods']):
pelletdb['woods'].remove(delWood)
WritePelletDB(pelletdb)
event['type'] = 'updated'
event['text'] = delWood + ' successfully deleted.'
else:
event['type'] = 'error'
event['text'] = delWood + ' not found in pellet wood list.'
elif('newWood' in response):
newWood = response['newWood']
if(newWood in pelletdb['woods']):
event['type'] = 'error'
event['text'] = newWood + ' already in pellet wood list.'
else:
pelletdb['woods'].append(newWood)
WritePelletDB(pelletdb)
event['type'] = 'updated'
event['text'] = newWood + ' successfully added.'
elif (request.method == 'POST' and action == 'addprofile'):
response = request.form
if('addprofile' in response):
profile_id = ''.join(filter(str.isalnum, str(datetime.datetime.now())))
pelletdb['archive'][profile_id] = {
'id' : profile_id,
'brand' : response['brand_name'],
'wood' : response['wood_type'],
'rating' : int(response['rating']),
'comments' : response['comments']
}
event['type'] = 'updated'
event['text'] = 'Successfully added profile to database.'
if(response['addprofile'] == 'add_load'):
pelletdb['current']['pelletid'] = profile_id
# TODO: Implement Hopper Level Check
pelletdb['current']['hopper_level'] = 100
now = str(datetime.datetime.now())
now = now[0:19] # Truncate the microseconds
pelletdb['current']['date_loaded'] = now
pelletdb['log'][now] = profile_id
event['text'] = 'Successfully added profile and loaded.'
WritePelletDB(pelletdb)
elif (request.method == 'POST' and action == 'editprofile'):
response = request.form
if('editprofile' in response):
profile_id = response['editprofile']
pelletdb['archive'][profile_id]['brand'] = response['brand_name']
pelletdb['archive'][profile_id]['wood'] = response['wood_type']
pelletdb['archive'][profile_id]['rating'] = int(response['rating'])
pelletdb['archive'][profile_id]['comments'] = response['comments']
WritePelletDB(pelletdb)
event['type'] = 'updated'
event['text'] = 'Successfully updated ' + response['brand_name'] + ' ' + response['wood_type'] + ' profile in database.'
elif('delete' in response):
profile_id = response['delete']
if(pelletdb['current']['pelletid'] == profile_id):
event['type'] = 'error'
event['text'] = 'Error: ' + response['brand_name'] + ' ' + response['wood_type'] + ' profile cannot be deleted if it is currently loaded.'
else:
pelletdb['archive'].pop(profile_id) # Remove the profile from the archive
for index in pelletdb['log']: # Remove this profile ID for the logs
if(pelletdb['log'][index] == profile_id):
pelletdb['log'][index] = 'deleted'
WritePelletDB(pelletdb)
event['type'] = 'updated'
event['text'] = 'Successfully deleted ' + response['brand_name'] + ' ' + response['wood_type'] + ' profile in database.'
elif (request.method == 'POST' and action == 'deletelog'):
response = request.form
if('delLog' in response):
delLog = response['delLog']
if(delLog in pelletdb['log']):
pelletdb['log'].pop(delLog)
WritePelletDB(pelletdb)
event['type'] = 'updated'
event['text'] = 'Log successfully deleted.'
else:
event['type'] = 'error'
event['text'] = 'Item not found in pellet log.'
return render_template('pellets.html', alert=event, pelletdb=pelletdb, page_theme=settings['globals']['page_theme'], grill_name=settings['globals']['grill_name'])
@app.route('/recipes', methods=['POST','GET'])
def recipespage(action=None):
#print('Recipes Page')
# Show current recipes
# Add a recipe
# Delete a Recipe
# Run a Recipe
global settings
return render_template('recipes.html', page_theme=settings['globals']['page_theme'], grill_name=settings['globals']['grill_name'])
@app.route('/settings/<action>', methods=['POST','GET'])
@app.route('/settings', methods=['POST','GET'])
def settingspage(action=None):
global settings
control = ReadControl()
pelletdb = ReadPelletDB()
event = {}
event = {
'type' : 'none',
'text' : ''
}
if (request.method == 'POST') and (action == 'probes'):
response = request.form
if('grill1enable' in response):
if(response['grill1enable'] == "0"):
settings['probe_settings']['grill_probe_enabled'][0] = 0
else:
settings['probe_settings']['grill_probe_enabled'][0] = 1
if('grill2enable' in response):
if(response['grill2enable'] == "0"):
settings['probe_settings']['grill_probe_enabled'][1] = 0
else:
settings['probe_settings']['grill_probe_enabled'][1] = 1
if('probe1enable' in response):
if(response['probe1enable'] == "0"):
settings['probe_settings']['probes_enabled'][1] = 0
else:
settings['probe_settings']['probes_enabled'][1] = 1
if('probe2enable' in response):
if(response['probe2enable'] == "0"):
settings['probe_settings']['probes_enabled'][2] = 0
else:
settings['probe_settings']['probes_enabled'][2] = 1
if('grill_probes' in response):
if(response['grill_probes'] == 'grill_probe1'):
settings['grill_probe_settings']['grill_probe_enabled'][0] = 1
settings['grill_probe_settings']['grill_probe_enabled'][1] = 0
settings['grill_probe_settings']['grill_probe_enabled'][2] = 0
settings['grill_probe_settings']['grill_probe'] = response['grill_probes']
event['type'] = 'updated'
event['text'] = 'Grill Probe selection updated. Settings saved.'
elif(response['grill_probes'] == 'grill_probe2'):
settings['grill_probe_settings']['grill_probe_enabled'][0] = 0
settings['grill_probe_settings']['grill_probe_enabled'][1] = 1
settings['grill_probe_settings']['grill_probe_enabled'][2] = 0
settings['grill_probe_settings']['grill_probe'] = response['grill_probes']
event['type'] = 'updated'
event['text'] = 'Grill Probe selection updated. Settings saved.'
elif(response['grill_probes'] == 'grill_probe3'):
settings['grill_probe_settings']['grill_probe_enabled'][0] = 0
settings['grill_probe_settings']['grill_probe_enabled'][1] = 0
settings['grill_probe_settings']['grill_probe_enabled'][2] = 1
settings['grill_probe_settings']['grill_probe'] = response['grill_probes']
event['type'] = 'updated'
event['text'] = 'Grill Probe selection updated. Settings saved.'
if('grill_probe1_type' in response):
if(response['grill_probe1_type'] != settings['probe_types']['grill1type']):
settings['probe_types']['grill1type'] = response['grill_probe1_type']
control['probe_profile_update'] = True
event['type'] = 'updated'
event['text'] = 'Probe type updated. Settings saved.'
if('grill_probe2_type' in response):
if(response['grill_probe2_type'] != settings['probe_types']['grill2type']):
settings['probe_types']['grill2type'] = response['grill_probe2_type']
control['probe_profile_update'] = True
event['type'] = 'updated'
event['text'] = 'Probe type updated. Settings saved.'
if('probe1_type' in response):
if(response['probe1_type'] != settings['probe_types']['probe1type']):
settings['probe_types']['probe1type'] = response['probe1_type']
control['probe_profile_update'] = True
event['type'] = 'updated'
event['text'] = 'Probe type updated. Settings saved.'
if('probe2_type' in response):
if(response['probe2_type'] != settings['probe_types']['probe2type']):
settings['probe_types']['probe2type'] = response['probe2_type']
control['probe_profile_update'] = True
event['type'] = 'updated'
event['text'] = 'Probe type updated. Settings saved.'
# Take all settings and write them
WriteSettings(settings)
WriteControl(control)
if (request.method == 'POST') and (action == 'notify'):
response = request.form
if('ifttt_enabled' in response):
if(response['ifttt_enabled'] == 'on'):
settings['ifttt']['enabled'] = True
else:
settings['ifttt']['enabled'] = False
if('pushbullet_enabled' in response):
if(response['pushbullet_enabled'] == 'on'):
settings['pushbullet']['enabled'] = True
else:
settings['pushbullet']['enabled'] = False
if('pushover_enabled' in response):
if(response['pushover_enabled'] == 'on'):
settings['pushover']['enabled'] = True
else:
settings['pushover']['enabled'] = False
if('onesignal_enabled' in response):
if(response['onesignal_enabled'] == 'on'):
settings['onesignal']['enabled'] = True
else:
settings['onesignal']['enabled'] = False
if('iftttapi' in response):
if(response['iftttapi'] == "0") or (response['iftttapi'] == ''):
settings['ifttt']['APIKey'] = ''
else:
settings['ifttt']['APIKey'] = response['iftttapi']
if('pushover_apikey' in response):
if((response['pushover_apikey'] == "0") or (response['pushover_apikey'] == '')) and (settings['pushover']['APIKey'] != ''):
settings['pushover']['APIKey'] = ''
elif(response['pushover_apikey'] != settings['pushover']['APIKey']):
settings['pushover']['APIKey'] = response['pushover_apikey']
if('pushover_userkeys' in response):
if((response['pushover_userkeys'] == "0") or (response['pushover_userkeys'] == '')) and (settings['pushover']['UserKeys'] != ''):
settings['pushover']['UserKeys'] = ''
elif(response['pushover_userkeys'] != settings['pushover']['UserKeys']):
settings['pushover']['UserKeys'] = response['pushover_userkeys']
if('pushover_publicurl' in response):
if((response['pushover_publicurl'] == "0") or (response['pushover_publicurl'] == '')) and (settings['pushover']['PublicURL'] != ''):
settings['pushover']['PublicURL'] = ''
elif(response['pushover_publicurl'] != settings['pushover']['PublicURL']):
settings['pushover']['PublicURL'] = response['pushover_publicurl']
if('pushbullet_apikey' in response):
if((response['pushbullet_apikey'] == "0") or (response['pushbullet_apikey'] == '')) and (settings['pushbullet']['APIKey'] != ''):
settings['pushbullet']['APIKey'] = ''
elif(response['pushbullet_apikey'] != settings['pushbullet']['APIKey']):
settings['pushbullet']['APIKey'] = response['pushbullet_apikey']
if('pushbullet_publicurl' in response):
if((response['pushbullet_publicurl'] == "0") or (response['pushbullet_publicurl'] == '')) and (settings['pushbullet']['PublicURL'] != ''):
settings['pushbullet']['PublicURL'] = ''
elif(response['pushbullet_publicurl'] != settings['pushbullet']['PublicURL']):
settings['pushbullet']['PublicURL'] = response['pushbullet_publicurl']
if 'influxdb_enabled' in response:
settings['influxdb']['enabled'] = response['influxdb_enabled'] == 'on'
if 'influxdb_url' in response:
settings['influxdb']['url'] = response['influxdb_url']
if 'influxdb_token' in response:
settings['influxdb']['token'] = response['influxdb_token']
if 'influxdb_org' in response:
settings['influxdb']['org'] = response['influxdb_org']
if 'influxdb_bucket' in response:
settings['influxdb']['bucket'] = response['influxdb_bucket']
if('delete_device' in response):
DeviceID = response['delete_device']
settings['onesignal']['devices'].pop(DeviceID)
if('edit_device' in response):
if(response['edit_device'] != ''):
DeviceID = response['edit_device']
settings['onesignal']['devices'][DeviceID] = {
'friendly_name' : response['FriendlyName_' + DeviceID],
'device_name' : response['DeviceName_' + DeviceID],
'app_version' : response['AppVersion_' + DeviceID]
}
event['type'] = 'updated'
event['text'] = 'Successfully updated notification settings.'
# Take all settings and write them
WriteSettings(settings)
if (request.method == 'POST') and (action == 'editprofile'):
response = request.form
if('delete' in response):
UniqueID = response['delete'] # Get the string of the UniqueID
try:
settings['probe_settings']['probe_profiles'].pop(UniqueID)
WriteSettings(settings)
event['type'] = 'updated'
event['text'] = 'Successfully removed ' + response['Name_' + UniqueID] + ' profile.'
except:
event['type'] = 'error'
event['text'] = 'Error: Failed to remove ' + response['Name_' + UniqueID] + ' profile.'
if('editprofile' in response):
if(response['editprofile'] != ''):
# Try to convert input values
try:
UniqueID = response['editprofile'] # Get the string of the UniqueID
settings['probe_settings']['probe_profiles'][UniqueID] = {
'Vs' : float(response['Vs_' + UniqueID]),
'Rd' : int(response['Rd_' + UniqueID]),
'A' : float(response['A_' + UniqueID]),
'B' : float(response['B_' + UniqueID]),
'C' : float(response['C_' + UniqueID]),
'name' : response['Name_' + UniqueID]
}
if (response['UniqueID_' + UniqueID] != UniqueID):
# Copy Old Profile to New Profile
settings['probe_settings']['probe_profiles'][response['UniqueID_' + UniqueID]] = settings['probe_settings']['probe_profiles'][UniqueID]
# Remove the Old Profile
settings['probe_settings']['probe_profiles'].pop(UniqueID)
event['type'] = 'updated'
event['text'] = 'Successfully added ' + response['Name_' + UniqueID] + ' profile.'
# Write the new probe profile to disk
WriteSettings(settings)
except:
event['type'] = 'error'
event['text'] = 'Something bad happened when trying to format your inputs. Try again.'
else:
event['type'] = 'error'
event['text'] = 'Error. Profile NOT saved.'
if (request.method == 'POST') and (action == 'addprofile'):
response = request.form
if(response['UniqueID'] != '') and (response['Name'] != '') and (response['Vs'] != '') and (response['Rd'] != '') and (response['A'] != '') and (response['B'] != '') and (response['C'] != ''):
# Try to convert input values
try:
settings['probe_settings']['probe_profiles'][response['UniqueID']] = {
'Vs' : float(response['Vs']),
'Rd' : int(response['Rd']),
'A' : float(response['A']),
'B' : float(response['B']),
'C' : float(response['C']),
'name' : response['Name']
}
event['type'] = 'updated'
event['text'] = 'Successfully added ' + response['Name'] + ' profile.'
# Write the new probe profile to disk
WriteSettings(settings)
except:
event['type'] = 'error'
event['text'] = 'Something bad happened when trying to format your inputs. Try again.'
else:
event['type'] = 'error'
event['text'] = 'All fields must be completed before submitting. Profile NOT saved.'
if (request.method == 'POST') and (action == 'cycle'):
response = request.form
if('pmode' in response):
if(response['pmode'] != ''):
settings['cycle_data']['PMode'] = int(response['pmode'])
if('holdcycletime' in response):
if(response['holdcycletime'] != ''):
settings['cycle_data']['HoldCycleTime'] = int(response['holdcycletime'])
if('smokecycletime' in response):
if(response['smokecycletime'] != ''):
settings['cycle_data']['SmokeCycleTime'] = int(response['smokecycletime'])
if('propband' in response):
if(response['propband'] != ''):
settings['cycle_data']['PB'] = float(response['propband'])
if('integraltime' in response):
if(response['integraltime'] != ''):
settings['cycle_data']['Ti'] = float(response['integraltime'])
if('derivtime' in response):
if(response['derivtime'] != ''):
settings['cycle_data']['Td'] = float(response['derivtime'])
if('u_min' in response):
if(response['u_min'] != ''):
settings['cycle_data']['u_min'] = float(response['u_min'])
if('u_max' in response):
if(response['u_max'] != ''):
settings['cycle_data']['u_max'] = float(response['u_max'])
if('center' in response):
if(response['center'] != ''):
settings['cycle_data']['center'] = float(response['center'])
if('sp_cycle' in response):
if(response['sp_cycle'] != ''):
settings['smoke_plus']['cycle'] = int(response['sp_cycle'])
if('minsptemp' in response):
if(response['minsptemp'] != ''):
settings['smoke_plus']['min_temp'] = int(response['minsptemp'])
if('maxsptemp' in response):
if(response['maxsptemp'] != ''):
settings['smoke_plus']['max_temp'] = int(response['maxsptemp'])
if('defaultsmokeplus' in response):
if(response['defaultsmokeplus'] == 'on'):
settings['smoke_plus']['enabled'] = True
else:
settings['smoke_plus']['enabled'] = False
if('keep_warm_temp' in response):
if(response['keep_warm_temp'] != ''):
settings['keep_warm']['temp'] = int(response['keep_warm_temp'])
if('keep_warm_s_plus' in response):
if(response['keep_warm_s_plus'] == 'on'):
settings['keep_warm']['s_plus'] = True
else:
settings['keep_warm']['s_plus'] = False
event['type'] = 'updated'
event['text'] = 'Successfully updated cycle settings.'
WriteSettings(settings)
if (request.method == 'POST') and (action == 'timers'):
response = request.form
if('shutdown_timer' in response):
if(response['shutdown_timer'] != ''):
settings['globals']['shutdown_timer'] = int(response['shutdown_timer'])
if('startup_timer' in response):
if(response['startup_timer'] != ''):
settings['globals']['startup_timer'] = int(response['startup_timer'])
if('auto_power_off' in response):
if(response['auto_power_off'] == 'on'):
settings['globals']['auto_power_off'] = True
else:
settings['globals']['auto_power_off'] = False
if('smartstart_enable' in response):
if(response['smartstart_enable'] == 'on'):
settings['smartstart']['enabled'] = True
else:
settings['smartstart']['enabled'] = False
event['type'] = 'updated'
event['text'] = 'Successfully updated startup/shutdown settings.'
WriteSettings(settings)
if (request.method == 'POST') and (action == 'history'):
response = request.form
if('historymins' in response):
if(response['historymins'] != ''):
settings['history_page']['minutes'] = int(response['historymins'])
if('clearhistorystartup' in response):
if(response['clearhistorystartup'] == 'on'):
settings['history_page']['clearhistoryonstart'] = True
else:
settings['history_page']['clearhistoryonstart'] = False
if('historyautorefresh' in response):
if(response['historyautorefresh'] == 'on'):
settings['history_page']['autorefresh'] = 'on'
else:
settings['history_page']['autorefresh'] = 'off'
if('datapoints' in response):
if(response['datapoints'] != ''):
settings['history_page']['datapoints'] = int(response['datapoints'])
event['type'] = 'updated'
event['text'] = 'Successfully updated history settings.'
WriteSettings(settings)
if (request.method == 'POST') and (action == 'pagesettings'):
response = request.form
if('darkmode' in response):
if(response['darkmode'] == 'on'):
settings['globals']['page_theme'] = 'dark'
else:
settings['globals']['page_theme'] = 'light'
event['type'] = 'updated'
event['text'] = 'Successfully updated page settings.'
WriteSettings(settings)
if (request.method == 'POST') and (action == 'safety'):
response = request.form
if('minstartuptemp' in response):
if(response['minstartuptemp'] != ''):
settings['safety']['minstartuptemp'] = int(response['minstartuptemp'])
if('maxstartuptemp' in response):
if(response['maxstartuptemp'] != ''):
settings['safety']['maxstartuptemp'] = int(response['maxstartuptemp'])
if('reigniteretries' in response):
if(response['reigniteretries'] != ''):
settings['safety']['reigniteretries'] = int(response['reigniteretries'])
if('maxtemp' in response):
if(response['maxtemp'] != ''):
settings['safety']['maxtemp'] = int(response['maxtemp'])
event['type'] = 'updated'
event['text'] = 'Successfully updated safety settings.'
WriteSettings(settings)
if (request.method == 'POST') and (action == 'grillname'):
response = request.form
if('grill_name' in response):
settings['globals']['grill_name'] = response['grill_name']
event['type'] = 'updated'
event['text'] = 'Successfully updated grill name.'
WriteSettings(settings)
if (request.method == 'POST') and (action == 'pellets'):
response = request.form
if('pelletwarning' in response):
if('pelletwarning' == 'on'):
settings['pelletlevel']['warning_enabled'] = True
else:
settings['pelletlevel']['warning_enabled'] = False
if('warninglevel' in response):
settings['pelletlevel']['warning_level'] = int(response['warninglevel'])
if('empty' in response):
settings['pelletlevel']['empty'] = int(response['empty'])
if('full' in response):
settings['pelletlevel']['full'] = int(response['full'])
event['type'] = 'updated'
event['text'] = 'Successfully updated pellet settings.'
WritePelletDB(pelletdb)
if (request.method == 'POST') and (action == 'units'):
response = request.form
if('units' in response):
if(response['units'] == 'C') and (settings['globals']['units'] == 'F'):
settings = convert_settings_units('C', settings)
WriteSettings(settings)
event['type'] = 'updated'
event['text'] = 'Successfully updated units to Celsius.'
control = ReadControl()
control['updated'] = True
control['units_change'] = True
WriteControl(control)