Beispiel #1
0
def ZigateConf(channel, discover):

    ################### ZiGate - get Firmware version #############
    # answer is expected on message 8010
    sendZigateCmd("0010", "")

    ################### ZiGate - set channel ##################
    sendZigateCmd("0021",
                  "0000" + z_tools.returnlen(2,
                                             hex(int(channel))[2:4]) + "00")

    ################### ZiGate - Set Type COORDINATOR #################
    sendZigateCmd("0023", "00")

    ################### ZiGate - start network ##################
    sendZigateCmd("0024", "")

    ################### ZiGate - Request Device List #############
    # answer is expected on message 8015. Only available since firmware 03.0b
    #	if str(z_var.FirmwareVersion) == "030d" or str(z_var.FirmwareVersion) == "030c" or str(z_var.FirmwareVersion) == "030b" :
    Domoticz.Log("ZigateConf -  Request : Get List of Device " +
                 str(z_var.FirmwareVersion))
    sendZigateCmd("0015", "")
    #	else :
    #		Domoticz.Error("Cannot request Get List of Device due to low firmware level" + str(z_var.FirmwareVersion) )

    ################### ZiGate - discover mode 255 sec Max ##################
    #### Set discover mode only if requested - so != 0                  #####
    if str(discover) != "0":
        if str(discover) == "255":
            Domoticz.Status("Zigate enter in discover mode for ever")
        else:
            Domoticz.Status("Zigate enter in discover mode for " +
                            str(discover) + " Secs")
        sendZigateCmd("0049", "FFFC" + hex(int(discover))[2:4] + "00")
Beispiel #2
0
 def new_connection_status(self, new_status):
     try:
         global _plugin
         # new_status.status will be one of the CONNECTION_STATUS_ constants defined in the
         # socket_client module.
         if new_status.status == "CONNECTED":
             Domoticz.Status("Succesfully connected to '" + self.name + "'")
             self.cast.set_volume(0.5)
             Domoticz.Status("Volume is '" +
                             str(self.cast.status.volume_level) + "'")
             _plugin.ConnectedChromecasts[self.name][3] = new_status.status
         elif new_status.status == 'CONNECTING':
             if self.counter == 0:
                 Domoticz.Log("Trying to connect to '" + self.name + "'")
         elif new_status.status == 'FAILED':
             if self.counter == 0:
                 Domoticz.Log("Failed to connect to '" + self.name + "'")
             elif self.counter == 10:
                 self.cast.disconnect()
                 Domoticz.Status(
                     "Disconnecting '" + self.name +
                     "' as reconnecting did not succeed for 10 times.")
                 self.counter = -1
             self.counter += 1
         elif new_status.status == 'LOST':
             Domoticz.Error("Connection with '" + self.name + "'' is lost.")
             _plugin.ConnectedChromecasts[self.name][3] = new_status.status
         else:
             Domoticz.Error("Status of '" + self.name +
                            "'' is changed to " + str(new_status))
     except Exception as e:
         senderror(e)
Beispiel #3
0
 def onSecurityEvent(self, Unit, Level, Description):
     Domoticz.Status("onSecurityEvent called for Level " + str(Level) +
                     ": Description '" + str(Description) +
                     "', Connected: " + str(self.alarmConn.Connected()))
     # Multiple events can be passed for the same action, e.g during arming 1 event when requested, 1 event after exit timer counts to 0
     if (Level == 0):  # Disarm
         if ((self.alarmState['partition'][1]['status']['armed_stay']
              == True)
                 or (self.alarmState['partition'][1]['status']['armed_away']
                     == True)):
             Domoticz.Status("Requesting partition Disarm")
             self.alarmConn.Send(
                 CreateChecksum(evl_Commands['Disarm'] + '1' +
                                Parameters["Mode4"]))
     elif (Level == 1):  # Arm Stay
         if ((self.alarmState['partition'][1]['status']['armed_stay']
              == False) and
             (self.alarmState['partition'][1]['status']['armed_away']
              == False)):
             Domoticz.Status("Requesting partition Armed Stay")
             self.alarmConn.Send(
                 CreateChecksum(evl_Commands['ArmStay'] + '1'))
     elif (Level == 2):  # Arm Away
         if ((self.alarmState['partition'][1]['status']['armed_stay']
              == False) and
             (self.alarmState['partition'][1]['status']['armed_away']
              == False)):
             Domoticz.Status("Requesting partition Armed Away")
             self.alarmConn.Send(
                 CreateChecksum(evl_Commands['ArmAway'] + '1'))
     else:
         Domoticz.Error("Security Event contains unknown data: '" +
                        str(Level) + "' with description: '" + Description +
                        "'")
def checkNack(self, Data):
    if chr(Data[3]) == '0':
        if self._lastCmd == "UpdateStatus": #If a device is outside the network, TODO
            return
        Domoticz.Error("Nack on last command: " + self._lastCmd)
        if self._lastCmd == "join":
            self._connection.Send("*13*60*##",2)
    elif chr(Data[3]) == '1' :
        if self._lastCmd == "join" :
            self._joinedNetwork = True
            Domoticz.Status("Network joined, start communication.")
            self._lastCmd = "scan"
            self._connection.Send("*13*65*##")
        elif self._lastCmd == "scan" :
            Domoticz.Status("Scan network begin.")
            self._scanningNetwork = True
        elif self._lastCmd == "On":
            Devices[self._lastTargetUnit].Update(nValue = 1,sValue="1")
        elif self._lastCmd == "Off":
            Devices[self._lastTargetUnit].Update(nValue = 0,sValue="0")
            if self._lastTargetUnit == 255 : #All off
                for item in Devices:
                    Devices[item].Update(nValue = 0,sValue="0")
    else:
        Domoticz.Error("Unknown frame format")
Beispiel #5
0
    def ManageInit(self, pop=False):

        if pop:
            self.INIT_STEP.pop(0)
        if len(self.INIT_STEP) < 1:
            self.Ready = True

            Domoticz.Status("### deCONZ ready")
            l, s, g, b, o, c = Count_Type(self.Devices)
            Domoticz.Status("### Found " + str(l) + " Operators, " + str(s) +
                            " Sensors, " + str(g) + " Groups, " + str(c) +
                            " Scenes and " + str(o) + " others, with " +
                            str(b) + " Ignored")

            # Compare devices bases
            for i in Devices:
                if Devices[i].DeviceID not in self.Devices:
                    Domoticz.Status(
                        '### Device ' + Devices[i].DeviceID + '(' +
                        Devices[i].Name +
                        ') Not in deCONZ ATM, the device is deleted or not ready.'
                    )

            return

        Domoticz.Log("### Request " + self.INIT_STEP[0])
        self.SendCommand("/api/" + Parameters["Mode2"] + "/" +
                         self.INIT_STEP[0] + "/")
    def onStart(self):
        Domoticz.Status("onStart")
        self._joinedNetwork = False
        self._scanningNetwork = False
        self._scannedNetwork = False
    
        # loggingPlugin( self, 'Debug', "ListOfDevices : " )
        # for e in self.ListOfDevices.items(): 
            # loggingPlugin( self, 'Debug', " "+str(e))
        id = 255
        if id not in Devices:
            Domoticz.Device(Name = "Switch all off",  Unit = id, TypeName = "Push Off").Create()
            Domoticz.Status("Device Switch all created.")
            
        self._serialPort=Parameters["SerialPort"]
        
        
        if self._connection is not None:
            del self._connection
            self._connection = None


        if self._serialPort.find('/dev/') != -1 or self._serialPort.find('COM') != -1:
            Domoticz.Status("Connection...")
            BAUDS = 19200
            self._connection = Domoticz.Connection(Name="MyHome", Transport="Serial", Protocol="None",
                                                   Address=self._serialPort, Baud=BAUDS)
                                                   
        if self._connection:
            self._connection.Connect()
        else:
            Domoticz.Error("openConn _connection note set!")
Beispiel #7
0
	def onStop(self):
		try:
			if hasattr(self,"pFileserver"):
				self.pFileserver.terminate()
				Domoticz.Status("Stopping fileserver process.")

			if hasattr(self,"pYouTube"):
				self.pYouTube.terminate()
				Domoticz.Status("Stopping YouTube process.")

			if hasattr(self,"pSpotify"):
				self.pSpotify.terminate()
				Domoticz.Status("Stopping Spotify process.")

			if hasattr(self,"pRecheck"):
				self.pRecheck.terminate()
				Domoticz.Status("Stopping recheck process.")

			for ChromecastName in self.ConnectedChromecasts:
				if self.ConnectedChromecasts[ChromecastName]["CC"] != "":
					cc=self.ConnectedChromecasts[ChromecastName]["CC"]
					Domoticz.Status("Disconnecting from '"+cc.name+"'")
					cc.disconnect()
		except Exception as e:
			senderror(e)
Beispiel #8
0
	def onHeartbeat(self):
		try:
			if CheckInternet() == False:
				self.Error = "You do not have a working internet connection."
				self.Internet = False
				Domoticz.Error(self.Error)
			elif CheckInternet() == True and self.Internet == False:
				self.Internet = True
				Domoticz.Error("Your internet connection is back.")
				self.Error = False

			if self.Error == False:
				RecheckNeeded=False

				self.GetSpotifyToken()

				while self.q2.empty()==False:
					Result=self.q2.get()
					if "Error" in str(Result):
						Domoticz.Error(Result)
					else:
						Domoticz.Status(Result)
				#p.terminate()

				for ChromecastName in self.ConnectedChromecasts:
					cc=self.ConnectedChromecasts[ChromecastName]["CC"]
					#Check if chromecast is already connected
					if cc == "":
						Domoticz.Status("Will scan for available chromecasts, as " + ChromecastName + " is currently not connected.")
						RecheckNeeded=True
					else:
						if cc.status != None and cc.status.display_name == "Spotify":
							TrackInfo = self.SpotifyClient.current_user_playing_track()
							if TrackInfo != None:
								if TrackInfo['is_playing'] == True:
									Level = 20
								else:
									Level = 30
								DeviceID = self.ConnectedChromecasts[cc.name]["Index"]*10+1
								UpdateDevice(DeviceID,Level, Level)

					self.PlayMessage(ChromecastName)

				if RecheckNeeded == True:
					#Check if a chromecast is available in a seperate process.
					#If available connect to it in this process.
					self.pRecheck = Process(target=ScanForChromecasts, args=(self.q,self.ConnectedChromecasts,))
					self.pRecheck.start()
					if self.q.empty() == False:
						self.Recheck = self.q.get()
					self.pRecheck.terminate()

					if self.Recheck == True:
						Domoticz.Log("Connecting to available chromecasts")
						self.ConnectChromeCast()
					else:
						Domoticz.Log(str(self.Recheck))
		except Exception as e:
			senderror(e)
Beispiel #9
0
def handle_unused_unit(unit, remove_it=False):
    if remove_it:
        Domoticz.Status("Tag " + Devices[unit].Name +
                        " no longer monitored --> removed")
        Devices[unit].Delete()
    else:
        Domoticz.Status("Tag  " + Devices[unit].Name +
                        " no longer monitored --> marked as timed-out")
        Devices[unit].Update(nValue=0, sValue='Off', TimedOut=1)
def GrpMgtv2Migration(self):

    Domoticz.Status("Group Migration to new format")
    for GrpId in self.ListOfGroups:
        Domoticz.Status("--- GroupId: %s" % GrpId)
        migrateIfTradfriRemote(self, GrpId)

        for item in list(self.ListOfGroups[GrpId]["Devices"]):
            migrateTupleToList(self, GrpId, item)
Beispiel #11
0
	def startListening(self,chromecast):
		Domoticz.Status("Registering listeners for '" + chromecast.name+"'")
		listenerCast = StatusListener(chromecast)
		chromecast.register_status_listener(listenerCast)

		listenerMedia = StatusMediaListener(chromecast)
		chromecast.media_controller.register_status_listener(listenerMedia)
		
		connectioncast=ConnectionListener(chromecast)
		chromecast.register_connection_listener(connectioncast)

		Domoticz.Status("Done registering listeners for '"+ chromecast.name+"'")
def migrateTupleToList(self, GrpId, tupleItem):

    lenItem = len(tupleItem)
    if lenItem not in [2, 3]:
        self.logging(
            "Error", "For Group: %s unexpected Group Device %s droping" %
            (GrpId, str(tupleItem)))
        return

    if lenItem == 2:
        NwkId, Ep = tupleItem
        if "IEEE" not in self.ListOfDevices[NwkId]:
            self.logging(
                "Error", "For Group: %s unexpected Group Device %s droping" %
                (GrpId, str(tupleItem)))
            return
        Ieee = self.ListOfDevices[NwkId]["IEEE"]
        # Migrate from Tuple to List
        self.ListOfGroups[GrpId]["Devices"].remove((NwkId, Ep))
        self.ListOfGroups[GrpId]["Devices"].append([NwkId, Ep, Ieee])

    elif lenItem == 3:
        # Migrate from Tuple to List
        NwkId, Ep, Ieee = tupleItem
        self.ListOfGroups[GrpId]["Devices"].remove((NwkId, Ep, Ieee))
        self.ListOfGroups[GrpId]["Devices"].append([NwkId, Ep, Ieee])

    Domoticz.Status("--- --- NwkId: %s Ep: %s Ieee: %s" % (NwkId, Ep, Ieee))
    if NwkId not in self.ListOfDevices:
        self.logging(
            "Error",
            "migrateTupleToList - NwkId: %s not found in current database" %
            NwkId)
        if Ieee not in self.IEEE2NWK:
            return
        NwkId = self.IEEE2NWK[Ieee]
        Domoticz.Status("---> Retreive new NwkId: %s from Ieee: %s" %
                        (NwkId, Ieee))

    if "GroupMemberShip" not in self.ListOfDevices[NwkId]:
        self.ListOfDevices[NwkId]["GroupMemberShip"] = {}

    if Ep not in self.ListOfDevices[NwkId]["GroupMemberShip"]:
        self.ListOfDevices[NwkId]["GroupMemberShip"][Ep] = {}

    if GrpId not in self.ListOfDevices[NwkId]["GroupMemberShip"][Ep]:
        self.ListOfDevices[NwkId]["GroupMemberShip"][Ep][GrpId] = {}

    self.ListOfDevices[NwkId]["GroupMemberShip"][Ep][GrpId]["Status"] = "OK"
    self.ListOfDevices[NwkId]["GroupMemberShip"][Ep][GrpId]["TimeStamp"] = 0
Beispiel #13
0
    def onStart(self):
        Domoticz.Log("onStart called")
        Domoticz.Heartbeat(30)
        Domoticz.Log('Mode6: %s' %Parameters["Mode6"])
        Domoticz.Debugging(int(Parameters["Mode6"]))
        self.username = Parameters["Username"]
        self.password = Parameters["Password"]
        list_macs = (Parameters["Mode4"].strip()).split(',')
        self.macs = []
        self.ip = Parameters["Address"]
        list_device_mac = []
        homeicon = "idetect-home"
        homeiconid =  None
        Domoticz.Log("--> %s" %str(Images))
        if homeicon not in Images:
            Domoticz.Log("Uploading Orbi-Presence Icons")
            Domoticz.Image('ihome.zip').Create()
        homeiconid=Images[homeicon].ID
        Domoticz.Log("Images: %s" %str(Images))
        for img in Images:
            Domoticz.Log("Images: %s ==> Id: %s, Name: %s " %(img, Images[ img ].ID, Images[ img ].Name))

        Domoticz.Log("--> homeiconid: %s" %homeiconid)


        #Create "Anyone home" device
        if 1 not in Devices:
            Domoticz.Debug('Create Widget Anyone @ Home' )
            if homeiconid:
                myDev = Domoticz.Device(DeviceID='#Anyone', Name="Anyone@Home", Unit=1, TypeName="Switch", Used=1, Image=homeiconid)
            else:
                myDev = Domoticz.Device(DeviceID='#Anyone', Name="Anyone@Home", Unit=1, TypeName="Switch", Used=1)
            myDev.Create()

        for iterDev in Devices:
            list_device_mac.append(Devices[iterDev].DeviceID )
        Domoticz.Debug("List of Devices: %s" %str(list_device_mac))
        for iter in Parameters["Mode4"].split(','):
            mac = format_mac(iter)

            Domoticz.Status('- watching MAC@: %s' %mac)
            if mac not in list_device_mac:
                Domoticz.Debug('Create Widget for %s' %mac)
                myDev = Domoticz.Device(DeviceID=mac, Name=mac+" Presence", Unit=FreeUnit(Devices), Type=244)
                myDev.Create()
            self.macs.append(iter.strip(' '))
        Domoticz.Status("Connect to Orbi")
        self.session= requests.Session()
        self.session.auth = ( self.username, self.password )
    def onHeartbeat(self):
        try:
            self.runAgain -= self.HEARTBEAT_SEC

            # In case the API fails, generate en error every 12 hours
            if self.access_error_generated > 0:
                self.access_error_generated -= self.HEARTBEAT_SEC

            if self.runAgain <= 0:
                if self.NestThread is not None and self.NestThread.isAlive():
                    Domoticz.Debug("NestThread still running")
                else:
                    self.NestThread = threading.Thread(name="NestThread", target=BasePlugin.NestUpdate, args=(self,))
                    self.NestThread.start()

                # Run again following the period in the settings
                self.runAgain = int(Parameters["Mode5"]) * 60

            elif self.nest_update_status == _NEST_UPDATE_STATUS_DONE and self.access_error_generated <= 0:
                updated_units = self.updateThermostats() + self.updateProtects()

                Domoticz.Status("Updated {} units for {} device(s)".format(
                    updated_units,
                    len(self.myNest.device_list) + len(self.myNest.protect_list)
                ))
                self.nest_update_status = _NEST_UPDATE_STATUS_NONE

            Domoticz.Debug("Wait {} seconds to update devices".format(self.runAgain))

        except Exception as e:
            self._nest_access_error = "Unforseen exception occured in onHeartbeat: {}".format(e)
            log(traceback.format_exc())
 def onConnect(self, Connection, Status, Description):
     logging(self, "onConnect")
     
     if self._connection.Connected():
         Domoticz.Status("Connected to Name: MyHome, Transport: Serial, Address: %s" % (self._serialPort))
         self._lastCmd = "join"
         self._connection.Send("*13*60##")
Beispiel #16
0
    def onStart(self):
        Domoticz.Debug("onStart called")
        #CreateDevice('1111','sensors','On/Off light')

        #Check Domoticz IP
        if Parameters["Address"] != '127.0.0.1' and Parameters[
                "Address"] != 'localhost':
            global DOMOTICZ_IP
            DOMOTICZ_IP = get_ip()
            Domoticz.Log(
                "Your haven't use 127.0.0.1 as IP, so I suppose deCONZ and Domoticz aren't on same machine"
            )
            Domoticz.Log("Taking " + DOMOTICZ_IP + " as Domoticz IP")

            if DOMOTICZ_IP == Parameters["Address"]:
                Domoticz.Status(
                    "Your have same IP for deCONZ and Domoticz why don't use 127.0.0.1 as IP"
                )
        else:
            Domoticz.Log("Domoticz and deCONZ are on same machine")

        if Parameters["Mode3"] != "0":
            Domoticz.Debugging(int(Parameters["Mode3"]))
            #DumpConfigToLog()

        #Read banned devices
        with open(Parameters["HomeFolder"] + "banned_devices.txt",
                  'r') as myPluginConfFile:
            for line in myPluginConfFile:
                if not line.startswith('#'):
                    self.Banned_Devices.append(line.strip())
        myPluginConfFile.close()
Beispiel #17
0
    def SensorTimedOut(self, idx, name, datestring):
        def LastUpdate(datestring):
            dateformat = "%Y-%m-%d %H:%M:%S"
            # the below try/except is meant to address an intermittent python bug in some embedded systems
            try:
                result = datetime.strptime(datestring, dateformat)
            except TypeError:
                result = datetime(
                    *(time.strptime(datestring, dateformat)[0:6]))
            return result

        timedout = LastUpdate(datestring) + timedelta(
            minutes=int(Settings["SensorTimeout"])) < datetime.now()

        # handle logging of time outs... only log when status changes (less clutter in logs)
        if timedout:
            if self.ActiveSensors[idx]:
                Domoticz.Error(
                    "skipping timed out temperature sensor '{}'".format(name))
                self.ActiveSensors[idx] = False
        else:
            if not self.ActiveSensors[idx]:
                Domoticz.Status(
                    "previously timed out temperature sensor '{}' is back online"
                    .format(name))
                self.ActiveSensors[idx] = True

        return timedout
Beispiel #18
0
    def onConnect(self, Connection, Status, Description):
        Domoticz.Debug("onConnect called")

        if Connection.Name == 'deCONZ_WebSocket':

            if (Status != 0):
                Domoticz.Error("WebSocket connexion error : " +
                               str(Connection))
                Domoticz.Error("Status : " + str(Status) + " Description : " +
                               str(Description))
                return

            Domoticz.Status("Launching websocket on port " +
                            str(Connection.Port))
            #Need to Add Sec-Websocket-Protocol : domoticz ????
            #Boring error > Socket Shutdown Error: 9, Bad file descriptor
            wsHeader = "GET / HTTP/1.1\r\n" \
                        "Host: "+ Parameters["Address"] + ':' + str(Connection.Port) + "\r\n" \
                        "User-Agent: Domoticz/1.0\r\n" \
                        "Sec-WebSocket-Version: 13\r\n" \
                        "Origin: http://" + DOMOTICZ_IP + "\r\n" \
                        "Sec-WebSocket-Key: qqMLBxyyjz9Tog1bll7K6A==\r\n" \
                        "Connection: keep-alive, Upgrade\r\n" \
                        "Upgrade: websocket\r\n\r\n"
            #"Accept: Content-Type: text/html; charset=UTF-8\r\n" \
            #"Pragma: no-cache\r\n" \
            #"Cache-Control: no-cache\r\n" \
            #"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n" \
            self.WebSocket.Send(wsHeader)

        else:
            Domoticz.Error("Unknow connexion : " + str(Connection))
            Domoticz.Error("Status : " + str(Status) + " Description : " +
                           str(Description))
            return
Beispiel #19
0
def switchPiZigate_mode(self, mode="run"):

    if mode != "run":
        return

    try:
        Domoticz.Status(
            """Python version: %s dist: %s linux_distribution: %s system: %s machine: %s platform: %s uname: %s version: %s mac_ver: %s """
            % (
                sys.version.split("\n"),
                str(platform.dist()),
                linux_distribution(),
                platform.system(),
                platform.machine(),
                platform.platform(),
                platform.uname(),
                platform.version(),
                platform.mac_ver(),
            ))

    except Exception as e:
        Domoticz.Error(
            "switchPiZigate_mode - unable to find distribution: Assuming debian, Error: %s"
            % e)
        runmode_with_gpiomodule()
        return

    if platform.dist()[0] in ("fedora"):
        runmode_with_gpiomodule()

    if platform.dist()[0] in ("debian"):
        runmode_with_gpiocommand()
Beispiel #20
0
 def onStop(self):
     global p
     for chromecast in self.ConnectedChromecasts:
         if self.ConnectedChromecasts[chromecast][1] != "":
             cc = self.ConnectedChromecasts[chromecast][1]
             Domoticz.Status("Disconnected from " + cc.name)
             cc.disconnect()
def restartPluginViaDomoticzJsonApi(self):

    if not os.path.isfile(CURL_COMMAND):
        Domoticz.Log("Unable to restart the plugin, %s not available" % CURL_COMMAND)
        return

    if self.WebUsername and self.WebPassword:
        url = "http://%s:%[email protected]:%s" % (self.WebUsername, self.WebPassword, self.pluginconf.pluginConf["port"])
    else:
        url = "http://127.0.0.1:%s" % self.pluginconf.pluginConf["port"]

    url += "/json.htm?type=command&param=updatehardware&htype=94"
    url += "&idx=%s" % self.pluginParameters["HardwareID"]
    url += "&name=%s" % self.pluginParameters["Name"].replace(" ", "%20")
    url += "&address=%s" % self.pluginParameters["Address"]
    url += "&port=%s" % self.pluginParameters["Port"]
    url += "&serialport=%s" % self.pluginParameters["SerialPort"]
    url += "&Mode1=%s" % self.pluginParameters["Mode1"]
    url += "&Mode2=%s" % self.pluginParameters["Mode2"]
    url += "&Mode3=%s" % self.pluginParameters["Mode3"]
    url += "&Mode4=%s" % self.pluginParameters["Mode4"]
    url += "&Mode5=%s" % self.pluginParameters["Mode5"]
    url += "&Mode6=%s" % self.pluginParameters["Mode6"]
    url += "&extra=%s" % self.pluginParameters["Key"]
    url += "&enabled=true"
    url += "&datatimeout=0"
    if "LogLevel" in self.pluginParameters:
        url += "&loglevel=%s" % self.pluginParameters["LogLevel"]

    Domoticz.Status("Plugin Restart command : %s" % url)

    _cmd = CURL_COMMAND + " '%s' &" % url
    os.system(_cmd)  # nosec
Beispiel #22
0
	def getactivemacs(self, router):
		errorcount=self.routers[router]['errorcount']
		if self.routers[router]['initialized']:
			Domoticz.Debug("Polling presense data from " + router)
			success, sshdata=self.getfromssh(router, self.routers[router]['user'], self.routerpass, self.routers[router]['cmd'], port=self.routers[router]['port'])
			if success:
				if errorcount > 0:
					self.routers[router]['errorcount'] = 0
					Domoticz.Status('Connection restored for ' + router)

				list = self.mac_format.findall(sshdata.decode("utf-8").upper())
				return True, list
		else:
			Domoticz.Debug(router + " was not properly initialized. Retrying to get router capabilities (and skipping this poll round).")
			gotit, self.routers[router] = self.getrouter(router, self.routers[router]['user'], self.routerpass, routerport=self.routers[router]['port'], mode=self.detectmode)
			if gotit:
				self.routers[router]['errorcount'] = 0
				return False, None
		#If anything worked we should have retuned by now
		self.routers[router]['errorcount'] = errorcount + 1
		delayme = min(120, self.routers[router]['errorcount'] * 30)
		self.routers[router]['prospone'] = datetime.now() + timedelta(seconds=delayme)
		if self.routers[router]['errorcount'] % 3 == 0:
			if self.routers[router]['initialized']:
				Domoticz.Error('Polling ' + router + ' has failed ' + str(self.routers[router]['errorcount']) + ' times. Poll interval automatically reduced for this router.')
			else:
				Domoticz.Error('Failed ' + str(self.routers[router]['errorcount']) + ' times to get capabilities for ' + router + '. Retry interval automatically reduced for this router.')
		Domoticz.Debug('Routerinfo:' + str(self.routers[router]))
		return False, None
Beispiel #23
0
def uninstallFE(self):
    Domoticz.Status('Uninstalling plugin custom page...')

    from shutil import rmtree

    try:
        templates_path = os.path.abspath(
            os.path.dirname(os.path.abspath(__file__)) +
            '/../../www/templates')
        dst_plugin_path = templates_path + '/deCONZ'

        Domoticz.Debug('Removing files from ' + templates_path)

        #if (os.path.isdir(dst_plugin_path)):
        #    rmtree(dst_plugin_path)

        if os.path.exists(templates_path + "/deCONZ.html"):
            os.remove(templates_path + "/deCONZ.html")

        if os.path.exists(templates_path + "/deCONZ.js"):
            os.remove(templates_path + "/deCONZ.js")

        Domoticz.Log('Uninstalled plugin custom page succesfully!')
    except Exception as e:
        Domoticz.Error('Error during uninstalling plugin custom page')
        Domoticz.Error(repr(e))
Beispiel #24
0
	def prepare_for_polling(self):
		build_script = ''
		self.command_support = self.find_tracker_command()
		if self.command_support is None:
			self.is_ready = False
			return
		for supported_command in tracker_cli_helper.chipset_methods:
			if supported_command in self.command_support:
				interfaces = self.find_tracker_interfaces(supported_command)
				if interfaces is None:
					continue
				else:
					for found_interface in interfaces:
						build_script = build_script + tracker_cli_helper.get_tracker_cli(supported_command, self.command_support[supported_command], found_interface)
		if build_script == '':
			for generic_command in tracker_cli_helper.generic_method_order:
				if generic_command in self.command_support:
					build_script = tracker_cli_helper.get_tracker_cli(generic_command, self.command_support[generic_command])
					Domoticz.Status(self.tracker_ip + ' No supported chipset found. Using generic mode: ' + generic_command)
					break
		if build_script == '':
			Domoticz.Debug(self.tracker_ip + ' FAILED: No suitable polling command found on this tracker!')
			self.is_ready = False
			return
		self.trackerscript = tracker_cli_helper.wrap_command(build_script)
		Domoticz.Debug(self.tracker_ip + ' Prepared to poll using: ' + self.trackerscript)
		self.is_ready = True
Beispiel #25
0
    def login(self, force=False):
        if not force and self.loginSid is not None:
            return self.loginSid

        try:
            url = "%s/login.json" % self.baseUrl
            payload = '{"pass" : "%s", "right" : "usr"}' % Parameters[
                "Password"]
            r = requests.post(url,
                              data=payload,
                              headers=self.headers,
                              verify=False,
                              timeout=self.httpTimeout)
        except Exception as e:
            Domoticz.Log("Error accessing SMA inverter on %s; %s" %
                         (Parameters["Address"], e))
        else:
            j = r.json()
            try:
                sid = j['result']['sid']
                if sid is None:
                    Domoticz.Error(
                        "Unable to login to SMA inverter on %s using supplied password"
                        % Parameters["Address"])
                self.loginSid = sid
                Domoticz.Status(
                    "Successfully logged in to SMA inverter on %s" %
                    Parameters["Address"])
                Domoticz.Debug("Received SID: %s" % sid)
                return self.loginSid
            except:
                Domoticz.Log("No valid response from SMA inverter on %s; %s" %
                             (Parameters["Address"], j))
    def MapLevelToMethodParam(self, unit, command, level):
        try:
            field = unit["bindingStatusField"]
            status_old = getattr(self.status, field)
            status_new = level

            mapLevelStatus = unit["map_level_status"]
            if mapLevelStatus is not None:
                status_new = mapLevelStatus(self, unit, level)
                if status_new == status_old:
                    Domoticz.Log(
                        "The command is consistent with the status:" + str(command)
                    )
                    return None

            method = unit["map_level_method"]
            method = rgetattr(self, method)
            param = level
            mapLevelParam = unit["map_level_param"]
            if mapLevelParam is not None:
                param = mapLevelParam(self, unit, level)

            result = method(param)

            Domoticz.Debug("Method call result:" + str(result))
            if result[0]["code"] == 0:
                return status_new
            else:
                Domoticz.Status("Command call result NOK")

        except Exception as updateError:
            Domoticz.Error("MapLevelToMethodParam: " + repr(updateError))

        return None
Beispiel #27
0
 def manage_presence(self):
     if self.override.has_expired(self.present_count > 0):
         Domoticz.Status('Override has ended')
         self.override.set_inactive()
         update_domoticz_status(self.OVERRIDE_UNIT, False)
     self.present_count = 0
     for d in self.tags_to_monitor:
         self.tags_to_monitor[d].check_if_seen()
     for d in self.tags_to_monitor:
         if self.tags_to_monitor[d].present and not self.tags_to_monitor[
                 d].ignore_for_anyonehome:
             self.present_count = self.present_count + 1
     Domoticz.Debug(
         str(self.present_count) +
         ' devices are present (excluding ignored devices)')
     if (self.present_count == 0
             and not self.override.active) and self.anyone_home:
         updated = update_domoticz_status(self.ANYONE_HOME_UNIT, False)
         if updated:
             self.anyone_home = False
     elif (self.present_count > 0
           or self.override.active) and not self.anyone_home:
         updated = update_domoticz_status(self.ANYONE_HOME_UNIT, True)
         if updated:
             self.anyone_home = True
Beispiel #28
0
    def handle_message(self, device_data, message):
        device_address = device_data['ieee_addr']
        device = self.get_device(device_address, self.alias)

        Domoticz.Debug('zigbee device:' + str(device_address) +
                       ' sent message:' + str(message.raw))

        n_value = None
        s_value = None
        color_value = None

        if (device == None):
            Domoticz.Status('no device in message')
            # Due to internal domoticz bug, app crashes if we try to use device just after we create it
            # so just create and exit for now
            # device = self._create_device(device_data, message)
            return self._create_device(device_data)

        if "brightness" in message.raw:
            value = message.raw["brightness"]
            n_value = 1 if value > 0 else 0
            s_value = str(int(value * 100 / 255))

        signal_level = message.get_signal_level()

        if "state" in message.raw:
            if message.raw['state'].upper() == 'OFF':
                n_value = 0
            else:
                n_value = 1

        if "color" in message.raw:
            color_value = self.get_color_value(message)

        #when no values in message, reuse existing values from device

        payload = {}
        if (n_value != None):
            payload['nValue'] = n_value

        if (s_value != None):
            payload['sValue'] = s_value

        if (signal_level != None):
            payload['SignalLevel'] = signal_level

        if (color_value != None):
            payload['Color'] = color_value

        Domoticz.Debug("update domticz device: '" + str(payload) + "'")

        if payload:
            if not 'nValue' in payload:
                payload['nValue'] = device.nValue
            if not 'sValue' in payload:
                payload['sValue'] = device.sValue
            device.Update(**payload)
        else:
            Domoticz.Debug("no usable data in message... hearbeat message???")
Beispiel #29
0
    def DeleteDeviceFromdeCONZ(self, _id):

        url = '/api/' + Parameters["Mode2"] + '/sensors/' + str(_id)

        self.Buffer_Command.append((url, 'delete'))
        self.UpdateBuffer()

        Domoticz.Status("### Deleting device " + str(_id))
Beispiel #30
0
    def ReadConfig(self,_Data):
        #trick to test is deconz is ready
        fw = _Data['fwversion']
        if fw == '0x00000000':
            Domoticz.Error("Wrong startup, retrying !!")
            #Cancel this part to restart it after 1 heartbeat (10s)
            return
        Domoticz.Status("Firmware version : " + _Data['fwversion'] )
        Domoticz.Status("Websocketnotifyall : " + str(_Data['websocketnotifyall']))
        if not _Data['websocketnotifyall'] == True:
            Domoticz.Error("Websocketnotifyall is not set to True")

        #Launch Web socket connexion
        self.WebSocket = Domoticz.Connection(Name="deCONZ_WebSocket", Transport="TCP/IP", Address=Parameters["Address"], Port=str(_Data['websocketport']) )
        self.WebSocket.Connect()

        self.ManageInit(True)