def mainloop(): global timer100ms, timer20ms, timer1s, timer2s, timer30s, init_ok, prevminute while init_ok: time.sleep(0.05) if (timeoutReached(timer20ms)): run50timespersecond() timer20ms = millis() + 20 if (timeoutReached(timer100ms)): run10timespersecond() timer100ms = millis() + 100 if (timeoutReached(timer1s)): runoncepersecond() timer1s = millis() + 1000 if (str(prevminute) != str(datetime.now().strftime('%M'))): commands.rulesProcessing( "Clock#Time=" + str(datetime.now().strftime('%a,%H:%M')), rpieGlobals.RULE_CLOCK) prevminute = datetime.now().strftime('%M') if (timeoutReached(timer30s)): runon30seconds() timer30s = millis() + 30000 if (timeoutReached(timer2s)): runon2seconds() timer2s = millis() + 2000
def set_value(self,valuenum,value,publish=True,suserssi=-1,susebattery=-1): # implement if GPIO used!! if float(valuenum)<=self.valuecount and float(valuenum)>0: rval = value if self.formulaoption: # handle formulas tval = False if len(self.formula[valuenum-1])>0 and commands.isformula(self.formula[valuenum-1]): tval = commands.parseformula(self.formula[valuenum-1],float(value)) if tval!=False: rval = tval if self.pininversed: # only binary sensors supported for inversion! if type(rval) is str: if (rval.lower() == "off") or (rval=="0"): rval = 1 else: rval = 0 else: if (float(rval) == 0): rval = 1 else: rval = 0 if int(float(self.decimals[valuenum-1]))>=0: # handle decimals if needed try: rval = misc.formatnum(rval,int(float(self.decimals[valuenum-1]))) except: pass self.uservar[valuenum-1] = rval if self.valuenames[valuenum-1]!= "": commands.rulesProcessing(self.taskname+"#"+self.valuenames[valuenum-1]+"="+str(rval),rpieGlobals.RULE_USER) if self.senddataoption and publish: self.plugin_senddata(puserssi=suserssi,pusebattery=susebattery,pchangedvalue=valuenum) try: if self.writecallback is not None: self.writecallback(self.taskindex,valuenum) except: pass
def signal_handler(signal, frame): global init_ok init_ok = False commands.rulesProcessing("System#Shutdown", rpieGlobals.RULE_SYSTEM) Settings.savetasks() procarr = [] for x in range(0, len(Settings.Tasks)): if (Settings.Tasks[x]) and type( Settings.Tasks[x]) is not bool: # device exists if (Settings.Tasks[x].enabled): # device enabled t = threading.Thread(target=Settings.Tasks[x].plugin_exit) t.daemon = True procarr.append(t) t.start() if len(procarr) > 0: for process in procarr: process.join(1) webserver.WebServer.stop() gpios.HWPorts.cleanup() for y in range(0, len(Settings.Controllers)): if (Settings.Controllers[y]): if (Settings.Controllers[y].enabled): t = threading.Thread( target=Settings.Controllers[y].controller_exit) t.daemon = True procarr.append(t) t.start() if len(procarr) > 0: for process in procarr: process.join() time.sleep(1) print("\nProgram exiting gracefully") sys.exit(0)
def isconnected(self, ForceCheck=True): res = False if self.enabled and self.initialized: if ForceCheck == False: return self.laststatus if self.mqttclient is not None: gtopic = self.inchannel gval = "PING" mres = 1 try: (mres, mid) = self.mqttclient.publish(gtopic, gval) except: mres = 1 if mres == 0: res = 1 # connected else: res = 0 # not connected if res != self.laststatus: if res == 0: commands.rulesProcessing("DomoMQTT#Disconnected", rpieGlobals.RULE_SYSTEM) else: commands.rulesProcessing("DomoMQTT#Connected", rpieGlobals.RULE_SYSTEM) self.laststatus = res if res == 1 and self.connectinprogress == 1: self.connectinprogress = 0 return res
def isconnected(self,ForceCheck=True): res = False if self.enabled and self.initialized: if ForceCheck==False: return (self.laststatus==1) if self.mqttclient is not None: tstart = self.outch[:len(self.outch)-1] gtopic = tstart+"status" gval = "PING" mres = 1 try: (mres,mid) = self.mqttclient.publish(gtopic,gval) except: mres = 1 if mres==0: res = 1 # connected else: res = 0 # not connected if res != self.laststatus: if res==0: commands.rulesProcessing("GenMQTT#Disconnected",rpieGlobals.RULE_SYSTEM) else: try: (mres,mid) = self.mqttclient.publish(self.lwt_t,self.lwtconnmsg) except: pass commands.rulesProcessing("GenMQTT#Connected",rpieGlobals.RULE_SYSTEM) self.laststatus = res if res == 1 and self.connectinprogress==1: self.connectinprogress=0 return res
def checkNetwork(): global netmode, lastdisconntime, lastaptime try: if Settings.NetMan.WifiDevWatch>=0 and Settings.NetMan.WifiDevNum>=0: if Settings.NetworkDevices[Settings.NetMan.WifiDevNum].apmode==0: anetmode = Settings.NetworkDevices[Settings.NetMan.WifiDevWatch].isconnected() if anetmode!=netmode: # network mode changed netmode=anetmode if netmode: # if connected lastdisconntime = 0 # forgive last disconnect time commands.rulesProcessing("Network#Connected",rpieGlobals.RULE_SYSTEM) return True else: lastdisconntime = time.time() # store last disconnect time commands.rulesProcessing("Network#Disconnected",rpieGlobals.RULE_SYSTEM) return True elif anetmode==False: # otherwise, if in disconnect state if Settings.NetMan.APMode not in [-1,100]: if lastdisconntime!=0: if (time.time()-lastdisconntime)>int(Settings.NetMan.APModeTime): Network.AP_start(Settings.NetMan.WifiDevNum) lastdisconntime = 0 # forgive last disconnect time lastaptime = time.time() else: lastdisconntime = time.time() # store last disconnect time else: # apmode active if Settings.NetMan.APStopTime>-1: if Settings.NetMan.APMode not in [-1,100]: if lastaptime!=0: if (time.time()-lastaptime)>int(Settings.NetMan.APStopTime): Network.AP_stop(Settings.NetMan.WifiDevNum) lastaptime = 0 lastdisconntime = 0 # forgive last disconnect time except Exception as e: print(e)
def syncvalue(bcmpin,value): for x in range(0,len(settings.Tasks)): if (settings.Tasks[x]) and type(settings.Tasks[x]) is not bool: # device exists if (settings.Tasks[x].enabled): if (settings.Tasks[x].pluginid==29) and (settings.Tasks[x].taskdevicepin[0]==bcmpin): # output on specific pin settings.Tasks[x].uservar[0] = value if settings.Tasks[x].valuenames[0]!= "": commands.rulesProcessing(settings.Tasks[x].taskname+"#"+settings.Tasks[x].valuenames[0]+"="+str(value),pglobals.RULE_USER) settings.Tasks[x].plugin_senddata() break
def RulesInit(): rules = "" try: with open(rpieGlobals.FILE_RULES, 'r') as f: rules = f.read() except: pass if rules != "": #print("Loading rules...") commands.splitruletoevents(rules) commands.rulesProcessing("System#Boot", rpieGlobals.RULE_SYSTEM)
def disconnect(self): try: self._mqttclient.disconnect() except: pass self._connected = False self.laststatus = 0 try: commands.rulesProcessing("DomoMQTT#Disconnected", pglobals.RULE_SYSTEM) except: pass
def disconnect(self): try: self.mqttclient.loop_stop(True) except: pass try: self.mqttclient.disconnect() except: pass stat=self.isconnected() if self.enabled!=True: commands.rulesProcessing("DomoMQTT#Disconnected",rpieGlobals.RULE_SYSTEM) return stat
def RulesInit(): rules = "" try: with open(pglobals.FILE_RULES, 'r', encoding="utf8") as f: rules = f.read() except: pass try: if rules != "": print("Loading rules...") commands.splitruletoevents(rules) commands.rulesProcessing("System#Boot", pglobals.RULE_SYSTEM) except Exception as e: print("Rule loading error:", str(e))
def disconnect(self): try: (mres,mid) = self.mqttclient.publish(self.lwt_t,self.lwtdisconnmsg) except Exception as e: print(e) try: self.mqttclient.loop_stop(True) except: pass try: self.mqttclient.disconnect() except: pass stat=self.isconnected() if self.enabled!=True: commands.rulesProcessing("GenMQTT#Disconnected",rpieGlobals.RULE_SYSTEM) return stat
def syncpwm(bcmpin, value): for x in range(0, len(Settings.Tasks)): if (Settings.Tasks[x]) and type( Settings.Tasks[x]) is not bool: # device exists if (Settings.Tasks[x].enabled): if (Settings.Tasks[x].pluginid == 213) and (Settings.Tasks[x].taskdevicepin[0] == bcmpin): # pwm on specific pin try: Settings.Tasks[x].uservar[0] = value except: pass if Settings.Tasks[x].valuenames[0] != "": commands.rulesProcessing( Settings.Tasks[x].taskname + "#" + Settings.Tasks[x].valuenames[0] + "=" + str(value), rpieGlobals.RULE_USER) Settings.Tasks[x].plugin_senddata() break
def mainloop(): global timer100ms, timer20ms, timer1s, timer2s, timer30s, init_ok, prevminute ret = None amin = "" days = ['Mon', 'Tue', "Wed", "Thu", "Fri", "Sat", "Sun"] while init_ok: try: utime.sleep_ms(5) if (timeoutReached(timer20ms)): run50timespersecond() timer20ms = utime.ticks_add(utime.ticks_ms(), 20) if (timeoutReached(timer100ms)): run10timespersecond() timer100ms = utime.ticks_add(utime.ticks_ms(), 100) if (timeoutReached(timer1s)): runoncepersecond() timer1s = utime.ticks_add(utime.ticks_ms(), 1000) if (timeoutReached(timer30s)): runon30seconds() timer30s = utime.ticks_add(utime.ticks_ms(), 30000) ret = utime.localtime() amin = str('{:02}'.format(ret[4])) if (str(prevminute) != amin): try: commands.rulesProcessing( str('Clock#Time={},{:02}:{:02}'.format( days[int(ret[6])], ret[3], ret[4])), pglobals.RULE_CLOCK) prevminute = amin except Exception as e: print(e) gc.collect() if (timeoutReached(timer2s)): runon2seconds() timer2s = utime.ticks_add(utime.ticks_ms(), 2000) except SystemExit: init_ok = False except KeyboardInterrupt: init_ok = False except EOFError: init_ok = False except: pass
def isconnected(self, ForceCheck=True): res = -1 if self.enabled and self.initialized: if ForceCheck == False: return self._connected if self._mqttclient is not None: try: self._mqttclient.ping() res = 1 except: res = 0 if res != self.laststatus: if res == 0: commands.rulesProcessing("DomoMQTT#Disconnected", pglobals.RULE_SYSTEM) else: commands.rulesProcessing("DomoMQTT#Connected", pglobals.RULE_SYSTEM) self.laststatus = res if res == 1 and self.connectinprogress == 1: self.connectinprogress = 0 return res
def disconnect_handler(): global blynkconnected blynkconnected = False commands.rulesProcessing("blynk_disconnected", rpieGlobals.RULE_SYSTEM)
def parseResponse(self, gpsChars): misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG_DEV, "We have a response") misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG_MORE, f"gpsChars = {gpsChars}") try: if '*' in gpsChars: gpsStr, chkSum = gpsChars.split('*') elif '_' in gpsChars: gpsStr, chkSum = gpsChars.split('_') else: chkSum = gpsChars[-2:] gpsStr = gpsChars[:-2] except: chkSum = gpsChars[-2:] gpsStr = gpsChars[:-2] gpsComponents = gpsStr.split(',') gpsStart = gpsComponents[0] if ("GGA" in gpsStart): misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG, "Valid GGA from GNSS/GPS") if self.devfound == False: misc.addLog(rpieGlobals.LOG_LEVEL_INFO, "GNSS/GPS found") self.devfound = True prevval = self.validloc self.validloc = 0 chkVal = 0 for ch in gpsStr[1:]: # Remove the $ chkVal ^= ord(ch) if (chkVal == int(chkSum, 16)): misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG_MORE, f"chkVal = {chkVal}") for i, k in enumerate([ 'strType', 'fixTime', 'lat', 'latDir', 'lon', 'lonDir', 'fixQual', 'numSat', 'horDil', 'alt', 'altUnit', 'galt', 'galtUnit', 'DPGS_updt', 'DPGS_ID' ]): self.GPSDAT[k] = gpsComponents[i] try: if int(self.GPSDAT['fixQual']) > 0: self.validloc = 1 except: self.validloc = 0 if self.validloc == 1: # refresh values misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG, "GPS fix OK") self.lat = dm_to_sd(self.GPSDAT['lat']) if self.GPSDAT['latDir'] == 'S': self.lat = self.lat * -1 self.lon = dm_to_sd(self.GPSDAT['lon']) if str(self.GPSDAT['lonDir']) == 'W': self.lon = self.lon * -1 misc.addLog( rpieGlobals.LOG_LEVEL_DEBUG, f"latitude(dm) = {self.GPSDAT['lat']} : longitude(dm) = {self.GPSDAT['lon']}" ) misc.addLog( rpieGlobals.LOG_LEVEL_DEBUG, f"latitude(sd) = {self.lat} : longitude(sd) = {self.lon}" ) if self.validloc != prevval: # status changed if self.validloc == 1: commands.rulesProcessing("GPS#GotFix", rpieGlobals.RULE_SYSTEM) else: commands.rulesProcessing("GPS#LostFix", rpieGlobals.RULE_SYSTEM) misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG_MORE, f"GPSDAT = {json.dumps(self.GPSDAT)}") if ("RMC" in gpsStart): misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG, "Valid RMC from GNSS/GPS") chkVal = 0 for ch in gpsStr[1:]: # Remove the $ chkVal ^= ord(ch) if (chkVal == int(chkSum, 16)): for i, k in enumerate([ 'strType', 'fixTime', 'status', 'lat', 'latdir', 'lon', 'londir', 'speed_over_ground_knots', 'track_made_good', 'fixDate', 'mag_variation', 'mag_variation_dir', 'faa_mode', 'checksum' ]): self.GNSSRMC[k] = gpsComponents[i] misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG_MORE, f"GNSSRMC = {json.dumps(self.GNSSRMC)}") if ("ZDA" in gpsStart): misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG, "Valid ZDA from GNSS/GPS") chkVal = 0 for ch in gpsStr[1:]: # Remove the $ chkVal ^= ord(ch) if (chkVal == int(chkSum, 16)): for i, k in enumerate([ 'strType', 'fixTime', 'day', 'mon', 'year', 'lzoneh', 'lzonem' ]): self.GPSDATE[k] = gpsComponents[i] misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG_MORE, f"GPSDATE = {json.dumps(self.GPSDATE)}") if ("VTG" in gpsStart): misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG, "Valid VTG from GNSS/GPS") chkVal = 0 for ch in gpsStr[1:]: # Remove the $ chkVal ^= ord(ch) if (chkVal == int(chkSum, 16)): for i, k in enumerate([ 'strType', 'trueTrack', 'trueTrackRel', 'magnetTrack', 'magnetTrackRel', 'speedKnot', 'speedKnotUnit', 'speedKm', 'speedKmUnit' ]): self.GPSTRACK[k] = gpsComponents[i] # print(gpsChars) misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG_MORE, f"GPSTRACK = {json.dumps(self.GPSTRACK)}")
def parseResponse(self, gpsLine): # global lastLocation # gpsChars = ''.join(chr(c) for c in gpsLine) # if "*" not in gpsChars: # return False gpsChars = str(gpsLine) gpsStr, chkSum = gpsChars.split('*') gpsComponents = gpsStr.split(',') gpsStart = gpsComponents[0] if ("GGA" in gpsStart): # print("Valid GGA from GPS") # DEBUG if self.devfound == False: misc.addLog(rpieGlobals.LOG_LEVEL_INFO, "GPS found") self.devfound = True prevval = self.validloc self.validloc = 0 chkVal = 0 for ch in gpsStr[1:]: # Remove the $ chkVal ^= ord(ch) if (chkVal == int(chkSum, 16)): for i, k in enumerate([ 'strType', 'fixTime', 'lat', 'latDir', 'lon', 'lonDir', 'fixQual', 'numSat', 'horDil', 'alt', 'altUnit', 'galt', 'galtUnit', 'DPGS_updt', 'DPGS_ID' ]): self.GPSDAT[k] = gpsComponents[i] try: if int(self.GPSDAT['fixQual']) > 0: self.validloc = 1 except: self.validloc = 0 if self.validloc == 1: # refresh values # print("GPS fix OK") # debug lon = float(self.GPSDAT['lon']) if str(self.GPSDAT['lonDir']) == 'W': lon = lon * -1 self.lon = dm_to_sd(str(lon)) lat = float(self.GPSDAT['lat']) if self.GPSDAT['latDir'] == 'S': lat = lat * -1 self.lat = dm_to_sd(str(lat)) if self.validloc != prevval: # status changed if self.validloc == 1: commands.rulesProcessing("GPS#GotFix", rpieGlobals.RULE_SYSTEM) else: commands.rulesProcessing("GPS#LostFix", rpieGlobals.RULE_SYSTEM) #print(gpsChars) #print(json.dumps(self.GPSDAT, indent=2)) elif ("ZDA" in gpsStart): chkVal = 0 for ch in gpsStr[1:]: # Remove the $ chkVal ^= ord(ch) if (chkVal == int(chkSum, 16)): for i, k in enumerate([ 'strType', 'fixTime', 'day', 'mon', 'year', 'lzoneh', 'lzonem' ]): self.GPSDATE[k] = gpsComponents[i] #print(gpsChars) #print(json.dumps(self.GPSDATE, indent=2)) elif ("VTG" in gpsStart): chkVal = 0 for ch in gpsStr[1:]: # Remove the $ chkVal ^= ord(ch) if (chkVal == int(chkSum, 16)): for i, k in enumerate([ 'strType', 'trueTrack', 'trueTrackRel', 'magnetTrack', 'magnetTrackRel', 'speedKnot', 'speedKnotUnit', 'speedKm', 'speedKmUnit' ]): self.GPSTRACK[k] = gpsComponents[i]