-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbrewpi.py
executable file
·1892 lines (1684 loc) · 90.8 KB
/
brewpi.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
# Copyright (C) 2018, 2019 Lee C. Bussy (@LBussy)
# This file is part of LBussy's BrewPi Script Remix (BrewPi-Script-RMX).
#
# BrewPi Script RMX is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# BrewPi Script RMX is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with BrewPi Script RMX. If not, see <https://www.gnu.org/licenses/>.
# These scripts were originally a part of brewpi-script, a part of
# the BrewPi project. Legacy support (for the very popular Arduino
# controller) seems to have been discontinued in favor of new hardware.
# All credit for the original brewpi-script goes to @elcojacobs,
# @m-mcgowan, @rbrady, @steersbob, @glibersat, @Niels-R and I'm sure
# many more contributors around the world. My apologies if I have
# missed anyone; those were the names listed as contributors on the
# Legacy branch.
# See: 'original-license.md' for notes about the original project's
# license and credits. */
# Standard Imports
import _thread
import argparse
import asyncio
import getopt
import grp
import os
import pwd
import shutil
import socket
import stat
import sys
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request
from decimal import *
from distutils.version import LooseVersion
from pprint import pprint
from struct import calcsize, pack, unpack
import git
import serial
import simplejson as json
from configobj import ConfigObj
import BrewConvert
import brewpiJson
import BrewPiProcess
import BrewPiUtil as util
import brewpiVersion
import expandLogMessage
import pinList
import programController as programmer
import temperatureProfile
import Tilt
from backgroundserial import BackGroundSerial
from BrewPiUtil import (Unbuffered, addSlash, logError, logMessage,
readCfgWithDefaults)
# ********************************************************************
####
# IMPORTANT NOTE: I don't care if you play with the code, but if
# you do, please comment out the next lines. Otherwise I will
# receive a notice for every mistake you make.
####
# ********************************************************************
#import sentry_sdk
# sentry_sdk.init("https://[email protected]/1803681")
hwVersion = None
compatibleHwVersion = "0.2.4"
# Settings will be read from controller, initialize with same defaults as
# controller. This is mainly to show what's expected. Will all be overwritten
# on the first update from the controller
# Control Settings Dictionary
cs = dict(mode='b', beerSet=20.0, fridgeSet=20.0, heatEstimator=0.2,
coolEstimator=5)
# Control Constants Dictionary
cc = dict(tempFormat="C", tempSetMin=1.0, tempSetMax=30.0, pidMax=10.0,
Kp=20.000, Ki=0.600, Kd=-3.000, iMaxErr=0.500, idleRangeH=1.000,
idleRangeL=-1.000, heatTargetH=0.301, heatTargetL=-0.199,
coolTargetH=0.199, coolTargetL=-0.301, maxHeatTimeForEst="600",
maxCoolTimeForEst="1200", fridgeFastFilt="1", fridgeSlowFilt="4",
fridgeSlopeFilt="3", beerFastFilt="3", beerSlowFilt="5",
beerSlopeFilt="4", lah=0, hs=0)
# Control Variables Dictionary
cv = dict(beerDiff=0.000, diffIntegral=0.000, beerSlope=0.000, p=0.000,
i=0.000, d=0.000, estPeak=0.000, negPeakEst=0.000,
posPeakEst=0.000, negPeak=0.000, posPeak=0.000)
# listState = "", "d", "h", "dh" to reflect whether the list is up to date for
# installed (d) and available (h)
deviceList = dict(listState="", installed=[], available=[])
version = "0.0.0"
branch = "unknown"
commit = "unknown"
configFile = None
config = None
dontRunFilePath = None
checkDontRunFile = False
checkStartupOnly = False
logToFiles = False
logPath = None
outputJson = None # Print JSON to logs
localJsonFileName = None
localCsvFileName = None
wwwJsonFileName = None
wwwCsvFileName = None
lastDay = None
day = None
thread = False
threads = []
tilt = None
ispindel = None
tiltbridge = False
# Timestamps to expire values
lastBbApi = 0
timeoutBB = 300
lastiSpindel = 0
timeoutiSpindel = 3600
lastTiltbridge = 0
timeoutTiltbridge = 300
# Keep track of time between new data requests
prevDataTime = 0
prevTimeOut = 0
prevLcdUpdate = 0
prevSettingsUpdate = 0
serialCheckInterval = 0.5 # Blocking socket functions wait in seconds
phpSocket = None # Listening socket to communicate with PHP
serialConn = None # Serial connection to communicate with controller
bgSerialConn = None # For background serial processing, put whole lines in a queue
# Initialize prevTempJson with base values:
prevTempJson = {
'BeerTemp': 0,
'FridgeTemp': 0,
'BeerAnn': None,
'FridgeAnn': None,
'RoomTemp': None,
'State': None,
'BeerSet': 0,
'FridgeSet': 0,
}
# Default LCD text
lcdText = ['Script starting up.', ' ', ' ', ' ']
statusType = ['N/A', 'N/A', 'N/A', 'N/A']
statusValue = ['N/A', 'N/A', 'N/A', 'N/A']
def getGit():
# Get the current script version
# version = os.popen('git describe --tags $(git rev-list --tags --max-count=1)').read().strip()
# branch = os.popen('git branch | grep \* | cut -d " " -f2').read().strip()
# commit = os.popen('git -C . log --oneline -n1').read().strip()
global version
global branch
global commit
repo = git.Repo(util.scriptPath())
version = (next((tag for tag in reversed(repo.tags)), None))
branch = repo.active_branch.name
commit = str(repo.head.commit)[0:7]
def options(): # Parse command line options
global version
global configFile
global checkStartupOnly
global logToFiles
parser = argparse.ArgumentParser(
description="Main BrewPi script which communicates with the controller(s)")
parser.add_argument("-v", "--version", action="version", version=version)
parser.add_argument("-c", "--config", metavar="<config file>",
help="select config file to use", action="store")
parser.add_argument(
"-s", "--status", help="check running scripts", action='store_true')
parser.add_argument(
"-q", "--quit", help="send quit to all instances", action='store_true')
parser.add_argument(
"-k", "--kill", help="kill all instances", action='store_true')
parser.add_argument(
"-f", "--force", help="quit/kill others and keep this one", action='store_true')
parser.add_argument(
"-l", "--log", help="redirect output to log files", action='store_true')
parser.add_argument(
"-t", "--datetime", help="prepend log entries with date/time stamp", action='store_true')
parser.add_argument(
"-d", "--donotrun", help="check for do not run semaphore", action='store_true')
parser.add_argument(
"-o", "--check", help="exit after startup checks", action='store_true')
args = parser.parse_args()
# Supply a config file
if args.config:
configFile = os.path.abspath(args.config)
if not os.path.exists(configFile):
print('ERROR: Config file {0} was not found.'.format(
configFile), file=sys.stderr)
sys.exit(1)
# Send quit instruction to all running instances of BrewPi
if args.status:
allProcesses = BrewPiProcess.BrewPiProcesses()
allProcesses.update()
running = allProcesses.as_dict()
if running:
pprint(running)
else:
print("No BrewPi scripts running.", file=sys.stderr)
sys.exit(0)
# Quit running instances
if args.quit:
print("Asking all BrewPi processes to quit on their socket.", file=sys.stderr)
allProcesses = BrewPiProcess.BrewPiProcesses()
allProcesses.quitAll()
time.sleep(2)
sys.exit(0)
# Send SIGKILL to all running instances of BrewPi
if args.kill:
print("Killing all BrewPi processes.", file=sys.stderr)
allProcesses = BrewPiProcess.BrewPiProcesses()
allProcesses.killAll()
sys.exit(0)
# Close all existing instances of BrewPi by quit/kill and keep this one
if args.force:
logMessage(
"Closing all existing processes of BrewPi and keeping this one.")
allProcesses = BrewPiProcess.BrewPiProcesses()
if len(allProcesses.update()) > 1: # if I am not the only one running
allProcesses.quitAll()
time.sleep(2)
if len(allProcesses.update()) > 1:
print(
"Asking the other processes to quit did not work. Forcing them now.", file=sys.stderr)
allProcesses.killAll()
time.sleep(2)
if len(allProcesses.update()) > 1:
print("Unable to kill existing BrewPi processes.",
file=sys.stderr)
sys.exit(0)
# Redirect output of stderr and stdout to files in log directory
if args.log:
logToFiles = True
# Redirect output of stderr and stdout to files in log directory
if args.datetime:
os.environ['USE_TIMESTAMP_LOG'] = 'True'
# Only start brewpi when the dontrunfile is not found
if args.donotrun:
checkDontRunFile = True
# Exit after startup checks
if args.check:
checkStartupOnly = True
def config(): # Load config file
global configFile
global config
config = util.readCfgWithDefaults(configFile)
def checkDoNotRun(): # Check do not run file
global dontRunFilePath
global config
global checkDontRunFile
dir(config)
dontRunFilePath = '{0}do_not_run_brewpi'.format(
util.addSlash(config['wwwPath']))
# Check dont run file when it exists and exit it it does
if os.path.exists(dontRunFilePath):
# Do not print anything or it will flood the logs
sys.exit(1)
else:
# This is here to exit with the semaphore anyway, but print notice
# This should only be hit when running interactively.
if os.path.exists(dontRunFilePath):
print("Semaphore exists, exiting.")
sys.exit(1)
def checkOthers(): # Check for other running brewpi
global checkDontRunFile
allProcesses = BrewPiProcess.BrewPiProcesses()
allProcesses.update()
myProcess = allProcesses.me()
if allProcesses.findConflicts(myProcess):
if not checkDontRunFile:
logMessage(
"A conflicting BrewPi is running. This instance will exit.")
sys.exit(1)
def setUpLog(): # Set up log files
global logToFiles
global logPath
if logToFiles:
logPath = '{0}logs/'.format(util.scriptPath())
# Skip logging for this message
print("Logging to {0}.".format(logPath))
print("Output will not be shown in console.")
# Append stderr, unbuffered
sys.stderr = Unbuffered(open(logPath + 'stderr.txt', 'a+'))
# Overwrite stdout, unbuffered
sys.stdout = Unbuffered(open(logPath + 'stdout.txt', 'w+'))
# Start the logs
logError('Starting BrewPi.') # Timestamp stderr
if logToFiles:
# Make sure we send a message to daemon
print('Starting BrewPi.', file=sys.__stdout__)
else:
logMessage('Starting BrewPi.')
def getWwwSetting(settingName): # Get www json setting with default
setting = None
wwwPath = util.addSlash(config['wwwPath'])
userSettings = '{0}userSettings.json'.format(wwwPath)
defaultSettings = '{0}defaultSettings.json'.format(wwwPath)
try:
json_file = open(userSettings, 'r')
data = json.load(json_file)
# If settingName exists, get value
if checkKey(data, settingName):
setting = data[settingName]
json_file.close()
except:
# userSettings.json does not exist
try:
json_file = open(defaultSettings, 'r')
data = json.load(json_file)
# If settingName exists, get value
if checkKey(data, settingName):
setting = data[settingName]
json_file.close()
except:
# defaultSettings.json does not exist, use None
pass
return setting
def checkKey(dict, key): # Check to see if a key exists in a dictionary
if key in list(dict.keys()):
return True
else:
return False
def changeWwwSetting(settingName, value):
# userSettings.json is a copy of some of the settings that are needed by the
# web server. This allows the web server to load properly, even when the script
# is not running.
wwwSettingsFileName = '{0}userSettings.json'.format(
util.addSlash(config['wwwPath']))
if os.path.exists(wwwSettingsFileName):
wwwSettingsFile = open(wwwSettingsFileName, 'r+b')
try:
wwwSettings = json.load(wwwSettingsFile) # read existing settings
except json.JSONDecodeError:
logMessage(
"Error while decoding userSettings.json, creating new empty json file.")
# Start with a fresh file when the json is corrupt.
wwwSettings = {}
else:
wwwSettingsFile = open(wwwSettingsFileName, 'w+b') # Create new file
wwwSettings = {}
try:
wwwSettings[settingName] = value
wwwSettingsFile.seek(0)
wwwSettingsFile.write(json.dumps(wwwSettings).encode(encoding="cp437"))
wwwSettingsFile.truncate()
wwwSettingsFile.close()
except:
logError("Ran into an error writing the WWW JSON file.")
def setFiles():
global config
global localJsonFileName
global localCsvFileName
global wwwJsonFileName
global wwwCsvFileName
global lastDay
global day
# Concatenate directory names for the data
beerFileName = config['beerName']
dataPath = '{0}data/{1}/'.format(
util.scriptPath(), beerFileName)
wwwDataPath = '{0}data/{1}/'.format(
util.addSlash(config['wwwPath']), beerFileName)
# Create path and set owner and perms (recursively) on directories and files
owner = 'brewpi'
group = 'brewpi'
uid = pwd.getpwnam(owner).pw_uid # Get UID
gid = grp.getgrnam(group).gr_gid # Get GID
fileMode = stat.S_IRWXU | stat.S_IRWXG | stat.S_IROTH | stat.S_IXOTH | stat.S_IROTH # 664
dirMode = stat.S_IRWXU | stat.S_IRWXG | stat.S_IROTH | stat.S_IXOTH | stat.S_IROTH | stat.S_IXOTH # 775
if not os.path.exists(dataPath):
os.makedirs(dataPath) # Create path if it does not exist
os.chown(dataPath, uid, gid) # chown root directory
os.chmod(dataPath, dirMode) # chmod root directory
for root, dirs, files in os.walk(dataPath):
for dir in dirs:
os.chown(os.path.join(root, dir), uid, gid) # chown directories
os.chmod(dir, dirMode) # chmod directories
for file in files:
if os.path.isfile(file):
os.chown(os.path.join(root, file), uid, gid) # chown files
os.chmod(file, fileMode) # chmod files
# Create path and set owner and perms (recursively) on directories and files
owner = 'brewpi'
group = 'www-data'
uid = pwd.getpwnam(owner).pw_uid # Get UID
gid = grp.getgrnam(group).gr_gid # Get GID
fileMode = stat.S_IRWXU | stat.S_IRWXG | stat.S_IROTH | stat.S_IXOTH | stat.S_IROTH # 664
dirMode = stat.S_IRWXU | stat.S_IRWXG | stat.S_IROTH | stat.S_IXOTH | stat.S_IROTH | stat.S_IXOTH # 775
if not os.path.exists(wwwDataPath):
os.makedirs(wwwDataPath) # Create path if it does not exist
os.chown(wwwDataPath, uid, gid) # chown root directory
os.chmod(wwwDataPath, dirMode) # chmod root directory
for root, dirs, files in os.walk(wwwDataPath):
for dir in dirs:
os.chown(os.path.join(root, dir), uid, gid) # chown directories
os.chmod(dir, dirMode) # chmod directories
for file in files:
if os.path.isfile(file):
os.chown(os.path.join(root, file), uid, gid) # chown files
os.chmod(file, fileMode) # chmod files
# Keep track of day and make new data file for each day
day = time.strftime("%Y%m%d")
lastDay = day
# Define a JSON file to store the data
jsonFileName = '{0}-{1}'.format(beerFileName, day)
# If a file for today already existed, add suffix
if os.path.isfile('{0}{1}.json'.format(dataPath, jsonFileName)):
i = 1
while os.path.isfile('{0}{1}-{2}.json'.format(dataPath, jsonFileName, str(i))):
i += 1
jsonFileName = '{0}-{1}'.format(jsonFileName, str(i))
localJsonFileName = '{0}{1}.json'.format(dataPath, jsonFileName)
# Handle if we are running Tilt or iSpindel
if checkKey(config, 'tiltColor'):
brewpiJson.newEmptyFile(localJsonFileName, config['tiltColor'], None)
elif checkKey(config, 'iSpindel'):
brewpiJson.newEmptyFile(localJsonFileName, None, config['iSpindel'])
else:
brewpiJson.newEmptyFile(localJsonFileName, None, None)
# Define a location on the web server to copy the file to after it is written
wwwJsonFileName = wwwDataPath + jsonFileName + '.json'
# Define a CSV file to store the data as CSV (might be useful one day)
localCsvFileName = (dataPath + beerFileName + '.csv')
wwwCsvFileName = (wwwDataPath + beerFileName + '.csv')
def startBeer(beerName):
global config
if config['dataLogging'] == 'active':
setFiles()
changeWwwSetting('beerName', beerName)
def startNewBrew(newName):
global config
if len(newName) > 1:
config = util.configSet('beerName', newName, configFile)
config = util.configSet('dataLogging', 'active', configFile)
startBeer(newName)
logMessage("Restarted logging for beer '%s'." % newName)
return {'status': 0, 'statusMessage': "Successfully switched to new brew '%s'. " % urllib.parse.unquote(newName) +
"Please reload the page."}
else:
return {'status': 1, 'statusMessage': "Invalid new brew name '%s', please enter\n" +
"a name with at least 2 characters" % urllib.parse.unquote(newName)}
def stopLogging():
global config
logMessage("Stopped data logging temp control continues.")
config = util.configSet('beerName', None, configFile)
config = util.configSet('dataLogging', 'stopped', configFile)
changeWwwSetting('beerName', None)
return {'status': 0, 'statusMessage': "Successfully stopped logging."}
def pauseLogging():
global config
logMessage("Paused logging data, temp control continues.")
if config['dataLogging'] == 'active':
config = util.configSet('dataLogging', 'paused', configFile)
return {'status': 0, 'statusMessage': "Successfully paused logging."}
else:
return {'status': 1, 'statusMessage': "Logging already paused or stopped."}
def resumeLogging():
global config
logMessage("Continued logging data.")
if config['dataLogging'] == 'paused':
config = util.configSet('dataLogging', 'active', configFile)
return {'status': 0, 'statusMessage': "Successfully continued logging."}
else:
return {'status': 1, 'statusMessage': "Logging was not paused."}
def checkBluetooth(interface=0):
exceptions = []
sock = None
try:
sock = socket.socket(family=socket.AF_BLUETOOTH,
type=socket.SOCK_RAW,
proto=socket.BTPROTO_HCI)
sock.setblocking(False)
sock.setsockopt(socket.SOL_HCI, socket.HCI_FILTER, pack(
"IIIh2x", 0xffffffff, 0xffffffff, 0xffffffff, 0))
try:
sock.bind((interface,))
except OSError as exc:
exc = OSError(
exc.errno, 'error while attempting to bind on '
'interface {!r}: {}'.format(
interface, exc.strerror))
exceptions.append(exc)
except OSError as exc:
if sock is not None:
sock.close()
exceptions.append(exc)
except:
if sock is not None:
sock.close()
raise
if len(exceptions) == 1:
raise exceptions[0]
elif len(exceptions) > 1:
model = str(exceptions[0])
if all(str(exc) == model for exc in exceptions):
raise exceptions[0]
raise OSError('Multiple exceptions: {}'.format(
', '.join(str(exc) for exc in exceptions)))
return sock
def initTilt(): # Set up Tilt
global config
global tilt
if checkKey(config, 'tiltColor') and config['tiltColor'] != "":
if not checkBluetooth():
logError("Configured for Tilt but no Bluetooth radio available.")
else:
try:
tilt.stop()
except:
pass
tilt = None
#try:
tilt = Tilt.TiltManager(60, 10, 0)
tilt.loadSettings()
tilt.start()
# Create prevTempJson for Tilt
if not checkKey(prevTempJson, config['tiltColor'] + 'SG'):
prevTempJson.update({
config['tiltColor'] + 'HWVer': 0,
config['tiltColor'] + 'SWVer': 0,
config['tiltColor'] + 'SG': 0,
config['tiltColor'] + 'Temp': 0,
config['tiltColor'] + 'Batt': 0
})
def initISpindel(): # Initialize iSpindel
global ispindel
global config
global prevTempJson
if checkKey(config, 'iSpindel') and config['iSpindel'] != "":
ispindel = True
# Create prevTempJson for iSpindel
prevTempJson.update({
'spinSG': 0,
'spinBatt': 0,
'spinTemp': 0
})
def renameTempKey(key):
rename = {
'bt': 'BeerTemp',
'bs': 'BeerSet',
'ba': 'BeerAnn',
'ft': 'FridgeTemp',
'fs': 'FridgeSet',
'fa': 'FridgeAnn',
'rt': 'RoomTemp',
's': 'State',
't': 'Time',
'tg': 'TiltSG',
'tt': 'TiltTemp',
'tb': 'TiltBatt',
'sg': 'spinSG',
'st': 'spinTemp',
'sb': 'spinBatt',
}
return rename.get(key, key)
def setSocket(): # Create a listening socket to communicate with PHP
global phpSocket
global serialCheckInterval
is_windows = sys.platform.startswith('win')
useInetSocket = bool(config.get('useInetSocket', is_windows))
if useInetSocket:
phpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
socketPort = config.get('socketPort', 6332)
phpSocket.bind(
(config.get('socketHost', 'localhost'), int(socketPort)))
logMessage('Bound to TCP socket on port %d ' % int(socketPort))
else:
socketFile = util.scriptPath() + 'BEERSOCKET'
if os.path.exists(socketFile):
# If socket already exists, remove it
os.remove(socketFile)
phpSocket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
phpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
phpSocket.bind(socketFile) # Bind BEERSOCKET
# Set owner and permissions for socket
try:
fileMode = stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP # 660
owner = 'brewpi'
group = 'www-data'
uid = pwd.getpwnam(owner).pw_uid
gid = grp.getgrnam(group).gr_gid
os.chown(socketFile, uid, gid) # chown socket
os.chmod(socketFile, fileMode) # chmod socket
except IOError as e:
logError("Error({0}) while setting permissions on:".format(e.errno))
logError("{0}:".format(socketFile))
logError("{0}.".format(e.strerror))
logError("You are not running as root or brewpi, or your")
logError("permissions are not set correctly. To fix this, run:")
logError("sudo {0}utils/doPerms.sh".format(util.scriptPath()))
# Set socket behavior
phpSocket.setblocking(1) # Set socket functions to be blocking
phpSocket.listen(10) # Create a backlog queue for up to 10 connections
# Timeout wait 'serialCheckInterval' seconds
phpSocket.settimeout(serialCheckInterval)
def startLogs(): # Log startup messages
global config
global version
global branch
global commit
global outputJson
# Output the current script version
logMessage('{0} ({1}) [{2}]'.format(version, branch, commit))
# Log JSON:
# True = Full
# False = Terse message
# None = No JSON
if checkKey(config, 'logJson'):
if config['logJson'] == 'True':
outputJson = True
else:
outputJson = False
if config['beerName'] == 'None':
logMessage("Not currently logging.")
else:
logMessage("Starting '" +
urllib.parse.unquote(config['beerName']) + ".'")
def clamp(raw, minn, maxn):
# Clamps value (raw) between minn and maxn
return max(min(maxn, raw), minn)
def startSerial(): # Start controller
global config
global serialConn
global bgSerialConn
global hwVersion
global compatibleHwVersion
try:
# Bytes are read from nonblocking serial into this buffer and processed when
# the buffer contains a full line.
serialConn = util.setupSerial(config)
if not serialConn:
sys.exit(1)
else:
# Wait for 10 seconds to allow an Uno to reboot
logMessage("Waiting 10 seconds for board to restart.")
time.sleep(int(config.get('startupDelay', 10)))
logMessage("Checking software version on controller.")
hwVersion = brewpiVersion.getVersionFromSerial(serialConn)
if hwVersion is None:
logMessage("ERROR: Cannot receive version number from controller.")
logMessage("Your controller is either not programmed or running a")
logMessage("very old version of BrewPi. Please upload a new version")
logMessage("of BrewPi to your controller.")
# Script will continue so you can at least program the controller
lcdText = ['Could not receive', 'ver from controller', 'Please (re)program', 'your controller.']
else:
logMessage("Found " + hwVersion.toExtendedString() + " on port " + serialConn.name + ".")
if LooseVersion(hwVersion.toString()) < LooseVersion(compatibleHwVersion):
logMessage("Warning: Minimum BrewPi version compatible with this")
logMessage("script is {0} but version number received is".format(
compatibleHwVersion))
logMessage("{0}.".format(hwVersion.toString()))
if int(hwVersion.log) != int(expandLogMessage.getVersion()):
logMessage("Warning: version number of local copy of logMessages.h")
logMessage("does not match log version number received from")
logMessage(
"controller. Controller version = {0}, local copy".format(hwVersion.log))
logMessage("version = {0}.".format(
str(expandLogMessage.getVersion())))
if serialConn is not None:
serialConn.flush()
# Set up background serial processing, which will continuously read data
# from serial and put whole lines in a queue
bgSerialConn = BackGroundSerial(serialConn)
bgSerialConn.start()
# Request settings from controller, processed later when reply is received
bgSerialConn.writeln("s") # request control settings cs
bgSerialConn.writeln("c") # request control constants cc
bgSerialConn.writeln("v") # request control variables cv
# Answer from controller is received asynchronously later.
# Keep track of time between new data requests
prevDataTime = 0
prevTimeOut = time.time()
prevLcdUpdate = time.time()
prevSettingsUpdate = time.time()
startBeer(config['beerName']) # Set up files and prep for run
except KeyboardInterrupt:
print() # Simply a visual hack if we are running via command line
logMessage("Detected keyboard interrupt, exiting.")
except RuntimeError:
logError(e)
type, value, traceback = sys.exc_info()
fname = os.path.split(traceback.tb_frame.f_code.co_filename)[1]
logError("Caught a Runtime Error.")
logError("Error info:")
logError("\tError: ({0}): '{1}'".format(
getattr(e, 'errno', ''), getattr(e, 'strerror', '')))
logError("\tType: {0}".format(type))
logError("\tFilename: {0}".format(fname))
logError("\tLineNo: {0}".format(traceback.tb_lineno))
logMessage("Caught a Runtime Error.")
except Exception as e:
type, value, traceback = sys.exc_info()
fname = os.path.split(traceback.tb_frame.f_code.co_filename)[1]
logError("Caught an unexpected exception.")
logError("Error info:")
logError("\tType: {0}".format(type))
logError("\tFilename: {0}".format(fname))
logError("\tLineNo: {0}".format(traceback.tb_lineno))
logError("\tError:\n{0}".format(e))
logMessage("Caught an unexpected exception.")
def loop(): # Main program loop
global config
global hwVersion
global lastDay
global day
global lcdText
global statusType
global statusValue
global cs
global cc
global cv
global prevTempJson
global deviceList
global dontRunFilePath
global lastBbApi
global timeoutBB
global lastiSpindel
global timeoutiSpindel
global lastTiltbridge
global timeoutTiltbridge
global phpSocket
global serialConn
global bgSerialConn
global prevDataTime
global prevTimeOut
global prevLcdUpdate
global prevSettingsUpdate
global serialCheckInterval
global tilt
global tiltbridge
global ispindel
bc = BrewConvert.BrewConvert()
run = True # Allow script loop to run
try: # Main loop
while run:
if config['dataLogging'] == 'active':
# Check whether it is a new day
lastDay = day
day = time.strftime("%Y%m%d")
if lastDay != day:
logMessage("New day, creating new JSON file.")
setFiles()
if os.path.exists(dontRunFilePath):
# Allow stopping script via semaphore
logMessage("Semaphore detected, exiting.")
run = False
# Wait for incoming phpSocket connections. If nothing is received,
# socket.timeout will be raised after serialCheckInterval seconds.
# bgSerialConn receive will then process. If messages are expected
# on serial, the timeout is raised explicitly.
try: # Process socket messages
phpConn, addr = phpSocket.accept()
phpConn.setblocking(1)
# Blocking receive, times out in serialCheckInterval
message = phpConn.recv(4096).decode(encoding="cp437")
if "=" in message: # Split to message/value if message has an '='
messageType, value = message.split("=", 1)
else:
messageType = message
value = ""
if messageType == "ack": # Acknowledge request
phpConn.send("ack".encode(encoding="utf-8"))
elif messageType == "lcd": # LCD contents requested
phpConn.send(json.dumps(lcdText).encode(encoding="utf-8"))
elif messageType == "getMode": # Echo mode setting
phpConn.send(cs['mode'].encode(encoding="utf-8"))
elif messageType == "getFridge": # Echo fridge temperature setting
phpConn.send(json.dumps(cs['fridgeSet']).encode(encoding="utf-8"))
elif messageType == "getBeer": # Echo beer temperature setting
phpConn.send(json.dumps(cs['beerSet']).encode(encoding="utf-8"))
elif messageType == "getControlConstants": # Echo control constants
phpConn.send(json.dumps(cc).encode(encoding="utf-8"))
elif messageType == "getControlSettings": # Echo control settings
if cs['mode'] == "p":
profileFile = util.scriptPath() + 'settings/tempProfile.csv'
with open(profileFile, 'r') as prof:
cs['profile'] = prof.readline().split(
",")[-1].rstrip("\n")
cs['dataLogging'] = config['dataLogging']
phpConn.send(json.dumps(cs).encode(encoding="utf-8"))
elif messageType == "getControlVariables": # Echo control variables
phpConn.send(json.dumps(cv).encode(encoding="utf-8"))
elif messageType == "refreshControlConstants": # Request control constants from controller
bgSerialConn.writeln("c")
raise socket.timeout
elif messageType == "refreshControlSettings": # Request control settings from controller
bgSerialConn.writeln("s")
raise socket.timeout
elif messageType == "refreshControlVariables": # Request control variables from controller
bgSerialConn.writeln("v")
raise socket.timeout
elif messageType == "loadDefaultControlSettings":
bgSerialConn.writeln("S")
raise socket.timeout
elif messageType == "loadDefaultControlConstants":
bgSerialConn.writeln("C")
raise socket.timeout
elif messageType == "setBeer": # New constant beer temperature received
try:
newTemp = Decimal(value)
except ValueError:
logMessage("Cannot convert temperature '" +
value + "' to float.")
continue
if cc['tempSetMin'] <= newTemp <= cc['tempSetMax']:
cs['mode'] = 'b'
# Round to 2 dec, python will otherwise produce 6.999999999
cs['beerSet'] = round(newTemp, 2)
bgSerialConn.writeln(
"j{mode:\"b\", beerSet:" + json.dumps(cs['beerSet']) + "}")
logMessage("Beer temperature set to {0} degrees by web.".format(
str(cs['beerSet'])))
raise socket.timeout # Go to serial communication to update controller
else:
logMessage(
"Beer temperature setting {0} is outside of allowed".format(str(newTemp)))
logMessage("range {0} - {1}. These limits can be changed in".format(
str(cc['tempSetMin']), str(cc['tempSetMax'])))
logMessage("advanced settings.")
elif messageType == "setFridge": # New constant fridge temperature received
try:
newTemp = Decimal(value)
except ValueError:
logMessage(
"Cannot convert temperature '{0}' to float.".format(value))
continue
if cc['tempSetMin'] <= newTemp <= cc['tempSetMax']:
cs['mode'] = 'f'
cs['fridgeSet'] = round(newTemp, 2)
bgSerialConn.writeln("j{mode:\"f\", fridgeSet:" +
json.dumps(cs['fridgeSet']) + "}")
logMessage("Fridge temperature set to {0} degrees by web.".format(
str(cs['fridgeSet'])))
raise socket.timeout # Go to serial communication to update controller
else:
logMessage(
"Fridge temperature setting {0} is outside of allowed".format(str(newTemp)))
logMessage("range {0} - {1}. These limits can be changed in".format(
str(cc['tempSetMin']), str(cc['tempSetMax'])))
logMessage("advanced settings.")
elif messageType == "setOff": # Control mode set to OFF
cs['mode'] = 'o'
bgSerialConn.writeln("j{mode:\"o\"}")
logMessage("Temperature control disabled.")
raise socket.timeout
elif messageType == "setParameters": # Receive JSON key:value pairs to set parameters on the controller
try:
decoded = json.loads(value)
bgSerialConn.writeln("j" + json.dumps(decoded))
if 'tempFormat' in decoded:
# Change in web interface settings too
changeWwwSetting(
'tempFormat', decoded['tempFormat'])
except json.JSONDecodeError:
logMessage(
"ERROR: Invalid JSON parameter. String received:")
logMessage(value)
raise socket.timeout
elif messageType == "stopScript": # Exit instruction received. Stop script.
# Voluntary shutdown.
logMessage('Stop message received on socket.')
sys.stdout.flush()
# Also log stop back to daemon
if logToFiles:
print('Stop message received on socket.',
file=sys.__stdout__)
run = False
# Write a file to prevent the daemon from restarting the script
util.createDontRunFile(dontRunFilePath)
elif messageType == "quit": # Quit but do not write semaphore
# Quit instruction received. Probably sent by another brewpi
# script instance
logMessage("Quit message received on socket.")
run = False
# Leave dontrunfile alone.
# This instruction is meant to restart the script or replace
# it with another instance.
continue
elif messageType == "eraseLogs": # Erase stderr and stdout
open(util.scriptPath() + '/logs/stderr.txt', 'wb').close()
open(util.scriptPath() + '/logs/stdout.txt', 'wb').close()