def rebootPi(why): pclogging.systemlog(config.INFO, "Pi Rebooting: %s" % why) if (config.USEBLYNK): updateBlynk.blynkTerminalUpdate("Pi Rebooting: %s" % why) pclogging.systemlog(config.INFO, "Pi Rebooting: %s" % why) os.system("sudo shutdown -r now")
def on_WirelessMQTTClientmessage(client, userdata, message): print("Wireless MQTT Message received: ", message.payload) MQTTJSON = json.loads(message.payload.decode("utf-8")) if (str(MQTTJSON['messagetype']) == str(MQTTVALVECHANGE)): if (config.SWDEBUG): print("Valve Change Received") pclogging.writeMQTTValveChangeRecord(MQTTJSON) if (str(MQTTJSON['messagetype']) == str(MQTTALARM)): if (config.SWDEBUG): print("Alarm Message Received") pclogging.systemlog(config.CRITICAL, MQTTJSON['argument']) if (str(MQTTJSON['messagetype']) == str(MQTTDEBUG)): if (config.SWDEBUG): print("Debug Message Recieved") temp = str(MQTTJSON['id']) + ", " + str(MQTTJSON['value']) pclogging.systemlog(config.DEBUG, temp) if (str(MQTTJSON['messagetype']) == str(MQTTSENSORS)): if (config.SWDEBUG): print("Sensor Message Recieved") processSensorMessage(MQTTJSON)
def processF016TH(sLine): if (config.SWDEBUG): sys.stdout.write('Processing F016TH data' + '\n') sys.stdout.write('This is the raw data: ' + sLine + '\n') var = json.loads(sLine) state.mainID = var["device"] + var["channel"] state.lastIndoorReading = nowStr() if (state.previousIndoorReading == "Never"): pclogging.systemlog(config.INFO, "Indoor Weather Sensor Found") print("Indoor Weather Sensors Found") state.previousIndoorReading = state.lastIndoorReading state.IndoorTemperature = round( ((var["temperature_F"] - 32.0) / (9.0 / 5.0)), 2) state.IndoorHumidity = var["humidity"] state.lastIndoorReading = var["time"] state.insideID = var["channel"] indoorTH.addITReading(var["device"], var["channel"], state.IndoorTemperature, var["humidity"], var["battery"], var["time"]) #print("looking for buildJSONSemaphore acquire") state.buildJSONSemaphore.acquire() #print("buildJSONSemaphore acquired") state.StateJSON = buildJSON.getStateJSON() #if (config.SWDEBUG): # print("currentJSON = ", state.StateJSON) state.buildJSONSemaphore.release()
def shutdownPi(why): pclogging.systemlog(config.INFO, "Pi Shutting Down: %s" % why) sendemail.sendEmail("test", "SkyWeather2 Shutting down:" + why, "The SkyWeather2 Raspberry Pi shutting down.", config.notifyAddress, config.fromAddress, "") sys.stdout.flush() time.sleep(10.0) os.system("sudo shutdown -h now")
def processF016TH(sLine): if (config.SWDEBUG): sys.stdout.write('Processing F016TH data'+'\n') sys.stdout.write('This is the raw data: ' + sLine + '\n') var = json.loads(sLine) IT = round(((var["temperature_F"] - 32.0)/(9.0/5.0)),2) # check for bad read (not caught by checksum for some reason) # may be related to low battery if ((IT > 100.00) or (IT < -35)): # bad temperatures / Humidity #skip read return state.mainID = var["device"] + var["channel"] state.lastIndoorReading = nowStr() if (config.MQTT_Enable == True): mqtt_publish_single(sLine, f"F016TH/{var['channel']}") if (state.previousIndoorReading == "Never"): pclogging.systemlog(config.INFO,"Indoor Weather Sensor Found") print("Indoor Weather Sensors Found") state.previousIndoorReading = state.lastIndoorReading state.IndoorTemperature = IT state.IndoorHumidity = var["humidity"] state.lastIndoorReading = var["time"] state.insideID = var["channel"] indoorTH.addITReading(var["device"], var["channel"], state.IndoorTemperature, var["humidity"], var["battery"], var["time"]) #print("looking for buildJSONSemaphore acquire") state.buildJSONSemaphore.acquire() #print("buildJSONSemaphore acquired") state.StateJSON = buildJSON.getStateJSON() #if (config.SWDEBUG): # print("currentJSON = ", state.StateJSON) # pass state.buildJSONSemaphore.release()
def updateDeviceStatus(Log): #state.deviceStatus = {} wirelessJSON = readJSON.getJSONValue("WirelessDeviceJSON") for single in wirelessJSON: myID = str(single["id"]) deviceResult = checkDeviceStatus(single["id"]) if (deviceResult == False): # check again if false deviceResult = checkDeviceStatus(single["id"]) if (deviceResult): try: if (state.deviceStatus[str(single['id'])] == False): pclogging.systemlog( config.INFO, "Wireless Device ID %s Reactivated" % (myID)) except: #traceback.print_exc() pass if (Log): pclogging.systemlog(config.INFO, "Wireless Device ID %s Active" % (myID)) state.deviceStatus[str(single["id"])] = True else: try: if (state.deviceStatus[str(single['id'])] == True): pclogging.systemlog( config.INFO, "Wireless Device ID %s has gone Inactive" % (myID)) except: #traceback.print_exc() pass state.deviceStatus[str(single["id"])] = False if (Log): pclogging.systemlog( config.INFO, "Wireless Device ID %s is Inactive" % (myID)) state.deviceStatus[str(single["id"])] = False
def initializeSGSPart1(): print("###############################################") print("SGS2 Version "+SGSVERSION+" - SwitchDoc Labs") print("###############################################") print("") print("Program Started at:"+ time.strftime("%Y-%m-%d %H:%M:%S")) print("") # read in JSON # read in JSON if (readJSON.readJSON("") == False): print("#############################") print("No SGS.JSON file present - configure with 'sudo python3 SGSConfigure.py'") print("#############################") exit() readJSON.readJSONSGSConfiguration("") #init blynk app state if (config.USEBLYNK): updateBlynk.blynkInit() message = "SGS Version "+SGSVERSION+" Started" pclogging.systemlog(config.INFO,message) pclogging.systemlog(config.JSON,"SGS.JSON Loaded: "+json.dumps(config.JSONData )) pclogging.systemlog(config.JSON,"SGSConfigurationJSON.JSON Loaded: "+json.dumps(config.SGSConfigurationJSON )) pclogging.systemlog(config.CRITICAL,"No Alarm") if (config.GardenCam_Present): pclogging.systemlog(config.INFO,"Garden Cam Present") else: pclogging.systemlog(config.INFO,"Garden Cam NOT Present") # scan and check for resources # get if weather is being used config.Weather_Present = readJSON.getJSONValue("weather") pass
# Main Loop ############# while True: # check for new JSON files if (os.path.exists('NEWJSON') == True): # remove file print("-----------------------") print("New JSON files detected") print("SGS2 reloading JSON configuration") print("-----------------------") os.remove('NEWJSON') restartSGS() pclogging.systemlog(config.INFO,"Reloading SGS with New JSON") else: #print("No New JSON Files Detected") pass time.sleep(10.0) except KeyboardInterrupt: # here you put any code you want to run before the program # exits when you press CTRL+C print("exiting program") #except: # this catches ALL other exceptions including errors. # You won't get any error messages for debugging
def processF020(sLine): if (config.SWDEBUG): sys.stdout.write("processing FT020T Data\n") sys.stdout.write('This is the raw data: ' + sLine + '\n') var = json.loads(sLine) # outside temperature and Humidity state.mainID = var["id"] state.lastMainReading = nowStr() if (state.previousMainReading == "Never"): pclogging.systemlog(config.INFO, "Main Weather Sensors Found") print("Main Weather Sensors Found") pclogging.systemlog(config.INFO, "Blynk Updates Started") state.previousMainReading = state.lastMainReading wTemp = var["temperature"] ucHumi = var["humidity"] wTemp = (wTemp - 400) / 10.0 # deal with error condtions if (wTemp > 140.0): # error condition from sensor if (config.SWDEBUG): sys.stdout.write("error--->>> Temperature reading from FT020T\n") sys.stdout.write('This is the raw temperature: ' + str(wTemp) + '\n') # put in previous temperature wtemp = state.OudoorTemperature #print("wTemp=%s %s", (str(wTemp),nowStr() )); if (ucHumi > 100.0): # bad humidity # put in previous humidity ucHumi = state.OutdoorHumidity state.OutdoorTemperature = round(((wTemp - 32.0) / (9.0 / 5.0)), 2) state.OutdoorHumidity = ucHumi state.WindSpeed = round(var["avewindspeed"] / 10.0, 1) state.WindGust = round(var["gustwindspeed"] / 10.0, 1) state.WindDirection = var["winddirection"] state.TotalRain = round(var["cumulativerain"] / 10.0, 1) state.Rain60Minutes = 0.0 wLight = var["light"] if (wLight >= 0x1fffa): wLight = wLight | 0x7fff0000 wUVI = var["uv"] if (wUVI >= 0xfa): wUVI = wUVI | 0x7f00 state.SunlightVisible = wLight state.SunlightUVIndex = round(wUVI / 10.0, 1) if (var['batterylow'] == 0): state.BatteryOK = "OK" else: state.BatteryOK = "LOW" #print("looking for buildJSONSemaphore acquire") state.buildJSONSemaphore.acquire() #print("buildJSONSemaphore acquired") state.StateJSON = buildJSON.getStateJSON() #if (config.SWDEBUG): # print("currentJSON = ", state.StateJSON) state.buildJSONSemaphore.release()
def readSensors(): print("") print("######") # Create our sub-process... # Note that we need to either ignore output from STDERR or merge it with STDOUT due to a limitation/bug somewhere under the covers of "subprocess" # > this took awhile to figure out a reliable approach for handling it... p = Popen(cmd, stdout=PIPE, stderr=STDOUT, bufsize=1, close_fds=ON_POSIX) q = Queue() t = Thread(target=enqueue_output, args=('stdout', p.stdout, q)) t.daemon = True # thread dies with the program t.start() # --------------------------------------------------------------------------------------------------------------------------------------------------------------- pulse = 0 print("starting 433MHz scanning") print("######") lastTimeSensorReceived = time.time() while True: # Other processing can occur here as needed... #sys.stdout.write('Made it to processing step. \n') timeSinceLastSample = time.time() - lastTimeSensorReceived if (timeSinceLastSample > 720.0): # restart if no reads in 12 minutes if (config.SWDEBUG): print(">>>>>>>>>>>>>>restarting SDR thread.....") lastTimeSensorReceived = time.time() if (config.SWDEBUG): print("Killing SDR Thread") p.kill() t.join() pclogging.systemlog(config.INFO, "SDR Restarted") if (config.SWDEBUG): print("starting SDR Thread again") print("") print("######") print("Read Wireless Sensors") print("######") p = Popen(cmd, stdout=PIPE, stderr=STDOUT, bufsize=1, close_fds=ON_POSIX) q = Queue() t = Thread(target=enqueue_output, args=('stdout', p.stdout, q)) t.daemon = True # thread dies with the program t.start() try: src, line = q.get(timeout=1) #print(line.decode()) except Empty: pulse += 1 else: # got line pulse -= 1 sLine = line.decode() #if ( sLine.find('F007TH') != -1) or ( sLine.find('FT0300') != -1) or ( sLine.find('F016TH') != -1) or ( sLine.find('FT020T') != -1): # pclogging.systemlog(config.INFO,"SDR Received data in =%6.2f seconds"%(timeSinceLastSample)) lastTimeSensorReceived = time.time() # See if the data is something we need to act on... if (sLine.find('F007TH') != -1) or ( sLine.find('FT0300') != -1 ) or (sLine.find('F016TH') != -1) or (sLine.find('FT020T') != -1): if ((sLine.find('F007TH') != -1) or (sLine.find('F016TH') != -1)): processF016TH(sLine) if ((sLine.find('FT0300') != -1) or (sLine.find('FT020T') != -1)): processF020(sLine) sys.stdout.flush()
print(util.returnStatusEnable("UseWSLIGHTNING", config.USEWSLIGHTNING)) print(util.returnStatusEnable("UseWSAQI", config.USEWSAQI)) print(util.returnStatusEnable("UseWSSKYCAM", config.USEWSSKYCAM)) print(util.returnStatusEnable("UseMySQL", config.enable_MySQL_Logging)) print(util.returnStatusEnable("UseMQTT", config.MQTT_Enable)) print(util.returnStatusLine("Check WLAN", config.enable_WLAN_Detection)) print( util.returnStatusLine("WeatherUnderground", config.WeatherUnderground_Present)) print(util.returnStatusLine("UseWeatherStem", config.USEWEATHERSTEM)) print("----------------------") # startup pclogging.systemlog(config.INFO, "SkyWeather2 Startup Version " + config.SWVERSION) if (config.USEBLYNK): updateBlynk.blynkEventUpdate("SW Startup Version " + config.SWVERSION) updateBlynk.blynkTerminalUpdate("SW Startup Version " + config.SWVERSION) subjectText = "The " + config.STATIONKEY + " SkyWeather2 Raspberry Pi has #rebooted." ipAddress = subprocess.check_output(['hostname', '-I']) bodyText = "SkyWeather2 Version " + config.SWVERSION + " Startup \n" + ipAddress.decode( ) + "\n" if (config.SunAirPlus_Present): sampleSunAirPlus() bodyText = bodyText + "\n" + "BV=%0.2fV/BC=%0.2fmA/SV=%0.2fV/SC=%0.2fmA" % ( batteryVoltage, batteryCurrent, solarVoltage, solarCurrent) sendemail.sendEmail("test", bodyText, subjectText, config.notifyAddress,
def blynkStatusUpdate(): if (DEBUGBLYNK): print("blynkStatusUpdate Entry") try: put_header = {"Content-Type": "application/json"} # read button and menu selection states # state.WirelessDeviceSelectorPlant r = requests.get(config.BLYNK_URL + config.BLYNK_AUTH + '/get/V49') # read button state myText = r.text #print("myTextB=", myText) if (myText == "[]"): myText = "0" myText = myText.replace('["', '') myText = myText.replace('"]', '') #print("myText=", myText) state.WirelessDeviceSelectorPlant = int(myText) # now do the choices on page two and three myName = "No Wireless Unit Selected" PlantIPAddress = "" if (state.WirelessDeviceSelectorPlant > 0): myJSONWireless = readJSON.getJSONValue("WirelessDeviceJSON") i = 0 if (len(myJSONWireless) > state.WirelessDeviceSelectorPlant): myName = str(i) + ":" + "No Wireless Unit Selected" for single in myJSONWireless: i = i + 1 if (state.WirelessDeviceSelectorPlant == i): myName = str(i) + ": " + str( single["id"] ) + "/" + single["name"] + "/" + single["ipaddress"] PlantIPAddress = single["ipaddress"] val = myName put_body = json.dumps([val]) r = requests.put(config.BLYNK_URL + config.BLYNK_AUTH + '/update/V40', data=put_body, headers=put_header) # state.WirelessDeviceSelectorControl r = requests.get(config.BLYNK_URL + config.BLYNK_AUTH + '/get/V45') # read button state myText = r.text if (myText == "[]"): myText = "0" myText = myText.replace('["', '') myText = myText.replace('"]', '') state.WirelessDeviceSelectorControl = int(myText) # now do the choices on page two and three myControlName = "No Wireless Unit Selected" ControlIPAddress = "" ControlID = "" if (state.WirelessDeviceSelectorControl > 0): myJSONWireless = readJSON.getJSONValue("WirelessDeviceJSON") i = 0 if (len(myJSONWireless) > state.WirelessDeviceSelectorControl): myControlName = str(i) + ":" + "No Wireless Unit Selected" for single in myJSONWireless: i = i + 1 if (state.WirelessDeviceSelectorControl == i): myControlName = str(i) + ": " + str( single["id"] ) + "/" + single["name"] + "/" + single["ipaddress"] ControlIPAddress = single["ipaddress"] ControlID = str(single["id"]) val = myControlName put_body = json.dumps([val]) r = requests.put(config.BLYNK_URL + config.BLYNK_AUTH + '/update/V39', data=put_body, headers=put_header) # state.ValveSelector r = requests.get(config.BLYNK_URL + config.BLYNK_AUTH + '/get/V46') # read button state myText = r.text if (myText == "[]"): myText = "0" myText = myText.replace('["', '') myText = myText.replace('"]', '') state.ValveSelector = int(myText) # state.SecondsToTurnOn r = requests.get(config.BLYNK_URL + config.BLYNK_AUTH + '/get/V47') # read button state myText = r.text if (myText == "[]"): myText = "0" myText = myText.replace('["', '') myText = myText.replace('"]', '') state.SecondsToTurnOn = int(myText) # state.TurnOnValveButton # Look for Valve turn on r = requests.get(config.BLYNK_URL + config.BLYNK_AUTH + '/get/V41') # read button state if (r.text == '["1"]'): state.TurnOnValveButton = True if (DEBUGBLYNK): print( "blynkStatusUpdate:POSTBRC:state.TurnOnValveButton set to True" ) else: state.TurnOnValveButton = False if (DEBUGBLYNK): print( "blynkStatusUpdate:POSTBRC:state.TurnOnValveButton set to False" ) # state.BlinkWirelessUnit r = requests.get(config.BLYNK_URL + config.BLYNK_AUTH + '/get/V48') # read button state if (r.text == '["1"]'): state.BlinkWirelessUnit = True if (DEBUGBLYNK): print( "blynkStatusUpdate:POSTBRC:state.BlinkWirelessUnit set to True" ) else: state.BlinkWirelessUnit = False if (DEBUGBLYNK): print( "blynkStatusUpdate:POSTBRC:state.BlinkWirelessUnit set to False" ) if (DEBUGBLYNK): print("state.WirelessDeviceSelectorPlant =", state.WirelessDeviceSelectorPlant) print("state.WirelessDeviceSelectorControl =", state.WirelessDeviceSelectorControl) print("state.ValveSelector =", state.ValveSelector) print("state.SecondsToTurnOn =", state.SecondsToTurnOn) print("state.TurnOnValveButton =", state.TurnOnValveButton) print("state.BlinkWirelessUnit =", state.BlinkWirelessUnit) r = requests.get(config.BLYNK_URL + config.BLYNK_AUTH + '/update/V5?color=%23FF0000') # Red time.sleep(1) r = requests.get(config.BLYNK_URL + config.BLYNK_AUTH + '/update/V5?color=%2300FF00') # Green # now deal with the button pushes if (state.BlinkWirelessUnit == True): if (ControlIPAddress != ""): myCommand = "blinkPixelCommand?params=admin" result = AccessValves.sendCommandToWireless( ControlIPAddress, myCommand) r = requests.get(config.BLYNK_URL + config.BLYNK_AUTH + '/update/V48?value=0') if (state.TurnOnValveButton == True): if (ControlID != ""): if (state.ValveSelector > 0): if (state.SecondsToTurnOn > 0): if (config.manual_water == True): MQTTFunctions.sendMQTTValve( ControlID, str(state.ValveSelector), 1, str(state.SecondsToTurnOn)) message = "Manual Valve %d Actuated: %s" % ( state.ValveSelector, myControlName) pclogging.systemlog(config.INFO, message) pclogging.valvelog(ControlID, str(state.ValveSelector), 1, "Manual Event ", "", state.SecondsToTurnOn) r = requests.get(config.BLYNK_URL + config.BLYNK_AUTH + '/update/V41?value=0') blynkStateUpdate() return 1 except Exception as e: print("exception in blynkStatusUpdate") print(e) return 0
def processFT020T(sLine, lastFT020TTimeStamp, UpdateWR2 ): if (config.SWDEBUG): sys.stdout.write("processing FT020T Data\n") sys.stdout.write('This is the raw data: ' + sLine + '\n') var = json.loads(sLine) if (lastFT020TTimeStamp == var["time"]): # duplicate if (config.SWDEBUG): sys.stdout.write("duplicate found\n") return "" lastFT020TTimeStamp = var["time"] if (config.MQTT_Enable == True): mqtt_publish_single(sLine, "FT020T") # now check for adding record # outside temperature and Humidity state.mainID = var["id"] state.lastMainReading = nowStr() if (state.previousMainReading == "Never"): pclogging.systemlog(config.INFO,"Main Weather Sensors Found") print("Main Weather Sensors Found") pclogging.systemlog(config.INFO,"Blynk Updates Started") state.previousMainReading = state.lastMainReading wTemp = var["temperature"] ucHumi = var["humidity"] wTemp = (wTemp - 400)/10.0 # deal with error condtions if (wTemp > 140.0): # error condition from sensor if (config.SWDEBUG): sys.stdout.write("error--->>> Temperature reading from FT020T\n") sys.stdout.write('This is the raw temperature: ' + str(wTemp) + '\n') # put in previous temperature wtemp = state.OutdoorTemperature #print("wTemp=%s %s", (str(wTemp),nowStr() )); if (ucHumi > 100.0): # bad humidity # put in previous humidity ucHumi = state.OutdoorHumidity state.OutdoorTemperature = round(((wTemp - 32.0)/(9.0/5.0)),2) state.OutdoorHumidity = ucHumi state.WindSpeed = round(var["avewindspeed"]/10.0, 1) state.WindGust = round(var["gustwindspeed"]/10.0, 1) state.WindDirection = var["winddirection"] state.TotalRain = round(var["cumulativerain"]/10.0,1) wLight = var["light"] #if (wLight >= 0x1fffa): # wLight = wLight | 0x7fff0000 wUVI =var["uv"] if (wUVI >= 0xfa): wUVI = wUVI | 0x7f00 state.SunlightVisible = wLight state.SunlightUVIndex = round(wUVI/10.0, 1 ) if (var['batterylow'] == 0): state.BatteryOK = "OK" else: state.BatteryOK = "LOW" state.SerialNumber = var['id'] state.RSSI = var['rssi'] state.SNR = var['snr'] state.NOISE = var['noise'] #print("looking for buildJSONSemaphore acquire") state.buildJSONSemaphore.acquire() #print("buildJSONSemaphore acquired") if (UpdateWR2): # now add to MWR2Array WeatherRack2Array.addWR2Reading(var) state.StateJSON = buildJSON.getStateJSON() #if (config.SWDEBUG): # print("currentJSON = ", state.StateJSON) state.buildJSONSemaphore.release() #print("buildJSONSemaphore released") return lastFT020TTimeStamp