Пример #1
0
 def controller_init(self, enablecontroller=None):
     if enablecontroller != None:
         self.enabled = enablecontroller
     self.initialized = False
     if self.enabled:
         if int(Settings.Settings["Unit"]) > 0:
             self.controllerport = Settings.Settings["Unit"]
         self.lastsysinfo = 0
         if self.bleserv is not None:
             try:
                 self.bleserv.stop()
                 time.sleep(1)
             except:
                 pass
         try:
             output = os.popen(
                 OS.cmdline_rootcorrect("sudo systemctl stop bluetooth"))
             for l in output:
                 pass
         except Exception as e:
             print(e)
         try:
             output = os.popen(
                 OS.cmdline_rootcorrect("sudo hciconfig hci0 up"))
             for l in output:
                 pass
         except Exception as e:
             print(e)
         try:
             self.bleclient = BLEClient(self.defaultdestination, self.duty)
             self.bleserv = BLEServer(Settings.Settings["Name"],
                                      self.pkt_receiver, self.getmode)
             if self.enablerec:
                 self.bleserv.start()
             if self.enablesend == False:
                 self.defaultdestination = ""
             self.initialized = True
             time.sleep(1)
             misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG,
                         "BLE Direct initialized")
         except Exception as e:
             self.initialized = False
             misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,
                         "BLE Direct init error: " + str(e))
     else:
         if self.bleserv is not None:
             try:
                 self.bleserv.stop()
             except:
                 pass
     return True
Пример #2
0
def AP_start(ndi, force=False):  # index in NetworkDevices array
    ndi = int(ndi)
    if ndi >= len(Settings.NetworkDevices) or ndi < 0:
        print("NetworkDevice " + str(ndi) + " not found")
        return False
    if force == False:
        if Settings.NetworkDevices[
                ndi].ip == "192.168.4.1" or Settings.NetworkDevices[
                    ndi].apmode == 1:
            return False  # already in apmode
        if Settings.NetMan.APMode < 0:
            return False
    APName = Settings.Settings["Name"]
    if APName == "RPIEasy":
        APName += "-" + str(Settings.Settings["Unit"])
    try:
        chan = Settings.NetMan.WifiAPChannel
    except:
        chan = 1
    if len(Settings.NetMan.WifiAPKey.strip()
           ) < 8:  # wpa password can not be shorter than 8 character
        Settings.NetMan.WifiAPKey = "configrpi"
    Settings.NetworkDevices[ndi].apmode = 1
    cmdline = 'sudo lib/scripts/ap_start.sh ' + str(
        Settings.NetworkDevices[ndi].devicename) + " " + str(
            APName) + " " + str(Settings.NetMan.WifiAPKey) + " " + str(chan)
    #    print(cmdline) # debug
    subprocess.call(shlex.split(OS.cmdline_rootcorrect(cmdline)))
    return True
Пример #3
0
def upgrade_pip(pkgs):
    if len(Settings.UpdateString) > 0:
        if Settings.UpdateString[0] == "!":
            misc.addLog(rpieGlobals.LOG_LEVEL_INFO, "Update in progress")
            return False
    if len(pkgs) < 1:
        return False
    sf = 0
    us = 0
    for p in pkgs:
        ustr = "Upgrading package " + str(p)
        Settings.UpdateString = "!" + ustr
        misc.addLog(rpieGlobals.LOG_LEVEL_INFO, ustr)
        try:
            output = os.popen(
                OS.cmdline_rootcorrect('sudo -H pip3 install --upgrade ' +
                                       str(p)))
            for line in output:
                pass
            sf += 1
        except:
            us += 1
    ustr = "PIP upgrade ended (successful:" + str(sf) + ",unsuccesful:" + str(
        us) + ")"
    Settings.UpdateString = "=" + ustr
    misc.addLog(rpieGlobals.LOG_LEVEL_INFO, ustr)
    return True
Пример #4
0
 def play(self,level):
   try:
    level = int(level)
   except:
    level = 0
   if level==1:
    if (Settings.SoundSystem["inuse"] and Settings.SoundSystem["usingplugintaskindex"] != self.taskindex):
     if Settings.SoundSystem["askplugintorelease"] != None:
      try:
       Settings.SoundSystem["askplugintorelease"](True) # ask to stop
      except Exception as e:
       pass
      time.sleep(0.2)
    try:
      output = os.popen(OS.cmdline_rootcorrect('sudo systemctl start snapclient'))
      for line in output:
       pass
    except:
      pass
    state = self.getstatus()
    if state==1:
     Settings.SoundSystem["inuse"] = True
     Settings.SoundSystem["usingplugintaskindex"] = self.taskindex
     Settings.SoundSystem["askplugintorelease"] = self.stop
   else:
     self.stop()
Пример #5
0
def installdeps(modulename):
 global modulelist
 for i in range(len(modulelist)):
  if modulelist[i]["name"]==modulename and modulelist[i]["installed"]!=1:
   modulelist[i]["installed"] = -1
   try:
    if modulelist[i]["apt"]:
     installprog = " "
     for j in range(len(modulelist[i]["apt"])):
      if rpieGlobals.ossubtype==2: # arch exceptions
       if "python3-pip" in modulelist[i]["apt"][j]:
        modulelist[i]["apt"][j].replace("python3-pip","python-pip")
      installprog += modulelist[i]["apt"][j] + " "
     if rpieGlobals.ossubtype in [1,10]:
      installprog = OS.cmdline_rootcorrect("sudo apt-get update && sudo apt-get install -y "+ installprog.strip())
     elif rpieGlobals.ossubtype==2:
      installprog = OS.cmdline_rootcorrect("yes | sudo pacman -S "+ installprog.strip())
     misc.addLog(rpieGlobals.LOG_LEVEL_INFO,installprog)
     proc = subprocess.Popen(installprog, shell=True, stdin=None, stdout=open(os.devnull,"wb"), executable="/bin/bash")
     proc.wait()
   except Exception as e:
     misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,str(e))
   try:
    if modulelist[i]["pip"]:
     installprog = " "
     for j in range(len(modulelist[i]["pip"])):
      installprog += modulelist[i]["pip"][j] + " "
     installprog = "sudo -H pip3 install "+ installprog.strip()
     if OS.is_command_found("sudo")==False: # if sudo is installed use it because -H option is important
      installprog = OS.cmdline_rootcorrect("sudo -H pip3 install "+ installprog.strip())
     misc.addLog(rpieGlobals.LOG_LEVEL_INFO,installprog)
     proc = subprocess.Popen(installprog, shell=True, stdin=None, stdout=open(os.devnull,"wb"), executable="/bin/bash")
     proc.wait()
   except Exception as e:
     misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,str(e))
   try:
    if modulelist[i]["installcmd"]:
     installprog = OS.cmdline_rootcorrect(modulelist[i]["installcmd"].strip())
     misc.addLog(rpieGlobals.LOG_LEVEL_INFO,installprog)
     proc = subprocess.Popen(installprog, shell=True, stdin=None, stdout=open(os.devnull,"wb"), executable="/bin/bash")
     proc.wait()
   except Exception as e:
     if e!='installcmd':
      misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,str(e))
   break
Пример #6
0
 def getstatus(self):
     status = False
     try:
      output = os.popen(OS.cmdline_rootcorrect('sudo systemctl is-active snapclient'))
      for line in output:
       if line.strip().startswith("active"):
        status = True
     except Exception as e:
      print(e)
     self.uservar[0]=int(status)
     return status
Пример #7
0
def AP_stop(ndi): # index in NetworkDevices array
    ndi = int(ndi)
    if ndi>=len(Settings.NetworkDevices) or ndi<0:
     print("NetworkDevice "+str(ndi)+" not found")
     return False
    if Settings.NetworkDevices[ndi].ip!="192.168.4.1" and Settings.NetworkDevices[ndi].apmode==0:
     return False # not in apmode
    Settings.NetworkDevices[ndi].apmode = 0
    cmdline = 'sudo lib/scripts/ap_stop.sh '+str(Settings.NetworkDevices[ndi].devicename)
#    print(cmdline) # debug
    subprocess.call(shlex.split(OS.cmdline_rootcorrect(cmdline)))
    return True
Пример #8
0
 def stop(self,AddEvent=False):
  if int(self.uservar[0])>0:
    try:
      output = os.popen(OS.cmdline_rootcorrect('sudo systemctl stop snapclient'))
      for line in output:
       pass
    except:
      pass
    if Settings.SoundSystem["inuse"] and Settings.SoundSystem["usingplugintaskindex"] == self.taskindex:
     Settings.SoundSystem["inuse"] = False
     Settings.SoundSystem["usingplugintaskindex"] = -1
     Settings.SoundSystem["askplugintorelease"] = None
    self.getstatus()
    if AddEvent:
     plugin.PluginProto.set_value(self,1,0)
Пример #9
0
def update_apt():
    if len(Settings.UpdateString) > 0:
        if Settings.UpdateString[0] == "!":
            misc.addLog(rpieGlobals.LOG_LEVEL_INFO, "Update in progress")
            return False
    ustr = "Getting fresh apt package list"
    Settings.UpdateString = "!" + ustr
    misc.addLog(rpieGlobals.LOG_LEVEL_INFO, ustr)
    try:
        output = os.popen(OS.cmdline_rootcorrect('sudo apt update'))
        for line in output:
            pass
        misc.addLog(rpieGlobals.LOG_LEVEL_INFO, "apt update list ready")
    except Exception as e:
        ustr = "ATP update failed " + str(e)
        Settings.UpdateString = "=" + ustr
        misc.addLog(rpieGlobals.LOG_LEVEL_ERROR, ustr)

    ustr = "Getting upgradable apt package list"
    Settings.UpdateString = "!" + ustr
    misc.addLog(rpieGlobals.LOG_LEVEL_INFO, ustr)

    htm = "<form method='post' action='/update' enctype='multipart/form-data'>"
    htm += "<center><input type='hidden' name='mode' value='aptupgrade'><input type='submit' value='Upgrade All'><br>Upgradable packages:<p><textarea readonly rows='20' wrap='on'>"
    try:
        output = os.popen(OS.cmdline_rootcorrect('sudo apt list --upgradable'))
        for line in output:
            htm += str(line)
        Settings.UpdateString = htm + "</textarea></center></form>"
        misc.addLog(rpieGlobals.LOG_LEVEL_INFO, "apt upgrade list ready")
        return True
    except Exception as e:
        ustr = "APT update failed " + str(e)
        Settings.UpdateString = "=" + ustr
        misc.addLog(rpieGlobals.LOG_LEVEL_ERROR, ustr)
    return False
Пример #10
0
def set_ir_protocols(protolist):
    protos = []
    if " " in protolist:
        protos = protolist.split(" ")
    elif "," in protolist:
        protos = protolist.split(",")
    elif type(protolist) in (tuple, list):
        protos = protolist
    else:
        protos.append(str(protolist))
    if len(protos) < 1:
        return
    cmdline = OS.cmdline_rootcorrect("sudo ir-keytable")
    for i in range(len(protos)):
        cmdline += " -p " + str(protos[i])
    try:
        output = os.popen(cmdline)
        for line in output:
            pass
    except:
        pass
Пример #11
0
def upgrade_apt():
    if len(Settings.UpdateString) > 0:
        if Settings.UpdateString[0] == "!":
            misc.addLog(rpieGlobals.LOG_LEVEL_INFO, "Update in progress")
            return False
    ustr = "Upgrading APT packages<br>Please do not interrupt!"
    misc.addLog(rpieGlobals.LOG_LEVEL_INFO, ustr)
    ustr += "<p style='font-weight:normal;font-size:12px;text-align:left'>"
    Settings.UpdateString = "!" + ustr
    try:
        output = os.popen(OS.cmdline_rootcorrect('sudo apt upgrade -y'))
        for line in output:
            if len(Settings.UpdateString) > 2000:
                Settings.UpdateString = "!" + ustr
            Settings.UpdateString += line + "<br>"
    except Exception as e:
        ustr = "APT upgrade failed " + str(e)
        Settings.UpdateString = "=" + ustr
        misc.addLog(rpieGlobals.LOG_LEVEL_ERROR, ustr)
        return False
    ustr = "APT upgrade ended"
    Settings.UpdateString = "=" + ustr
    misc.addLog(rpieGlobals.LOG_LEVEL_INFO, ustr)
    return True
Пример #12
0
def update_pip():
    if len(Settings.UpdateString) > 0:
        if Settings.UpdateString[0] == "!":
            misc.addLog(rpieGlobals.LOG_LEVEL_INFO, "Update in progress")
            return False
    ustr = "Getting upgradable pip package list"
    Settings.UpdateString = "!" + ustr
    misc.addLog(rpieGlobals.LOG_LEVEL_INFO, ustr)
    oldpy = False
    htm = ""
    if sys.version_info.major <= 3 and sys.version_info.minor < 5:
        oldpy = True
        htm += "<p><b>WARNING: Latest PIP3 depends on Python 3.5, so either <a href='http://forums.debian.net/viewtopic.php?f=8&t=125904'>install it</a>, or forget pip upgrades!</b><p>"
    htm += "<form method='post' action='/update' enctype='multipart/form-data'>"
    htm += "<center><input type='hidden' name='mode' value='pipupgrade'><input type='submit' value='Upgrade selected'><table>"
    pnum = 0
    oldpip = False
    try:
        output = os.popen(
            OS.cmdline_rootcorrect('sudo -H pip3 list --outdated')
        )  #  --format columns not supported in v19
        for line in output:
            lc = line.split()
            if oldpip == False and len(lc) == 5:
                if 'Current' in line and 'Latest' in line:
                    oldpip = True
            valid = False
            if oldpip:
                if len(lc) == 5:
                    try:
                        if int(lc[2][0]) >= 0:
                            valid = True
                    except:
                        pass
                if lc[0] == "pip" and oldpy:
                    valid = False
                if valid:
                    htm += "<tr><td><input type='checkbox' name='p_" + str(
                        pnum) + "' value='" + lc[0] + "' checked>" + lc[
                            0] + "<td>" + lc[2] + "<td>" + lc[4] + "</tr>"
                    pnum += 1
            else:
                if len(lc) == 4:
                    try:
                        if int(lc[1][0]) >= 0:
                            valid = True
                    except:
                        pass
                if lc[0] == "pip" and oldpy:
                    valid = False
                if valid:
                    htm += "<tr><td><input type='checkbox' name='p_" + str(
                        pnum) + "' value='" + lc[0] + "' checked>" + lc[
                            0] + "<td>" + lc[1] + "<td>" + lc[2] + "<td>" + lc[
                                3] + "</tr>"
                    pnum += 1

        if pnum == 0 and oldpy == False:
            htm += "<tr><td><input type='checkbox' name='p_pip' value='pip' checked>pip<td>Either everything is up to date or outdated parameter failed<td><td></tr>"
        Settings.UpdateString = htm + "</table></center></form>"
        misc.addLog(rpieGlobals.LOG_LEVEL_INFO, "pip upgrade list ready")
        return True
    except Exception as e:
        ustr = "PIP update failed " + str(e)
        Settings.UpdateString = "=" + ustr
        misc.addLog(rpieGlobals.LOG_LEVEL_ERROR, ustr)
    return False
Пример #13
0
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(rpieGlobals.LOG_LEVEL_INFO,
                "CMD: " + cmdline.replace("==", "="))

    if cmdarr[0] == "delay":
        try:
            s = float(cmdarr[1])
        except:
            s = 1000
        s = (s / 1000)
        time.sleep(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 == -1:
            s, v = Settings.getTaskValueIndex(cmdarr[1], cmdarr[2])
        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 == -1:
            s, v = Settings.getTaskValueIndex(cmdarr[1], cmdarr[2])
        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(rpieTime.Timers) < 1:
            return False
        try:
            s = int(cmdarr[1])
        except:
            s = -1
        if s > 0 and (s < len(rpieTime.Timers)):
            s = s - 1  # array is 0 based, timers is 1 based
            rpieTime.Timers[s].pause()
        commandfound = True
        return commandfound

    elif cmdarr[0] == "timerresume":
        if len(rpieTime.Timers) < 1:
            return False
        try:
            s = int(cmdarr[1])
        except:
            s = -1
        if s > 0 and (s < len(rpieTime.Timers)):
            s = s - 1  # array is 0 based, timers is 1 based
            rpieTime.Timers[s].resume()
        commandfound = True
        return commandfound

    elif cmdarr[0] == "timerset":
        if len(rpieTime.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(rpieTime.Timers)):
            s = s - 1  # array is 0 based, timers is 1 based
            if v == 0:
                rpieTime.Timers[s].stop(False)
            else:
                rpieTime.Timers[s].addcallback(TimerCallback)
                rpieTime.Timers[s].start(v)
        commandfound = True
        return commandfound

    elif cmdarr[0] == "event":
        rulesProcessing(cmdarr[1], rpieGlobals.RULE_USER)
        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(rpieGlobals.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(rpieGlobals.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(rpieGlobals.LOG_LEVEL_ERROR,
                            "LORA controller not found!")
        commandfound = True
        return commandfound

    elif cmdarr[0] == "espnowcommand":
        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 "ESPNow" in Settings.Controllers[
                                y].getcontrollername():
                            Settings.Controllers[y].sendcommand(unitno, data)
                            cfound = True
            if cfound == False:
                misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,
                            "ESPNow controller not found!")
        commandfound = True
        return commandfound

    elif cmdarr[0] == "serialcommand":
        data = ""
        if len(cmdarr) > 1:
            sepp = cmdline.find(',')
            data = cmdline[sepp + 1:].replace("==", "=")
        else:
            return False
        cfound = False
        for y in range(len(Settings.Controllers)):
            if (Settings.Controllers[y]):
                if (Settings.Controllers[y].enabled):
                    if "ESPNow" in Settings.Controllers[y].getcontrollername():
                        Settings.Controllers[y].serialcommand(data)
                        cfound = True
        if cfound == False:
            misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,
                        "ESPNow 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)
                                commandfound = True
                                cfound = True
                                break
                        except:
                            cfound = False
            if cfound == False:
                misc.addLog(rpieGlobals.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
            t = threading.Thread(target=urlget, args=(curl, ))
            t.daemon = True
            t.start()
        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 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            for r in range(0, 1):
                s.sendto(bytes(data, "utf-8"), (destaddr, int(destport)))
                if r < 1:
                    time.sleep(0.1)
            commandfound = True
        else:
            commandfound = False
        return commandfound
    elif cmdarr[0] == "wifiapmode":
        if int(Settings.NetMan.WifiDevNum) >= 0:
            apdev = int(Settings.NetMan.WifiDevNum)
        else:
            apdev = Settings.NetMan.getfirstwirelessdevnum()
        Network.AP_start(apdev, True)
        commandfound = True
        return commandfound
    elif cmdarr[0] == "wifistamode":
        if int(Settings.NetMan.WifiDevNum) >= 0:
            apdev = int(Settings.NetMan.WifiDevNum)
        else:
            apdev = Settings.NetMan.getfirstwirelessdevnum()
        Network.AP_stop(apdev)
        Settings.NetMan.APMode = -1
        commandfound = True
        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":
        doCleanup()
        os.popen(OS.cmdline_rootcorrect("sudo reboot"))
        #  os.kill(os.getpid(), signal.SIGINT)
        commandfound = True
        return commandfound
    elif cmdarr[0] == "reset":
        try:
            os.popen("rm -r data/*.json")
        except:
            pass
        Settings.Controllers = [False]
        Settings.NetworkDevices = []
        Settings.Pinout = []
        Settings.Settings = {
            "Name": "RPIEasy",
            "Unit": 0,
            "Password": "",
            "Delay": 60
        }
        Settings.Tasks = [False]
        Settings.NetMan.networkinit()
        commandfound = True
        return commandfound
    elif cmdarr[0] == "halt":
        doCleanup()
        os.popen(OS.cmdline_rootcorrect("sudo shutdown -h now"))
        #  os.kill(os.getpid(), signal.SIGINT)
        commandfound = True
        return commandfound
    elif cmdarr[0] == "update":
        misc.addLog(rpieGlobals.LOG_LEVEL_INFO, "Starting git clone")
        os.popen(
            "cp -rf run.sh run.sh.bak && rm -rf update && git clone https://github.com/enesbcs/rpieasy.git update"
        ).read()
        time.sleep(2)
        if os.path.isdir("update"):
            misc.addLog(rpieGlobals.LOG_LEVEL_INFO,
                        "Download successful, starting to overwrite files")
            os.popen(
                "rm -rf .git && rm -rf update/data update/files && mv -f update/.git .git && cp -rf update/lib/* lib/ && cp -rf update/img/* img/ && rm -rf update/lib update/img && mv -f update/* . && rm -rf update && cp -rf run.sh.bak run.sh"
            ).read()
            time.sleep(0.5)
            os.kill(os.getpid(), signal.SIGINT)
        else:
            misc.addLog(rpieGlobals.LOG_LEVEL_ERROR, "Update failed")
        commandfound = True
        return commandfound
    elif cmdarr[0] == "exit":
        os.kill(os.getpid(), signal.SIGINT)
        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] == "setvolume":
        vmr = 0
        if "+" in cmdarr[1] or "-" in cmdarr[1]:
            vmr = 1
        try:
            vol = int(cmdarr[1])
        except:
            vol = -200
        if (vmr == 0):  # absolute vol
            if (vol >= 0 and vol <= 100):
                try:
                    OS.setvolume(vol)
                    commandfound = True
                except Exception as e:
                    commandfound = str(e)
        else:
            if (vol >= -100 and vol <= 100):  # relative vol
                try:
                    avol = OS.getvolume()
                    OS.setvolume(int(avol) + vol)
                    commandfound = True
                except Exception as e:
                    commandfound = str(e)
        return commandfound

    if commandfound == False:
        commandfound = doExecutePluginCommand(retval)
    if commandfound == False:
        misc.addLog(rpieGlobals.LOG_LEVEL_ERROR, "Unknown command: " + cmdline)
    return commandfound
Пример #14
0
def installdeps2(modulename):
    global modulelist
    Settings.UpdateString = "!Installing " + modulename + " dependencies"
    for i in range(len(modulelist)):
        if modulelist[i][
                "name"] == modulename and modulelist[i]["installed"] != 1:
            modulelist[i]["installed"] = -1
            try:
                if modulelist[i]["apt"]:
                    installprog = " "
                    for j in range(len(modulelist[i]["apt"])):
                        if rpieGlobals.ossubtype == 2:  # arch exceptions
                            if "python3-pip" in modulelist[i]["apt"][j]:
                                modulelist[i]["apt"][j].replace(
                                    "python3-pip", "python-pip")
                        installprog += modulelist[i]["apt"][j] + " "
                    if rpieGlobals.ossubtype in [1, 3, 10]:
                        installprog = OS.cmdline_rootcorrect(
                            "sudo apt-get update && sudo apt-get install -y " +
                            installprog.strip())
                    elif rpieGlobals.ossubtype == 2:
                        installprog = OS.cmdline_rootcorrect(
                            "yes | sudo pacman -S " + installprog.strip())
                    ustr = "apt: " + installprog
                    Settings.UpdateString = "!" + ustr
                    misc.addLog(rpieGlobals.LOG_LEVEL_INFO, ustr)
                    proc = subprocess.Popen(installprog,
                                            shell=True,
                                            stdin=None,
                                            stdout=open(os.devnull, "wb"),
                                            executable="/bin/bash")
                    proc.wait()
            except Exception as e:
                misc.addLog(rpieGlobals.LOG_LEVEL_ERROR, str(e))
            try:
                if modulelist[i]["pip"]:
                    installprog = " "
                    for j in range(len(modulelist[i]["pip"])):
                        installprog += modulelist[i]["pip"][j] + " "
                    installprog = "sudo -H pip3 install " + installprog.strip()
                    if OS.is_command_found(
                            "sudo"
                    ) == False:  # if sudo is installed use it because -H option is important
                        installprog = OS.cmdline_rootcorrect(
                            "sudo -H pip3 install " + installprog.strip())
                    ustr = "pip3: " + installprog
                    Settings.UpdateString = "!" + ustr
                    misc.addLog(rpieGlobals.LOG_LEVEL_INFO, ustr)
                    proc = subprocess.Popen(installprog,
                                            shell=True,
                                            stdin=None,
                                            stdout=open(os.devnull, "wb"),
                                            executable="/bin/bash")
                    proc.wait()
            except Exception as e:
                misc.addLog(rpieGlobals.LOG_LEVEL_ERROR, str(e))
            try:
                if modulelist[i]["installcmd"]:
                    installprog = OS.cmdline_rootcorrect(
                        modulelist[i]["installcmd"].strip())
                    ustr = "exec: " + installprog
                    Settings.UpdateString = "!" + ustr
                    misc.addLog(rpieGlobals.LOG_LEVEL_INFO, ustr)
                    proc = subprocess.Popen(installprog,
                                            shell=True,
                                            stdin=None,
                                            stdout=open(os.devnull, "wb"),
                                            executable="/bin/bash")
                    proc.wait()
            except Exception as e:
                if e != 'installcmd':
                    misc.addLog(rpieGlobals.LOG_LEVEL_ERROR, str(e))
            break
    Settings.UpdateString = "=" + modulename + " dependency install finished<br>"  #<a class='button link wide' href='plugins'>Back to dependencies</a><br>"
    return True