Exemplo n.º 1
0
def ToDic(uString):
    """
    converts a (unicode) string into a dict

    :rtype: dict
    :param string uString: The string representation of a dict
    :return: The dict
    """
    if isinstance(uString, dict):
        return uString
    if uString == u'':
        return {}

    try:
        if uString.startswith(u'{'):
            uRet = json.loads(uString)
        else:
            uRet = ast.literal_eval(uString)

        if not isinstance(uRet, dict):
            LogError(u'ToDic: can\'t convert string to dic:' + uString)
        return uRet

    except Exception as e:
        LogErrorSmall(u'ToDic: Dictionary Convert error', e)
        LogErrorSmall(uString)
    return uString
Exemplo n.º 2
0
    def DumpStatus(self, **kwargs) -> None:
        """ Dumps the lights and groups status into varsvars """
        try:
            vResult = kwargs['result']
            if isinstance(vResult, str):
                vResult = ToDic(ReplaceVars(vResult))

            dResult: Dict = vResult
            self.dStatus = dResult
            uPrefix: str = kwargs.get('retvar', '')
            if uPrefix == '':
                oAction: cAction = kwargs['oAction']
                if oAction is not None:
                    uPrefix = oAction.uRetVar
            dLights: Dict = dResult['lights']
            dGroups: Dict = dResult['groups']

            # Vars for Lights & Groups in one list
            iIndex: int = 0
            for uLightKey in dLights:
                self.DumpSingleLight(iIndex, uLightKey, dLights[uLightKey],
                                     uPrefix, "Light")
                iIndex += 1
            for uGroupKey in dGroups:
                self.DumpSingleLight(iIndex, uGroupKey, dGroups[uGroupKey],
                                     uPrefix, "Group")
                iIndex += 1
            return None
        except Exception as e:
            LogErrorSmall(uMsg="DumpStatus: Error parsing HUE Bridge response",
                          oException=e)
            return None
Exemplo n.º 3
0
    def DumpGroup(self, **kwargs) -> None:
        """ Dumps a specific light status set into customs vars """
        try:
            vResult = kwargs['result']
            if isinstance(vResult, str):
                vResult = ToDic(ReplaceVars(vResult))

            dResult: Dict = vResult
            uPrefix: str = kwargs.get('retvar', '')
            uLightKey: str = kwargs.get('index', '')
            if uPrefix == '':
                oAction: cAction = kwargs['oAction']
                if oAction is not None:
                    uPrefix = oAction.uRetVar

            self.DumpSingleLight(iID=-1,
                                 uLightKey=uLightKey,
                                 dLight=dResult,
                                 uPrefix=uPrefix,
                                 uType=u'Group')
            return None
        except Exception as e:
            LogErrorSmall(uMsg="DumpGroup: Error parsing HUE Bridge response",
                          oException=e)
            return None
Exemplo n.º 4
0
    def RunScript(self, *args, **kwargs) -> Union[Dict, None]:
        """ Main Entry point, parses the cmd_type and calls the relevant functions """
        try:
            if 'cmd_type' in kwargs:
                uCmdType = kwargs['cmd_type']
                if uCmdType == u'evaluate_status':
                    self.DumpStatus(**kwargs)
                    return None
                if uCmdType == u'evaluate_light':
                    self.DumpLight(**kwargs)
                    return None
                if uCmdType == u'evaluate_group':
                    self.DumpGroup(**kwargs)
                    return None
                if uCmdType == u'RGB2XY':
                    self.RGB2XY(**kwargs)
                    return None
                if uCmdType == u'XY2RGB':
                    self.XY2RGB(**kwargs)
                    return None

            return None
        except Exception as e:
            LogErrorSmall(
                uMsg="Can't run Hue Helper script, invalid parameter",
                oException=e)
            return None
Exemplo n.º 5
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)
Exemplo n.º 6
0
    def ShowError(self,uMsg,oException=None):
        """ creates a error debug line """
        iErrNo = 0
        if oException is not None:
            if hasattr(oException,'errno'):
                iErrNo=oException.errno
        if iErrNo is None:
            iErrNo=12345

        uRet=LogErrorSmall (u'Script '+self.uScriptName+u': '+ uMsg + " (%d) " % (iErrNo),oException)
        return uRet
Exemplo n.º 7
0
    def Discover(self, **kwargs):

        uConfigName = kwargs.get('configname', self.uConfigName)
        oSetting = self.GetSettingObjectForConfigName(uConfigName=uConfigName)
        fTimeOut = ToFloat(
            kwargs.get('timeout', oSetting.aScriptIniSettings.fTimeOut))
        bOnlyOnce = ToBool(kwargs.get('onlyonce', "1"))

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

        uIPSubNet = Globals.uIPGateWayAssumedV4
        uIPSubNet = uIPSubNet[:uIPSubNet.rfind(".")] + "."

        for i in range(154, 155):
            uIP = uIPSubNet + str(i)
            oThread = cThread_CheckIP(uIP=uIP,
                                      bOnlyOnce=bOnlyOnce,
                                      fTimeOut=fTimeOut,
                                      oCaller=self)
            self.aThreads.append(oThread)
            oThread.start()

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

        if len(self.aResults):
            uHost = self.aResults[0]["ip"]
            uPort = self.aResults[0]["port"]
            uModel = self.aResults[0]["model"]
            uHostName = self.aResults[0]["hostname"]
            uIPVersion = self.aResults[0]["ipversion"]
            return {
                'Host': uHost,
                'Port': uPort,
                'Model': uModel,
                'Hostname': uHostName,
                "IPVersion": uIPVersion,
                'Exception': None
            }

        LogErrorSmall(
            "Enigma-Discover: Could not find a Enigma Receiver on the network")
        return {
            'Host': '',
            'Port': '',
            'Model': '',
            'Hostname': '',
            "IPVersion": '',
            'Exception': None
        }
Exemplo n.º 8
0
    def DumpGroup(self, **kwargs):
        """ Dumps a spezific light status set into customs vars """
        try:
            dResult = kwargs['result']
            uPrefix = kwargs.get('retvar', '')
            uLightKey = kwargs.get('index', '')
            if uPrefix == '':
                oAction = kwargs['oAction']
                if oAction is not None:
                    uPrefix = oAction.uRetVar

            self.DumpSingleLight(-1, uLightKey, dResult, uPrefix, u'Group')
        except Exception as e:
            LogErrorSmall("DumpGroup: Error parsing HUE Bridge response", e)
        return 0
Exemplo n.º 9
0
    def ShowError(self, uMsg, oException=None):
        """ Shows an error"""
        iErrNo = 0
        if oException is not None:
            if hasattr(oException, 'errno'):
                iErrNo = oException.errno
        if iErrNo is None:
            iErrNo = -1

        uRet = LogErrorSmall(
            u'Script %s/%s %s (%d):' %
            (self.oScript.uScriptName, self.uConfigName, uMsg, iErrNo),
            oException)

        return uRet
Exemplo n.º 10
0
    def ShowError(self, *, uMsg: str, oException: Exception = None) -> str:
        """ Shows an error"""
        iErrNo: int = 0
        if oException is not None:
            if hasattr(oException, 'errno'):
                iErrNo = ToInt(oException.errno)
        if iErrNo is None:
            iErrNo = -1

        uRet: str = LogErrorSmall(
            uMsg=u'%s %s/%s %s (%d):' %
            (self.uType.capitalize(), self.oObject.uObjectName,
             self.uConfigName, uMsg, iErrNo),
            oException=oException)

        return uRet
Exemplo n.º 11
0
    def XY2RGB(self, **kwargs) -> None:
        """ Converts HUE xy to rgb and dumps it into vars """
        try:
            r: float
            g: float
            b: float
            fX: float
            fY: float

            fX = ToFloat(kwargs.get('x', 1.0))
            fY = ToFloat(kwargs.get('y', 1.0))
            uPrefix = kwargs.get('retvar', '')
            uLightKey = kwargs.get('index', '')
            uType = kwargs.get('type', 'Light')
            if uType == "Group":
                uType = "groups"
            else:
                uType = "lights"
            tGammut: Tuple = self._GetGamut(self.dStatus[uType][uLightKey].get(
                'modelid', ""))
            oConverter = self.oHueConverter.Converter(tGammut)
            r, g, b = oConverter.xy_to_rgb(fX, fY)

            dStatusLight: Dict = self.dStatus.get(uLightKey, {})
            if len(dStatusLight) > 0:
                uType = dStatusLight["lightstype"]

            self.oResultParser.SetVar2(str(r),
                                       "",
                                       uPrefix,
                                       u'Storing R-Value',
                                       uAddName=u"_r")
            self.oResultParser.SetVar2(str(g),
                                       "",
                                       uPrefix,
                                       u'Storing G-Value',
                                       uAddName=u"_g")
            self.oResultParser.SetVar2(str(b),
                                       "",
                                       uPrefix,
                                       u'Storing B-Value',
                                       uAddName=u"_b")
            return None
        except Exception as e:
            LogErrorSmall(uMsg="XY2RGB: Error parsing parameter", oException=e)
            return None
Exemplo n.º 12
0
    def DumpStatus(self, **kwargs):
        """ Dumps the lights and groups status into varsvars """
        try:
            dResult = kwargs['result']
            self.dStatus = dResult
            uPrefix = kwargs.get('retvar', '')
            if uPrefix == '':
                oAction = kwargs['oAction']
                if oAction is not None:
                    uPrefix = oAction.uRetVar
            dLights = dResult['lights']
            dGroups = dResult['groups']
            '''
            # Vars for Lights only
            iIndex=0
            for uLightKey in dLights:
                self.DumpSingleLight(iIndex,uLightKey,dLights[uLightKey],uPrefix,"Light")
                iIndex+=1

            # Vars for Groups only
            dGroups = dResult['groups']
            iIndex=0
            for uGroupKey in dGroups:
                self.DumpSingleLight(iIndex,uGroupKey,dGroups[uGroupKey],uPrefix,"Group")
                iIndex+=1
            '''

            # Vars for Lights & Groups in one list
            iIndex = 0
            for uLightKey in dLights:
                self.DumpSingleLight(iIndex, uLightKey, dLights[uLightKey],
                                     uPrefix, "Light")
                iIndex += 1
            for uGroupKey in dGroups:
                self.DumpSingleLight(iIndex, uGroupKey, dGroups[uGroupKey],
                                     uPrefix, "Group")
                iIndex += 1
        except Exception as e:
            LogErrorSmall("DumpStatus: Error parsing HUE Bridge response", e)
        return 0
Exemplo n.º 13
0
    def RGB2XY(self, **kwargs) -> None:
        """ Converts rgb values to hue xy and dumps it into vars """
        try:
            fR: float = ToFloat(ReplaceVars(kwargs.get('r', 1.0)))
            fG: float = ToFloat(ReplaceVars(kwargs.get('g', 1.0)))
            fB: float = ToFloat(ReplaceVars(kwargs.get('b', 1.0)))
            uPrefix: str = ReplaceVars(kwargs.get('retvar', ''))
            uLightKey: str = ReplaceVars(kwargs.get('index', ''))
            uType: str = ReplaceVars(kwargs.get('type', 'Light'))
            if uType == "Group":
                uType = "groups"
            else:
                uType = "lights"

            tGammut: Tuple = self._GetGamut(self.dStatus[uType][uLightKey].get(
                'modelid', ""))
            oConverter = self.oHueConverter.Converter(tGammut)
            x, y = oConverter.rgb_to_xy(fR, fG, fB)
            if uPrefix == '':
                oAction = kwargs['oAction']
                if oAction is not None:
                    uPrefix = oAction.uRetVar

            self.oResultParser.SetVar2(str(x),
                                       "",
                                       uPrefix,
                                       u'Storing X-Value',
                                       uAddName=u"_x")
            self.oResultParser.SetVar2(str(y),
                                       "",
                                       uPrefix,
                                       u'Storing Y-Value',
                                       uAddName=u"_y")
            return None
        except Exception as e:
            LogErrorSmall(uMsg="RGB2XY: Error parsing parameter", oException=e)
            return None
Exemplo n.º 14
0
    def DumpSingleLight(self, iID: int, uLightKey: str, dLight: Dict,
                        uPrefix: str, uType: str) -> None:
        """ Helper function to dump a light/group into vars """

        try:

            uIndex: str = u""
            uOnTag: str = u"on"
            uDetailsTag: str = u"state"

            r: float = 1.0
            g: float = 1.0
            b: float = 1.0
            x: float = 1.0
            y: float = 1.0
            bri: float = 1.0

            if iID >= 0:
                uIndex = u"[" + str(iID) + u"]"

            if uType == u"Group":
                uOnTag = u"all_on"
                uDetailsTag = "action"

            # Some devices return just single values (Philips is really bad!)
            x = dLight[uDetailsTag].get('xy', (1.0, 1.0))[0]
            y = dLight[uDetailsTag].get('xy', (1.0, 1.0))[1]

            uOn = str(dLight['state'][uOnTag])

            bri = dLight[uDetailsTag].get('bri', -1.0)
            if bri == -1.0:
                if uOn == "true":
                    bri = 254
                else:
                    bri = 0

            dLight["lightstype"] = uType
            self.oResultParser.SetVar2(uLightKey,
                                       "",
                                       uPrefix,
                                       u'Storing Light Configuration',
                                       uAddName=u"_index" + uIndex)
            self.oResultParser.SetVar2(uType,
                                       "",
                                       uPrefix,
                                       u'Storing Light Configuration',
                                       uAddName=u"_category" + uIndex)
            self.oResultParser.SetVar2(dLight['name'],
                                       "",
                                       uPrefix,
                                       u'Storing Light Configuration',
                                       uAddName=u"_name" + uIndex)
            self.oResultParser.SetVar2(str(dLight['state'][uOnTag]),
                                       "",
                                       uPrefix,
                                       u'Storing Light Configuration',
                                       uAddName=u"_on" + uIndex)
            self.oResultParser.SetVar2(dLight[uDetailsTag].get(
                'colormode', "none"),
                                       "",
                                       uPrefix,
                                       u'Storing Light Configuration',
                                       uAddName=u"_colormode" + uIndex)
            self.oResultParser.SetVar2(str(bri),
                                       "",
                                       uPrefix,
                                       u'Storing Light Configuration',
                                       uAddName=u"_bri" + uIndex)
            self.oResultParser.SetVar2(str(dLight[uDetailsTag].get('ct', 0)),
                                       "",
                                       uPrefix,
                                       u'Storing Light Configuration',
                                       uAddName=u"_ct" + uIndex)
            self.oResultParser.SetVar2(str(dLight[uDetailsTag].get('hue', 0)),
                                       "",
                                       uPrefix,
                                       u'Storing Light Configuration',
                                       uAddName=u"_hue" + uIndex)
            self.oResultParser.SetVar2(str(dLight[uDetailsTag].get('hs', 0)),
                                       "",
                                       uPrefix,
                                       u'Storing Light Configuration',
                                       uAddName=u"_hs" + uIndex)
            self.oResultParser.SetVar2(dLight[uDetailsTag].get(
                'effect', "none"),
                                       "",
                                       uPrefix,
                                       u'Storing Light Configuration',
                                       uAddName=u"_effect" + uIndex)
            self.oResultParser.SetVar2(str(x),
                                       "",
                                       uPrefix,
                                       u'Storing Light Configuration',
                                       uAddName=u"_x" + uIndex)
            self.oResultParser.SetVar2(str(y),
                                       "",
                                       uPrefix,
                                       u'Storing Light Configuration',
                                       uAddName=u"_y" + uIndex)
            self.oResultParser.SetVar2(str(dLight[uDetailsTag].get('sat', 0)),
                                       "",
                                       uPrefix,
                                       u'Storing Light Configuration',
                                       uAddName=u"_sat" + uIndex)
            self.oResultParser.SetVar2(dLight.get('manufacturername', ""),
                                       "",
                                       uPrefix,
                                       u'Storing Light Configuration',
                                       uAddName=u"_manufacturername" + uIndex)
            self.oResultParser.SetVar2(dLight['type'],
                                       "",
                                       uPrefix,
                                       u'Storing Light Configuration',
                                       uAddName=u"_type" + uIndex)
            self.oResultParser.SetVar2(dLight.get('modelid', ""),
                                       "",
                                       uPrefix,
                                       u'Storing Light Configuration',
                                       uAddName=u"_modelid" + uIndex)
            self.oResultParser.SetVar2(str(dLight['state'].get(
                'any_on', "true")),
                                       "",
                                       uPrefix,
                                       u'Storing Group Configuration',
                                       uAddName=u"_all_on" + uIndex)
            self.oResultParser.SetVar2(dLight['state'].get('class', 'unknown'),
                                       "",
                                       uPrefix,
                                       u'Storing Group Configuration',
                                       uAddName=u"_class" + uIndex)

            if x != 0.0 or y != 0.0:
                tGammut = self._GetGamut(dLight.get('modelid', ""))
                oConverter = self.oHueConverter.Converter(tGammut)
                r, g, b = oConverter.xy_to_rgb(x, y, bri)
            self.oResultParser.SetVar2(str(r),
                                       "",
                                       uPrefix,
                                       u'Storing Light Configuration',
                                       uAddName=u"_r" + uIndex)
            self.oResultParser.SetVar2(str(g),
                                       "",
                                       uPrefix,
                                       u'Storing Light Configuration',
                                       uAddName=u"_g" + uIndex)
            self.oResultParser.SetVar2(str(b),
                                       "",
                                       uPrefix,
                                       u'Storing Light Configuration',
                                       uAddName=u"_b" + uIndex)
            return None
        except Exception as e:
            LogErrorSmall(
                uMsg=
                "Error parsing HUE Bridge response for single light/group of status",
                oException=e)
            return None
Exemplo n.º 15
0
def ToDic(uString: Union[str, Dict]) -> Dict:
    """
    converts a (unicode) string into a dict

    :rtype: dict
    :param uString: The string representation of a dict
    :return: The dict
    """
    """  
    This is complex by purpose, as we might face "invalid" dic strings, from devices or by the system
    eg quotes/double quotes 
    eg backslashes in windows paths
    So i try different tools 
    """

    dRet: Dict[Any, Any]
    uString2: str
    bDoubleBack: bool = False

    if isinstance(uString, dict):
        return uString

    if uString == u'' or uString == "{}":
        return {}

    if "\\" in uString:
        uString2 = uString.replace("\\", "***BaCkSlAsH***")
        bDoubleBack = True
    else:
        uString2 = cast(str, uString)

    try:
        for i in range(2):
            if i == 1:
                uString2 = uString2.replace("\'", "\"")

            try:
                dRet = cast(Dict[Any, Any], json.loads(uString2))
                if bDoubleBack:
                    DictUnescaceBackslash(dRet)
                return dRet
            except Exception:
                pass

            try:
                dRet = cast(Dict[Any, Any], demjson.decode(uString2))
                if bDoubleBack:
                    DictUnescaceBackslash(dRet)
                return dRet
            except Exception:
                pass

            try:
                dRet = ast.literal_eval(uString2)
                if bDoubleBack:
                    DictUnescaceBackslash(dRet)
                return dRet
            except Exception:
                pass

        LogError(uMsg=u'ToDic: can\'t convert string to dic:' + uString)
        return {}

    except Exception as e:
        LogErrorSmall(uMsg=u'ToDic: Dictionary Convert error', oException=e)
        LogErrorSmall(uMsg=uString)
    return {}