예제 #1
0
파일: Queue.py 프로젝트: thica/ORCA-Remote
    def WorkOnQueueDoAction(self, *,
                            oAction: cAction) -> Union[eReturnCode, int]:
        """ Executes a single action in a queue (including condition verifying)"""

        eRet: eReturnCode = eReturnCode.Success
        bCheckSuccess: bool = CheckCondition(oPar=oAction)

        if oAction.iActionId == Globals.oActions.oActionType.If:
            # we do the If statement only in case of the condition fails
            if bCheckSuccess:
                Globals.oEvents.LogAction(uTxt="if",
                                          oAction=oAction,
                                          uAddText="executing actions")
            # we need to run the if command in any way to skip the actions
            bCheckSuccess = not bCheckSuccess

        if bCheckSuccess:
            #We set / replace Action Command Pars by Definition/Button pars
            eRet = self.ExecuteAction(oAction=oAction)
            if eRet != eReturnCode.Nothing:
                SetVar(uVarName=u'LASTERRORCODE', oVarValue=ToUnicode(eRet))
                if eRet != eReturnCode.Success:
                    Logger.debug("Action returned LASTERRORCODE " +
                                 ToUnicode(eRet))
        return eRet
예제 #2
0
def ReplaceVars(uOrgIn: str, uContext: str = u'') -> str:
    """
    Replaces all occurences of $var(xxx) and $lvar(lll) with the uservars or language vars, with name xxx/lll.
    Multiple var placeholder can be given in on string in any combination.
    Nested var placeholder "$var($var(xxx)) are not allowed.
    A warning will be given if the variable name does not exist

    :param str uOrgIn: The string, where the variable placeholer should be replaced
    :param str uContext: The context for the var, default empty. This should be the same context as given in SetVar
    :return: The string with replaced variables or the orginal string, if not variables are defined
    """
    uTmp: str = ""

    if uOrgIn is None:
        return ""

    try:
        uTmp = re.sub(rPatternVar, _VarReplace, uOrgIn)
        uTmp = re.sub(rPatternLVar, _LanguageVarReplace, uTmp)
        if uContext != "":
            ORCA.vars.Globals.uRepContext = uContext
            uTmp = re.sub(rPatternCVar, _ContextVarReplace, uOrgIn)

    except Exception as e:
        if "$var(" in uOrgIn or "$lvar(" in uOrgIn:
            LogError(uMsg=u'Vars: ReplaceVars: Runtime Error:' +
                     ToUnicode(uOrgIn) + u':',
                     oException=e)
        else:
            uTmp = uOrgIn

    return ToUnicode(uTmp)
예제 #3
0
파일: IRDB.py 프로젝트: thica/ORCA-Remote
    def ConvertItach2CCF(self) -> None:
        #todo : remove when we know, it is not used anymore
        oXMLCode: Element
        uFile: str
        uCmd: str
        uRepeat: str
        uFileName: str
        uFinal: str
        aFiles: List[str] = Globals.oPathCodesets.GetFolderList()
        aFiles2: List[str] = []
        for uFile in aFiles:
            if uFile.startswith("CODESET_iTach_"):
                aFiles2.append(uFile)

        for uFile in aFiles2:
            oFile: cFileName = cFileName(Globals.oPathCodesets) + uFile
            oXMLCodeset: Element = LoadXMLFile(oFile=oFile)
            oXMLCodes: List[Element] = oXMLCodeset.findall('code')
            for oXMLCode in oXMLCodes:
                uCmd = GetXMLTextAttribute(oXMLNode=oXMLCode,
                                           uTag="cmd",
                                           bMandatory=False,
                                           vDefault="")
                if uCmd.startswith("sendir,"):
                    uRepeat, uCmd = ITach2CCF(uCmd)
                    oXMLCode.set("cmd_ccf", uCmd)
                    oXMLCode.set("repeatcount", uRepeat)
                    del oXMLCode.attrib["cmd"]
            uFileName = oFile.string.replace("_iTach_", "_infrared_ccf_")
            uFinal = ToUnicode(XMLPrettify(oElem=oXMLCodeset))
            uFinal = uFinal.replace(u'<?xml version="1.0"?>',
                                    u'<?xml version="1.0" encoding="UTF-8"?>')
            with codecs.open(uFileName, 'w', 'utf-8') as oOutfile:
                oOutfile.write(uFinal)
예제 #4
0
    def ConvertItach2CCF(self):
        #todo : remove when we know, it is not used anymore
        from ORCA.utils.XML import GetXMLTextAttribute
        import codecs
        aFiles = Globals.oPathCodesets.GetFolderList()
        aFiles2 = []
        for uFile in aFiles:
            if uFile.startswith("CODESET_iTach_"):
                aFiles2.append(uFile)

        for uFile in aFiles2:
            oFile = cFileName(Globals.oPathCodesets) + uFile
            oXMLCodeset = ElementTree(file=oFile.string).getroot()
            oXMLCodes = oXMLCodeset.findall('code')
            for oXMLCode in oXMLCodes:
                uCmd = GetXMLTextAttribute(oXMLCode, "cmd", False, "")
                if uCmd.startswith("sendir,"):
                    uRepeat, uCmd = ITach2CCF(uCmd)
                    oXMLCode.set("cmd_ccf", uCmd)
                    oXMLCode.set("repeatcount", uRepeat)
                    del oXMLCode.attrib["cmd"]
            uFileName = oFile.string.replace("_iTach_", "_infrared_ccf_")
            uFinal = ToUnicode(XMLPrettify(oXMLCodeset))
            uFinal = uFinal.replace(u'<?xml version="1.0"?>',
                                    u'<?xml version="1.0" encoding="UTF-8"?>')
            with codecs.open(uFileName, 'w', 'utf-8') as outfile:
                outfile.write(uFinal)
예제 #5
0
        def Receive(self) -> None:
            #Main Listening Thread to receice eiscp messages

            uResponses: str
            uResponse: str
            aResponses: List
            aActionTrigger: List[cBaseTrigger]

            #Loop until closed by external flag
            try:
                while not self.bStopThreadEvent:
                    if self.oSocket is not None:
                        ready: Tuple = select.select([self.oSocket], [], [],
                                                     1.0)
                        # the first element of the returned list is a list of readable sockets
                        if ready[0]:
                            byResponses = self.oSocket.recv(self.iBufferSize)
                            # there could be more than one response, so we need to split them
                            uResponses = ToUnicode(byResponses)
                            aResponses = uResponses.split("[EOL]")
                            for uResponse in aResponses:
                                # Todo: find proper encoding
                                if not uResponse == u'' and not uResponse == u'ORCA.ORCA Connecting...':
                                    if True:
                                        # If the returned Command is a response to the send message
                                        if uResponse.startswith(
                                                u'RemoteGhost.'):
                                            self.ShowDebug(
                                                uMsg=u'Returned Message:' +
                                                uResponse)
                                            #todo: parse the command from return
                                            # We do not need to wait for an response anymore
                                            StartWait(0)
                                            # we got our response, all other responses are for somebody else
                                            self.uMsg = u''
                                        else:
                                            # we have a notification issued by the device, so lets have a look, if we have a trigger assigned to it
                                            aActionTrigger = self.GetTrigger(
                                                uResponse)
                                            if len(aActionTrigger) > 0:
                                                for oActionTrigger in aActionTrigger:
                                                    self.CallTrigger(
                                                        oActionTrigger,
                                                        uResponse)
                                            else:
                                                self.ShowDebug(
                                                    uMsg=u'Discard message:' +
                                                    uResponse)

            except Exception as e:
                self.ShowError(uMsg=u'Error Receiving Response:', oException=e)
                self.bIsConnected = False
            try:
                if not self.oSocket is None:
                    self.ShowDebug(uMsg=u'Closing socket in Thread')
                    self.oSocket.close()
            except Exception as e:
                self.ShowError(uMsg=u'Error closing socket in Thread',
                               oException=e)
예제 #6
0
    def ParseFile(self, oFileName, iStartLine=0):
        """ parses a single file """

        i = 0

        if oFileName.string.endswith("__init__.py"):
            return self.oPages

        if iStartLine == 0:
            Logger.debug("Reading File:" + oFileName.string)
        try:
            if oFileName.Exists():
                uContent = ToUnicode(LoadFile(oFileName))
                aContent = uContent.split("\n")
                bFound = False
                for i, uLine in enumerate(aContent):
                    if i > iStartLine:
                        uLine = uLine.strip()
                        if uLine.startswith(u'WikiDoc:Doc'):
                            bFound = True
                        elif uLine.startswith(u'WikiDoc:End'):
                            bFound = False
                            self.oPages.append(self)
                            break
                        elif uLine.startswith("WikiDoc:Context:"):
                            uParts = uLine.split(":")
                            self.uContext = uParts[-1]
                        elif uLine.startswith("WikiDoc:Page:"):
                            uParts = uLine.split(":")
                            self.uPage = uParts[-1]
                            Logger.debug("Parsed Wikipage:" + self.uPage)
                        elif uLine.startswith("WikiDoc:TOCTitle:"):
                            uParts = uLine.split(":")
                            self.uTOCTitle = uParts[-1]
                        elif "'''" in uLine:
                            pass
                        elif '"""' in uLine:
                            pass
                        else:
                            if bFound:
                                self.uContent.append(uLine)
            else:
                LogError(u'cWikiDoc:Cant find file:' + oFileName.string)

            if len(self.oPages) > 0:
                oPage = cWikiPage()
                oPages = oPage.ParseFile(oFileName, i)
                if len(oPages) > 0:
                    self.oPages.extend(oPages)
            else:
                if iStartLine == 0:
                    Logger.warning("No Wikidoc entry in file:" +
                                   oFileName.string)
            return self.oPages
        except Exception as e:
            LogError(u'WikiDoc:Unexpected error reading file:', e)
            return []
예제 #7
0
 def UpdateVars(self) -> None:
     """ updates the destination vars """
     if not self.uDestVar == u'':
         SetVar(uVarName=self.uDestVar, oVarValue=ToUnicode(self.fValue))
         if self.oObject:
             SetVar(uVarName=self.uDestVar + u'_degree',
                    oVarValue=ToUnicode(self.oObject.iAngle))
             SetVar(uVarName=self.uDestVar + u'_direction',
                    oVarValue=ToUnicode(self.oObject.uDirection))
         SetVar(uVarName=self.uDestVar + u'_absdegree',
                oVarValue=ToUnicode(self.iAbsAngle))
예제 #8
0
    def _Parse_Dict(self, uResponse: Any, uGetVar: str,
                    uParseResultFlags: str) -> Tuple:
        """ parses the result as dict """
        uResult: str = u''
        aResult: List
        if not isinstance(uResponse, dict):
            uResponse = ToDic(uResponse)
        if isinstance(uResponse, dict):
            if "U" in uParseResultFlags:
                aResult = ParseDictAny(vObj=uResponse, uSearchKey=uGetVar)
            else:
                if "E" in uParseResultFlags:
                    dResult = ParseDictAll(vObj=uResponse, uPrefix="")
                    uLocalDestVar = self.uLocalDestVar
                    uGlobalDestVar = self.uGlobalDestVar
                    for uFoundKey, uValue in dResult.items():
                        if uLocalDestVar:
                            self.uLocalDestVar = uLocalDestVar + "%s" % uFoundKey
                        if uGlobalDestVar:
                            self.uGlobalDestVar = uGlobalDestVar + "%s" % uFoundKey
                        self._SetVar(uValue, u'Dictionary value')
                    self.uLocalDestVar = uLocalDestVar
                    self.uGlobalDestVar = uGlobalDestVar
                    aResult = []
                else:
                    aResult = ParseDictKeyTree(vObj=uResponse,
                                               aKeys=ToList(uGetVar))

            if aResult:
                if not "A" in uParseResultFlags:
                    uResult = ToUnicode(aResult[0])
                    self._SetVar(uResult, u'Dictionary value')
                else:
                    iIndex = 0
                    uLocalDestVar = self.uLocalDestVar
                    uGlobalDestVar = self.uGlobalDestVar
                    for uResult in aResult:
                        if uLocalDestVar:
                            self.uLocalDestVar = uLocalDestVar + "[%d]" % iIndex
                        if uGlobalDestVar:
                            self.uGlobalDestVar = uGlobalDestVar + "[%d]" % iIndex
                        self._SetVar(uResult, u'Dictionary value')
                        iIndex += 1
                    self.uLocalDestVar = uLocalDestVar
                    self.uGlobalDestVar = uGlobalDestVar
            else:
                self._SetVar(uResult, u'Dictionary value')
            return uGetVar, uResult
        else:
            self.ShowDebug(u'Warning: can'
                           't parse none dict as dict:' + ToUnicode(uResponse))
        return u'', u''
예제 #9
0
def Var_Find(uVarName, uFindVar, uDestVar):
    """
    Finds the posiion of a substring in a variable value.
    The changed variable value will be returned and stored in the destination var (Triggers raised if set)

    :rtype: string
    :param string uVarName: The variable name for the action, from where the value is pulled
    :param string uFindVar: The string to search for
    :param string uDestVar: The name of the variable for the result (the Position) If not found, '-1' will be returned
    :return: The position of the substring
    """

    uValue = GetVar(uVarName=uVarName)
    uValue = uVarName
    if uValue == u'':
        uValue = uVarName
    uValue = ReplaceVars(uValue)

    uFindVar = ReplaceVars(uFindVar)
    iPos = uValue.find(uFindVar)
    uResult = ToUnicode(iPos)
    SetVar(uVarName=uDestVar, oVarValue=uResult)
    Logger.debug(u'Var_Find: [%s] in [%s] returned [%s]  (stored in [%s])' %
                 (uFindVar, uValue, uResult, uDestVar))
    return uResult
예제 #10
0
    def ParseSingle(self,uResponse,uGetVar,uParseResultOption, uTokenizeString=u''):
        """ Parses a single result """

        if uParseResultOption == '':
            uParseResultOption = self.uGlobalParseResultOption

        if uParseResultOption == u'no' or uParseResultOption == u'':
            return u'',u''

        self.ShowDebug(u'Response: '+ToUnicode(uResponse))
        try:
            if uParseResultOption == u'store':
                return self._Parse_Store(uResponse,uGetVar)
            if uParseResultOption == u'json':
                return self._Parse_Json(uResponse,uGetVar)
            if uParseResultOption == u'tokenize':
                return self._Parse_Tokenize(uResponse,uGetVar,uTokenizeString)
            if uParseResultOption == u'xml':
                return self._Parse_XML(uResponse,uGetVar)
            if uParseResultOption == u'dict':
                return self._Parse_Dict(uResponse,uGetVar)
        except Exception as e:
            self.ShowError(u'can\'t Parse Result',oException=e)
            return u'',u''
        return u'',u''
예제 #11
0
    def ShowError(self,
                  *,
                  uMsg: str,
                  uParConfigName: str = u"",
                  uParAdd: str = u"",
                  oException: Exception = None) -> str:
        """
        writes an error message

        :param str uMsg: The error message
        :param str uParConfigName: The configuration name
        :param str uParAdd: The additional text
        :param exception oException: Optional, an exception to show
        :return: The written logfile entry
        """

        uRet: str = self._FormatShowMessage(uMsg=uMsg,
                                            uParConfigName=uParConfigName,
                                            uParAdd=uParAdd)
        iErrNo: int = 0
        if oException is not None:
            if hasattr(oException, 'errno'):
                iErrNo = ToInt(oException.errno)
        if iErrNo is None:
            iErrNo = 12345
        if iErrNo != 0:
            uRet = uRet + u" " + ToUnicode(iErrNo)
        uRet = LogError(uMsg=uRet, oException=oException)
        return uRet
예제 #12
0
    def Delete(self):
        """
        Deletes a folder (Needs to be inside the Orca folder structure)

        :rtype: bool
        :return: True, if successful
        """

        uPath = self.string

        if uPath == '':
            return False
        if uPath == '/':
            return False
        if uPath == '\\':
            return False
        if uPath.startswith('.'):
            return False

        try:
            rmtree(uPath, False)
            return True
        except Exception as e:
            uMsg = u'can\'t remove folder [%s]: %s  ' % (uPath, ToUnicode(e))
            Logger.warning(uMsg)
            return False
예제 #13
0
    def GetFileList(self, bSubDirs=False, bFullPath=False):
        """
        Returns a dict of all files in a folder

        :rtype: list
        :param bool bSubDirs: If true, includes files in folders
        :param bool bFullPath: If True, the file entries include the full folder struture, otherwise on the filename is returned
        :return: A list of all files
        """

        oDirList = []
        try:
            uRootDir = self.string
            for oItem in listdir(uRootDir):
                if not isdir(join(uRootDir, oItem)):
                    if not bFullPath:
                        oDirList.append(oItem)
                    else:
                        oDirList.append(AdjustPathToOs(uRootDir + '/' + oItem))
                else:
                    if bSubDirs:
                        oDirList.extend((cPath(uRootDir) + oItem).GetFileList(
                            bSubDirs, bFullPath))
        except Exception as e:
            uMsg = u'can\'t get File list:' + ToUnicode(e) + " :" + uRootDir
            Logger.warning(uMsg)

        return oDirList
예제 #14
0
 def On_Duration_Change(self,instance, value):
     """ Handle the change of the Duration """
     if self.oConnection:
         iDuration=int(value)
         if iDuration!=self.iOldDuration:
             self.iOldDuration = iDuration
             self.oConnection.Receive(u'duration:'+ToUnicode(iDuration))
예제 #15
0
 def On_Position_change(self,instance, value):
     """ Handles the change of the position """
     if self.oConnection:
         iPosition=int(value)
         if not iPosition==self.iOldPosition:
             self.iOldPosition = iPosition
             self.oConnection.Receive(u'position:'+ToUnicode(iPosition))
예제 #16
0
def ToAtlas(oFileName):
    """
    checks if a a picture is already availble in a atlas file

    :rtype: string
    :param cFileName oFileName:
    :return: Found FileName
    """
    uRetFileName = oFileName.string
    oFnSkinPic = Globals.oTheScreen.oSkin.dSkinPics.get(uRetFileName)
    if not oFnSkinPic is None:
        uRetFileName = oFnSkinPic.string

    if Globals.bIgnoreAtlas:
        return uRetFileName

    uKey = os.path.splitext(os.path.basename(uRetFileName))[0]

    if uRetFileName.startswith(Globals.oPathSkin.string):
        oFn = Globals.oFnAtlasSkin
    elif uRetFileName.startswith(
            Globals.oDefinitionPathes.oPathDefinition.string):
        oFn = Globals.oDefinitionPathes.oFnDefinitionAtlas
    else:
        return uRetFileName

    oAtlas = Cache.get('kv.atlas', oFn.string)

    if oAtlas:
        if not oAtlas.textures.get(uKey) is None:
            return ToUnicode(u'atlas://' + oFn.string + u'/' + uKey)

    return uRetFileName
예제 #17
0
def Config_GetDefault_Str(*, oConfig: ConfigParser, uSection: str,
                          uOption: str, vDefaultValue: Union[None, bool,
                                                             str]) -> str:
    """
    Replacement for the kivy function

    :param oConfig: The configparser object
    :param uSection: The name of the section
    :param uOption: The name of the option
    :param vDefaultValue: The default value
    :return: The value of an ini setting or the default value
    """
    uDefaultValue: str = u""

    if not oConfig.has_section(uSection):
        oConfig.add_section(uSection)
    if not oConfig.has_option(uSection, uOption):
        if vDefaultValue is not None:
            if type(vDefaultValue) == bool:
                if vDefaultValue:
                    uDefaultValue: str = u'1'
                else:
                    uDefaultValue: str = u'0'
            else:
                uDefaultValue = vDefaultValue
            oConfig.set(uSection, uOption, uDefaultValue)
        return uDefaultValue
    uRetVal: str = ToUnicode(oConfig.get(uSection, uOption))
    return uRetVal
예제 #18
0
파일: Access.py 프로젝트: thica/ORCA-Remote
def SetVarWithOutVarTranslation(uVarName:str, oVarValue:Any, uContext:str=u'') -> None:
    """
    Sets a specific variable with a given value.

    :param str uVarName: Variable name to use. This can't be a variable
    :param oVarValue: Value to set, usually a unicode string, can be any other object.
    If you pass a dict, then for each dict member a varname with its value will get assigned (the dict member names will be separed by an underscore)
    If you pass a list or tuple, then for each list member a varname with its value will get assigned as a array [x] where x starts with 0)
    :param str uContext: The context for the variable. Internally the context will be added as a prefix to the variable name
    """

    uRealVarName:str = uContext + uVarName

    if isinstance(oVarValue, str):
        _SetVarSub(uVarName = uRealVarName, oVarValue = oVarValue)
        return

    if type(oVarValue) == dict:
        for uKey in oVarValue:
            _SetVarSub(uVarName = uRealVarName + u'_' + uKey, oVarValue = oVarValue[uKey])
        return

    if type(oVarValue) == list or type(oVarValue) == tuple:
        i = 0
        for uValue in oVarValue:
            _SetVarSub(uVarName = uRealVarName + u'_[' + ToUnicode(i)+u']', oVarValue = oVarValue[uValue])
            i += 1
        return
    _SetVarSub(uVarName = uRealVarName, oVarValue = oVarValue)
예제 #19
0
파일: Path.py 프로젝트: thica/ORCA-Remote
    def GetFileList(self,*,bSubDirs:bool=False, bFullPath:bool=False) -> List:
        """
        Returns a dict of all files in a folder

        :param bool bSubDirs: If true, includes files in folders
        :param bool bFullPath: If True, the file entries include the full folder struture, otherwise on the filename is returned
        :return: A list of all files
        """

        oDirList:List = []
        uRootDir:str = self.string
        uItem:str
        try:
            for uItem in listdir(uRootDir):
                if not isdir(join(uRootDir, uItem)):
                    if not bFullPath:
                        oDirList.append(uItem)
                    else:
                        oDirList.append(AdjustPathToOs(uPath=uRootDir + '/' + uItem))
                else:
                    if bSubDirs:
                        oDirList.extend((cPath(uRootDir) + uItem).GetFileList(bSubDirs= bSubDirs,bFullPath=bFullPath))
        except Exception as e:
            Logger.debug(u'can\'t get File list:' + ToUnicode(str(e)) + " :" + uRootDir)

        return oDirList
예제 #20
0
    def ShowError(self, uMsg, uParConfigName="", oException=None):
        """
        writes an error message

        :rtype: string
        :param string uMsg: The error message
        :param string uParConfigName: The configuration name
        :param exception oException: Optional, an exception to show
        :return: The written logfile entry
        """

        # uRet = self._FormatShowMessage(uMsg,uParConfigName)
        # Logger.debug (uRet)
        # return uRet
        uRet = self._FormatShowMessage(uMsg, uParConfigName)
        iErrNo = 0
        if oException is not None:
            if hasattr(oException, 'errno'):
                iErrNo = oException.errno
        if iErrNo is None:
            iErrNo = 12345
        if iErrNo != 0:
            uRet = uRet + u" " + ToUnicode(iErrNo)
        uRet = LogError(uRet, oException)
        return uRet
예제 #21
0
def Var_Int2Hex(uVarName: str, uFormat: str = '{0:0>2X}') -> str:
    """
    Converts a Variable which represents an int value to a string of a hex value
    The changed variable value will be return and stored in the user vars (Triggers raised if set)

    :param str uVarName: The variable name for the action, from where the value is pulled
    :param str uFormat: The format to use for the conversion
    :return: The changed variable value
    """

    uValue: str = GetVar(uVarName=uVarName)
    try:

        if uValue == '':
            return u'0'
        if uValue == 'Error':
            return u'0'

        uValue = uFormat.format(int(uValue))
        uValue = ToUnicode(uValue)
        SetVar(uVarName=uVarName, oVarValue=uValue)
        return uValue
    except Exception as e:
        LogError(uMsg=u'Var_Int2Hex: Invalid Argument (%s):' % uValue,
                 oException=e)
        return u'0'
예제 #22
0
def Var_Round(uVarName: str, uPos: str) -> str:
    """
    Rounds a var value to the given round position.
    The changed variable value will be return and stored in the user vars (Triggers raised if set)
    Example: Round(1.81,0) return 2. Round(1.81,1) returns 1.80

    :param str uVarName: The variable name for the action, from where the value is pulled
    :param str uPos: The round position
    :return: The changed variable value
    """

    uValue: str = GetVar(uVarName=uVarName)

    try:
        if uValue == u'':
            return u''

        uPosToUse: str = GetVar(uVarName=uPos)
        if uPosToUse == u'':
            uPosToUse = uPos
        iPos: int = int(uPosToUse)
        uValue = ToUnicode(Round(ToFloat(uValue), iPos))
        SetVar(uVarName=uVarName, oVarValue=uValue)
        return uValue

    except Exception as e:
        LogError(uMsg=u'Var_Round: Invalid Argument [' + uVarName + u'=' +
                 uValue + u']:',
                 oException=e)
        return u'Error'
예제 #23
0
def Var_Hex2Int(uVarName: str) -> str:
    """
    Converts a Variable which represents an hex value to a string of an Int value
    The changed variable value will be return and stored in the user vars (Triggers raised if set)

    :param str uVarName: The variable name for the action, from where the value is pulled
    :return: The changed variable value
    """

    uValue: str = GetVar(uVarName=uVarName)
    try:
        if uValue == '':
            return u'0'
        if uValue == 'Error':
            return u'0'

        if uValue.lower().startswith('0x'):
            iValue = int(uValue, 0)
        else:
            iValue = int(uValue, 16)

        uValue = ToUnicode(iValue)
        uValue = Var_NormalizeInt(uValue)
        SetVar(uVarName=uVarName, oVarValue=uValue)
        return uValue
    except Exception as e:
        LogError(uMsg=u'Var_Hex2Int: Invalid Argument (%s):' % uValue,
                 oException=e)
        return u'0'
예제 #24
0
파일: Path.py 프로젝트: thica/ORCA-Remote
    def GetFolderList(self,*,bFullPath:bool=False) -> List:
        """
        Returns a list of all folders in a path

        :param bool bFullPath: If True, the folder entries include the full folder struture, otherwise on the foldername is returned
        :return: A list of all folder in a folder
        """

        oDirList:List = []
        uRootDir:str = u''
        uItem:str
        try:

            # stdout_encoding = sys.getfilesystemencoding()
            # print 'stdout_encoding:', stdout_encoding
            uRootDir = CleanUp(uFinal=self.string)
            for uItem in listdir(uRootDir):
                if isdir(join(uRootDir, uItem)):
                    if not bFullPath:
                        oDirList.append(uItem)
                    else:
                        oDirList.append(AdjustPathToOs(uPath=uRootDir + '/' + uItem))
        except Exception as e:
            Logger.warning(u'can\'t get Dirlist ' + ToUnicode(e) + " " + uRootDir)
        return oDirList
예제 #25
0
def Var_Power(uVarName: str, uPower: str) -> str:
    """
    Exponentiate a given variable value.
    The changed variable value will be return and stored in the user vars (Triggers raised if set)

    :param str uVarName: The variable name for the action, from where the value is pulled
    :param str uPower: The value to exponentiate the original value with, can be a variable itself
    :return: The changed variable value
    """

    try:
        uValue: str = GetVar(uVarName=uVarName)
        uValueOrg: str = uValue
        if uValue == u'':
            return u''

        uPowerToUse: str = GetVar(uVarName=uPower)
        if uPowerToUse == u'':
            uPowerToUse = uPower
        uPowerToUse = ReplaceVars(uPowerToUse)
        fPower: float = ToFloat(uPowerToUse)
        fValue: float = ToFloat(uValue)
        fValue = fValue**fPower
        uValue = ToUnicode(fValue)
        uValue = Var_NormalizeInt(uValue)
        SetVar(uVarName=uVarName, oVarValue=uValue)
        Logger.debug(
            u'Var_Power: [%s] ^ [%s] returned [%s]  (stored in [%s])' %
            (uValueOrg, uPowerToUse, uValue, uVarName))
        return uValue
    except Exception as e:
        LogError(uMsg=u'Var_Power: Invalid Argument', oException=e)
        return u'Error'
예제 #26
0
 def _Parse_Tokenize(self, uResponse: str, uGetVar: str,
                     uParseResultTokenizeString: str) -> Tuple:
     """ tokenizes the result """
     uCmd: str = u''
     if uResponse == '':
         self._SetVar(uResponse, u'_Parse_Tokenize: Storing Empty Response')
         return uGetVar, uResponse
     else:
         aLines: List = uResponse.splitlines()
         for uLine in aLines:
             if uParseResultTokenizeString == u'':
                 uParseResultTokenizeString = self.uGlobalTokenizeString
             tResp: Tuple[str] = uLine.split(uParseResultTokenizeString)
             if len(tResp) == 2:
                 uResponse: str = tResp[1]
                 uCmd: str = tResp[0]
                 self._SetVar(uResponse, u'Tokenized one result', uCmd)
             elif len(tResp) > 2:
                 i: int = 1
                 while i < len(tResp):
                     uResponse: str = tResp[1]
                     uCmd: str = tResp[0]
                     self._SetVar(uResponse, u'Tokenized multi results',
                                  uCmd + "_" + ToUnicode(i))
                     i += 1
             else:
                 self._SetVar(uResponse, u'No Tokens found, storing result')
     return uCmd, uResponse
예제 #27
0
    def __init__(self, **kwargs):

        self.oLayout = FloatLayout(size_hint=(1, 1))
        super(SettingPicture,
              self).__init__(**RemoveNoClassArgs(kwargs, SettingFile))

        try:
            oFnPic = cFileName().ImportFullPath(self.value)
            self.oPic = Image(source=UnEscapeUnicode(ToAtlas(oFnPic)),
                              size_hint=(1, 1),
                              pos_hint={
                                  'x': 0.0,
                                  'y': 0.0
                              })
            oFnBack = cFileName(Globals.oPathResources +
                                "pics") + "imagepicker_background.png"
            self.oBack = Image(source=ToAtlas(oFnBack),
                               size_hint=(1, 1),
                               pos_hint={
                                   'x': 0.0,
                                   'y': 0.0
                               })
            self.oLayout.add_widget(self.oBack)
            self.oLayout.add_widget(self.oPic)
            self.add_widget(self.oLayout)
            self.content.children[1].text = ''
        except Exception as e:
            uMsg = u'Settings: Picture: can\'t load image file: ' + ToUnicode(
                e) + " " + oFnPic
            Logger.error(uMsg)
예제 #28
0
파일: Screen.py 프로젝트: thica/ORCA-Remote
    def InitVars(self) -> None:
        """ (re) Initialises all vars (also after a definition change) """
        InitSystemVars()
        Globals.oDefinitions.InitVars()
        SetVar(uVarName = u'REPVERSION', oVarValue = ToUnicode(Globals.iVersion))

        # Name of the Current page
        # List for settings dialog
        self.bIntransition              = False
        self.dGestures.clear()
        self.dPopups.clear()
        self.iLastWidgetPage            = 0
        Globals.oActions.InitVars()
        self.oCurrentPage               = None
        self.oFonts.DeInit()
        self.oGdb                       = GestureDatabase()
        self.oPopup                     = None
        self.oScreenPages.DeInit()
        self.uCurrentEffect             = u''
        self.uCurrentEffectDirection    = u''
        self.uCurrentPageName           = u''
        self.uDefaultTransmitterPictureName = u''
        self.uDefaultWaitPictureName    = u''
        self.uDefName                   = u''
        self.uFirstPageName             = u''
        self.uInterFaceToConfig         = u''
        self.uScriptToConfig            = u''
        self.uConfigToConfig            = u''
        self.uSplashText                = u''
        self.iBlockCount                = 0
        self.iBlockAskCount             = 0
        if Globals.oTheScreen:
            Globals.oTheScreen.oSkin.dSkinRedirects.clear()
        gc.collect()
예제 #29
0
        def Receive(self, uResponse: str):
            aActionTrigger: Optional[List[cBaseTrigger]]
            uResponse = ToUnicode(uResponse)
            if self.oAction is not None:
                uCmd, uRetVal = self.oInterFace.ParseResult(
                    self.oAction, uResponse, self)
                self.ShowDebug(uMsg=u'Parsed Responses:' + uRetVal)
                if not self.uRetVar == u'' and not uRetVal == u'':
                    SetVar(uVarName=self.uRetVar, oVarValue=uRetVal)
                # We do not need to wait for an response anymore
                StartWait(0)
                self.oAction = None
            else:
                oAction: cAction = self.dStandardActions["defaultresponse"]
                if oAction:
                    uCommand = self.oInterFace.ParseResult(
                        oAction, uResponse, self)
                    if not isinstance(uCommand, str):
                        if len(uCommand) > 0:
                            uCommand = uCommand[1]

                    # we have a notification issued by the device, so lets have a look, if we have a trigger assigned to it
                    aActionTrigger = self.GetTrigger(uCommand)
                    if aActionTrigger is not None:
                        for oActionTrigger in oActionTrigger:
                            self.CallTrigger(oActionTrigger, uResponse)
                    else:
                        self.ShowDebug(uMsg=u'Discard message:' + uCommand +
                                       ':' + uResponse)
예제 #30
0
    def Unzip(self, oPath):
        """
        Unzips a zip file  to a path
        If the output location does not yet exist, it creates it

        :rtype: bool
        :param cPath oPath:
        :return: True if successful
        """

        oZip = None
        try:

            Logger.debug(u'Extracting file [%s] to path [%s]' % (self.string, oPath.string))

            oZip = ZipFile(self.string, 'r')
            if not oPath.IsDir():
                oPath.Create()
            for each in oZip.namelist():
                each=ToUnicode(each)

                Logger.debug(u'Extracting ' + ToUnicode(basename(each)) + ' ...')
                # Check to see if the item was written to the zip file with an
                # archive name that includes a parent directory. If it does, create
                # the parent folder in the output workspace and then write the file,
                # otherwise, just write the file to the workspace.
                #
                if not each.endswith('/'):
                    root, name = split(each)
                    oFolder = cPath(oPath) + root
                    if not oFolder.IsDir():
                        oFolder.Create()
                    oFn = cFileName(oFolder) + name
                    uFn = oFn.string
                    Logger.debug(u'... Writing to ' + uFn)
                    oFile = open(uFn, 'wb')
                    oFile.write(oZip.read(each))
                    oFile.close()
            oZip.close()
            return True
        except Exception as e:
            LogError(u'Unzip: Fatal Error unzipping file', e)
            try:
                oZip.close()
            except Exception:
                pass
            return False
예제 #31
0
 def ParseFile(self,uFileName,iStartLine=0):
     ''' parses a single file '''
     Logger.debug("Reading File:"+uFileName)
     try:
         if FileExists(uFileName):
             f = open(uFileName, 'r')
             uContent=ToUnicode(f.read())
             f.close()
             aContent=uContent.split("\n")
             bFound = False
             for  i,uLine in enumerate(aContent):
                 if i>iStartLine:
                     uLine=uLine.strip()
                     if uLine.startswith(u'WikiDoc:Doc'):
                         bFound = True
                     elif uLine.startswith(u'WikiDoc:End'):
                         bFound = False
                         self.oPages.append(self)
                         break
                     elif uLine.startswith("WikiDoc:Context:"):
                         uParts=uLine.split(":")
                         self.uContext=uParts[-1]
                     elif uLine.startswith("WikiDoc:Page:"):
                         uParts=uLine.split(":")
                         self.uPage=uParts[-1]
                     elif uLine.startswith("WikiDoc:TOCTitle:"):
                         uParts=uLine.split(":")
                         self.uTOCTitle=uParts[-1]
                     elif "'''" in uLine:
                         if bFound:
                             bFound = False
                             self.oPages.append(self)
                             break
                     else:
                         if bFound:
                             self.uContent.append(uLine)
         else:
             LogError(u'cWikiDoc:Cant find file:'+uFileName)
         if len(self.oPages)>0:
             oPage=cWikiPage()
             oPages=oPage.ParseFile(uFileName,i)
             if len(oPages)>0:
                 self.oPages.extend(oPages)
         return self.oPages
     except Exception as e:
         LogError(u'WikiDoc:Unexpected error reading file:',e)
         return []
예제 #32
0
        def Receive(self):
            #Main Listening Thread to receice eiscp messages

            #Loop until closed by external flag
            try:
                while self.bStopThreadEvent==False:
                    if not self.oSocket==None:
                        ready = select.select([self.oSocket], [], [],1.0)
                        # the first element of the returned list is a list of readable sockets
                        if ready[0]:
                            sResponses = self.oSocket.recv(self.iBufferSize)
                            # there could be more than one response, so we need to split them
                            uResponses = ToUnicode(sResponses)
                            aResponses=uResponses.split("[EOL]")
                            for uResponse in aResponses:
                                # Todo: find proper encoding
                                if not uResponse==u'' and not uResponse==u'ORCA.ORCA Connecting...':
                                    if "RemoteGhost.Pong" in uResponse:
                                        self.bPingAnswer=True
                                    else:
                                         # If the returned Command is a response to the send message
                                        if uResponse.startswith(u'RemoteGhost.'):
                                            self.ShowDebug(u'Returned Message:'+uResponse)
                                            #todo: parse the command from return
                                            # We do not need to wait for an response anymore
                                            oORCA.StartWait(0)
                                            # we got our response, all other responses are for somebody else
                                            self.uMsg=u''
                                        else:
                                            # we have a notification issued by the device, so lets have a look, if we have a trigger assigned to it
                                            oActionTrigger=self.GetTrigger(uResponse)
                                            if not oActionTrigger==None:
                                                self.CallTrigger(oActionTrigger,uResponse)
                                            else:
                                                self.ShowDebug(u'Discard message:'+uResponse)
                
            except Exception as e:
                self.ShowError(u'Error Receiving Response:',e)
                self.bIsConnected=False
            try:
                if not self.oSocket is None:
                    self.ShowDebug(u'Closing socket in Thread')
                    self.oSocket.close()
            except Exception as e:
                self.ShowError(u'Error closing socket in Thread',e)
예제 #33
0
파일: Screen.py 프로젝트: thica/ORCA-Remote
    def SetPageEffect(self,uEffect):
        ''' Sets the page effect for showing a page '''
        self.uCurrentEffect=uEffect
        try:
            if uEffect==u'':
                return True
            uType=ToUnicode(type(self.oRootSM.transition))
            if uEffect==u'no':
                self.oRootSM.transition = NoTransition()
            if uEffect==u'fade':
                if uType.endswith(u'FadeTransition\'>'):
                    return True
                self.oRootSM.transition = FadeTransition()
            elif uEffect==u'slide':
                if uType.endswith(u'SlideTransition\'>'):
                    return True
                self.oRootSM.transition = SlideTransition()
            elif uEffect==u'wipe':
                if uType.endswith(u'WipeTransition\'>'):
                    return True
                self.oRootSM.transition = WipeTransition()
            elif uEffect==u'swap':
                if uType.endswith(u'SwapTransition\'>'):
                    return True
                self.oRootSM.transition = SwapTransition()
            elif uEffect==u'fallout':
                if uType.endswith(u'FallOutTransition\'>'):
                    return True
                self.oRootSM.transition = FallOutTransition()
            elif uEffect==u'risein':
                if uType.endswith(u'RiseInTransition\'>'):
                    return True
                self.oRootSM.transition = RiseInTransition()

            self.oRootSM.transition.bind(on_complete=self.On_Transition_Complete)
            self.oRootSM.transition.bind(on_progress=self.On_Transition_Started)
            return True

        except Exception as e:
            uMsg=LogError(u'TheScreen: Can not set page effect:' + uEffect,e)
            ShowErrorPopUp(uMessage=uMsg)
            return False
        uMsg=u'TheScreen: Can not set page effect, wrong page effect:' + uEffect
        Logger.warning (uMsg)
        ShowErrorPopUp(uTitle='Warning',uMessage=uMsg)
        return False
예제 #34
0
    def _Parse_Json(self,uOrgResponse,uGetVar):
        ''' parses the result a json '''
        uResponse     = ToUnicode(uOrgResponse)
        uResponse2    = ToUnicode(uOrgResponse)
        tJsonResponse = uResponse

        try:
            tJsonResponse = json.loads(uResponse)
        except Exception as e:   # pylint: disable=unused-variable
            #uResponse = uResponse.replace("'", "blalala")
            #uResponse = uResponse.replace('"', "'")
            #uResponse = uResponse.replace("blalala",'"')

            uResponse=fixLazyJsonWithComments(uResponse)

            try:
                tJsonResponse = json.loads(uResponse)
            except Exception as e:
                uResponse     = uResponse.replace('u"', '"')
                tJsonResponse = json.loads(uResponse)
        lGetVars = uGetVar.split(',')
        uResult  = tJsonResponse
        iIndex   = 0
        UnSplit(lGetVars)
        if uGetVar == u'':
            return u'',u''
        for uVar in lGetVars:
            self.ShowDebug(u'Parsing Vartoken:' + uVar + " in:"+uResponse)
            iIndex=iIndex+1
            # we split [aa=bb,ccc}
            uVar = uVar.split(',')
            #and remove the brackets
            if len(uVar)>1:
                if uVar[0].startswith(u'['):
                    uVar[0] = uVar[0][1:]
                if uVar[1].endswith(u']'):
                    uVar[1] = uVar[1][:-1]
            #If we got a dict
            if isinstance(uResult,dict):
                self.ShowDebug(u'Parsing Result as Dict')
                # and should only receive one value, its simple, we do it
                if len(uVar) == 1:
                    uResult = uResult.get(uVar[0])    # pylint: disable=no-member
                # If we have to pull a specific value from a dict, than use the specific one (Not Testet: ToDo: Needs to reworked as soon as i got an example)
                else:
                    uResult = uResult.get(uVar[1])
            #If we got a list
            elif isinstance(uResult,list):
                self.ShowDebug(u'Parsing Result as List')
                #if we need nothing special, then use the first one
                if len(uVar) == 1:
                    if len(uResult) > 0:
                        uResult = uResult[0]
                        self.ShowDebug(u'Parsing Result as List, pulling first element:' + uResponse)
                else:
                    self.ShowDebug(u'Parsing Result as List: Pulling given Value')
                    #now it gets complicated
                    # Lets split the first part (xxx=yyy
                    lTmp=uVar[0].split('=')
                    if len(lTmp) == 2:
                        for oTmpResult in uResult:
                            if isinstance(oTmpResult,dict):
                                uFinalResult = u''
                                bFound       = False
                                for uKey, uValue in oTmpResult.items():
                                    if uKey == uVar[1]:
                                        uFinalResult = uValue
                                    if uKey == lTmp[0]:
                                        if uValue == lTmp[1]:
                                            bFound = True
                                if bFound:
                                    uResult = uFinalResult
                                    break
                        #sResult=sResult.get(lTmp[1])
                    else:
                        uResult = uResult[0]
            if iIndex == len(lGetVars):
                if isinstance(uResult, int) or isinstance(uResult, str) or isinstance(uResult, float):
                    uResult = ToUnicode(uResult)
                if isinstance(uResult, unicode):
                    self._SetVar(uResult,u'JSON:Storing Value')
                    return uVar,uResult
                else:
                    self.ShowError(u'Incomplete parse options')
                    self._SetVar(uResponse2,u'Storing incomplete Value')
                    return uVar,uResponse2
        return u'',u''
예제 #35
0
        def Receive(self):
            #Main Listening Thread to receive json messages

            #Loop until closed by external flag
            try:
                while self.bStopThreadEvent==False:
                    if not self.oSocket==None:
                        ready = select.select([self.oSocket], [], [],1.0)
                        # the first element of the returned list is a list of readable sockets
                        if ready[0]:
                            self.bHandled=False
                            sResponses = self.oSocket.recv(self.iBufferSize)
                            uResponses = ToUnicode(sResponses)
                            # there could be more than one response, so we need to split them
                            # unfortunately, there is no end char in a json respone
                            aResponses=uResponses.split('}{')
                            if not len(aResponses)==1:
                                i=0
                                while i<len(aResponses):
                                    if i==0:
                                        aResponses[i]+='}'
                                    else:
                                        aResponses[i]=u'{'+aResponses[i]
                                    i+=1
                            uID=0
                            for uResponse in aResponses:
                                if not uResponse==u'':
                                    if '"result":"pong"' in uResponse:
                                        self.bPingAnswer=True
                                    else:
                                        
                                        # Get the Command and the payload
                                        # If the returned Command is a response to the send message
                                        uCommand,uID=self.oInterFace.ParseResult_JsonHeader(uResponse)
                                        if uID==self.uID:
                                        
                                            uCmd,uRetVal=self.oInterFace.ParseResult(self.oCodesetCode,uResponse,self)

                                            self.ShowDebug(u'Parsed Respones:'+uRetVal)
                                        
                                            if not self.uRetVar==u'' and not uRetVal==u'':
                                                SetVar(self.uRetVar,uRetVal)
                                            # We do not need to wait for an response anymore
                                            oORCA.StartWait(0)
                                            self.bHandled=True


                                        if self.bHandled==False:
                                            # we have a notification issued by the device, so lets have a look, if we have a trigger assigned to it
                                            oActionTrigger=self.GetTrigger(uCommand)
                                            if not oActionTrigger==None:
                                                self.CallTrigger(oActionTrigger,uResponse)
                                            else:
                                                self.ShowDebug(u'Discard message:'+uCommand +':'+uResponse)
                            #print "LEAVE PARSE"
                            fSleep(0.01)
                
            except Exception as e:
                if self.bIsConnected:
                    self.ShowError(u'Error Receiving Response:',e)
                self.bIsConnected=False
            try:
                if not self.oSocket==None:
                    self.ShowDebug(u'Closing socket in Thread')
                    self.oSocket.close()
            except Exception as e:
                self.ShowError(u'Error closing socket in Thread',e)