def updateStaticBlynk(): put_header = {"Content-Type": "application/json"} val = str(len(readJSON.getJSONValue("WirelessDeviceJSON"))) put_body = json.dumps([val]) r = requests.put(config.BLYNK_URL + config.BLYNK_AUTH + '/update/V60', data=put_body, headers=put_header) val = str(config.valve_count) put_body = json.dumps([val]) r = requests.put(config.BLYNK_URL + config.BLYNK_AUTH + '/update/V61', data=put_body, headers=put_header) val = str(config.moisture_sensor_count) put_body = json.dumps([val]) r = requests.put(config.BLYNK_URL + config.BLYNK_AUTH + '/update/V62', data=put_body, headers=put_header) # now do the choices on page two and three myJSONWireless = readJSON.getJSONValue("WirelessDeviceJSON") labels = "" for single in myJSONWireless: myName = str( single["id"]) + "/" + single["name"] + "/" + single["ipaddress"] labels = labels + "'" + myName + "'," '''
def CRUnits(rain): English_Metric = readJSON.getJSONValue("English_Metric") if (English_Metric == False): # english units rain = rain / 25.4 return rain
def getNameFromID(myID): wirelessJSON = readJSON.getJSONValue("WirelessDeviceJSON") for singleWireless in wirelessJSON: if (str(myID).replace(" ", "") == str(singleWireless["id"]).replace( " ", "")): return singleWireless["name"] return "Inactive"
def CTUnits(temperature): English_Metric = readJSON.getJSONValue("English_Metric") if (English_Metric == False): # english units temperature = (9.0 / 5.0 * temperature) + 32.0 return temperature
def CWUnits(wind): English_Metric = readJSON.getJSONValue("English_Metric") if (English_Metric == False): # english units wind = wind * 2.23694 return wind
def CBUnits(barometricpressure): English_Metric = readJSON.getJSONValue("English_Metric") if (English_Metric == False): # english units barometricpressure = barometricpressure * .2953 return barometricpressure
def TUnits(): English_Metric = readJSON.getJSONValue("English_Metric") if (English_Metric == False): # english units units = " F" else: units = " C" return units
def WUnits(): English_Metric = readJSON.getJSONValue("English_Metric") if (English_Metric == False): # english units units = " mph" else: units = " m/s" return units
def BUnits(): English_Metric = readJSON.getJSONValue("English_Metric") if (English_Metric == False): # english units units = " in" else: units = " hPa" return units
def readAllMoistureSensors(): # force read from wireless systems if (config.LOCKDEBUG): print("UpdateStateLock Acquire Attempt - readAllMoistureSensors ") state.UpdateStateLock.acquire() if (config.LOCKDEBUG): print("UpdateStateLock Acquired - readAllMoistureSensors ") #wireless extender wirelessJSON = readJSON.getJSONValue("WirelessDeviceJSON") for singleWireless in wirelessJSON: myIP = singleWireless["ipaddress"] myCommand = "enableMoistureSensors?params=admin,1,1,1,1" returnJSON = AccessValves.sendCommandToWireless(myIP, myCommand) #print("returnJSON=", returnJSON) myCommand = "readMoistureSensors?params=admin" returnJSON = AccessValves.sendCommandToWireless(myIP, myCommand) #print("returnJSON=", returnJSON) if (len(returnJSON) != 0): parseSensors = returnJSON["return_string"] parseSensorsArray = parseSensors.split(",") for i in range(0, 4): for singleSensor in state.moistureSensorStates: if (singleSensor["id"] == singleWireless["id"]): if (singleSensor["sensorNumber"] == str(i + 1)): singleSensor["sensorValue"] = str( parseSensorsArray[i * 2 + 1]) currentTime = datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S') singleSensor["timestamp"] = currentTime #myCommand = "enableMoistureSensors?params=admin,0,0,0,0" #returnJSON = AccessValves.sendCommandToWireless(myIP, myCommand) pass if (config.SWDEBUG): print("-----------------") print("MoistureSensorStates") print(state.moistureSensorStates) print("-----------------") for singleSensor in state.moistureSensorStates: pclogging.sensorlog(singleSensor["id"], singleSensor["sensorNumber"], singleSensor["sensorValue"], singleSensor["sensorType"], singleSensor["timestamp"]) if (config.LOCKDEBUG): print("UpdateStateLock Releasing - readAllMoistureSensors") state.UpdateStateLock.release() if (config.LOCKDEBUG): print("UpdateStateLock Released - readAllMoistureSensors")
def turnOffAllValves(): wirelessJSON = readJSON.getJSONValue("WirelessDeviceJSON") for singlewireless in wirelessJSON: #adminpassword, valve0state, valve0length, valve1state, valve1state, ....... myIP = singlewireless["ipaddress"] myCommand = "setValves?params=admin,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0" result = sendCommandToWireless(myIP, myCommand) if (config.SWDEBUG): print("return=", result)
def initMoistureSensors(): state.moistureSensorStates = [] wirelessJSON = readJSON.getJSONValue("WirelessDeviceJSON") for singleWireless in wirelessJSON: for i in range(1, 5): element = {} element["id"] = str(singleWireless["id"]) element["sensorType"] = "C1" element["sensorNumber"] = str(i) element["sensorValue"] = "0.0" element["timestamp"] = datetime.datetime.now() state.moistureSensorStates.append(element)
def checkDeviceStatus(id): wirelessJSON = readJSON.getJSONValue("WirelessDeviceJSON") for single in wirelessJSON: ipAddress = single["ipaddress"] myID = single["id"] if (str(id).replace(" ", "") == str(myID)): myJSON = checkForDeviceFromIP(ipAddress) if (len(myJSON) > 0): #pclogging.systemlog(config.INFO,"Wireless Device ID %s Active" %(myID)) return True else: #pclogging.systemlog(config.INFO,"Wireless Device ID %s Inactive" %(myID)) return False return False
def turnOnTimedValve(singleValve): if (len(str(singleValve["id"]).replace(" ", "")) > 1): # wireless ID wirelessJSON = readJSON.getJSONValue("WirelessDeviceJSON") ''' for singlewireless in wirelessJSON: if (str(singleValve["id"]).replace(" ","") == str(singlewireless["id"]).replace(" ","")): myIP = singlewireless["ipaddress"] myCommand = "setSingleValve?params=admin,"+str(singleValve["ValveNumber"])+",1,"+str(singleValve["OnTimeInSeconds"]) sendCommandToWireless(myIP, myCommand) ''' MQTTFunctions.sendMQTTValve(str(singleValve["id"]), str(singleValve["ValveNumber"]), 1, str(singleValve["OnTimeInSeconds"])) # # DEBUG slow down by 1 second # time.sleep(1)
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
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 returnIndicators(): totalLayout = [] wirelessJSON = readJSON.getJSONValue("WirelessDeviceJSON") for singleWireless in wirelessJSON: myLabelLayout = [] valveStatus = returnLatestValveRecord(singleWireless['id'] ) myLabelLayout.append( html.H6(singleWireless['name'] +"/"+singleWireless['id'], ) ) myIndicatorLayout = [] for valve in range(1,9): currentValue = returnIndicatorValue(valveStatus, valve) if (currentValue): myColor = "greenyellow" else: myColor = "red" myIndicatorLayout.append( daq.Indicator( id = {'type' : 'SPdynamic', 'index': valve , 'DeviceID' : singleWireless['id'] }, color = myColor, label="Valve "+str(valve), value=True, style={ 'margin': '10px' } ) ) #myIndicatorCount = myIndicatorCount +1 totalLayout.append(dbc.Row( myLabelLayout)) totalLayout.append(dbc.Row(myIndicatorLayout)) return totalLayout
def generateCurrentWeatherJSON(): try: con = mdb.connect('localhost', 'root', config.MySQL_Password, 'SkyWeather2') cur = con.cursor() query = "SELECT * FROM `WeatherData` ORDER BY id DESC LIMIT 1" #print("query=", query) cur.execute(query) records = cur.fetchall() weatherRecordCount = len(records) #print ("queryrecords=",records) # get column names query = "SHOW COLUMNS FROM WeatherData" cur.execute(query) names = cur.fetchall() fieldcount = len(names) CWJSON = {} for i in range(0, fieldcount): if (names[i][0] == "TimeStamp"): if (weatherRecordCount == 0): CWJSON[names[i][0]] = 0 else: CWJSON[names[i][0]] = records[0][i] else: if (names[i][0] == "BatteryOK"): if (weatherRecordCount == 0): CWJSON[names[i][0]] = "LOW" else: CWJSON[names[i][0]] = records[0][i] else: if (weatherRecordCount == 0): CWJSON[names[i][0]] = 0 else: CWJSON[names[i][0]] = float(records[0][i]) if (weatherRecordCount == 0): CWJSON["StringTime"] = "" else: CWJSON["StringTime"] = records[0][1].strftime("%d-%b-%Y %H:%M:%S") CWJSON["StringTimeUnits"] = "" # now calculate rain # calendar day rain query = "SELECT id, TotalRain, TimeStamp FROM WeatherData WHERE DATE(TimeStamp) = CURDATE() ORDER by id ASC" cur.execute(query) rainspanrecords = cur.fetchall() if (len(rainspanrecords) > 0): rainspan = rainspanrecords[len(rainspanrecords) - 1][1] - rainspanrecords[0][1] else: rainspan = 0 CWJSON["CalendarDayRain"] = round(rainspan, 2) # Calendar Month query = "SELECT id, TotalRain, TimeStamp FROM WeatherData WHERE MONTH(TimeStamp) = MONTH(NOW()) AND YEAR(TimeStamp) = YEAR(NOW())" cur.execute(query) rainspanrecords = cur.fetchall() if (len(rainspanrecords) > 0): rainspan = rainspanrecords[len(rainspanrecords) - 1][1] - rainspanrecords[0][1] else: rainspan = 0 CWJSON["CalendarMonthRain"] = round(rainspan, 2) # last 30 days timeDelta = datetime.timedelta(days=30) now = datetime.datetime.now() before = now - timeDelta before = before.strftime('%Y-%m-%d %H:%M:%S') query = "SELECT id, TotalRain, TimeStamp FROM WeatherData WHERE (TimeStamp > '%s') ORDER BY TimeStamp " % ( before) cur.execute(query) rainspanrecords = cur.fetchall() if (len(rainspanrecords) > 0): rainspan = rainspanrecords[len(rainspanrecords) - 1][1] - rainspanrecords[0][1] else: rainspan = 0 CWJSON["30DayRain"] = round(rainspan, 2) # last 24 hours timeDelta = datetime.timedelta(days=1) now = datetime.datetime.now() before = now - timeDelta before = before.strftime('%Y-%m-%d %H:%M:%S') query = "SELECT id, TotalRain, TimeStamp FROM WeatherData WHERE (TimeStamp > '%s') ORDER BY TimeStamp " % ( before) cur.execute(query) rainspanrecords = cur.fetchall() if (len(rainspanrecords) > 0): rainspan = rainspanrecords[len(rainspanrecords) - 1][1] - rainspanrecords[0][1] else: rainspan = 0 CWJSON["24HourRain"] = round(rainspan, 2) # last 7 days timeDelta = datetime.timedelta(days=7) now = datetime.datetime.now() before = now - timeDelta before = before.strftime('%Y-%m-%d %H:%M:%S') query = "SELECT id, TotalRain, TimeStamp FROM WeatherData WHERE (TimeStamp > '%s') ORDER BY TimeStamp " % ( before) cur.execute(query) rainspanrecords = cur.fetchall() if (len(rainspanrecords) > 0): rainspan = rainspanrecords[len(rainspanrecords) - 1][1] - rainspanrecords[0][1] else: rainspan = 0 CWJSON["7DaysRain"] = round(rainspan, 2) con.commit() # convert to appropiate units and add units # set units English_Metric = readJSON.getJSONValue("English_Metric") if (English_Metric == False): # deal with English Units # temperature CWJSON["OutdoorTemperature"] = round( CTUnits(CWJSON["OutdoorTemperature"]), 1) CWJSON["OutdoorTemperatureUnits"] = TUnits() CWJSON["IndoorTemperature"] = round( CTUnits(CWJSON["IndoorTemperature"]), 1) CWJSON["IndoorTemperatureUnits"] = TUnits() CWJSON["BarometricTemperature"] = round( CTUnits(CWJSON["BarometricTemperature"]), 1) CWJSON["BarometricTemperatureUnits"] = TUnits() # wind units CWJSON["WindSpeed"] = round(CWUnits(CWJSON["WindSpeed"]), 1) CWJSON["WindSpeedUnits"] = WUnits() CWJSON["WindGust"] = round(CWUnits(CWJSON["WindGust"]), 1) CWJSON["WindGustUnits"] = WUnits() # rain units CWJSON["TotalRain"] = round(CRUnits(CWJSON["TotalRain"]), 1) CWJSON["TotalRainUnits"] = RUnits() CWJSON["CalendarDayRain"] = round( CRUnits(CWJSON["CalendarDayRain"]), 1) CWJSON["CalendarDayRainUnits"] = RUnits() CWJSON["CalendarMonthRain"] = round( CRUnits(CWJSON["CalendarMonthRain"]), 1) CWJSON["CalendarMonthRainUnits"] = RUnits() CWJSON["30DayRain"] = round(CRUnits(CWJSON["30DayRain"]), 1) CWJSON["30DayRainUnits"] = RUnits() CWJSON["24HourRain"] = round(CRUnits(CWJSON["24HourRain"]), 1) CWJSON["24HourRainUnits"] = RUnits() CWJSON["7DaysRain"] = round(CRUnits(CWJSON["7DaysRain"]), 1) CWJSON["7DaysRainUnits"] = RUnits() # Barometric Pressure CWJSON["BarometricPressureSeaLevel"] = round( CBUnits(CWJSON["BarometricPressureSeaLevel"]), 2) CWJSON["BarometricPressureSeaLevelUnits"] = BUnits() CWJSON["BarometricPressure"] = round( CBUnits(CWJSON["BarometricPressure"]), 2) CWJSON["BarometricPressureUnits"] = BUnits() else: # temperature units CWJSON["OutdoorTemperatureUnits"] = TUnits() CWJSON["IndoorTemperatureUnits"] = TUnits() CWJSON["BarometricTemperatureUnits"] = TUnits() # wind units CWJSON["WindSpeedUnits"] = WUnits() CWJSON["WindGustUnits"] = WUnits() # rain units CWJSON["TotalRainUnits"] = RUnits() CWJSON["CalendarDayRainUnits"] = RUnits() CWJSON["CalendarMonthRainUnits"] = RUnits() CWJSON["30DayRainUnits"] = RUnits() CWJSON["24HourRainUnits"] = RUnits() CWJSON["7DaysRainUnits"] = RUnits() # Barometric Pressure CWJSON["BarometricPressureSeaLevelUnits"] = BUnits() CWJSON["BarometricPressureUnits"] = BUnits() # always same units CWJSON["OutdoorHumidityUnits"] = "%" CWJSON["IndoorHumidityUnits"] = "%" CWJSON["SunlightVisibleUnits"] = "lux" CWJSON["SunlightUVIndexUnits"] = "" CWJSON["AQIUnits"] = "" CWJSON["AQI24AverageUnits"] = "" CWJSON["WindDirectionUnits"] = "deg" return CWJSON except: traceback.print_exc() #sys.exit(1) finally: cur.close() con.close() print("done generating CWJSON=", CWJSON) return CWJSON
def buildOutdoorTemperature_Humidity_Graph_Figure(): timeDelta = datetime.timedelta(days=7) records = fetchOTH(timeDelta) Time = [] Temperature = [] Humidity = [] for record in records: Time.append(record[2]) Temperature.append(record[0]) Humidity.append(record[1]) if (len(records) == 0): fig = go.Figure() fig.update_layout(height=800, title_text='No Weather Data Available') return fig # set units English_Metric = readJSON.getJSONValue("English_Metric") if (English_Metric == False): # english units for i in range(0, len(Temperature)): Temperature[i] = (9.0 / 5.0 * Temperature[i]) + 32.0 units = "F" else: units = "C" # Create figure with secondary y-axis fig = go.Figure() fig = make_subplots(specs=[[{"secondary_y": True}]]) # Add traces fig.add_trace( go.Scatter( x=Time, y=Temperature, name="Temperature", line=dict( color=('red'), width=2, ), ), secondary_y=False, ) fig.add_trace(go.Scatter( x=Time, y=Humidity, name="Humidity", line=dict( color=('blue'), width=2, ), ), secondary_y=True) # Add figure title fig.update_layout(title_text="Outdoor Temperature and Humidity ", height=400) # Set x-axis title fig.update_xaxes(title_text="Time") minTemp = min(Temperature) * 0.9 maxTemp = max(Temperature) * 1.10 # Set y-axes titles fig.update_yaxes(title_text="<b>Temperature (" + units + ")</b>", range=(minTemp, maxTemp), secondary_y=False, side='left') fig.update_yaxes(title_text="<b>Humidity (%)</b>", range=(0, 100), secondary_y=True, side='right') return fig
def fetchProgramming(): myArray = [] wirelessJSON = readJSON.getJSONValue("WirelessDeviceJSON") print("wirelessJSON = ", wirelessJSON) myIDList = [] myNameList = [] myValveNumberList = [] myControlList = [] myMSThresholdPercentList = [] myDOWCoverageList = [] myTimerSelectList = [] myStartTimeList = [] myOnTimeInSecondsList = [] myShowGraphList = [] for wireless in wirelessJSON: myID = wireless["id"] myName = wireless["name"] ''' for i in range (0,9): myList = [] myList.append(str(myID)) myList.append(str(myName)) currentValve = fetchValveJSON(myID, i) if len(currentValve) > 0: #print ('currentValve=', currentValve) myList.append(str(currentValve["ValveNumber"])) myList.append(str(currentValve["Control"])) myList.append(str(currentValve["MSThresholdPercent"])) myList.append(str(currentValve["TimerSelect"])) myList.append(str(currentValve["StartTime"])) myList.append(str(currentValve["OnTimeInSeconds"])) myList.append(str(currentValve["ShowGraph"])) myTuple = tuple(myList) myArray.append(myTuple) ''' for i in range(1, 9): myIDList.append(str(myID)) myNameList.append(str(myName)) currentValve = fetchValveJSON(myID, i) if len(currentValve) > 0: print('currentValve=', currentValve) myValveNumberList.append(str(currentValve["ValveNumber"])) myControlList.append(str(currentValve["Control"])) myMSThresholdPercentList.append( str(currentValve["MSThresholdPercent"])) myDOWCoverageList.append(str(currentValve["DOWCoverage"])) myTimerSelectList.append(str(currentValve["TimerSelect"])) myStartTimeList.append(str(currentValve["StartTime"])) myOnTimeInSecondsList.append( str(currentValve["OnTimeInSeconds"])) myShowGraphList.append(str(currentValve["ShowGraph"])) myArray.append(myIDList) myArray.append(myNameList) myArray.append(myValveNumberList) myArray.append(myControlList) myArray.append(myMSThresholdPercentList) myArray.append(myDOWCoverageList) myArray.append(myTimerSelectList) myArray.append(myStartTimeList) myArray.append(myOnTimeInSecondsList) myArray.append(myShowGraphList) # set up table display print('myArray=', myArray) return myArray
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 blynkStateUpdate(): try: put_header = {"Content-Type": "application/json"} if (DEBUGBLYNK): print("blynkStateUpdate:") blynkEventUpdate() # do our percentage active wirelessJSON = readJSON.getJSONValue("WirelessDeviceJSON") active = 0 for single in wirelessJSON: if (state.deviceStatus[single['id']] == True): active = active + 1 myPercent = 100.0 * active / len(state.deviceStatus) # do the graphs val = "{:4.1f}".format(myPercent) put_body = json.dumps([val]) r = requests.put(config.BLYNK_URL + config.BLYNK_AUTH + '/update/V1', data=put_body, headers=put_header) if (state.lastMainReading != "Never"): val = state.Hour24_AQI put_body = json.dumps([val]) if (DEBUGBLYNK): print("blynkStateUpdate:Pre:put_body:", put_body) r = requests.put(config.BLYNK_URL + config.BLYNK_AUTH + '/update/V11', data=put_body, headers=put_header) if (DEBUGBLYNK): print("blynkStateUpdate:POST:r.status_code:", r.status_code) val = util.returnTemperatureCF(state.OutdoorTemperature) put_body = json.dumps([val]) r = requests.put(config.BLYNK_URL + config.BLYNK_AUTH + '/update/V12', data=put_body, headers=put_header) val = state.OutdoorHumidity put_body = json.dumps([val]) r = requests.put(config.BLYNK_URL + config.BLYNK_AUTH + '/update/V14', data=put_body, headers=put_header) val = util.returnTemperatureCF(state.SunlightVisible) put_body = json.dumps([val]) r = requests.put(config.BLYNK_URL + config.BLYNK_AUTH + '/update/V15', data=put_body, headers=put_header) # do the boxes val = "{:4.1f}%".format(psutil.cpu_percent()) put_body = json.dumps([val]) r = requests.put(config.BLYNK_URL + config.BLYNK_AUTH + '/update/V2', data=put_body, headers=put_header) val = "{:4.1f}%".format(psutil.virtual_memory().percent) put_body = json.dumps([val]) r = requests.put(config.BLYNK_URL + config.BLYNK_AUTH + '/update/V3', data=put_body, headers=put_header) myValue = psutil.disk_usage('/') myDPercent = myValue[3] myDPercent = 100.0 - myDPercent val = "{:4.1f}%".format(myDPercent) put_body = json.dumps([val]) r = requests.put(config.BLYNK_URL + config.BLYNK_AUTH + '/update/V4', data=put_body, headers=put_header) # page 2 SensorsLevels myID = "" 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" myID = "" for single in myJSONWireless: i = i + 1 if (state.WirelessDeviceSelectorPlant == i): myName = str(i) + ": " + str( single["id"] ) + "/" + single["name"] + "/" + single["ipaddress"] PlantIPAddress = single["ipaddress"] myID = single["id"] if (myID != ""): print("setting Valves by Plant") blynkSetValves(myID, 29) # now have ID, so can find sensor values if (len(state.moistureSensorStates) > 0): for singleSensor in state.moistureSensorStates: if (str(singleSensor["id"]) == str(myID)): updateVirtual = "V" + str( int(singleSensor["sensorNumber"]) + 21) val = "{:4.1f}%".format( float(singleSensor["sensorValue"])) put_body = json.dumps([val]) r = requests.put(config.BLYNK_URL + config.BLYNK_AUTH + '/update/' + updateVirtual, data=put_body, headers=put_header) if (state.WirelessDeviceSelectorControl > 0): myJSONWireless = readJSON.getJSONValue("WirelessDeviceJSON") if (len(myJSONWireless) > state.WirelessDeviceSelectorControl): myID = "" i = 0 for single in myJSONWireless: i = i + 1 if (state.WirelessDeviceSelectorControl == i): myID = single["id"] if (myID != ""): print("setting Valves by Control") blynkSetValves(myID, 49) return 1 except Exception as e: print(traceback.format_exc()) print("exception in blynkStateUpdate") print(e) return 0
def fetchProgramming(): myArray = [] wirelessJSON = readJSON.getJSONValue("WirelessDeviceJSON") print("wirelessJSON = ", wirelessJSON) nextScheduleList = [] myTimeOn = [] myIDList = [] myNameList = [] myValveNumberList = [] myDOWCoverageList = [] myControlList = [] for wireless in wirelessJSON: myID = wireless["id"] myName = wireless["name"] for i in range(1, 9): myIDList.append(str(myID)) myNameList.append(str(myName)) currentValve = fetchValveJSON(myID, i) if len(currentValve) > 0: #print ('currentValve=', currentValve) myControl = currentValve["Control"] DOWNever = "" if (currentValve["DOWCoverage"] == "NNNNNNN"): DOWNever = "(COW: Never)" if (myControl[0:2] == "MS"): # found Moisture sensor nextScheduleList.append("Moisture Sensor " + DOWNever) else: if (myControl[0:3] == "Off"): # found Moisture sensor nextScheduleList.append("Off") else: myTempTime = currentValve["StartTime"].split(":") NextTime = datetime.datetime.now( ) - datetime.timedelta(days=1) # if DOWCoverage current DOW is "N" then advance one day currentDayOfWeek = int( datetime.datetime.today().strftime('%w')) if (currentValve["DOWCoverage"][currentDayOfWeek] == "N"): NextTime = NextTime - datetime.timedelta(days=1) NextTime = NextTime.replace(hour=int(myTempTime[0]), minute=int(myTempTime[1]), second=0, microsecond=0) dayDelay = getDayDelay(currentValve["DOWCoverage"], currentDayOfWeek) if (dayDelay > 0): nowTime = datetime.datetime.now( ) + datetime.timedelta(days=dayDelay) nowTime = nowTime.replace(hour=int(myTempTime[0]), minute=int( myTempTime[1]), second=0, microsecond=0) else: nowTime = datetime.datetime.now() if (NextTime <= nowTime): #set up next fire timeDelta = getTimeDelta( currentValve["TimerSelect"], currentValve["DOWCoverage"]) while NextTime < nowTime: NextTime = NextTime + timeDelta myNextTime = NextTime.strftime('%Y-%m-%d %H:%M:%S') if (currentValve["DOWCoverage"] == "NNNNNNN"): DOWNever = "COW: Never" nextScheduleList.append(DOWNever) else: nextScheduleList.append(myNextTime) myTimeOn.append(str(currentValve["OnTimeInSeconds"])) myValveNumberList.append(str(currentValve["ValveNumber"])) myDOWCoverageList.append(str(currentValve["DOWCoverage"])) myControlList.append(str(currentValve["Control"])) myArray.append(nextScheduleList) myArray.append(myTimeOn) myArray.append(myIDList) myArray.append(myNameList) myArray.append(myValveNumberList) myArray.append(myDOWCoverageList) myArray.append(myControlList) #print('myArray=', myArray) return myArray
def build_graphLightning_figure(): con = mdb.connect("localhost", "root", config.MySQL_Password, "WeatherSenseWireless") #last 7 days timeDelta = datetime.timedelta(days=7) now = datetime.datetime.now() before = now - timeDelta before = before.strftime('%Y-%m-%d %H:%M:%S') nowTime = now.strftime('%Y-%m-%d %H:%M:%S') query = "SELECT timestamp,deviceid, interruptcount, lightningcount, irqsource, lightninglastdistance FROM TB433MHZ WHERE (TimeStamp > '%s') AND (irqsource = 8) AND (deviceid = %d) ORDER BY timestamp" % ( before, WSLGHTID) df = pd.read_sql(query, con) df['present'] = pd.Series([0 for x in range(len(df.index))]) query = "SELECT timestamp, deviceid, interruptcount, lightningcount, irqsource, lightninglastdistance FROM TB433MHZ WHERE (TimeStamp > '%s') AND (irqsource = 4) AND (deviceid = %d) ORDER BY timestamp" % ( before, WSLGHTID) df2 = pd.read_sql(query, con) df2['present'] = pd.Series([0 for x in range(len(df2.index))]) query = "SELECT timestamp, deviceid, interruptcount, lightningcount, irqsource, lightninglastdistance FROM TB433MHZ WHERE (TimeStamp > '%s') AND (irqsource = 0) AND (deviceid = %d) ORDER BY timestamp" % ( before, WSLGHTID) df3 = pd.read_sql(query, con) df3['present'] = pd.Series([0 for x in range(len(df3.index))]) English_Metric = readJSON.getJSONValue("English_Metric") if (English_Metric == False): trace1 = go.Scatter(x=df.timestamp, y=df.lightninglastdistance * 0.6214, name='Lightning Distance', mode="markers", marker=dict(size=10, color="blue")) else: trace1 = go.Scatter(x=df.timestamp, y=df.lightninglastdistance, name='Lightning Distance', mode="markers", marker=dict(size=10, color="blue")) trace1 = go.Scatter(x=df.timestamp, y=df.lightninglastdistance, name='Lightning Distance', mode="markers", marker=dict(size=10, color="blue")) trace2 = go.Scatter(x=df.timestamp, y=df.present, name='Lightning Stroke', mode="markers", marker=dict(size=15, color="red")) trace3 = go.Scatter(x=df2.timestamp, y=df2.present, name='Disruptor', mode="markers", marker=dict(size=15, color="orange"), showlegend=True) trace4 = go.Scatter(x=df3.timestamp, y=df3.present, name='KeepAlive', mode="markers", marker=dict(size=10, color="black")) if (English_Metric == False): myTitle = "Lightning Distance (miles)" else: myTitle = "Lightning Distance (km)" figure = { 'data': [trace1, trace2, trace3, trace4], 'layout': go.Layout(title='WeatherSense Lightning', xaxis_title="Updated at: " + nowTime, yaxis_range=[0, 30], showlegend=True, yaxis_title=myTitle) } con.close() return figure
def initializeSGSPart2(): # status reports print("----------------------") print("Local Devices") print("----------------------") print(returnStatusLine("OLED",config.OLED_Present)) print(returnStatusLine("BMP280",config.BMP280_Present)) print(returnStatusLine("DustSensor",config.DustSensor_Present)) #print(returnStatusLine("Sunlight Sensor",config.Sunlight_Present)) #print(returnStatusLine("hdc1000 Sensor",config.hdc1000_Present)) #print(returnStatusLine("Ultrasonic Level Sensor",config.UltrasonicLevel_Present)) print("----------------------") print("Checking Wireless SGS Devices") print("----------------------") scanForResources.updateDeviceStatus(True) # turn off All Valves AccessValves.turnOffAllValves() wirelessJSON = readJSON.getJSONValue("WirelessDeviceJSON") for single in wirelessJSON: print(returnStatusLine(str(single["name"])+" - "+str(single["id"]),state.deviceStatus[str(single["id"])])) # Set up Wireless MQTT Links MQTTFunctions.startWirelessMQTTClient() # subscribe to IDs if (len(wirelessJSON) == 0): print("################################") print("ERROR") print("################################") print("No Wireless SGS uinits present - run SGSConfigure.py") print("################################") exit() # wait for connection while state.WirelessMQTTClientConnected != True: #Wait for connection time.sleep(0.1) # subscribe to IDs for single in wirelessJSON: topic = "SGS/" + single["id"] print("subscribing to ", topic) state.WirelessMQTTClient.subscribe(topic) # write out to ValveChanges for startup myJSON = {} myJSON["id"] = single["id"] myJSON["valvestate"] = "V00000000" pclogging.writeMQTTValveChangeRecord(myJSON) print() print() print("----------------------") print("Plant / Sensor Counts") print("----------------------") config.moisture_sensor_count = len(readJSON.getJSONValue("WirelessDeviceJSON"))*4 config.valve_count = len(readJSON.getJSONValue("WirelessDeviceJSON"))*8 print( "Wireless Unit Count:", len(readJSON.getJSONValue("WirelessDeviceJSON")) ) print("Sensor Count: ",config.moisture_sensor_count) print("Valve Count: ",config.valve_count) print() if (config.USEBLYNK): updateBlynk.blynkTerminalUpdate( "Wireless Unit Count:%d"% len(readJSON.getJSONValue("WirelessDeviceJSON")) ) updateBlynk.blynkTerminalUpdate("Sensor Count: %d"%config.moisture_sensor_count) updateBlynk.blynkTerminalUpdate("Pump Count: %d"%config.valve_count) updateBlynk.updateStaticBlynk() print("----------------------") print("Other Smart Garden System Expansions") print("----------------------") print(returnStatusLine("Weather",config.Weather_Present)) print(returnStatusLine("GardenCam",config.GardenCam_Present)) print(returnStatusLine("SunAirPlus",config.SunAirPlus_Present)) print(returnStatusLine("SolarMAX",config.SunAirPlus_Present)) print(returnStatusLine("Lightning Mode",config.Lightning_Mode)) print(returnStatusLine("MySQL Logging Mode",config.enable_MySQL_Logging)) print(returnStatusLine("UseBlynk",config.USEBLYNK)) print() print("----------------------") #Establish WeatherSTEMHash if (config.USEWEATHERSTEM == True): state.WeatherSTEMHash = SkyCamera.SkyWeatherKeyGeneration(config.STATIONKEY)
def updateLightningLines(): con = mdb.connect("localhost", "root", config.MySQL_Password, "WeatherSenseWireless") cur = con.cursor() # build the data array timeDelta = datetime.timedelta(days=7) now = datetime.datetime.now() before = now - timeDelta before = before.strftime('%Y-%m-%d %H:%M:%S') nowTime = now.strftime('%Y-%m-%d %H:%M:%S') query = "SELECT timestamp, lightningcount, deviceid from TB433MHZ WHERE (irqsource = 8) AND (deviceid = %d) ORDER BY timestamp DESC LIMIT 1 " % WSLGHTID print("queryA=", query) cur.execute(query) records = cur.fetchall() if (len(records) > 0): LLJSON["LastLightning"] = records[0][0].strftime('%Y-%m-%d %H:%M:%S') else: LLJSON["LastLightning"] = "N/A" query = "SELECT timestamp, deviceid, lightninglastdistance, irqsource from TB433MHZ WHERE (timestamp > '%s') and (irqsource=8) AND (deviceid = %d) ORDER BY timestamp DESC LIMIT 1" % ( before, WSLGHTID) cur.execute(query) print("queryD=", query) records = cur.fetchall() if (len(records) > 0): English_Metric = readJSON.getJSONValue("English_Metric") if (English_Metric == False): LLJSON["LastLightningDistance"] = str( round(records[0][2] * 0.6214, 1)) + "miles" else: LLJSON["LastLightningDistance"] = str(round(records[0][2]), 1) + "km" else: LLJSON["LastLightningDistance"] = "N/A" query = "SELECT timestamp, deviceid, lightningcount from TB433MHZ WHERE (timestamp > '%s') AND (irqsource = 8) and (deviceid = %d)" % ( before, WSLGHTID) cur.execute(query) records = cur.fetchall() LLJSON["LightningCount"] = str(len(records)) query = "SELECT timestamp, deviceid, lightningcount from TB433MHZ WHERE (timestamp > '%s') AND (deviceid = %d) ORDER BY timestamp DESC LIMIT 1" % ( before, WSLGHTID) cur.execute(query) records = cur.fetchall() if (len(records) > 0): LLJSON["TotalLightningCount"] = str(records[0][2]) else: LLJSON["TotalLightningCount"] = "N/A" query = "SELECT timestamp, irqsource from TB433MHZ WHERE (timestamp > '%s') AND (irqsource = 4)" % before cur.execute(query) records = cur.fetchall() count = len(records) LLJSON["DisturberCount"] = str(count) query = "SELECT timestamp, irqsource, deviceid from TB433MHZ WHERE (timestamp > '%s') AND (irqsource = 1) AND deviceid = %d" % ( before, WSLGHTID) cur.execute(query) records = cur.fetchall() count = len(records) LLJSON["NoiseCount"] = str(count) query = "SELECT timestamp, deviceid from TB433MHZ WHERE deviceid = %d ORDER BY timestamp DESC LIMIT 1" % WSLGHTID cur.execute(query) records = cur.fetchall() if (len(records) > 0): LLJSON["UnitID"] = str(records[0][1]) else: LLJSON["UnitID"] = "N/A" query = "SELECT timestamp, messageID, deviceid from TB433MHZ WHERE deviceid = %d ORDER BY timestamp DESC LIMIT 1" % WSLGHTID cur.execute(query) records = cur.fetchall() if (len(records) > 0): LLJSON["LastMessageID"] = "ID: " + str( records[0][1]) + " Timestamp: " + records[0][0].strftime( "%d-%b-%Y %H:%M:%S") else: LLJSON["LastMessageID"] = "N/A"
def StatusPage(): wirelessJSON = readJSON.getJSONValue("WirelessDeviceJSON") numberOfWireless = len(wirelessJSON) numberOfValves = numberOfWireless * 8 numberOfSensors = numberOfWireless * 4 f = open("/proc/device-tree/model") piType = f.read() boottime =datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S") Row1 = html.Div( [ dbc.Button( ["Number of Wireless Units", dbc.Badge(numberOfWireless, color="light", className="ml-1")], color="primary",), dbc.Button( ["Number of Valves", dbc.Badge(numberOfValves, color="light", className="ml-1")], color="primary",), dbc.Button( ["Number of Sensors", dbc.Badge(numberOfSensors, color="light", className="ml-1")], color="primary",), dbc.Button( ["Raspberry Pi", dbc.Badge(piType, color="light", className="ml-1")], color="primary",), dbc.Button( ["SGS Start Time ", dbc.Badge(boottime, color="light", className="ml-1")], color="primary",), dbc.Button( ["Pi Boot Time ", dbc.Badge(boottime, color="light", className="ml-1")], color="primary",), ]) Row2 = dbc.Row( [ daq.Gauge( id = {'type' : 'SPGdynamic', 'GaugeType' :'pi-loading'}, label="Pi CPU Loading", value=0, color={"gradient":True,"ranges":{"green":[0,50],"yellow":[50,85],"red":[85,100]}}, showCurrentValue=True, units="%", size=190, max = 100, min = 0, ), daq.Gauge( id = {'type' : 'SPGdynamic', 'GaugeType' :'pi-memory'}, label="Pi Memory Usage", value=0, color={"gradient":True,"ranges":{"green":[0,50],"yellow":[50,85],"red":[85,100]}}, min = 0, max=100, size=190, showCurrentValue=True, units="%", ), daq.Gauge( id = {'type' : 'SPGdynamic', 'GaugeType' :'pi-disk'}, label="Pi Disk Free", value=0, showCurrentValue=True, units="%", size=190, color={"gradient":True,"ranges":{"red":[0,30],"yellow":[30,65],"green":[65,100]}}, max = 100, min = 0, ), ], no_gutters=True, ) Layouts = returnIndicators() Row3 = html.Div( Layouts , ) Row4 = html.Div( [ html.Div(id='log') ] ) Row5 = html.Div( [ dbc.Alert("No Alarm", color="primary"), ], style={'margin-top' : "-90px"} ) #layout = dbc.Container([ layout = dbc.Container([ Row1, Row2, Row5, Row3, Row4], className="status-1", ) return layout
client.loop_start() #start the loop # now read and get the wireless IDs # # topics are: # SGS/<wirelessid> ex: SGS/124d # read JSON import state import readJSON import config readJSON.readJSON("") wirelessJSON = readJSON.getJSONValue("WirelessDeviceJSON") # subscribe to IDs if (len(wirelessJSON) == 0): print("No Wireless SGS uinits present - run SGSConfigure.py") exit() # wait for connection while Connected != True: #Wait for connection time.sleep(0.1) # subscribe to IDs for single in wirelessJSON: topic = "SGS/" + single["id"]