def InitWidgetFromXml(self, *, oXMLNode: Element, oParentScreenPage: cScreenPage, uAnchor: str) -> bool: """ Reads further Widget attributes from a xml node """ bRet: bool = self.ParseXMLBaseNode(oXMLNode, oParentScreenPage, uAnchor) if bRet: self.uLineWidth = GetXMLTextAttributeVar(oXMLNode=oXMLNode, uTag=u'linewidth', bMandatory=False, uDefault="1.0") if self.uBackGroundColor == "#00000000": self.aBackGroundColor = Globals.oTheScreen.oSkin.dSkinAttributes.get( 'color border') fPercentage: float = -1.0 if not self.uLineWidth == u'': if self.uLineWidth.startswith('of:'): self.iLineWidth = self._ParseDimPosValue(self.uLineWidth) elif self.uLineWidth[0] == u'%': fPercentage = ToFloat(self.uLineWidth[1:]) elif self.uLineWidth[0] == u'd': self.iLineWidth = dp(ToInt( self.uLineWidth[1:])) + self.iAnchorPosX else: self.iLineWidth = ToInt(self.uLineWidth) if not fPercentage == -1.0: self.iLineWidth = ToInt(self.iAnchorPosX + ( (fPercentage / 100) * self.iAnchorWidth) - (self.iWidth * (fPercentage / 100))) self.iLineWidth = max(1, self.iLineWidth) return bRet
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
def On_ConfigChange(self, oSettings: KivySettings, oConfig: KivyConfigParser, uSection: str, uKey: str, uValue: str): """ reacts, if user changes a setting """ if uKey == u'configchangebuttons': self.uCurrentSection = uSection if uValue == u'button_add': SetVar(uVarName=u'SCRIPTINPUT', oVarValue=u'DEVICE_dummy') self.oInputKeyboard = ShowKeyBoard(uDestVar=u'SCRIPTINPUT', oFktNotify=self.On_InputAdd) if uValue == u'button_delete': ShowQuestionPopUp(uTitle=u'$lvar(5003)', uMessage=u'$lvar(5044)', fktYes=self.On_InputDel, uStringYes=u'$lvar(5001)', uStringNo=u'$lvar(5002)') if uValue == u'button_rename': SetVar(uVarName=u'SCRIPTINPUT', oVarValue=uSection) self.oInputKeyboard = ShowKeyBoard(uDestVar=u'SCRIPTINPUT', oFktNotify=self.On_InputRen) else: oSetting = self.oObject.GetSettingObjectForConfigName( uConfigName=uSection) if uKey in self.dSettingsCombined: uType = self.dSettingsCombined[uKey].get("type") if uType == "numeric" or uType == "numericslider": oSetting.aIniSettings[uKey] = ToInt(uValue) elif uType == "numericfloat": oSetting.aIniSettings[uKey] = ToFloat(uValue) elif uType == "bool": oSetting.aIniSettings[uKey] = ToBool(uValue) else: oSetting.aIniSettings[uKey] = uValue
def Config_GetDefault_Int(*, oConfig: ConfigParser, uSection: str, uOption: str, uDefaultValue: str) -> int: return ToInt( Config_GetDefault_Str(oConfig=oConfig, uSection=uSection, uOption=uOption, vDefaultValue=uDefaultValue))
def SendCommand(self, oAction, oSetting, uRetVar, bNoLogOut=False): cBaseInterFace.SendCommand(self, oAction, oSetting, uRetVar, bNoLogOut) iRet = 1 if oAction.uCCF_Code != u"": oAction.oIRCode = CCfToAndroidIR(oAction.uCCF_Code, ToInt(oAction.uRepeatCount)) oAction.uCCF_Code = u"" uCmd = ReplaceVars(oAction.uCmd) self.ShowInfo(u'Sending Command: ' + uCmd + u' to ' + oSetting.uConfigName) oSetting.Connect() if oSetting.bIsConnected: try: Logger.debug("Sending IR Commend to IRBLASTER") irblaster.transmit(oAction.oIRCode.iFrequency, oAction.oIRCode.aPattern) except Exception as e: self.ShowWarning(u'Can\'t send message: ' + e.message, oSetting.uConfigName) else: Logger.debug("Not Connected") return iRet
def ExecuteActionSetReturnCode(self, oAction): """ WikiDoc:Doc WikiDoc:Context:ActionsDetails WikiDoc:Page:Actions-SetReturnCode WikiDoc:TOCTitle:setreturncode = setreturncode = Set a specific return code <div style="overflow:auto; "> {| border=1 class="wikitable" ! align="left" | string |- |setreturncode |- |code |Error code to set |}</div> WikiDoc:End """ self.oEvenDispatcher.LogAction(u'SetReturnCode', oAction) self.oEvenDispatcher.bDoNext = True uCode = oAction.dActionPars.get("code", "0") return ToInt(uCode)
def SendCommand(self, oAction: cAction, oSetting: cInterFaceSettings, uRetVar: str, bNoLogOut: bool = False) -> eReturnCode: super().SendCommand(oAction=oAction, oSetting=oSetting, uRetVar=uRetVar, bNoLogOut=bNoLogOut) eRet: eReturnCode = eReturnCode.Error if oAction.uCCF_Code != u"": # noinspection PyUnresolvedReferences oAction.oIRCode = CCfToAndroidIR(oAction.uCCF_Code, ToInt(oAction.uRepeatCount)) oAction.uCCF_Code = u"" uCmd: str = ReplaceVars(oAction.uCmd) self.ShowInfo(uMsg=u'Sending Command: ' + uCmd + u' to ' + oSetting.uConfigName) oSetting.Connect() if oSetting.bIsConnected: try: Logger.debug("Sending IR Commend to IRBLASTER") irblaster.transmit(oAction.oIRCode.iFrequency, oAction.oIRCode.aPattern) eRet = eReturnCode.Success except Exception as ex: self.ShowWarning(uMsg=u'Can\'t send message: ' + str(ex)) else: Logger.debug("Not Connected") return eRet
def GetXMLIntAttribute(*, oXMLNode: Element, uTag: str, bMandatory: bool, iDefault: int) -> int: """ Returns an integer from a xml attribute """ return ToInt( GetXMLTextAttribute(oXMLNode=oXMLNode, uTag=uTag, bMandatory=bMandatory, vDefault=iDefault))
def ITach2CCF(uITACHString: str) -> Tuple[str, str]: aArray: List[str] uDelimiter: str = u',' uFinalString: str = u"0000 " #0000 denotes CCF type iFreqNum: int iFreq: int iPairData: int uTmpString: str iTransCount: int uTransCount: str uRepeatCount = u"0000" uITachRepeatCount: str aArray = uITACHString.split(uDelimiter) if len(aArray) < 6: Logger.error(u'ITach2CCF: Invalid String (#1)') return u'', u'' if aArray[3] == "": Logger.error(u'ITach2CCF: Invalid String (#2)') return u'', u'' iFreqNum = ToInt(aArray[3]) if iFreqNum == 0: Logger.error(u'ITach2CCF: Invalid String (#3)') return u'', u'' #todo Check if iFreq and Itranscount needs to converted to int iFreq = int(41450 / (iFreqNum / 100)) uTmpString = '{0:0>4X}'.format(iFreq) # tmpString = iFreq.ToString("X04") iTransCount = int((len(aArray) - 6) / 2) uTransCount = '{0:0>4X}'.format(iTransCount) #iTransCount.ToString("X04"); uITachRepeatCount = aArray[4] uFinalString = uFinalString + uTmpString + " " + uRepeatCount + " " + uTransCount for uElement in aArray[6:]: if uElement == "": Logger.error(u'ITach2CCF: Invalid String (#4)') return u'', u'' iPairData = ToInt(uElement) uTmpString = '{0:0>4X}'.format(iPairData) #iPairData.ToString("X04"); uFinalString = uFinalString + " " + uTmpString return uITachRepeatCount, uFinalString
def GetXMLFloatValue(*, oXMLNode: Element, uTag: str, bMandatory: bool, fDefault: float) -> float: """ Returns a float from a xml value """ return ToInt( GetXMLTextValue(oXMLNode=oXMLNode, uTag=uTag, bMandatory=bMandatory, vDefault=fDefault))
def ReadConfigFromIniFile(self, uConfigName): """ Reads the script config file """ if self.aScriptIniSettings.bInitCompleted: return self.aScriptIniSettings.bInitCompleted = True if uConfigName != u'': self.uConfigName = uConfigName self.uContext = self.oScript.uScriptName + u'/' + self.uConfigName self.uSection = self.uConfigName try: self.oScript.oScriptConfig.LoadConfig() SetVar(uVarName=u'ScriptConfigSection', oVarValue=uConfigName) dIniDef = self.oScript.oScriptConfig.CreateSettingJsonCombined( self) for uKey2 in dIniDef: oLine = dIniDef[uKey2] uType = oLine.get("type") uKey = oLine.get("key") uDefault = oLine.get("default") if uKey is None or uDefault is None: continue # we replace JSON defaults by script-settings defaults, if exists if self.aScriptIniSettings.queryget(uKey) is not None: uDefault = self.aScriptIniSettings.queryget(uKey) uResult = Config_GetDefault_Str( self.oScript.oScriptConfig.oConfigParser, self.uSection, uKey, uDefault) if uType == "scrolloptions" or uType == "string": self.aScriptIniSettings[uKey] = ReplaceVars(uResult) elif uType == "numeric" or uType == "numericslider": self.aScriptIniSettings[uKey] = ToInt(uResult) elif uType == "numericfloat": self.aScriptIniSettings[uKey] = ToFloat(uResult) elif uType == "bool": self.aScriptIniSettings[uKey] = ToBool(uResult) elif uType == "title" or uType == "buttons" or uType == "path" or uType == "varstring": pass else: self.ShowError( u'Cannot read config name (base), wrong attribute:' + self.oScript.oScriptConfig.oFnConfig.string + u' Section:' + self.uSection + " " + oLine["type"]) self.oScript.oScriptConfig.oConfigParser.write() except Exception as e: self.ShowError(uMsg=u'Cannot read config name (base):' + self.oScript.oScriptConfig.oFnConfig.string + u' Section:' + self.uSection, oException=e) return
def ReadAction(self, oAction: cAction) -> None: super().ReadAction(oAction) oAction.uParams = oAction.dActionPars.get(u'params', u'') oAction.uRequestType = oAction.dActionPars.get( u'requesttype', u'POST') oAction.uHeaders = oAction.dActionPars.get(u'headers', u'{}') oAction.uProtocol = oAction.dActionPars.get( u'protocol', u'http://') oAction.iCodeOK = ToInt(oAction.dActionPars.get(u'codeok', u'200'))
def GetXMLIntAttributeVar(*, oXMLNode: Element, uTag: str, bMandatory: bool, iDefault: int) -> int: """ Returns an integer from a xml attribute (given as var)""" return ToInt( ReplaceVars( GetXMLTextAttribute(oXMLNode=oXMLNode, uTag=uTag, bMandatory=bMandatory, vDefault=ToUnicode(iDefault))))
def CCfToAndroidIR(sCCFString: str, iRepeatCount: int) -> cIRCommand: iCount: int aList: List = sCCFString.split(" ") iFrequency: int = int(aList[1], 16) aList = aList[3:] iFrequency = ToInt(iFrequency * 0.241246) iPulses: int = int(1000000 / iFrequency) aPattern: List = [] for uElem in aList: iCount = int(uElem, 16) aPattern.append(int(iCount * iPulses)) return cIRCommand(iFrequency, aPattern)
def Finish(self) -> bool: """ Finish loading """ oET_Root: Element if self.oRef.dPars["Finalize"] == "REPOSITORY XML": try: oET_Root = LoadXMLFile(oFile=self.oFnDest, bNoCache=True) if not oET_Root is None: self.oRepository.ParseFromXMLNode(oXMLNode=oET_Root) except Exception as e: LogError(uMsg=u'can\'t parse repository:' + self.uUrl, oException=e) return True if self.oRef.dPars["Finalize"] == "FILE ZIP": try: if not self.bOnError: if self.uTarget.startswith('.' or '..' in self.uTarget): LogError( uMsg= 'All destination pathes must be inside the ORCA directory, absolute pathes are not allowed!:' + self.uTarget) else: oZipFile: cZipFile = cZipFile('').ImportFullPath( uFnFullName=self.oFnDest.string) if oZipFile.IsZipFile(): if not Globals.bProtected: oZipFile.Unzip( cPath('$var(APPLICATIONPATH)/' + self.uTarget)) else: LogError( uMsg="Protected: Nothing will be unzipped") else: if oZipFile.Exists(): Logger.error("Failed to unzip:" + oZipFile.string) else: Logger.error("Failed to download zip:" + oZipFile.string) #todo: handle unzipped files oZipFile.Delete() Logger.debug( 'LoadOnlineResource: Finished download Resource [%s][%s]' % (self.uType, self.uName)) RegisterDownLoad(uType=self.uType, uName=self.uName, iVersion=ToInt(self.uVersion)) except Exception as e: LogError(uMsg=u'can\'t unpack resources:' + self.uUrl, oException=e)
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
def SendCommand(self, oAction, oSetting, uRetVar, bNoLogOut=False): cBaseInterFace.SendCommand(self, oAction, oSetting, uRetVar, bNoLogOut) if oAction.uCCF_Code: oAction.uCmd = CCF2ITach(oAction.uCCF_Code, ToInt(oAction.uRepeatCount)) oAction.uCCF_Code = u"" uCmd = ReplaceVars(oAction.uCmd, self.uInterFaceName + u'/' + oSetting.uConfigName) uCmd = ReplaceVars(uCmd) self.ShowInfo( u'Sending Command: ' + uCmd + u' to ' + oSetting.aInterFaceIniSettings.uHost + ':' + oSetting.aInterFaceIniSettings.uPort, oSetting.uConfigName) oSetting.Connect() iRet = 1 if oSetting.bIsConnected: uMsg = uCmd + u'\r\n' try: if PY2: oSetting.oSocket.sendall(uMsg) else: oSetting.oSocket.sendall(ToBytes(uMsg)) self.sResponse = oSetting.oSocket.recv(self.iBufferSize) Logger.debug(u'Interface ' + self.uInterFaceName + ': resonse:' + self.sResponse) self.ShowDebug(u'Response' + self.sResponse, oSetting.uConfigName) if 'completeir' in self.sResponse: iRet = 0 else: iRet = 1 except Exception as e: self.ShowError(u'can\'t Send Message', u'', e) iRet = 1 if oSetting.bIsConnected: if oSetting.aInterFaceIniSettings.iTimeToClose == 0: oSetting.Disconnect() elif oSetting.aInterFaceIniSettings.iTimeToClose != -1: Clock.unschedule(oSetting.FktDisconnect) Clock.schedule_once( oSetting.FktDisconnect, oSetting.aInterFaceIniSettings.iTimeToClose) return iRet
def SendCommand(self, oAction: cAction, oSetting: cInterFaceSettings, uRetVar: str, bNoLogOut: bool = False) -> eReturnCode: super().SendCommand(oAction=oAction, oSetting=oSetting, uRetVar=uRetVar, bNoLogOut=bNoLogOut) eRet: eReturnCode = eReturnCode.Error if oAction.uCCF_Code: # noinspection PyUnresolvedReferences oAction.uCmd = CCF2ITach(oAction.uCCF_Code, ToInt(oAction.uRepeatCount)) oAction.uCCF_Code = u"" uCmd: str = ReplaceVars(oAction.uCmd, self.uObjectName + u'/' + oSetting.uConfigName) uCmd = ReplaceVars(uCmd) self.ShowInfo(uMsg=u'Sending Command: ' + uCmd + u' to ' + oSetting.aIniSettings.uHost + ':' + oSetting.aIniSettings.uPort) oSetting.Connect() if oSetting.bIsConnected: uMsg: str = uCmd + u'\r\n' try: oSetting.oSocket.sendall(ToBytes(uMsg)) byResponse = oSetting.oSocket.recv(self.iBufferSize) self.ShowDebug(uMsg=u'Response' + ToUnicode(byResponse), uParConfigName=oSetting.uConfigName) if 'completeir' in ToUnicode(byResponse): eRet = eReturnCode.Success else: eRet = eReturnCode.Error except Exception as e: self.ShowError(uMsg=u'can\'t Send Message', uParConfigName=u'', oException=e) eRet = eReturnCode.Error self.CloseSettingConnection(oSetting=oSetting, bNoLogOut=bNoLogOut) return eRet
def SendCommand(self,oAction,oSetting,uRetVar,bNoLogOut=False): cBaseInterFace.SendCommand(self,oAction,oSetting,uRetVar,bNoLogOut) iRet=1 if oAction.uCCF_Code != u"": oAction.uCmd=CCfToKeene(oAction.uCCF_Code,ToInt(oAction.uRepeatCount)) oAction.uCCF_Code = u"" uCmd=ReplaceVars(oAction.uCmd) self.ShowInfo(u'Sending Command: '+uCmd + u' to '+oSetting.aInterFaceIniSettings.uHost+':'+oSetting.aInterFaceIniSettings.uPort,oSetting.uConfigName) oSetting.Connect() if oSetting.bIsConnected: uMsg=uCmd+u'\r\n' try: uMsg=ReplaceVars(uMsg,self.uInterFaceName+'/'+oSetting.uConfigName) if PY2: oSetting.oSocket.sendto(uMsg, (oSetting.aInterFaceIniSettings.uHost, int(oSetting.aInterFaceIniSettings.uPort))) else: oSetting.oSocket.sendto(ToBytes(uMsg), (oSetting.aInterFaceIniSettings.uHost, int(oSetting.aInterFaceIniSettings.uPort))) self.sResponse, addr = oSetting.oSocket.recvfrom(self.iBufferSize) if not PY2: self.sResponse = ToUnicode(self.sResponse) self.ShowDebug(u'Response'+self.sResponse,oSetting.uConfigName) if 'ACK' in self.sResponse: iRet=0 else: iRet=1 except Exception as e: if e.message!="timed out": self.ShowError(u'Can\'t send message',oSetting.uConfigName,e) else: self.ShowWarning(u'Can\'t send message: time out',oSetting.uConfigName) iRet=1 if oSetting.bIsConnected: if oSetting.aInterFaceIniSettings.iTimeToClose==0: oSetting.Disconnect() elif oSetting.aInterFaceIniSettings.iTimeToClose!=-1: Clock.unschedule(oSetting.FktDisconnect) Clock.schedule_once(oSetting.FktDisconnect, oSetting.aInterFaceIniSettings.iTimeToClose) return iRet
def SendCommand(self,oAction:cAction,oSetting:cInterFaceSettings,uRetVar:str,bNoLogOut:bool=False) -> eReturnCode: super().SendCommand(oAction=oAction,oSetting=oSetting,uRetVar=uRetVar,bNoLogOut=bNoLogOut) eRet:eReturnCode = eReturnCode.Error if oAction.uCCF_Code != u"": # noinspection PyUnresolvedReferences oAction.uCmd=CCfToKeene(oAction.uCCF_Code,ToInt(oAction.uRepeatCount)) oAction.uCCF_Code = u"" uCmd:str=ReplaceVars(oAction.uCmd) self.ShowInfo(uMsg=u'Sending Command: '+uCmd + u' to '+oSetting.aIniSettings.uHost+':'+oSetting.aIniSettings.uPort) oSetting.Connect() if oSetting.bIsConnected: uMsg=uCmd+u'\r\n' try: uMsg=ReplaceVars(uMsg,self.uObjectName+'/'+oSetting.uConfigName) oSetting.oSocket.sendto(ToBytes(uMsg), (oSetting.aIniSettings.uHost, int(oSetting.aIniSettings.uPort))) byResponse, addr = oSetting.oSocket.recvfrom(self.iBufferSize) uResponse = ToUnicode(byResponse) self.ShowDebug(uMsg=u'Response'+uResponse,uParConfigName=oSetting.uConfigName) if 'ACK' in uResponse: eRet = eReturnCode.Success else: eRet = eReturnCode.Error except Exception as e: if str(e)!="timed out": self.ShowError(uMsg=u'Can\'t send message',uParConfigName=oSetting.uConfigName,oException=e) else: self.ShowWarning(uMsg=u'Can\'t send message: time out',uParConfigName=oSetting.uConfigName) eRet = eReturnCode.Error self.CloseSettingConnection(oSetting=oSetting, bNoLogOut=bNoLogOut) return eRet
def Connect(self) -> bool: if not super().Connect(): return False if self.aIniSettings.uHost == '': return False try: if self.oDevice is None: # self.oDevice = Cube(address=self.aIniSettings.uHost, port=ToInt(self.aIniSettings.uPort)) self.oDevice = MaxCube( MaxCubeConnection(host=self.aIniSettings.uHost, port=ToInt(self.aIniSettings.uPort))) # self.oDevice.connect() self.oInterFace.oObjectConfig.WriteDefinitionConfigPar( uSectionName=self.uSection, uVarName=u'OldDiscoveredIP', uVarValue=self.aIniSettings.uHost) self.bIsConnected = True return self.bIsConnected except Exception as e: if hasattr(e, "errno"): # noinspection Mypy if e.errno == 10051: self.bOnError = True self.ShowWarning(uMsg=u'Cannot connect (No Network):' + self.aIniSettings.uHost + ':' + self.aIniSettings.uPort) return False self.ShowError(uMsg=u'Cannot connect:' + self.aIniSettings.uHost + ':' + self.aIniSettings.uPort, oException=e) self.bOnError = True return False
def Var_StringToTime(uVarName: str, uFormat: str, uGap: str): """ Converts a time string into a language local time string 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 (python datetime.strptime syntax). You might add the requested output to the format at the beginning of the string: #D #T #DT, If not given, date and time will returned. eg: #D%Y-%m-%dT%H:%M:%SZ will just return the date :param str uGap: The time delta to add (in milliseconnds if no time given, :return: The changed variable value """ bUseDate: bool = False bUseTime: bool = False uValue: str uFormatToUse: str uResult: str = u'' oDateTime: datetime iGap: int try: uValue = GetVar(uVarName=uVarName) if uValue is None: return u'' uFormatToUse: str = ORCA.vars.Globals.dUserVars.get(uFormat) if uFormatToUse is None: uFormatToUse = uFormat if uFormatToUse.startswith('#'): if uFormatToUse.startswith('#DT') or uFormatToUse.startswith( '#TD'): bUseDate = True bUseTime = True uFormatToUse = uFormatToUse[3:] elif uFormatToUse.startswith('#D'): bUseDate = True uFormatToUse = uFormatToUse[2:] elif uFormatToUse.startswith('#T'): bUseTime = True uFormatToUse = uFormatToUse[2:] else: bUseDate = True bUseTime = True oDateTime = datetime.strptime(uValue, uFormatToUse) if uGap: iGap = ToInt(uGap) oDateTime = oDateTime + timedelta(milliseconds=iGap) if bUseDate: uResult = Globals.oLanguage.GetLocalizedDate( Globals.bLongDate, Globals.bLongMonth, Globals.bLongDay, oDateTime.timetuple()) if bUseTime: uResult = uResult + " " if bUseTime: uResult = uResult + Globals.oLanguage.GetLocalizedTime( Globals.bClockWithSeconds, oDateTime.timetuple()) + " " SetVar(uVarName=uVarName, oVarValue=uResult) return uResult except Exception as e: LogError(uMsg=u'Var_StringToTime: Invalid Argument', oException=e) return u''
def GetXMLIntAttribute(oXMLNode, uTag, bMandantory, iDefault): """ Returns an integer from a xml attribute """ return ToInt(GetXMLTextAttribute(oXMLNode, uTag, bMandantory, iDefault))
def GetXMLIntAttributeVar(oXMLNode, uTag, bMandantory, iDefault): """ Returns an integer from a xml attribute (given as var)""" return ToInt( ReplaceVars( GetXMLTextAttribute(oXMLNode, uTag, bMandantory, ToUnicode(iDefault))))
def _ParseDimPosValue(self, uValue: str) -> int: tSplit: List[str] = uValue.split(":") fRetVal: float = 0 ''' of:width:[last/self/widgetname:calc] of:height:[last/self/widgetname:calc] of:bottom:[last/self/widgetname:calc] of:top:[last/self/widgetname:calc] of:left:[last/self/widgetname:calc] of:right:[last/self/widgetname:calc] of:totop:[last/self/widgetname:calc] of:tobottom:[last/self/widgetname:calc] of:toleft:[last/self/widgetname:calc] ''' global oLastWidget if len(tSplit) > 2: uDim = tSplit[1] tFrom = tSplit[2] if tFrom == 'last': tFrom = oLastWidget elif tFrom == 'self': tFrom = self else: aFrom = Globals.oTheScreen.FindWidgets( uPageName=self.oParentScreenPage.uPageName, uWidgetName=tSplit[2]) if len(aFrom) > 0: tFrom = aFrom[0] else: tFrom = None if tFrom is not None: if uDim == 'top': fRetVal = tFrom.iPosY elif uDim == 'left': fRetVal = tFrom.iPosX elif uDim == 'bottom': fRetVal = tFrom.iPosY + tFrom.iHeight elif uDim == 'right': fRetVal = tFrom.iPosX + tFrom.iWidth elif uDim == 'width': fRetVal = tFrom.iWidth elif uDim == 'height': fRetVal = tFrom.iHeight elif uDim == 'totop': fRetVal = tFrom.iPosY - self.iHeight elif uDim == 'tobottom': fRetVal = tFrom.iPosY + tFrom.iHeight - self.iHeight elif uDim == 'toleft': fRetVal = tFrom.iPosX - self.iWidth elif uDim == 'toright': fRetVal = tFrom.iPosX + tFrom.iWidth - self.iWidth else: LogError(uMsg=u'Unknown Reference:' + uDim) else: LogError(uMsg=u'Unknown Widget: [%s][%s][%s]' % (self.oParentScreenPage.uPageName, tSplit[2], self.uFileNames)) if len(tSplit) > 3: uOperator = tSplit[3] if len(uOperator) > 1: if uOperator[0] == '*': fRetVal = fRetVal * float(uOperator[1:]) elif uOperator[0] == '/': fRetVal = fRetVal / float(uOperator[1:]) else: LogError(uMsg=u'Unknown Operator:' + uOperator) return ToInt(fRetVal)
def ExecuteActionModifyVar(self, oAction: cAction) -> eReturnCode: """ WikiDoc:Doc WikiDoc:Context:ActionsDetails WikiDoc:Page:Actions-ModifyVar WikiDoc:TOCTitle:modifyvar = modifyvar = Modifies an existing variable. This is an inplace modification, so the given variable will be changed: a=fkt(a). If you need something like a=fkt(b), you need to copy the variable using setvar prior using this functions. "Increase" and "decrease" works on numeric variables only. "Invert" works on numeric (0/1) or on string variables (True/False). "Lowercase","Uppercase","Trim" works on string variables "Concatenate" , "Getpart", "Format" works on all variable types "Getlen" and "Find" are the only sub action, that will not modify the var, it will return the result in a different var "Load" and "Save" are options to create persistent variables. You can sav a variable value and reload the value at the next application start. Some note on "Getpart", which is to extract a part of string from a string. It follows python rules (eg.: string[start:end]) where start or end could be empty "Fromvar" converts a variable name into its variable value. "Exists" checks if the variable exist or if a function name with the variable name exists <div style="overflow:auto; "> {| class="wikitable" ! align="left" | Attribute ! align="left" | Description |- |string |modifyvar |- |varname |Variable to use/modify |- |parameter1 |First parameter for operator |- |parameter2 |Second parameter for operator |- |Operator |Operator for the command. Use one of the following keywords * "increase" * "decrease" * "multiply" * "divide" * "invert" * "lowercase" * "uppercase" * "trim" * "concatenate" * "getpart" * "format" * "totime" * "getlen" * "find" * "power" * "save" * "load" * "delete" * "round" * "fromvar" * "hex2int" * "hexstringtostring" * "stringtohexstring" * "loadfile" * "tovar" * "addtoarray" * "removefromarray" * "exists" |}</div> Remarks on some operators <div style="overflow:auto; "> {| class="wikitable" ! align="left" | Operator ! align="left" | Parameter1 ! align="left" | Parameter2 |- |increase |The delta value (like a=a+x) |Optional: The upper limit |- |decrease |The delta value (like a=a-x) |Optional: The lower limit |- |multiply |The Multiplier (like a=a*x) | |- |devide |The Devidor (like a=a/x) | |- |power |The power (like a=a^x) | |- |concatenate |The string / stringvar to add (like a=a+"mystring") | |- |getpart |The start position |The end position |- |fromvar (gets the variable content from a variable name given in a variable) |The context of the var | |- |delete either deletes a single var or an array if the var name ends with [] | | |- |tovar (assigns a variable name to a new variable without variable replacement) |newvarname: the new var name, where the var name should be assigned to | |- |format |The format string, following the python string.format syntax e.g.: "(int)FFFF00{0:0>2x}" | |totime |The format string for the python datetime.datetime.strptime function e.g.: "%Y-%m-%dT%H:%M:%SZ" | Time offset (milliseconds of no unit given) |- |round |The rounding position (eg 0=round to int) | |- |getlen |the destination var for the length | |- |save |A prefix for the cookie name | |- |load |A prefix for the cookie name |The default value, if no save value is available |- |loadfile |The filename, from which the content should be loaded into the var |The default value, if no save value is available |- |addtoarray |The var value to be added |Boolean, if 1, than only add, if value is not already in array |- |removefromarray |The var value to be removed | |- |exist |The var name to return, if the var exists (0/1) | |}</div> A short example: <div style="overflow-x: auto;"><syntaxhighlight lang="xml"> <action name="" string="modifyvar" varname="DIMVALUE" operator="divide" parameter1="6.25"/> </syntaxhighlight></div> WikiDoc:End """ uVarName: str = ReplaceVars(oAction.dActionPars.get("varname", "")) uParameter1: str = oAction.dActionPars.get("parameter1", "") uParameter2: str = oAction.dActionPars.get("parameter2", "") uOperator: str = ReplaceVars(oAction.dActionPars.get("operator", "")) bNoVarDetails: bool = False iLevel: int aVars: List[str] uLast: str uMax: str uOldVar: str uVarName: str aVars: List[str] uValue: str uNewVarName: str uTmp: str if uOperator == u'increase': Var_Increase(uVarName=uVarName, uStep=ReplaceVars(uParameter1), uMax=ReplaceVars(uParameter2)) elif uOperator == u'decrease': Var_Decrease(uVarName=uVarName, uStep=ReplaceVars(uParameter1), uMin=ReplaceVars(uParameter2)) elif uOperator == u'multiply': Var_Multiply(uVarName=uVarName, uFactor=ReplaceVars(uParameter1)) elif uOperator == u'divide': Var_Divide(uVarName=uVarName, uDivisor=ReplaceVars(uParameter1)) elif uOperator == u'power': Var_Power(uVarName=uVarName, uPower=ReplaceVars(uParameter1)) elif uOperator == u'invert': Var_Invert(uVarName=uVarName) elif uOperator == u'delete': if uVarName.endswith(u'[]'): Var_DelArray(uVarName=uVarName) else: DelVar(uVarName=uVarName) elif uOperator == u'round': Var_Round(uVarName=uVarName, uPos=uParameter1) elif uOperator == u'lowercase': Var_LowerCase(uVarName=uVarName) elif uOperator == u'uppercase': Var_UpperCase(uVarName=uVarName) elif uOperator == u'trim': Var_Trim(uVarName=uVarName) elif uOperator == u'fromvar': uOldVar = GetVar(uVarName=uVarName) Var_FromVar(uVarName=uVarName, uContext=ReplaceVars(uParameter1)) Logger.debug(u'FromVar: ' + uVarName + "=" + GetVar(uVarName=uVarName) + u" [" + uOldVar + u"]") elif uOperator == u'tovar': uVarName = oAction.dActionPars.get("varname", "") Var_ToVar(uVarName=uVarName, uNewVarName=uParameter1) Logger.debug(u'ToVar: ' + uVarName + "=" + uParameter1) elif uOperator == u'concatenate': Var_Concatenate(uVarName=uVarName, uAddVar=ReplaceVars(uParameter1)) elif uOperator == u'getpart': Var_Part(uVarName=uVarName, uStart=uParameter1, uEnd=uParameter2) elif uOperator == u'getlen': Var_Len(uVarName=uVarName, uDestVar=uParameter1) elif uOperator == u'find': Var_Find(uVarName=uVarName, uFindVar=uParameter1, uDestVar=uParameter2) elif uOperator == u'format': Var_Format(uVarName=uVarName, uFormat=uParameter1) elif uOperator == u'hex2int': Var_Hex2Int(uVarName=uVarName) elif uOperator == u'hexstringtostring': Var_HexStringToString(uVarName=uVarName) elif uOperator == u'totime': Var_StringToTime(uVarName=uVarName, uFormat=ReplaceVars(uParameter1), uGap=ReplaceVars(uParameter2)) elif uOperator == u'stringtohexstring': Var_StringToHexString(uVarName=uVarName) elif uOperator == u'load': Var_Load(uVarName=uVarName, uDefault=ReplaceVars(uParameter1), uPrefix=ReplaceVars(uParameter2)) elif uOperator == u'save': Var_Save(uVarName=uVarName, uPrefix=ReplaceVars(uParameter1)) elif uOperator == u'addtoarray': iLevel = uVarName.count('[') aVars = sorted(Var_GetArray(uVarName=uVarName, iLevel=iLevel)) uValue = ReplaceVars(uParameter1) if uParameter2 == "1": for uTmp in aVars: if GetVar(uVarName=uTmp) == uValue: return eReturnCode.Nothing uMax = "1" if len(aVars): uLast = aVars[-1] uMax = uLast[uLast.rfind("[") + 1:][:-1] if ToFloat2(uMax): uMax = str(ToInt(uMax) + 1) else: Logger.warning(u'addtoarray:' + uVarName + " Array contains non numeric indices") uNewVarName = uVarName[:-2] + "[" + uMax + "]" SetVar(uVarName=uNewVarName, oVarValue=uValue) Logger.debug(u'addtoarray:' + uNewVarName + "=" + uValue) elif uOperator == u'removefromarray': iLevel = uVarName.count('[') aVars = sorted(Var_GetArray(uVarName=uVarName, iLevel=iLevel)) uValue = ReplaceVars(uParameter1) for uTmp in aVars: if GetVar(uVarName=uTmp) == uValue: DelVar(uVarName=uTmp) elif uOperator == u'loadfile': Var_LoadFile(uVarName=uVarName, uFileName=ReplaceVars(uParameter1)) bNoVarDetails = True elif uOperator == u'exists': if ExistVar( uVarName) or uVarName in Globals.oActions.dActionsCommands: SetVar(uParameter1, "1") else: SetVar(uParameter1, "0") bNoVarDetails = True else: LogError(uMsg=u'Action: ModifyVar: Wrong modifier:' + uOperator) return eReturnCode.Error if bNoVarDetails: self.oEventDispatcher.LogAction(uTxt=u'ModifyVar', oAction=oAction) else: self.oEventDispatcher.LogAction(uTxt=u'ModifyVar', oAction=oAction, uAddText="Result:" + GetVar(uVarName=uVarName)) return eReturnCode.Nothing
def ExecuteActionForIn(self, oAction: cAction) -> eReturnCode: """ WikiDoc:Doc WikiDoc:Context:ActionsDetails WikiDoc:Page:Actions-ForIn WikiDoc:TOCTitle:forin = ForIn = Loops through an array of custom vars <div style="overflow:auto; "> {| class="wikitable" ! align="left" | Attribute ! align="left" | Description |- |string |forin |- |varname |Variable name to loop through (without brackets) |- |level |the bracket level to use (from left), 1 = leftmost |- |actionname |multi line action / macro name to call for each var |- |breakvar |Break Var to exit the loop, set to 1 to exit the forin loop |}</div> A short example: <div style="overflow-x: auto;"><syntaxhighlight lang="xml"> <action name="loop through vars" string="forin" varname="myarray[]" level="1" actionname="fkt dosomething"/> </syntaxhighlight></div> Given, you have the following var array myarray[1] = "Apple" myarray[2] = "Orange" myarray[3] = "Cherry" This will create the following pars for the first iteration Varname: $par(forin_value) = "Apple" $par(forin_var) = "myarray[1]" $par(forin_varcore) = "myarray" $par(forin_index) = "1" <div style="overflow-x: auto;"><syntaxhighlight lang="xml"> <action name="loop through vars" string="forin" varname="myarray[1]_subelement[]" dstvarname="elementname" level="2" actionname="fkt dosomething"/> </syntaxhighlight></div> Given, you have the following var array myarray[1]_sublement[1] = "Green Apple" myarray[1]_sublement[2] = "Red Apple" myarray[1]_sublement[3] = "Yellow Apple" myarray[2]_sublement[1] = "Green Orange" myarray[2]_sublement[2] = "Orange Orange" myarray[3]_sublement[1] = "Small Cherry" This will create the following subvars for the second iteration. Note, it will iterate only through the Apples, not through the oranges Varname: $par(forin_value) = "Red Apple" $par(forin_var) = "myarray[1]_sublement[2]" $par(forin_varcore) = "myarray[1]_sublement" $par(forin_index) = "2" WikiDoc:End """ self.oEventDispatcher.LogAction(uTxt=u'ForIn', oAction=oAction) uVarName: str = ReplaceVars(oAction.dActionPars.get("varname", "")) iLevel: int = ToInt(oAction.dActionPars.get("level", "1")) uActionName: str = ReplaceVars( oAction.dActionPars.get("actionname", "")) uBreakVar: str = ReplaceVars(oAction.dActionPars.get("breakvar", "")) aActions: List[cAction] = [] aVars: List[str] = Var_GetArray(uVarName=uVarName, iLevel=iLevel, bSort=True) SetVar(uVarName=uBreakVar, oVarValue="0") uVar: str uVarCore: str uVarIndex: str iPosStart: int iPosEnd: int for uVar in aVars: uVarCore = u"" uVarIndex = u"" iPosStart = Find_nth_Character(uVar, "[", iLevel) iPosEnd = Find_nth_Character(uVar, "]", iLevel) if iPosEnd > iPosStart: uVarCore = uVar[:iPosStart] uVarIndex = uVar[iPosStart + 1:iPosEnd] if uBreakVar == u'': self.oEventDispatcher.AddToSimpleActionList( aActionList=aActions, aActions=[{ 'name': 'Call ForIn Action', 'string': 'call', 'actionname': uActionName, "forin_value": GetVar(uVarName=uVar), "forin_var": uVar, "forin_varcore": uVarCore, "forin_index": uVarIndex, }]) else: self.oEventDispatcher.AddToSimpleActionList( aActionList=aActions, aActions=[{ 'name': 'Call ForIn Action', 'string': 'call', 'actionname': uActionName, "forin_value": GetVar(uVarName=uVar), "forin_var": uVar, "forin_varcore": uVarCore, "forin_index": uVarIndex, "condition": "$var(" + uBreakVar + ")==0" }]) self.oEventDispatcher.ExecuteActionsNewQueue(aActions, None) return eReturnCode.Nothing
def OrcaConfigParser_On_Setting_Change(config: kivyConfig, section: str, key: str, value: str) -> None: uSection: str = section uKey: str = key uValue: str = value # uValue = ToUnicode(value) if uSection == "ORCA": if uKey == u'button_clear_atlas': ClearAtlas() elif uKey == u"button_notification": uNotification = uValue.split("_")[-1] Globals.oNotifications.SendNotification( uNotification=uNotification, **{ "key": uKey, "value": uValue }) elif uKey == u'button_discover_rediscover': if uValue == u'button_discover_rediscover': Globals.oInterFaces.DiscoverAll() else: Globals.oInterFaces.DiscoverAll(bForce=True) elif uKey == u'button_discover_results': from ORCA.utils.Discover import cDiscover_List Globals.oApp.oDiscoverList = cDiscover_List() Globals.oApp.oDiscoverList.ShowList() elif uKey == u'button_installed_reps': Globals.oDownLoadSettings.LoadDirect(uDirect=uValue, bForce=True) elif uKey == u'button_show_installationhint': Var_DeleteCookie(uVarName='SHOWINSTALLATIONHINT', uPrefix=Globals.uDefinitionName) Globals.oTheScreen.AddActionToQueue( aActions=[{ 'string': 'call', 'actionname': 'Fkt ShowInstallationHint' }]) elif uKey == u'button_show_powerstati': Globals.oTheScreen.AddActionShowPageToQueue( uPageName=u'Page_PowerStati') elif uKey == u'button_updateallreps': Globals.oDownLoadSettings.UpdateAllInstalledRepositories( bForce=True) elif uKey == u'showborders': Globals.bShowBorders = not Globals.bShowBorders Globals.oTheScreen.AddActionToQueue( aActions=[{ 'string': 'updatewidget *@*' }]) elif uKey == u'language': # Changes the languages, reloads all strings and reloads the settings dialog Globals.uLanguage = uValue Globals.oApp.InitPathes() Globals.oNotifications.SendNotification( uNotification="on_language_change") elif uKey == u'locales': Globals.uLocalesName = uValue Globals.oTheScreen.LoadLocales() elif uKey == u'startrepeatdelay': Globals.fStartRepeatDelay = float(uValue) elif uKey == u'longpresstime': Globals.fLongPressTime = float(uValue) elif uKey == u'contrepeatdelay': Globals.fContRepeatDelay = float(uValue) elif uKey == u'clockwithseconds': Globals.bClockWithSeconds = (uValue == '1') elif uKey == u'longdate': Globals.bLongDate = (uValue == '1') elif uKey == u'longday': Globals.bLongDay = (uValue == '1') elif uKey == u'longmonth': Globals.bLongMonth = (uValue == '1') elif uKey == u'checkfornetwork': Globals.bConfigCheckForNetwork = (uValue == '1') elif uKey == u'vibrate': Globals.bVibrate = (uValue == '1') elif uKey == u'button_configureinterface': uButton, Globals.oTheScreen.uInterFaceToConfig, Globals.oTheScreen.uConfigToConfig = uValue.split( ':') Globals.oTheScreen.AddActionShowPageToQueue( uPageName=u'Page_InterfaceSettings') elif uKey == u'button_configurescripts': uAction: str uScriptName: str uAction, uScriptName = uValue.split(':') if uAction == "button_configure": Globals.oTheScreen.uScriptToConfig = uScriptName Globals.oTheScreen.AddActionShowPageToQueue( uPageName=u'Page_ScriptSettings') elif uAction == "button_run": kwargs = {"caller": "settings"} Globals.oScripts.RunScript(uScriptName, **kwargs) elif uKey == u'definition': ShowQuestionPopUp( uTitle='$lvar(599)', uMessage='$lvar(5026)', fktYes=Globals.oApp.on_config_change_change_definition, uStringYes='$lvar(5001)', uStringNo='$lvar(5002)') elif uKey == u'skin': Globals.oApp.ReStart() elif uKey == u'rootpath': if not Globals.bInit: Globals.oApp.close_settings() Globals.oApp._app_settings = None kivyConfig.write() Clock.schedule_once(Globals.oApp.Init_ReadConfig, 0) else: ShowMessagePopUp(uMessage=u'$lvar(5011)') elif uKey == u'sound_muteall': Globals.oSound.bMute = ToBool(uValue) elif uKey.startswith(u'soundvolume_'): uSoundName = uKey[12:] Globals.oSound.SetSoundVolume(uSoundName=uSoundName, iValue=ToInt(uValue)) Globals.oSound.PlaySound(uSoundName=uSoundName) elif uKey == u'button_changedefinitionsetting': Globals.uDefinitionToConfigure = uValue[7:] Globals.oTheScreen.AddActionShowPageToQueue( uPageName=u'Page_DefinitionSettings') if uKey in Globals.oDefinitions.aDefinitionSettingVars: SetVar(uVarName=uKey, oVarValue=uValue) else: pass
def ReadConfigFromIniFile(self, *, uConfigName: str) -> None: """ Reads the object config file :param string uConfigName: The configuration name to read :return: None """ if self.aIniSettings.bInitCompleted: return self.aIniSettings.bInitCompleted = True if uConfigName != u'': self.uConfigName = uConfigName self.uContext = self.oObject.uObjectName + u'/' + self.uConfigName self.SetContextVar(uVarName="context", uVarValue=self.uContext) self.uSection = self.uConfigName try: self.oObject.oObjectConfig.LoadConfig() if self.oObject.uObjectType == "interface": SetVar(uVarName=u'InterfaceCodesetList', oVarValue=self.oObject.CreateCodesetListJSONString()) SetVar(uVarName=u'ObjectConfigSection', oVarValue=uConfigName) dIniDef: Dict[ str, Dict] = self.oObject.oObjectConfig.CreateSettingJsonCombined( oSetting=self) for uKey2 in dIniDef: dLine: Dict = dIniDef[uKey2] uType: str = dLine.get("type") uKey: str = dLine.get("key") uDefault: str = dLine.get("default") if uKey is None or uDefault is None: continue # we replace JSON defaults by interface-settings defaults, if exists if self.aIniSettings.queryget(uKey) is not None: uDefault = self.aIniSettings.queryget(uKey) uResult: str = Config_GetDefault_Str( oConfig=self.oObject.oObjectConfig.oConfigParser, uSection=self.uSection, uOption=uKey, vDefaultValue=uDefault) if uType == "scrolloptions" or uType == "string": self.aIniSettings[uKey] = ReplaceVars(uResult) elif uType == "numeric" or uType == "numericslider": self.aIniSettings[uKey] = ToInt(uResult) elif uType == "numericfloat": self.aIniSettings[uKey] = ToFloat(uResult) elif uType == "bool": self.aIniSettings[uKey] = ToBool(uResult) elif uType == "varstring": self.aIniSettings[uKey] = ReplaceVars(uResult) elif uType == "path": if isinstance(uResult, str): self.aIniSettings[uKey] = cPath(uResult) else: self.aIniSettings[uKey] = uResult elif uType == "title" or uType == "buttons": pass else: self.ShowError( uMsg=u'Cannot read config name (base), wrong attribute:' + self.oObject.oObjectConfig.oFnConfig.string + u' Section:' + self.uSection + " " + dLine["type"]) if uKey == 'FNCodeset': self.ReadCodeset() self.oObject.oObjectConfig.oConfigParser.write() except Exception as e: self.ShowError(uMsg=u'Cannot read config name (base):' + self.oObject.oObjectConfig.oFnConfig.string + u' Section:' + self.uSection, oException=e) return
def Connect(self) -> bool: oSocket: socket.socket if not super().Connect(): return False try: try: self.ShowDebug( uMsg= u'Connecting to %s:%s with user: [%s] , password: [%s]' % (str(self.aIniSettings.uHost), str(self.aIniSettings.uPort), self.aIniSettings.uUser, self.aIniSettings.uPassword)) self.oTelnet = telnetlib.Telnet( ToBytes(self.aIniSettings.uHost), ToInt(self.aIniSettings.uPort), self.aIniSettings.fTimeOut) oSocket = self.oTelnet.get_socket() oSocket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 2048) ''' if not self.aIniSettings.uTerminalType == u'' and False: self.oTelnet.set_option_negotiation_callback(self.SetOption) ''' if not self.aIniSettings.uUser == u'': self.oTelnet.read_until(ToBytes("login: "******"\n")) if not self.aIniSettings.uPassword == u'': self.oTelnet.read_until(ToBytes("assword: "), 5) self.ShowDebug(uMsg=u'Sending Password') self.oTelnet.write( ToBytes(self.aIniSettings.uPassword + "\n")) except socket.gaierror as e: self.ShowError(uMsg=u'Cannot open telnet session:' + self.aIniSettings.uHost, oException=e) self.bOnError = True return False except socket.error as e: self.ShowError(uMsg=u'Connection refused:' + self.aIniSettings.uHost, oException=e) self.bOnError = True return False self.ShowDebug(uMsg=u'Connected!') if self.oThread: self.bStopThreadEvent = True self.oThread.join() self.oThread = None self.bStopThreadEvent = False self.oThread = Thread(target=self.Receive, ) self.oThread.start() self.bIsConnected = True except Exception as e: self.ShowError(uMsg=u'Cannot open socket #2:' + self.aIniSettings.uHost, oException=e) self.bOnError = True return False return True