Beispiel #1
0
 def timer_thirty_second(self):
     if self.enabled:
         #send alive signals
         dp = data_packet()
         try:
             defdev = Settings.NetMan.getprimarydevice()
         except Exception as e:
             misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,
                         "C013 sysinfo: " + str(e))
             defdev = -1
         if defdev != -1:
             dp.infopacket["mac"] = Settings.NetworkDevices[defdev].mac
             dp.infopacket["ip"] = Settings.NetworkDevices[defdev].ip
         else:
             dp.infopacket["mac"] = "00:00:00:00:00:00"
             dp.infopacket["ip"] = ""
         if dp.infopacket["ip"] == "":
             try:
                 dp.infopacket["ip"] = str(OS.get_ip())
             except:
                 pass
         if dp.infopacket["ip"] == "":
             dp.infopacket["ip"] = "0.0.0.0"
         dp.infopacket["unitno"] = int(Settings.Settings["Unit"])
         dp.infopacket["build"] = int(rpieGlobals.BUILD)
         dp.infopacket["name"] = Settings.Settings["Name"]
         dp.infopacket["type"] = int(rpieGlobals.NODE_TYPE_ID_RPI_EASY_STD)
         dp.infopacket["port"] = int(Settings.WebUIPort)
         try:
             dp.encode(1)
             self.udpsender(255, dp.buffer, 1)
         except Exception as e:
             misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,
                         "C013 sysinfo: " + str(e))
         #clear old nodes
         for n in range(len(Settings.nodelist)):
             try:
                 if Settings.nodelist[n]["age"] >= 10:
                     misc.addLog(
                         rpieGlobals.LOG_LEVEL_INFO,
                         "P2P unit disappeared: " +
                         str(Settings.nodelist[n]["unitno"]))
                     del Settings.nodelist[n]
                 else:
                     Settings.nodelist[n]["age"] += 1
             except:
                 pass
     return True
Beispiel #2
0
 def getIP(self):
     if time.time() - self.iptime > 30:
         self.iptime = time.time()
         ip = ""
         try:
             defdev = Settings.NetMan.getprimarydevice()
         except:
             defdev = -1
         if defdev != -1:
             ip = Settings.NetworkDevices[defdev].ip
         else:
             ip = ""
         if ip == "":
             ip = str(OS.get_ip())
         if ip != "":
             self.ip = ip
     return self.ip
Beispiel #3
0
 def webform_load(self):
     webserver.addFormNote("Hint: only the Controller Port parameter used!")
     options = ["Primary net", "Secondary net", "Manual"]
     optionvalues = [0, 1, 2]
     try:
         netm = self.netmethod
     except:
         netm = 0
     webserver.addFormSelector("IP address", "c013_net", len(optionvalues),
                               options, optionvalues, None, int(netm))
     try:
         oip = self.ownip
     except:
         oip = ""
     if netm != 2:
         oip = ""
     elif oip == "":
         oip = str(OS.get_ip())
     webserver.addFormTextBox("Force own IP to broadcast", "c013_ip",
                              str(oip), 16)
     webserver.addFormCheckBox("Enable dynamic task number allocation",
                               "c013_dyntask", self.dynamictasknum)
     return True
Beispiel #4
0
def getglobalvar(varname):
 global SysVars, suntimesupported
 svname = varname.strip().lower()
 par = ""
 if ("-" in svname):
  resarr = svname.split("-")
  svname = resarr[0]
  par = "-"+resarr[1]
 if ("+" in svname):
  resarr = svname.split("+")
  svname = resarr[0]
  par = "+"+resarr[1]
 res = ""
 if svname in SysVars:
   if svname==SysVars[0]: #%systime%	01:23:54
    return datetime.now().strftime('%H:%M:%S')
   elif svname==SysVars[1]: #%systm_hm% 	01:23 
    return datetime.now().strftime('%H:%M')
   elif svname==SysVars[2]: #%lcltime% 	2018-03-16 01:23:54 
    return datetime.now().strftime('%Y-%m-%d %H:%M:%S')
   elif svname==SysVars[3]: #%syshour% 	11 	Current hour (hh)
    return int(datetime.now().strftime('%H'))
   elif svname==SysVars[4]: #%sysmin% 	22 	Current minute (mm)
    return int(datetime.now().strftime('%M'))
   elif svname==SysVars[5]: #%syssec% 	33 	Current second (ss)
    return int(datetime.now().strftime('%S'))
   elif svname==SysVars[6]: #%sysday% 	16 	Current day of month (DD)
    return int(datetime.now().strftime('%d'))
   elif svname==SysVars[7]: #%sysmonth% 	3 	Current month (MM)
    return int(datetime.now().strftime('%m'))
   elif svname==SysVars[8]: #%sysyear% 	2018 	4 digits (YYYY)
    return datetime.now().strftime('%Y')
   elif svname==SysVars[9]: #%sysyears% 	18 	2 digits (YY)
    return datetime.now().strftime('%y')
   elif svname==SysVars[10]: #%sysweekday% 	5 	Weekday (integer) - 1, 2, 3... (1=Sunday, 2=Monday etc.)
    return str(int(datetime.now().strftime('%w'))+1)
   elif svname==SysVars[11]: #%sysweekday_s% 	Fri 	Weekday (verbose) - Sun, Mon, Tue
    return datetime.now().strftime('%a')
   elif svname==SysVars[12]: #%unixtime% 	1521731277 	Unix time (seconds since epoch, 1970-01-01 00:00:00)
    return str(int(time.time()))
   elif svname==SysVars[13]: #%uptime% 	3244 	Uptime in minutes
    return str(rpieTime.getuptime(2))
   elif svname==SysVars[14]: #%rssi% 	-45 	WiFi signal strength (dBm)
    return str(OS.get_rssi())
   elif svname==SysVars[15]: #%ip% 	192.168.0.123 	Current IP address
    return str(OS.get_ip())
   elif svname==SysVars[16]: #%ip4% ipcim 4.byte
    res2 = str(OS.get_ip())
    resarr = res2.split(".")
    if len(resarr)>3:
     return resarr[3]
   elif svname==SysVars[17]: #%sysname%	name
    return Settings.Settings["Name"]
   elif svname==SysVars[18]: #%unit% 	32 	Unit number
    return Settings.Settings["Unit"]
   elif svname==SysVars[19]: #%ssid% 	H4XX0R njietwork! 
    wdev = False
    try:
     wdev = Settings.NetMan.getfirstwirelessdev()
    except:
     wdev = False
    if wdev:
     res = str(Network.get_ssid(wdev))
   elif svname==SysVars[20]: #%mac% 	00:14:22:01:23:45 	MAC address
    pd = -1
    try:
     pd = Settings.NetMan.getprimarydevice()
    except:
     pd = -1
    if pd<0 and len(Settings.NetworkDevices)>0:
     pd = 0
    if pd!="" and pd>=0:
     return Settings.NetworkDevices[pd].mac
   elif svname==SysVars[21]: #%mac_int% 	2212667 	MAC address in integer to be used in rules (only the last 24 bit)
    pd = -1
    try:
     pd = Settings.NetMan.getprimarydevice()
    except:
     pd = -1
    if pd<0 and len(Settings.NetworkDevices)>0:
     pd = 0
    if pd>=0:
     try:
      res2 = Settings.NetworkDevices[pd].mac
      resarr = res2.split(":")
      if len(resarr)>5:
       res = str(int("0x"+resarr[3]+resarr[4]+resarr[5],16))
     except:
      res = ""
    return res
   elif svname==SysVars[22]: #%build%
    bstr = str(rpieGlobals.BUILD)
    return bstr
   elif svname==SysVars[23]: #sunrise
    try:
      from suntime import Sun
      suntimesupported = 1
    except:
      suntimesupported = 0
    if suntimesupported==1:
     try:
      sun = Sun(Settings.AdvSettings["Latitude"],Settings.AdvSettings["Longitude"])
      abd_sr = sun.get_local_sunrise_time(datetime.now())
      if par!="":
       abd_sr = addtoTime(abd_sr,par)
      res = abd_sr.strftime('%H:%M')
     except Exception as e:
      res = "00:00"
     return res
   elif svname==SysVars[24]: #sunset
    try:
      from suntime import Sun
      suntimesupported = 1
    except:
      suntimesupported = 0
    if suntimesupported==1:
     try:
      sun = Sun(Settings.AdvSettings["Latitude"],Settings.AdvSettings["Longitude"])
      abd_ss = sun.get_local_sunset_time(datetime.now())
      if par!="":
       abd_ss = addtoTime(abd_ss,par)
      res = abd_ss.strftime('%H:%M')
     except Exception as e:
      res = "00:00"
     return res

   elif svname==SysVars[25]: #sun altitude
    try:
      from pytz import reference
      from pysolar.solar import get_altitude
      pysolarsupported = 1
    except:
      pysolarsupported = 0
    res = "0"
    if pysolarsupported==1:
     try:
      localtime = reference.LocalTimezone()
      today = datetime.now(localtime)
      res = get_altitude(Settings.AdvSettings["Latitude"],Settings.AdvSettings["Longitude"], today)
     except Exception as e:
      print(e)
      res = "0"
     return res

   elif svname==SysVars[26]: #sun azimuth
    try:
      from pytz import reference
      from pysolar.solar import get_azimuth
      pysolarsupported = 1
    except:
      pysolarsupported = 0
    res = "0"
    if pysolarsupported==1:
     try:
      localtime = reference.LocalTimezone()
      today = datetime.now(localtime)
      res = get_azimuth(Settings.AdvSettings["Latitude"],Settings.AdvSettings["Longitude"], today)
     except Exception as e:
      print(e)
      res = "0"
     return res

   elif svname==SysVars[27]: #sun radiation
    try:
      from pytz import reference
      from pysolar.solar import get_altitude
      from pysolar.radiation import get_radiation_direct
      pysolarsupported = 1
    except:
      pysolarsupported = 0
    res = "-1"
    if pysolarsupported==1:
     try:
      localtime = reference.LocalTimezone()
      today = datetime.now(localtime)
      altitude_deg = get_altitude(Settings.AdvSettings["Latitude"],Settings.AdvSettings["Longitude"], today)
      res = get_radiation_direct(today, altitude_deg)
     except Exception as e:
      print(e)
     return res

   elif svname==SysVars[28]: #%br%
    return str("\r\n")

   elif svname==SysVars[29]: #%lf%
    return str("\n")

   elif svname==SysVars[30]: #%tab%
    return str("	")

 return res
Beispiel #5
0
def handle_dash(self):
    try:
        if (not webserver.isLoggedIn(self.get, self.cookie)):
            return self.redirect('/login')
        webserver.navMenuIndex = 7

        dashtask = None
        for t in range(0, len(Settings.Tasks)):
            if (Settings.Tasks[t] and (type(Settings.Tasks[t]) is not bool)):
                try:
                    if Settings.Tasks[t].enabled:
                        if Settings.Tasks[t].pluginid == 212:
                            dashtask = Settings.Tasks[t]
                            break
                except:
                    pass
        webserver.TXBuffer = ""
        if (dashtask is not None) and (dashtask.taskdevicepluginconfig[2]):
            webserver.sendHeadandTail("TmplStd", webserver._HEAD)
            webserver.TXBuffer += "<link rel='stylesheet' href='/img/dash.css'>"
        else:
            webserver.TXBuffer += "<!DOCTYPE html><html lang='en'><head><meta charset='utf-8'/><link rel='stylesheet' href='/img/dash.css'></head><body>"

        if (dashtask is not None) and (len(dashtask.celldata) > 0):
            astr = ""
            estr = ""
            vstr = ""
            if int(dashtask.taskdevicepluginconfig[0]) > 1 and int(
                    dashtask.taskdevicepluginconfig[0]) < 7:
                astr = " tab" + str(dashtask.taskdevicepluginconfig[0])
            webserver.addHtml("<table width='100%' class='tab " + astr + "'>")
            offs = 0
            for r in range(int(dashtask.taskdevicepluginconfig[1])):
                if offs >= len(dashtask.celldata):
                    break
                webserver.addHtml("<tr>")
                for c in range(int(dashtask.taskdevicepluginconfig[0])):
                    if offs >= len(dashtask.celldata):
                        break
                    webserver.addHtml("<td>")
                    offs = (r * int(dashtask.taskdevicepluginconfig[0])) + c
                    try:
                        dtype = int(dashtask.celldata[offs]["type"])
                        tid = str(dashtask.celldata[offs]["data"])
                        estr += '"' + tid + '",'
                        ti = tid.split("_")
                        tasknum = int(ti[0])
                        valnum = int(ti[1])
                        vstr += '"' + str(
                            Settings.Tasks[tasknum].uservar[valnum]) + '",'
                        try:
                            namestr = str(dashtask.celldata[offs]["name"])
                        except:
                            namestr = ""
                        if namestr.strip() == "":
                            namestr = str(Settings.Tasks[tasknum].gettaskname(
                            )) + "#" + str(
                                Settings.Tasks[tasknum].valuenames[valnum])
                        webserver.addHtml("<div class='div_d' id='valuename_" +
                                          str(tid) + "'>" + namestr + "</div>")
                    except:
                        dtype = -1
                    try:
                        udata = str(dashtask.celldata[offs]["unit"])
                    except:
                        udata = ""
                    if dtype == 0:
                        webserver.addHtml(
                            "<div class='textval' id='value_" + str(tid) +
                            "'>" +
                            str(Settings.Tasks[tasknum].uservar[valnum]) +
                            "</div>")
                    elif dtype == 1:
                        webserver.addHtml(
                            "<div class='centered'><input type='checkbox' id='value_"
                            + str(tid) +
                            "' class='state' disabled='disabled'/><label for='value_"
                            + str(tid) +
                            "' class='toggleWrapper'><div class='toggle'></div></label></div>"
                        )
                    elif dtype == 2:
                        webserver.addHtml(
                            "<div class='switch'><input id='value_" +
                            str(tid) +
                            "' class='cmn-toggle cmn-toggle-round' type='checkbox' onchange='cboxchanged(this)'><label for='value_"
                            + str(tid) + "'></label></div>")
                    elif dtype == 3:
                        try:
                            umin = float(dashtask.celldata[offs]["min"])
                        except:
                            umin = 0
                        try:
                            umax = float(dashtask.celldata[offs]["max"])
                        except:
                            umax = 100
                        webserver.addHtml(
                            "<div style='width:100%'><meter id='value_" +
                            str(tid) + "' min='" + str(umin) + "' max='" +
                            str(umax) + "' value='" +
                            str(Settings.Tasks[tasknum].uservar[valnum]) +
                            "' class='meter'></meter>")
                        sval = umin
                        stepval = (umax - umin) / 5
                        webserver.addHtml(
                            "<ul id='scale'><li style='width: 10%'><span></span></li>"
                        )
                        while sval < (umax - stepval):
                            sval = sval + stepval
                            webserver.addHtml("<li><span id='scale'>" +
                                              str(sval) + "</span></li>")
                        webserver.addHtml(
                            "<li style='width: 10%'><span id='scale'></span></li></ul></div>"
                        )
                    elif dtype == 4:
                        webserver.addHtml(
                            "<div class='gauge' id='value_" + str(tid) +
                            "'><div class='gauge__body'><div class='gauge__fill'></div><div class='gauge__cover'></div></div></div>"
                        )
                    elif dtype == 5:
                        try:
                            umin = float(dashtask.celldata[offs]["min"])
                        except:
                            umin = 0
                        try:
                            umax = float(dashtask.celldata[offs]["max"])
                        except:
                            umax = 100
                        webserver.addHtml(
                            "<input type='range' min='" + str(umin) +
                            "' max='" + str(umax) + "' value='" +
                            str(Settings.Tasks[tasknum].uservar[valnum]) +
                            "' class='slider' id='value_" + str(tid) +
                            "' onchange='sselchanged(this)' oninput='this.nextElementSibling.value = this.value'>"
                        )
                        webserver.addHtml(
                            "<output>" +
                            str(Settings.Tasks[tasknum].uservar[valnum]) +
                            "</output>")
                    elif dtype == 6:
                        webserver.addHtml(
                            "<div class='box'><select name='value_" +
                            str(tid) + "' id='value_" + str(tid) +
                            "' onchange='sselchanged(this)'>")
                        optionnames = []
                        if "," in dashtask.celldata[offs]["optionnames"]:
                            optionnames = dashtask.celldata[offs][
                                "optionnames"].split(",")
                        elif ";" in dashtask.celldata[offs]["optionnames"]:
                            optionnames = dashtask.celldata[offs][
                                "optionnames"].split(",")
                        options = []
                        if "," in dashtask.celldata[offs]["options"]:
                            options = dashtask.celldata[offs]["options"].split(
                                ",")
                        elif ";" in dashtask.celldata[offs]["options"]:
                            options = dashtask.celldata[offs]["options"].split(
                                ",")
                        ol = len(optionnames)
                        if ol > len(options):
                            ol = len(options)
                        for o in range(ol):
                            webserver.addHtml("<option value='" +
                                              str(options[o]) + "'>" +
                                              str(optionnames[o]) +
                                              "</option>")
                        webserver.addHtml("</select></div>")
                    else:
                        webserver.addHtml("&nbsp;")
                    if udata.strip() != "":
                        webserver.addHtml(textparse(udata))
                    webserver.addHtml("</td>")
                webserver.addHtml("</tr>")
            webserver.addHtml("</table>")
            webserver.addHtml(
                '<script type="text/javascript" src="/img/dash.js"></script>')
            webserver.addHtml("<script>var elements=[" + estr +
                              "]; var values=[" + vstr + "];")
            offs = (dashtask.taskdevicepluginconfig[0] *
                    dashtask.taskdevicepluginconfig[1])
            pstr = ""
            for o in range(offs):
                if "min" in dashtask.celldata[o]:
                    pstr += "[" + str(dashtask.celldata[o]["min"]) + "," + str(
                        dashtask.celldata[o]["max"]) + "],"
                else:
                    pstr += '[0,100],'
            webserver.addHtml('var props=[' + str(pstr) + '];')
            webserver.addHtml("var ownurl='http://" + str(OS.get_ip()) + ":" +
                              str(Settings.WebUIPort) + "';")
            webserver.addHtml(
                "refreshDatas();setInterval(function(){ getDatas(); }, " +
                str(dashtask.interval * 1000) + ");</script>")
        else:
            webserver.TXBuffer += "<p>Setup dashboard first!"
        if dashtask.taskdevicepluginconfig[2]:
            webserver.sendHeadandTail("TmplStd", webserver._TAIL)
        else:
            webserver.TXBuffer += "</body></html>"
    except Exception as e:
        print("Config error, try to delete and recreate task!")
    return webserver.TXBuffer