-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathcontrol.py
executable file
·1361 lines (1192 loc) · 58.7 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 Process
==============================================================================
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.
==============================================================================
'''
'''
==============================================================================
Imported Modules
==============================================================================
'''
import logging
import importlib
import atexit
from common import * # Common Module for WebUI and Control Program
from common.process_mon import Process_Monitor
from common.redis_queue import RedisQueue
from notify.notifications import *
from file_mgmt.recipes import convert_recipe_units
from file_mgmt.cookfile import create_cookfile
from file_mgmt.common import read_json_file_data
from os.path import exists
'''
==============================================================================
Read and initialize Settings, Control, History, Metrics, and Error Data
==============================================================================
'''
# Read Settings to get Modules Configuration
settings = read_settings(init=True)
# Setup logging
log_level = logging.DEBUG if settings['globals']['debug_mode'] else logging.ERROR
controlLogger = create_logger('control', filename='./logs/control.log', messageformat='%(asctime)s [%(levelname)s] %(message)s', level=log_level)
log_level = logging.DEBUG if settings['globals']['debug_mode'] else logging.INFO
eventLogger = create_logger('events', filename='/tmp/events.log', messageformat='%(asctime)s [%(levelname)s] %(message)s', level=log_level)
eventLogger.info('Control Script Starting Up.')
controlLogger.info('Control Script Starting Up.')
# Flush Redis DB and create JSON structure
control = read_control(flush=True)
# Delete Redis DB for history / current
read_history(0, flushhistory=True)
# Flush metrics DB for tracking certain metrics
write_metrics(flush=True)
# Create/Flush errors list
errors = read_errors(flush=True)
eventLogger.info('Flushing Redis DB and creating new control structure')
platform_config = settings['platform']
platform_config['frequency'] = settings['pwm']['frequency']
units = settings['globals']['units']
'''
Set up GrillPlatform Module
'''
try:
grill_platform = settings['modules']['grillplat']
GrillPlatModule = importlib.import_module(f'grillplat.{grill_platform}')
except:
control['critical_error'] = True
write_control(control, direct_write=True, origin='control')
controlLogger.exception(f'Error occurred importing grillplatform module ({settings["modules"]["grillplat"]}). Trace dump: ')
GrillPlatModule = importlib.import_module('grillplat.prototype')
error_event = f'An error occurred importing the [{settings["modules"]["grillplat"]}] platform module. The ' \
f'prototype module has been imported instead. This sometimes means that the module does not exist or is not ' \
f'properly named. Please run the configuration wizard again from the admin ' \
f'panel to fix this issue.'
errors.append(error_event)
write_errors(errors)
eventLogger.error(error_event)
controlLogger.error(error_event)
if settings['globals']['debug_mode']:
raise
try:
grill_platform = GrillPlatModule.GrillPlatform(platform_config)
except:
control['critical_error'] = True
write_control(control, direct_write=True, origin='control')
controlLogger.exception(f'Error occurred configuring grillplatform module ({settings["modules"]["grillplat"]}). Trace dump: ')
from grillplat.prototype import GrillPlatform # Simulated Library for controlling the grill platform
grill_platform = GrillPlatform(platform_config)
error_event = f'An error occurred configuring the [{settings["modules"]["grillplat"]}] platform object. The ' \
f'prototype module has been loaded instead. This sometimes means that the hardware is not ' \
f'connected properly, or the module is not configured. Please run the configuration wizard ' \
f'again from the admin panel to fix this issue.'
errors.append(error_event)
write_errors(errors)
eventLogger.error(error_event)
controlLogger.error(error_event)
if settings['globals']['debug_mode']:
raise
'''
Set up Probes Input Module
'''
try:
from probes.main import ProbesMain # Probe device library: loads probe devices and maps them to ports
probe_complex = ProbesMain(settings["probe_settings"]["probe_map"], settings['globals']['units'])
except:
controlLogger.exception(f'Error occurred loading probes modules. Trace dump: ')
#settings['probe_settings']['probe_map'] = default_probe_map(settings["probe_settings"]['probe_profiles'])
probe_complex = ProbesMain(settings["probe_settings"]["probe_map"], settings['globals']['units'], disable=True)
error_event = f'An error occurred loading the probes module(s). All probes & probe devices have been disabled. ' \
f'This sometimes means that the hardware is not connected properly, or the module is not configured correctly. ' \
f'Please run the configuration wizard again from the admin panel to fix this issue. '
errors.append(error_event)
write_errors(errors)
eventLogger.error(error_event)
controlLogger.error(error_event)
if settings['globals']['debug_mode']:
raise
# Get probe initialization errors and pass along to the frontend
probe_errors = probe_complex.get_errors()
if len(probe_errors) > 0:
for error in probe_errors:
eventLogger.error(error)
errors.append(error)
write_errors(errors)
# Get probe device info for frontend
probe_device_info = probe_complex.get_device_info()
write_generic_key('probe_device_info', probe_device_info)
'''
Set up Display Module
'''
try:
display_name = settings['modules']['display']
DisplayModule = importlib.import_module(f'display.{display_name}')
display_config = settings['display']['config'][display_name]
display_config['probe_info'] = get_probe_info(settings['probe_settings']['probe_map']['probe_info'])
disp_rotation = display_config.get('rotation', 0)
except:
controlLogger.exception(f'Error occurred loading the display module ({display_name}). Trace dump: ')
DisplayModule = importlib.import_module('display_none')
error_event = f'An error occurred loading the [{settings["modules"]["display"]}] display module. The ' \
f'"display_none" module has been loaded instead. This sometimes means that the hardware is ' \
f'not connected properly, or the module is not configured. Please run the configuration wizard ' \
f'again from the admin panel to fix this issue.'
errors.append(error_event)
write_errors(errors)
eventLogger.error(error_event)
controlLogger.error(error_event)
if settings['globals']['debug_mode']:
raise
try:
display_device = DisplayModule.Display(dev_pins=settings['platform']['devices'], buttonslevel=settings['platform']['buttonslevel'],
rotation=disp_rotation, units=units, config=display_config)
except:
controlLogger.exception(f'Error occurred configuring the display module ({settings["modules"]["display"]}). Trace dump: ')
from display.none import Display # Simulated Library for controlling the grill platform
display_device = Display(dev_pins=settings['platform']['devices'], buttonslevel=settings['platform']['buttonslevel'], rotation=disp_rotation, units=units, config={})
error_event = f'An error occurred configuring the [{settings["modules"]["display"]}] display object. The ' \
f'"display_none" module has been loaded instead. This sometimes means that the hardware is ' \
f'not connected properly, or the module is not configured. Please run the configuration wizard ' \
f'again from the admin panel to fix this issue.'
errors.append(error_event)
write_errors(errors)
eventLogger.error(error_event)
controlLogger.error(error_event)
if settings['globals']['debug_mode']:
raise
'''
Set up Distance (Hopper Level) Module
'''
try:
dist_name = settings['modules']['dist']
DistanceModule = importlib.import_module(f'distance.{dist_name}')
except:
controlLogger.exception(f'Error occurred loading the distance module ({dist_name}). Trace dump: ')
DistanceModule = importlib.import_module('distance.none')
error_event = f'An error occurred loading the [{settings["modules"]["dist"]}] distance module. The none ' \
f'module has been loaded instead. This sometimes means that the hardware is not connected ' \
f'properly, or the module is not configured. Please run the configuration wizard again from the ' \
f'admin panel to fix this issue.'
errors.append(error_event)
write_errors(errors)
eventLogger.error(error_event)
controlLogger.error(error_event)
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(
dev_pins=settings['platform']['devices'], empty=settings['pelletlevel']['empty'], full=settings['pelletlevel']['full'],
debug=settings['globals']['debug_mode'], random=True)
else:
dist_device = DistanceModule.HopperLevel(
dev_pins=settings['platform']['devices'], empty=settings['pelletlevel']['empty'], full=settings['pelletlevel']['full'],
debug=settings['globals']['debug_mode'])
except:
controlLogger.exception(f'Error occurred configuring the distance module ({dist_name}). Trace dump: ')
from distance.none import HopperLevel # Simulated Library for controlling the grill platform
dist_device = HopperLevel(
dev_pins=settings['platform']['devices'], empty=settings['pelletlevel']['empty'], full=settings['pelletlevel']['full'],
debug=settings['globals']['debug_mode'])
error_event = f'An error occurred configuring the [{settings["modules"]["dist"]}] distance object. The ' \
f'none module has been loaded instead. This sometimes means that the hardware is not ' \
f'connected properly, or the module is not configured. Please run the configuration wizard again ' \
f'from the admin panel to fix this issue.'
errors.append(error_event)
write_errors(errors)
eventLogger.error(error_event)
controlLogger.error(error_event)
# Get current hopper level and save it to the current pellet information
pelletdb = read_pellet_db()
pelletdb['current']['hopper_level'] = dist_device.get_level(override=True)
write_pellet_db(pelletdb)
eventLogger.info(f'Hopper Level Checked @ {pelletdb["current"]["hopper_level"]}%')
'''
*****************************************
Function Definitions
*****************************************
'''
def _start_fan(settings, duty_cycle=None):
"""
Check for DC Fan and set duty cycle when turning ON otherwise turn AC fan ON normally.
:param settings: Settings
:param duty_cycle: Duty Cycle to set. If not provided will be set to max_duty_cycle (dc_fan only)
"""
if settings['platform']['dc_fan']:
if duty_cycle is not None:
adjusted_dc = max(duty_cycle, settings['pwm']['min_duty_cycle'])
adjusted_dc = min(adjusted_dc, settings['pwm']['max_duty_cycle'])
else:
adjusted_dc = settings['pwm']['max_duty_cycle']
grill_platform.fan_on(adjusted_dc)
else:
grill_platform.fan_on()
def _process_system_commands(grill_platform):
# Setup access to the system command queue
system_commands = RedisQueue('control:systemq')
# Setup access to the system output queue
system_output = RedisQueue('control:systemo')
# Initialize variable for supported commands (only look for supported commands if we have something to process)
supported_cmds = []
while system_commands.length() > 0:
if supported_cmds == []:
# Get list of supported system commands
supported_cmds = grill_platform.supported_commands(None)['data']['supported_cmds']
command = system_commands.pop()
if command[0] in supported_cmds:
command_method = getattr(grill_platform, command[0])
result = command_method(command)
result['command'] = command
else:
result = {
'command' : command,
'result' : 'ERROR',
'message' : f'ERROR: Command [{command[0]}] is not supported with the current platform.',
'data' : {}
}
system_output.push(result)
def _work_cycle(mode, grill_platform, probe_complex, display_device, dist_device):
"""
Work Cycle Function
:param mode: Requested Mode
:param grill_platform: Grill Platform
:param probe_complex: ADC Device
:param display_device: Display Device
:param dist_device: Distance Device
"""
# Setup Process Monitor and Start
monitor = Process_Monitor('control', ['supervisorctl', 'restart', 'control'], timeout=30)
monitor.start_monitor()
# Precondition for entering into main control loop
status = 'Active'
# Setup Cycle Parameters
settings = read_settings()
control = read_control()
pelletdb = read_pellet_db()
control['hopper_check'] = True
write_control(control, direct_write=True, origin='control')
eventLogger.info(f'{mode} Mode started.')
# Pre-Loop Setup Recipe Triggers
if control['mode'] == "Recipe":
if mode in ['Smoke', 'Hold']:
recipe_trigger_set = False
# If requested, set Timer Trigger
if control['recipe']['step_data']['timer'] > 0:
# Set notify/trigger for timer
for index, item in enumerate(control['notify_data']):
if item['type'] == 'timer':
control['notify_data'][index]['req'] = True
timer_start = time.time()
control['timer']['start'] = timer_start
control['timer']['paused'] = 0
control['timer']['end'] = timer_start + (control['recipe']['step_data']['timer'] * 60)
control['timer']['shutdown'] = False
control['notify_data'][index]['shutdown'] = False
control['notify_data'][index]['keep_warm'] = False
recipe_trigger_set = True
# If requested, set Probe Temp Triggers
for probe, value in control['recipe']['step_data']['trigger_temps'].items():
if value > 0:
# Set notify/trigger for probe
for index, item in enumerate(control['notify_data']):
if item['type'] == 'probe' and item['label'] == probe:
control['notify_data'][index]['target'] = value
control['notify_data'][index]['req'] = True
recipe_trigger_set = True
break
if recipe_trigger_set:
write_control(control, direct_write=True, origin='control')
else:
eventLogger.warning('No trigger set for Hold/Smoke mode in recipe.')
# Get ON/OFF Switch state and set as last state
last = grill_platform.get_input_status()
# Set DC fan frequency if it has changed since init
if settings['platform']['dc_fan']:
pwm_frequency = settings['pwm']['frequency']
frequency_status = grill_platform.get_output_status()
if not pwm_frequency == frequency_status['frequency']:
grill_platform.set_pwm_frequency(pwm_frequency)
# Set Starting Configuration for Igniter, Fan , Auger
grill_platform.igniter_off()
grill_platform.auger_off()
if mode in ('Startup', 'Reignite', 'Smoke', 'Hold', 'Shutdown'):
_start_fan(settings)
grill_platform.power_on()
eventLogger.debug('Power ON, Fan ON, Igniter OFF, Auger OFF')
elif mode in ('Prime'):
grill_platform.fan_off()
grill_platform.power_on()
eventLogger.debug('Power ON, Fan OFF, Igniter OFF, Auger OFF')
else: # (Monitor, Manual)
grill_platform.fan_off()
grill_platform.power_off()
eventLogger.debug('Power OFF, Fan OFF, Igniter OFF, Auger OFF')
write_metrics(new_metric=True)
metrics = read_metrics()
metrics['mode'] = mode
metrics['smokeplus'] = control['s_plus']
metrics['primary_setpoint'] = control['primary_setpoint']
metrics['pellet_level_start'] = pelletdb['current']['hopper_level']
current_pellet_id = pelletdb['current']['pelletid']
pellet_brand = pelletdb['archive'][current_pellet_id]['brand']
pellet_type = pelletdb['archive'][current_pellet_id]['wood']
metrics['pellet_brand_type'] = f'{pellet_brand} {pellet_type}'
write_metrics(metrics)
if mode in ('Startup', 'Reignite'):
grill_platform.igniter_on()
eventLogger.debug('Igniter ON')
if mode in ('Startup', 'Reignite', 'Smoke', 'Hold', 'Prime'):
grill_platform.auger_on()
eventLogger.debug('Auger ON')
if mode in ('Startup', 'Reignite', 'Smoke'):
OnTime = settings['cycle_data']['SmokeOnCycleTime'] # Auger On Time (Default 15s)
OffTime = settings['cycle_data']['SmokeOffCycleTime'] + (settings['cycle_data']['PMode'] * 10) # Auger Off Time
CycleTime = OnTime + OffTime # Total Cycle Time
CycleRatio = RawCycleRatio = 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']['SmokeOnCycleTime']
write_metrics(metrics)
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 = RawCycleRatio = settings['cycle_data']['u_min'] # Ratio of OnTime to CycleTime
LidOpenDetect = False
LidOpenEventExpires = 0
'''
Load Controller Module (i.e. PID)
'''
try:
controller_type = settings['controller']['selected']
controller_module = importlib.import_module(f'controller.{controller_type}')
except:
controlLogger.exception(f'Error occurred loading controller module({controller_type}). Trace dump: ')
status = 'Inactive'
controllerCore = controller_module.Controller(settings['controller']['config'][controller_type], settings['globals']['units'], settings['cycle_data'])
controllerCore.set_target(control['primary_setpoint']) # Initialize with Set Point for grill
eventLogger.debug('On Time = ' + str(OnTime) + ', OffTime = ' + str(OffTime) + ', CycleTime = ' + str(
CycleTime) + ', CycleRatio = ' + str(CycleRatio))
if mode == 'Prime':
auger_rate = settings['globals']['augerrate']
prime_amount = control['prime_amount']
prime_duration = int(prime_amount / auger_rate) # Auger On Time = Prime Amount (Grams) / (Grams per Second)
OnTime = prime_duration
OffTime = 1 # Auger Off Time
CycleTime = OnTime + OffTime # Total Cycle Time
CycleRatio = RawCycleRatio = OnTime / CycleTime # Ratio of OnTime to CycleTime
''' Allow for the igniter to be turned on during prime mode - user selected '''
if settings['globals']['prime_ignition'] and control['next_mode'] == 'Startup':
grill_platform.igniter_on()
eventLogger.debug('Igniter ON')
# Get initial probe sensor data, temperatures
sensor_data = probe_complex.read_probes()
ptemp = list(sensor_data['primary'].values())[0] # Primary Temperature or the Pit Temperature
# Safety Controls
if mode in ('Startup', 'Reignite'):
raw_startup_temp = ptemp # This value is needed for the case when the grill starts hot and exit temp has been exceeded
control['safety']['startuptemp'] = int(max((ptemp * 0.9), settings['safety']['minstartuptemp']))
control['safety']['startuptemp'] = int(
min(control['safety']['startuptemp'], settings['safety']['maxstartuptemp']))
control['safety']['afterstarttemp'] = ptemp
write_control(control, direct_write=True, origin='control')
# Check if the temperature of the grill dropped below the startuptemp
elif mode in ('Smoke', 'Hold'):
if control['safety']['afterstarttemp'] < control['safety']['startuptemp']:
if control['safety']['reigniteretries'] == 0:
status = 'Inactive'
display_device.display_text('ERROR')
control['mode'] = 'Error'
control['updated'] = True
write_control(control, direct_write=True, origin='control')
send_notifications("Grill_Error_02", control, settings, pelletdb)
else:
control['safety']['reigniteretries'] -= 1
control['safety']['reignitelaststate'] = mode
status = 'Inactive'
display_device.display_text('Re-Ignite')
control['mode'] = 'Reignite'
control['updated'] = True
write_control(control, direct_write=True, origin='control')
send_notifications("Grill_Error_03", control, settings, pelletdb)
# Apply Smart Start Settings if Enabled
startup_timer = settings['startup']['duration']
if settings['startup']['smartstart']['enabled'] and mode in ('Startup', 'Reignite', 'Smoke'):
# If Startup, then save initial temperature & select the profile
if mode in ('Startup', 'Reignite'):
control['smartstart']['startuptemp'] = int(ptemp)
# Cycle through profiles, and set profile if startup temperature falls below the minimum temperature
for profile_selected in range(0, len(settings['startup']['smartstart']['temp_range_list'])):
if control['smartstart']['startuptemp'] < settings['startup']['smartstart']['temp_range_list'][profile_selected]:
control['smartstart']['profile_selected'] = profile_selected
write_control(control, direct_write=True, origin='control')
break # Break out of the loop
if profile_selected == len(settings['startup']['smartstart']['temp_range_list']) - 1:
control['smartstart']['profile_selected'] = profile_selected + 1
write_control(control, direct_write=True, origin='control')
# Apply the profile
profile_selected = control['smartstart']['profile_selected']
OnTime = settings['startup']['smartstart']['profiles'][profile_selected]['augerontime'] # Auger On Time (Default 15s)
OffTime = settings['cycle_data']['SmokeOffCycleTime'] + (settings['startup']['smartstart']['profiles'][profile_selected]['p_mode'] * 10) # Auger Off Time
CycleTime = OnTime + OffTime # Total Cycle Time
CycleRatio = RawCycleRatio = OnTime / CycleTime # Ratio of OnTime to CycleTime
startup_timer = settings['startup']['smartstart']['profiles'][profile_selected]['startuptime']
# Write Metrics
metrics['smart_start_profile'] = profile_selected
metrics['startup_temp'] = control['smartstart']['startuptemp']
metrics['p_mode'] = settings['startup']['smartstart']['profiles'][profile_selected]['p_mode']
metrics['auger_cycle_time'] = settings['startup']['smartstart']['profiles'][profile_selected]['augerontime']
write_metrics(metrics)
# Set the start time
start_time = time.time()
if mode == 'Startup':
control['startup_timestamp'] = start_time
write_control(control, direct_write=True, origin='control')
# Set time since toggle for temperature
temp_toggle_time = start_time
# Set time since toggle for checking ETA
eta_toggle_time = start_time
# Set time since toggle for auger
auger_toggle_time = start_time
# Set time since toggle for display
display_toggle_time = start_time
# Initializing Start Time for Smoke Plus Mode
sp_cycle_toggle_time = start_time
# Set time since toggle for hopper check
hopper_toggle_time = start_time
# Set time since fan speed update
fan_update_time = start_time
# Set Hold Mode Target Temp Boolean
target_temp_achieved = False
# Set Fan Ramping Boolean
pwm_fan_ramping = False
# Setup Display Data
status_data = {}
in_data = {}
# ============ Main Work Cycle ============
while status == 'Active':
now = time.time()
execute_control_writes()
control = read_control()
_process_system_commands(grill_platform)
# Check if new mode has been requested
if control['updated']:
break
# Check if user changed settings and reload
if control['settings_update']:
control['settings_update'] = False
write_control(control, direct_write=True, origin='control')
settings = read_settings()
# Change the log level if settings were updated
if settings['globals']['debug_mode']:
eventLogger.setLevel(logging.DEBUG)
else:
eventLogger.setLevel(logging.INFO)
if mode in ('Startup', 'Reignite', 'Smoke'):
OnTime = settings['cycle_data']['SmokeOnCycleTime'] # Auger On Time (Default 15s)
OffTime = settings['cycle_data']['SmokeOffCycleTime'] + (settings['cycle_data']['PMode'] * 10) # Auger Off Time
CycleTime = OnTime + OffTime # Total Cycle Time
CycleRatio = RawCycleRatio = OnTime / CycleTime # Ratio of OnTime to CycleTime
# Write Metrics (note these will overwrite the previous value)
metrics['p_mode'] = settings['cycle_data']['PMode']
metrics['auger_cycle_time'] = settings['cycle_data']['SmokeOnCycleTime']
write_metrics(metrics)
# Check if user changed hopper levels and update if required
if control['distance_update']:
empty = settings['pelletlevel']['empty']
full = settings['pelletlevel']['full']
dist_device.update_distances(empty, full)
control['distance_update'] = False
write_control(control, direct_write=True, origin='control')
# Check hopper level when requested or every 300 seconds
if control['hopper_check'] or (now - hopper_toggle_time) > 60:
pelletdb = read_pellet_db()
override = False
if control['hopper_check']:
control['hopper_check'] = False
write_control(control, direct_write=True, origin='control')
override = True
# Get current hopper level and save it to the current pellet information
pelletdb['current']['hopper_level'] = dist_device.get_level(override=override)
write_pellet_db(pelletdb)
hopper_toggle_time = now
eventLogger.info("Hopper Level Checked @ " + str(pelletdb['current']['hopper_level']) + "%")
# Check for update in ON/OFF Switch
if not settings['platform']['standalone'] and last != grill_platform.get_input_status():
last = grill_platform.get_input_status()
if not last:
eventLogger.info('Switch set to off, going to monitor mode.')
control['updated'] = True # Change mode
control['mode'] = 'Stop'
control['status'] = 'active'
write_control(control, direct_write=True, origin='control')
break
current_output_status = grill_platform.get_output_status()
if mode == 'Manual':
if control['manual']['change']:
if control['manual']['fan'] and not current_output_status['fan']:
grill_platform.fan_on()
eventLogger.debug('Fan ON')
elif not control['manual']['fan'] and current_output_status['fan']:
grill_platform.fan_off()
eventLogger.debug('Fan OFF')
if control['manual']['auger'] and not current_output_status['auger']:
grill_platform.auger_on()
eventLogger.debug('Auger ON')
elif not control['manual']['auger'] and current_output_status['auger']:
grill_platform.auger_off()
eventLogger.debug('Auger OFF')
if control['manual']['igniter'] and not current_output_status['igniter']:
grill_platform.igniter_on()
eventLogger.debug('Igniter ON')
elif not control['manual']['igniter'] and current_output_status['igniter']:
grill_platform.igniter_off()
eventLogger.debug('Igniter OFF')
if control['manual']['power'] and not current_output_status['power']:
grill_platform.power_on()
eventLogger.debug('Power ON')
elif not control['manual']['power'] and current_output_status['power']:
grill_platform.power_off()
eventLogger.debug('Power OFF')
if settings['platform']['dc_fan'] and control['manual']['fan'] and current_output_status['fan'] and \
not control['manual']['pwm'] == current_output_status['pwm']:
speed = control['manual']['pwm']
eventLogger.debug('PWM Speed: ' + str(speed) + '%')
grill_platform.set_duty_cycle(speed)
control['manual']['change'] = False
write_control(control, direct_write=True, origin='control')
# Change Auger State based on Cycle Time
if mode in ('Startup', 'Reignite', 'Smoke', 'Hold', 'Prime'):
# If Auger is OFF and time since toggle is greater than Off Time
if not current_output_status['auger'] and (now - auger_toggle_time) > (CycleTime * (1 - CycleRatio)):
grill_platform.auger_on()
auger_toggle_time = now
eventLogger.debug('Cycle Event: Auger On')
# Reset Cycle Time for HOLD Mode
if mode == 'Hold':
CycleRatio = RawCycleRatio = settings['cycle_data']['u_min'] if LidOpenDetect else controllerCore.update(ptemp)
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
eventLogger.debug('On Time = ' + str(OnTime) + ', OffTime = ' + str(
OffTime) + ', CycleTime = ' + str(CycleTime) + ', CycleRatio = ' + str(CycleRatio))
#publish pid info to mqtt if enabled
if settings['notify_services'].get('mqtt') != None and settings['notify_services']['mqtt']['enabled']:
pid_data = controllerCore.__dict__
pid_data['cycle_ratio'] = round(CycleRatio, 2)
check_notify(settings, control, pid_data=pid_data)
# If Auger is ON and time since toggle is greater than On Time
if current_output_status['auger'] and (now - auger_toggle_time) > (CycleTime * CycleRatio):
grill_platform.auger_off()
# Add auger ON time to the metrics
metrics['augerontime'] += now - auger_toggle_time
write_metrics(metrics)
# Set current last toggle time to now
auger_toggle_time = now
eventLogger.debug('Cycle Event: Auger Off')
# Grab current probe profiles if they have changed since the last loop.
if control['probe_profile_update']:
settings = read_settings()
control['probe_profile_update'] = False
write_control(control, direct_write=True, origin='control')
# Add new probe profiles to probe complex object
probe_complex.update_probe_profiles(settings['probe_settings']['probe_map']['probe_info'])
# Get temperatures from all probes
sensor_data = probe_complex.read_probes()
ptemp = list(sensor_data['primary'].values())[0] # Primary Temperature or the Pit Temperature
in_data['probe_history'] = sensor_data
in_data['primary_setpoint'] = control['primary_setpoint'] if mode == 'Hold' else 0
in_data['notify_targets'] = get_notify_targets(control['notify_data'])
# If Extended Data Mode is Enabled, Populate Extra Data Here
if settings['globals']['ext_data']:
in_data['ext_data'] = {}
in_data['ext_data']['CR'] = CycleRatio if 'CycleRatio' in locals() else 0
in_data['ext_data']['RCR'] = RawCycleRatio if 'RawCycleRatio' in locals() else 0
# Save current data to the database
write_current(in_data)
# Write Tr data to the database if in tuning mode
if control['tuning_mode']:
write_tr(in_data['probe_history']['tr'])
# Every 20 seconds, update ETA for any pending notifications
if (now - eta_toggle_time) > 20:
eta_toggle_time = time.time()
update_eta = True
else:
update_eta = False
# Check to see if there are any pending notifications (i.e. Timer / Temperature Settings)
control = check_notify(settings, control, in_data=in_data, pelletdb=pelletdb, grill_platform=grill_platform, update_eta=update_eta)
# Publish the cycle ratio to mqtt. Note if in HOLD mode it was already published.
if mode in ('Startup', 'Smoke') and 'CycleRatio' in locals():
pid_data = {}
pid_data['cycle_ratio'] = round(CycleRatio, 2)
check_notify(settings, control, pid_data=pid_data)
# Send Current Status / Temperature Data to Display Device every 0.5 second (Display Refresh)
if (now - display_toggle_time) > 0.5:
status_data['notify_data'] = control['notify_data'] # Get any flagged notifications
status_data['timer'] = control['timer'] # Get the timer information
status_data['s_plus'] = control['s_plus']
status_data['hopper_level'] = pelletdb['current']['hopper_level']
status_data['units'] = settings['globals']['units']
status_data['mode'] = mode
status_data['recipe'] = True if control['mode'] == 'Recipe' else False
status_data['start_time'] = start_time
status_data['start_duration'] = startup_timer
status_data['shutdown_duration'] = settings['shutdown']['shutdown_duration']
status_data['prime_duration'] = prime_duration if mode == 'Prime' else 0 # Enable Timer for Prime Mode
status_data['prime_amount'] = prime_amount if mode == 'Prime' else 0 # Enable Display of Prime Amount
status_data['lid_open_detected'] = LidOpenDetect if mode == 'Hold' else False
status_data['lid_open_endtime'] = LidOpenEventExpires if mode == 'Hold' else 0
status_data['p_mode'] = metrics.get('p_mode', None)
status_data['startup_timestamp'] = control['startup_timestamp']
if control['mode'] == 'Recipe':
status_data['recipe_paused'] = True if control['recipe']['step_data']['triggered'] and control['recipe']['step_data']['pause'] else False
else:
status_data['recipe_paused'] = False
status_data['outpins'] = {}
current = grill_platform.get_output_status() # Get current pin settings
for item in settings['platform']['outputs']:
try:
status_data['outpins'][item] = current[item]
except KeyError:
continue
# Send Data to Display
display_device.display_status(in_data, status_data)
# Save Status Data to Redis
write_status(status_data)
display_toggle_time = time.time() # Reset the display_toggle_time to current time
# Safety Controls
if mode in ('Startup', 'Reignite'):
control['safety']['afterstarttemp'] = ptemp
elif mode in ('Smoke', 'Hold'):
if ptemp < control['safety']['startuptemp']:
if control['safety']['reigniteretries'] == 0:
display_device.display_text('ERROR')
control['mode'] = 'Error'
control['updated'] = True
write_control(control, direct_write=True, origin='control')
send_notifications("Grill_Error_02", control, settings, pelletdb)
break
else:
control['safety']['reigniteretries'] -= 1
control['safety']['reignitelaststate'] = mode
display_device.display_text('Re-Ignite')
control['mode'] = 'Reignite'
control['updated'] = True
write_control(control, direct_write=True, origin='control')
send_notifications("Grill_Error_03", control, settings, pelletdb)
break
if mode in ('Smoke', 'Hold'):
# Check if target temperature has been achieved before utilizing Smoke Plus Mode
if mode == 'Hold' and ptemp >= control['primary_setpoint'] and not target_temp_achieved:
target_temp_achieved = True
# Check if a lid open event has occurred only after hold mode has been achieved
if target_temp_achieved and settings['cycle_data']['LidOpenDetectEnabled'] and (ptemp < (control['primary_setpoint'] * ((100 - settings['cycle_data']['LidOpenThreshold']) / 100))):
LidOpenDetect = True
grill_platform.auger_off()
_start_fan(settings)
auger_toggle_time = now
LidOpenEventExpires = now + settings['cycle_data']['LidOpenPauseTime']
target_temp_achieved = False
# Clear Lid Open Detect Event, Reset
if mode == 'Hold':
if LidOpenDetect and time.time() > LidOpenEventExpires:
LidOpenDetect = False
# If PWM Fan Control enabled set duty_cycle based on temperature
if (settings['platform']['dc_fan'] and mode == 'Hold' and control['pwm_control'] and
(now - fan_update_time) > settings['pwm']['update_time']):
fan_update_time = now
if ptemp > control['primary_setpoint']:
control['duty_cycle'] = settings['pwm']['min_duty_cycle']
write_control(control, direct_write=True, origin='control')
else:
# Cycle through profiles, and set duty cycle if setpoint temp is within range
for temp_profile in range(0, len(settings['pwm']['temp_range_list'])):
if ((control['primary_setpoint'] - ptemp) <=
settings['pwm']['temp_range_list'][temp_profile]):
duty_cycle = settings['pwm']['profiles'][temp_profile]['duty_cycle']
duty_cycle = max(duty_cycle, settings['pwm']['min_duty_cycle'])
duty_cycle = min(duty_cycle, settings['pwm']['max_duty_cycle'])
control['duty_cycle'] = duty_cycle
write_control(control, direct_write=True, origin='control')
break # Break out of the loop
if temp_profile == len(settings['pwm']['temp_range_list']) - 1:
control['duty_cycle'] = settings['pwm']['max_duty_cycle']
write_control(control, direct_write=True, origin='control')
# If in Smoke Plus Mode, Cycle the Fan
if (mode == 'Smoke' or (mode == 'Hold' and target_temp_achieved)) and control['s_plus']:
# If Temperature is > settings['smoke_plus']['max_temp']
# or Temperature is < settings['smoke_plus']['min_temp'] then turn on fan
if (ptemp > settings['smoke_plus']['max_temp'] or
ptemp < settings['smoke_plus']['min_temp']):
if not current_output_status['fan']:
_start_fan(settings, control['duty_cycle'])
eventLogger.debug('Smoke Plus: Over or Under Temp Fan ON')
elif (now - sp_cycle_toggle_time) > settings['smoke_plus']['on_time'] and current_output_status['fan']:
grill_platform.fan_off()
sp_cycle_toggle_time = now
eventLogger.debug('Smoke Plus: Fan OFF')
elif ((now - sp_cycle_toggle_time) > settings['smoke_plus']['off_time'] and
not current_output_status['fan']):
sp_cycle_toggle_time = now
if (settings['platform']['dc_fan'] and (mode == 'Smoke' or (mode == 'Hold' and not control['pwm_control'])) and
settings['smoke_plus']['fan_ramp']):
on_time = settings['smoke_plus']['on_time']
max_duty_cycle = settings['pwm']['max_duty_cycle']
min_duty_cycle = settings['pwm']['min_duty_cycle']
sp_duty_cycle = settings['smoke_plus']['duty_cycle']
grill_platform.pwm_fan_ramp(on_time, min_duty_cycle, max_duty_cycle * (sp_duty_cycle / 100))
pwm_fan_ramping = True
eventLogger.debug('Smoke Plus: Fan Ramping Up')
else:
_start_fan(settings, control['duty_cycle'])
eventLogger.debug('Smoke Plus: Fan ON')
# If Smoke Plus was disabled when fan is OFF return fan to ON
elif not current_output_status['fan'] and not control['s_plus']:
_start_fan(settings, control['duty_cycle'])
eventLogger.debug('Smoke Plus: Fan Returned to On')
# If Smoke Plus was disabled while fan was ramping return it to the correct duty cycle
elif (settings['platform']['dc_fan'] and current_output_status['pwm'] != control['duty_cycle'] and not
control['s_plus'] and pwm_fan_ramping):
pwm_fan_ramping = False
grill_platform.set_duty_cycle(control['duty_cycle'])
eventLogger.debug('Smoke Plus: Fan Returned to ' + str(control['duty_cycle']) + '% duty cycle')
# Set Fan Duty Cycle based on Average Grill Temp Using Profile
elif settings['platform']['dc_fan'] and control['pwm_control'] and current_output_status['pwm'] != control['duty_cycle']:
grill_platform.set_duty_cycle(control['duty_cycle'])
eventLogger.debug('Temp Fan Control: Fan Set to ' + str(control['duty_cycle']) + '% duty cycle')
# If PWM Fan Control is turned off check current Duty Cycle and set back to max_duty_cycle if required
elif (settings['platform']['dc_fan'] and not control['pwm_control'] and current_output_status['pwm'] !=
settings['pwm']['max_duty_cycle']):
control['duty_cycle'] = settings['pwm']['max_duty_cycle']
write_control(control, direct_write=True, origin='control')
grill_platform.set_duty_cycle(control['duty_cycle'])
eventLogger.debug('Temp Fan Control: Set to OFF, Fan Returned to Max Duty Cycle')
# Write History & Issue Heartbeat after 3 seconds has passed
if (now - temp_toggle_time) > 3:
temp_toggle_time = time.time()
ext_data = True if settings['globals']['ext_data'] else False # If passing in extended data, set to True
write_history(in_data, ext_data=ext_data)
monitor.heartbeat() # Issue a heartbeat for the process monitor
# Check if startup time has elapsed since startup/reignite mode started or if exit temperature has been achieved
if mode in ('Startup', 'Reignite'):
if settings['startup']['smartstart']['enabled']:
profile_selected = control['smartstart']['profile_selected']
startup_timer = settings['startup']['smartstart']['profiles'][profile_selected]['startuptime']
# Check case where the grill starts hot (perhaps due to previous failure)
if raw_startup_temp >= settings['startup']['smartstart']['exit_temp']:
exit_temp = 0 # Force ignite
else:
exit_temp = settings['startup']['smartstart']['exit_temp']
else:
startup_timer = settings['startup']['duration']
exit_temp = settings['startup']['startup_exit_temp']
# Check case where the grill starts hot (perhaps due to previous failure)
if raw_startup_temp >= settings['startup']['startup_exit_temp']:
exit_temp = 0 # Force ignite
else:
exit_temp = settings['startup']['startup_exit_temp']
if (now - start_time) > startup_timer:
break
if (exit_temp != 0) and (ptemp >= exit_temp):
break
# Check if shutdown time has elapsed since shutdown mode started
if mode == 'Shutdown' and (now - start_time) > settings['shutdown']['shutdown_duration']:
break
# Check if prime time has elapsed
if mode == 'Prime' and (now - start_time) > prime_duration:
break
# Max Temp Safety Control
if ptemp > settings['safety']['maxtemp']:
display_device.display_text('ERROR')
control['mode'] = 'Error'
control['updated'] = True
write_control(control, direct_write=True, origin='control')
send_notifications("Grill_Error_01", control, settings, pelletdb)
break
# End of Loop Recipe Check
if control['mode'] == 'Recipe':
# If a recipe event was triggered and no pause is requested
if control['recipe']['step_data']['triggered'] and not control['recipe']['step_data']['pause']:
# If a notification / message was requested
if control['recipe']['step_data']['notify']:
send_notifications('Recipe_Step_Message', control, settings, pelletdb)
# Exit the main work cycle
break
# If a recipe event was triggered and a pause was requested
elif control['recipe']['step_data']['triggered'] and control['recipe']['step_data']['pause']:
# If notification / message was requested, notify and clear notification
if control['recipe']['step_data']['notify']:
send_notifications('Recipe_Step_Message', control, settings, pelletdb)
control['recipe']['step_data']['notify'] = False
write_control(control, direct_write=True, origin='control')
# Continue until 'pause' variable is cleared
time.sleep(0.05)
# *********
# END Mode Loop
# *********
# Clean-up and Exit
grill_platform.auger_off()
grill_platform.igniter_off()
eventLogger.debug('Auger OFF, Igniter OFF')
if mode in ('Shutdown', 'Monitor', 'Manual', 'Prime'):
grill_platform.fan_off()
grill_platform.power_off()
eventLogger.debug('Fan OFF, Power OFF')
if mode in ('Startup', 'Reignite'):
control['safety']['afterstarttemp'] = ptemp
write_control(control, direct_write=True, origin='control')
eventLogger.info(f'{mode} mode ended.')
# Save Pellets Used
pelletdb = read_pellet_db()
pelletdb['current']['est_usage'] += metrics['augerontime'] * settings['globals']['augerrate']
write_pellet_db(pelletdb)
# Log the end time
metrics['endtime'] = time.time() * 1000
metrics['pellet_level_end'] = pelletdb['current']['hopper_level']
write_metrics(metrics)
monitor.stop_monitor()
if status_data != {}:
status_data['mode'] = control['mode']
display_device.display_status(in_data, status_data)
return ()
def _next_mode(next_mode, setpoint=0):
execute_control_writes()
control = read_control()
# If no other request, then transition to next mode, otherwise exit
if not control['updated']:
control['mode'] = next_mode
control['primary_setpoint'] = setpoint if next_mode == 'Hold' else 0 # If next mode is 'Hold'
control['updated'] = True
write_control(control, direct_write=True, origin='control')
return control
def _recipe_mode(grill_platform, probe_complex, display_device, dist_device, start_step=0):
"""
Recipe Mode Control
:param grill_platform: Grill Platform
:param probe_complex: ADC Device
:param display_device: Display Device
:param dist_device: Distance Device
"""
settings = read_settings()
eventLogger.info('Recipe Mode started.')
# Find Recipe File
control = read_control()
recipe_file = control['recipe']['filename']