-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
app.py
executable file
·4042 lines (3616 loc) · 158 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
'''
==============================================================================
PiFire Web UI (Flask App) Process
==============================================================================
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.
==============================================================================
'''
'''
==============================================================================
Imported Modules
==============================================================================
'''
from flask import Flask, request, abort, render_template, make_response, send_file, jsonify, redirect, render_template_string
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
import pathlib
from threading import Thread
from datetime import datetime
from updater import * # Library for doing project updates from GitHub
from file_mgmt.common import fixup_assets, read_json_file_data, update_json_file_data, remove_assets
from file_mgmt.cookfile import read_cookfile, upgrade_cookfile, prepare_chartdata
from file_mgmt.media import add_asset, set_thumbnail, unpack_thumb
from file_mgmt.recipes import read_recipefile, create_recipefile
'''
==============================================================================
Constants & Globals
==============================================================================
'''
BACKUP_PATH = './backups/' # Path to backups of settings.json, pelletdb.json
UPLOAD_FOLDER = BACKUP_PATH # Point uploads to the backup path
HISTORY_FOLDER = './history/' # Path to historical cook files
RECIPE_FOLDER = './recipes/' # Path to recipe files
LOGS_FOLDER = './logs/' # Path to log files
ALLOWED_EXTENSIONS = {'json', 'pifire', 'pfrecipe', 'jpg', 'jpeg', 'png', 'gif', 'bmp', 'log'}
server_status = 'available'
app = Flask(__name__)
socketio = SocketIO(app, cors_allowed_origins="*")
QRcode(app)
Mobility(app)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['HISTORY_FOLDER'] = HISTORY_FOLDER
app.config['RECIPE_FOLDER'] = RECIPE_FOLDER
'''
==============================================================================
App Routes
==============================================================================
'''
@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 = read_control()
errors = read_errors()
warnings = read_warnings()
current = settings['dashboard']['current']
dash_template = settings['dashboard']['dashboards'][current].get('html_name', 'dash_default.html')
dash_data = settings['dashboard']['dashboards'].get(current, {})
''' Check if control process is up and running. '''
process_command(action='sys', arglist=['check_alive'], origin='dash') # Request supported commands
data = _get_system_command_output(requested='check_alive')
if data['result'] != 'OK':
errors.append('The control process did not respond to a request and may be stopped. Try reloading the page or restarting the system. Check logs for details.')
return render_template(dash_template,
settings=settings,
control=control,
dash_data=dash_data,
errors=errors,
warnings=warnings,
page_theme=settings['globals']['page_theme'],
grill_name=settings['globals']['grill_name'])
@app.route('/dashconfig', methods=['POST','GET'])
def dash_config():
global settings
current = settings['dashboard']['current']
dash_data = settings['dashboard']['dashboards'].get(current, {})
meta_data_filename = dash_data.get('metadata', None)
dash_metadata = read_generic_json(f'./dashboard/{meta_data_filename}')
if request.method == 'GET':
render_string = "{% from '_macro_generic_config.html' import render_dash_config_card %}{{ render_dash_config_card(dash_metadata, dash_data) }}"
return render_template_string(render_string, dash_metadata=dash_metadata, dash_data=dash_data)
elif request.method == 'POST':
dash_config_request = request.form
for key, value in dash_config_request.items():
if 'dashConfig_' in key:
dash_data['config'][key.replace('dashConfig_','')] = value
settings['dashboard']['dashboards'][current]['config'] = dash_data['config']
write_settings(settings)
return redirect('/dash')
return 'Bad Request'
@app.route('/hopperlevel')
def hopper_level():
pelletdb = read_pellet_db()
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 })
'''
This route will be deprecated in an upcoming release and has been replaced with the API calls /api/[get,set]/timer
'''
@app.route('/timer', methods=['POST','GET'])
def timer():
global settings
control = read_control()
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:
for index, notify_obj in enumerate(control['notify_data']):
if notify_obj['type'] == 'timer':
break
if 'timer_start' == request.form['input']:
control['notify_data'][index]['req'] = 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'][index]['shutdown'] = True
else:
control['notify_data'][index]['shutdown'] = False
if 'keepWarmTimer' in request.form:
if request.form['keepWarmTimer'] == 'true':
control['notify_data'][index]['keep_warm'] = True
else:
control['notify_data'][index]['keep_warm'] = False
write_log('Timer started. Ends at: ' + epoch_to_time(control['timer']['end']))
write_control(control, origin='app')
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
write_log('Timer unpaused. Ends at: ' + epoch_to_time(control['timer']['end']))
write_control(control, origin='app')
elif 'timer_pause' == request.form['input']:
if control['timer']['start'] != 0:
control['notify_data'][index]['req'] = False
now = time.time()
control['timer']['paused'] = now
write_log('Timer paused.')
write_control(control, origin='app')
else:
control['notify_data'][index]['req'] = False
control['timer']['start'] = 0
control['timer']['end'] = 0
control['timer']['paused'] = 0
control['notify_data'][index]['shutdown'] = False
control['notify_data'][index]['keep_warm'] = False
write_log('Timer cleared.')
write_control(control, origin='app')
elif 'timer_stop' == request.form['input']:
control['notify_data'][index]['req'] = False
control['timer']['start'] = 0
control['timer']['end'] = 0
control['notify_data'][index]['shutdown'] = False
control['notify_data'][index]['keep_warm'] = False
write_log('Timer stopped.')
write_control(control, origin='app')
return jsonify({'result':'success'})
@app.route('/history/<action>', methods=['POST','GET'])
@app.route('/history', methods=['POST','GET'])
def history_page(action=None):
global settings
control = read_control()
errors = []
if request.method == 'POST':
response = request.form
if(action == 'cookfile'):
if('delcookfile' in response):
filename = './history/' + response["delcookfile"]
os.remove(filename)
return redirect('/history')
if('opencookfile' in response):
cookfilename = HISTORY_FOLDER + response['opencookfile']
cookfilestruct, status = read_cookfile(cookfilename)
if(status == 'OK'):
events = cookfilestruct['events']
event_totals = _prepare_event_totals(events)
comments = cookfilestruct['comments']
for comment in comments:
comment['text'] = comment['text'].replace('\n', '<br>')
metadata = cookfilestruct['metadata']
metadata['starttime'] = epoch_to_time(metadata['starttime'] / 1000)
metadata['endtime'] = epoch_to_time(metadata['endtime'] / 1000)
labels = cookfilestruct['graph_labels']
assets = cookfilestruct['assets']
filenameonly = response['opencookfile']
return render_template('cookfile.html', settings=settings, cookfilename=cookfilename,
filenameonly=filenameonly, events=events, event_totals=event_totals, comments=comments,
metadata=metadata, labels=labels, assets=assets, errors=errors,
page_theme=settings['globals']['page_theme'], grill_name=settings['globals']['grill_name'])
else:
errors.append(status)
if 'version' in status:
errortype = 'version'
elif 'asset' in status:
errortype = 'asset'
else:
errortype = 'other'
return render_template('cferror.html', settings=settings, cookfilename=cookfilename, errortype=errortype, errors=errors, page_theme=settings['globals']['page_theme'], grill_name=settings['globals']['grill_name'])
if('dlcookfile' in response):
filename = './history/' + response['dlcookfile']
return send_file(filename, as_attachment=True, max_age=0)
if(action == 'setmins'):
if('minutes' in response):
if(response['minutes'] != ''):
num_items = int(response['minutes']) * 20
settings['history_page']['minutes'] = int(response['minutes'])
write_settings(settings)
elif (request.method == 'GET') and (action == 'export'):
exportfilename = prepare_csv()
return send_file(exportfilename, as_attachment=True, max_age=0)
return render_template('history.html',
control=control, settings=settings,
page_theme=settings['globals']['page_theme'],
grill_name=settings['globals']['grill_name'])
@app.route('/historyupdate/<action>', methods=['POST','GET'])
@app.route('/historyupdate')
def history_update(action=None):
global settings
if action == 'stream':
# GET - Read current temperatures and set points for history streaming
control = read_control()
json_response = {}
if control['mode'] in ['Stop', 'Error']:
json_response['current'] = read_current(zero_out=True) # Probe Temps Zero'd Out
else:
json_response['current'] = read_current() # Probe Temps Zero'd Out
# Calculate Displayed Start Time
displayed_starttime = time.time() - (settings['history_page']['minutes'] * 20)
json_response['annotations'] = _prepare_annotations(displayed_starttime)
json_response['mode'] = control['mode']
json_response['ui_hash'] = create_ui_hash()
json_response['timestamp'] = int(time.time() * 1000)
return jsonify(json_response)
elif action == 'refresh':
# POST - Get number of minutes into the history to refresh the history chart
control = read_control()
request_json = request.json
if 'num_mins' in request_json:
num_items = int(request_json['num_mins']) * 20 if int(request_json['num_mins']) > 0 else 20 # Calculate number of items requested
settings['history_page']['minutes'] = int(request_json['num_mins']) if int(request_json['num_mins']) > 0 else 1
write_settings(settings)
elif 'zoom' in request_json:
num_items = int(request_json['zoom']) * 20
else:
num_items = int(settings['history_page']['minutes'] * 20)
# Get Chart Data Structures
json_response = prepare_chartdata(settings['history_page']['probe_config'], num_items=num_items, reduce=True, data_points=settings['history_page']['datapoints'])
json_response['ui_hash'] = create_ui_hash()
# Calculate Displayed Start Time
displayed_starttime = time.time() - (int(num_items / 20) * 60)
json_response['annotations'] = _prepare_annotations(displayed_starttime)
'''
json_response = {
'annotations' : [],
'time_labels' : time_labels,
'probe_mapper' : probe_mapper,
'chart_data' : chart_data
}
'''
return jsonify(json_response)
return jsonify({'status' : 'ERROR'})
@app.route('/cookfiledata', methods=['POST', 'GET'])
def cookfiledata(action=None):
global settings
errors = []
if(request.method == 'POST') and ('json' in request.content_type):
requestjson = request.json
if('full_graph' in requestjson):
filename = requestjson['filename']
cookfiledata, status = read_cookfile(filename)
if(status == 'OK'):
annotations = _prepare_annotations(0, cookfiledata['events'])
json_data = {
'chart_data' : cookfiledata['graph_data']['chart_data'],
'time_labels' : cookfiledata['graph_data']['time_labels'],
'probe_mapper' : cookfiledata['graph_data']['probe_mapper'],
'annotations' : annotations
}
return jsonify(json_data)
if('getcommentassets' in requestjson):
assetlist = []
cookfilename = requestjson['cookfilename']
commentid = requestjson['commentid']
comments, status = read_json_file_data(cookfilename, 'comments')
for comment in comments:
if comment['id'] == commentid:
assetlist = comment['assets']
break
return jsonify({'result' : 'OK', 'assetlist' : assetlist})
if('managemediacomment' in requestjson):
# Grab list of all assets in file, build assetlist
assetlist = []
cookfilename = requestjson['cookfilename']
commentid = requestjson['commentid']
assets, status = read_json_file_data(cookfilename, 'assets')
metadata, status = read_json_file_data(cookfilename, 'metadata')
for asset in assets:
asset_object = {
'assetname' : asset['filename'],
'assetid' : asset['id'],
'selected' : False
}
assetlist.append(asset_object)
# Grab list of selected assets in comment currently
selectedassets = []
comments, status = read_json_file_data(cookfilename, 'comments')
for comment in comments:
if comment['id'] == commentid:
selectedassets = comment['assets']
break
# For each item in asset list, if in comment, mark selected
for object in assetlist:
if object['assetname'] in selectedassets:
object['selected'] = True
return jsonify({'result' : 'OK', 'assetlist' : assetlist})
if('getallmedia' in requestjson):
# Grab list of all assets in file, build assetlist
assetlist = []
cookfilename = requestjson['cookfilename']
assets, status = read_json_file_data(cookfilename, 'assets')
for asset in assets:
asset_object = {
'assetname' : asset['filename'],
'assetid' : asset['id'],
}
assetlist.append(asset_object)
return jsonify({'result' : 'OK', 'assetlist' : assetlist})
if('navimage' in requestjson):
direction = requestjson['navimage']
mediafilename = requestjson['mediafilename']
commentid = requestjson['commentid']
cookfilename = requestjson['cookfilename']
comments, status = read_json_file_data(cookfilename, 'comments')
if status == 'OK':
assetlist = []
for comment in comments:
if comment['id'] == commentid:
assetlist = comment['assets']
break
current = 0
found = False
for index in range(0, len(assetlist)):
if assetlist[index] == mediafilename:
current = index
found = True
break
if found and direction == 'next':
if current == len(assetlist)-1:
mediafilename = assetlist[0]
else:
mediafilename = assetlist[current+1]
return jsonify({'result' : 'OK', 'mediafilename' : mediafilename})
elif found and direction == 'prev':
if current == 0:
mediafilename = assetlist[-1]
else:
mediafilename = assetlist[current-1]
return jsonify({'result' : 'OK', 'mediafilename' : mediafilename})
errors.append('Something unexpected has happened.')
return jsonify({'result' : 'ERROR', 'errors' : errors})
if(request.method == 'POST') and ('form' in request.content_type):
requestform = request.form
if('dl_cookfile' in requestform):
# Download the full JSON Cook File Locally
filename = requestform['dl_cookfile']
return send_file(filename, as_attachment=True, max_age=0)
if('dl_eventfile' in requestform):
filename = requestform['dl_eventfile']
cookfiledata, status = read_json_file_data(filename, 'events')
if(status == 'OK'):
csvfilename = _prepare_metrics_csv(cookfiledata, filename)
return send_file(csvfilename, as_attachment=True, max_age=0)
if('dl_graphfile' in requestform):
# Download CSV of the raw temperature data (and extended data)
filename = requestform['dl_graphfile']
cookfiledata, status = read_cookfile(filename)
if(status == 'OK'):
csvfilename = prepare_csv(cookfiledata['raw_data'], filename)
return send_file(csvfilename, as_attachment=True, max_age=0)
if('ulcookfilereq' in requestform):
# Assume we have request.files and localfile in response
remotefile = request.files['ulcookfile']
if (remotefile.filename != ''):
# If the user does not select a file, the browser submits an
# empty file without a filename.
if remotefile and _allowed_file(remotefile.filename):
filename = secure_filename(remotefile.filename)
remotefile.save(os.path.join(app.config['HISTORY_FOLDER'], filename))
else:
errors.append('Disallowed File Upload.')
return redirect('/history')
if('thumbSelected' in requestform):
thumbnail = requestform['thumbSelected']
filename = requestform['filename']
# Reload Cook File
cookfilename = HISTORY_FOLDER + filename
cookfilestruct, status = read_cookfile(cookfilename)
if status=='OK':
cookfilestruct['metadata']['thumbnail'] = thumbnail
update_json_file_data(cookfilestruct['metadata'], HISTORY_FOLDER + filename, 'metadata')
events = cookfilestruct['events']
event_totals = _prepare_event_totals(events)
comments = cookfilestruct['comments']
for comment in comments:
comment['text'] = comment['text'].replace('\n', '<br>')
metadata = cookfilestruct['metadata']
metadata['starttime'] = epoch_to_time(metadata['starttime'] / 1000)
metadata['endtime'] = epoch_to_time(metadata['endtime'] / 1000)
labels = cookfilestruct['graph_labels']
assets = cookfilestruct['assets']
return render_template('cookfile.html', settings=settings, \
cookfilename=cookfilename, filenameonly=filename, \
events=events, event_totals=event_totals, \
comments=comments, metadata=metadata, labels=labels, \
assets=assets, errors=errors, \
page_theme=settings['globals']['page_theme'], \
grill_name=settings['globals']['grill_name'])
if('ulmediafn' in requestform) or ('ulthumbfn' in requestform):
# Assume we have request.files and localfile in response
if 'ulmediafn' in requestform:
#uploadedfile = request.files['ulmedia']
uploadedfiles = request.files.getlist('ulmedia')
cookfilename = HISTORY_FOLDER + requestform['ulmediafn']
filenameonly = requestform['ulmediafn']
else:
uploadedfile = request.files['ulthumbnail']
cookfilename = HISTORY_FOLDER + requestform['ulthumbfn']
filenameonly = requestform['ulthumbfn']
uploadedfiles = [uploadedfile]
status = 'ERROR'
for remotefile in uploadedfiles:
if (remotefile.filename != ''):
# Reload Cook File
cookfilestruct, status = read_cookfile(cookfilename)
parent_id = cookfilestruct['metadata']['id']
tmp_path = f'/tmp/pifire/{parent_id}'
if not os.path.exists(tmp_path):
os.mkdir(tmp_path)
if remotefile and _allowed_file(remotefile.filename):
filename = secure_filename(remotefile.filename)
pathfile = os.path.join(tmp_path, filename)
remotefile.save(pathfile)
asset_id, asset_filetype = add_asset(cookfilename, tmp_path, filename)
if 'ulthumbfn' in requestform:
set_thumbnail(cookfilename, f'{asset_id}.{asset_filetype}')
# Reload all of the data
cookfilestruct, status = read_cookfile(cookfilename)
else:
errors.append('Disallowed File Upload.')
if(status == 'OK'):
events = cookfilestruct['events']
event_totals = _prepare_event_totals(events)
comments = cookfilestruct['comments']
for comment in comments:
comment['text'] = comment['text'].replace('\n', '<br>')
metadata = cookfilestruct['metadata']
metadata['starttime'] = epoch_to_time(metadata['starttime'] / 1000)
metadata['endtime'] = epoch_to_time(metadata['endtime'] / 1000)
labels = cookfilestruct['graph_labels']
assets = cookfilestruct['assets']
return render_template('cookfile.html', settings=settings, \
cookfilename=cookfilename, filenameonly=filenameonly, \
events=events, event_totals=event_totals, \
comments=comments, metadata=metadata, labels=labels, \
assets=assets, errors=errors, \
page_theme=settings['globals']['page_theme'], \
grill_name=settings['globals']['grill_name'])
if('cookfilelist' in requestform):
page = int(requestform['page'])
reverse = True if requestform['reverse'] == 'true' else False
itemsperpage = int(requestform['itemsperpage'])
filelist = _get_cookfilelist()
cookfilelist = []
for filename in filelist:
cookfilelist.append({'filename' : filename, 'title' : '', 'thumbnail' : ''})
paginated_cookfile = _paginate_list(cookfilelist, 'filename', reverse, itemsperpage, page)
paginated_cookfile['displaydata'] = _get_cookfilelist_details(paginated_cookfile['displaydata'])
return render_template('_cookfile_list.html', pgntdcf = paginated_cookfile)
if('repairCF' in requestform):
cookfilename = requestform['repairCF']
filenameonly = requestform['repairCF'].replace(HISTORY_FOLDER, '')
cookfilestruct, status = upgrade_cookfile(cookfilename, repair=True)
if status != 'OK':
errors.append(status)
if 'version' in status:
errortype = 'version'
elif 'asset' in status:
errortype = 'asset'
else:
errortype = 'other'
errors.append('Repair Failed.')
return render_template('cferror.html', settings=settings, \
cookfilename=cookfilename, errortype=errortype, \
errors=errors, page_theme=settings['globals']['page_theme'], \
grill_name=settings['globals']['grill_name'])
# Fix issues with assets
cookfilestruct, status = read_cookfile(cookfilename)
cookfilestruct, status = fixup_assets(cookfilename, cookfilestruct)
if status != 'OK':
errors.append(status)
if 'version' in status:
errortype = 'version'
elif 'asset' in status:
errortype = 'asset'
else:
errortype = 'other'
errors.append('Repair Failed.')
return render_template('cferror.html', settings=settings, \
cookfilename=cookfilename, errortype=errortype, \
errors=errors, page_theme=settings['globals']['page_theme'], \
grill_name=settings['globals']['grill_name'])
else:
events = cookfilestruct['events']
event_totals = _prepare_event_totals(events)
comments = cookfilestruct['comments']
for comment in comments:
comment['text'] = comment['text'].replace('\n', '<br>')
metadata = cookfilestruct['metadata']
metadata['starttime'] = epoch_to_time(metadata['starttime'] / 1000)
metadata['endtime'] = epoch_to_time(metadata['endtime'] / 1000)
labels = cookfilestruct['graph_labels']
assets = cookfilestruct['assets']
return render_template('cookfile.html', settings=settings, \
cookfilename=cookfilename, filenameonly=filenameonly, \
events=events, event_totals=event_totals, \
comments=comments, metadata=metadata, labels=labels, \
assets=assets, errors=errors, \
page_theme=settings['globals']['page_theme'], \
grill_name=settings['globals']['grill_name'])
if('upgradeCF' in requestform):
cookfilename = requestform['upgradeCF']
filenameonly = requestform['upgradeCF'].replace(HISTORY_FOLDER, '')
cookfilestruct, status = upgrade_cookfile(cookfilename)
if status != 'OK':
errors.append(status)
if 'version' in status:
errortype = 'version'
elif 'asset' in status:
errortype = 'asset'
else:
errortype = 'other'
return render_template('cferror.html', settings=settings, \
cookfilename=cookfilename, errortype=errortype, \
errors=errors, page_theme=settings['globals']['page_theme'], \
grill_name=settings['globals']['grill_name'])
else:
events = cookfilestruct['events']
event_totals = _prepare_event_totals(events)
comments = cookfilestruct['comments']
for comment in comments:
comment['text'] = comment['text'].replace('\n', '<br>')
metadata = cookfilestruct['metadata']
metadata['starttime'] = epoch_to_time(metadata['starttime'] / 1000)
metadata['endtime'] = epoch_to_time(metadata['endtime'] / 1000)
labels = cookfilestruct['graph_labels']
assets = cookfilestruct['assets']
return render_template('cookfile.html', settings=settings, \
cookfilename=cookfilename, filenameonly=filenameonly, \
events=events, event_totals=event_totals, \
comments=comments, metadata=metadata, labels=labels, \
assets=assets, errors=errors, \
page_theme=settings['globals']['page_theme'], \
grill_name=settings['globals']['grill_name'])
if('delmedialist' in requestform):
cookfilename = HISTORY_FOLDER + requestform['delmedialist']
filenameonly = requestform['delmedialist']
assetlist = requestform['delAssetlist'].split(',') if requestform['delAssetlist'] != '' else []
status = remove_assets(cookfilename, assetlist)
cookfilestruct, status = read_cookfile(cookfilename)
if status != 'OK':
errors.append(status)
if 'version' in status:
errortype = 'version'
elif 'asset' in status:
errortype = 'asset'
else:
errortype = 'other'
return render_template('cferror.html', settings=settings, \
cookfilename=cookfilename, errortype=errortype, \
errors=errors, page_theme=settings['globals']['page_theme'], \
grill_name=settings['globals']['grill_name'])
else:
events = cookfilestruct['events']
event_totals = _prepare_event_totals(events)
comments = cookfilestruct['comments']
for comment in comments:
comment['text'] = comment['text'].replace('\n', '<br>')
metadata = cookfilestruct['metadata']
metadata['starttime'] = epoch_to_time(metadata['starttime'] / 1000)
metadata['endtime'] = epoch_to_time(metadata['endtime'] / 1000)
labels = cookfilestruct['graph_labels']
assets = cookfilestruct['assets']
return render_template('cookfile.html', settings=settings, \
cookfilename=cookfilename, filenameonly=filenameonly, \
events=events, event_totals=event_totals, \
comments=comments, metadata=metadata, labels=labels, \
assets=assets, errors=errors, \
page_theme=settings['globals']['page_theme'], \
grill_name=settings['globals']['grill_name'])
errors.append('Something unexpected has happened.')
return jsonify({'result' : 'ERROR', 'errors' : errors})
@app.route('/updatecookfile', methods=['POST','GET'])
def updatecookdata(action=None):
global settings
if(request.method == 'POST'):
requestjson = request.json
if('comments' in requestjson):
filename = requestjson['filename']
cookfiledata, status = read_json_file_data(filename, 'comments')
if('commentnew' in requestjson):
now = datetime.datetime.now()
comment_struct = {}
comment_struct['text'] = requestjson['commentnew']
comment_struct['id'] = generate_uuid()
comment_struct['edited'] = ''
comment_struct['date'] = now.strftime('%Y-%m-%d')
comment_struct['time'] = now.strftime('%H:%M')
comment_struct['assets'] = []
cookfiledata.append(comment_struct)
result = update_json_file_data(cookfiledata, filename, 'comments')
if(result == 'OK'):
return jsonify({'result' : 'OK', 'newcommentid' : comment_struct['id'], 'newcommentdt': comment_struct['date'] + ' ' + comment_struct['time']})
if('delcomment' in requestjson):
for item in cookfiledata:
if item['id'] == requestjson['delcomment']:
cookfiledata.remove(item)
result = update_json_file_data(cookfiledata, filename, 'comments')
if(result == 'OK'):
return jsonify({'result' : 'OK'})
if('editcomment' in requestjson):
for item in cookfiledata:
if item['id'] == requestjson['editcomment']:
return jsonify({'result' : 'OK', 'text' : item['text']})
if('savecomment' in requestjson):
for item in cookfiledata:
if item['id'] == requestjson['savecomment']:
now = datetime.datetime.now()
item['text'] = requestjson['text']
item['edited'] = now.strftime('%Y-%m-%d %H:%M')
result = update_json_file_data(cookfiledata, filename, 'comments')
if(result == 'OK'):
return jsonify({'result' : 'OK', 'text' : item['text'].replace('\n', '<br>'), 'edited' : item['edited'], 'datetime' : item['date'] + ' ' + item['time']})
if('metadata' in requestjson):
filename = requestjson['filename']
cookfiledata, status = read_json_file_data(filename, 'metadata')
if(status == 'OK'):
if('editTitle' in requestjson):
cookfiledata['title'] = requestjson['editTitle']
result = update_json_file_data(cookfiledata, filename, 'metadata')
if(result == 'OK'):
return jsonify({'result' : 'OK'})
else:
return jsonify({'result' : 'ERROR'})
if('graph_labels' in requestjson):
filename = requestjson['filename']
''' Update graph_labels.json '''
cookfiledata, result = read_json_file_data(filename, 'graph_labels')
if(result != 'OK'):
return jsonify({'result' : 'ERROR'})
old_label = requestjson['old_label']
new_label = requestjson['new_label']
new_label_safe = _create_safe_name(new_label)
for category in cookfiledata:
if new_label_safe in cookfiledata[category].keys():
result = 'Label already exists!'
break
if old_label in cookfiledata[category].keys():
cookfiledata[category].pop(old_label)
cookfiledata[category][new_label_safe] = new_label
if(result != 'OK'):
return jsonify({'result' : 'ERROR'})
result = update_json_file_data(cookfiledata, filename, 'graph_labels')
if(result != 'OK'):
return jsonify({'result' : 'ERROR'})
''' Update graph_data.json '''
cookfiledata, result = read_json_file_data(filename, 'graph_data')
if(result != 'OK'):
return jsonify({'result' : 'ERROR'})
for category in cookfiledata['probe_mapper']:
if old_label in cookfiledata['probe_mapper'][category].keys():
cookfiledata['probe_mapper'][category][new_label_safe] = cookfiledata['probe_mapper'][category][old_label]
cookfiledata['probe_mapper'][category].pop(old_label)
list_position = cookfiledata['probe_mapper'][category][new_label_safe]
if category == 'targets':
addendum = ' Target'
elif category == 'primarysp':
addendum = ' Set Point'
else:
addendum = ''
cookfiledata['chart_data'][list_position]['label'] = new_label + addendum
result = update_json_file_data(cookfiledata, filename, 'graph_data')
if(result != 'OK'):
return jsonify({'result' : 'ERROR'})
return jsonify({'result' : 'OK', 'new_label_safe' : new_label_safe})
if('media' in requestjson):
filename = requestjson['filename']
assetfilename = requestjson['assetfilename']
commentid = requestjson['commentid']
state = requestjson['state']
comments, status = read_json_file_data(filename, 'comments')
result = 'OK'
for index in range(0, len(comments)):
if comments[index]['id'] == commentid:
if assetfilename in comments[index]['assets'] and state == 'selected':
comments[index]['assets'].remove(assetfilename)
result = update_json_file_data(comments, filename, 'comments')
elif assetfilename not in comments[index]['assets'] and state == 'unselected':
comments[index]['assets'].append(assetfilename)
result = update_json_file_data(comments, filename, 'comments')
break
return jsonify({'result' : result})
return jsonify({'result' : 'ERROR'})
@app.route('/tuner/<action>', methods=['POST','GET'])
@app.route('/tuner', methods=['POST','GET'])
def tuner_page(action=None):
global settings
control = read_control()
# This POST path will load/render portions of the tuner page
if request.method == 'POST' and ('form' in request.content_type):
requestform = request.form
if 'command' in requestform.keys():
if 'render' in requestform['command']:
render_string = "{% from '_macro_tuner.html' import render_" + requestform["value"] + " %}{{ render_" + requestform["value"] + "(settings, control) }}"
return render_template_string(render_string, settings=settings, control=control)
# This POST path provides data back to the page
if request.method == 'POST' and 'json' in request.content_type:
requestjson = request.json
command = requestjson.get('command', None)
if command == 'stop_tuning':
if control['tuning_mode']:
control['tuning_mode'] = False # Disable tuning mode
write_control(control, origin='app')
if control['mode'] == 'Monitor':
# If in Monitor Mode, stop
control['mode'] = 'Stop' # Go to Stop mode
control['updated'] = True
write_control(control, origin='app')
if command == 'read_tr':
if not control['tuning_mode']:
control['tuning_mode'] = True # Enable tuning mode
write_control(control, origin='app')
if control['mode'] == 'Stop':
# Turn on Monitor Mode if the system is stopped
control['mode'] = 'Monitor' # Enable monitor mode
control['updated'] = True
write_control(control, origin='app')
cur_probe_tr = read_tr()
if requestjson['probe_selected'] in cur_probe_tr.keys():
return jsonify({ 'trohms' : cur_probe_tr[requestjson['probe_selected']]})
else:
return jsonify({ 'trohms' : 0 })
if command == 'manual_finish' or command == 'auto_finish':
if control['tuning_mode']:
control['tuning_mode'] = False # Disable tuning mode
write_control(control, origin='app')
if control['mode'] == 'Monitor':
# If in Monitor Mode, stop
control['mode'] = 'Stop' # Go to Stop mode
control['updated'] = True
write_control(control, origin='app')
tunerManualHighTemp = requestjson.get('tunerManualHighTemp', 0.1)
tunerManualHighTemp = 0 if tunerManualHighTemp == '' else float(tunerManualHighTemp)
tunerManualHighTr = requestjson.get('tunerManualHighTr', 0.1)
tunerManualHighTr = 0 if tunerManualHighTr == '' else int(float(tunerManualHighTr))
tunerManualMediumTemp = requestjson.get('tunerManualMediumTemp', 0.1)
tunerManualMediumTemp = 0 if tunerManualMediumTemp == '' else float(tunerManualMediumTemp)
tunerManualMediumTr = requestjson.get('tunerManualMediumTr', 0.1)
tunerManualMediumTr = 0 if tunerManualMediumTr == '' else int(float(tunerManualMediumTr))
tunerManualLowTemp = requestjson.get('tunerManualLowTemp', 0.1)
tunerManualLowTemp = 0 if tunerManualLowTemp == '' else float(tunerManualLowTemp)
tunerManualLowTr = requestjson.get('tunerManualLowTr', 0.1)
tunerManualLowTr = 0 if tunerManualLowTr == '' else int(float(tunerManualLowTr))
a, b, c = _calc_shh_coefficients(tunerManualLowTemp, tunerManualMediumTemp,
tunerManualHighTemp, tunerManualLowTr,
tunerManualMediumTr, tunerManualHighTr,
units=settings['globals']['units'])
tr_points = [int(tunerManualHighTr), int(tunerManualMediumTr), int(tunerManualLowTr)]
labels, chart_data = _calc_shh_chart(a, b, c, units=settings['globals']['units'], temp_range=220, tr_points=tr_points)
return jsonify({'labels' : labels, 'chart_data' : chart_data, 'coefficients' : {'a' : a, 'b': b, 'c': c}})
if command == 'read_auto_status':
first_run = False
if not control['tuning_mode']:
control['tuning_mode'] = True # Enable tuning mode
write_control(control, origin='app')
read_autotune(flush=True) # Flush autotune data
first_run = True
if control['mode'] == 'Stop':
# Turn on Monitor Mode if the system is stopped
control['mode'] = 'Monitor' # Enable monitor mode
control['updated'] = True
write_control(control, origin='app')
status_data = {
'current_tr' : 0,
'current_temp' : 0,
'high_tr' : 0,
'high_temp' : 0,
'medium_tr' : 0,
'medium_temp' : 0,
'low_tr' : 0,
'low_temp' : 0,
'ready' : False
}
# Get Tr Data from all probes
cur_probe_tr = read_tr()
if requestjson['probe_selected'] in cur_probe_tr.keys():
status_data['current_tr'] = cur_probe_tr[requestjson['probe_selected']]
else:
status_data['current_tr'] = -1
# Get Temp Data from all probes
cur_probe_temps = read_current()
if requestjson['probe_reference'] in cur_probe_temps['P'].keys():
status_data['current_temp'] = cur_probe_temps['P'][requestjson['probe_reference']]
elif requestjson['probe_reference'] in cur_probe_temps['F'].keys():
status_data['current_temp'] = cur_probe_temps['F'][requestjson['probe_reference']]
elif requestjson['probe_reference'] in cur_probe_temps['AUX'].keys():
status_data['current_temp'] = cur_probe_temps['AUX'][requestjson['probe_reference']]
else:
status_data['current_temp'] = -1
# Some probes (i.e. the DS18B20) may be slow to respond when Monitor mode starts, and may report 0 degrees
# Thus we should ignore these first few data points if they are 0
autotune_data_size = read_autotune(size_only=True)
if (autotune_data_size > 4 or status_data['current_temp'] > 0) and \
status_data['current_tr'] >= 0 and \
status_data['current_temp'] >= 0 and \
not first_run:
# Record Temperature / Tr Values in Auto-Tune Record
data = {
'ref_T' : status_data['current_temp'],
'probe_Tr' : status_data['current_tr']
}
write_autotune(data)
data = read_autotune()
if len(data) > 10:
# If more than 10 datapoints, then calculate high / low / medium
temp_list = []
tr_list = []
for datapoint in data:
'''
Check if the ref_T value is already in the list and overwrite if so.
This assumes that the last temperature is the most recent and is likely
the most accurate resistance value to take.
'''
if datapoint['ref_T'] in temp_list:
index = temp_list.index(datapoint['ref_T'])
tr_list[index] = datapoint['probe_Tr']
else:
temp_list.append(datapoint['ref_T'])
tr_list.append(datapoint['probe_Tr'])
# Determine High Temp / Tr
status_data['high_temp'] = max(temp_list)
index = temp_list.index(max(temp_list))
status_data['high_tr'] = tr_list[index]
# Determine Low Temp / Tr
status_data['low_temp'] = min(temp_list)
index = temp_list.index(min(temp_list))
status_data['low_tr'] = tr_list[index]
# Determine Medium Temp / Tr
# Find best fit to Medium Temp
medium_temp = ((status_data['high_temp'] - status_data['low_temp']) // 2) + status_data['low_temp']
delta_temp = 1000 # Initial value is outside of any normal expected bounds
for index, temp in enumerate(temp_list):
if abs(temp - medium_temp) < delta_temp:
delta_temp = abs(temp - medium_temp)
delta_index = index
status_data['medium_temp'] = temp_list[delta_index]
status_data['medium_tr'] = tr_list[delta_index]
# Minimum range to be able to calculate temp
if settings['globals']['units'] == 'F':
min_range = 50
else: