Esempio n. 1
0
    def ELV_getrooms(self, oSetting, oAction, dParams):  #check
        """
        Returns a list of rooms

        :param cInterface.cInterFaceSettings oSetting: The setting object
        :param cAction oAction: The action object (unused)
        :param dict dParams: The parameter (unused)
        :return: list: A list of dicts: key:name=room name , rf_address= Rf Address of Room
        :rtype: list
        """

        aRet = []
        i = 0

        for oRoom in oSetting.oDevice.rooms:
            dLine = QueryDict()
            dLine.uVarSuffix = "[" + str(i) + "]"
            dLine.dValue = {
                "name": oRoom.name,
                "rf_address": str(oRoom.rf_address)
            }
            aRet.append(dLine)
            i = i + 1

        return aRet
Esempio n. 2
0
 def __init__(self):
     cDiscoverScriptTemplate.__init__(self)
     self.uSubType = u'UPNP'
     self.bStopWait = False
     self.aResults = []
     self.aThreads = []
     self.oReq = QueryDict()
Esempio n. 3
0
 def __init__(self):
     cDiscoverScriptTemplate.__init__(self)
     self.uSubType = u'EISCP (Onkyo)'
     self.aResults = []
     self.aThreads = []
     self.oReq = QueryDict()
     self.bOnlyOnce = True
     self.uIPVersion = "Auto"
Esempio n. 4
0
    def _CreateSimpleResult(self, uResult):
        """
        Helper Function to create a simple one line result

        :param uResult:
        :return: a dict key:result=Result
        :rtype: QueryDict
        """
        aRet = []
        dLine = QueryDict()
        dLine.uVarSuffix = ""
        dLine.dValue = {"result": uResult}
        aRet.append(dLine)
        return aRet
Esempio n. 5
0
 def GetDeviceDetails(self,sData,tSenderAddr):
     oRet                     = QueryDict()
     oRet.sFoundIP            = tSenderAddr[0]
     oRet.uFoundPort          = tSenderAddr[1]
     oRet.bFound              = True
     oRet.sData               = sData
     oRet.uIPVersion          = self.uIPVersion
     return oRet
Esempio n. 6
0
    def ListDiscover(self):
        oSetting = self.GetSettingObjectForConfigName(
            uConfigName=self.uConfigName)
        fTimeOut = oSetting.aScriptIniSettings.fTimeOut
        dArgs = {}
        dArgs["onlyonce"] = 0

        self.Discover(**dArgs)

        try:

            for dResult in self.aResults:
                aDevice = QueryDict()
                aDevice.sFoundIP = dResult["ip"]
                aDevice.uFoundPort = str(dResult["port"])
                aDevice.uFoundModel = dResult["model"]
                aDevice.uFoundHostName = dResult["hostname"]
                Logger.info(u'Bingo: Discovered device %s:%s' %
                            (aDevice.uFoundModel, aDevice.sFoundIP))
                uTageLine = aDevice.sFoundIP + aDevice.uFoundModel
                if self.aDevices.get(uTageLine) is None:
                    self.aDevices[uTageLine] = aDevice
                    self.AddLine([
                        aDevice.sFoundIP, aDevice.uFoundHostName,
                        aDevice.uFoundPort, aDevice.uFoundModel
                    ], aDevice)
        except Exception as e:
            LogErrorSmall(u'Error on Enigma discover', e)
Esempio n. 7
0
    def GetDeviceDetails(self, sData, tSenderAddr):

        oRet = QueryDict()
        oRet.sFoundIP = tSenderAddr[0]
        oRet.sData = sData
        oRet.uFoundName = sData[0:8].decode('utf-8')
        oRet.uFoundSerial = sData[8:18].decode('utf-8')
        oRet.uFoundHostName = socket.gethostbyaddr(oRet.sFoundIP)[0]
        oRet.uIPVersion = u"IPv4"

        Logger.info(u'Bingo: Dicovered device %s:%s:%s at %s' %
                    (oRet.uFoundName, oRet.uFoundHostName, oRet.uFoundSerial,
                     oRet.sFoundIP))

        return oRet
Esempio n. 8
0
    def Run(self, fTimeOut):

        self.bStopThreadEvent = False

        Logger.debug(u'iTach Start Discover Thread')

        p = re.compile((r'AMXB<-UUID=GlobalCache_(?P<UUID>.{12}).+'
                        r'Model=iTach(?P<Model>.+?)>.+'
                        r'Revision=(?P<Revision>.+?)>.+'
                        r'Config-URL=http://(?P<IP>.+?)>.+'
                        r'PCB_PN=(?P<PN>.+?)>.+'
                        r'Status=(?P<Status>.+?)>'))

        try:
            self.oSocket.settimeout(fTimeOut)
            self.oSocket.bind(('', 9131))
            group = socket.inet_aton('239.255.250.250')
            mreq = struct.pack('4sL', group, socket.INADDR_ANY)
            self.oSocket.setsockopt(socket.IPPROTO_IP,
                                    socket.IP_ADD_MEMBERSHIP, mreq)
        except Exception as e:
            self.cScript.ShowError("iTach-Discover -3: Error occured", e)

        try:
            while not self.bStopThreadEvent:
                if self.oSocket is not None:
                    ready = select.select([self.oSocket], [], [],
                                          int(fTimeOut))
                    # the first element of the returned list is a list of readable sockets
                    if ready[0]:
                        data = self.oSocket.recv(1024)
                        match = p.match(data)
                        if match:
                            oiTachEntry = QueryDict()
                            oiTachEntry.uIP = match.group('IP')
                            oiTachEntry.uUUID = match.group('UUID')
                            oiTachEntry.uModel = match.group('Model')
                            oiTachEntry.uRevision = match.group('Revision')
                            oiTachEntry.uPartNumber = match.group('PN')
                            oiTachEntry.uStatus = match.group('Status')

                            if not oiTachEntry.uIP in self.aDevices:
                                self.aDevices[oiTachEntry.uIP] = oiTachEntry
                                Logger.info(
                                    "iTach-Discover: iTach found! IP: %s, UUID:%s, Model:%s, Revision:%s, Part number:%s, Status:%s"
                                    %
                                    (oiTachEntry.uIP, oiTachEntry.uUUID,
                                     oiTachEntry.uModel, oiTachEntry.uRevision,
                                     oiTachEntry.uPartNumber,
                                     oiTachEntry.uStatus))

        except socket.timeout:
            if len(self.aDevices) == 0:
                Logger.debug(
                    "iTach-Discover: Could not find an iTach on the network")
        except Exception as e:
            self.cScript.ShowError("iTach-Discover: Error occured", e)
        finally:
            Logger.debug(u'iTach-Discover: Stop Discover Thread')
            self.oSocket.close()
            return
Esempio n. 9
0
class cScript(cDiscoverScriptTemplate):
    """
    WikiDoc:Doc
    WikiDoc:Context:Scripts
    WikiDoc:Page:Scripts-Discover-UPNP
    WikiDoc:TOCTitle:Discover UPNP
    = Script Discover UPNP =

    The UPNP discover script discover devices which runs a upnp server.
    You can filter the discover result by passing the following parameters::
    <div style="overflow:auto; ">
    {| class="wikitable"
    ! align="left" | Attribute
    ! align="left" | Description
    |-
    |discovermanufacturer
    |Discover models only from a specific manufacturer
    |-
    |discovermodels
    |Discover specific models
    |-
    |discoverprettyname
    |Some devices reports a pretty name (like mac address, or IP addrees, a a further name). You can specify to discover just aspecific preetty name
    |-
    |servicetypes
    |Specifies the servicetypes for discover (eg.: upnp:rootdevice)
    |-
    |ipversion
    |Specifies which IPVersion to use for discovery: Could be IPv4Only,IPv6Only,All,Auto. Auto prefers IPv6, if available
    |-
    |timeout
    |Specifies the timout for discover
    |}</div>

    Blank options will not be used. You could eg use the pretty name just to match a specific device, or just the manufacturer name to match all devices in the network of this manufacturer.

    WikiDoc:End
    """
    class cScriptSettings(cBaseScriptSettings):
        def __init__(self, oScript):
            cBaseScriptSettings.__init__(self, oScript)
            self.aScriptIniSettings.fTimeOut = 15.0

    def __init__(self):
        cDiscoverScriptTemplate.__init__(self)
        self.uSubType = u'UPNP'
        self.bStopWait = False
        self.aResults = []
        self.aThreads = []
        self.oReq = QueryDict()

    def Init(self, uScriptName, uScriptFile=u''):
        cDiscoverScriptTemplate.Init(self, uScriptName, uScriptFile)
        self.oScriptConfig.dDefaultSettings['TimeOut']['active'] = "enabled"

    def GetHeaderLabels(self):
        return [
            '$lvar(5029)', '$lvar(5035)', '$lvar(5030)', '$lvar(5031)',
            '$lvar(5032)', '$lvar(SCRIPT_DISC_UPNP_1)'
        ]

    def ListDiscover(self):

        dArgs = {}
        dArgs["onlyonce"] = 0
        dArgs["servicetypes"] = "ssdp:all"
        dArgs["ipversion"] = "All"
        aDevices = {}

        self.Discover(**dArgs)

        for aDevice in self.aResults:
            uTageLine = aDevice.sFoundIP + aDevice.uFoundHostName + aDevice.uFoundManufacturer + aDevice.uFoundModel + aDevice.uFoundFriendlyName + aDevice.uFoundServiceType
            if aDevices.get(uTageLine) is None:
                aDevices[uTageLine] = aDevice
                self.AddLine([
                    aDevice.sFoundIP, aDevice.uFoundHostName,
                    aDevice.uFoundManufacturer, aDevice.uFoundModel,
                    aDevice.uFoundFriendlyName, aDevice.uFoundServiceType
                ], aDevice)
        return

    def CreateDiscoverList_ShowDetails(self, instance):
        uText=  u"$lvar(5029): %s \n" \
                u"$lvar(5035): %s \n" \
                u"$lvar(5030): %s \n"\
                u"$lvar(5031): %s \n"\
                u"$lvar(5032): %s \n"\
                u"$lvar(SCRIPT_DISC_UPNP_1): %s \n"\
                u"\n"\
                u"%s\n"\
                u"\n"\
                u"%s" % (instance.oDevice.sFoundIP,instance.oDevice.uFoundHostName,instance.oDevice.uFoundManufacturer,instance.oDevice.uFoundModel,instance.oDevice.uFoundFriendlyName,instance.oDevice.uFoundServiceType,instance.oDevice.sData,instance.oDevice.uResult)

        ShowMessagePopUp(uMessage=uText)

    def Discover(self, **kwargs):

        self.oReq.clear()
        uConfigName = kwargs.get('configname', self.uConfigName)
        oSetting = self.GetSettingObjectForConfigName(uConfigName=uConfigName)
        self.oReq.uManufacturer = kwargs.get('manufacturer', "")
        self.oReq.uModels = kwargs.get('models', "")
        self.oReq.uFriendlyName = kwargs.get('prettyname', "")
        self.oReq.bReturnPort = ToBool(kwargs.get('returnport', "0"))
        fTimeOut = ToFloat(
            kwargs.get('timeout', oSetting.aScriptIniSettings.fTimeOut))
        uParST = kwargs.get('servicetypes', "ssdp:all")
        uIPVersion = kwargs.get('ipversion', "IPv4Only")
        aST = uParST.split(',')
        bOnlyOnce = ToBool(kwargs.get('onlyonce', "1"))

        Logger.debug(
            u'Try to discover %s device by UPNP:  Models: %s , PrettyName: %s '
            % (self.oReq.uManufacturer, self.oReq.uModels,
               self.oReq.uFriendlyName))

        del self.aResults[:]
        del self.aThreads[:]

        try:
            for uST in aST:
                oThread = None
                if uIPVersion == "IPv4Only" or uIPVersion == "All" or (
                        uIPVersion == "Auto" and Globals.uIPAddressV6 == ""):
                    oThread = cThread_Discover_UPNP(bOnlyOnce=bOnlyOnce,
                                                    oReq=self.oReq,
                                                    uIPVersion="IPv4Only",
                                                    fTimeOut=fTimeOut,
                                                    uST=uST,
                                                    oCaller=self)
                    self.aThreads.append(oThread)
                    self.aThreads[-1].start()
                if uIPVersion == "IPv6Only" or uIPVersion == "All" or (
                        uIPVersion == "Auto" and Globals.uIPAddressV6 != ""):
                    oThread = cThread_Discover_UPNP(bOnlyOnce=bOnlyOnce,
                                                    oReq=self.oReq,
                                                    uIPVersion="IPv6Only",
                                                    fTimeOut=fTimeOut,
                                                    uST=uST,
                                                    oCaller=self)
                    self.aThreads.append(oThread)
                    self.aThreads[-1].start()

            for oT in self.aThreads:
                oT.join()

            if len(self.aResults) > 0:
                return {
                    "Host": self.aResults[0].sFoundIP,
                    "Hostname": self.aResults[0].uFoundHostName,
                    "Model": self.aResults[0].uFoundModel,
                    "FriendlyName": self.aResults[0].uFoundFriendlyName,
                    "Manufacturer": self.aResults[0].uFoundManufacturer,
                    "ServiceType": self.aResults[0].uFoundServiceType,
                    "IPVersion": self.aResults[0].uIPVersion,
                    'Exception': None
                }
            else:
                Logger.warning(u'No device found device %s:%s:%s' %
                               (self.oReq.uManufacturer, self.oReq.uModels,
                                self.oReq.uFriendlyName))
            return {
                "Host": "",
                "Hostname": "",
                "Model": "",
                "FriendlyName": "",
                "Manufacturer": "",
                "ServiceType": "",
                "IPVersion": "",
                'Exception': None
            }

        except Exception as e:
            LogError(u'Error on discover uPnP', e)
            return {
                "Host": "",
                "Hostname": "",
                "Model": "",
                "FriendlyName": "",
                "Manufacturer": "",
                "ServiceType": "",
                "IPVersion": "",
                'Exception': e
            }

    @classmethod
    def GetConfigJSONforParameters(cls, dDefaults):
        return {
            "Manufacturer": {
                "type": "string",
                "order": 0,
                "title": "$lvar(6013)",
                "desc": "$lvar(6014)",
                "key": "manufacturer",
                "default": ""
            },
            "Models": {
                "type": "string",
                "order": 1,
                "title": "$lvar(6015)",
                "desc": "$lvar(6016)",
                "key": "models",
                "default": ""
            },
            "PrettyName": {
                "type": "string",
                "order": 2,
                "title": "$lvar(6017)",
                "desc": "$lvar(6018)",
                "key": "prettyname",
                "default": ""
            },
            "ServiceTypes": {
                "type":
                "string",
                "order":
                3,
                "title":
                "$lvar(6023)",
                "desc":
                "$lvar(6024)",
                "key":
                "servicetypes",
                "default":
                "urn:dial-multiscreen-org:service:dial:1,urn:schemas-upnp-org:service:AVTransport:1"
            },
            "IP Version": {
                "type": "scrolloptions",
                "order": 4,
                "title": "$lvar(6037)",
                "desc": "$lvar(6038)",
                "key": "ipversion",
                "default": "IPv4Only",
                "options": ["IPv4Only", "IPv6Only", "All", "Auto"]
            },
            "TimeOut": {
                "type": "numericfloat",
                "order": 6,
                "title": "$lvar(6019)",
                "desc": "$lvar(6020)",
                "key": "timeout",
                "default": "15.0"
            }
        }
Esempio n. 10
0
    def GetDeviceDetails(self, sData, tSenderAddr):
        oRet = QueryDict()
        oRet.uFoundManufacturer = u""
        oRet.uFoundModel = u""
        oRet.uFoundFriendlyName = u""
        oRet.uFoundServiceType = u""
        oRet.sFoundIP = tSenderAddr[0]
        oRet.uIPVersion = self.uIPVersion[:4]
        oRet.bFound = False
        oRet.sData = sData
        oRet.uResult = u""
        oRet.uFoundHostName = u""
        uUrl = u""

        if not PY2:
            oRet.sData = ToUnicode(oRet.sData)

        if oRet.uIPVersion == "IPv6":
            oRet.sFoundIP = "[%s}" % oRet.sFoundIP

        # if we got a response
        if '200 OK' in oRet.sData:
            aData = oRet.sData.splitlines()
            uFoundServiceType = ""

            # The location field as part of DIAL specification and contains a link to an XML with further device infos
            for uLine in aData:
                if uLine.upper().startswith('LOCATION:'):
                    uUrl = uLine[9:].strip()
                if uLine.startswith('ST'):
                    oRet.uFoundServiceType = uLine[3:].strip()
                    uFoundServiceType = uFoundServiceType

            Logger.debug(u'Trying to get device details from  %s' % uUrl)

            try:

                self.oUrlRequest = UrlRequest(uUrl,
                                              method="GET",
                                              req_body='',
                                              req_headers={
                                                  "Connection": "Keep-Alive",
                                                  "Accept-Encoding": "gzip"
                                              },
                                              timeout=self.fTimeOut,
                                              on_error=self.OnError)
                self.NewWait(0.05)
                iStatusCode = self.oUrlRequest.resp_status

                if iStatusCode == 200 and "device" in self.oUrlRequest.result:
                    oRet.uResult = RemoveURN(self.oUrlRequest.result)
                    oNode = ElementTree(fromstring(oRet.uResult))
                    oNode = oNode.find("device")
                    oRet.uFoundManufacturer = oNode.find("manufacturer").text
                    oRet.uFoundModel = oNode.find("modelName").text

                    try:
                        oRet.uFoundFriendlyName = oNode.find(
                            "friendlyName").text
                    except Exception as e:
                        pass
                    oRet.bFound = True
                    Logger.debug(u'Found Device %s:%s:%s (%s)' %
                                 (oRet.uFoundManufacturer, oRet.uFoundModel,
                                  oRet.uFoundFriendlyName, oRet.sFoundIP))
            except Exception as e:
                LogError("Can''t get device details. skipping device: " + uUrl,
                         e)

        return oRet
Esempio n. 11
0
    def Discover(self, **kwargs):

        oSendSocket = None
        oReceiveSocket = None
        iPort = 23272
        uSerial = kwargs.get('serialnumber', "")
        uConfigName = kwargs.get('configname', self.uConfigName)
        oSetting = self.GetSettingObjectForConfigName(uConfigName=uConfigName)
        fTimeOut = ToFloat(
            kwargs.get('timeout', oSetting.aScriptIniSettings.fTimeOut))
        del self.aResults[:]

        Logger.debug(u'Try to discover ELV MAX device:  %s ' % uSerial)

        try:
            oSendSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM,
                                        socket.IPPROTO_UDP)
            oSendSocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST,
                                   True)
            oSendSocket.settimeout(10)

            bData = bytearray("eQ3Max", "utf-8") + \
                    bytearray("*\0",    "utf-8") + \
                    bytearray('*' * 10, "utf-8") + \
                    bytearray('I',      "utf-8")

            oSendSocket.sendto(bData, ("255.255.255.255", iPort))

            oReceiveSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            oReceiveSocket.settimeout(fTimeOut)
            oReceiveSocket.bind(("0.0.0.0", iPort))

            # sData, tSenderAddr = oReceiveSocket.recvfrom(50)
            # oRet = self.GetDeviceDetails(sData, tSenderAddr)
            # if uSerial == "" or oRet.uSerial == uSerial:
            #     self.aResults.append(oRet)

            while True:
                # we do not wait too long
                ready = select.select([oReceiveSocket], [], [], fTimeOut)
                if ready[0]:
                    # Get a response
                    sData, tSenderAddr = oReceiveSocket.recvfrom(50)
                    oRet = self.GetDeviceDetails(sData, tSenderAddr)
                    if uSerial == "" or oRet.uSerial == uSerial:
                        self.aResults.append(oRet)
                else:
                    break

            if oSendSocket:
                oSendSocket.close()
            if oReceiveSocket:
                oReceiveSocket.close()

            if len(self.aResults) > 0:
                return QueryDict([("Host", self.aResults[0].sFoundIP),
                                  ("Hostname",
                                   self.aResults[0].uFoundHostName),
                                  ("Serial", self.aResults[0].uFoundSerial),
                                  ("Name", self.aResults[0].uFoundName)])

        except Exception as e:
            pass

        if oSendSocket:
            oSendSocket.close()
        if oReceiveSocket:
            oReceiveSocket.close()

        Logger.warning(u'No ELV MAX Cube found %s' % uSerial)
        return QueryDict([("Host", ""), ("Hostname", ""), ("Serial", ""),
                          ("Name", "")])
Esempio n. 12
0
 def __init__(self):
     cDiscoverScriptTemplate.__init__(self)
     self.uSubType        = u'Keene Kira'
     self.aResults        = []
     self.aThreads        = []
     self.oReq            = QueryDict()
Esempio n. 13
0
class cScript(cDiscoverScriptTemplate):
    """
    WikiDoc:Doc
    WikiDoc:Context:Scripts
    WikiDoc:Page:Scripts-Discover-Kira
    WikiDoc:TOCTitle:Discover Kira
    = Script Discover Keene Kira =

    The Kira discover script discover Keene Kira Infrared transmitter devices.
    You can filter the discover result by passing the following parameters::
    <div style="overflow:auto; ">
    {| class="wikitable"
    ! align="left" | Attribute
    ! align="left" | Description
    |-
    |timeout
    |Specifies the timout for discover
    |}</div>

    WikiDoc:End
    """
    class cScriptSettings(cBaseScriptSettings):
        def __init__(self,oScript):
            cBaseScriptSettings.__init__(self,oScript)
            self.aScriptIniSettings.fTimeOut                     = 10.0

    def __init__(self):
        cDiscoverScriptTemplate.__init__(self)
        self.uSubType        = u'Keene Kira'
        self.aResults        = []
        self.aThreads        = []
        self.oReq            = QueryDict()

    def Init(self,uScriptName,uScriptFile=u''):
        """
        Init function for the script

        :param string uScriptName: The name of the script (to be passed to all scripts)
        :param uScriptFile: The file of the script (to be passed to all scripts)
        """
        cDiscoverScriptTemplate.Init(self, uScriptName, uScriptFile)
        self.oScriptConfig.dDefaultSettings['TimeOut']['active']                     = "enabled"

    def GetHeaderLabels(self):
        return ['$lvar(5029)','$lvar(5035)','$lvar(6002)']

    def ListDiscover(self):

        dArgs                   = {}
        dArgs["onlyonce"]       = 0
        dArgs["ipversion"]      = "IPv4Only"
        aDevices                = {}

        self.Discover(**dArgs)

        for aDevice in self.aResults:
            uTageLine=aDevice.sFoundIP+aDevice.uFoundHostName+aDevice.uFoundPort
            if aDevices.get(uTageLine) is None:
               aDevices[uTageLine]=aDevice
               self.AddLine([aDevice.sFoundIP,aDevice.uFoundHostName,aDevice.uFoundPort],aDevice)
        return

    def CreateDiscoverList_ShowDetails(self,instance):

        uText=  u"$lvar(5029): %s \n" \
                u"$lvar(6002): %s \n" \
                u"$lvar(5035): %s \n"\
                u"\n"\
                u"%s" % (instance.oDevice.sFoundIP,instance.oDevice.uFoundPort,instance.oDevice.uFoundHostName,instance.oDevice.sData)

        ShowMessagePopUp(uMessage=uText)


    def Discover(self,**kwargs):

        self.oReq.clear()
        uConfigName              = kwargs.get('configname',self.uConfigName)
        oSetting                 = self.GetSettingObjectForConfigName(uConfigName=uConfigName)
        self.oReq.bReturnPort    = ToBool(kwargs.get('returnport',"0"))
        fTimeOut                 = ToFloat(kwargs.get('timeout',oSetting.aScriptIniSettings.fTimeOut))
        uIPVersion               = kwargs.get('ipversion',"IPv4Only")
        bOnlyOnce                = ToBool(kwargs.get('onlyonce',"1"))

        Logger.debug (u'Try to discover device by Kira Discovery (%s)' % uIPVersion)

        del self.aResults[:]
        del self.aThreads[:]

        try:
            oThread = None
            if uIPVersion == "IPv4Only" or uIPVersion == "All" or (uIPVersion == "Auto" and Globals.uIPAddressV6 == ""):
                oThread = cThread_Discover_Kira(bOnlyOnce=bOnlyOnce,oReq=self.oReq,uIPVersion="IPv4Only", fTimeOut=fTimeOut, oCaller=self)
                self.aThreads.append(oThread)
                self.aThreads[-1].start()
            if uIPVersion == "IPv6Only" or uIPVersion == "All" or (uIPVersion == "Auto" and Globals.uIPAddressV6 != ""):
                oThread = cThread_Discover_Kira(bOnlyOnce=bOnlyOnce, oReq=self.oReq, uIPVersion="IPv6Only", fTimeOut=fTimeOut, oCaller=self)
                self.aThreads.append(oThread)
                self.aThreads[-1].start()

            for oT in self.aThreads:
                oT.join()

            if len(self.aResults)>0:
                return {"Host":self.aResults[0].sFoundIP,
                        "Hostname": self.aResults[0].uFoundHostName,
                        'Exception': None}
            else:
                Logger.warning(u'Kira Discover: No device found' )
            return {"Host": "",
                    "Hostname": "",
                    'Exception': None}

        except Exception as e:
            LogError(u'Error on discover uPnP',e)
            return {"Host": "",
                    "Hostname": "",
                    'Exception': e}

    @classmethod
    def GetConfigJSONforParameters(cls,dDefaults):
        return  {"Name":            {"type": "string",       "order":0,  "title": "$lvar(6013)", "desc": "$lvar(6014)", "key": "name",            "default":""           },
                 "IP Version":      {"type": "scrolloptions","order":4,  "title": "$lvar(6037)", "desc": "$lvar(6038)", "key": "ipversion",       "default":"IPv4Only", "options":["IPv4Only","IPv6Only","All","Auto"]},
                 "TimeOut":         {"type": "numericfloat", "order":6,  "title": "$lvar(6019)", "desc": "$lvar(6020)", "key": "timeout",         "default":"15.0"}
                }
Esempio n. 14
0
    def _ELV_getroomdevices(self, oSetting, oAction, dParams,
                            bAddRoom):  #check
        """
        Internal Helper function to get a list of devices of a room

        :param cInterface.cInterFaceSettings oSetting: The setting object
        :param cAction oAction: The action object (unused)
        :param dict dParams: The parameter, needs to include room
        :param boolean bAddRoom: Flag to include the room name as first element
        :return: list: A list of dicts: key:name=room name , rf_address= Rf Address of Room
        :rtype: list
        """

        aRet = []
        i = 0
        uRoom = ReplaceVars(dParams["room"],
                            self.uInterFaceName + u'/' + oSetting.uConfigName)

        aTmpDestVar = ToList(oAction.uGlobalDestVar)
        for uVarName in aTmpDestVar:
            Var_DelArray(uVarName=uVarName + u'[]')

        for oRoom in oSetting.oDevice.rooms:
            if oRoom.name == uRoom:
                if bAddRoom:
                    dLine = QueryDict()
                    dLine.uVarSuffix = "[" + str(i) + "]"
                    dLine.dValue = {}
                    uRfAddress = str(oRoom.rf_address)
                    dLine.dValue = {
                        "name": oRoom.name,
                        "rf_address": uRfAddress
                    }
                    aRet.append(dLine)
                    i = i + 1

                for oDevice in oSetting.oDevice.devices_by_room(oRoom):
                    dLine = QueryDict()
                    dLine.uVarSuffix = "[" + str(i) + "]"
                    uRfAddress = str(oDevice.rf_address)
                    dLine.dValue = {}
                    dLine.dValue["name"] = oDevice.name
                    dLine.dValue["rf_address"] = str(uRfAddress)
                    aRet.append(dLine)
                    i = i + 1
                break
        return aRet
Esempio n. 15
0
class cScript(cDiscoverScriptTemplate):
    """
    WikiDoc:Doc
    WikiDoc:Context:Scripts
    WikiDoc:Page:Scripts-Discover-EISCP
    WikiDoc:TOCTitle:Discover EISCP
    = Script Discover EISCP =

    The EISCP discover script discover ONKYO devices which supports the EISCP protocol.
    You can filter the discover result by passing the following parameters::
    <div style="overflow:auto; ">
    {| class="wikitable"
    ! align="left" | Attribute
    ! align="left" | Description
    |-
    |models
    |Discover only specific Onkyo models
    |-
    |timeout
    |Specifies the timout for discover
    |}</div>

    Blank options will not be used.

    WikiDoc:End
    """
    class cScriptSettings(cBaseScriptSettings):
        def __init__(self, oScript):
            cBaseScriptSettings.__init__(self, oScript)
            self.aScriptIniSettings.fTimeOut = 10.0

    def __init__(self):
        cDiscoverScriptTemplate.__init__(self)
        self.uSubType = u'EISCP (Onkyo)'
        self.aResults = []
        self.aThreads = []
        self.oReq = QueryDict()
        self.bOnlyOnce = True
        self.uIPVersion = "Auto"

    def Init(self, uScriptName, uScriptFile=u''):
        """
        Init function for the script

        :param string uScriptName: The name of the script (to be passed to all scripts)
        :param uScriptFile: The file of the script (to be passed to all scripts)
        """

        cDiscoverScriptTemplate.Init(self, uScriptName, uScriptFile)
        self.oScriptConfig.dDefaultSettings['TimeOut']['active'] = "enabled"

    def GetHeaderLabels(self):
        return ['$lvar(5029)', '$lvar(6002)', '$lvar(5031)', '$lvar(5032)']

    def ListDiscover(self):
        dArgs = {}
        dArgs["onlyonce"] = 0
        dArgs["ipversion"] = "All"
        aDevices = {}

        self.Discover(**dArgs)

        for aDevice in self.aResults:
            uTageLine = aDevice.sFoundIP + aDevice.uFoundModel + aDevice.uFoundIdentifier
            if aDevices.get(uTageLine) is None:
                aDevices[uTageLine] = aDevice
                self.AddLine([
                    aDevice.sFoundIP, aDevice.uFoundPort, aDevice.uFoundModel,
                    aDevice.uFoundIdentifier
                ], aDevice)
        return

    def CreateDiscoverList_ShowDetails(self, instance):
        uText=  u"$lvar(5029): %s \n"\
                u"$lvar(6002): %s \n"\
                u"$lvar(5031): %s \n"\
                u"$lvar(5032): %s \n"\
                u"\n"\
                u"%s" % (instance.oDevice.sFoundIP,instance.oDevice.uFoundPort,instance.oDevice.uFoundModel,instance.oDevice.uFoundIdentifier,instance.oDevice.sData)

        ShowMessagePopUp(uMessage=uText)

    def Discover(self, **kwargs):

        self.oReq.clear()
        uConfigName = kwargs.get('configname', self.uConfigName)
        oSetting = self.GetSettingObjectForConfigName(uConfigName=uConfigName)
        fTimeOut = ToFloat(
            kwargs.get('timeout', oSetting.aScriptIniSettings.fTimeOut))
        self.oReq.uModels = kwargs.get('models', "")
        bOnlyOnce = ToBool(kwargs.get('onlyonce', "1"))
        uIPVersion = kwargs.get('ipversion', "IPv4Only")

        Logger.debug(u'Try to discover Onkyo device by EISCP:  Models: %s ' %
                     self.oReq.uModels)

        del self.aResults[:]
        del self.aThreads[:]

        try:
            oThread = None
            if uIPVersion == "IPv4Only" or uIPVersion == "All" or (
                    uIPVersion == "Auto" and Globals.uIPAddressV6 == ""):
                oThread = cThread_Discover_EISCP(bOnlyOnce=bOnlyOnce,
                                                 oReq=self.oReq,
                                                 uIPVersion="IPv4Only",
                                                 fTimeOut=fTimeOut,
                                                 oCaller=self)
                self.aThreads.append(oThread)
                self.aThreads[-1].start()
            if uIPVersion == "IPv6Only" or uIPVersion == "All" or (
                    uIPVersion == "Auto" and Globals.uIPAddressV6 != ""):
                oThread = cThread_Discover_EISCP(bOnlyOnce=bOnlyOnce,
                                                 oReq=self.oReq,
                                                 uIPVersion="IPv6Only",
                                                 fTimeOut=fTimeOut,
                                                 oCaller=self)
                self.aThreads.append(oThread)
                self.aThreads[-1].start()

            for oT in self.aThreads:
                oT.join()

            if len(self.aResults) > 0:
                return {
                    'Model': self.aResults[0].uFoundModel,
                    'Host': self.aResults[0].sFoundIP,
                    'Port': self.aResults[0].uFoundPort,
                    'Category': self.aResults[0].uFoundCategory,
                    'Exception': None
                }
            else:
                Logger.warning(u'No device found Models: %s' %
                               self.oReq.uModels)
            return {
                'Model': '',
                'Host': '',
                'Port': '',
                'Category': '',
                'Exception': None
            }

        except Exception as e:
            Logger.debug(u'No EISCP device found, possible timeout')
            return {
                'Model': '',
                'Host': '',
                'Port': '',
                'Category': '',
                'Exception': e
            }

    @classmethod
    def GetConfigJSONforParameters(cls, dDefaults):
        return {
            "TimeOut": {
                "type": "numericfloat",
                "active": "enabled",
                "order": 0,
                "title": "$lvar(6019)",
                "desc": "$lvar(6020)",
                "key": "timeout",
                "default": "2.0"
            },
            "Models": {
                "type": "string",
                "active": "enabled",
                "order": 1,
                "title": "$lvar(SCRIPT_DISC_EISCP_1)",
                "desc": "$lvar(SCRIPT_DISC_EISCP_2)",
                "key": "models",
                "default": ""
            },
            "IP Version": {
                "type": "scrolloptions",
                "order": 4,
                "title": "$lvar(6037)",
                "desc": "$lvar(6038)",
                "key": "ipversion",
                "default": "IPv4Only",
                "options": ["IPv4Only", "IPv6Only", "All", "Auto"]
            }
        }
Esempio n. 16
0
    def GetDeviceDetails(self, sData, tSenderAddr):
        oRet = QueryDict()
        oRet.bFound = False
        oRet.sFoundIP = ""
        oRet.uFoundPort = ""
        oRet.uFoundModel = ""
        oRet.uFoundIdentifier = ""
        oRet.uFoundCategory = ""
        oRet.sData = ""

        if PY2:
            uResponse = sData[16:]
        else:
            uResponse = ToUnicode(sData)[16:]

        if uResponse.find('ECN') != -1:
            info = re.match(self.rMatch, uResponse.strip(),
                            re.VERBOSE).groupdict()
            uResponse = uResponse[10:]
            oRet.sFoundIP = tSenderAddr[0]
            oRet.uFoundPort = ToUnicode(info['iscp_port'])
            oRet.uFoundModel = info['model_name']
            oRet.uFoundIdentifier = info['identifier']
            oRet.uFoundCategory = ToUnicode(info['device_category'])
            oRet.sData = uResponse
            oRet.bFound = True
        return oRet