Example #1
0
 def plugin_init(self,enableplugin=None):
  plugin.PluginProto.plugin_init(self,enableplugin)
  self.uservar[0] = 0
  self.timer100ms = False
  self.initialized = False
  self.readinprogress = False
  self.lastread = 0
  if self.enabled:
   try:
    i2cport = gpios.HWPorts.geti2clist()
   except:
    i2cport = []
   if len(i2cport)>0:
     try:
      self.s = RTIMU.Settings("RTIMULib")
      self.mpu = RTIMU.RTIMU(self.s)
      misc.addLog(rpieGlobals.LOG_LEVEL_INFO,"MPU: "+str(self.mpu.IMUName()))
      self.initialized = self.mpu.IMUInit()
     except Exception as e:
      self.mpu = None
   if (self.mpu is None) or self.initialized==False:
    misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"MPU can not be initialized! ")
    return False
   else:
    self.mpu.setSlerpPower(0.02)
    self.mpu.setGyroEnable(True)
    self.mpu.setAccelEnable(True)
    self.mpu.setCompassEnable(True)
    self.interval2 = 0.1
    self.enabled=False
    time.sleep(1)
    self.enabled=True
    if self.interval==0:
      self.timer100ms = True # enable periodic check if interval not specified
      self.interval2 = 0.1
    elif self.interval < 2:
      self.interval2 = 0.5
    elif self.interval < 60:
      self.interval2 = 1
    else:
      self.interval2 = 5
    bgt = threading.Thread(target=self.bgreader)
    bgt.daemon = True
    bgt.start()
Example #2
0
    def connect(self):
        if self.enabled and self.initialized:
            if self._connected:
                misc.addLog(pglobals.LOG_LEVEL_DEBUG,
                            "Already connected force disconnect!")
                self.disconnect()
            self.connectinprogress = 1
            self.lastreconnect = utime.time()
            try:
                am = self.authmode
            except:
                am = 0
            cname = settings.Settings["Name"] + str(utime.time())
            mna = self.controlleruser
            if mna.strip() == "":
                mna = None
            mpw = self.controllerpassword
            if mpw.strip() == "":
                mpw = None
            try:
                self._mqttclient = MQTTClient(cname,
                                              self.controllerip,
                                              port=int(self.controllerport),
                                              user=mna,
                                              password=mpw,
                                              keepalive=self.keepalive,
                                              ssl=(am != 0))
                self._mqttclient.set_callback(self.on_message)
                self._mqttclient.connect()
                self._connected = self.isconnected()
                self._mqttclient.subscribe(self._outch.encode())
#    self.laststatus = 1
#    commands.rulesProcessing("DomoMQTT#Connected",pglobals.RULE_SYSTEM)
            except Exception as e:
                misc.addLog(
                    pglobals.LOG_LEVEL_ERROR,
                    "MQTT controller: " + self.controllerip + ":" +
                    str(self.controllerport) + " connection failed " + str(e))
                self._connected = False
                self.laststatus = 0
        else:
            self._connected = False
            self.laststatus = 0
        return self._connected
Example #3
0
def initprogram():
    global timer100ms, timer20ms, timer1s, timer2s, timer30s, init_ok

    try:
        os.chdir(os.path.dirname(os.path.realpath(__file__)))
    except:
        pass
    #print("Loading settings")
    Settings.loadsettings()
    hardwareInit()
    PluginInit()
    CPluginInit()
    NPluginInit()
    RulesInit()
    timer100ms = millis()
    timer20ms = timer100ms
    timer1s = timer100ms
    timer2s = timer100ms
    timer30s = timer100ms
    init_ok = True
    t = threading.Thread(
        target=mainloop)  # starting sensors and background functions
    t.daemon = True
    t.start()
    ports = [80, 8080, 8008]  # check for usable ports
    up = 0
    for p in ports:
        up = p
        try:
            serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            serversocket.bind((socket.gethostname(), up))
            serversocket.close()
        except:
            up = 0
        if up > 0:
            break
    if up == 0:
        misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,
                    "Webserver can not be started, no available port found!")
    else:
        misc.addLog(rpieGlobals.LOG_LEVEL_INFO,
                    "Webserver starting at port " + str(up))
        Settings.WebUIPort = up
        webserver.WebServer.start('', up)  # starts webserver GUI
Example #4
0
 def plugin_init(self,enableplugin=None):
  global realanalog,rpiok
  plugin.PluginProto.plugin_init(self,enableplugin)
  self.decimals[0]=0
  self.initialized=False
  if realanalog:
    try:
     self.adc = virtADC(int(self.taskdevicepluginconfig[1]))
     self.initialized = True
    except Exception as e:
     misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"Analog init error: "+str(e))
  elif rpiok:
   try:
    if str(self.taskdevicepluginconfig[1])=="" or str(self.taskdevicepluginconfig[1])=="0":
     self.taskdevicepluginconfig[1]=0.33
   except:
     self.taskdevicepluginconfig[1]=0.33
   try:
    if str(self.taskdevicepluginconfig[2])=="" or str(self.taskdevicepluginconfig[2])=="0":
     self.taskdevicepluginconfig[2]=10000
   except:
     self.taskdevicepluginconfig[2]=10000
   try:
    if str(self.taskdevicepluginconfig[3])=="" or str(self.taskdevicepluginconfig[3])=="0":
     self.taskdevicepluginconfig[3]=1.35
   except:
     self.taskdevicepluginconfig[3]=1.35
   try:
    if str(self.taskdevicepluginconfig[4])=="" or str(self.taskdevicepluginconfig[4])=="0":
     self.taskdevicepluginconfig[4]=1000
   except:
     self.taskdevicepluginconfig[4]=1000
   try:
    if str(self.taskdevicepluginconfig[5])=="" or str(self.taskdevicepluginconfig[5])=="0":
     self.taskdevicepluginconfig[5]=3800
   except:
     self.taskdevicepluginconfig[5]=3800
   if self.enabled and self.taskdevicepin[0]>=0 and self.taskdevicepin[1]>=0:
    self.readinprogress = False
    try:
     self.adc = Analog.PiAnalog(gpioinit=False,a_pin=self.taskdevicepin[0],b_pin=self.taskdevicepin[1],C=self.taskdevicepluginconfig[1],R1=self.taskdevicepluginconfig[2],Vt=self.taskdevicepluginconfig[3])
     self.initialized = True
    except Exception as e:
     misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"PiAnalog init error: "+str(e))
Example #5
0
 def plugin_init(self, enableplugin=None):
     plugin.PluginProto.plugin_init(self, enableplugin)
     self.decimals[0] = -1
     self.initialized = False
     time.sleep(1)
     if self.enabled:
         self.i2cport = -1
         try:
             for i in range(0, 2):
                 if gpios.HWPorts.is_i2c_usable(
                         i) and gpios.HWPorts.is_i2c_enabled(i):
                     self.i2cport = i
                     break
         except:
             self.i2cport = -1
         if self.i2cport > -1:
             self.preset = str(self.taskdevicepin[0]).strip()
             if self.preset == "" or self.preset == "-1":
                 self.preset = None
             else:
                 try:
                     self.preset = int(reset)
                 except:
                     self.preset = None
             self.ver = ""
             try:
                 self.pn = pn532.PN532_I2C(reset=self.preset,
                                           i2c_c=self.i2cport)
                 ic, ver, rev, supp = self.pn.get_firmware_version(
                 )  # get fw version
                 self.ver = str(ver) + "." + str(rev)
                 self.pn.SAM_configuration()  # set mifare type
                 misc.addLog(rpieGlobals.LOG_LEVEL_INFO,
                             "PN532 v" + str(self.ver) + " initialized")
                 self.initialized = True
             except Exception as e:
                 self.initialized = False
                 misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,
                             "PN532 init error:" + str(e))
             self.processing = False
             if self.initialized:
                 bgt = threading.Thread(target=self.bgreader)
                 bgt.daemon = True
                 bgt.start()
Example #6
0
 def sync(self):
     if self.enabled:
         if self.taskdevicepin[0] >= 0:
             v1 = 0
             cs = gpios.GPIO_get_statusid(self.taskdevicepin[0])
             try:
                 if cs > -1:
                     if gpios.GPIOStatus[cs]["mode"] == "pwm":
                         v1 = int(gpios.GPIOStatus[cs]["state"])
             except:
                 pass
             if self.taskdevicepluginconfig[0] == True:
                 ot = False
                 for p in range(len(Settings.Pinout)):
                     if str(Settings.Pinout[p]["BCM"]) == str(
                             self.taskdevicepin[0]):
                         if Settings.Pinout[p]["startupstate"] in [
                                 4, 5, 6, 7
                         ]:
                             ot = True
                             break
                 if ot == False:
                     misc.addLog(
                         rpieGlobals.LOG_LEVEL_ERROR,
                         "Pin is not an Output, State preserving disabled")
                     self.taskdevicepluginconfig[0] = False
             if v1 != self.uservar[0]:
                 if self.taskdevicepluginconfig[0] == True:
                     self.set_value(
                         1, int(self.uservar[0]),
                         True)  # restore previous state from uservar
                     misc.addLog(
                         rpieGlobals.LOG_LEVEL_INFO,
                         self.taskname + ": Restoring previous PWM value " +
                         str(self.uservar[0]))
                 else:
                     self.uservar[
                         0] = v1  # store actual pin state into uservar
                     if self.taskdevicepluginconfig[1]:
                         self.plugin_senddata()
                     misc.addLog(
                         rpieGlobals.LOG_LEVEL_INFO, self.taskname +
                         ": Syncing actual PWM value " + str(v1))
             elif self.taskdevicepluginconfig[1]:
                 self.plugin_senddata()
             self.initialized = True
         if self.initialized:
             if self.taskdevicepluginconfig[0] == True:
                 sps = "en"
             else:
                 sps = "dis"
             misc.addLog(rpieGlobals.LOG_LEVEL_INFO,
                         "State preserving is " + sps + "abled")
Example #7
0
 def webform_save(self,params): # process settings post reply
  paddr = self.taskdevicepluginconfig[1]
  ninit = False
  par = webserver.arg("p206_saddr",params)
  try:
   self.taskdevicepluginconfig[1] = int(par)
  except:
   self.taskdevicepluginconfig[1] = 1
  try:
   if int(paddr) != int(self.taskdevicepluginconfig[1]):
    ninit = True
  except:
   ninit = True
  try:
   self.taskdevicepluginconfig[6] = int(webserver.arg("plugin_206_slow",params))
  except:
   self.taskdevicepluginconfig[6] = 0
  try:
   self.taskdevicepluginconfig[0] = self.stripstring(webserver.arg("p206_addr",params))
   for v in range(0,4):
    par = webserver.arg("plugin_206_ind"+str(v),params)
    if par == "":
     par = -1
    else:
     par=int(par)
    if str(self.taskdevicepluginconfig[v+2])!=str(par):
     self.uservar[v] = 0
    self.taskdevicepluginconfig[v+2] = par
    if int(par)>0 and self.valuecount!=v+1:
     self.valuecount = (v+1)
   if self.valuecount == 1:
    self.vtype = rpieGlobals.SENSOR_TYPE_SINGLE
   elif self.valuecount == 2:
    self.vtype = rpieGlobals.SENSOR_TYPE_DUAL
   elif self.valuecount == 3:
    self.vtype = rpieGlobals.SENSOR_TYPE_TRIPLE
   elif self.valuecount == 4:
    self.vtype = rpieGlobals.SENSOR_TYPE_QUAD
  except Exception as e:
   misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,+str(e))
  if ninit:
   self.plugin_init()
  return True
Example #8
0
 def lorasend(self, payload):
     if self.tx_active:
         return False
     self.tx_start = millis()
     if self.tx_start < self.nexttransmit:
         misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG,
                     "Next possible transmit " + str(self.nexttransmit))
         return False
     self.tx_active = True
     try:
         self.write_payload(list(payload))
         self.set_dio_mapping([1, 0, 0, 0, 0, 0])
     except:
         self.tx_active = False
         return False
     self.tx_start = millis()
     self.set_mode(MODE.TX)
     #       print("Sending ",payload) #DEBUG
     return True
Example #9
0
def parseruleline(linestr,rulenum=-1):
 global GlobalRules
 cline = linestr.strip()
 state = "CMD"
 if "[" in linestr:
  m = re.findall(r"\[([A-Za-z0-9_#]+)\]", linestr)
  if len(m)>0: # replace with values
   for r in range(len(m)):
    tval = str(gettaskvaluefromname(m[r]))
    if tval=="None":
     state = "INV"
    cline = cline.replace("["+m[r]+"]",tval)
 if ("%eventvalue%" in linestr) and (rulenum!=-1):
  cline = cline.replace("%eventvalue%",GlobalRules[rulenum]["evalue"])
 if "%" in cline:
  m = re.findall(r"\%([A-Za-z0-9_#]+)\%", cline)
  if len(m)>0: # replace with values
   for r in range(len(m)):
    if m[r] in SysVars:
     cline = cline.replace("%"+m[r]+"%",str(getglobalvar(m[r])))
 cline = parseconversions(cline)
 equ = getfirstequpos(cline)
 if equ!=-1:
  if cline[:3].lower() == "if ":
   if "=" in getequchars(cline,True):
    cline = cline.replace("=","==") # prep for python interpreter
    cline = cline.replace("!==","!=") # revert invalid operators
    cline = cline.replace(">==",">=")
    cline = cline.replace("<==","<=")
   tline = cline
   state = "IFST"
   try:
    cline = eval(cline[3:])
   except:
    cline = False                 # error checking?
   misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG,"Parsed condition: "+str(tline)+" "+str(cline))
 elif "endif" in cline:
  cline = True
  state = "IFEN"
 elif "else" in cline:
  cline = False
  state = "IFEL"
 return cline,state
Example #10
0
 def plugin_read(
         self):  # deal with data processing at specified time interval
     result = False
     if self.enabled and self.initialized and self.readinprogress == 0:
         self.readinprogress = 1
         try:
             val1, val2, val3 = self.p049_read()
         except Exception as e:
             val1 = None
             misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG, "MH-Z19: " + str(e))
         if val1 is not None:
             self.set_value(1, val1, False)
             self.set_value(2, val2, False)
             self.set_value(3, val3, False)
             self.plugin_senddata()
             self._lastdataservetime = rpieTime.millis()
         result = True
         self.readinprogress = 0
     return result
Example #11
0
def CPluginInit():
 tarr = []
 filenames = glob.glob('_C*.py')
 filenames.sort()
 for fname in filenames:
  tarr = [0,0,0]
  tarr[0] = fname
  with open(fname,"r",encoding="utf8") as fcont:
   for line in fcont:
    if "CONTROLLER_ID" in line:
     tarr[1] = line[line.find("=")+1:].strip().replace('"',"")
    if "CONTROLLER_NAME" in line:
     tarr[2] = line[line.find("=")+1:].strip().replace('"',"")
     break
  tarr[0] = tarr[0].replace(".py","")
  rpieGlobals.controllerselector.append(tarr) # create list for form select

 print("Load controllers from file")
 Settings.loadcontrollers()
 for x in range(0,len(Settings.Tasks)):
  try:
   if (Settings.Tasks[x]) and type(Settings.Tasks[x]) is not bool: # device exists
    if (Settings.Tasks[x].enabled): # device enabled
     Settings.Tasks[x].plugin_init(None) # init plugin at startup
     for y in range(len(Settings.Tasks[x].senddataenabled)):
       if (Settings.Tasks[x].senddataenabled[y]):
        if (Settings.Controllers[y]):
         if (Settings.Controllers[y].enabled):
          Settings.Tasks[x].controllercb[y] = Settings.Controllers[y].senddata # assign controller callback to plugins that sends data
  except Exception as e:
    Settings.Tasks[x].enabled = False
    misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"Task " +str(x+1)+ " disabled! "+str(e))

 for y in range(0,len(Settings.Controllers)):
   if (Settings.Controllers[y]):
    try:
     if (Settings.Controllers[y].enabled): 
       Settings.Controllers[y].controller_init(None) # init controller at startup
       Settings.Controllers[y].setonmsgcallback(Settings.callback_from_controllers) # set global msg callback for 2way comm
    except Exception as e:
       Settings.Controllers[y].enabled = False
       misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"Controller " +str(y+1)+ " disabled! "+str(e))
 return 0
Example #12
0
 def plugin_read(
         self):  # deal with data processing at specified time interval
     result = False
     if self.initialized and self.readinprogress == 0 and self.enabled:
         self.readinprogress = 1
         try:
             temp = self.htu.read_temperature()
             hum = self.htu.read_humidity()
             self.set_value(1, temp, False)
             self.set_value(2, hum, False)
         except Exception as e:
             misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,
                         "HTU21 read error! " + str(e))
             self.enabled = False
         self.plugin_senddata()
         self._lastdataservetime = rpieTime.millis()
         result = True
         self.readinprogress = 0
     return result
Example #13
0
 def plugin_read(
         self):  # deal with data processing at specified time interval
     result = False
     if self.enabled and self.initialized and self.readinprogress == 0:
         self.readinprogress = 1
         try:
             temp, hum = self.read_sht30()
         except Exception as e:
             temp = None
             hum = None
             misc.addLog(rpieGlobals.LOG_LEVEL_ERROR, "SHT30: " + str(e))
         if temp is not None:
             self.set_value(1, temp, False)
             self.set_value(2, hum, False)
             self.plugin_senddata()
             self._lastdataservetime = rpieTime.millis()
         result = True
         self.readinprogress = 0
     return result
Example #14
0
 def plugin_read(
         self):  # deal with data processing at specified time interval
     result = False
     if self.initialized and self.readinprogress == 0 and self.enabled:
         self.readinprogress = 1
         try:
             succ, temp = self.read_temperature()
             if succ:
                 self.set_value(1, temp, True)
             else:
                 misc.addLog(pglobals.LOG_LEVEL_ERROR, "Dallas read error!")
         except Exception as e:
             misc.addLog(pglobals.LOG_LEVEL_ERROR,
                         "Dallas read error! " + str(e))
             self.enabled = False
         self._lastdataservetime = utime.ticks_ms()
         result = True
         self.readinprogress = 0
     return result
Example #15
0
 def connect(self):
  self.connected = False
  self.sysinfosent = 0
  try:
   if self.lora is not None:
    self.lora.set_mode(MODE.STDBY)
    self.lora.set_pa_config(pa_select=1, max_power=21, output_power=15)
    self.lora.set_spreading_factor(self.sf)
    self.lora.set_bw(self.bw)
    self.lora.set_coding_rate(self.coding)
    self.lora.set_rx_crc(True)
    self.lora.set_freq(self.freq)
    self.lora.set_sync_word(self.sync) # default setting of 0x12 and a LoRaWAN setting of 0x34
    assert(self.lora.get_agc_auto_on() == 1)
    self.lora.loraduty = self.duty
    self.lora.start()
    self.connected = True
  except Exception as e:
    misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"LORA Direct connect error: "+str(e))
Example #16
0
 def rfconnect(self):
     if int(self.taskdevicepin[0]) >= 0 and self.enabled:
         try:
             self.rfdevice = getRFDev(True)
             pval = self.rfdevice.initpin()
             if self.rfdevice and int(pval) > 0:
                 self.initialized = True
                 self.rfdevice.setReceiveTolerance(
                     int(self.taskdevicepluginconfig[0]))
                 self.rfdevice.enableReceive(int(self.taskdevicepin[0]))
                 self.timer100ms = True
         except Exception as e:
             misc.addLog(rpieGlobals.LOG_LEVEL_ERROR, "RF433: " + str(e))
             self.initialized = False
             self.timer100ms = False
     else:
         #      print("Not yet initialized")
         self.initialized = False
         self.timer100ms = False
Example #17
0
 def plugin_init(self,enableplugin=None):
  plugin.PluginProto.plugin_init(self,enableplugin)
  self.uservar[0] = 0
  if self.enabled:
   try:
    i2cok = gpios.HWPorts.i2c_init()
    if i2cok:
     if self.interval>2:
      nextr = self.interval-2
     else:
      nextr = self.interval
     self._lastdataservetime = rpieTime.millis()-(nextr*1000)
     self.lastread = 0
    else:
     misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"I2C can not be initialized!")
     self.enabled = False
   except Exception as e:
    misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,str(e))
    self.enabled = False
Example #18
0
 def plugin_init(self, enableplugin=None):
     plugin.PluginProto.plugin_init(self, enableplugin)
     self.decimals[0] = 0
     self.initialized = False
     self.timer100ms = False
     if int(self.taskdevicepin[0]) >= 0 and self.enabled:
         try:
             self._pin = TouchPad(Pin(int(self.taskdevicepin[0])))
             self.refvalue = int(
                 self._pin.read() / 2
             )  # get value at startup, hope that it is in non-touched state, for reference
             self._pin.config(200)
             self.timer100ms = True
             self.initialized = True
             misc.addLog(pglobals.LOG_LEVEL_DEBUG,
                         "Touch init, ref: " + str(self.refvalue))
         except Exception as e:
             misc.addLog(pglobals.LOG_LEVEL_ERROR,
                         "Touch config failed " + str(e))
Example #19
0
 def plugin_init(self, enableplugin=None):
     plugin.PluginProto.plugin_init(self, enableplugin)
     self.initialized = False
     if self.enabled:
         try:
             i2cl = self.i2c
         except:
             i2cl = -1
         try:
             i2cport = gpios.HWPorts.geti2clist()
             if i2cl == -1:
                 i2cl = int(i2cport[0])
         except:
             i2cport = []
         if len(i2cport) > 0 and i2cl > -1:
             if self.interval > 2:
                 nextr = self.interval - 2
             else:
                 nextr = self.interval
             self._lastdataservetime = rpieTime.millis() - (nextr * 1000)
             self.lastread = 0
             try:
                 shunt = 0.1
                 amps = int(self.taskdevicepluginconfig[1])
                 if amps < 1:
                     amps = None
                 vrange = int(self.taskdevicepluginconfig[2])
                 if vrange not in [0, 1]:
                     vrange = 1
                 if int(self.taskdevicepluginconfig[0]) > 0x39:
                     self.ina = INA219(shunt,
                                       busnum=i2cl,
                                       address=int(
                                           self.taskdevicepluginconfig[0]),
                                       max_expected_amps=amps)
                     self.ina.configure(voltage_range=vrange)
                     self.initialized = True
             except Exception as e:
                 misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,
                             "INA219 can not be initialized: " + str(e))
                 self.ina = None
                 self.initialized = False
Example #20
0
 def senddata(self, idx, taskobj, changedvalue=-1):
     if self.enabled:
         if int(idx) != 0:
             if int(taskobj.vtype) == pglobals.SENSOR_TYPE_SWITCH:
                 url = "/json.htm?type=command&param=switchlight&idx="
                 url += str(idx)
                 url += "&switchcmd="
                 if round(float(taskobj.uservar[0])) == 0:
                     url += "Off"
                 else:
                     url += "On"
             elif int(taskobj.vtype) == pglobals.SENSOR_TYPE_DIMMER:
                 url = "/json.htm?type=command&param=switchlight&idx="
                 url += str(idx)
                 url += "&switchcmd="
                 if float(taskobj.uservar[0]) == 0:
                     url += "Off"
                 else:
                     url += "Set%20Level&level="
                     url += str(taskobj.uservar[0])
             else:
                 url = "/json.htm?type=command&param=udevice&idx="
                 url += str(idx)
                 url += "&nvalue=0&svalue="
                 url += formatDomoticzSensorType(taskobj.vtype,
                                                 taskobj.uservar)
             url += "&rssi="
             url += mapRSSItoDomoticz(taskobj.rssi)
             if taskobj.battery != -1 and taskobj.battery != 255:  # battery input 0..100%, 255 means not supported
                 url += "&battery="
                 url += str(int(taskobj.battery))
             else:
                 bval = misc.get_battery_value()
                 url += "&battery="
                 url += str(int(bval))
             urlstr = self.controllerip + ":" + self.controllerport + url + self.getaccountstr(
             )
             misc.addLog(pglobals.LOG_LEVEL_DEBUG, urlstr)  # sendviahttp
             self.urlget(urlstr)
         else:
             misc.addLog(pglobals.LOG_LEVEL_ERROR,
                         "MQTT : IDX cannot be zero!")
Example #21
0
def doCleanup():
  rulesProcessing("System#Shutdown",rpieGlobals.RULE_SYSTEM)
  try:
   if (len(Settings.Tasks)>1) or ( (len(Settings.Tasks)==1) and (Settings.Tasks[0] != False) ):
    Settings.savetasks()
  except Exception as e:
    misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"Shutdown error: "+str(e))
  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
      t = threading.Thread(target=Settings.Tasks[x].plugin_exit)
      t.daemon = True
      procarr.append(t)
      t.start()
    except:
     pass
  if len(procarr)>0:
   for process in procarr:
     process.join(1)
  try:
   for t in range(0,rpieGlobals.RULES_TIMER_MAX):
    rpieTime.Timers[t].pause()
   for t in range(0,rpieGlobals.SYSTEM_TIMER_MAX):
    rpieTime.SysTimers[t].pause()
  except:
   pass
  procarr = []
  for y in range(0,len(Settings.Controllers)):
   if (Settings.Controllers[y]):
    if (Settings.Controllers[y].enabled):
      t = threading.Thread(target=Settings.Controllers[y].controller_exit)
      t.daemon = True
      procarr.append(t)
      t.start()
  if int(Settings.NetMan.WifiDevNum)>=0 and int(Settings.NetMan.APMode>-1):
    apdev = int(Settings.NetMan.WifiDevNum)
    Network.AP_stop(apdev) # try to stop AP mode if needed
  if len(procarr)>0:
   for process in procarr:
     process.join()
Example #22
0
def formatDomoticzSensorType(sensortype, valuearr):
    valuestr = ""
    if (sensortype
            == pglobals.SENSOR_TYPE_SINGLE) or (sensortype
                                                == pglobals.SENSOR_TYPE_TEXT):
        valuestr += str(valuearr[0]).strip()
    elif (sensortype == pglobals.SENSOR_TYPE_LONG):
        valuearr[0] = float(valuearr[0])
        valuearr[1] = float(valuearr[1])
        valuestr += str(valuearr[0] + (valuearr[1] << 16)).strip()
    elif (sensortype == pglobals.SENSOR_TYPE_DUAL):
        valuestr += str(valuearr[0]).strip() + ";" + str(valuearr[1]).strip()
    elif (sensortype == pglobals.SENSOR_TYPE_TEMP_HUM):
        valuestr += str(valuearr[0]).strip() + ";" + str(
            valuearr[1]).strip() + ";" + humStatDomoticz(valuearr[1])
    elif (sensortype == pglobals.SENSOR_TYPE_TEMP_HUM_BARO):
        valuestr += str(valuearr[0]).strip() + ";" + str(
            valuearr[1]).strip() + ";" + humStatDomoticz(valuearr[1])
        valuestr += ";" + str(valuearr[2]).strip() + ";0"
    elif (sensortype == pglobals.SENSOR_TYPE_TEMP_BARO):
        valuestr += str(valuearr[0]).strip() + ";" + str(valuearr[1]).strip()
        valuestr += ";0;0"
    elif (sensortype == pglobals.SENSOR_TYPE_TEMP_EMPTY_BARO):
        valuestr += str(valuearr[0]).strip() + ";" + str(valuearr[2]).strip()
        valuestr += ";0;0"
    elif (sensortype == pglobals.SENSOR_TYPE_TRIPLE):
        valuestr += str(valuearr[0]).strip() + ";" + str(valuearr[1]).strip()
        valuestr += ";" + str(valuearr[2]).strip()
    elif (sensortype == pglobals.SENSOR_TYPE_QUAD):
        valuestr += str(valuearr[0]).strip() + ";" + str(valuearr[1]).strip()
        valuestr += ";" + str(valuearr[2]).strip() + ";" + str(
            valuearr[3]).strip()
    elif (sensortype
          == pglobals.SENSOR_TYPE_SWITCH) or (sensortype
                                              == pglobals.SENSOR_TYPE_DIMMER):
        pass  # Too specific for HTTP/MQTT
    else:
        misc.addLog(
            pglobals.LOG_LEVEL_ERROR,
            "Domoticz Controller: Not yet implemented sensor type: " +
            sensortype)
    return valuestr
Example #23
0
    def plugin_init(self, enableplugin=None):
        initok = False
        self.readinprogress = False
        if self.enabled:
            if self.taskdevicepin[0] >= 0:
                try:
                    gpios.HWPorts.add_event_detect(self.taskdevicepin[0],
                                                   gpios.FALLING,
                                                   self.p064_handler, 200)
                    self.timer100ms = False
                except Exception as e:
                    if str(self.taskdevicepluginconfig[0]) == "0":
                        self.timer100ms = True
                    misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,
                                "Interrupt error " + str(e))
            else:
                if str(self.taskdevicepluginconfig[0]) == "0":
                    self.timer100ms = True

            try:
                i2cok = gpios.HWPorts.i2c_init()
                if i2cok:
                    if self.interval > 2:
                        nextr = self.interval - 2
                    else:
                        nextr = self.interval
                    self.apds = APDS9960(gpios.HWPorts.i2cbus)
                    self._lastdataservetime = rpieTime.millis() - (nextr *
                                                                   1000)
                    self.lastread = 0
                    initok = True
                else:
                    self.enabled = False
                    misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,
                                "I2C can not be initialized!")
            except Exception as e:
                self.enabled = False
                misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,
                            "APDS init error " + str(e))
        if initok:
            try:
                self.apds.setProximityIntLowThreshold(50)
                if str(self.taskdevicepluginconfig[0]) == "1":
                    self.apds.enableProximitySensor()
                    self.apds.enableLightSensor()
                else:
                    self.apds.enableGestureSensor()
            except Exception as e:
                misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,
                            "APDS setup error " + str(e))
            plugin.PluginProto.plugin_init(self, enableplugin)
        self.initialized = initok
Example #24
0
 def senddata(self,
              idx,
              sensortype,
              value,
              userssi=-1,
              usebattery=-1,
              tasknum=-1,
              changedvalue=-1):  # called by plugin
     if tasknum != -1 and self.enabled:
         if tasknum < len(Settings.Tasks):
             if Settings.Tasks[tasknum] != False:
                 hn = str(
                     urllib.parse.quote(
                         str(Settings.Tasks[tasknum].gettaskname())))
                 templatestra = self.templatestr.replace('%tskname%', hn)
                 templatestra = templatestra.replace(
                     '%id%', str(tasknum + 1))
                 procarr = []
                 for u in range(Settings.Tasks[tasknum].valuecount):
                     vn = str(Settings.Tasks[tasknum].valuenames[u]).strip()
                     if vn != "":
                         vn = str(urllib.parse.quote(vn))
                         templatestr = templatestra.replace('%valname%', vn)
                         val = str(
                             urllib.parse.quote(
                                 str(Settings.Tasks[tasknum].uservar[u])))
                         templatestr = templatestr.replace('%value%', val)
                         urlstr = "http://" + str(
                             self.controllerip) + ":" + str(
                                 self.controllerport) + "/" + templatestr
                         misc.addLog(rpieGlobals.LOG_LEVEL_DEBUG,
                                     urlstr)  # sendviahttp
                         t = threading.Thread(
                             target=self.urlget,
                             args=(urlstr,
                                   ))  # use threading to avoid blocking
                         t.daemon = True
                         procarr.append(t)
                         t.start()
                 if len(procarr) > 0:
                     for process in procarr:
                         process.join()
Example #25
0
 def notify(self,pmsg=""):
  if self.initialized==False or self.enabled==False:
   return False
  if pmsg=="":
   message = self.msgparse(self.body)
  else:
   message = self.msgparse(pmsg)
  if self.server=="0.0.0.0" or self.server=="":
   return False
  jdata = {}
  jdata['chat_id'] = self.chatid
  jdata['parse_mode'] = 'HTML'
  jdata['text'] = message
  jdata = urllib.parse.urlencode(jdata).encode("utf-8")
  urlstr = "https://"+str(self.server)+":"+str(self.port)+"/bot"+str(self.passw)+"/sendMessage"
  misc.addLog(rpieGlobals.LOG_LEVEL_INFO,"Sending telegram notification")
  httpproc = threading.Thread(target=self.urlpost, args=(urlstr,jdata,))  # use threading to avoid blocking
  httpproc.daemon = True
  httpproc.start()
  return True
Example #26
0
 def plugin_read(
         self):  # deal with data processing at specified time interval
     result = False
     if self.enabled and self.initialized and self.readinprogress == 0:
         self.readinprogress = 1
         try:
             raw = self.VEML6070_readraw()
         except Exception as e:
             raw = None
             misc.addLog(rpieGlobals.LOG_LEVEL_ERROR, "VEML6070: " + str(e))
         if raw is not None:
             self.set_value(1, raw, False)
             risk = self.VEML6070_uvrisklevel(raw)
             self.set_value(2, risk, False)
             self.set_value(3, self.VEML6070_uvpower(risk), False)
             self.plugin_senddata()
         self._lastdataservetime = rpieTime.millis()
         result = True
         self.readinprogress = 0
     return result
Example #27
0
 def plugin_init(self, enableplugin=None):
     self.decimals[0] = 0
     try:
         if (enableplugin == True and self.enabled == False) or (len(
                 vusb.usbrelay.getcompatibledevlist()) < 1):
             vusb.vusb_force_refresh()
     except:
         pass
     plugin.PluginProto.plugin_init(self, enableplugin)
     success = False
     try:
         success = self.plugin_read()
     except Exception as e:
         success = False
     if success == False:
         self.initialized = False
         misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,
                     "Unable to init USB relay!")
         #   self.enabled = False
         self.set_value(1, 0, True)
Example #28
0
 def plugin_init(self, enableplugin=None):
     plugin.PluginProto.plugin_init(self, enableplugin)
     if self.enabled:
         try:
             try:
                 i2cl = self.i2c
             except:
                 i2cl = -1
             self.bus = gpios.HWPorts.i2c_init(i2cl)
             if i2cl == -1:
                 self.bus = gpios.HWPorts.i2cbus
             if self.bus is not None:
                 self.initialized = True
             else:
                 misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,
                             "I2C can not be initialized!")
                 self.initialized = False
         except Exception as e:
             misc.addLog(rpieGlobals.LOG_LEVEL_ERROR, str(e))
             self.initialized = False
Example #29
0
 def p515_get_value(self, ptype):
     value = 0
     try:
         if ptype == 1:
             value = self.flora.get_temperature()
         elif ptype == 2:
             value = self.flora.get_light()
         elif ptype == 3:
             value = self.flora.get_moisture()
         elif ptype == 4:
             value = self.flora.get_conductivity()
         elif ptype == 5:
             value = self.flora.battery_level()
     except Exception as e:
         self.failures += 1
         misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,
                     "MiFlora error: " + str(e))
         if self.failures > 5:
             self.enabled = False
     return value
Example #30
0
 def setstate(self, devid, state):
     for name, stype in self.devices.items():
         if "_" + str(devid) + "." in name:
             i = self.zeroconf.get_service_info(stype, name)
             data = {}
             url = "http://" + parseAddress(i.address) + ":" + str(
                 i.port) + "/zeroconf/switch"  # create url for switching
             data["sequence"] = str(int(time.time()))
             data["deviceid"] = str(devid)
             if int(state) == 1:  # construct json dataset
                 data["data"] = {"switch": "on"}
             else:
                 data["data"] = {"switch": "off"}
             if self.sendwithecho == False:
                 self.status[name] = int(state)
                 misc.addLog(
                     1, "Sending POST command " + str(state) + " to " +
                     str(devid))
             self.send_data(send_url=url, send_data=data)
             break