def toDict(): "This compiles all data into a python list format." sharedFunc.sPrint("Compile: Creating data dictionary...") # compile individual module data to one big file data = {} #dataToCheck = ["presenceBt","presencePc","presenceMotion","presenceWifi","roomSleep","pcAwake","lightLevel"] dataToCheck = [ "presenceBt", "presencePc", "presenceMotion", "presenceWifi", "roomSleep", "keepPcAwake", "sensorsMode" ] for sItem in dataToCheck: data[sItem] = getValue(sItem) # set presence value (only for BT and PC) if (data['presenceBt'] == 1) or (data['presencePc'] == 1): if (data['presenceBt'] == 1) and (data['presencePc'] == 1): data['presence'] = int(9) elif (data['presencePc'] == 1): data['presence'] = int(2) elif (data['presenceBt'] == 1): data['presence'] = int(1) else: data['presence'] = int(0) # light sensor data['lightLevel'] = float(sensorLight.readLight()) # temp sensor data['temperature'] = float(sensorTemp.read_temp()) return data
def exportJson(): "This compiles all data into json format." sharedFunc.sPrint("\nType: exportJson") data = toDict() # save main/all settings to file dataJson = json.dumps(data) sharedFunc.sPrint("Data: " + dataJson) outFile = open(jsonFilePath, 'w') outFile.write(dataJson) outFile.close() sharedFunc.sPrint("Export: " + jsonFilePath) return
def checkAll(data={}): "This checks data against rules." sharedFunc.sPrint("\nType: checkAll") sharedFunc.sPrint("Time: " + time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime())) # check if data dictionary has any keys at all if (any(data) == False): data = dataCompiler.toDict() else: # prepare essential data data["sensorsMode"] = dataCompiler.getValue("sensorsMode") data["lightLevel"] = dataCompiler.getValue("lightLevel") data["roomSleep"] = dataCompiler.getValue("roomSleep") data["presenceMotion"] = dataCompiler.getValue("presenceMotion") data["presenceWifi"] = dataCompiler.getValue("presenceWifi") sharedFunc.sPrint("Data: " + str(data)) # AUTOMATION RULES resultStr = "" sharedFunc.sPrint("Check: All Rules") # disable if sensorsMode is 0 if (data.get('sensorsMode', 'NA') == 0): # end now sharedFunc.sPrint('sesnorMode is 0, all rules bypassed.') return # based on roomSleep if (data['roomSleep'] == 0) or (data['roomSleep'] == -1): if (data['lightLevel'] < lightThreshold[0]): #resultStr += "Light is below threshold of "+lightThreshold[0]+", " if (data.get('presenceMotion', 0) == 1): sharedFunc.sPrint('Presence: Motion') sharedFunc.sPrint('Elapsed: ' + str(time.time() - float(data['presenceMotion']))) sharedFunc.sPrint('Ambient: Dark') switchRegulator.bedroomLamp('on') resultStr += "Motion detected recently. Bedroom Lamp = On. " elif (data.get('presenceBt', 'NA') == 0): sharedFunc.sPrint('BT: Missing') switchRegulator.bedroomLamp('off') resultStr += "Missing BT device. Bedroom Lamp = Off. " #elif ((data.get('presenceBt',0) == 1) or (data.get('presencePc',0) == 1)): elif (data.get('presenceBt', 0) == 1 or data.get('presencePc', 'NA') == 1): sharedFunc.sPrint('Presence: BT/PC') sharedFunc.sPrint('Ambient: Dark') switchRegulator.bedroomLamp('on') #resultStr += "presenceBt and/or presencePc is 1. Bedroom Lamp = On." resultStr += "Present BT device and/or PC is active. Bedroom Lamp = On. " # if BT is detected but presenceWifi is still 0, then set presenceWifi as "just home" aka 9 if (data.get('presenceWifi', 'NA') == 9) and (data.get( 'presencePc', 'NA') == -1): switchRegulator.bedroomPc('wake') elif (data['lightLevel'] > lightThreshold[1]): sharedFunc.sPrint('Ambient: Bright') switchRegulator.bedroomLamp('off') resultStr += "Light is above threshold of " + str( lightThreshold[1]) + ". Bedroom Lamp = Off. " # if roomSleep is set to No for the first time if (data['roomSleep'] == -1): resultStr += "Resetting roomSleep to 0. " sharedFunc.valSave(0, sys.path[0] + '/data/roomSleep.dat') if (data['presencePc'] == -1) or (dataCompiler.getValue("presencePc") == -1): switchRegulator.bedroomPc('wake') resultStr += "Jin's PC = Wake. " elif (data['roomSleep'] == 1): switchRegulator.bedroomLamp('off') resultStr += "Bedroom Lamp = Off. " if (dataCompiler.getValue("keepPcAwake") == 0) and (dataCompiler.getValue("presencePc") != -1): switchRegulator.bedroomPc('sleep') resultStr += "Jin's PC = Sleep. " # (if phone is not at home, in that no BT and no Wifi) if (data.get('presenceWifi', 'NA') == 0) and (data.get('presenceBt', 'NA') == 0): resultStr += "Jin is not currently at home. " if (dataCompiler.getValue("presenceHome") == 1): sharedFunc.valSave(0, sys.path[0] + '/data/presenceHome.dat') sharedFunc.pushbullet( "Goodbye Jin! Devices will now be turned off.") if (data['roomSleep'] != 0): # set roomSleep as 0 sharedFunc.valSave(0, sys.path[0] + '/data/roomSleep.dat') resultStr += "roomSleep is set to 0. " if (data.get('presencePc', 'NA') != -1): # turn off PC switchRegulator.bedroomPc('sleep') resultStr += "Jin's PC = Sleep." # (if phone just got home) if (data.get('presenceWifi', 'NA') == 9): if (dataCompiler.getValue("presenceHome") == 0): sharedFunc.valSave(1, sys.path[0] + '/data/presenceHome.dat') if (data.get('presencePc', 'NA') == -1): switchRegulator.bedroomPc('wake') # new code for fan (not optimised, newish) if (data.get('presenceBt', 'NA') == 0): switchRegulator.bedroomFan('off') resultStr += "Bedroom Fan = Off. " elif (data.get('presenceBt', 'NA') == 1): switchRegulator.bedroomFan('on') resultStr += "Bedroom Fan = On. " if (resultStr == ""): sharedFunc.sPrint('No rules are matched. No action is taken.') logger.info(callerName + "'s request using " + str(data) + ". " + resultStr) return
if (data.get('presenceBt', 'NA') == 0): switchRegulator.bedroomFan('off') resultStr += "Bedroom Fan = Off. " elif (data.get('presenceBt', 'NA') == 1): switchRegulator.bedroomFan('on') resultStr += "Bedroom Fan = On. " if (resultStr == ""): sharedFunc.sPrint('No rules are matched. No action is taken.') logger.info(callerName + "'s request using " + str(data) + ". " + resultStr) return if __name__ == "__main__": if "-silent" in sys.argv: sharedFunc.sPrint_silent = 1 if "-loop" in sys.argv: switchRegulator.setParentName("rulesProcessor (Loop)") callerName = "rulesProcessor (Loop)" triggerLight_last = 'none' try: while True: checkAll() sharedFunc.sPrint("\n[*] Sleeping for 120 seconds") time.sleep(120) except KeyboardInterrupt: sharedFunc.sPrint("\nQuit") else: checkAll()
def exportJson(): "This compiles all data into json format." sharedFunc.sPrint("\nType: exportJson") data = toDict() # save main/all settings to file dataJson = json.dumps(data) sharedFunc.sPrint("Data: " + dataJson) outFile = open(jsonFilePath, 'w') outFile.write(dataJson) outFile.close() sharedFunc.sPrint("Export: " + jsonFilePath) return if __name__ == "__main__": if "-silent" in sys.argv: sharedFunc.sPrint_silent = 1 if "-jsonExport" in sys.argv: while True: exportJson() sharedFunc.sPrint("\n[*] Sleeping for 5 seconds") time.sleep(5) else: print(toDict())
def checkBt(): print "presenceBt Module (CTRL-C to exit)" sharedFunc.sPrint("Data: " + outFilePath) missingNo = 0 foundNo = 0 sleepAmt = 20 try: while True: startRulesProcessor = 0 sharedFunc.sPrint("\nType: presenceBt") sharedFunc.sPrint( "Time: " + time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime())) sharedFunc.sPrint("Find: " + btStr + " (" + btMac + ")") try: result = bluetooth.lookup_name(btMac, timeout=3) except: sharedFunc.sPrint( "\n[*] Unable to scan. Trying again in 5 seconds.") time.sleep(5) else: resultInt = 0 if (result != None): if (foundNo >= 2 or checkInstantly): sharedFunc.sPrint("Result: Found") logger.info("Found") sleepAmt = 60 resultInt = 1 if (foundNo == 2 or checkInstantly): startRulesProcessor = 1 if (foundNo <= 19): sleepAmt = 30 foundNo += 1 else: sharedFunc.sPrint("Result: Possibly Found") logger.info("Possibly Found") sleepAmt = 5 resultInt = -1 missingNo = 0 foundNo += 1 else: if (missingNo >= 4): sharedFunc.sPrint("Result: Missing") logger.info("Missing") sleepAmt = 120 resultInt = 0 if (missingNo == 4): startRulesProcessor = 1 # if BT is missing, then set motion as (current time - 301 seconds) sharedFunc.valSave(str(time.time() - 301), motionFilePath) if (missingNo <= 19): sleepAmt = 30 missingNo += 1 else: sharedFunc.sPrint("Result: Possibly Missing") logger.info("Possibly Missing") sleepAmt = 5 resultInt = -1 foundNo = 0 missingNo += 1 if (resultInt != -1): sharedFunc.valSave(resultInt, outFilePath) if (startRulesProcessor == 1): # call main.py #runpy.run_path(sys.path[0]+"/main.py") rulesProcessor.checkAll({"presenceBt": resultInt}) startRulesProcessor = 0 if checkInstantly: break else: sharedFunc.sPrint("\n[*] Sleeping for " + str(sleepAmt) + " seconds") time.sleep(sleepAmt) except KeyboardInterrupt: print "\nQuit" return
if len(sys.argv) > 1 and sys.argv[1] == "-silent": sharedFunc.sPrint_silent = 1 # setup logging for switchRegulator (to move to rulesProcessor) switchRegulator.setParentName("presenceMotion") rulesProcessor.callerName = "presenceMotion" # Use BCM GPIO references # instead of physical pin numbers GPIO.setmode(GPIO.BCM) # Define GPIO to use on Pi GPIO_PIR = 7 print "presenceMotion Module (CTRL-C to exit)" sharedFunc.sPrint("Data: " + outFilePath) # Set pin as input GPIO.setup(GPIO_PIR, GPIO.IN) # Echo Current_State = 0 Previous_State = 0 try: sharedFunc.sPrint("\nWaiting for PIR to settle ...") # Loop until PIR output is 0 while GPIO.input(GPIO_PIR) == 1: Current_State = 0 sharedFunc.sPrint("\nType: presenceMotion")