forked from nebhead/PiFire
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.py
More file actions
executable file
·1758 lines (1468 loc) · 51 KB
/
common.py
File metadata and controls
executable file
·1758 lines (1468 loc) · 51 KB
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 Common Library
# *****************************************
#
# Description: This library provides functions that are common to
# both app.py and control.py
#
# *****************************************
# *****************************************
# Imported Libraries
# *****************************************
import time
import datetime
import os
import io
import json
import math
import redis
import uuid
import random
import zipfile
import pathlib
import tempfile
import shutil
HISTORY_FOLDER = './history/' # Path to historical cook files
# *****************************************
# Functions
# *****************************************
# Setup Command / Status database connection
cmdsts = redis.StrictRedis('localhost', 6379, charset="utf-8", decode_responses=True)
def default_settings():
settings = {}
settings['versions'] = {
'server' : "1.3.5",
'cookfile' : "1.0.1" # Current cookfile format version
}
settings['history_page'] = {
'minutes' : 15, # Sets default number of minutes to show in history
'clearhistoryonstart' : True, # Clear history when StartUp Mode selected
'autorefresh' : 'on', # Sets history graph to auto refresh ('live' graph)
'datapoints' : 60 # Number of data points to show on the history chart
}
settings['probe_settings'] = {
'probe_profiles' : _default_probe_profiles(),
'probes_enabled' : [1,1,1],
'probe_sources' : ['ADC0', 'ADC1', 'ADC2', 'ADC3'], # Probe sources can be ADC0-3 or max31865
'probe_options' : ['ADC0', 'ADC1', 'ADC2', 'ADC3'] # Probe source options (max31865 can be added but requires spi-dev to be installed and control.py to be restarted to load the module)
}
settings['globals'] = {
'grill_name' : '',
'debug_mode' : False,
'page_theme' : 'light',
'triggerlevel' : 'LOW',
'buttonslevel' : 'HIGH',
'disp_rotation' : 0,
'shutdown_timer' : 60,
'startup_timer' : 240,
'auto_power_off' : False,
'four_probes' : False,
'dc_fan': False,
'standalone': True,
'units' : 'F',
'augerrate' : 0.3, # (grams per second) default auger load rate is 10 grams / 30 seconds
'first_time_setup' : True, # Set to True on first setup, to run wizard on load
}
settings['apprise'] = {
'enabled': False,
'locations': {} # list of locations
}
settings['ifttt'] = {
'enabled': False,
'APIKey': '' # API Key for WebMaker IFTTT App notification
}
settings['pushbullet'] = {
'enabled': False,
'APIKey': '', # API Key for PushBullet notifications
'PublicURL': '' # Used in PushBullet notifications
}
settings['pushover'] = {
'enabled': False,
'APIKey': '', # API Key for Pushover notifications
'UserKeys': '', # Comma-separated list of user keys
'PublicURL': '' # Used in Pushover notifications
}
settings['onesignal'] = {
'enabled': False,
'uuid' : _generate_uuid(),
'app_id' : '',
'devices' : {}
}
settings['influxdb'] = {
'enabled': False,
'url': '',
'token': '',
'org': '',
'bucket': ''
}
settings['probe_types'] = {
'grill1type' : 'PT-1000-OEM',
'grill2type' : 'TWPS00',
'probe1type' : 'TWPS00',
'probe2type' : 'TWPS00'
}
settings['grill_probe_settings'] = {
'grill_probes': _default_grill_probes(),
'grill_probe' : 'grill_probe1',
'grill_probe_enabled' : [1,0,0]
}
settings['outpins'] = {
'power' : 4,
'auger' : 14,
'fan' : 15,
'igniter' : 18,
'dc_fan' : 26,
'pwm' : 13
}
settings['inpins'] = { 'selector' : 17 }
settings['dev_pins'] = { # Device Pin Assignment
'input': {
'up_clk': 16, # Up Button or CLK for encoder
'enter_sw' : 21, # Enter Button or SW for encoder
'down_dt' : 20 # Down Button or DT for encoder
},
'display': {
'led' : 5, # ILI9341: LED - ST7789: BL
'dc' : 24, # ILI9341: DC - ST7789: DC
'rst' : 25 # ILI9341: RST - ST7789: RST
},
'distance': {
'trig': 23, # For hcsr04
'echo' : 27 # For hcsr04
},
}
# PID controller based on proportional band in standard PID form
# https://en.wikipedia.org/wiki/PID_controller#Ideal_versus_standard_PID_form
# u = Kp (e(t)+ 1/Ti INT + Td de/dt)
# PB = Proportional Band
# Ti = Goal of eliminating in Ti seconds
# Td = Predicts error value at Td in seconds
settings['cycle_data'] = {
'PB' : 60.0,
'Ti' : 180.0,
'Td' : 45.0,
'HoldCycleTime' : 20,
'SmokeCycleTime' : 15,
'PMode' : 2, # http://tipsforbbq.com/Definition/Traeger-P-Setting
'u_min' : 0.15,
'u_max' : 1.0,
'center' : 0.5
}
settings['keep_warm'] = {
'temp' : 165,
's_plus' : False
}
settings['smoke_plus'] = {
'enabled' : False, # Sets default Enable/Disable (True = Enabled, False = Disabled)
'min_temp' : 160, # Minimum temperature to cycle fan on/off
'max_temp' : 220, # Maximum temperature to cycle fan on/off
'on_time' : 5, # Number of seconds the fan will remain ON
'off_time' : 5, # Number of seconds the fan will remain OFF
'duty_cycle' : 75, # Duty cycle that will be used during fan ramping. 20-100%
'fan_ramp' : False # If enabled fan will ramp up to speed instead of just turning on
}
settings['pwm'] = {
'pwm_control': False,
'update_time' : 10,
'frequency' : 30, # PWM Fan Frequency. This may vary with different fans
'min_duty_cycle' : 20, # This is the minimum duty cycle that can be set. Some fans stall below a certain speed
'max_duty_cycle' : 100, # This is the maximum duty cycle that can be set. Can limit fans that are overpowered
'temp_range_list' : [3, 7, 10, 15], # Temp Bands for Each Profile
'profiles' : [
{
'duty_cycle' : 20 # Duty Cycle to set fan
},
{
'duty_cycle' : 35
},
{
'duty_cycle' : 50
},
{
'duty_cycle' : 75
},
{
'duty_cycle' : 100
}
]
}
settings['safety'] = {
'minstartuptemp' : 75, # User Defined. Minimum temperature allowed for startup.
'maxstartuptemp' : 100, # User Defined. Take this value if the startup temp is higher than maxstartuptemp
'maxtemp' : 550, # User Defined. If temp exceeds value in any mode, shut off. (including monitor mode)
'reigniteretries' : 1 # Number of tries to reignite grill if it has gone below the safe temp (0 to disable)
}
settings['pelletlevel'] = {
'warning_enabled' : True,
'warning_level' : 25, # Percent to begin low pellet warning notifications
'warning_time' : 20, # Number of minutes to check for low pellets and send notification
'empty' : 22, # Number of centimeters from the sensor that indicates empty
'full' : 4 # Number of centimeters from the sensor that indicates full
}
settings['modules'] = {
'grillplat' : 'prototype',
'adc' : 'prototype',
'display' : 'prototype',
'dist' : 'prototype'
}
settings['lastupdated'] = {
'time' : math.trunc(time.time())
}
settings['smartstart'] = {
'enabled' : True,
'temp_range_list' : [60, 80, 90], # Min Temps for Each Profile
'profiles' : [
{
'startuptime' : 360,
'augerontime' : 15,
'p_mode' : 0
},
{
'startuptime' : 360,
'augerontime' : 15,
'p_mode' : 1
},
{
'startuptime' : 240,
'augerontime' : 15,
'p_mode' : 3
},
{
'startuptime' : 240,
'augerontime' : 15,
'p_mode' : 5
}
]
}
settings['start_to_mode'] = {
'after_startup_mode' : 'Smoke',
'grill1_setpoint' : 165 # If Hold, set the setpoint
}
settings['dashboard'] = {
'current' : 'Default',
'dashboards' : [
{ 'name' : 'Default',
'friendly_name' : 'Default/Classic Dashboard',
'html_name' : 'dash_default.html'
},
{ 'name' : 'Modern',
'friendly_name' : 'Modern Dashboard',
'html_name' : 'dash_default.html'
},
]
}
return settings
def default_control():
control = {}
control['updated'] = True
control['mode'] = 'Stop'
control['next_mode'] = 'Stop'
settings = read_settings()
control['s_plus'] = settings['smoke_plus']['enabled'] # Smoke-Plus Feature Enable/Disable
control['pwm_control'] = settings['pwm']['pwm_control'] # Temp Fan Control Enable/Disable
control['duty_cycle'] = settings['pwm']['max_duty_cycle'] # Set PWM Fan Duty Cycle
control['hopper_check'] = False # Trigger a synchronous hopper level check
control['recipe'] = ''
control['status'] = ''
control['probe_profile_update'] = False
control['settings_update'] = False
control['distance_update'] = False
control['units_change'] = False # Used to indicate that a units change has been requested
control['tuning_mode'] = False # Used to set tuning mode enabled so Tr values will be recorded (False by default)
control['safety'] = {
'startuptemp' : 0, # Set by control function at startup
'afterstarttemp' : 0, # Set by control function during startup
'reigniteretries' : settings['safety']['reigniteretries'], # Set by user to attempt a re-ignite when the grill drops below a certain temp
'reignitelaststate' : 'Smoke' # Set by control function to remember the last state we were in when the temp dropped below safety levels
}
control['setpoints'] = {
'grill' : 0,
'probe1' : 0,
'probe2' : 0,
'grill_notify' : 0
}
control['notify_req'] = {
'grill' : False,
'probe1' : False,
'probe2' : False,
'timer' : False
}
control['notify_data'] = {
'hopper_low' : False,
'p1_shutdown' : False,
'p2_shutdown' : False,
'timer_shutdown' : False,
'p1_keep_warm' : False,
'p2_keep_warm' : False,
'timer_keep_warm' : False
}
control['timer'] = {
'start' : 0,
'paused' : 0,
'end' : 0,
'shutdown' : False
}
control['manual'] = {
'change' : False,
'fan' : False,
'auger' : False,
'igniter' : False,
'power' : False,
'pwm' : 100
}
control['errors'] = []
control['smartstart'] = {
'startuptemp' : 0,
'profile_selected' : 0
}
control['prime_amount'] = 10 # Default Prime Amount in Grams
return(control)
"""
List of Tuples ('metric_key', default_value)
- This structure will be used to build the default metrics structure, and to export the data easily
- To add a metric, simply add a tuple to this list.
"""
metrics_items = [
('id', 0),
('starttime', 0),
('starttime_c', 0), # Converted Start Time
('endtime', 0),
('endtime_c', 0), # Converted End Time
('timeinmode', 0), # Calculated Time in Mode
('mode', ''),
('augerontime', 0),
('augerontime_c', 0), # Converted Auger On Time
('estusage_m', ''), # Estimated pellet usage in metric (grams)
('estusage_i', ''), # Estimated pellet usage in pounds (and ounces)
('fanontime', 0),
('fanontime_c', 0), # Converted Fan On Time
('smokeplus', True),
('grill_settemp', 0),
('smart_start_profile', 0), # Smart Start Profile Selected
('startup_temp', 0), # Smart Start Start Up Temp
('p_mode', 0), # P_mode selected
('auger_cycle_time', 0), # Auger Cycle Time
('pellet_level_start', 0), # Pellet Level at the begining of this mode
('pellet_level_end', 0), # Pellet Level at the end of this mode
('pellet_brand_type', '') # Pellet Brand and Wood Type
]
def default_metrics():
metrics = {}
for index in range(0, len(metrics_items)):
metrics[metrics_items[index][0]] = metrics_items[index][1]
return(metrics)
def default_recipes():
recipes = {}
recipes['321ribs'] = {
'metadata': {
'display_name': '3-2-1 Baby Back Ribs',
'image': ''
},
'steps' : {
'step_00': {
'smoke' : True, # Start with smoke temp for grill
'timer' : 180, # Go for three hours (180 minutes)
'notify' : True,
'description' : 'Set grill to smoke at 165F.'
},
'step_01': {
'grill_temp' : 275,
'notify' : True,
'timer' : 120, # Go for two hours (120 minutes)
'description' : 'Wrap ribs and increase grill temp to 275F'
},
'step_02': {
'grill_temp' : 300,
'timer' : 60,
'notify' : True,
'description' : 'Un-wrap ribs and increase grill temp to 300F'
}
}
}
return recipes
def default_pellets():
pelletdb = {}
now = str(datetime.datetime.now())
now = now[0:19] # Truncate the microseconds
ID = ''.join(filter(str.isalnum, str(datetime.datetime.now())))
pelletdb['current'] = {
'pelletid' : ID, # Pellet ID for the profile currently loaded
'hopper_level' : 100, # Percentage of pellets remaining
'date_loaded' : now, # Date that current pellets loaded
'est_usage' : 0 # Estimated usage since loading (use auger load rate, and auger on time)
}
pelletdb['woods'] = [
'Alder',
'Almond',
'Apple',
'Apricot',
'Blend',
'Competition',
'Cherry',
'Chestnut',
'Hickory',
'Lemon',
'Maple',
'Mesquite',
'Mulberry',
'Nectarine',
'Oak',
'Orange',
'Peach',
'Pear',
'Plum',
'Walnut'
]
pelletdb['brands'] = ['Generic', 'Custom']
pelletdb['archive'] = {
ID : {
'id' : ID,
'brand' : 'Generic',
'wood' : 'Alder',
'rating' : 4,
'comments' : 'This is a placeholder profile. Alder is generic and used in almost all pellets, '
'regardless of the wood type indicated on the packaging. It tends to burn '
'consistently and produces a mild smoke.',
}
}
pelletdb['log'] = {
now : ID
}
pelletdb['lastupdated'] = {
'time' : math.trunc(time.time())
}
return pelletdb
def _default_probe_profiles():
probe_profiles = {}
probe_profiles['TWPS00'] = {
'Vs' : 3.28, # Vs = Voltage Source input to resistor divider
'Rd' : 10000, # Divider Resistance Ohms (Default 10k Ohm)
'A' : 7.3431401e-4, # Coefficient A for SHH # from HeaterMeter?
'B' : 2.1574370e-4, # Coefficient B for SHH
'C' : 9.5156860e-8, # Coefficient C for SHH
'name' : 'Thermoworks-Pro-Series-HeaterMeter'
}
probe_profiles['ET73-HM'] = {
'Vs' : 3.28, # Vs = Voltage Source input to resistor divider
'Rd' : 10000, # Divider Resistance Ohms (Default 10k Ohm)
'A' : 2.4723753e-04, # Coefficient A for SHH # from HeaterMeter?
'B' : 2.3402251e-04, # Coefficient B for SHH
'C' : 1.3879768e-07, # Coefficient C for SHH
'name' : 'ET-73-Heatermeter'
}
probe_profiles['iGrill-HM'] = {
'Vs' : 3.28, # Vs = Voltage Source input to resistor divider
'Rd' : 10000, # Divider Resistance Ohms (Default 10k Ohm)
'A' : 0.7739251279e-3, # Coefficient A for SHH # from HeaterMeter?
'B' : 2.088025997e-4, # Coefficient B for SHH
'C' : 1.154400438e-7, # Coefficient C for SHH
'name' : 'iGrill-Heatermeter'
}
probe_profiles["PT-1000-OEM"] = {
"Vs": 3.28,
"Rd": 10000,
"A": 0.04136906456,
"B": -0.00677987613,
"C": 2.760294589e-05,
"name": "PT-1000-Grill-Probe-OEM" # This profile was for the original probe on my Traeger
}
probe_profiles["PT-1000-PiFire"] = {
"Vs": 3.28,
"Rd": 10000,
"A": 0.05469905897345206,
"B": -0.009473055040089443,
"C": 4.3768560703857386e-5,
"name": "PT-1000-Grill-Probe-PiFire" # This profile is for a replacement PT-1000 grill probe
}
probe_profiles['ET73-SP'] = {
'Vs' : 3.28, # Vs = Voltage Source input to resistor divider
'Rd' : 10000, # Divider Resistance Ohms (Default 10k Ohm)
# from: https://github.com/skyeperry1/Maverick-ET-73-Meat-Probe-Arduino-Library/blob/master/ET73.h
'A' : 2.3067434E-4,
'B' : 2.3696596E-4,
'C' : 1.2636414E-7,
'name' : 'ET-73-skyeperry1'
}
return probe_profiles
def _default_grill_probes():
grill_probes = {}
grill_probes['grill_probe1'] = {
'name' : 'Grill Probe 1'
}
grill_probes['grill_probe2'] = {
'name' : 'Grill Probe 2'
}
grill_probes['grill_probe3'] = {
'name' : 'Avg Grill Probes'
}
return grill_probes
def _default_cookfilestruct():
settings = read_settings()
cookfilestruct = {}
cookfilestruct['metadata'] = {
'title' : '',
'starttime' : '',
'endtime' : '',
'units' : settings['globals']['units'],
'thumbnail' : '', # UUID of the thumbnail for this cook file - found in assets
'id' : _generate_uuid(),
'version' : settings['versions']['cookfile'] # PiFire Cook File Version
}
cookfilestruct['graph_data'] = {
"time_labels" : [],
"grill1_temp" : [],
"probe1_temp" : [],
"probe2_temp" : [],
"grill1_setpoint" : [],
"probe1_setpoint" : [],
"probe2_setpoint" : []
}
cookfilestruct['graph_labels'] = {
"grill1_label" : "Grill",
"probe1_label" : "Probe 1",
"probe2_label" : "Probe 2"
}
cookfilestruct['events'] = []
cookfilestruct['comments'] = []
cookfilestruct['assets'] = []
return cookfilestruct
def _generate_uuid():
"""
Generate a uuid based on mac address and random int
:return: A string uuid
"""
node = uuid.getnode()
rand_int = random.randint(100, 200)
generated_uuid = uuid.uuid1(node + rand_int)
return str(generated_uuid)
def read_control(flush=False):
"""
Read Control from Redis DB
:param flush: True to clean control. False otherwise
:return: control
"""
global cmdsts
try:
if flush:
# Remove all control structures in Redis DB (not history or current)
cmdsts.delete('control:general')
# The following set's no persistence so that we don't get writes to the disk / SDCard
cmdsts.config_set('appendonly', 'no')
cmdsts.config_set('save', '')
control = default_control()
write_control(control)
else:
control = json.loads(cmdsts.get('control:general'))
except:
control = default_control()
return(control)
def write_control(control):
"""
Read Control from Redis DB
:param control: Control
"""
global cmdsts
cmdsts.set('control:general', json.dumps(control))
def read_errors(flush=False):
"""
Read Errors from Redis DB
:param flush: True to clear errors. False otherwise
:return: errors
"""
global cmdsts
try:
if flush:
# Remove all error structures in Redis DB
cmdsts.delete('errors')
errors = []
write_errors(errors)
else:
errors = json.loads(cmdsts.get('errors'))
except:
errors = ['Unable to reach Redis database. You may need to reinstall PiFire or enable redis-server.']
return(errors)
def write_errors(errors):
"""
Write Errors to Redis DB
:param errors: Errors
"""
global cmdsts
cmdsts.set('errors', json.dumps(errors))
def read_metrics(all=False):
"""
Read Metrics from Redis DB
:param all: True to read entire list. False for top of list.
"""
global cmdsts
if not(cmdsts.exists('metrics:general')):
write_metrics(flush=True)
return([])
if all:
# Read entire list of Metrics
llength = cmdsts.llen('metrics:general')
metrics = cmdsts.lrange('metrics:general', 0, -1)
metrics_list = []
for index in range(0, llength):
metrics_list.append(json.loads(metrics[index]))
return(metrics_list)
# Read current Metrics Record (i.e. top of the list)
return(json.loads(cmdsts.lindex('metrics:general', -1)))
def write_metrics(metrics=default_metrics(), flush=False, new_metric=False):
"""
Write metrics to Redis DB
:param metrics: Metrics Data
:param flush: True to clear metrics. False otherwise
:param new_metric:
"""
global cmdsts
if(flush or not(cmdsts.exists('metrics:general'))):
# Remove all metrics structures in Redis DB
cmdsts.delete('metrics:general')
# The following set's no persistence so that we don't get writes to the disk / SDCard
cmdsts.config_set('appendonly', 'no')
cmdsts.config_set('save', '')
if not flush:
new_metric=True
else:
return
if new_metric:
metrics['starttime'] = time.time() * 1000
metrics['id'] = _generate_uuid()
cmdsts.rpush('metrics:general', json.dumps(metrics))
else:
cmdsts.rpop('metrics:general')
cmdsts.rpush('metrics:general', json.dumps(metrics))
def read_settings(filename='settings.json'):
"""
Read Settings from file
:param filename: Filename to use (default settings.json)
"""
# Get latest settings format
settings = default_settings()
try:
json_data_file = os.fdopen(os.open(filename, os.O_RDONLY))
json_data_string = json_data_file.read()
settings_struct = json.loads(json_data_string)
json_data_file.close()
except(IOError, OSError):
# Default settings
settings = default_settings()
# Issue with reading states JSON, so create one/write new one
write_settings(settings)
return(settings)
except(ValueError):
# A ValueError Exception occurs when multiple accesses collide, this code attempts a retry.
event = 'ERROR: Value Error Exception - JSONDecodeError reading settings.json'
write_log(event)
json_data_file.close()
# Retry Reading Settings
settings_struct = read_settings(filename=filename)
# Overlay the read values over the top of the default settings
# This ensures that any NEW fields are captured.
update_settings = False # set flag in case an update needs to be written back
# If default version is different from what is currently saved, update version in saved settings
if 'versions' not in settings_struct.keys():
settings_struct['versions'] = {
'server' : settings['versions']['server']
}
update_settings = True
elif settings_struct['versions']['server'] != settings['versions']['server']:
settings_struct['versions']['server'] = settings['versions']['server']
update_settings = True
# Prevent the wizard from popping up on existing installations
if 'first_time_setup' not in settings_struct['globals'].keys():
settings_struct['globals']['first_time_setup'] = False
update_settings = True
print(' === DEBUG: Setting First Time Setup to False!! ')
for key in settings.keys():
if key in settings_struct.keys():
for subkey in settings[key].keys():
if subkey not in settings_struct[key].keys():
update_settings = True
settings[key].update(settings_struct.get(key, {}))
else:
update_settings = True
if update_settings or filename != 'settings.json': # If any of the keys were added, then write back the changes
write_settings(settings)
#print('key mismatch - update flag set')
return(settings)
def write_settings(settings):
"""
Write all settings to JSON file
:param settings: Settings
"""
settings['lastupdated']['time'] = math.trunc(time.time())
json_data_string = json.dumps(settings, indent=2, sort_keys=True)
with open("settings.json", 'w') as settings_file:
settings_file.write(json_data_string)
def read_recipes():
"""
Read RecipeDB from File
:return: Recipes
"""
# Read all lines of recipes.json into a list(array)
try:
json_data_file = os.fdopen(os.open('recipes.json', os.O_RDONLY))
#json_data_file = open("recipes.json", "r")
json_data_string = json_data_file.read()
recipes = json.loads(json_data_string)
json_data_file.close()
except(IOError, OSError):
# Issue with reading JSON, so create one/write new one
recipes = default_recipes()
write_recipes(recipes)
return(recipes)
def write_recipes(recipes):
"""
Write RecipeDB to JSON file
:param recipes: Recipes
"""
json_data_string = json.dumps(recipes)
with open("recipes.json", 'w') as recipes_file:
recipes_file.write(json_data_string)
def read_pellet_db(filename='pelletdb.json'):
"""
Read Pellet DataBase from file
:param filename: Filename to use (default pelletdb.json)
"""
pelletdb = default_pellets()
# Read all lines of pelletdb.json into a list(array)
try:
json_data_file = os.fdopen(os.open(filename, os.O_RDONLY))
json_data_string = json_data_file.read()
pelletdb_struct = json.loads(json_data_string)
json_data_file.close()
except(IOError, OSError):
# Issue with reading JSON, so create one/write new one
pelletdb = default_pellets()
write_pellet_db(pelletdb)
return(pelletdb)
# Overlay the read values over the top of the default values
# This ensures that any NEW fields are captured.
update_db = False # set flag in case an update needs to be written back
for key in pelletdb.keys():
if key in pelletdb_struct.keys():
pelletdb[key] = pelletdb_struct[key].copy()
else:
update_db = True
# If any of the keys were added or if restoring from file, then write back the changes
if update_db or filename != 'pelletdb.json':
write_pellet_db(pelletdb)
return(pelletdb)
def write_pellet_db(pelletdb):
"""
Write Pellet DataBase to JSON file
:param pelletdb: Pellet Database
"""
json_data_string = json.dumps(pelletdb, indent=2, sort_keys=True)
with open("pelletdb.json", 'w') as json_file:
json_file.write(json_data_string)
def read_log(legacy=True):
"""
Read event.log and populate an array of events.
if legacy=true:
:return: (event_list, num_events)
if legacy=false:
:return: (event_list, num_events)
"""
# Read all lines of events.log into a list(array)
try:
with open('/tmp/events.log') as event_file:
event_lines = event_file.readlines()
event_file.close()
# If file not found error, then create events.log file
except(IOError, OSError):
event_file = open('/tmp/events.log', "w")
event_file.close()
event_lines = []
# Initialize event_list list
event_list = []
# Get number of events
num_events = len(event_lines)
if legacy:
for x in range(num_events):
event_list.insert(0, event_lines[x].split(" ",2))
# Error handling if number of events is less than 10, fill array with empty
if num_events < 10:
for line in range((10-num_events)):
event_list.append(["--------","--:--:--","---"])
num_events = 10
else:
for x in range(num_events):
event_list.append(event_lines[x].split(" ",2))
return event_list
return(event_list, num_events)
def write_log(event):
"""
Write event to event.log
:param event: String event
"""
now = str(datetime.datetime.now())
now = now[0:19] # Truncate the microseconds
logfile = open("/tmp/events.log", "a")
logfile.write(now + ' ' + event + '\n')
logfile.close()
def write_event(settings, event):
"""
Send event to log and console if debug mode enabled or only to log if
string does not begin with *
:param settings: Settings
:param event: String event
"""
if settings['globals']['debug_mode']:
print(event)
write_log(event)
elif not event.startswith('*'):
write_log(event)
def read_history(num_items=0, flushhistory=False):
"""
Read history from Redis DB and populate a list of data
:param num_items: Items from end of the history
:param flushhistory: True to clean history / current. False otherwise
:return: List of history items
"""