def doCleanup(): rulesProcessing("System#Shutdown", pglobals.RULE_SYSTEM) if (len(settings.Tasks) > 1) or ((len(settings.Tasks) == 1) and (settings.Tasks[0] != False)): 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 try: if (settings.Tasks[x].enabled): # device enabled settings.Tasks[x].plugin_exit() except: pass try: for t in range(0, pglobals.RULES_TIMER_MAX): upyTime.Timers[t].pause() except: pass procarr = [] for y in range(0, len(settings.Controllers)): if (settings.Controllers[y]): if (settings.Controllers[y].enabled): settings.Controllers[y].controller_exit()
def doExecuteCommand(cmdline, Parse=True): if Parse: retval, state = parseruleline(cmdline) else: retval = cmdline cmdarr = retval.split(",") if (" " in retval) and not ("," in retval): cmdarr = retval.split(" ") elif (" " in retval) and ( "," in retval): # workaround for possible space instead comma problem fsp = retval.find(" ") fco = retval.find(",") if fsp < fco: c2 = retval.split(" ") cmdarr = retval[(fsp + 1):].split(",") cmdarr = [c2[0]] + cmdarr cmdarr[0] = cmdarr[0].strip().lower() commandfound = False misc.addLog(pglobals.LOG_LEVEL_INFO, "CMD: " + cmdline.replace("==", "=")) if cmdarr[0] == "delay": try: s = float(cmdarr[1]) except: s = 1000 utime.sleep_ms(s) commandfound = True return commandfound elif cmdarr[0] == "taskrun": if len(settings.Tasks) < 1: return False try: s = int(cmdarr[1]) except: s = -1 if s > 0 and (s <= len(settings.Tasks)): s = s - 1 # array is 0 based, tasks is 1 based if (type(settings.Tasks[s]) != bool) and (settings.Tasks[s]): if (settings.Tasks[s].enabled): settings.Tasks[s].plugin_read() commandfound = True return commandfound elif cmdarr[0] == "taskvalueset": if len(settings.Tasks) < 1: return False try: s = int(cmdarr[1]) except: s = -1 try: v = int(cmdarr[2]) except: v = 1 #v=v-1 if s > 0 and (s <= len(settings.Tasks)): s = s - 1 # array is 0 based, tasks is 1 based if (type(settings.Tasks[s]) != bool) and (settings.Tasks[s]): if v > (settings.Tasks[s].valuecount): v = settings.Tasks[s].valuecount if v < 1: v = 1 try: settings.Tasks[s].set_value( v, parsevalue(str(cmdarr[3].strip())), False) except Exception as e: pass # print("Set value error: ",e) commandfound = True return commandfound elif cmdarr[0] == "taskvaluesetandrun": if len(settings.Tasks) < 1: return False try: s = int(cmdarr[1]) except: s = -1 try: v = int(cmdarr[2]) except: v = 1 #v=v-1 if s > 0 and (s <= len(Settings.Tasks)): s = s - 1 # array is 0 based, tasks is 1 based if (type(settings.Tasks[s]) != bool) and (settings.Tasks[s]): if v > (settings.Tasks[s].valuecount): v = settings.Tasks[s].valuecount if v < 1: v = 1 settings.Tasks[s].set_value(v, parsevalue(str(cmdarr[3]).strip()), True) commandfound = True return commandfound elif cmdarr[0] == "timerpause": if len(upyTime.Timers) < 1: return False try: s = int(cmdarr[1]) except: s = -1 if s > 0 and (s < len(upyTime.Timers)): s = s - 1 # array is 0 based, timers is 1 based upyTime.Timers[s].pause() commandfound = True return commandfound elif cmdarr[0] == "timerresume": if len(upyTime.Timers) < 1: return False try: s = int(cmdarr[1]) except: s = -1 if s > 0 and (s < len(upyTime.Timers)): s = s - 1 # array is 0 based, timers is 1 based upyTime.Timers[s].resume() commandfound = True return commandfound elif cmdarr[0] == "timerset": if len(upyTime.Timers) < 1: return False try: s = int(cmdarr[1]) except: s = -1 try: v = int(cmdarr[2]) except: v = 1 if s > 0 and (s < len(upyTime.Timers)): s = s - 1 # array is 0 based, timers is 1 based try: if v == 0: upyTime.Timers[s].stop(False) else: upyTime.Timers[s].addcallback(TimerCallback) upyTime.Timers[s].start(v) except Exception as e: misc.addLog(pglobals.LOG_LEVEL_ERROR, "Timer start: " + str(e)) commandfound = True return commandfound elif cmdarr[0] == "looptimerset": if len(upyTime.Timers) < 1: return False try: s = int(cmdarr[1]) except: s = -1 try: v = int(cmdarr[2]) except: v = 1 try: c = int(cmdarr[3]) except: c = -1 if s > 0 and (s < len(upyTime.Timers)): s = s - 1 # array is 0 based, timers is 1 based try: if v == 0: upyTime.Timers[s].stop(False) else: upyTime.Timers[s].addcallback(TimerCallback) upyTime.Timers[s].start(v, looping=True, maxloops=c) except Exception as e: misc.addLog(pglobals.LOG_LEVEL_ERROR, "Timer start: " + str(e)) commandfound = True return commandfound elif cmdarr[0] == "event": rulesProcessing(cmdarr[1], pglobals.RULE_USER) commandfound = True return commandfound elif cmdarr[0] == "let": global GlobalVars try: s = int(cmdarr[1]) - 1 except: s = -1 try: v = parsevalue(cmdarr[2]) except: v = 0 if s >= 0 and s < 16: GlobalVars[s] = v commandfound = True return commandfound elif cmdarr[0] == "sendto": try: unitno = int(cmdarr[1]) except: unitno = -1 data = "" if len(cmdarr) > 2: sepp = (len(cmdarr[0]) + len(cmdarr[1]) + 1) sepp = cmdline.find(',', sepp) data = cmdline[sepp + 1:].replace("==", "=") else: unitno = -1 if unitno >= 0 and unitno <= 255: cfound = False for y in range(len(settings.Controllers)): if (settings.Controllers[y]): if (settings.Controllers[y].enabled): if "ESPEasy P2P" in settings.Controllers[ y].getcontrollername(): settings.Controllers[y].udpsender(unitno, data, 1) cfound = True if cfound == False: misc.addLog(pglobals.LOG_LEVEL_ERROR, "ESPEasy P2P controller not found!") commandfound = True return commandfound elif cmdarr[0] == "blecommand": try: unitno = int(cmdarr[1]) except: unitno = -1 data = "" if len(cmdarr) > 2: sepp = (len(cmdarr[0]) + len(cmdarr[1]) + 1) sepp = cmdline.find(',', sepp) data = cmdline[sepp + 1:].replace("==", "=") else: unitno = -1 if unitno >= 0 and unitno <= 255: cfound = False for y in range(len(settings.Controllers)): if (settings.Controllers[y]): if (settings.Controllers[y].enabled): if "BLE Direct" in settings.Controllers[ y].getcontrollername(): settings.Controllers[y].sendcommand(unitno, data) cfound = True if cfound == False: misc.addLog(pglobals.LOG_LEVEL_ERROR, "BLE controller not found!") commandfound = True return commandfound elif cmdarr[0] == "loracommand": try: unitno = int(cmdarr[1]) except: unitno = -1 data = "" if len(cmdarr) > 2: sepp = (len(cmdarr[0]) + len(cmdarr[1]) + 1) sepp = cmdline.find(',', sepp) data = cmdline[sepp + 1:].replace("==", "=") else: unitno = -1 if unitno >= 0 and unitno <= 255: cfound = False for y in range(len(settings.Controllers)): if (settings.Controllers[y]): if (settings.Controllers[y].enabled): if "LORA Direct" in settings.Controllers[ y].getcontrollername(): settings.Controllers[y].sendcommand(unitno, data) cfound = True if cfound == False: misc.addLog(pglobals.LOG_LEVEL_ERROR, "LORA controller not found!") commandfound = True return commandfound elif cmdarr[0] == "publish": topic = cmdarr[1].strip() data = "" if len(cmdarr) > 2: sepp = (len(cmdarr[0]) + len(cmdarr[1]) + 1) sepp = cmdline.find(',', sepp) data = cmdline[sepp + 1:].replace("==", "=") else: topic = "" commandfound = False if topic != "": cfound = False for y in range(len(settings.Controllers)): if (settings.Controllers[y]): if (settings.Controllers[y].enabled): try: if settings.Controllers[y].mqttclient is not None: settings.Controllers[y].mqttclient.publish( topic, data) #MISSING!!! commandfound = True cfound = True break except: cfound = False if cfound == False: misc.addLog(pglobals.LOG_LEVEL_ERROR, "MQTT capable controller not found!") return commandfound elif cmdarr[0] == "sendtohttp": destaddr = cmdarr[1].strip() try: destport = int(cmdarr[2]) except: destport = -1 data = "" if len(cmdarr) > 3: sepp = (len(cmdarr[0]) + len(cmdarr[1]) + len(cmdarr[2]) + 2) sepp = cmdline.find(',', sepp) data = cmdline[sepp + 1:].replace("==", "=") else: destport = -1 if destport > 0: commandfound = True curl = "http://" + destaddr + ":" + str(destport) + data urlget(curl) else: commandfound = False return commandfound elif cmdarr[0] == "sendtoudp": destaddr = cmdarr[1].strip() try: destport = int(cmdarr[2]) except: destport = -1 data = "" if len(cmdarr) > 3: sepp = (len(cmdarr[0]) + len(cmdarr[1]) + len(cmdarr[2]) + 2) sepp = cmdline.find(',', sepp) data = cmdline[sepp + 1:].replace("==", "=") else: destport = -1 if destport > 0: s = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM) for r in range(0, 1): s.sendto(bytes(data, "utf-8"), (destaddr, int(destport))) if r < 1: utime.sleep(0.1) commandfound = True else: commandfound = False return commandfound elif cmdarr[0] == "wifiapmode": commandfound = False return commandfound elif cmdarr[0] == "wifistamode": commandfound = False return commandfound elif cmdarr[0] == "wificonnect": # implement it commandfound = False return commandfound elif cmdarr[0] == "wifimode": # implement it commandfound = False return commandfound elif cmdarr[0] == "reboot": # print("rst upt:",misc.getuptime(0))#debug doCleanup() OS.reboot() commandfound = True return commandfound elif cmdarr[0] == "reset": try: import os files = os.listdir('data') for fn in files: if '.dat' in fn: os.remove('data/' + fn) except: pass try: settings.Settings = { "Name": "mpyEasy", "Unit": "2", "Password": "", "Delay": 60, "WifiClient": false, "AP1SSID": "", "AP1KEY": "", "AP2SSID": "", "AP2KEY": "", "WifiAP": 2, "APSSID": "mpyEasy", "APKEY": "configesp", "LANIF": false, "WDHCP": true, "WIP": "", "WMask": "", "WGW": "", "WDNS": "", "LDHCP": true, "LIP": "", "LMask": "", "LGW": "", "LDNS": "" } settings.Controllers = [False] settings.Tasks = [False] settings.Pinout = [] settings.savesettings() settings.savetasks() except: pass OS.reboot() commandfound = True return commandfound elif cmdarr[0] == "notify": try: plugin = int(cmdarr[1]) except: plugin = 0 data = "" if len(cmdarr) > 1 and plugin > 0: sepp = (len(cmdarr[0]) + len(cmdarr[1]) + 2) data = cmdline[sepp:].replace("==", "=") commandfound = doExecuteNotification(plugin - 1, data) return commandfound elif cmdarr[0] in gpiohelper.commandlist: commandfound = True try: res = gpiohelper.gpio_commands(retval) except Exception as e: print("gpio err", str(e)) #debug return res if commandfound == False: commandfound = doExecutePluginCommand(retval) if commandfound == False: misc.addLog(pglobals.LOG_LEVEL_ERROR, "Unknown command: " + cmdline) return commandfound
def handle_devices(httpResponse,responsearr): ws.navMenuIndex=4 ws.TXBuffer = "" httpResponse.WriteResponseOk( headers = ({'Cache-Control': 'no-cache'}), contentType = 'text/html', contentCharset = 'UTF-8', content = "" ) taskdevicenumber = ws.arg('TDNUM',responsearr) if taskdevicenumber=='': taskdevicenumber=0 else: taskdevicenumber=int(float(taskdevicenumber)) taskdevicetimer = ws.arg('TDT',responsearr) if taskdevicetimer=='': taskdevicetimer=0 else: taskdevicetimer=float(taskdevicetimer) edit = ws.arg("edit",responsearr) page = ws.arg("page",responsearr) setpage = ws.arg("setpage",responsearr) taskIndex = ws.arg("index",responsearr) runIndex = ws.arg("run",responsearr) toggleIndex = ws.arg("toggle",responsearr) if page=='': page=0 else: page=int(float(page)) if page==0: page = 1 if setpage=='': setpage=0 else: setpage=int(float(setpage)) if (setpage>0): if setpage <= (pglobals.TASKS_MAX / ws.TASKS_PER_PAGE): page = setpage else: page = int(pglobals.TASKS_MAX / ws.TASKS_PER_PAGE) ws.sendHeadandTail("TmplStd",ws._HEAD) taskIndexNotSet = (taskIndex == 0) or (taskIndex == '') import settings import misc if taskIndex!="": taskIndex = int(taskIndex) - 1 if ws.arg('del',responsearr) != '': taskdevicenumber=0 ttid = -1 try: ttid = settings.Tasks[taskIndex].pluginid except: ttid = -1 if ttid != -1: try: settings.Tasks[taskIndex].plugin_exit() taskIndexNotSet = True settings.Tasks[taskIndex] = False settings.savetasks() # savetasksettings!!! except Exception as e: misc.addLog(pglobals.LOG_LEVEL_ERROR, "Deleting failed: "+str(e)) if runIndex != "": if len(settings.Tasks)<1: return False try: s = int(runIndex) except: s = -1 try: if s >0 and (s<=len(settings.Tasks)): s = s-1 # array is 0 based, tasks is 1 based if (type(settings.Tasks[s])!=bool) and (settings.Tasks[s]): if (settings.Tasks[s].enabled): settings.Tasks[s].plugin_read() except Exception as e: print(e) httpResponse._write(ws.TXBuffer,strEncoding='UTF-8') ws.TXBuffer = "" if toggleIndex != "": if len(settings.Tasks)<1: return False try: s = int(toggleIndex) except: s = -1 try: if s >0 and (s<=len(settings.Tasks)): s = s-1 # array is 0 based, tasks is 1 based if (type(settings.Tasks[s])!=bool) and (settings.Tasks[s]): if (settings.Tasks[s].enabled): settings.Tasks[s].set_value(1,(1-int(settings.Tasks[s].uservar[0])),publish=True) except Exception as e: print(e) if taskIndexNotSet: # show all tasks as table ws.TXBuffer += "<table class='multirow' border=1px frame='box' rules='all'><TR><TH style='width:70px;'>" if (pglobals.TASKS_MAX != ws.TASKS_PER_PAGE): ws.TXBuffer += "<a class='button link' href='devices?setpage=" if (page > 1): ws.TXBuffer += str(page - 1) else: ws.TXBuffer += str(page) ws.TXBuffer += "'><</a><a class='button link' href='devices?setpage=" if (page < (pglobals.TASKS_MAX / ws.TASKS_PER_PAGE)): ws.TXBuffer += str(page + 1) else: ws.TXBuffer += str(page) ws.TXBuffer += "'>></a><TH style='width:50px;'>Task<TH style='width:100px;'>Enabled<TH>Device<TH>Name<TH>Port<TH style='width:100px;'>Ctr (IDX)<TH style='width:70px;'>GPIO<TH>Values" for x in range( ((page - 1) * ws.TASKS_PER_PAGE), ((page) * ws.TASKS_PER_PAGE) ): ws.TXBuffer += "<TR><TD><a class='button link' href='devices?index={0}&page={1}'>Edit</a>".format((x+1),page) try: if settings.Tasks[x] and settings.Tasks[x].enabled and settings.Tasks[x].remotefeed<1: ws.TXBuffer += "<a class='button link' href='devices?run={0}&page={1}'>Run</a>".format((x+1),page) if settings.Tasks[x].recdataoption and settings.Tasks[x].vtype==pglobals.SENSOR_TYPE_SWITCH: ws.TXBuffer += "<a class='button link' href='devices?toggle={0}&page={1}'>Toggle</a>".format((x+1),page) except: pass ws.TXBuffer += "<TD>{0}<TD>".format(x+1) lent = False try: if settings.Tasks[x]: lent = True except: lent = False if (len(settings.Tasks)>x) and (lent): try: ws.addEnabled(settings.Tasks[x].enabled) except Exception as e: pass ws.TXBuffer += "<TD>{0}<TD>{1}<TD>".format(settings.Tasks[x].getdevicename(),settings.Tasks[x].gettaskname()) try: if (str(settings.Tasks[x].ports) != "0" and str(settings.Tasks[x].ports) != ""): ws.TXBuffer += str(settings.Tasks[x].ports) except: pass if settings.Tasks[x].remotefeed: ws.TXBuffer += "<TD style='background-color:#00FF00'>" else: ws.TXBuffer += "<TD>" try: if (settings.Tasks[x].senddataoption): doBR = False maxcon = len(settings.Controllers) if maxcon>pglobals.CONTROLLER_MAX: maxcon = pglobals.CONTROLLER_MAX try: for controllerNr in range(0,maxcon): if (settings.Tasks[x]) and (settings.Tasks[x].senddataenabled[controllerNr]) and (settings.Controllers[controllerNr].enabled): if (doBR): ws.TXBuffer += "<BR>" ws.TXBuffer += ws.getControllerSymbol(controllerNr) if (settings.Controllers[controllerNr].usesID): ws.TXBuffer += " ({0})".format(settings.Tasks[x].controlleridx[controllerNr]) if (int(settings.Tasks[x].controlleridx[controllerNr]) <= 0): ws.TXBuffer += " " + HTML_SYMBOL_WARNING doBR = True except Exception as e: pass ws.TXBuffer += "<TD>" except Exception as e: print(e) if (settings.Tasks[x].dtype == pglobals.DEVICE_TYPE_I2C): try: i2cpins = settings.get_i2c_pins(settings.Tasks[x].i2c) ws.TXBuffer += "{0}<BR>{1}".format(i2cpins[0],i2cpins[1]) except: ws.TXBuffer += "NO-I2C" if (settings.Tasks[x].dtype == pglobals.DEVICE_TYPE_SPI): try: ws.TXBuffer += "SPI{0}".format(settings.Tasks[x].spi) except: ws.TXBuffer += "NO-SPI" for tp in range(0,len(settings.Tasks[x].taskdevicepin)): if int(settings.Tasks[x].taskdevicepin[tp])>=0: ws.TXBuffer += "<br>GPIO-{0}".format(settings.Tasks[x].taskdevicepin[tp]) ws.TXBuffer += "<TD>" customValues = False # customValues = PluginCall(PLUGIN_WEBFORM_SHOW_VALUES, &TempEvent,ws.TXBuffer.buf); if not(customValues): if (settings.Tasks[x].vtype == pglobals.SENSOR_TYPE_LONG): try: numtodisp = str(float(settings.Tasks[x].uservar[0]) + float(settings.Tasks[x].uservar[1] << 16)) ws.TXBuffer += "<div class='div_l' id='valuename_{0}_0'>{1}:</div><div class='div_r' id='value_{2}_0'>{3}</div>".format(x,settings.Tasks[x].getdevicevaluenames()[0],x,str(misc.formatnum(numtodisp,0))) except Exception as e: print(e) else: try: for varNr in range(0,pglobals.VARS_PER_TASK): if ((settings.Tasks[x].enabled) and (varNr < settings.Tasks[x].valuecount)): if (varNr > 0): ws.TXBuffer += "<div class='div_br'></div>" numtodisp = settings.Tasks[x].uservar[varNr] decimalv = settings.Tasks[x].decimals[varNr] ws.TXBuffer += "<div class='div_l' id='valuename_{0}_{1}'>{2}:</div><div class='div_r' id='value_{3}_{4}'>{5}</div>".format(x,varNr,settings.Tasks[x].getdevicevaluenames()[varNr],x,varNr,str(misc.formatnum(numtodisp,decimalv))) except Exception as e: print(e) else: ws.TXBuffer += "<TD><TD><TD><TD><TD><TD>" httpResponse._write(ws.TXBuffer,strEncoding='UTF-8') ws.TXBuffer = "" ws.TXBuffer += "</table></form>" ws.sendHeadandTail("TmplStd",ws._TAIL) httpResponse._write(ws.TXBuffer,strEncoding='UTF-8') ws.TXBuffer = ""
def handle_devices(httpResponse, responsearr): ws.navMenuIndex = 4 ws.TXBuffer = "" httpResponse.WriteResponseOk(headers=({ 'Cache-Control': 'no-cache' }), contentType='text/html', contentCharset='UTF-8', content="") taskdevicenumber = ws.arg('TDNUM', responsearr) if taskdevicenumber == '': taskdevicenumber = 0 else: taskdevicenumber = int(float(taskdevicenumber)) taskdevicetimer = ws.arg('TDT', responsearr) if taskdevicetimer == '': taskdevicetimer = 0 else: taskdevicetimer = float(taskdevicetimer) edit = ws.arg("edit", responsearr) page = ws.arg("page", responsearr) setpage = ws.arg("setpage", responsearr) taskIndex = ws.arg("index", responsearr) runIndex = ws.arg("run", responsearr) if page == '': page = 0 else: page = int(float(page)) if page == 0: page = 1 if setpage == '': setpage = 0 else: setpage = int(float(setpage)) if (setpage > 0): if setpage <= (pglobals.TASKS_MAX / ws.TASKS_PER_PAGE): page = setpage else: page = int(pglobals.TASKS_MAX / ws.TASKS_PER_PAGE) ws.sendHeadandTail("TmplStd", ws._HEAD) taskIndexNotSet = (taskIndex == 0) or (taskIndex == '') if taskIndex != "": taskIndex = int(taskIndex) - 1 if ws.arg('del', responsearr) != '': taskdevicenumber = 0 ttid = -1 try: ttid = settings.Tasks[taskIndex].pluginid except: ttid = -1 if ttid != -1: try: settings.Tasks[taskIndex].plugin_exit() taskIndexNotSet = True settings.Tasks[taskIndex] = False settings.savetasks() # savetasksettings!!! except Exception as e: misc.addLog(pglobals.LOG_LEVEL_ERROR, "Deleting failed: " + str(e)) if runIndex != "": if len(settings.Tasks) < 1: return False try: s = int(runIndex) except: s = -1 try: if s > 0 and (s <= len(settings.Tasks)): s = s - 1 # array is 0 based, tasks is 1 based if (type(settings.Tasks[s]) != bool) and (settings.Tasks[s]): if (settings.Tasks[s].enabled): settings.Tasks[s].plugin_read() except Exception as e: print(e) httpResponse._write(ws.TXBuffer, strEncoding='UTF-8') ws.TXBuffer = "" if taskIndexNotSet == False: #Show edit form if a specific entry is chosen with the edit button ws.TXBuffer += "<form name='frmselect' method='post'><table class='normal'>" ws.addFormHeader("Task Settings") ws.TXBuffer += "<TR><TD style='width:150px;' align='left'>Device:<TD>" tte = taskdevicenumber try: tte = settings.Tasks[taskIndex].pluginid except: pass if (tte <= 0): ws.addSelector_Head("TDNUM", True) for y in range(0, len(pglobals.deviceselector)): pname = pglobals.deviceselector[y][2] try: if int(pglobals.deviceselector[y][1]) != 0: pname = "P" + str(int( pglobals.deviceselector[y][1])).rjust( 3, "0") + " - " + pglobals.deviceselector[y][2] except: pass ws.addSelector_Item(pname, int(pglobals.deviceselector[y][1]), (pglobals.deviceselector[y][1] == tte), False, "") ws.addSelector_Foot() httpResponse._write(ws.TXBuffer, strEncoding='UTF-8') ws.TXBuffer = "" else: # device selected createnewdevice = True try: if (settings.Tasks[taskIndex].getpluginid() == int(tte)): createnewdevice = False except: pass exceptstr = "" gc.collect() if createnewdevice: for y in range(len(pglobals.deviceselector)): if int(pglobals.deviceselector[y][1]) == int(tte): if len(settings.Tasks) <= taskIndex: while len(settings.Tasks) <= taskIndex: settings.Tasks.append(False) try: m = __import__(pglobals.deviceselector[y][0]) except Exception as e: settings.Tasks[taskIndex] = False exceptstr += str(e) m = False if m: try: settings.Tasks[taskIndex] = m.Plugin(taskIndex) except Exception as e: settings.Tasks.append(m.Plugin(taskIndex)) exceptstr += str(e) break if settings.Tasks[taskIndex] == False: ws.TXBuffer += "Importing failed: {0}</td></tr></table>".format( exceptstr) ws.sendHeadandTail("TmplStd", ws._TAIL) httpResponse._write(ws.TXBuffer, strEncoding='UTF-8') ws.TXBuffer = "" return True else: try: enableit = (ws.arg("TDE", responsearr) == "on") # print("plugin init",enableit) if enableit: settings.Tasks[taskIndex].plugin_init( True ) # call plugin init / (ws.arg("TDE",responsearr) == "on") else: settings.Tasks[taskIndex].plugin_init( ) # call plugin init / (ws.arg("TDE",responsearr) == "on") except: pass if edit != '' and not (taskIndexNotSet): # when form submitted if taskdevicenumber != 0: # save settings if taskdevicetimer > 0: settings.Tasks[taskIndex].interval = taskdevicetimer else: if not (settings.Tasks[taskIndex].timeroptional ): # set default delay settings.Tasks[ taskIndex].interval = settings.Settings[ "Delay"] else: settings.Tasks[taskIndex].interval = 0 tasknamestr = str(ws.arg("TDN", responsearr)).strip() settings.Tasks[taskIndex].taskname = tasknamestr.replace( " ", "") if tasknamestr: settings.Tasks[taskIndex].taskdeviceport = ws.arg( "TDP", responsearr) maxcon = len(settings.Controllers) if maxcon > pglobals.CONTROLLER_MAX: maxcon = pglobals.CONTROLLER_MAX for controllerNr in range(0, maxcon): if ((settings.Controllers[controllerNr]) and (settings.Controllers[controllerNr].enabled)): sid = "TDSD" sid += str(controllerNr + 1) settings.Tasks[taskIndex].senddataenabled[ controllerNr] = (ws.arg(sid, responsearr) == "on") if (settings.Tasks[taskIndex]. senddataenabled[controllerNr]): if (settings.Controllers[controllerNr]): if (settings.Controllers[controllerNr]. enabled): settings.Tasks[taskIndex].controllercb[ controllerNr] = settings.Controllers[ controllerNr].senddata if (settings.Tasks[taskIndex]. senddataenabled[controllerNr]): sid = "TDID" sid += str(controllerNr + 1) ctrlidx = str(ws.arg(sid, responsearr)).strip() if ctrlidx == "": ctrlidx = -1 else: ctrlidx = int(ctrlidx) settings.Tasks[taskIndex].controlleridx[ controllerNr] = ctrlidx for pins in range(0, 4): pinnum = ws.arg("taskdevicepin" + str(pins + 1), responsearr) if pinnum: settings.Tasks[taskIndex].taskdevicepin[ pins] = int(pinnum) # if settings.Tasks[taskIndex].pullupoption: # settings.Tasks[taskIndex].pullup = (ws.arg("TDPPU",responsearr) == "on") if settings.Tasks[taskIndex].inverselogicoption: settings.Tasks[taskIndex].pininversed = (ws.arg( "TDPI", responsearr) == "on") for varnr in range(0, settings.Tasks[taskIndex].valuecount): tvname = str( ws.arg("TDVN" + str(varnr + 1), responsearr)) if tvname: settings.Tasks[taskIndex].valuenames[ varnr] = tvname.replace(" ", "") settings.Tasks[taskIndex].formula[varnr] = ws.arg( "TDF" + str(varnr + 1), responsearr) tvdec = ws.arg("TDVD" + str(varnr + 1), responsearr) if tvdec == "" or tvdec == False or tvdec == None: tvdec = 0 settings.Tasks[taskIndex].decimals[varnr] = tvdec else: settings.Tasks[taskIndex].valuenames[varnr] = "" try: settings.Tasks[taskIndex].i2c = int( ws.arg("i2c", responsearr)) except: settings.Tasks[taskIndex].i2c = -1 try: settings.Tasks[taskIndex].spi = int( ws.arg("spi", responsearr)) except: settings.Tasks[taskIndex].spi = -1 if settings.Tasks[taskIndex].taskname == "": settings.Tasks[taskIndex].enabled = False settings.Tasks[taskIndex].webform_save( responsearr) # call plugin read FORM settings.Tasks[taskIndex].enabled = (ws.arg( "TDE", responsearr) == "on") settings.savetasks() # savetasksettings!!! ws.TXBuffer += "<input type='hidden' name='TDNUM' value='{0}'>{1}".format( settings.Tasks[taskIndex].pluginid, settings.Tasks[taskIndex].getdevicename()) ws.addFormTextBox("Name", "TDN", str(settings.Tasks[taskIndex].gettaskname()), 40) ws.addFormCheckBox("Enabled", "TDE", settings.Tasks[taskIndex].enabled) # section: Sensor / Actuator httpResponse._write(ws.TXBuffer, strEncoding='UTF-8') ws.TXBuffer = "" if (settings.Tasks[taskIndex].dtype >= pglobals.DEVICE_TYPE_SINGLE and settings.Tasks[taskIndex].dtype <= pglobals.DEVICE_TYPE_QUAD): ws.addFormSubHeader("Sensor" if settings.Tasks[taskIndex]. senddataoption else "Actuator") # if (Settings.Tasks[taskIndex].ports != 0): # addFormNumericBox("Port", "TDP", Settings.Tasks[taskIndex].taskdeviceport) # if (settings.Tasks[taskIndex].pullupoption): # ws.addFormCheckBox("Internal PullUp", "TDPPU", settings.Tasks[taskIndex].pullup) if (settings.Tasks[taskIndex].inverselogicoption): ws.addFormCheckBox("Inversed Logic", "TDPI", settings.Tasks[taskIndex].pininversed) if (settings.Tasks[taskIndex].dtype >= pglobals.DEVICE_TYPE_SINGLE and settings.Tasks[taskIndex].dtype <= pglobals.DEVICE_TYPE_QUAD): ws.addFormPinSelect( "1st GPIO", "taskdevicepin1", settings.Tasks[taskIndex].taskdevicepin[0], settings.Tasks[taskIndex].pinfilter[0]) if (settings.Tasks[taskIndex].dtype >= pglobals.DEVICE_TYPE_DUAL and settings.Tasks[taskIndex].dtype <= pglobals.DEVICE_TYPE_QUAD): ws.addFormPinSelect( "2nd GPIO", "taskdevicepin2", settings.Tasks[taskIndex].taskdevicepin[1], settings.Tasks[taskIndex].pinfilter[1]) if (settings.Tasks[taskIndex].dtype >= pglobals.DEVICE_TYPE_TRIPLE and settings.Tasks[taskIndex].dtype <= pglobals.DEVICE_TYPE_QUAD): ws.addFormPinSelect( "3rd GPIO", "taskdevicepin3", settings.Tasks[taskIndex].taskdevicepin[2], settings.Tasks[taskIndex].pinfilter[2]) if (settings.Tasks[taskIndex].dtype == pglobals.DEVICE_TYPE_QUAD): ws.addFormPinSelect( "4th GPIO", "taskdevicepin4", settings.Tasks[taskIndex].taskdevicepin[3], settings.Tasks[taskIndex].pinfilter[3]) if (settings.Tasks[taskIndex].dtype == pglobals.DEVICE_TYPE_I2C): try: import inc.libhw as libhw options = libhw.geti2clist() except: options = [] ws.addHtml("<tr><td>I2C line:<td>") ws.addSelector_Head("i2c", True) for d in range(len(options)): ws.addSelector_Item( "I2C" + str(options[d]), options[d], (settings.Tasks[taskIndex].i2c == options[d]), False) ws.addSelector_Foot() if (settings.Tasks[taskIndex].dtype == pglobals.DEVICE_TYPE_SPI): try: import inc.libhw as libhw options = libhw.getspilist() except: options = [] ws.addHtml("<tr><td>SPI line:<td>") ws.addSelector_Head("spi", True) for d in range(len(options)): ws.addSelector_Item( "SPI" + str(options[d]), options[d], (settings.Tasks[taskIndex].spi == options[d]), False) ws.addSelector_Foot() httpResponse._write(ws.TXBuffer, strEncoding='UTF-8') ws.TXBuffer = "" try: settings.Tasks[taskIndex].webform_load( ) # call plugin function to fill ws.TXBuffer except Exception as e: print(e) httpResponse._write(ws.TXBuffer, strEncoding='UTF-8') ws.TXBuffer = "" if (settings.Tasks[taskIndex].senddataoption ): # section: Data Acquisition ws.addFormSubHeader("Data Acquisition") maxcon = len(settings.Controllers) if maxcon > pglobals.CONTROLLER_MAX: maxcon = pglobals.CONTROLLER_MAX for controllerNr in range(0, maxcon): if ((settings.Controllers[controllerNr]) and (settings.Controllers[controllerNr].enabled)): sid = "TDSD" sid += str(controllerNr + 1) ws.TXBuffer += "<TR><TD>Send to Controller {0}<TD>".format( ws.getControllerSymbol(controllerNr)) ws.addCheckBox( sid, settings.Tasks[taskIndex]. senddataenabled[controllerNr]) sid = "TDID" sid += str(controllerNr + 1) if (settings.Controllers[controllerNr].enabled ) and settings.Tasks[taskIndex].senddataenabled[ controllerNr]: if (settings.Controllers[controllerNr].usesID): ws.TXBuffer += "<TR><TD>IDX:<TD>" ws.addNumericBox( sid, settings.Tasks[taskIndex]. controlleridx[controllerNr], 0, 9999) else: ws.TXBuffer += "<input type='hidden' name='{0}' value='0'>".format( sid) # no id, set to 0 else: ws.TXBuffer += "<input type='hidden' name='{0}' value='-1'>".format( sid) # disabled set to -1 ws.addFormSeparator(2) httpResponse._write(ws.TXBuffer, strEncoding='UTF-8') ws.TXBuffer = "" if (settings.Tasks[taskIndex].timeroption): ws.addFormNumericBox("Interval", "TDT", settings.Tasks[taskIndex].interval, 0, 65535) ws.addUnit("sec") if (settings.Tasks[taskIndex].timeroptional): ws.TXBuffer += " (Optional for this Device)" if (settings.Tasks[taskIndex].valuecount > 0): # //section: Values ws.addFormSubHeader("Values") ws.TXBuffer += "</table><table class='normal'><TR><TH style='width:30px;' align='center'>#<TH align='left'>Name" if (settings.Tasks[taskIndex].formulaoption): ws.TXBuffer += "<TH align='left'>Formula" if (settings.Tasks[taskIndex].formulaoption or settings.Tasks[taskIndex].decimalsonly): ws.TXBuffer += "<TH style='width:30px;' align='left'>Decimals" for varNr in range(0, settings.Tasks[taskIndex].valuecount): ws.TXBuffer += "<TR><TD>{0}<TD>".format(str(varNr + 1)) sid = "TDVN" + str(varNr + 1) ws.addTextBox( sid, settings.Tasks[taskIndex].getdevicevaluenames()[varNr], 40) if (settings.Tasks[taskIndex].formulaoption): ws.TXBuffer += "<TD>" sid = "TDF" + str(varNr + 1) ws.addTextBox(sid, settings.Tasks[taskIndex].formula[varNr], 140) if (settings.Tasks[taskIndex].formulaoption or settings.Tasks[taskIndex].decimalsonly): ws.TXBuffer += "<TD>" sid = "TDVD" + str(varNr + 1) ws.addNumericBox( sid, settings.Tasks[taskIndex].decimals[varNr], 0, 6) ws.addFormSeparator(4) httpResponse._write(ws.TXBuffer, strEncoding='UTF-8') ws.TXBuffer = "" gc.collect() ws.TXBuffer += "<TR><TD><TD colspan='3'><a class='button link' href='devices?setpage={0}'>Close</a>".format( page) ws.addSubmitButton() ws.TXBuffer += "<input type='hidden' name='edit' value='1'>" if taskIndex != '': ws.TXBuffer += "<input type='hidden' name='index' value='{0}'>".format( taskIndex + 1) ws.TXBuffer += "<input type='hidden' name='page' value='1'>" if (tte > 0): # if user selected a device, add the delete button ws.addSubmitButton("Delete", "del") ws.TXBuffer += "</table></form>" ws.sendHeadandTail("TmplStd", ws._TAIL) httpResponse._write(ws.TXBuffer, strEncoding='UTF-8') ws.TXBuffer = ""
def pkt_receiver(self, payload): if self.enabled: try: rssi = self._lora.packet_rssi() except: rssi = -100 try: dp = p2pbuffer.data_packet() dp.buffer = payload dp.decode() # print("REC",payload,dp.buffer) #debug except: pass try: if dp.pkgtype != 0: if dp.pkgtype == 1: # print(dp.infopacket) if int(dp.infopacket["unitno"]) == int( settings.Settings["Unit"] ): # skip own messages return False un = getunitordfromnum( dp.infopacket["unitno"] ) # process incoming alive reports if un == -1: # CAPABILITIES byte: first bit 1 if able to send, second bit 1 if able to receive settings.p2plist.append({ "protocol": "LORA", "unitno": dp.infopacket["unitno"], "name": dp.infopacket["name"], "build": dp.infopacket["build"], "type": dp.infopacket["type"], "mac": dp.infopacket["mac"], "lastseen": utime.localtime(), "lastrssi": rssi, "cap": dp.infopacket["cap"] }) misc.addLog( pglobals.LOG_LEVEL_INFO, "New LORA unit discovered: " + str(dp.infopacket["unitno"]) + " " + str(dp.infopacket["name"])) settings.p2plist.sort(reverse=False, key=self.nodesort) else: misc.addLog( pglobals.LOG_LEVEL_DEBUG, "Unit alive: " + str(dp.infopacket["unitno"])) if settings.p2plist[un]["type"] == 0: settings.p2plist[un]["name"] = dp.infopacket[ "name"] settings.p2plist[un]["build"] = dp.infopacket[ "build"] settings.p2plist[un]["type"] = dp.infopacket[ "type"] settings.p2plist[un]["mac"] = dp.infopacket[ "mac"] settings.p2plist[un]["cap"] = dp.infopacket["cap"] settings.p2plist[un]["lastseen"] = utime.localtime( ) settings.p2plist[un]["lastrssi"] = rssi elif dp.pkgtype == 5: # process incoming data if int(dp.sensordata["sunit"]) == int( settings.Settings["Unit"]): return False un = getunitordfromnum(dp.sensordata["sunit"]) if un > -1: # refresh lastseen data settings.p2plist[un]["lastseen"] = utime.localtime( ) settings.p2plist[un]["lastrssi"] = rssi else: settings.p2plist.append({ "protocol": "LORA", "unitno": dp.sensordata["sunit"], "name": "", "build": 0, "type": 0, "mac": "", "lastseen": utime.localtime(), "lastrssi": rssi, "cap": 1 }) if (int(settings.Settings["Unit"]) == int( dp.sensordata["dunit"] )) or ( 0 == int(dp.sensordata["dunit"]) ): # process only if we are the destination or broadcast ltaskindex = -1 for x in range( 0, len(settings.Tasks) ): # check if the sent IDX already exists? try: if (type(settings.Tasks[x]) is not bool and settings.Tasks[x]): if settings.Tasks[x].controlleridx[ self.controllerindex] == int( dp.sensordata["idx"]): ltaskindex = x break except Exception as e: print(e) dvaluecount = int(dp.sensordata["valuecount"]) if pglobals.VARS_PER_TASK < dvaluecount: # avoid possible buffer overflow dvaluecount = pglobals.VARS_PER_TASK if ltaskindex < 0: # create new task if necessarry devtype = int(dp.sensordata["pluginid"]) m = False try: for y in range(len( pglobals.deviceselector)): if int(pglobals.deviceselector[y] [1]) == devtype: m = __import__( pglobals.deviceselector[y][0]) break except: m = False TempEvent = None if m: try: TempEvent = m.Plugin(-1) except: TempEvent = None if True: ltaskindex = -1 for x in range( 0, len(settings.Tasks) ): # check if there are free TaskIndex slot exists try: if (type(settings.Tasks[x]) is bool): if settings.Tasks[x] == False: ltaskindex = x break except: pass devtype = 33 # dummy device m = False try: for y in range( len(pglobals.deviceselector)): if int(pglobals.deviceselector[y] [1]) == devtype: m = __import__( pglobals.deviceselector[y] [0]) break except: m = False if m: if ltaskindex < 0: ltaskindex = len(settings.Tasks) try: settings.Tasks[ ltaskindex] = m.Plugin( ltaskindex) except: ltaskindex = len(settings.Tasks) settings.Tasks.append( m.Plugin(ltaskindex) ) # add a new device settings.Tasks[ltaskindex].plugin_init( True) settings.Tasks[ ltaskindex].remotefeed = True # Mark that this task accepts incoming data updates! settings.Tasks[ ltaskindex].enabled = True settings.Tasks[ltaskindex].interval = 0 settings.Tasks[ ltaskindex].senddataenabled[ self.controllerindex] = True settings.Tasks[ ltaskindex].controlleridx[ self.controllerindex] = int( dp.sensordata["idx"]) if TempEvent is not None: settings.Tasks[ ltaskindex].taskname = TempEvent.PLUGIN_NAME.replace( " ", "") for v in range(dvaluecount): settings.Tasks[ ltaskindex].valuenames[ v] = TempEvent.valuenames[ v] settings.Tasks[ ltaskindex].taskdevicepluginconfig[ 0] = TempEvent.vtype settings.Tasks[ ltaskindex].vtype = TempEvent.vtype else: settings.Tasks[ ltaskindex].taskname = settings.Tasks[ ltaskindex].PLUGIN_NAME.replace( " ", "") settings.Tasks[ ltaskindex].valuecount = dvaluecount settings.savetasks() if ltaskindex < 0: return False misc.addLog( pglobals.LOG_LEVEL_DEBUG, "Sensordata update arrived from unit " + str(dp.sensordata["sunit"]) ) # save received values if settings.Tasks[ltaskindex].remotefeed: recok = False try: if self._onmsgcallbackfunc is not None and settings.Tasks[ ltaskindex].recdataoption: self._onmsgcallbackfunc( self.controllerindex, -1, self._dp.sensordata["values"], settings.Tasks[ltaskindex]. gettaskname()) recok = True except: pass if recok == False: for v in range(dvaluecount): settings.Tasks[ltaskindex].set_value( v + 1, dp.sensordata["values"][v], False) settings.Tasks[ltaskindex].plugin_senddata( ) elif dp.pkgtype == 7: # process incoming command if int(dp.cmdpacket["sunit"]) == int( settings.Settings["Unit"]): return False un = getunitordfromnum(dp.cmdpacket["sunit"]) if un > -1: # refresh lastseen data settings.p2plist[un]["lastseen"] = utime.localtime( ) settings.p2plist[un]["lastrssi"] = rssi else: settings.p2plist.append({ "protocol": "LORA", "unitno": dp.cmdpacket["sunit"], "name": "", "build": 0, "type": 0, "mac": "", "lastseen": utime.localtime(), "lastrssi": rssi, "cap": 1 }) if (int(settings.Settings["Unit"]) == int( dp.cmdpacket["dunit"] )) or ( 0 == int(dp.cmdpacket["dunit"]) ): # process only if we are the destination or broadcast misc.addLog( pglobals.LOG_LEVEL_INFO, "Command arrived from " + str(dp.cmdpacket["sunit"])) # print(dp.cmdpacket["cmdline"]) # DEBUG commands.doExecuteCommand(dp.cmdpacket["cmdline"], True) except Exception as e: print("C20 decode error", str(e))