-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
control.py
executable file
·1799 lines (1544 loc) · 69.9 KB
/
control.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 Main Control Program
# *****************************************
#
# Description: This script will start at boot, initialize the relays and
# wait for further commands from the web user interface.
#
# This script runs as a separate process from the Flask / Gunicorn
# implementation which handles the web interface.
#
# *****************************************
# Prototype Mode is now selected through modifying the module selections in the settings.json file.
# Run 'bash modules.sh' from the command prompt to select prototype modules, for prototype mode
# *****************************************
# Base Imported Libraries
# *****************************************
import importlib
import requests
from pushbullet import Pushbullet # Pushbullet Import
import pid as PID # Library for calculating PID setpoints
from common import * # Common Library for WebUI and Control Program
from temp_queue import TempQueue
'''
Read and initialize Settings, Control, History, Metrics, and Error Data
'''
# Read Settings & Wizard Manifest to Get Modules Configuration
settings = ReadSettings()
wizardData = ReadWizard()
# Flush Redis DB and create JSON structure
control = ReadControl(flush=True)
# Delete Redis DB for history / current
ReadHistory(0, flushhistory=True)
# Flush metrics DB for tracking certain metrics
WriteMetrics(flush=True)
# Create errors log
errors = ReadErrors(flush=True)
event = 'Flushing Redis DB and creating new control structure'
WriteLog(event)
'''
Set up GrillPlatform Module
'''
try:
grillplatform = settings['modules']['grillplat']
filename = 'grillplat_' + wizardData['modules']['grillplatform'][grillplatform]['filename']
GrillPlatModule = importlib.import_module(filename)
except:
GrillPlatModule = importlib.import_module('grillplat_prototype')
error_event = f'An error occured loading the [{settings["modules"]["grillplat"]}] platform module. The prototype module has been loaded instead. This sometimes means that the hardware is not connected properly, or the module is not configured. Please run the configuration wizard again from the admin panel to fix this issue.'
errors.append(error_event)
WriteErrors(errors)
WriteLog(error_event)
if settings['globals']['debug_mode']:
raise
outpins = settings['outpins']
inpins = settings['inpins']
triggerlevel = settings['globals']['triggerlevel']
buttonslevel = settings['globals']['buttonslevel']
units = settings['globals']['units']
if triggerlevel == 'LOW':
AUGERON = 0
AUGEROFF = 1
FANON = 0
FANOFF = 1
IGNITERON = 0
IGNITEROFF = 1
POWERON = 0
POWEROFF = 1
else:
AUGERON = 1
AUGEROFF = 0
FANON = 1
FANOFF = 0
IGNITERON = 1
IGNITEROFF = 0
POWERON = 1
POWEROFF = 0
try:
grill_platform = GrillPlatModule.GrillPlatform(outpins, inpins, triggerlevel)
except:
from grillplat_prototype import GrillPlatform # Simulated Library for controlling the grill platform
grill_platform = GrillPlatform(outpins, inpins, triggerlevel)
error_event = f'An error occured configuring the [{settings["modules"]["grillplat"]}] platform object. The prototype module has been loaded instead. This sometimes means that the hardware is not connected properly, or the module is not configured. Please run the configuration wizard again from the admin panel to fix this issue.'
errors.append(error_event)
WriteErrors(errors)
WriteLog(error_event)
if settings['globals']['debug_mode']:
raise
# If powering on, check the on/off switch and set grill power appropriately.
last = grill_platform.GetInputStatus()
if last == 0:
grill_platform.PowerOn()
else:
grill_platform.PowerOff()
'''
Set up Probes Input (ADC) Module
'''
try:
probesinput = settings['modules']['adc']
filename = 'adc_' + wizardData['modules']['probes'][probesinput]['filename']
ProbesModule = importlib.import_module(filename)
except:
ProbesModule = importlib.import_module('adc_prototype')
error_event = f'An error occured loading the [{settings["modules"]["adc"]}] probes module. The prototype module has been loaded instead. This sometimes means that the hardware is not connected properly, or the module is not configured. Please run the configuration wizard again from the admin panel to fix this issue.'
errors.append(error_event)
WriteErrors(errors)
WriteLog(error_event)
if settings['globals']['debug_mode']:
raise
# Start ADC object and set profiles
grill1type = settings['probe_types']['grill1type']
grill2type = settings['probe_types']['grill2type']
probe1type = settings['probe_types']['probe1type']
probe2type = settings['probe_types']['probe2type']
try:
adc_device = ProbesModule.ReadADC(
settings['probe_settings']['probe_profiles'][grill1type],
settings['probe_settings']['probe_profiles'][grill2type],
settings['probe_settings']['probe_profiles'][probe1type],
settings['probe_settings']['probe_profiles'][probe2type],
units=settings['globals']['units'])
except:
from adc_prototype import ReadADC # Simulated Library for controlling the grill platform
adc_device = ReadADC(
settings['probe_settings']['probe_profiles'][grill1type],
settings['probe_settings']['probe_profiles'][grill2type],
settings['probe_settings']['probe_profiles'][probe1type],
settings['probe_settings']['probe_profiles'][probe2type],
units=settings['globals']['units'])
error_event = f'An error occured configuring the [{settings["modules"]["adc"]}] probes object. The prototype module has been loaded instead. This sometimes means that the hardware is not connected properly, or the module is not configured. Please run the configuration wizard again from the admin panel to fix this issue.'
errors.append(error_event)
WriteErrors(errors)
WriteLog(error_event)
if settings['globals']['debug_mode']:
raise
for probe_source in settings['probe_settings']['probe_sources']:
# if any of the probes uses max31865 then load the library
if 'max31865' in probe_source:
from probe_max31865 import probe_max31865_read
break
'''
Set up Display Module
'''
try:
displayname = settings['modules']['display']
filename = 'display_' + wizardData['modules']['display'][displayname]['filename']
DisplayModule = importlib.import_module(filename)
except:
DisplayModule = importlib.import_module('display_prototype')
error_event = f'An error occured loading the [{settings["modules"]["display"]}] display module. The prototype module has been loaded instead. This sometimes means that the hardware is not connected properly, or the module is not configured. Please run the configuration wizard again from the admin panel to fix this issue.'
errors.append(error_event)
WriteErrors(errors)
WriteLog(error_event)
if settings['globals']['debug_mode']:
raise
try:
if str(settings['modules']['display']).endswith('b'):
display_device = DisplayModule.Display(buttonslevel=buttonslevel, units=units)
else:
display_device = DisplayModule.Display(units=units)
except:
from display_prototype import Display # Simulated Library for controlling the grill platform
display_device = Display(units=units)
error_event = f'An error occured configuring the [{settings["modules"]["display"]}] display object. The prototype module has been loaded instead. This sometimes means that the hardware is not connected properly, or the module is not configured. Please run the configuration wizard again from the admin panel to fix this issue.'
errors.append(error_event)
WriteErrors(errors)
WriteLog(error_event)
if settings['globals']['debug_mode']:
raise
'''
Set up Distance (Hopper Level) Module
'''
try:
distname = settings['modules']['dist']
filename = 'distance_' + wizardData['modules']['distance'][distname]['filename']
DistanceModule = importlib.import_module(filename)
except:
DistanceModule = importlib.import_module('distance_prototype')
error_event = f'An error occured loading the [{settings["modules"]["dist"]}] distance module. The prototype module has been loaded instead. This sometimes means that the hardware is not connected properly, or the module is not configured. Please run the configuration wizard again from the admin panel to fix this issue.'
errors.append(error_event)
WriteErrors(errors)
WriteLog(error_event)
if settings['globals']['debug_mode']:
raise
try:
if (settings['modules']['grillplat'] == 'prototype') and (settings['modules']['dist'] == 'prototype'):
# If in prototype mode, enable test reading (i.e. random values from proto distance sensor)
dist_device = DistanceModule.HopperLevel(settings['pelletlevel']['empty'], settings['pelletlevel']['full'], test=True)
else:
dist_device = DistanceModule.HopperLevel(settings['pelletlevel']['empty'], settings['pelletlevel']['full'])
except:
from distance_prototype import HopperLevel # Simulated Library for controlling the grill platform
dist_device = HopperLevel(settings['pelletlevel']['empty'], settings['pelletlevel']['full'])
error_event = f'An error occured configuring the [{settings["modules"]["dist"]}] distance object. The prototype module has been loaded instead. This sometimes means that the hardware is not connected properly, or the module is not configured. Please run the configuration wizard again from the admin panel to fix this issue.'
errors.append(error_event)
WriteErrors(errors)
WriteLog(error_event)
if settings['globals']['debug_mode']:
raise
# Get current hopper level and save it to the current pellet information
pelletdb = ReadPelletDB()
pelletdb['current']['hopper_level'] = dist_device.GetLevel()
WritePelletDB(pelletdb)
if settings['globals']['debug_mode']:
event = "* Hopper Level Checked @ " + str(pelletdb['current']['hopper_level']) + "%"
print(event)
WriteLog(event)
# *****************************************
# Function Definitions
# *****************************************
def ReadProbes(settings, adc_device, units):
adc_data = adc_device.ReadAllPorts()
prob_data = {}
probe_ids = ['Grill1', 'Probe1', 'Probe2', 'Grill2']
adc_properties = ['Temp', 'Tr']
adc_probe_indices = ['Grill1', 'Probe1', 'Probe2', 'Grill2']
for idx, probe_source in enumerate(settings['probe_settings']['probe_sources']):
if 'ADC' in probe_source and len(probe_source) > 3:
# map ADC proves to the output probes. i.e ADC0 is adc_probe_indices[0] => 'Grill' so if this is defined
# for first source map Grill to Grill. If ADC1 in first source map it to Probe1
source_index = int(probe_source[3:])
for p in adc_properties:
prob_data[probe_ids[idx] + p] = adc_data[adc_probe_indices[source_index] + p]
elif 'max31865' in probe_source:
temperature, resistance = probe_max31865_read(units=units)
prob_data[probe_ids[idx] + adc_properties[0]] = temperature
prob_data[probe_ids[idx] + adc_properties[1]] = resistance
return prob_data
def GetStatus(grill_platform, control, settings, pelletdb):
# *****************************************
# Get Status Details for Display Function
# *****************************************
status_data = {}
status_data['outpins'] = {}
current = grill_platform.GetOutputStatus() # Get current pin settings
if settings['globals']['triggerlevel'] == 'LOW':
for item in settings['outpins']:
status_data['outpins'][item] = current[item]
else:
for item in settings['outpins']:
status_data['outpins'][item] = not current[item] # Reverse Logic
status_data['mode'] = control['mode'] # Get current mode
status_data['notify_req'] = control['notify_req'] # Get any flagged notificiations
status_data['timer'] = control['timer'] # Get the timer information
status_data['ipaddress'] = '192.168.10.43' # Future implementation (TODO)
status_data['s_plus'] = control['s_plus']
status_data['hopper_level'] = pelletdb['current']['hopper_level']
status_data['units'] = settings['globals']['units']
return (status_data)
def WorkCycle(mode, grill_platform, adc_device, display_device, dist_device):
# *****************************************
# Work Cycle Function
# *****************************************
event = mode + ' Mode started.'
WriteLog(event)
# Setup Cycle Parameters
settings = ReadSettings()
control = ReadControl()
pelletdb = ReadPelletDB()
# Get ON/OFF Switch state and set as last state
last = grill_platform.GetInputStatus()
# Set Starting Configuration for Igniter, Fan , Auger
grill_platform.FanOn()
grill_platform.IgniterOff()
grill_platform.AugerOff()
grill_platform.PowerOn()
WriteMetrics(new_metric=True)
metrics = ReadMetrics()
metrics['mode'] = str(control['mode'])
metrics['smokeplus'] = control['s_plus']
metrics['grill_settemp'] = control['setpoints']['grill']
WriteMetrics(metrics)
if settings['globals']['debug_mode']:
event = '* Fan ON, Igniter OFF, Auger OFF'
print(event)
WriteLog(event)
if (mode == 'Startup') or (mode == 'Reignite'):
grill_platform.IgniterOn()
if settings['globals']['debug_mode']:
event = '* Igniter ON'
print(event)
WriteLog(event)
if (mode == 'Smoke') or (mode == 'Hold') or (mode == 'Startup') or (mode == 'Reignite'):
grill_platform.AugerOn()
if settings['globals']['debug_mode']:
event = '* Auger ON'
print(event)
WriteLog(event)
if mode == 'Startup' or 'Smoke' or 'Reignite':
OnTime = settings['cycle_data']['SmokeCycleTime'] # Auger On Time (Default 15s)
OffTime = 45 + (settings['cycle_data']['PMode'] * 10) # Auger Off Time
CycleTime = OnTime + OffTime # Total Cycle Time
CycleRatio = OnTime / CycleTime # Ratio of OnTime to CycleTime
# Write Metrics (note these will be overwritten if smart start is enabled)
metrics['p_mode'] = settings['cycle_data']['PMode']
metrics['auger_cycle_time'] = settings['cycle_data']['SmokeCycleTime']
WriteMetrics(metrics)
if mode == 'Shutdown':
OnTime = 0 # Auger On Time
OffTime = 100 # Auger Off Time
CycleTime = 100 # Total Cycle Time
CycleRatio = 0 # Ratio of OnTime to CycleTime
if mode == 'Hold':
OnTime = settings['cycle_data']['HoldCycleTime'] * settings['cycle_data']['u_min'] # Auger On Time
OffTime = settings['cycle_data']['HoldCycleTime'] * (1 - settings['cycle_data']['u_min']) # Auger Off Time
CycleTime = settings['cycle_data']['HoldCycleTime'] # Total Cycle Time
CycleRatio = settings['cycle_data']['u_min'] # Ratio of OnTime to CycleTime
PIDControl = PID.PID(settings['cycle_data']['PB'], settings['cycle_data']['Ti'], settings['cycle_data']['Td'])
PIDControl.setTarget(control['setpoints']['grill']) # Initialize with setpoint for grill
if settings['globals']['debug_mode']:
event = '* On Time = ' + str(OnTime) + ', OffTime = ' + str(OffTime) + ', CycleTime = ' + str(
CycleTime) + ', CycleRatio = ' + str(CycleRatio)
print(event)
WriteLog(event)
# Initialize all temperature variables
AvgGT = TempQueue(units=settings['globals']['units'])
AvgP1 = TempQueue(units=settings['globals']['units'])
AvgP2 = TempQueue(units=settings['globals']['units'])
# Check pellets level notification upon starting cycle
CheckNotifyPellets(control, settings, pelletdb)
# Collect Initial Temperature Information
# Get Probe Types From Settings
grill1type = settings['probe_types']['grill1type']
grill2type = settings['probe_types']['grill2type']
probe1type = settings['probe_types']['probe1type']
probe2type = settings['probe_types']['probe2type']
adc_device.SetProfiles(settings['probe_settings']['probe_profiles'][grill1type],
settings['probe_settings']['probe_profiles'][grill2type],
settings['probe_settings']['probe_profiles'][probe1type],
settings['probe_settings']['probe_profiles'][probe2type])
adc_data = ReadProbes(settings, adc_device, units)
if settings['globals']['four_probes']:
if settings['grill_probe_settings']['grill_probe_enabled'][2] == 1:
AvgGT.enqueue((adc_data['Grill1Temp'] + adc_data['Grill2Temp']) / 2)
elif settings['grill_probe_settings']['grill_probe_enabled'][1] == 1:
AvgGT.enqueue(adc_data['Grill2Temp'])
else:
AvgGT.enqueue(adc_data['Grill1Temp'])
else:
AvgGT.enqueue(adc_data['Grill1Temp'])
AvgP1.enqueue(adc_data['Probe1Temp'])
AvgP2.enqueue(adc_data['Probe2Temp'])
status = 'Active'
# Safety Controls
if (mode == 'Startup') or (mode == 'Reignite'):
# control = ReadControl() # Read Modify Write
control['safety']['startuptemp'] = int(max((AvgGT.average() * 0.9), settings['safety']['minstartuptemp']))
control['safety']['startuptemp'] = int(
min(control['safety']['startuptemp'], settings['safety']['maxstartuptemp']))
control['safety']['afterstarttemp'] = AvgGT.average()
WriteControl(control)
# Check if the temperature of the grill dropped below the startuptemperature
elif (mode == 'Hold') or (mode == 'Smoke'):
if control['safety']['afterstarttemp'] < control['safety']['startuptemp']:
if control['safety']['reigniteretries'] == 0:
status = 'Inactive'
event = 'ERROR: Grill temperature dropped below minimum startup temperature of ' + str(
control['safety']['startuptemp']) + settings['globals'][
'units'] + '! Shutting down to prevent firepot overload.'
WriteLog(event)
display_device.DisplayText('ERROR')
# control = ReadControl() # Read Modify Write
control['mode'] = 'Error'
control['updated'] = True
WriteControl(control)
SendNotifications("Grill_Error_02", control, settings, pelletdb)
else:
# control = ReadControl() # Read Modify Write
control['safety']['reigniteretries'] -= 1
control['safety']['reignitelaststate'] = mode
status = 'Inactive'
event = 'ERROR: Grill temperature dropped below minimum startup temperature of ' + str(
control['safety']['startuptemp']) + settings['globals'][
'units'] + '. Starting a re-ignite attempt, per user settings.'
WriteLog(event)
display_device.DisplayText('Re-Ignite')
control['mode'] = 'Reignite'
control['updated'] = True
WriteControl(control)
# Apply Smart Start Settings if Enabled
if(settings['smartstart']['enabled']) and ((control['mode'] == 'Startup') or (control['mode'] == 'Smoke')):
# If Startup, then save intial temperature & select the profile
if control['mode'] == 'Startup':
control['smartstart']['startuptemp'] = int(AvgGT.average())
# Cycle through profiles, and set profile if startup temperature falls below the minimum temperature
for profile_selected in range(0, len(settings['smartstart']['temp_range_list'])):
if control['smartstart']['startuptemp'] < settings['smartstart']['temp_range_list'][profile_selected]:
control['smartstart']['profile_selected'] = profile_selected
WriteControl(control)
break # Break out of the loop
if profile_selected == len(settings['smartstart']['temp_range_list'])-1:
control['smartstart']['profile_selected'] = profile_selected + 1
WriteControl(control)
# Apply the profile
profile_selected = control['smartstart']['profile_selected']
OnTime = settings['smartstart']['profiles'][profile_selected]['augerontime'] # Auger On Time (Default 15s)
OffTime = 45 + (settings['smartstart']['profiles'][profile_selected]['p_mode'] * 10) # Auger Off Time
CycleTime = OnTime + OffTime # Total Cycle Time
CycleRatio = OnTime / CycleTime # Ratio of OnTime to CycleTime
# Write Metrics
metrics['smart_start_profile'] = profile_selected
metrics['startup_temp'] = control['smartstart']['startuptemp']
metrics['p_mode'] = settings['smartstart']['profiles'][profile_selected]['p_mode']
metrics['auger_cycle_time'] = settings['smartstart']['profiles'][profile_selected]['augerontime']
WriteMetrics(metrics)
# Set the start time
starttime = time.time()
# Set time since toggle for temperature
temptoggletime = starttime
# Set time since toggle for auger
augertoggletime = starttime
# Set time since toggle for display
displaytoggletime = starttime
# Initializing Start Time for Smoke Plus Mode
sp_cycletoggletime = starttime
# Set time since toggle for hopper check
hoppertoggletime = starttime
# Set time since last control check
controlchecktime = starttime
# Set time since last pellet level check
pelletschecktime = starttime
# Initialize Current Auger State Structure
current_output_status = {}
# Set Hold Mode Target Temp Boolean
target_temp_achieved = False
# ============ Main Work Cycle ============
while status == 'Active':
now = time.time()
# Check for button input event
display_device.EventDetect()
# Check for update in control status every 0.1 seconds
if now - controlchecktime > 0.1:
control = ReadControl()
controlchecktime = now
# Check for pellet level notifications every 20 minutes
if now - pelletschecktime > 1200:
CheckNotifyPellets(control, settings, pelletdb)
pelletschecktime = now
# Check if new mode has been requested
if control['updated']:
status = 'Inactive'
break
# Check hopper level when requested or every 300 seconds
if (control['hopper_check'] == True) or (now - hoppertoggletime > 300):
pelletdb = ReadPelletDB()
# Get current hopper level and save it to the current pellet information
pelletdb['current']['hopper_level'] = dist_device.GetLevel()
WritePelletDB(pelletdb)
hoppertoggletime = now
if control['hopper_check']:
# control = ReadControl() # Read Modify Write
control['hopper_check'] = False
WriteControl(control)
if settings['globals']['debug_mode']:
event = "* Hopper Level Checked @ " + str(pelletdb['current']['hopper_level']) + "%"
print(event)
WriteLog(event)
# Check for update in ON/OFF Switch
if last != grill_platform.GetInputStatus():
last = grill_platform.GetInputStatus()
if last == 1:
status = 'Inactive'
event = 'Switch set to off, going to monitor mode.'
WriteLog(event)
# control = ReadControl() # Read Modify Write
control['updated'] = True # Change mode
control['mode'] = 'Stop'
control['status'] = 'active'
WriteControl(control)
break
# Change Auger State based on Cycle Time
current_output_status = grill_platform.GetOutputStatus()
# If Auger is OFF and time since toggle is greater than Off Time
if (current_output_status['auger'] == AUGEROFF) and (now - augertoggletime > CycleTime * (1 - CycleRatio)):
grill_platform.AugerOn()
augertoggletime = now
# Reset Cycle Time for HOLD Mode
if mode == 'Hold':
CycleRatio = PIDControl.update(AvgGT.average())
CycleRatio = max(CycleRatio, settings['cycle_data']['u_min'])
CycleRatio = min(CycleRatio, settings['cycle_data']['u_max'])
OnTime = settings['cycle_data']['HoldCycleTime'] * CycleRatio
OffTime = settings['cycle_data']['HoldCycleTime'] * (1 - CycleRatio)
CycleTime = OnTime + OffTime
if settings['globals']['debug_mode']:
event = '* On Time = ' + str(OnTime) + ', OffTime = ' + str(OffTime) + ', CycleTime = ' + str(
CycleTime) + ', CycleRatio = ' + str(CycleRatio)
print(event)
WriteLog(event)
if settings['globals']['debug_mode']:
event = '* Cycle Event: Auger On'
print(event)
WriteLog(event)
# If Auger is ON and time since toggle is greater than On Time
if (current_output_status['auger'] == AUGERON) and (now - augertoggletime > CycleTime * CycleRatio):
grill_platform.AugerOff()
# Add auger ON time to the metrics
metrics['augerontime'] += now - augertoggletime
WriteMetrics(metrics)
# Set current last toggle time to now
augertoggletime = now
if settings['globals']['debug_mode']:
event = '* Cycle Event: Auger Off'
print(event)
WriteLog(event)
# Grab current probe profiles if they have changed since the last loop.
if control['probe_profile_update']:
settings = ReadSettings()
# control = ReadControl() # Read Modify Write
control['probe_profile_update'] = False
WriteControl(control)
# Get new probe profiles
grill1type = settings['probe_types']['grill1type']
grill2type = settings['probe_types']['grill2type']
probe1type = settings['probe_types']['probe1type']
probe2type = settings['probe_types']['probe2type']
# Add new probe profiles to ADC Object
adc_device.SetProfiles(settings['probe_settings']['probe_profiles'][grill1type],
settings['probe_settings']['probe_profiles'][grill2type],
settings['probe_settings']['probe_profiles'][probe1type],
settings['probe_settings']['probe_profiles'][probe2type])
# Get temperatures from all probes
adc_data = ReadProbes(settings, adc_device, units)
# Test temperature data returned for errors (+/- 20% Temp Variance), and average the data since last reading
if settings['globals']['four_probes']:
if settings['grill_probe_settings']['grill_probe_enabled'][2] == 1:
AvgGT.enqueue((adc_data['Grill1Temp'] + adc_data['Grill2Temp']) / 2 )
elif settings['grill_probe_settings']['grill_probe_enabled'][1] == 1:
AvgGT.enqueue(adc_data['Grill2Temp'])
else:
AvgGT.enqueue(adc_data['Grill1Temp'])
else:
AvgGT.enqueue(adc_data['Grill1Temp'])
AvgP1.enqueue(adc_data['Probe1Temp'])
AvgP2.enqueue(adc_data['Probe2Temp'])
in_data = {}
in_data['GrillTemp'] = AvgGT.average()
in_data['GrillSetPoint'] = control['setpoints']['grill']
in_data['Probe1Temp'] = AvgP1.average()
in_data['Probe1SetPoint'] = control['setpoints']['probe1']
in_data['Probe2Temp'] = AvgP2.average()
in_data['Probe2SetPoint'] = control['setpoints']['probe2']
if settings['globals']['four_probes']:
if settings['grill_probe_settings']['grill_probe_enabled'][2] == 1:
in_data['GrillTr'] = 0 # This is an average of two probes so it should be disabled for editing.
elif settings['grill_probe_settings']['grill_probe_enabled'][1] == 1:
in_data['GrillTr'] = adc_data['Grill2Tr'] # For Temp Resistance Tuning
else:
in_data['GrillTr'] = adc_data['Grill1Tr'] # For Temp Resistance Tuning
else:
in_data['GrillTr'] = adc_data['Grill1Tr'] # For Temp Resistance Tuning
in_data['Probe1Tr'] = adc_data['Probe1Tr'] # For Temp Resistance Tuning
in_data['Probe2Tr'] = adc_data['Probe2Tr'] # For Temp Resistance Tuning
# Check to see if there are any pending notifications (i.e. Timer / Temperature Settings)
control = CheckNotify(in_data, control, settings, pelletdb, grill_platform)
# Check for button input event
display_device.EventDetect()
# Send Current Status / Temperature Data to Display Device every 0.5 second (Display Refresh)
if now - displaytoggletime > 0.5:
status_data = GetStatus(grill_platform, control, settings, pelletdb)
display_device.DisplayStatus(in_data, status_data)
displaytoggletime = time.time() # Reset the displaytoggletime to current time
# Safety Controls
if (mode == 'Startup') or (mode == 'Reignite'):
control['safety']['afterstarttemp'] = AvgGT.average()
elif (mode == 'Hold') or (mode == 'Smoke'):
if AvgGT.average() < control['safety']['startuptemp']:
if control['safety']['reigniteretries'] == 0:
status = 'Inactive'
event = 'ERROR: Grill temperature dropped below minimum startup temperature of ' + str(
control['safety']['startuptemp']) + settings['globals'][
'units'] + '! Shutting down to prevent firepot overload.'
WriteLog(event)
display_device.DisplayText('ERROR')
# control = ReadControl() # Read Modify Write
control['mode'] = 'Error'
control['updated'] = True
WriteControl(control)
SendNotifications("Grill_Error_02", control, settings, pelletdb)
else:
control['safety']['reigniteretries'] -= 1
control['safety']['reignitelaststate'] = mode
status = 'Inactive'
event = 'ERROR: Grill temperature dropped below minimum startup temperature of ' + str(
control['safety']['startuptemp']) + settings['globals'][
'units'] + '. Starting a re-ignite attempt, per user settings.'
WriteLog(event)
display_device.DisplayText('Re-Ignite')
# control = ReadControl() # Read Modify Write
control['mode'] = 'Reignite'
control['updated'] = True
WriteControl(control)
if AvgGT.average() > settings['safety']['maxtemp']:
status = 'Inactive'
event = 'ERROR: Grill exceed maximum temperature limit of ' + str(
settings['safety']['maxtemp']) + 'F! Shutting down.'
WriteLog(event)
display_device.DisplayText('ERROR')
# control = ReadControl() # Read Modify Write
control['mode'] = 'Error'
control['updated'] = True
WriteControl(control)
SendNotifications("Grill_Error_01", control, settings, pelletdb)
# Check if target temperature has been achieved before utilizing Smoke Plus Mode
if ((mode == 'Hold') and (AvgGT.average() >= control['setpoints']['grill']) and (
target_temp_achieved == False)):
target_temp_achieved = True
# If in Smoke Plus Mode, Cycle the Fan
if ((mode == 'Smoke') or ((mode == 'Hold') and (target_temp_achieved))) and (control['s_plus'] == True):
# If Temperature is > settings['smoke_plus']['max_temp'] then turn on fan
if AvgGT.average() > settings['smoke_plus']['max_temp']:
grill_platform.FanOn()
# elif Temperature is < settings['smoke_plus']['min_temp'] then turn on fan
elif AvgGT.average() < settings['smoke_plus']['min_temp']:
grill_platform.FanOn()
# elif now - sp_cycletoggletime > settings['smoke_plus']['cycle'] / 2 then toggle fan, reset sp_cycletoggletime = now
elif (now - sp_cycletoggletime) > (settings['smoke_plus']['cycle'] * 0.5):
grill_platform.FanToggle()
sp_cycletoggletime = now
if settings['globals']['debug_mode']:
event = '* Smoke Plus: Fan Toggled'
print(event)
WriteLog(event)
elif (current_output_status['fan'] == FANOFF) and (control['s_plus'] == False):
grill_platform.FanOn()
# Write History after 3 seconds has passed
if now - temptoggletime > 3:
temptoggletime = time.time()
WriteHistory(in_data, tuning_mode=control['tuning_mode'])
# Check if startup time has elapsed since startup/reignite mode started
if (mode == 'Startup') or (mode == 'Reignite'):
if settings['smartstart']['enabled']:
startup_timer = settings['smartstart']['profiles'][profile_selected]['startuptime']
else:
startup_timer = settings['globals']['startup_timer']
if (now - starttime) > startup_timer:
status = 'Inactive'
# Check if shutdown time has elapsed since shutdown mode started
if (mode == 'Shutdown') and ((now - starttime) > settings['globals']['shutdown_timer']):
status = 'Inactive'
time.sleep(0.05)
# *********
# END Mode Loop
# *********
# Clean-up and Exit
grill_platform.AugerOff()
grill_platform.IgniterOff()
if settings['globals']['debug_mode']:
event = '* Auger OFF, Igniter OFF'
print(event)
WriteLog(event)
if mode == 'Shutdown':
grill_platform.FanOff()
grill_platform.PowerOff()
if settings['globals']['debug_mode']:
event = '* Fan OFF, Power OFF'
print(event)
WriteLog(event)
if (mode == 'Startup') or (mode == 'Reignite'):
# control = ReadControl() # Read Modify Write
control['safety']['afterstarttemp'] = AvgGT.average()
WriteControl(control)
event = mode + ' mode ended.'
WriteLog(event)
# Log the end time
metrics['endtime'] = time.time()
WriteMetrics(metrics)
return ()
# ******************************
# Monitor Grill Temperatures while alternative OEM controller is running
# ******************************
def Monitor(grill_platform, adc_device, display_device, dist_device):
event = 'Monitor Mode started.'
WriteLog(event)
# Get ON/OFF Switch state and set as last state
last = grill_platform.GetInputStatus()
grill_platform.AugerOff()
grill_platform.IgniterOff()
grill_platform.FanOff()
grill_platform.PowerOff()
# Setup Cycle Parameters
settings = ReadSettings()
control = ReadControl()
pelletdb = ReadPelletDB()
# Initialize all temperature objects
AvgGT = TempQueue(units=settings['globals']['units'])
AvgP1 = TempQueue(units=settings['globals']['units'])
AvgP2 = TempQueue(units=settings['globals']['units'])
# Check pellets level notification upon starting cycle
CheckNotifyPellets(control, settings, pelletdb)
# Collect Initial Temperature Information
# Get Probe Types From Settings
grill1type = settings['probe_types']['grill1type']
grill2type = settings['probe_types']['grill2type']
probe1type = settings['probe_types']['probe1type']
probe2type = settings['probe_types']['probe2type']
adc_device.SetProfiles(settings['probe_settings']['probe_profiles'][grill1type],
settings['probe_settings']['probe_profiles'][grill2type],
settings['probe_settings']['probe_profiles'][probe1type],
settings['probe_settings']['probe_profiles'][probe2type])
adc_data = ReadProbes(settings, adc_device, units)
if settings['globals']['four_probes']:
if settings['grill_probe_settings']['grill_probe_enabled'][2] == 1:
AvgGT.enqueue((adc_data['Grill1Temp'] + adc_data['Grill2Temp']) / 2 )
elif settings['grill_probe_settings']['grill_probe_enabled'][1] == 1:
AvgGT.enqueue(adc_data['Grill2Temp'])
else:
AvgGT.enqueue(adc_data['Grill1Temp'])
else:
AvgGT.enqueue(adc_data['Grill1Temp'])
AvgP1.enqueue(adc_data['Probe1Temp'])
AvgP2.enqueue(adc_data['Probe2Temp'])
now = time.time()
# Set time since toggle for temperature
temptoggletime = now
# Set time since toggle for display
displaytoggletime = now
# Set time since toggle for hopper check
hoppertoggletime = now
# Set time since last control check
controlchecktime = now
# Set time since last pellet level check
pelletschecktime = now
status = 'Active'
while status == 'Active':
now = time.time()
# Check for update in control status every 0.5 seconds
if now - controlchecktime > 0.5:
control = ReadControl()
controlchecktime = now
# Check for pellet level notifications every 20 minutes
if now - pelletschecktime > 1200:
CheckNotifyPellets(control, settings, pelletdb)
pelletschecktime = now
# Check for update in control status
if control['updated'] == True:
status = 'Inactive'
break
# Check for update in ON/OFF Switch
if last != grill_platform.GetInputStatus():
last = grill_platform.GetInputStatus()
if last == 1:
status = 'Inactive'
event = 'Switch set to off, going to Stop mode.'
WriteLog(event)
# control = ReadControl() # Read Modify Write
control['updated'] = True # Change mode
control['mode'] == 'Stop'
control['status'] == 'active'
WriteControl(control)
break
# Check hopper level when requested or every 300 seconds
if (control['hopper_check'] == True) or (now - hoppertoggletime > 300):
pelletdb = ReadPelletDB()
# Get current hopper level and save it to the current pellet information
pelletdb['current']['hopper_level'] = dist_device.GetLevel()
WritePelletDB(pelletdb)
hoppertoggletime = now
if control['hopper_check']:
# control = ReadControl() # Read Modify Write
control['hopper_check'] = False
WriteControl(control)
if settings['globals']['debug_mode']:
event = "* Hopper Level Checked @ " + str(pelletdb['current']['hopper_level']) + "%"
print(event)
WriteLog(event)
# Grab current probe profiles if they have changed since the last loop.
if control['probe_profile_update']:
settings = ReadSettings()
# control = ReadControl() # Read Modify Write
control['probe_profile_update'] = False
WriteControl(control)
# Get new probe profiles
grill1type = settings['probe_types']['grill1type']
grill2type = settings['probe_types']['grill2type']
probe1type = settings['probe_types']['probe1type']
probe2type = settings['probe_types']['probe2type']
# Add new probe profiles to ADC Object
adc_device.SetProfiles(settings['probe_settings']['probe_profiles'][grill1type],
settings['probe_settings']['probe_profiles'][grill2type],
settings['probe_settings']['probe_profiles'][probe1type],
settings['probe_settings']['probe_profiles'][probe2type])
adc_data = ReadProbes(settings, adc_device, units)
# Test temperature data returned for errors (+/- 20% Temp Variance), and average the data since last reading
if settings['globals']['four_probes']:
if settings['grill_probe_settings']['grill_probe_enabled'][2] == 1:
AvgGT.enqueue((adc_data['Grill1Temp'] + adc_data['Grill2Temp']) / 2 )
elif settings['grill_probe_settings']['grill_probe_enabled'][1] == 1:
AvgGT.enqueue(adc_data['Grill2Temp'])
else:
AvgGT.enqueue(adc_data['Grill1Temp'])
else:
AvgGT.enqueue(adc_data['Grill1Temp'])
AvgP1.enqueue(adc_data['Probe1Temp'])
AvgP2.enqueue(adc_data['Probe2Temp'])
in_data = {}
in_data['GrillTemp'] = AvgGT.average()
in_data['GrillSetPoint'] = control['setpoints']['grill']
in_data['Probe1Temp'] = AvgP1.average()
in_data['Probe1SetPoint'] = control['setpoints']['probe1']
in_data['Probe2Temp'] = AvgP2.average()
in_data['Probe2SetPoint'] = control['setpoints']['probe2']
if settings['globals']['four_probes']:
if settings['grill_probe_settings']['grill_probe_enabled'][2] == 1:
in_data['GrillTr'] = 0 # This is an average of two probes so it should be disabled for editing.
elif settings['grill_probe_settings']['grill_probe_enabled'][1] == 1:
in_data['GrillTr'] = adc_data['Grill2Tr'] # For Temp Resistance Tuning
else:
in_data['GrillTr'] = adc_data['Grill1Tr'] # For Temp Resistance Tuning
else:
in_data['GrillTr'] = adc_data['Grill1Tr'] # For Temp Resistance Tuning
in_data['Probe1Tr'] = adc_data['Probe1Tr'] # For Temp Resistance Tuning
in_data['Probe2Tr'] = adc_data['Probe2Tr'] # For Temp Resistance Tuning
# Check to see if there are any pending notifications (i.e. Timer / Temperature Settings)
control = CheckNotify(in_data, control, settings, pelletdb, grill_platform)
# Check for button input event
display_device.EventDetect()
# Update Display Device after 1 second has passed
if now - displaytoggletime > 1:
status_data = GetStatus(grill_platform, control, settings, pelletdb)
display_device.DisplayStatus(in_data, status_data)
displaytoggletime = now
# Write History after 3 seconds has passed
if now - temptoggletime > 3:
temptoggletime = now
WriteHistory(in_data, tuning_mode=control['tuning_mode'])
# Safety Control Section
if AvgGT.average() > settings['safety']['maxtemp']:
status = 'Inactive'
event = 'ERROR: Grill exceed maximum temperature limit of ' + str(settings['safety']['maxtemp']) + \
settings['globals']['units'] + '! Shutting down.'
WriteLog(event)
display_device.DisplayText('ERROR')
# control = ReadControl() # Read Modify Write
control['mode'] = 'Error'
control['updated'] = True
control['status'] = 'monitor'
WriteControl(control)
SendNotifications("Grill_Error_01", control, settings, pelletdb)
time.sleep(0.05)
event = 'Monitor mode ended.'
WriteLog(event)
return ()
# ******************************
# Manual Mode Control
# ******************************
def Manual_Mode(grill_platform, adc_device, display_device, dist_device):
# Setup Cycle Parameters
settings = ReadSettings()
control = ReadControl()
pelletdb = ReadPelletDB()
event = 'Manual Mode started.'
WriteLog(event)
# Get ON/OFF Switch state and set as last state