forked from rtlindne/RaspberryPints
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPintDispatch.py
More file actions
655 lines (564 loc) · 24.3 KB
/
PintDispatch.py
File metadata and controls
655 lines (564 loc) · 24.3 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
#!/usr/bin/python
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42 3/4):
# <[email protected]> wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return
# -Th
# ----------------------------------------------------------------------------
import threading
import time
import signal
import sys
import os
import struct
import socket
import MySQLdb as mdb
from FlowMonitor import FlowMonitor
from threading import Timer
from threading import Lock
import SocketServer
import pprint
import serial
import datetime
from sys import stdin
from mod_pywebsocket.standalone import WebSocketServer
from mod_pywebsocket.standalone import _parse_args_and_config
from mod_pywebsocket.standalone import _configure_logging
from Config import config
GPIO_IMPORT_SUCCESSFUL = True
try:
import RPi.GPIO as GPIO
except:
GPIO_IMPORT_SUCCESSFUL = False
PINTS_DIR = config['pints.dir' ]
INCLUDES_DIR = PINTS_DIR + "/includes"
PYTHON_DIR = PINTS_DIR + "/python"
PYTHON_WSH_DIR = PYTHON_DIR + "/ws"
ADMIN_DIR = PINTS_DIR + "/admin"
ADMIN_INCLUDES_DIR = ADMIN_DIR + "/includes"
# mcast group and port to send flow and valve updates to
MCAST_GRP = '224.1.1.1'
MCAST_PORT = 0xBEE2
MCAST_RETRY_ATTEMPTS = 10
MCAST_RETRY_SLEEP_SEC=5
def debug(msg):
if(config['dispatch.debug']):
log(msg)
def log(msg):
print datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') + " RPINTS: " + msg
sys.stdout.flush()
class CommandTCPHandler(SocketServer.StreamRequestHandler):
def handle(self):
self.data = self.rfile.readline().strip()
if not self.data:
self.wfile.write("RPNAK\n")
return
reading = self.data.split(":")
if ( len(reading) < 2 ):
log( "Unknown message: "+ self.data)
self.wfile.write("RPNAK\n")
return
if(reading[0] == "RPC"): # reconfigure
debug("reconfigure trigger: " + reading[1])
if ( reading[1] == "valve" ):
debug("updating valve status from db")
self.server.pintdispatch.updateValvePins()
if ( reading[1] == "fan" ):
debug("updating fan status from db")
self.server.pintdispatch.resetFanConfig()
if ( reading[1] == "config" ):
debug("triggering config update refresh")
self.server.pintdispatch.sendconfigupdate()
if ( reading[1] == "flow" ):
debug("updating flow meter config from db")
self.server.pintdispatch.updateFlowmeterConfig()
if ( reading[1] == "alamode" or reading[1] == "all" ):
debug("resetting alamode config from db")
self.server.pintdispatch.triggerAlaModeReset()
if ( reading[1] == "tare" ):
debug("Requesting Load Cells to check tare")
self.server.pintdispatch.flowmonitor.tareRequest()
if ( reading[1] == "tempProbe" ):
debug("Requesting Reset of Temp Probes")
self.server.pintdispatch.flowmonitor.reconfigTempProbes()
if ( reading[1] == "shutdown" ):
log("Requesting Pi ShutDown")
self.server.pintdispatch.shutdown()
if ( reading[1] == "restart" ):
log("Requesting Pi Restart")
self.server.pintdispatch.restart()
if ( reading[1] == "restartservice" ):
debug("Requesting Reset of Service")
self.server.pintdispatch.restartService()
self.wfile.write("RPACK\n")
# override server_bind method to ensure that the tcp port can be reconnected to when server is killed
class CommandTCPServer(SocketServer.TCPServer):
def server_bind(self):
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(self.server_address)
# main class, handles comm between flow mon, multicast connection, tcp command server and GPIO
class PintDispatch(object):
def __init__(self):
self.OPTION_USE_3_WIRE_VALVES = self.getConfigValueByName("use3WireValves")
self.OPTION_RESTART_FANTIMER_AFTER_POUR = self.getConfigValueByName("restartFanAfterPour")
setupSocket = MCAST_RETRY_ATTEMPTS
if GPIO_IMPORT_SUCCESSFUL:
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD) # Broadcom pin-numbering scheme
self.alaModeReconfig = False;
while setupSocket > 0:
try:
#multicast socket
self.mcast = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.mcast.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
self.mcast.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
setupSocket = 0
except socket.error as msg:
setupSocket = setupSocket - 1
log(msg.strerror + " - Sleeping to try again")
time.sleep(MCAST_RETRY_SLEEP_SEC)
if setupSocket == MCAST_RETRY_ATTEMPTS:
log(str(setupSocket))
log("FATAL: Unable to setup socket")
quit()
self.valvesState = []
self.fanTimer = None
self.valvePowerTimer = None
if int(self.OPTION_USE_3_WIRE_VALVES) == 1:
self.valvePowerTimer = Timer(OPTION_VALVEPOWERON, self.valveStopPower)
self.updateFlowmeterConfig()
self.updateValvePins()
self.commandserver = CommandTCPServer(('localhost', MCAST_PORT), CommandTCPHandler)
self.commandserver.pintdispatch = self
self.fanControl = FanControlThread("fanControl1", self)
self.flowmonitor = FlowMonitor(self)
def parseConnFile(self):
connFileName = ADMIN_INCLUDES_DIR + "/conn.php"
connDict = dict()
with open(connFileName) as connFile:
for line in connFile:
instructions = line.split(";")
if(len(instructions) < 1):
continue
php = instructions[0].strip()
php = php.strip("$")
keyValue = php.split("=")
if(len(keyValue) != 2):
continue
connDict[keyValue[0]] = keyValue[1].strip("\"")
return connDict
def connectDB(self):
cp = self.parseConnFile()
con = mdb.connect(cp['host'],cp['username'],cp['password'],cp['db_name'])
return con
def getConfig(self):
con = self.connectDB()
cursor = con.cursor(mdb.cursors.DictCursor)
cursor.execute("SELECT * from config")
rows = cursor.fetchall()
con.close()
return rows
def getConfigValueByName(self, name):
con = self.connectDB()
cursor = con.cursor(mdb.cursors.DictCursor)
cursor.execute("SELECT configValue from config WHERE configName='"+name+"'")
rows = cursor.fetchall()
con.close()
if len(rows) == 0:
return None
return rows[0]['configValue']
def getTapConfig(self):
con = self.connectDB()
cursor = con.cursor(mdb.cursors.DictCursor)
cursor.execute("SELECT tc.tapId,tc.flowPin,tc.valvePin,tc.valveOn FROM tapconfig tc LEFT JOIN taps t ON tc.tapId = t.id WHERE t.active = 1 ORDER BY tc.tapId")
rows = cursor.fetchall()
con.close()
return rows
def getRFIDReaders(self):
con = self.connectDB()
cursor = con.cursor(mdb.cursors.DictCursor)
cursor.execute("SELECT * from rfidReaders ORDER BY priority")
rows = cursor.fetchall()
con.close()
return rows
def getMotionDetectors(self):
con = self.connectDB()
cursor = con.cursor(mdb.cursors.DictCursor)
cursor.execute("SELECT * from motionDetectors ORDER BY priority")
rows = cursor.fetchall()
con.close()
return rows
def getLoadCellConfig(self):
con = self.connectDB()
cursor = con.cursor(mdb.cursors.DictCursor)
cursor.execute("SELECT tapId,loadCellCmdPin,loadCellRspPin,loadCellUnit FROM tapconfig WHERE loadCellCmdPin IS NOT NULL ORDER BY tapId")
rows = cursor.fetchall()
con.close()
return rows
def getTareRequest(self, tapId):
con = self.connectDB()
cursor = con.cursor(mdb.cursors.DictCursor)
cursor.execute("SELECT tapId,loadCellTareReq FROM tapconfig WHERE tapId = " + str(tapId))
rows = cursor.fetchall()
con.close()
if len(rows) == 0:
return False
return rows[0]['loadCellTareReq'] == 1
def setTareRequest(self, tapId, tareRequested):
tareReq = "0"
if tareRequested:
tareReq = "1"
sql = "UPDATE tapconfig SET loadCellTareReq="+tareReq
if not tareRequested:
sql = sql + ",loadCellTareDate=NOW()"
sql = sql + " WHERE tapId = " + str(tapId)
con = self.connectDB()
cursor = con.cursor(mdb.cursors.DictCursor)
result = cursor.execute(sql)
con.commit()
con.close()
def addTempProbeAsNeeded(self, probe):
sql = "SELECT * FROM tempProbes WHERE name='"+probe+"';"
con = self.connectDB()
cursor = con.cursor(mdb.cursors.DictCursor)
result = cursor.execute(sql)
if(cursor.rowcount <= 0):
cursor.execute("INSERT INTO tempProbes (name, type) VALUES('"+probe+"', 0)")
con.commit()
con.close()
def saveTemp(self, probe, temp, tempUnit):
insertLogSql = "INSERT INTO tempLog (probe, temp, tempUnit, takenDate) "
insertLogSql += "VALUES('"+probe+"',"+str(temp)+"+ COALESCE((SELECT manualAdj FROM tempProbes WHERE name = '"+probe+"'), 0), '"+str(tempUnit)+"', NOW());"
con = self.connectDB()
cursor = con.cursor(mdb.cursors.DictCursor)
result = cursor.execute(insertLogSql)
con.commit()
con.close()
self.archiveTemp()
def getTempProbeConfig(self):
useTempProbes = self.getConfigValueByName("useTempProbes")
if(useTempProbes is not None and int(useTempProbes) == 1):
return True
return False
#set to -1 so on startup archive is checked
lastArchiveCheck = -1
#Combine all readings older than 2 months into 1 average for the month to reduce rows in the table
def archiveTemp(self):
#only archive if the month has changed
if self.lastArchiveCheck == datetime.datetime.now().month:
return
insertLogSql = """INSERT INTO tempLog (takenDate, probe, temp, humidity)
(SELECT CAST(DATE_FORMAT(takenDate,'%Y-%m-01') as DATE), 'History', TRUNCATE(AVG(temp), 2), TRUNCATE(hl.humidity, 2)
FROM tempLog tl
LEFT JOIN (SELECT CAST(DATE_FORMAT(takenDate,'%Y-%m-01') AS DATE) as takenMonth, AVG(humidity) AS humidity
FROM tempLog
WHERE probe != 'History' AND humidity IS NOT NULL AND
takenDate < CAST(DATE_FORMAT(NOW() ,'%Y-%m-01') as DATE)
GROUP BY MONTH(takenDate)) hl ON CAST(DATE_FORMAT(tl.takenDate,'%Y-%m-01') as DATE) = hl.takenMonth
WHERE probe != 'History' AND
takenDate < CAST(DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH) ,'%Y-%m-01') as DATE)
GROUP BY MONTH(takenDate));"""
deleteSQL = """DELETE FROM tempLog
WHERE probe != 'History' AND
takenDate < CAST(DATE_FORMAT(DATE_SUB(NOW(), INTERVAL 1 MONTH) ,'%Y-%m-01') as DATE) ;"""
con = self.connectDB()
cursor = con.cursor(mdb.cursors.DictCursor)
result = cursor.execute(insertLogSql)
result = cursor.execute(deleteSQL)
con.commit()
con.close()
self.lastArchiveCheck = datetime.datetime.now().month
def useFanControl(self):
useFanControl = self.getConfigValueByName("useFanControl")
if(useFanControl is None or int(useFanControl) == 0):
return False
return True
def getFanPin(self):
fanPin = self.getConfigValueByName("useFanPin")
if fanPin is not None:
return int(fanPin)
return -1
def getFanOnTime(self):
fanPin = self.getConfigValueByName("fanOnTime")
if fanPin is not None:
return int(fanPin)
return 0
def getFanOffTime(self):
fanPin = self.getConfigValueByName("fanInterval")
if fanPin is not None:
return int(fanPin)
return 0
# check if we're exceeding the pour threshold
def sendflowupdate(self, pin, count):
return
# check if we're exceeding the pour threshold
def sendkickupdate(self, pin):
msg = "RPU:KICK:" + str(pin)
debug("Kicking Keg: " + msg.rstrip())
self.mcast.sendto(msg + "\n", (MCAST_GRP, MCAST_PORT))
# send a mcast flow update
def sendflowcount(self, rfid, pin, count):
if self.OPTION_RESTART_FANTIMER_AFTER_POUR:
self.fanControl.restartNeeded(True)
msg = "RPU:FLOW:" + str(pin) + "=" + str(count) +":" + rfid
debug("count update: " + msg.rstrip())
self.mcast.sendto(msg + "\n", (MCAST_GRP, MCAST_PORT))
# send a mcast valve/pin update
def sendvalveupdate(self, pin, value):
msg = "RPU:VALVE:" + str(pin) + "=" + str(value)
debug("valve update: " + msg.rstrip())
self.mcast.sendto(msg + "\n", (MCAST_GRP, MCAST_PORT))
# send a mcast fan update
def sendfanupdate(self, pin, value):
msg = "RPU:FAN:" + str(pin) + "=" + str(value)
debug("fan update: " + msg.rstrip())
self.mcast.sendto(msg + "\n", (MCAST_GRP, MCAST_PORT))
# send a mcast fan update
def sendconfigupdate(self,):
debug("config update: " + "RPU:CONFIG")
self.mcast.sendto("RPU:CONFIG\n", (MCAST_GRP, MCAST_PORT))
# start running the flow monitor in it's own thread
def spawn_flowmonitor(self):
while True:
try:
if(config['dispatch.debugMonitoring']):
self.flowmonitor.fakemonitor()
else:
self.flowmonitor.monitor()
except Exception, e:
log("serial connection stopped...")
debug( str(e) )
finally:
time.sleep(1)
log("flowmonitor aborted, restarting...")
def spawnWebSocketServer(self):
args = ["-p", "8081", "-d", "/var/www/html/python/ws"]
#only log all errors in the webservice if we are debuging, turn level to critical
if(not config['dispatch.debug']):
args.append("--log-level")
args.append("critical")
options, args = _parse_args_and_config(args=args)
options.cgi_directories = []
options.is_executable_method = None
os.chdir(options.document_root)
_configure_logging(options)
server = WebSocketServer(options)
server.serve_forever()
# main setup
def setup(self):
# need small delay to get logging going, otherwise first log entries are missing
time.sleep(2)
debug("starting setup...")
self.flowmonitor.setup()
# main start method
def start(self):
log("starting WS server")
t = threading.Thread(target=self.spawnWebSocketServer)
t.setDaemon(True)
t.start()
if self.useOption("useFlowMeter"):
log("starting tap flow meters...")
t = threading.Thread(target=self.spawn_flowmonitor)
t.setDaemon(True)
t.start()
else:
log("tap flow meters not enabled")
log("starting command server")
t = threading.Thread(target=self.commandserver.serve_forever)
t.setDaemon(True)
t.start()
log("starting fan control")
self.fanControl.start()
signal.pause()
debug( "exiting...")
#
def triggerAlaModeReset(self):
self.alaModeReconfig = True;
# check if something got changed which requires reset/reconfigure of alamode
def needAlaModeReconfig(self):
return 1 if self.alaModeReconfig else 0
# reset the alamode by tripping it's reset line
def resetAlaMode(self):
self.alaModeReconfig = False;
resetpin = 12
if GPIO_IMPORT_SUCCESSFUL:
GPIO.setup(int(resetpin), GPIO.OUT)
oldValue = GPIO.input(resetpin)
if (oldValue == 1):
value1 = 0
else:
value1 = 1
self.updatepin(resetpin, value1)
time.sleep(1)
self.updatepin(resetpin, oldValue)
self.OPTION_RESTART_FANTIMER_AFTER_POUR = self.getConfigValueByName("restartFanAfterPour")
# update PI gpio pin mode (either input or output), this requires that this is run as root
def setpinmode(self, pin, value):
if not GPIO_IMPORT_SUCCESSFUL:
return False
if (pin < 1):
debug("invalid pin " + str(pin))
return False
debug( "update pin MODE %s to %s" %(pin, value))
if int(value) == 0 :
GPIO.setup(int(pin), GPIO.IN)
else:
GPIO.setup(int(pin), GPIO.OUT)
return True
# update PI gpio pin (either turn on or off), this requires that this is run as root
def updatepin(self, pin, value):
if not GPIO_IMPORT_SUCCESSFUL:
return False
pin = int(pin)
value = int(value)
if (pin < 1):
debug("invalid pin " + str(pin))
return False
GPIO.setup(pin, GPIO.OUT)
oldValue = GPIO.input(pin)
if(oldValue != value):
#debug( "update pin %s from %s to %s" %(pin, oldValue, value))
if value == 0 :
GPIO.output(pin, GPIO.LOW)
else:
GPIO.output(pin, GPIO.HIGH)
sql = "UPDATE tapconfig SET valvePinState=" + str(value) + " WHERE valvePin =" + str(-1*pin)
con = self.connectDB()
cursor = con.cursor(mdb.cursors.DictCursor)
result = cursor.execute(sql)
con.commit()
con.close()
return True
return False
# update PI gpio pin (either turn on or off), this requires that this is run as root
def readpin(self, pin):
if not GPIO_IMPORT_SUCCESSFUL:
return 0
pin = int(pin)
if (pin < 1):
debug("invalid pin " + str(pin))
return 0
value = GPIO.input(pin)
debug( "read pin %s value %s" %(pin, value))
return value;
def valveStopPower(self):
debug( "stopping valve power on pin %s" %(OPTION_VALVEPOWERPIN))
self.updatepin(self.getValvesPowerPin(), 0)
def updateValvePins(self):
taps = self.getTapConfig()
ii = 0
for tap in taps:
if( len(self.valvesState) < ii + 1):
self.valvesState.append(-1)
if(tap["valveOn"] is None):
tap["valveOn"] = 0
if self.valvesState[ii] != int(tap["valveOn"]):
self.sendvalveupdate(ii, tap["valveOn"])
self.valvesState[ii] = int(tap["valveOn"])
ii = ii + 1
def getValvesState(self):
return self.valvesState
def getConfigItem(self, itemName):
config = self.getConfig()
for item in config:
if (item["configName"] == itemName):
return item
return None
def updateFlowmeterConfig(self):
pourShutOffCountItem = self.getConfigItem("pourShutOffCount")
if(pourShutOffCountItem is None):
self.pourShutOffCount = 0;
else:
self.pourShutOffCount = int(pourShutOffCountItem["configValue"])
def useOption(self, option):
cfItem = self.getConfigItem(option)
if cfItem is None:
return False
cfUse = cfItem["configValue"]
if(int(cfUse) == 1):
return True
return False
def getValvesPowerPin(self):
if self.useOption("useTapValves"):
valveItem = self.getConfigItem("valvesPowerPin")
if valveItem is not None:
return int(valveItem["configValue"])
return -1
def getValvesPowerTime(self):
if self.useOption("useTapValves"):
valveItem = self.getConfigItem("valvesOnTime")
if valveItem is not None:
return int(valveItem["configValue"])
return -1
def shutdown(self,):
log("Shuting Down System")
os.system('sudo shutdown -P now')
def restart(self,):
log("Rebooting System")
os.system('sudo reboot')
def restartService(self,):
log("Restarting Service")
os.system('sudo /etc/init.d/flowmon restart')
class FanControlThread (threading.Thread):
restart = False
def __init__(self, threadID, dispatch):
threading.Thread.__init__(self)
self.threadID = threadID
self.dispatch = dispatch
self.shutdown_required = False
self.restartLock = Lock()
self.restartNeeded(False)
def exit(self):
self.shutdown_required = True
def restartNeeded(self, restart=None):
self.restartLock.acquire()
if not restart is None:
if not self.restart and restart:
debug( "restarting fan timer after pour" )
self.restart = restart
ret = self.restart
self.restartLock.release()
return ret
def updatePinAndWait(self, pin, value, waitTimeMins):
waitTimeSecs = waitTimeMins*60
#if check restart is false then apply fan update
if not self.restartNeeded() and waitTimeSecs > 0:
if self.dispatch.updatepin(pin, value):
self.dispatch.sendfanupdate(pin, value)
intervalStart = time.time()
#Check if restart was requested then seconds till on time is up
while not self.restartNeeded() and int(time.time() - intervalStart) < waitTimeSecs:
#wait min of what is left of on time or 5 seconds
time.sleep(min(5, waitTimeSecs - int(time.time() - intervalStart)))
def run(self):
log("Fan Control " + self.threadID + " is Running")
logNotEnable = True
try:
while not self.shutdown_required:
fanConfig = self.dispatch.useFanControl()
if not fanConfig:
if logNotEnable:
#only log this once during the disabled period, if enabled then disabled log again
log("Not Configured to run Fan")
logNotEnable = False
#wait 60 seconds then check if fan config changed
time.sleep(60)
continue
logNotEnable = True
pin = self.dispatch.getFanPin()
if pin < 1:
log("Fan pin not configured correctly (currently "+str(pin)+")")
time.sleep(60)
continue
self.restartNeeded(False)
self.updatePinAndWait(pin, 1, self.dispatch.getFanOnTime() )
self.updatePinAndWait(pin, 0, self.dispatch.getFanOffTime())
except:
log("Unable to run Fan Control Thread")
return
dispatch = PintDispatch()
dispatch.setup()
dispatch.start()
debug( "Exiting...")