def ExecuteActionSendNotification(self,oAction): """ WikiDoc:Doc WikiDoc:Context:ActionsDetails WikiDoc:Page:Actions-SendNotification WikiDoc:TOCTitle:noaction = sendnotification = Will send an ORCA internal notification This action will not modify the error code <div style="overflow:auto; "> {| border=1 class="wikitable" ! align="left" | string ! align="left" | notification ! align="left" | actionpars |- |sendnotification |notification string to send |Optional: Actionpars to be submitted: Format "{'parname1':'varvalue1','parname2':'varvalue2'}" |}</div> WikiDoc:End """ uNotification = ReplaceVars(oAction.dActionPars.get("notification","")) dActionPars = ToDic(ReplaceVars(oAction.dActionPars.get("actionpars","{}"))) if not isinstance(dActionPars,dict): dActionPars = ToDic(oAction.dActionPars.get("actionpars", "{}")) self.oEvenDispatcher.bDoNext = True self.oEvenDispatcher.LogAction(u'SendNotification',oAction) Globals.oNotifications.SendNotification(uNotification,**dActionPars) return -2
def ParseResult(self,uResponse, uParseOptions): ''' The parser function ''' if uParseOptions!= u'': aParseOptions = ToDic(uParseOptions) uGetVar = aParseOptions.get('getvar',u'') uGlobalDestVar = aParseOptions.get('gdestvar',u'') uLocalDestVar = aParseOptions.get('ldestvar',u'') uParseResultOption = aParseOptions.get('parseoption',u'store') uParseResultTokenizeString = aParseOptions.get('parsetoken',u':') return self.Parse(uResponse,uGetVar,uParseResultOption,uGlobalDestVar,uLocalDestVar,uParseResultTokenizeString) return "",""
def ParseResult(self, *, uResponse: str, uParseOptions: str) -> Tuple[str, str]: """ The parser function :param string uResponse: The response to parse :param string uParseOptions: A string representing the parse options (string of a dict) :return: The result of the parsing """ if uParseOptions != u'': dParseOptions: Dict = ToDic(uParseOptions) uGetVar: str = dParseOptions.get('getvar', u'') uGlobalDestVar: str = dParseOptions.get('gdestvar', u'') uLocalDestVar: str = dParseOptions.get('ldestvar', u'') uParseResultOption: str = dParseOptions.get( 'parseoption', u'store') uParseResultTokenizeString: str = dParseOptions.get( 'parsetoken', u':') uParseResultFlags: str = dParseOptions.get('parseflags', u'') return self.Parse(uResponse=uResponse, uGetVar=uGetVar, uParseResultOption=uParseResultOption, uGlobalDestVar=uGlobalDestVar, uLocalDestVar=uLocalDestVar, uTokenizeString=uParseResultTokenizeString, uParseResultFlags=uParseResultFlags) return "", ""
def ParseAction(self, *, vSource: Union[str, Dict, Element], oParentWidget: Optional[cWidgetBase] = None) -> None: """ Parses the action parameter in the action :param vSource: The sources for the values, could be a string, a dict or a xml element :param oParentWidget: The parent widget for the action :return: None """ try: ''' parses an action from a given element , could be a dict or a XML node''' if isinstance(vSource, str): Logger.error("Invalid Action Parameter:" + vSource) self.uActionString = 'noaction' self.iActionId = GetActionID(self.uActionString) return if isinstance(vSource, dict): self.dActionPars = vSource else: self.dActionPars = copy(vSource.attrib) if self.uFunctionContext: for uKey in self.dActionPars: self.dActionPars[uKey] = self.dActionPars[uKey].replace( "$par(", "$var(" + self.uFunctionContext + "_parameter_") if "commandparameter" in self.dActionPars: self.dActionPars["commandparameter"] = ToDic( self.dActionPars.get("commandparameter")) self.uActionString = self.dActionPars.get(u'string', u'noaction') self.SplitAction(uActionString=self.uActionString) ''' Parses an action from a Source object ''' self.oParentWidget = oParentWidget self.uActionName = self.dActionPars.get(u'name', u'noname') self.uActionString = self.dActionPars.get(u'string', u'noaction') self.iActionId = GetActionID(self.uActionString) self.uActionTapType = self.dActionPars.get(u'taptype', u'both') # uConfigName:str = u'' uInterFace: str = u'' if self.oParentWidget: uInterFace = self.dActionPars.get( u'interface', oParentWidget.oParentScreenPage.uDefaultInterface) uInterFace = self.dActionPars.get(u'interface', uInterFace) if uInterFace: Globals.oInterFaces.dUsedInterfaces[uInterFace] = True self.uRetVar = self.dActionPars.get(u'retvar', u'') self.bForce = self.dActionPars.get(u'force', False) except Exception as e: LogError(uMsg="Cant parse Action", oException=e)
def DumpStatus(self, **kwargs) -> None: """ Dumps the lights and groups status into varsvars """ try: vResult = kwargs['result'] if isinstance(vResult, str): vResult = ToDic(ReplaceVars(vResult)) dResult: Dict = vResult self.dStatus = dResult uPrefix: str = kwargs.get('retvar', '') if uPrefix == '': oAction: cAction = kwargs['oAction'] if oAction is not None: uPrefix = oAction.uRetVar dLights: Dict = dResult['lights'] dGroups: Dict = dResult['groups'] # Vars for Lights & Groups in one list iIndex: int = 0 for uLightKey in dLights: self.DumpSingleLight(iIndex, uLightKey, dLights[uLightKey], uPrefix, "Light") iIndex += 1 for uGroupKey in dGroups: self.DumpSingleLight(iIndex, uGroupKey, dGroups[uGroupKey], uPrefix, "Group") iIndex += 1 return None except Exception as e: LogErrorSmall(uMsg="DumpStatus: Error parsing HUE Bridge response", oException=e) return None
def DumpGroup(self, **kwargs) -> None: """ Dumps a specific light status set into customs vars """ try: vResult = kwargs['result'] if isinstance(vResult, str): vResult = ToDic(ReplaceVars(vResult)) dResult: Dict = vResult uPrefix: str = kwargs.get('retvar', '') uLightKey: str = kwargs.get('index', '') if uPrefix == '': oAction: cAction = kwargs['oAction'] if oAction is not None: uPrefix = oAction.uRetVar self.DumpSingleLight(iID=-1, uLightKey=uLightKey, dLight=dResult, uPrefix=uPrefix, uType=u'Group') return None except Exception as e: LogErrorSmall(uMsg="DumpGroup: Error parsing HUE Bridge response", oException=e) return None
def GetXMLDicAttribute(*, oXMLNode: Element, uTag: str, bMandatory: bool, dDefault: Dict) -> Dict: """ Returns a dict from a xml attribute """ return ToDic( GetXMLTextAttribute(oXMLNode=oXMLNode, uTag=uTag, bMandatory=bMandatory, vDefault=dDefault))
def TriggerLinkActions(uVarName:str) -> None: """ Executes all Actions given as a variable link to a variable. The actions will get excecuted immmediatly :param str uVarName: The variable name, for which the actions should get executed """ aVarLinks:cLinkPar = ORCA.vars.Globals.dUserVarLinks.get(uVarName, []) if len(aVarLinks)==0: return if isinstance(aVarLinks, list): for uCmd in aVarLinks: Logger.debug(u'Call Triggered Var Link Actions for: %s -> %s' %(uVarName,ToUnicode(uCmd))) if isinstance(uCmd, list): Globals.oTheScreen.AddActionToQueue(aActions=uCmd, bNewQueue=True) else: Globals.oTheScreen.AddActionToQueue(aActions=[ToDic(uCmd)], bNewQueue=True) else: Globals.oTheScreen.AddActionToQueue(aActions=[ToDic(aVarLinks)], bNewQueue=True) """
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''
def ParseXMLBaseNode(self, oXMLNode: Element, oParentScreenPage: cScreenPage, uAnchor: str) -> bool: try: self.uActionName = GetXMLTextAttribute(oXMLNode=oXMLNode, uTag=u'action', bMandatory=False, vDefault=u'') self.uActionNameDoubleTap = GetXMLTextAttribute( oXMLNode=oXMLNode, uTag=u'actiondoubletap', bMandatory=False, vDefault=u'') self.uActionNameLongTap = GetXMLTextAttribute( oXMLNode=oXMLNode, uTag=u'actionlongtap', bMandatory=False, vDefault=u'') self.uActionNameDownOnly = GetXMLTextAttribute( oXMLNode=oXMLNode, uTag=u'actiondownonly', bMandatory=False, vDefault=u'') self.uActionNameUpOnly = GetXMLTextAttribute(oXMLNode=oXMLNode, uTag=u'actionuponly', bMandatory=False, vDefault=u'') uActionPars: str = GetXMLTextAttribute(oXMLNode=oXMLNode, uTag=u'actionpars', bMandatory=False, vDefault=u'{}') if uActionPars.startswith("$var("): uActionPars = ReplaceVars(uActionPars) self.dActionPars = ToDic(uActionPars) if self.uActionName.startswith("SendCommand "): if len(self.dActionPars) == 0: self.dActionPars = {"commandname": self.uActionName[12:]} self.uActionName = "Send" if not self.uInterFace == u'': Globals.oInterFaces.dUsedInterfaces[self.uInterFace] = True return super().ParseXMLBaseNode(oXMLNode, oParentScreenPage, uAnchor) except Exception as e: LogError(uMsg=u'Error parsing widget from element (Action):[' + self.uName + "", oException=e) return False
def TriggerLinkActions(uVarName): """ Executes all Actions given as a variable link to a variable. The actions will get excecuted immmediatly :rtype: None :param string uVarName: The variable name, for which the actions should get executed """ aVarLinks = ORCA.vars.Globals.dUserVarLinks.get(uVarName, []) for uCmd in aVarLinks: Logger.debug(u'Call Triggered Var Link Actions for:' + uVarName) if isinstance(uCmd, list): Globals.oTheScreen.AddActionToQueue(aActions=uCmd, bNewQueue=True) else: Globals.oTheScreen.AddActionToQueue(aActions=[ToDic(uCmd)], bNewQueue=True)
def ParseResult(self, uResponse, uParseOptions): """ The parser function :rtype: tuple :param string uResponse: The reponse to parse :param string uParseOptions: A string representing the parse options (string of a dict) :return: The result of the parsing """ if uParseOptions != u'': aParseOptions = ToDic(uParseOptions) uGetVar = aParseOptions.get('getvar', u'') uGlobalDestVar = aParseOptions.get('gdestvar', u'') uLocalDestVar = aParseOptions.get('ldestvar', u'') uParseResultOption = aParseOptions.get('parseoption', u'store') uParseResultTokenizeString = aParseOptions.get('parsetoken', u':') return self.Parse(uResponse, uGetVar, uParseResultOption, uGlobalDestVar, uLocalDestVar, uParseResultTokenizeString) return "", ""
def ExecuteActionRunScript(self, oAction: cAction) -> eReturnCode: """ WikiDoc:Doc WikiDoc:Context:ActionsDetails WikiDoc:Page:Actions-RunScript WikiDoc:TOCTitle:runscript = runscript = Runs a script. Script results will be parsed by the resultparser. <div style="overflow:auto; "> {| class="wikitable" ! align="left" | Attribute ! align="left" | Description |- |string |runscript |- |scriptname |Name of the script to run (without path) |- |commandparameter |Parameters to pass to the script, format (json): '{"arg":"value",...}' |- |getvar |Variable name to parse form result |- |gdestvar |Variable name to parse form result |- |ldestvar |Local destination var for parsed result |- |parseoption |Option, how to parse the result (eg store, split,tokenize...) |- |parseflags |Flags for parser |- |parsetoken |tokenize token to use |}</div> WikiDoc:End """ self.oEventDispatcher.LogAction(uTxt=u'RunScript:', oAction=oAction) uScriptName: str = oAction.dActionPars.get("scriptname", "") dParameters: Dict = ToDic( ReplaceVars(oAction.dActionPars.get("commandparameter", "{}"))) Globals.oEvents.CopyActionPars(dTarget=dParameters, dSource=oAction.dActionPars, uReplaceOption="donotreplacetarget", bIgnoreHiddenWords=True) if isinstance(dParameters, dict): dParameters["oAction"] = oAction dParameters["caller"] = "action" dResponse: Union[Dict, None] = Globals.oScripts.RunScript( uScriptName, **dParameters) if dResponse: oResultParser: cEventScriptResultParser = cEventScriptResultParser( oAction) oResultParser.ParseResult(uResponse=ToUnicode(dResponse), uParseOptions=ToUnicode( oAction.dActionPars)) else: Logger.warning("Can't run script, parameter error:" + str(dParameters)) return eReturnCode.Nothing
def Orca_includesub(oElem: Union[Element, List[Element]], pLoader: Callable, uOrgDefinitionContext: str, oDef: cDefinition, uFileName: str = "Unknown Filename") -> Element: """ sub function for the include loader """ global bBlockInclude aElemens: List[Element] = [] oReplacementVars: cDefinitionVars = cDefinitionVars() oSaveReplacementVars: cDefinitionVars = cDefinitionVars() for e in oElem: aElemens.append(e) if oDef: oReplacementVars = oDef.oDefinitionVars i: int = 0 for e in aElemens: if oDef: e.set('definitionalias', oDef.uAlias) if e.tag == 'startskip': if CheckCondition(oPar=e): bBlockInclude = True if e.tag == 'stopskip': bBlockInclude = False if e.tag == ElementInclude.XINCLUDE_INCLUDE: if CheckCondition(oPar=e) and not bBlockInclude: # process xinclude directive uHref: str = e.get("href") uHref = ReplaceVars(uHref) uParse: str = e.get("parse", None) if uParse is None: uParse = "xml" if uParse == "xml": uNewDefinitionContext = u'' if "DEFINITIONPATH[" in uHref: uNewDefinitionContext, uHref = GetSetDefinitionName( uText=uHref) oTmpReplacementVars = e.get("definitionvars") if oTmpReplacementVars is None: oTmpReplacementVars = oReplacementVars aIncludeReplacementVars = e.get("includedefinitionvars") if aIncludeReplacementVars is None: aIncludeReplacementVars = cDefinitionVars() else: aIncludeReplacementVars = ToDic( aIncludeReplacementVars) aIncludeReplacementVars = aIncludeReplacementVars.copy() if oTmpReplacementVars is not None: oTmpReplacementVars = oTmpReplacementVars.copy() oSaveReplacementVars = oReplacementVars oReplacementVars = oTmpReplacementVars oReplacementVars.update(aIncludeReplacementVars) if oDef: oDef.oDefinitionVars = oTmpReplacementVars aNodes: List[Element] = pLoader(uHref, uParse, None, oReplacementVars) oNodes: Element # included element not found if len(aNodes) == 0: del oElem[i] i -= 1 else: uHref2 = uHref if uNewDefinitionContext == u'': oNodes = Orca_includesub(aNodes, pLoader, uOrgDefinitionContext, oDef, uHref2) else: oNodes = Orca_includesub(aNodes, pLoader, uNewDefinitionContext, oDef, uHref2) if oTmpReplacementVars is not None: oReplacementVars = oSaveReplacementVars if oDef: oDef.oDefinitionVars = oSaveReplacementVars if uNewDefinitionContext != u'': SetDefinitionContext( uDefinitionName=uOrgDefinitionContext) # we got a valid list of nodes bFirst: bool = True for oNode in oNodes: oNode = copy(oNode) if e.tail: oNode.tail = (oNode.tail or "") + e.tail if bFirst: oElem[i] = oNode bFirst = False else: oElem.insert(i, oNode) i += 1 else: Orca_includesub(e, pLoader, uOrgDefinitionContext, oDef, uFileName) # pass i += 1 return oElem
def SendCommand(self, oAction, oSetting, uRetVar, bNoLogOut=False): cBaseInterFace.SendCommand(self, oAction, oSetting, uRetVar, bNoLogOut) iTryCount = 0 iRet = 1 uRetVar = ReplaceVars(uRetVar) oSetting.uRetVar = uRetVar if uRetVar != "": oAction.uGlobalDestVar = uRetVar dCmd = ToDic(oAction.uCmd) uCmd = dCmd["method"] dParams = dCmd["params"] while iTryCount < 2: iTryCount += 1 oSetting.Connect() if oSetting.bIsConnected: try: self.ShowDebug("Sending elv max command: %s" % uCmd) oFunc = self.dInterfaceFunctions.get(uCmd) aResult = [] if oFunc is not None: aResult = oFunc(oSetting=oSetting, oAction=oAction, dParams=dParams) else: self.ShowError("Function not implemented: %s" % uCmd) for dLine in aResult: uGlobalDestVarSave = oAction.uGlobalDestVar uLocalDestVarSave = oAction.uLocalDestVar if oAction.uGetVar.startswith('ORCAMULTI'): aTmpGlobalDestVar = ToList(oAction.uGlobalDestVar) aTmpLocalDestVar = ToList(oAction.uLocalDestVar) oAction.uGlobalDestVar = "".join( '"' + e + dLine.uVarSuffix + '",' for e in aTmpGlobalDestVar)[:-1] oAction.uLocalDestVar = "".join( '"' + e + dLine.uVarSuffix + '",' for e in aTmpLocalDestVar)[:-1] else: oAction.uGlobalDestVar = oAction.uGlobalDestVar + dLine.uVarSuffix oAction.uLocalDestVar = oAction.uLocalDestVar + dLine.uVarSuffix uCmd, uRetVal = self.ParseResult( oAction, dLine.dValue, oSetting) oAction.uGlobalDestVar = uGlobalDestVarSave oAction.uLocalDestVar = uLocalDestVarSave break except Exception as e: self.ShowError(u'can\'t Send Message', oSetting.uConfigName, e) iRet = 1 else: oSetting.bIsConnected = False self.iLastRet = iRet if not bNoLogOut: 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) iTryCount: int = 0 eRet: eReturnCode = eReturnCode.Error uRetVar = ReplaceVars(uRetVar) oSetting.uRetVar = uRetVar if uRetVar != "": oAction.uGlobalDestVar = uRetVar dCmd: Dict = ToDic(oAction.uCmd) uCmd: str = dCmd["method"] dParams: Dict = dCmd["params"] while iTryCount < self.iMaxTryCount: iTryCount += 1 oSetting.Connect() if oSetting.bIsConnected: try: self.ShowDebug(uMsg="Sending elv max command: %s" % uCmd) oFunc: Callable = self.dInterfaceFunctions.get(uCmd) aResult: List = [] if oFunc is not None: aResult = oFunc(oSetting=oSetting, oAction=oAction, dParams=dParams) else: self.ShowError(uMsg="Function not implemented: %s" % uCmd) for dLine in aResult: uGlobalDestVarSave: str = oAction.uGlobalDestVar uLocalDestVarSave: str = oAction.uLocalDestVar if u'L' in oAction.uParseResultFlags: aTmpGlobalDestVar: List = ToList( oAction.uGlobalDestVar) aTmpLocalDestVar: List = ToList( oAction.uLocalDestVar) oAction.uGlobalDestVar = "".join( '"' + e + dLine.uVarSuffix + '",' for e in aTmpGlobalDestVar)[:-1] oAction.uLocalDestVar = "".join( '"' + e + dLine.uVarSuffix + '",' for e in aTmpLocalDestVar)[:-1] else: oAction.uGlobalDestVar = oAction.uGlobalDestVar + dLine.uVarSuffix oAction.uLocalDestVar = oAction.uLocalDestVar + dLine.uVarSuffix uCmd, uRetVal = self.ParseResult( oAction, dLine.dValue, oSetting) oAction.uGlobalDestVar = uGlobalDestVarSave oAction.uLocalDestVar = uLocalDestVarSave eRet = eReturnCode.Success break except Exception as e: self.ShowError(uMsg=u'can\'t Send Message', uParConfigName=oSetting.uConfigName, oException=e) eRet = eReturnCode.Error else: oSetting.bIsConnected = False self.CloseSettingConnection(oSetting=oSetting, bNoLogOut=bNoLogOut) return eRet
def SendCommand_Helper(self, oAction, oSetting, uInterFaceName): iRet = None self.uResponse = u'' uUrlFull = oAction.uProtocol + oSetting.aInterFaceIniSettings.uHost + ":" + oSetting.aInterFaceIniSettings.uPort + oAction.uCmd uUrlFull = ReplaceVars(uUrlFull, uInterFaceName + u'/' + oSetting.uConfigName) uUrlFull = ReplaceVars(uUrlFull) # oSetting.SetContextVar('Host',oSetting.aInterFaceIniSettings.uHost) # oSetting.SetContextVar('Port',oSetting.aInterFaceIniSettings.uPort) sAuth = u'' #self.register_app('http://'+oAction.uHost,oSetting) #self.register_app(uUrlFull,oSetting) try: uData = oAction.uParams uData = ReplaceVars(uData, uInterFaceName + u'/' + oSetting.uConfigName) uData = ReplaceVars(uData) # we do nothing special on soap actions if oAction.uType == 'soap': pass # we do nothing special on plain string actions if oAction.uType == 'string': pass if oAction.uType == 'none': return -1 if oAction.uType == 'encode': if PY2: uData = urllib.urlencode(uData) else: uData = urllib.parse.urlencode(uData) uData = ReplaceVars(uData, uInterFaceName + u'/' + oSetting.uConfigName) uData = ReplaceVars(uData) SetVar(uVarName='datalenght', oVarValue=ToUnicode(len(uData)), uContext=uInterFaceName + u'/' + oSetting.uConfigName) if oAction.uActionName == 'logon' or True: # base64 encode the username and password uTmp = ReplaceVars( '%s:%s' % ('$cvar(CONTEXT_USER)', '$cvar(CONTEXT_PASSWORD)'), uInterFaceName + u'/' + oSetting.uConfigName) if PY2: sAuth = base64.encodestring(uTmp).replace('\n', '') else: bTmp = ToBytes(uTmp) #bTmp = base64.encodestring(bTmp) bTmp = base64.encodebytes(bTmp) uTmp = bTmp.decode('utf-8') sAuth = uTmp.replace('\n', '') #sAuth = base64.encodestring(bTmp).replace('\n', '') #construct and send the header uHeader = oAction.uHeaders uHeader = ReplaceVars(uHeader, uInterFaceName + u'/' + oSetting.uConfigName) uHeader = ReplaceVars(uHeader) uHeader = ReplaceVars(uHeader, uInterFaceName + u'/' + oSetting.uConfigName) aHeader = ToDic(uHeader) for uKey in aHeader: if isinstance(aHeader[uKey], string_types): aHeader[uKey] = UnEscapeUnicode(aHeader[uKey]) if not sAuth == u'': aHeader['Authorization'] = "Basic %s" % sAuth self.ShowInfo( u'Sending Command [%s]: %s %s to %s' % (oAction.uActionName, uData, UnEscapeUnicode(uHeader), uUrlFull), oSetting.uConfigName) if not oAction.bWaitForResponse: oSetting.bIgnoreTimeOut = True fTimeOut = 0.02 else: oSetting.bIgnoreTimeOut = False fTimeOut = oSetting.aInterFaceIniSettings.fTimeOut self.bStopWait = False self.oReq = UrlRequest(uUrlFull, method=oAction.uRequestType, req_body=uData, req_headers=aHeader, timeout=fTimeOut, on_error=oSetting.OnError, on_success=oSetting.OnReceive, debug=False) if oAction.bWaitForResponse: self.NewWait(0.05) if self.oReq.resp_status is not None: uCmd, uRetVal = self.ParseResult(oAction, self.oReq.result, oSetting) iRet = self.oReq.resp_status self.uResponse = self.oReq.result else: if self.oReq._error is not None: self.uResponse = self.oReq._error.strerror iRet = self.oReq._error.errno if iRet is None: iRet = 200 if self.uResponse is None: self.uResponse = "unknown" return iRet, self.uResponse else: return 200, '' except Exception as e: self.ShowError(u'can\'t Send Message #2', oSetting.uConfigName, e) return -1, ''
def DownloadDownloadQueue(self) -> None: """ starts to load the complete queue """ uRep: str tRep: Tuple bDoRestart: bool = False bDoRefresh: bool = False if "setting" in Globals.oTheScreen.uCurrentPageName.lower(): bDoRefresh = True oEvents = Globals.oEvents for uRep in self.aQueue: if uRep.startswith("definitions"): bDoRestart = True aActions: List[cAction] = oEvents.CreateSimpleActionList( aActions=[{ 'string': 'setvar', 'varname': 'DOWNLOADERROR', 'varvalue': '0' }, { 'string': 'showprogressbar', 'title': '$lvar(5015)', 'message': 'Load File', 'max': '100' }]) for uItem in self.aItemQueue: uType: str = ToDic(uItem)['Type'] uPrettyRepName: str = '?' for tRep in Globals.aRepNames: if tRep[1] == uType: uPrettyRepName = ReplaceVars(tRep[0]) break uName: str = '%s: %s' % (uPrettyRepName, ToDic(uItem)['Name']) oEvents.AddToSimpleActionList(aActionList=aActions, aActions=[{ 'string': 'showprogressbar', 'message': uName, 'current': '0' }, { 'string': 'loadresource', 'resourcereference': uItem, 'condition': "$var(DOWNLOADERROR)==0" }]) oEvents.AddToSimpleActionList(aActionList=aActions, aActions=[{ 'string': 'showprogressbar' }, { 'string': 'showquestion', 'title': '$lvar(595)', 'message': '$lvar(698)', 'actionyes': 'dummy', 'condition': '$var(DOWNLOADERROR)==1' }]) if bDoRefresh and not bDoRestart: oEvents.AddToSimpleActionList(aActionList=aActions, aActions=[{ 'string': 'updatewidget', 'widgetname': 'SettingsDownload' }]) if bDoRestart: oEvents.AddToSimpleActionList(aActionList=aActions, aActions=[{ 'string': 'restartafterdefinitiondownload', 'condition': '$var(DOWNLOADERROR)==0' }]) #Execute the Queue StopWait() oEvents.ExecuteActionsNewQueue(aActions=aActions, oParentWidget=None)
def Orca_includesub(elem, loader, uOrgDefinitionContext, oDef, uFileName="Unknown Filename"): """ sub function for the include loader """ global bBlockInclude elemens = [] oReplacementVars = cDefinitionVars() for e in elem: elemens.append(e) if oDef: oReplacementVars = oDef.oDefinitionVars i = 0 for e in elemens: e.set('definitioncontext', uOrgDefinitionContext) if oDef: e.set('definitionalias', oDef.uAlias) e.set('linefilename', uFileName) if e.tag == 'startskip': if CheckCondition(e): bBlockInclude = True if e.tag == 'stopskip': bBlockInclude = False if e.tag == ElementInclude.XINCLUDE_INCLUDE: if CheckCondition(e) and not bBlockInclude: # process xinclude directive href = e.get("href") parse = e.get("parse", "xml") if parse == "xml": uNewDefinitionContext = u'' if "DEFINITIONPATH[" in href: uNewDefinitionContext, href = GetSetDefinitionName( href) oTmpReplacementVars = e.get("definitionvars") if oTmpReplacementVars is None: oTmpReplacementVars = oReplacementVars aIncludeReplacementVars = e.get("includedefinitionvars") if aIncludeReplacementVars is None: aIncludeReplacementVars = cDefinitionVars() else: aIncludeReplacementVars = ToDic( aIncludeReplacementVars) # aIncludeReplacementVars = aIncludeReplacementVars.copy() if oTmpReplacementVars is not None: oTmpReplacementVars = oTmpReplacementVars.copy() #oTmpReplacementVars=ToDic(oTmpReplacementVars) aSaveReplacementVars = oReplacementVars oReplacementVars = oTmpReplacementVars oReplacementVars.update(aIncludeReplacementVars) if oDef: oDef.oDefinitionVars = oTmpReplacementVars oFnHRefRedirect = Globals.oTheScreen.oSkin.dSkinRedirects.get( cFileName(u'').ImportFullPath(ReplaceVars(href))) if oFnHRefRedirect is not None: oFnHRef = oFnHRefRedirect.string oFnHRef = cFileName(u'').ImportFullPath(ReplaceVars(href)) nodes = loader(oFnHRef.string, parse, None, oReplacementVars) if nodes is not None: if uNewDefinitionContext == u'': nodes = Orca_includesub(nodes, loader, uOrgDefinitionContext, oDef, oFnHRef.string) else: nodes = Orca_includesub(nodes, loader, uNewDefinitionContext, oDef, oFnHRef.string) if oTmpReplacementVars is not None: oReplacementVars = aSaveReplacementVars if oDef: oDef.oDefinitionVars = aSaveReplacementVars if uNewDefinitionContext != u'': SetDefinitionContext(uOrgDefinitionContext) if isinstance(nodes, list): bFirst = True for node in nodes: node = copy(node) if e.tail: node.tail = (node.tail or "") + e.tail if bFirst: elem[i] = node bFirst = False else: elem.insert(i, node) i = i + 1 elif nodes is None: del elem[i] i = i - 1 else: nodes = copy(nodes) if e.tail: nodes.tail = (nodes.tail or "") + e.tail elem[i] = nodes else: Orca_includesub(e, loader, uOrgDefinitionContext, oDef, uFileName) i = i + 1 return elem
def GetXMLDicAttribute(oXMLNode, uTag, bMandantory, aDefault): """ Returns a dict from a xml attribute """ return ToDic(GetXMLTextAttribute(oXMLNode, uTag, bMandantory, aDefault))
def ExecuteActionSendCommand(self, oAction: cAction) -> eReturnCode: """ WikiDoc:Doc WikiDoc:Context:ActionsDetails WikiDoc:Page:Actions-SendCommand WikiDoc:TOCTitle:sendcommand = sendcommand = The core action. This sends a command to an interface. The command parameter are passed to the interface, refer to the interface documentation, which parameters are used. <div style="overflow:auto; "> {| class="wikitable" ! align="left" | Attribute ! align="left" | Description |- |string |sendcommand |- |commandname |Name of the command to send to the interface |- |commandparameter |additional parameter to pass to interface/codeset |- |interface |Interface to use. If not given, it will be used as given in the following order: widget, anchor, page |- |configname |Configuration to use |}</div> A short example: <div style="overflow-x: auto;"><syntaxhighlight lang="xml"> <action name="Send Set Volume Sub" string="sendcommand setvolumesub" commandparameter='{"volumetoset":"$var(volumetoset)"}'/> </syntaxhighlight></div> WikiDoc:End """ uInterFace: str = u'' uConfigName: str = u'' uCommandName: str vCommandParameter: Union[str, Dict] = oAction.dActionPars.get( "commandparameter", "{}") if isinstance(vCommandParameter, str): oAction.dCommandParameter = ToDic(ReplaceVars(vCommandParameter)) if isinstance(vCommandParameter, dict): oAction.dCommandParameter = ToDic( ReplaceVars(DictToUnicode(vCommandParameter))) uCommandName = ReplaceVars(oAction.dActionPars.get("commandname", "")) try: uInterFace, uConfigName = self.oEventDispatcher.GetTargetInterfaceAndConfig( oAction=oAction) oInterface: cBaseInterFace = Globals.oInterFaces.GetInterface( uInterFace) if oInterface: if not oInterface.bIsInit: oInterface.Init(uInterFace) oTmpAction: cAction = copy(oAction) oTmpAction.uActionString = ReplaceVars( oTmpAction.uActionString) oTmpAction.dActionPars[u'configname'] = uConfigName Logger.debug( u'Action: Send Command: [%s] Interface: %s Config: %s' % (uCommandName, uInterFace, uConfigName)) eRet: eReturnCode = oInterface.DoAction(oTmpAction) SetVar(uVarName=u'INTERFACEERRORCODE_' + uInterFace + u'_' + uConfigName, oVarValue=ToUnicode(eRet)) return eRet else: if uInterFace != "": SetVar(uVarName=u'INTERFACEERRORCODE_' + uInterFace + u'_' + uConfigName, oVarValue=u'1') LogError( uMsg= u'Action: Send Command failed #1: [%s] Interface: %s Config: %s : Interface not found!' % (uCommandName, uInterFace, uConfigName)) else: LogError( uMsg= u'Action: Send Command failed #2: [%s]: No Interface given!' % uCommandName) return eReturnCode.Error except Exception as e: SetVar(uVarName=u'INTERFACEERRORCODE_' + uInterFace + u'_' + uConfigName, oVarValue=u"1") LogError( uMsg= u'Action: Send Command failed #2: [%s] Interface: %s Config: %s' % (uCommandName, uInterFace, uConfigName), oException=e) return eReturnCode.Error
def ParseXMLBaseNode(self, oXMLNode, oParentScreenPage, uAnchor): try: global oLastWidget self.GetWidgetTypeFromXmlNode(oXMLNode) uDefinitionContext = GetXMLTextAttribute( oXMLNode, u'definitioncontext', False, Globals.uDefinitionContext) uAlias = oXMLNode.get('definitionalias') oDef = None if uAlias is not None: oDef = Globals.oDefinitions.dDefinitionList_Dict[uAlias] self.oDef = oDef self.uDefinitionContext = uDefinitionContext self.uName = GetXMLTextAttribute(oXMLNode, u'name', True, u'NoName') self.oParentScreenPage = oParentScreenPage self.uPageName = self.oParentScreenPage.uPageName #default anchor is screen self.iAnchorPosX = 0 self.iAnchorPosY = 0 self.iAnchorWidth = self.oDef.iDefMaxX self.iAnchorHeight = self.oDef.iDefMaxY self.iGapX = oDef.iGapX self.iGapY = oDef.iGapY self.fRationX = oDef.fRationX self.fRationY = oDef.fRationY self.uAnchorName = GetXMLTextAttribute(oXMLNode, u'anchor', False, u'') if self.uAnchorName == u'': self.uAnchorName = uAnchor if self.uAnchorName: self.oTmpAnchor = self.oParentScreenPage.dWidgets.get( self.uAnchorName) if self.oTmpAnchor is not None: # oTmpAnchor is already aligned to screen size self.iAnchorPosX = self.oTmpAnchor.iPosX self.iAnchorPosY = self.oTmpAnchor.iPosY self.iAnchorWidth = self.oTmpAnchor.iWidth self.iAnchorHeight = self.oTmpAnchor.iHeight # We parse for Text and change later to integer self.iWidth = ReplaceVars( GetXMLTextAttribute(oXMLNode, u'width', False, u'')) self.iHeight = ReplaceVars( GetXMLTextAttribute(oXMLNode, u'height', False, u'')) iAnchorWidth = (self.iAnchorWidth) iAnchorHeight = (self.iAnchorHeight) bApplyWidth = False if self.iWidth == u'': self.iWidth = iAnchorWidth elif self.iWidth.startswith('of:height:self'): bApplyWidth = True elif self.iWidth.startswith('of:toleft'): bApplyWidth = True elif self.iWidth.startswith('of:'): self.iWidth = self._ParseDimPosValue(self.iWidth) elif self.iWidth[0] == u'%': fPercentage = float(self.iWidth[1:]) self.iWidth = ((fPercentage / 100) * iAnchorWidth) elif self.iWidth[0] == u'd': # we define: First Value is dp value, # second value is absolute value (unscaled) # eg d20:50 would result either d20 or 50, whatever is larger tTmp = SplitMax(self.iWidth[1:]) if tTmp[1] == 0: uVar = dp(tTmp[0]) else: uVar = max(dp(tTmp[0]), tTmp[1]) self.iWidth = uVar else: #Logger.warning("Depriciated absolute width used:"+self.uName+ " from:"+self.uPageName) self.iWidth = int(self.iWidth) if self.iHeight == u'': self.iHeight = iAnchorHeight elif self.iHeight[0] == u'%': fPercentage = float(self.iHeight[1:]) self.iHeight = ((fPercentage / 100) * iAnchorHeight) elif self.iHeight.startswith('of:'): if not bApplyWidth: self.iHeight = self._ParseDimPosValue(self.iHeight) else: self.iHeight = self._ParseDimPosValue(self.iHeight) elif self.iHeight[0] == u'd': # we define: First Value is dp value, # second value is absolute value (unscaled) tTmp = SplitMax(self.iHeight[1:]) if tTmp[1] == 0: uVar = dp(tTmp[0]) else: uVar = max(dp(tTmp[0]), tTmp[1]) self.iHeight = uVar else: #Logger.warning("Depriciated absolute height used:"+self.uName+ " from:"+self.uPageName) self.iHeight = int(self.iHeight) if bApplyWidth: self.iWidth = self._ParseDimPosValue(self.iWidth) #We parse for Text and change later to integer self.iPosX = ReplaceVars( GetXMLTextAttribute(oXMLNode, u'posx', False, u'left')) self.iPosY = ReplaceVars( GetXMLTextAttribute(oXMLNode, u'posy', False, u'top')) self.bEnabled = GetXMLBoolAttribute(oXMLNode, u'enabled', False, True) self.uCaption = u'' self.uBackGroundColor = GetXMLTextAttribute( oXMLNode, u'backgroundcolor', False, u'#00000000') self.tBackGroundColor = GetColorFromHex( ReplaceVars(self.uBackGroundColor)) self.uActionName = GetXMLTextAttribute(oXMLNode, u'action', False, u'') self.uActionNameDoubleTap = GetXMLTextAttribute( oXMLNode, u'actiondoubletap', False, u'') self.uActionNameLongTap = GetXMLTextAttribute( oXMLNode, u'actionlongtap', False, u'') self.uActionNameDownOnly = GetXMLTextAttribute( oXMLNode, u'actiondownonly', False, u'') self.uActionNameUpOnly = GetXMLTextAttribute( oXMLNode, u'actionuponly', False, u'') self.uInterFace = GetXMLTextAttribute(oXMLNode, u'interface', False, u'') self.uConfigName = GetXMLTextAttribute(oXMLNode, u'configname', False, u'') uActionPars = GetXMLTextAttribute(oXMLNode, u'actionpars', False, u'{}') if uActionPars.startswith("$var("): uActionPars = ReplaceVars(uActionPars) self.dActionPars = ToDic(uActionPars) if self.uActionName.startswith("SendCommand "): if len(self.dActionPars) == 0: self.dActionPars = {"commandname": self.uActionName[12:]} self.uActionName = "Send" if not self.uInterFace == u'': Globals.oInterFaces.dUsedInterfaces[self.uInterFace] = True fPercentage = -1.0 if not self.iPosY == u'': if self.iPosY == u'bottom': fPercentage = 100.0 elif self.iPosY.startswith('of:'): self.iPosY = self._ParseDimPosValue(self.iPosY) elif self.iPosY == u'top': fPercentage = 0.0 elif self.iPosY == u'middle': fPercentage = 50.0 elif self.iPosY.isdigit(): Logger.warning("Depriciated absolute PosY used:" + self.uName + " from:" + self.uPageName) self.iPosY = (int(self.iPosY) + self.iAnchorPosY) elif self.iPosY[0] == u'%': fPercentage = float(self.iPosY[1:]) elif self.iPosY[0] == u'd': self.iPosY = dp(float(self.iPosY[1:])) + self.iAnchorPosY self.iPosY = Globals.iAppHeight - self.iHeight - self.iPosY elif self.iPosY[0] == u's': self.iPosY = sp(float(self.iPosY[1:])) + self.iAnchorPosY self.iPosY = Globals.iAppHeight - self.iHeight - self.iPosY else: LogError(u'WidgetBase: Fatal Error:Wrong ypos:' + self.uName) self.iPosY = 0 if not fPercentage == -1.0: self.iPosY = self.iAnchorPosY + ( (fPercentage / 100) * self.iAnchorHeight) - (self.iHeight * (fPercentage / 100)) fPercentage = -1.0 if not self.iPosX == u'': if self.iPosX == u'right': fPercentage = 100.0 elif self.iPosX.startswith('of:'): self.iPosX = self._ParseDimPosValue(self.iPosX) elif self.iPosX == u'left': fPercentage = 0.0 elif self.iPosX == u'center': fPercentage = 50.0 elif self.iPosX.isdigit(): Logger.warning("Depriciated absolute PosX used:" + self.uName + " from:" + self.uPageName) self.iPosX = (int(self.iPosX)) + self.iAnchorPosX elif self.iPosX[0] == u'%': fPercentage = float(self.iPosX[1:]) elif self.iPosX[0] == u'd': self.iPosX = dp(float(self.iPosX[1:])) + self.iAnchorPosX elif self.iPosX[0] == u's': self.iPosX = sp(float(self.iPosX[1:])) + self.iAnchorPosX else: LogError(u'WidgetBase: Fatal Error:Wrong xpos:' + self.uName + " " + str(self.iPosX)) self.iPosX = 0 if not fPercentage == -1.0: self.iPosX = self.iAnchorPosX + ( (fPercentage / 100) * self.iAnchorWidth) - (self.iWidth * (fPercentage / 100)) if self.bHasText: self.uhTextAlign = GetXMLTextAttribute(oXMLNode, u'htextalign', False, u'center') self.uvTextAlign = GetXMLTextAttribute(oXMLNode, u'vtextalign', False, u'middle') self.bBold = GetXMLBoolAttribute(oXMLNode, u'bold', False, False) self.bItalic = GetXMLBoolAttribute(oXMLNode, u'italic', False, False) self.uFontIndex = GetXMLTextAttribute(oXMLNode, u'fontid', False, oDef.uDefaultFont) self.uOrgFontIndex = self.uFontIndex sFontSize = GetXMLTextAttribute(oXMLNode, u'fontsize', False, '0') sIconFontSize = GetXMLTextAttribute(oXMLNode, u'iconfontsize', False, sFontSize) self.tTextColor = GetXMLTextAttribute(oXMLNode, u'textcolor', False, u'') self.SetCaption( GetXMLTextAttribute(oXMLNode, u'caption', False, u'')) self.uOrgSecondCaption = GetXMLTextAttribute( oXMLNode, u'secondcaption', False, u'') Globals.oTheScreen.oFonts.dUsedFonts[self.uFontIndex] = True if self.tTextColor == u'': if self.iWidgetType == oWidgetType.Button or self.iWidgetType == oWidgetType.DropDown or self.iWidgetType == oWidgetType.Switch: self.tTextColor = Globals.oTheScreen.oSkin.dSkinAttributes.get( 'fontcolor button') elif self.iWidgetType == oWidgetType.TextField or self.iWidgetType == oWidgetType.TextInput or self.iWidgetType == oWidgetType.Slider: self.tTextColor = Globals.oTheScreen.oSkin.dSkinAttributes.get( 'fontcolor text') elif self.iWidgetType == oWidgetType.FileViewer or self.iWidgetType == oWidgetType.Settings: self.tTextColor = Globals.oTheScreen.oSkin.dSkinAttributes.get( 'fontcolor file') elif self.iWidgetType == oWidgetType.BackGround: self.tTextColor = GetColorFromHex(u'#FFFFFFFF') if self.tTextColor is None or self.tTextColor == u'': self.tTextColor = GetColorFromHex(u'#FFFFFFFF') else: self.tTextColor = GetColorFromHex(self.tTextColor) if sFontSize == "0": if self.iWidgetType == oWidgetType.Button or self.iWidgetType == oWidgetType.DropDown or self.iWidgetType == oWidgetType.Switch: sFontSize = str(oDef.iFontSize_Button) elif self.iWidgetType == oWidgetType.TextField or self.iWidgetType == oWidgetType.TextInput or self.iWidgetType == oWidgetType.Slider: sFontSize = str(oDef.iFontSize_Text) elif self.iWidgetType == oWidgetType.FileViewer or self.iWidgetType == oWidgetType.Settings: sFontSize = str(oDef.iFontSize_File) if sIconFontSize == "0": if self.iWidgetType == oWidgetType.Button or self.iWidgetType == oWidgetType.DropDown or self.iWidgetType == oWidgetType.Switch: sIconFontSize = str(oDef.iFontSize_Button) elif self.iWidgetType == oWidgetType.TextField or self.iWidgetType == oWidgetType.TextInput or self.iWidgetType == oWidgetType.Slider: sIconFontSize = str(oDef.iFontSize_Text) elif self.iWidgetType == oWidgetType.FileViewer or self.iWidgetType == oWidgetType.Settings: sIconFontSize = str(oDef.iFontSize_File) # todo: check where to scale fonts if sFontSize[0] == u'd': self.iFontSize = dp(sFontSize[1:]) * self.fRationX elif sFontSize[0] == u's': self.iFontSize = sp(sFontSize[1:]) * self.fRationX elif sFontSize.startswith(u'%h'): self.iFontSize = ((int(sFontSize[2:]) * self.iHeight) / 100 ) # *self.fRationY elif sFontSize.startswith(u'%w'): self.iFontSize = ((int(sFontSize[2:]) * self.iWidth) / 100 ) # *self.fRationX else: self.iFontSize = ToInt(sFontSize) if self.iFontSize != 0: Logger.warning("Depriciated absolute fontsize used:" + self.uName + " from:" + self.uPageName) if sIconFontSize[0] == u'd': self.iIconFontSize = dp(sIconFontSize[1:]) * self.fRationX elif sIconFontSize[0] == u's': self.iIconFontSize = sp(sIconFontSize[1:]) * self.fRationX elif sIconFontSize.startswith(u'%h'): self.iIconFontSize = ( (int(sIconFontSize[2:]) * self.iHeight) / 100 ) # *self.fRationY elif sIconFontSize.startswith(u'%w'): self.iIconFontSize = ( (int(sIconFontSize[2:]) * self.iWidth) / 100 ) # *self.fRationX else: self.iIconFontSize = ToInt(sIconFontSize) if self.iIconFontSize != 0: Logger.warning("Depriciated absolute fontsize used:" + self.uName + " from:" + self.uPageName) if not hasattr(self, 'bIsDropButton'): oLastWidget = self self.iPosXInit = self.iPosX self.iPosYInit = self.iPosY self.iWidthInit = self.iWidth self.iHeightInit = self.iHeight self.iFontSizeInit = self.iFontSize return True except Exception as e: LogError(u'Error parsing widget from element:[' + self.uName + "", e) return False
def __GetUsedDefinitions_Sub(self, uDefinitionName, bImportActions, bImportLanguages, bImportPages, bImportSettings, uParentDefinitionName, uParentDefinitionAlias, aDefinitionVarsFromParent, uAlias): aAdditionalDefVars = {} if not uAlias in self.dDefinitionList_Dict: oDefinitionPathes = cDefinitionPathes(uDefinitionName) SetVar(uVarName="DEFINITIONPATH[%s]" % (uDefinitionName), oVarValue=oDefinitionPathes.oPathDefinition.string) SetVar( uVarName="DEFINITIONPATHSKINELEMENTS[%s]" % (uDefinitionName), oVarValue=oDefinitionPathes.oPathDefinitionSkinElements.string) Globals.dDefinitionPathes[uDefinitionName] = oDefinitionPathes SetDefinitionPathes(uDefinitionName) oFnDefinition = Globals.oDefinitionPathes.oFnDefinition Logger.debug(u'TheScreen: Load Definition XmlFile:' + oFnDefinition) oDefinition = cDefinition(uDefinitionName, self) oDefinition.uParentDefinitionName = uParentDefinitionName oDefinition.bImportActions = bImportActions oDefinition.bImportLanguages = bImportLanguages oDefinition.bImportPages = bImportPages oDefinition.bImportSettings = bImportSettings oDefinition.oDefinitionVarsFromParent = aDefinitionVarsFromParent #we read the definitionvars first with raw funtions sET_Data = CachedFile(Globals.oDefinitionPathes.oFnDefinition) oET_Root = fromstring(sET_Data) oRef = oET_Root.find('def_parameter') # And merge / Replace the existing Vars oDefinition.oDefinitionVars.clear() oDefinition.oDefinitionVars.update( ToOrderedDic( GetXMLTextValue(oRef, u'definitionvars', False, u'{}'))) if len(aDefinitionVarsFromParent) > 0: for uVarName in oDefinition.oDefinitionVars: if uVarName in oDefinition.oDefinitionVarsFromParent: oDefinition.oDefinitionVars[ uVarName] = oDefinition.oDefinitionVarsFromParent[ uVarName] else: Logger.warning( "Importing definition %s from %s: Definition varname not passed: '%s', using default %s" % (oDefinition.uName, uParentDefinitionName, uVarName, oDefinition.oDefinitionVars[uVarName])) for uVarName in aDefinitionVarsFromParent: if not uVarName in oDefinition.oDefinitionVars: oDefinition.oDefinitionVars[ uVarName] = oDefinition.oDefinitionVarsFromParent[ uVarName] aAdditionalDefVars[ uVarName] = oDefinition.oDefinitionVarsFromParent[ uVarName] for uKey in oDefinition.oDefinitionVars: uVar = oDefinition.oDefinitionVars[uKey] if "$cookie(" in uVar: uValue = GetCookieValue(uVar) oDefinition.oDefinitionVars[uKey] = uValue if uAlias == u'': # this works on all python versions for uKey in oDefinition.oDefinitionVars: uAlias = oDefinition.oDefinitionVars[uKey] break if uAlias == '': uAlias = uDefinitionName oDefinition.uDefPublicTitle = uDefinitionName #create a default alias def var uAliasDefVar = "definition_alias_" + uAlias if oDefinition.oDefinitionVars.get(uAliasDefVar) is None: SetDefVar(uVarName=uAliasDefVar, uVarValue=uAlias, dArray=oDefinition.oDefinitionVars) else: oDefinition.uDefPublicTitle = "%s [%s]" % (uAlias, uDefinitionName) oDefinition.uAlias = uAlias if not uAlias in self.dDefinitionList_Dict: # create defvars for import pages aTmpDefinitionVars = copy(oDefinition.oDefinitionVars) for uVar in aTmpDefinitionVars: if not uVar.endswith("_IMPORTPAGES"): if bImportPages: SetDefVar(uVarName=uVar + "_IMPORTPAGES", uVarValue="1", dArray=oDefinition.oDefinitionVars) else: SetDefVar(uVarName=uVar + "_IMPORTPAGES", uVarValue="0", dArray=oDefinition.oDefinitionVars) #and now again with adjusted definitionvars oET_Root = Orca_FromString(sET_Data, oDefinition, "root") oDefinition.oET_Root = oET_Root oDefinition.sET_Data = sET_Data self.AddDefinition(oDefinition) oXMLIncludes = oET_Root.find('definitionimports') if oXMLIncludes is not None: for oXMLInclude in oXMLIncludes.findall('definition'): uDefinitionNameImp = GetXMLTextValue( oXMLInclude, u'', True, '') bImportActionsImp = GetXMLBoolAttribute( oXMLInclude, u'importactions', False, False) bImportLanguagesImp = GetXMLBoolAttribute( oXMLInclude, u'importlanguages', False, False) bImportPagesImp = GetXMLBoolAttribute( oXMLInclude, u'importpages', False, False) bImportSettingsImp = GetXMLBoolAttribute( oXMLInclude, u'importsettings', False, False) uAliasImp = GetXMLTextAttribute( oXMLInclude, u'alias', False, '') aDefinitionVarsImp = cDefinitionVars() aDefinitionVarsImp.update( ToDic( GetXMLTextAttribute(oXMLInclude, u'definitionvars', False, {}))) # Pass Through of additional Definitionvars for uVarName in aAdditionalDefVars: if not uVarName in aDefinitionVarsImp: aDefinitionVarsImp[ uVarName] = aAdditionalDefVars[uVarName] self.__GetUsedDefinitions_Sub( uDefinitionNameImp, bImportActionsImp, bImportLanguagesImp, bImportPagesImp, bImportSettingsImp, oDefinition.uName, oDefinition.uAlias, aDefinitionVarsImp, uAliasImp) else: Logger.debug( u'GetUsedDefinitions: Skipping duplicate xml %s [%s]' % (uAlias, uDefinitionName)) else: Logger.debug( u'GetUsedDefinitions: Skipping duplicate xml %s [%s]' % (uAlias, uDefinitionName))
def DoAction(self, oAction): """ Main entry function for performing an action. Handles repeating actions :rtype: int :param cAction oAction: :return: 0 if successfull, 1 onnexception error, -10 if codeset not found """ uConfigName = oAction.dActionPars.get(u'configname', u'') oSetting = self.GetSettingObjectForConfigName(uConfigName) uCmdName = ReplaceVars(oAction.dActionPars.get('commandname', "")) uCmdNameLocal = oSetting.MakeLocalActionName(uCmdName) aActions = Globals.oActions.GetActionList(uActionName=uCmdNameLocal, bNoCopy=False) if aActions is None: self.ShowError("Action not found:" + uCmdName, uConfigName) return -10 for uKey in oAction.dCommandParameter: oSetting.SetContextVar(uKey, oAction.dCommandParameter[uKey]) SetVar(uVarName=uKey, oVarValue=oAction.dCommandParameter[uKey]) aExecActions = [] uCmd = u'' try: for oTmpAction in aActions: uCmd = oTmpAction.uCmd if uCmd.startswith('{"REPEAT":'): dRepeatCmds = ToDic(uCmd) uRepeatCmd = dRepeatCmds["REPEAT"]["REPEATCMD"] uRepeatVarName = dRepeatCmds["REPEAT"]["REPEATVAR"] uRepeatVar = ReplaceVars( uRepeatVarName, self.uInterFaceName + u'/' + oSetting.uConfigName) if uRepeatVar == "": uRepeatVar = ReplaceVars(uRepeatVarName) iLen = len(uRepeatVar) for i in range(iLen): uRepeatChar = uRepeatVar[i] uKey2 = uRepeatCmd + uRepeatChar aActionRepeatActions = Globals.oActions.GetActionList( uActionName=oSetting.MakeLocalActionName( ReplaceVars(uKey2)), bNoCopy=False) if aActionRepeatActions is not None: for oRepeatAction in aActionRepeatActions: if oRepeatAction.iActionId == Globals.oActions.oActionType.Codeset: oRepeatAction.dActionPars['nologout'] = '1' aExecActions.append(oRepeatAction) else: Logger.error( u'Error Parsing/Sending Repeats, RepeatCommand not found %s' % (uKey2)) for oTmpAction1 in reversed(aExecActions): if oTmpAction1.iActionId == Globals.oActions.oActionType.Codeset: oTmpAction1.dActionPars['nologout'] = '0' break else: if oAction.uRetVar: oTmpAction.uRetVar = oAction.uRetVar aExecActions.append(oTmpAction) except Exception as e: self.ShowError(u'Error Parsing/Sending Repeats %s' % (uCmd), "", e) return 1 Globals.oEvents.ExecuteActionsNewQueue(aExecActions, oAction.oParentWidget) return 0